Mini Kabibi Habibi

Current Path : C:/Program Files/Adobe/Adobe Photoshop 2025/Required/UXP/com.adobe.ccx.start/js/
Upload File :
Current File : C:/Program Files/Adobe/Adobe Photoshop 2025/Required/UXP/com.adobe.ccx.start/js/8505.js.map

{"version":3,"file":"8505.js","mappings":";0LAiBWA,EAiBAC,EAkBAC,EAiBAC,EAQAC,EAOAC,EAYAC,EAKAC,EASAC,EAQAC,EAOAC,EAMAC,EAQAC,EAcAC,EAyDAC,EAkBAC,EChNAC,EASAC,EASAC,EAaAC,EC9BAC,EA6BAC,EClDAC,EAQAC,EAaAC,ECrBAC,ECwBAC,ECPAC,EAKAC,EAOAC,ECZAC,ECjBAC,ECAAC,ECAAC,EAKAC,ECYAC,ECAAC,EA0FAC,EA6CAC,ECxJAC,ECAAC,EAYAC,ECZAD,EAkCAC,EClCAC,ECCAC,EAIAC,EAkCAC,EAIAC,EAqBAC,EAWAC,EC3EPC,GCkBOC,GAKAC,GAMAC,GC7BAC,GAMAC,GAUAC,GChBAC,GAIAC,GAKAC,GAQAC,GAKAC,GAKAC,GAWAC,GAcAC,GAKAC,GAQAC,GAUAC,GAKAC,GC/DAC,GAOAC,GAIAC,GC5BAC,GAWAC,GAkCAC,GAkBAC,GAWAC,GA8BAC,GCxGAC,GAMAC,GCLAC,GAOAC,GCRAC,GAeAC,GAQAC,GCvBAC,GAKAC,GAKAnE,GRoBAkC,gBnBZX,SAAWpD,GAEPA,EAAoC,eAAI,kBAExCA,EAA6B,QAAI,UAEjCA,EAA4B,OAAI,SAGhCA,EAA2B,MAAI,QAE/BA,EAA2B,MAAI,OAClC,CAZD,CAYGA,IAAwBA,EAAsB,CAAC,IAKlD,SAAWC,GAEP,IAAWqF,EASAC,GATAD,EAOKrF,EAAIqF,aAAerF,EAAIqF,WAAa,CAAC,IAL/B,MAAI,QAItBA,EAAkB,MAAI,SAGfC,EAIUtF,EAAIsF,kBAAoBtF,EAAIsF,gBAAkB,CAAC,IAHxC,OAAI,SAC5BA,EAAw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AAU0C,QACnB5F,IAASkD,GAAU2C,IACnB7F,IAASkD,GAAU4C,WACnB9F,IAASkD,GAAU6C,WACnB/F,IAASkD,GAAU8C,SACnBhG,IAASkD,GAAU+C,MACnBjG,IAASkD,GAAUgD,OAEvB,CI+4CS4L,CAAsB9R,GAAQ,IAAIA,KAAUA,CACrD,CC3+CA,MAAM+R,GAAgB,gCAEtB,SAASC,GAAgBp7I,GACvB,OAAOq7I,GAAgBr7I,EAAI4O,WAAW,GACxC,CAEA,MAAMysI,GAAkB,CACtB,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,MACA,MACA,MACA,UACA,MACA,MACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,GACA,GACA,MACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,OACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,WCrKWC,GAAQ3jK,OAAO4jK,OAAO,CAAC,GAgF7B,SAASC,GAAMnqI,EAAMoqI,EAASC,EAAcrS,IACjD,MAAMsS,EAAgB,IAAI3jK,IAE1B,IAAK,MA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xR,EAASsxR,EACT,MAAMp/R,MAAM,gBAAgBuJ,OAAO61R,EAAc,6CAGrD,GADAz+R,KAAK64R,OACD74R,KAAKu4R,QACL,KAER,CACJ,EAEA//H,EAAOn2J,UAAU42R,UAAY,WACzB,MAAQj5R,KAAKu4R,SAAWV,GAAc73R,KAAK20J,SACvC30J,KAAK64R,MAEb,EAKArgI,EAAOn2J,UAAU82J,KAAO,WACpB,GAAIn5J,KAAKu4R,QACL,OAAO,KAEX,IAAI/5R,EAAOwB,KAAK20J,OACZxnJ,EAASnN,KAAKmN,SACduxR,EAAW1+R,KAAKtB,QAAQy2B,WAAWhoB,GAAU3O,GAAQ,MAAU,EAAI,IACvE,OAAOkgS,QAA2CA,EAAW,IACjE,EACOlmI,CACX,CA/yB2B,GAszB3B,SAASkgI,GAASqB,GACd,OAASA,GAAa,IAAMA,GAAa,KACpCA,GAAa,IAAMA,GAAa,EACzC,CA8BA,SAASlC,GAAc30R,GACnB,OAASA,GAAK,GAAUA,GAAK,IACnB,KAANA,GACM,MAANA,GACCA,GAAK,MAAUA,GAAK,MACf,OAANA,GACM,OAANA,CACR,CAKA,SAAS40R,GAAiB50R,GACtB,OAASA,GAAK,IAAUA,GAAK,IACnB,KAANA,GACCA,GAAK,IAAUA,GAAK,IACf,KAANA,GACM,KAANA,GACM,KAANA,GACM,KAANA,GACM,KAANA,GACM,KAANA,GACCA,GAAK,IAAUA,GAAK,IACpBA,GAAK,IAAUA,GAAK,IACpBA,GAAK,IAAUA,GAAK,IACpBA,GAAK,IAAUA,GAAK,IACf,KAANA,GACM,KAANA,GACM,KAANA,GACM,KAANA,GACM,KAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACCA,GAAK,KAAUA,GAAK,KACf,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,GACM,MAANA,G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AAK,MACf,OAANA,GACCA,GAAK,MAAUA,GAAK,MACpBA,GAAK,MAAUA,GAAK,MACpBA,GAAK,MAAUA,GAAK,MACf,OAANA,GACCA,GAAK,MAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACf,QAANA,GACCA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACCA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACf,QAANA,GACCA,GAAK,OAAUA,GAAK,OACpBA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,OACf,QAANA,GACM,QAANA,GACM,QAANA,GACM,QAANA,GACCA,GAAK,OAAUA,GAAK,KAC7B,CGvvCA,SAASy7R,GAAcC,GACnBA,EAAI32R,SAAQ,SAAU8kR,GAElB,UADOA,EAAG39H,SACNqjI,GAAgB1F,IAAO4F,GAAgB5F,GACvC,IAAK,IAAI7gR,KAAK6gR,EAAG9/Q,eACN8/Q,EAAG9/Q,QAAQf,GAAGkjJ,SACrBuvI,GAAc5R,EAAG9/Q,QAAQf,GAAGnH,YAG3ButR,GAAgBvF,IAAOiG,GAAiBjG,EAAGlI,SAG1C0N,GAAcxF,IAA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C,QAmDT,4GmE3De,CACXhT,EACAvF,EACA7nQ,EAAU,OAEV,MAAMspQ,EAAY,IAAIkF,GAAapB,EAAiBvF,EAAe7nQ,GACnE,OAAQ4+O,GAA8B0qB,EAAUnlL,QAAQy6J,EAAY,eCFzD,CACXwuB,EACAvF,EACA7nQ,EAAU,OAEV,MAAMspQ,EAAY,IAAIuF,GAAazB,EAAiBvF,EAAe7nQ,GACnE,OAAQ4+O,GAA8B0qB,EAAUnlL,QAAQy6J,EAAY,gBCJzD,CACXwuB,EACAvF,EACA7nQ,EAAU,OAEV,MAAMspQ,EAAY,IAAIyF,GAAc3B,EAAiBvF,EAAe7nQ,GACpE,OAAQ4+O,GAA8B0qB,EAAUnlL,QAAQy6J,EAAY,eCMzD,CACX8oB,EACA1nQ,EAAU,OAEV,MAAMspQ,EAAY,IAAI2F,GAAavH,OAAiB53Q,EAAWkQ,GAC/D,OAAQ4+O,GAA8B0qB,EAAUnlL,QAAQy6J,EAAY","sources":["webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/AssetBrowser/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/ccLibraries/message.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/ccLibraries/model.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/assets/AdobeAsset.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/assets/AssetContext.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/assets/NetworkStatus.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/BoardModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/collaboration/AvatarSizes.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/core/Environment.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/core/ItemLoaderState.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/core/ItemSource.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/core/SAMCore.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/core/SAMError.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/frameio/FrameioInterface.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/custom-models/legacy-cme/LegacyCustomModelModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/CustomModelModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/LinkUtils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/ProjectsModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/AssetModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/AssignmentModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/ClassroomMemberModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/ClassroomModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/GenerationHistoryAssetModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/LibraryModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/RepositoryModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/interface/StudentAssignmentModel.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/SAM/utils/RenditionFetcher.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@ccx-public/component-types/dist/Timeline/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/SAMError.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/node_modules/tslib/tslib.es6.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/key.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/cache.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/memoize.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/SAMEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ChangeEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/observable.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/uri-templates/uri-templates.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/LinkUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/ResponseCodes.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/retry.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/synchronized.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/weakCache.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/KeepAliveManager.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/event-target-shim/dist/event-target-shim.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/abort-controller/dist/abort-controller.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/abort-controller/polyfill.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/node_modules/uuid/lib/rng-browser.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/node_modules/uuid/lib/bytesToUuid.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/node_modules/uuid/v1.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/node_modules/uuid/v4.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/node_modules/uuid/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/uuid.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/MobX.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/Cache.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/SAMCoreEvents.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/FolderContentChangedEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/CollaboratorEvents.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AssetModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/ProjectsModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/CustomModelModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModelModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/Environment.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ObjectUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/CacheableResponse.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/encoding.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/ResponseCache.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/TypedEventEmitter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ExtendClass.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/path-browserify/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ItemBase.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/http-link-header/lib/link.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AsyncResponse.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/clamp.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/SAMObjectEventEmitter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/Resource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/InterfaceBase.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/RenditionFetcher.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AssetUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/searchParams.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AssetInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/oneTimeWarning.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/ManagedPromise.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/LazyLoadManager.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/ShareableItem.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/EmbeddedMetadataResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AppMetadataResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/ManifestResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/RepositoryModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ItemUpdater.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/PropertyUpdater.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/USSModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/excludeExpressArtifacts.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/ImplicitAdobeAssetFilterBase.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetSearchFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ItemOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AssetEvents.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/ModernSet.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/loaderUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetDirectoryLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/USSv3LoaderHelper.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/USSAssetFilterName.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/USSv3Model.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ItemLoaderState.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetDirectorySearchLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ItemFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/EverythingFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ItemList.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/WeakRefPolyfill.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/WeakRef.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/waitForListLoad.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ItemSource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/RenditionBlobHelper.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/RenditionResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AssetVersion.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AssetVersionLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/UpdateSession.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/ItemPool.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/FileContentResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AssetVersionFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/ImplicitDirectoryListingFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/addProjectIdToMetadata.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/RepoMetadataResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/EffectivePermissionsResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/ACPLModelInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/LocalAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/GenerationHistoryAssetModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/generation-history/utils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/LibraryInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/GenerationHistoryInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/PerUserMetadataResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/classroomUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetFactory.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAsset.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/InternalProperties.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/USSLoaderHelper.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/SpaceSearchAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/SpaceSearchAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/Space.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AssetReviewServiceInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/CommentInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/comments/Comment.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/comments/CommentLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/comments/CommentOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/comments/CommentsResourceChangeEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/comments/CommentsResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/NetworkStatus.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/throttle.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/patches/SAMCpp.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/Logging.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/AxonClientConfig.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/isomorphic-ws/browser.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/AxonFrame.interface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/AxonVirtualConnection.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/AxonSession.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/AxonStatusCodes.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/AxonClient.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/StateMachineEventEmitter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/AxonUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/patches/ACPLNext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/SAMCore.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/hasProperty.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/USSInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/InvitationInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/RepositoryInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/ONSEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/USSUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/SBMInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/SWYInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AdobeAssetSearchInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AdobeAssetGlobalSearchInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/RecentInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AssetTransferInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/RecentAdobeAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/RecentAdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/ConflictRetryHelper.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/MRUAdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/LibraryDataChangedEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/RestrictEditChangedEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/RenditionTileResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/RenditionTile.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/CustomModelInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/CustomModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/ImplicitCustomModelFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/TrainingSetCustomModelLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/Library.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/LibraryCollaborationUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/PublishedInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/USSAdobeAssetOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/PublishedAdobeAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/PublishedAdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/DiscardedAdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/DiscardedInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/DiscardedAdobeAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetGlobalSearchFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/USSv3Interface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/GlobalSearchLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/GlobalSearchInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetGlobalSearchLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/SWYAdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/ProjectsInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/OrganizationsChangedEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/SWYAdobeAssetOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/USSAdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AssetVersionOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/StudentAssignmentModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/StudentAssignmentsInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/ONSSubscription.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/ONSLongPollWorker.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/ONSAxonWorker.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/ONSContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sync-services/ONSWorker.interface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/LocalAdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/ImplicitFavoriteAdobeAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/FavoriteAdobeAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/PLSListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/PLSSWYAdobeAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/PLSRecentAdobeAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/IsSharedFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/AvatarSizes.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/AddressBookContact.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/GroupMemberLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AddressBookInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/Collaborator.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AddressBookModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/CollaboratorLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/InvitedCollaborator.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/InvitedCollaboratorLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/CollaboratorsByAssetID.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/CollaboratorsByAssetIDLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/BatchOperationQueue.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/AddressBook.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/AddressBookLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/CollaboratorOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/InvitedCollaboratorOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/AddressBookOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/CollaborationContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/FFBoardsLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/FFBoardsInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/SWYAdobeAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/MRUAdobeAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/AssetContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/LibraryModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/LibraryOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/LibraryFilterUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/LibraryFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/ElementOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/ClassroomModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/ClassroomMemberModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/classrooms/ClassroomOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/classroom-member/ClassroomMember.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/classroom-member/ClassroomMemberOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/classrooms/ClassroomMemberFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AssignmentModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/AssignmentOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/AssignmentFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentFileAppMetadataResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentFile.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentFileOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentFilesListFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentFileFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/enumMap.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/BoardModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/PostListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/PostOwner.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/Post.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/AssetLinkPost.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/TextPost.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/Board.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/PostOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/BoardOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/BoardFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/OrgRepository.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/FavoriteAdobeAssetOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/MRUAdobeAssetOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/PublishedAdobeAssetOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/ProjectOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/CustomModelOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/generation-history/GenerationHistoryAssetOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModelOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/OrgRepositoryOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/TeamOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/SpaceOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/CollaboratorsByAssetIDOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/whitespaceFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/ProjectFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/CustomModelFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/generation-history/GenerationHistoryAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModelFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/SpaceFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/TeamFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/Team.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/collaboration/AddressBookContactOrder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/Gradient.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioAuthorizationChangeEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioReviewLinksChangeEvent.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioBase.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioUser.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioAsset.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioLike.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioComment.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioFile.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioFolder.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioTeam.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioVersionStack.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioReviewLink.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioProject.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioAccount.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/frameio/FrameioContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/access-control/AccessControlModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/node_modules/tslib/tslib.es6.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/ts-invariant/node_modules/tslib/tslib.es6.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/ts-invariant/lib/invariant.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/version.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/globals/maybe.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/globals/global.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/makeUniqueId.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/stringifyForDisplay.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/globals/invariantWrappers.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/jsutils/devAssert.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/jsutils/invariant.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/location.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/printLocation.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/error/GraphQLError.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/jsutils/isObjectLike.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/error/syntaxError.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/ast.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/directiveLocation.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/kinds.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/tokenKind.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/characterClasses.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/blockString.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/lexer.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/jsutils/inspect.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/jsutils/instanceOf.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/source.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/parser.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/printString.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/visitor.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/printer.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql/language/predicates.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/graphql/directives.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@wry/trie/lib/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/canUse.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/objects.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/graphql/fragments.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@wry/caches/lib/strong.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@wry/caches/lib/weak.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/caching/caches.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/caching/sizes.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/caching/getMemoryInternals.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/canonicalStringify.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/graphql/storeUtils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/graphql/getFromAST.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/optimism/node_modules/@wry/trie/lib/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@wry/context/lib/slot.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/optimism/lib/context.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/optimism/lib/helpers.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/optimism/lib/entry.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/optimism/lib/dep.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/optimism/lib/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/graphql/DocumentTransform.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/graphql/print.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/arrays.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/graphql/transform.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/mergeDeep.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/zen-observable-ts/module.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/symbol-observable/es/ponyfill.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/symbol-observable/es/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/observables/Observable.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/cloneDeep.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/maybeDeepFreeze.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/observables/iteration.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/observables/asyncMap.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/observables/subclassing.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/observables/Concast.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/incrementalResult.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/errorHandling.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/compact.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/utilities/common/mergeOptions.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/utils/fromError.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/utils/throwServerError.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/core/ApolloLink.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/utils/createOperation.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/utils/transformOperation.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/utils/validateOperation.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/core/from.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/core/execute.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/iterators/reader.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/responseIterator.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/iterators/promise.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/iterators/async.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/iterators/nodeStream.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/errors/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/parseAndCheckHttpResponse.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/serializeFetchParameter.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/selectHttpOptionsAndBody.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/createHttpLink.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/HttpLink.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/checkFetcher.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/selectURI.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/utils/filterOperationVariables.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/http/rewriteURIForGET.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@wry/equality/lib/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/core/equalByQuery.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/core/cache.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/core/types/common.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/helpers.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/entityStore.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/object-canon.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/readFromStore.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/reactiveVars.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/key-extractor.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/policies.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/writeToStore.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/core/networkStatus.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/cache/inmemory/inMemoryCache.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/core/ObservableQuery.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/core/QueryInfo.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/core/QueryManager.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/core/LocalState.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/core/ApolloClient.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql-tag/node_modules/tslib/tslib.es6.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/graphql-tag/lib/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/retry/retryLink.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/retry/delayFunction.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@apollo/client/link/retry/retryFunction.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/models/AssetSubgraphModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/OperationType.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/NestedField.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/Utils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/adapters/DefaultAppSyncMutationAdapter.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/adapters/DefaultAppSyncQueryAdapter.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/adapters/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/adapters/DefaultMutationAdapter.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/adapters/DefaultQueryAdapter.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/adapters/DefaultSubscriptionAdapter.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/gql-query-builder/build/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/queries/fragments.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/queries/getAsset.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/mutations/LastAccessed.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/Log.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/Cache.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/Storage.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/Persistor.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/onCacheWrite.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/Trigger.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/onAppBackground.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/CachePersistor.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/persistCacheSync.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/models/typePolicies.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/ResourceQueryWatcher.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/GQLInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/apollo3-cache-persist/lib/persistCache.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/generation-history/GenerationHistoryAsset.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/convertGQLAssetToAdobeAssetData.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/GraphQLAssetResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/GQLManager.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/WorkspacesModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/WorkspacesInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/SpaceLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/TeamLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/OrgRepositoryLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workspaces/SpaceContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/GradientModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assets/ImplicitDirectoryListingAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/Project.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/ProjectsListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/ImplicitProjectFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/projects/ProjectContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/consolidated.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/ClassroomsInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/classroom-member/ClassroomMemberListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/classrooms/Classroom.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/classrooms/ClassroomListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/AssignmentsInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentAppMetadataResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentFilesListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignment.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/AssignmentAppMetadataResource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/ImplicitStudentAssignmentFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/Assignment.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/AssignmentListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/assignments/StudentAssignmentListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/version.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/internal/semver.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/diag/types.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/api/diag.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/baggage/utils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/context/context.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/api/context.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/context-api.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/diag-api.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/api/metrics.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/metrics-api.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/api/propagation.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/propagation-api.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/api/trace.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@opentelemetry/api/build/esm/trace-api.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/core/decorators/trace.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/classrooms/ClassroomContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/MockBoardResponses.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/BoardsInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/BoardListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/boards/BoardContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/ImplicitLibraryFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/LibraryListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/LibrarySearchLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/ImplicitLibrarySearchFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/SubscriptionLocation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/libraries/LibraryContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/CustomModelLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/utils/dateUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/CustomModelSearchLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/CustomModelSearchFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModelLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModelInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModelSearchLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyImplicitCustomModelFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModelSearchFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/legacy-cme/LegacyCustomModelContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/TrainingSetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/ImplicitCustomModelDashboardFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/custom-models/CustomModelContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/generation-history/ImplicitGenerationHistoryAssetFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/generation-history/GenerationHistoryAssetLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/generation-history/GenerationHistorySiblingLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/generation-history/GenerationHistoryContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/interface/WorkfrontInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/workfront/WorkfrontContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/knowledge-workspaces/KnowledgeWorkspaceContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/access-control/AdobeACL.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/access-control/AdobeACE.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/access-control/AccessControlContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/sharing/SharingContext.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/links/AssetLink.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/links/AssetLinkList.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/links/AssetLinkManager.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/queries/SWYAdobeAsset.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/queries/generationHistoryAssets.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/graphql/queries/Recents.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/MimeTypeUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/config/constants.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/utils/index.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/LinkUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/FileUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/errors/LibraryError.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/utils/RestrictedEventEmitter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/Logger.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/index.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/Configuration.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/errors/BaseError.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/SignalUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/Driver.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/PromiseCache.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/AsyncOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/errors/RequestError.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/AsyncResponseParser.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/AsyncResponse.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/config/CloudDriverConfig.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/Operation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/SingleOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/utils/index.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/RenditionUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/utils/rapiModelMappers.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/utils/melvilleModelMappers.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/SingleOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/PathUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/MoveCopyElementOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/MoveCopyElementOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/StoreUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/utils/operationUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/BatchOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/ContentOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/ParallelOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/ParallelOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/utils/rapiResponseUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/strict-uri-encode/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/decode-uri-component/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/split-on-first/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/filter-obj/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/query-string/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/crypt/crypt.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/charenc/charenc.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/is-buffer/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/md5/md5.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/AssetNotificationManager.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/GeneratorUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/utils/StorageInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/utils/samUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/index.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/CloudDriver/utils/responseUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LibraryAbortController.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/utils/restAPIModelMappers.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/utils/generalUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/utils/responseUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/BatchOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/ContentOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/SingleOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/ParallelOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/MoveCopyElementOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/MoveCopyGroupOperation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/node_modules/ws/browser.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/NotificationEventSource/index.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/NotificationEventSource/NodeWebsocketNotificationEventSource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/NotificationEventSource/WebsocketNotificationEventSource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/NotificationEventSource/SSENotificationEventSource.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/connectors/Connector.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/LocalDriver/index.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/drivers/HybridDriver/index.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/Vulcan/IVulcan.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/Vulcan/index.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/connectors/cepConnector.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/connectors/ccdConnector.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/connectors/nodeConnector.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/connectors/uxpConnector.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/ProgressiveLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/mobXRegistry.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/observable.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/Model.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/utils/AccessUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/utils/HasLibrary.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/utils/representationUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/utils/AttributeUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/Representation.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/ActionUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/ApplicationAction.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/utils/elementUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/PublishedModel.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/Element.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/Action.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/JSONPath.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/utils/reducer.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/FIFOStringSet.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/microdiff/dist/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/LibraryUtils.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/Store.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/ElementListLoader.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/ImplicitElementFilter.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/LibraryContents.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/Group.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/Team.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/tslib/tslib.es6.mjs","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/fast-memoize/lib/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-messageformat-parser/lib/error.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-messageformat-parser/lib/types.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-messageformat-parser/lib/regex.generated.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-skeleton-parser/lib/date-time.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-skeleton-parser/lib/regex.generated.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-skeleton-parser/lib/number.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-messageformat-parser/lib/time-data.generated.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-messageformat-parser/lib/parser.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-messageformat-parser/lib/date-time-pattern-generator.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/intl-messageformat/lib/src/error.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/icu-messageformat-parser/lib/index.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/intl-messageformat/lib/src/formatters.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/intl-messageformat/lib/src/core.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/error.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/utils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/message.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/ecma402-abstract/lib/utils.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/dateTime.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/displayName.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/list.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/plural.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/relativeTime.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/number.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/node_modules/@formatjs/intl/lib/src/create-intl.js","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/IntlInterface.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/FontManager.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/utils/ObservableMap.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/ModelCacheStub.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/models/OrchestratorStub.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/CCLibraries.ts","webpack://UniversalAssetBrowser/../../node_modules/@ccx-public/shared-asset-model-js/dist/src/library-contents/index.ts"],"sourcesContent":["/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe\n *  All Rights Reserved.\n *\n *  NOTICE:  All information contained herein is, and remains\n *  the property of Adobe and its suppliers, if any. The intellectual\n *  and technical concepts contained herein are proprietary to Adobe\n *  and its suppliers and are protected by all applicable intellectual\n *  property laws, including trade secret and copyright laws.\n *  Dissemination of this information or reproduction of this material\n *  is strictly forbidden unless prior written permission is obtained\n *  from Adobe.\n **************************************************************************/\nexport var ShowModalResultType;\n(function (ShowModalResultType) {\n    // The dialog was not shown because the host has not provided support for it.\n    ShowModalResultType[\"NotImplemented\"] = \"not_implemented\";\n    // The user followed the dialog flow to completion.\n    ShowModalResultType[\"Success\"] = \"success\";\n    // The user canceled the dialog.\n    ShowModalResultType[\"Cancel\"] = \"cancel\";\n    // The user interacted with the host in a way that closed the dialog (e.g. pressing escape,\n    // clicking outside the dialog, or clicking the close button at the top right).\n    ShowModalResultType[\"Close\"] = \"close\";\n    // The dialog was closed as part of an error flow, typically accompanied by a toast.\n    ShowModalResultType[\"Error\"] = \"error\";\n})(ShowModalResultType || (ShowModalResultType = {}));\n// TODO: https://jira.corp.adobe.com/browse/CCXCD-14030\n// Import these types and enums below from component-types into CDO/UAB\n/* eslint-disable @typescript-eslint/no-namespace */\nexport var CDO;\n(function (CDO) {\n    let ActionType;\n    (function (ActionType) {\n        /** Default action type. This action is shown for each asset in the Action menu, Context Menu and Action Bar */\n        ActionType[\"Asset\"] = \"asset\";\n        /** This action applies to the currently navigated route in CDO. It will be rendered in the Header of the provided route/tab\n         * Example: New Folder, Upload, etc.\n         */\n        ActionType[\"Route\"] = \"route\";\n    })(ActionType = CDO.ActionType || (CDO.ActionType = {}));\n    let ClickSelectType;\n    (function (ClickSelectType) {\n        ClickSelectType[\"Single\"] = \"single\";\n        ClickSelectType[\"Double\"] = \"double\";\n        ClickSelectType[\"None\"] = \"none\";\n    })(ClickSelectType = CDO.ClickSelectType || (CDO.ClickSelectType = {}));\n})(CDO || (CDO = {}));\nexport var ContentViewType;\n(function (ContentViewType) {\n    ContentViewType[\"CloudDocuments\"] = \"cloud-documents\";\n    ContentViewType[\"Deleted\"] = \"deleted\";\n    ContentViewType[\"SharedWithYou\"] = \"shared-with-you\";\n    ContentViewType[\"Recents\"] = \"recents\";\n    ContentViewType[\"ReviewLinks\"] = \"review-links\";\n    ContentViewType[\"ConvertToSketch\"] = \"sketch\";\n    ContentViewType[\"Libraries\"] = \"libraries\";\n    ContentViewType[\"Local\"] = \"local\";\n    ContentViewType[\"Projects\"] = \"projects\";\n    ContentViewType[\"Project\"] = \"project\";\n    ContentViewType[\"GenerationHistory\"] = \"generation-history\";\n    ContentViewType[\"FFBoards\"] = \"ffboards\";\n    ContentViewType[\"Favorites\"] = \"favorites\";\n    ContentViewType[\"AssetPreview\"] = \"asset-preview\";\n})(ContentViewType || (ContentViewType = {}));\nexport var OtherFileTypeValues;\n(function (OtherFileTypeValues) {\n    OtherFileTypeValues[\"AllFiles\"] = \"ALL_FILES\";\n    OtherFileTypeValues[\"Folder\"] = \"FOLDER\";\n    OtherFileTypeValues[\"Project\"] = \"PROJECT\";\n    OtherFileTypeValues[\"ReviewLink\"] = \"REVIEW_LINK\";\n    OtherFileTypeValues[\"AllCompatible\"] = \"ALL_COMPATIBLE\";\n})(OtherFileTypeValues || (OtherFileTypeValues = {}));\nexport var GenericFileTypeValues;\n(function (GenericFileTypeValues) {\n    GenericFileTypeValues[\"Assets3d\"] = \"ASSETS_3D\";\n    GenericFileTypeValues[\"Images\"] = \"IMAGES\";\n    GenericFileTypeValues[\"Videos\"] = \"VIDEOS\";\n    GenericFileTypeValues[\"Audio\"] = \"AUDIO\";\n})(GenericFileTypeValues || (GenericFileTypeValues = {}));\nexport var AdobeFileTypeValues;\n(function (AdobeFileTypeValues) {\n    AdobeFileTypeValues[\"Photoshop\"] = \"PHOTOSHOP\";\n    AdobeFileTypeValues[\"Illustrator\"] = \"ILLUSTRATOR\";\n    AdobeFileTypeValues[\"Express\"] = \"EXPRESS\";\n    AdobeFileTypeValues[\"Acrobat\"] = \"PDF\";\n    AdobeFileTypeValues[\"InDesign\"] = \"INDESIGN\";\n    AdobeFileTypeValues[\"Aero\"] = \"AERO\";\n    AdobeFileTypeValues[\"XD\"] = \"XD\";\n    AdobeFileTypeValues[\"Concept\"] = \"CONCEPT\";\n    AdobeFileTypeValues[\"Squirrel\"] = \"SQUIRREL\";\n})(AdobeFileTypeValues || (AdobeFileTypeValues = {}));\nexport var LibrariesAndBrandsTypeValues;\n(function (LibrariesAndBrandsTypeValues) {\n    LibrariesAndBrandsTypeValues[\"Libraries\"] = \"LIBRARIES\";\n    LibrariesAndBrandsTypeValues[\"Brands\"] = \"BRANDS\";\n})(LibrariesAndBrandsTypeValues || (LibrariesAndBrandsTypeValues = {}));\nexport var GenStudioBrandTypeValues;\n(function (GenStudioBrandTypeValues) {\n    GenStudioBrandTypeValues[\"AllBrands\"] = \"ALL_BRANDS\";\n    GenStudioBrandTypeValues[\"CreatedByYou\"] = \"CREATED_BY_YOU\";\n    GenStudioBrandTypeValues[\"Drafts\"] = \"DRAFTS\";\n    GenStudioBrandTypeValues[\"Published\"] = \"PUBLISHED\";\n    GenStudioBrandTypeValues[\"MyBrands\"] = \"MY_BRANDS\";\n    GenStudioBrandTypeValues[\"Public\"] = \"PUBLIC\";\n})(GenStudioBrandTypeValues || (GenStudioBrandTypeValues = {}));\nexport var FireflyGenerationTypeValues;\n(function (FireflyGenerationTypeValues) {\n    FireflyGenerationTypeValues[\"GenerationAll\"] = \"FIREFLY_GENERATION_ALL\";\n    FireflyGenerationTypeValues[\"GenerationImage\"] = \"FIREFLY_GENERATION_IMAGE\";\n    FireflyGenerationTypeValues[\"GenerationVideo\"] = \"FIREFLY_GENERATION_VIDEO\";\n    FireflyGenerationTypeValues[\"GenerationVector\"] = \"FIREFLY_GENERATION_VECTOR\";\n    FireflyGenerationTypeValues[\"GenerationAudio\"] = \"FIREFLY_GENERATION_AUDIO\";\n})(FireflyGenerationTypeValues || (FireflyGenerationTypeValues = {}));\nexport var SharedViewTypeValues;\n(function (SharedViewTypeValues) {\n    SharedViewTypeValues[\"All\"] = \"SHARED_VIEW_ALL\";\n    SharedViewTypeValues[\"Yours\"] = \"SHARED_VIEW_YOURS\";\n    SharedViewTypeValues[\"SharedWithYou\"] = \"SHARED_VIEW_SHARED_WITH_YOU\";\n})(SharedViewTypeValues || (SharedViewTypeValues = {}));\nexport const FileFilterTypeValues = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, GenericFileTypeValues), AdobeFileTypeValues), OtherFileTypeValues), LibrariesAndBrandsTypeValues), FireflyGenerationTypeValues), SharedViewTypeValues), GenStudioBrandTypeValues);\nexport var SAMLogLevel;\n(function (SAMLogLevel) {\n    SAMLogLevel[SAMLogLevel[\"Off\"] = 0] = \"Off\";\n    SAMLogLevel[SAMLogLevel[\"Medium\"] = 1] = \"Medium\";\n    SAMLogLevel[SAMLogLevel[\"High\"] = 2] = \"High\";\n})(SAMLogLevel || (SAMLogLevel = {}));\nexport var CDOLogLevel;\n(function (CDOLogLevel) {\n    CDOLogLevel[CDOLogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n    CDOLogLevel[CDOLogLevel[\"INFO\"] = 1] = \"INFO\";\n    CDOLogLevel[CDOLogLevel[\"WARN\"] = 2] = \"WARN\";\n    CDOLogLevel[CDOLogLevel[\"ERROR\"] = 3] = \"ERROR\";\n    CDOLogLevel[CDOLogLevel[\"DISABLED\"] = 4] = \"DISABLED\";\n})(CDOLogLevel || (CDOLogLevel = {}));\nexport var AccountType;\n(function (AccountType) {\n    AccountType[\"Personal\"] = \"type1\";\n    AccountType[\"Enterprise\"] = \"type2\";\n    AccountType[\"Business\"] = \"type3\";\n    AccountType[\"Federated\"] = \"type2e\";\n})(AccountType || (AccountType = {}));\n/**\n * PickerMode is an enum for quickly configuring parts of CDP UI to show/hide various\n * features including tabs, buttons, and behvaioral changes. Modes can be sent through several APIs including through\n * Panel.tsx, Commands.tsx, and WebCommands.tsx, returned from host.getPickerInfo() calls and\n * through a PICKERSTATECHANGED event sent from UXP which provides the new mode.\n * The mode is also sent through executeValidPickerAction call into the host.\n */\nexport var PickerMode;\n(function (PickerMode) {\n    /**\n     * Place mode that is for the 2021 Place workflow. This mode will be just like Open but will have different\n     * analytics and a different callback.\n     */\n    PickerMode[\"placeLinkOrEmbed\"] = \"placeLinkOrEmbed\";\n    /**\n     * Link Assets mode that is primarily used with XD. This mode is not considered a \"Save As\" mode meaning\n     * it's primarily used for \"Opening Documents\" scenarios.\n     * Visible Tabs - Cloud Documents, Shared With You, Convert To Sketch Libraries.\n     */\n    PickerMode[\"linkAssets\"] = \"linkAssets\";\n    /**\n     * The primary mode for users when selecting documents to open. When a document is clicked, it's\n     * selected and then highlights the \"Open\" button so the user can opened the selected document.\n     * This mode is not considered a \"Save As\" view mode.\n     * Visible Tabs - Recent Tab, Cloud Documents Tab, Shared With you tab.\n     */\n    PickerMode[\"open\"] = \"open\";\n    /**\n     * The primary mode for CDP when Saving Documents to the host application. Shows the \"Save As\" header\n     * with an input for the user to type. This mode is unlike \"Opening\" modes in that the users is supposed\n     * to provide a name for the file to be saved. It  shows a \"Save\" Button and no \"On Your Computer\"\n     * buttons. When an item is clicked, we set the Save As Input field to the name of the item that was clicked.\n     */\n    PickerMode[\"saveAs\"] = \"saveAs\";\n    /**\n     * This is another \"Save As\" mode that shoud be identical to PickerMode.saveAs. The main difference\n     * here is for the host app to know when a user invoked Save As Copy instead of just a plain\n     * Save As. When an item is clicked, we set the Save As Input field to the name of the item that was clicked.\n     */\n    PickerMode[\"saveAsCopy\"] = \"saveAsCopy\";\n    PickerMode[\"saveToFolder\"] = \"saveToFolder\";\n    /**\n     * This is another \"Save As\" mode that shoud be similar (not identical) to PickerMode.saveAs. Header and\n     * primaryButton labels will display 'export' specific labelling. Like \"Save As\", user can update the name of\n     * exported asset and choose the export format.\n     */\n    PickerMode[\"export\"] = \"export\";\n    /**\n     * Copy items to Projects or Cloud Documents.\n     */\n    PickerMode[\"copy\"] = \"copy\";\n    /**\n     * Generic move for moving items to new location.\n     */\n    PickerMode[\"move\"] = \"move\";\n    /**\n     * Move item(s) to a target location. (e.g. assets from Files to Projects)\n     */\n    PickerMode[\"moveFrom\"] = \"moveFrom\";\n    /**\n     * Generic mode for selecting an asset and returning it to the caller\n     */\n    PickerMode[\"add\"] = \"add\";\n})(PickerMode || (PickerMode = {}));\nexport var GetBlockedAssetsResponse;\n(function (GetBlockedAssetsResponse) {\n    /**\n     * Proceed with the operation\n     */\n    GetBlockedAssetsResponse[\"Ok\"] = \"ok\";\n    /**\n     * Skip the operation for this asset, perhaps because the host application\n     * performs the operation instead, or the operation is not supported or\n     * some other reason\n     */\n    GetBlockedAssetsResponse[\"Cancel\"] = \"cancel\";\n    /**\n     * Skip the operation for this asset, and notify the user that it could not\n     * be performed because the asset is open in the host application\n     */\n    GetBlockedAssetsResponse[\"CancelBecauseOpen\"] = \"cancel-open\";\n})(GetBlockedAssetsResponse || (GetBlockedAssetsResponse = {}));\nexport var Capability;\n(function (Capability) {\n    Capability[\"ShareSheetInvite\"] = \"invite\";\n    Capability[\"ShareSheetLink\"] = \"getLink\";\n    Capability[\"ShareSheetAction\"] = \"share\";\n})(Capability || (Capability = {}));\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe\n *  All Rights Reserved.\n *\n *  NOTICE:  All information contained herein is, and remains\n *  the property of Adobe and its suppliers, if any. The intellectual\n *  and technical concepts contained herein are proprietary to Adobe\n *  and its suppliers and are protected by all applicable intellectual\n *  property laws, including trade secret and copyright laws.\n *  Dissemination of this information or reproduction of this material\n *  is strictly forbidden unless prior written permission is obtained\n *  from Adobe.\n **************************************************************************/\n/**\n * TODO - pull in LinkStatus from SAM.js (wait until SAM.js converts to enums)\n */\nexport var LinkStatus;\n(function (LinkStatus) {\n    LinkStatus[\"UpToDate\"] = \"UpToDate\";\n    LinkStatus[\"OutOfDate\"] = \"OutOfDate\";\n    LinkStatus[\"MetadataOutOfDate\"] = \"MetadataOutOfDate\";\n    LinkStatus[\"Restricted\"] = \"Restricted\";\n    LinkStatus[\"Discarded\"] = \"Discarded\";\n    LinkStatus[\"Broken\"] = \"Broken\";\n})(LinkStatus || (LinkStatus = {}));\nexport var Role;\n(function (Role) {\n    Role[\"Edit\"] = \"Edit\";\n    Role[\"View\"] = \"View\";\n    Role[\"None\"] = \"None\";\n})(Role || (Role = {}));\n/**\n * Message types used in CCLibrariesInterface\n */\nexport var MessageType;\n(function (MessageType) {\n    MessageType[\"assets\"] = \"ccac.dap.in.notify.assets\";\n    MessageType[\"update\"] = \"ccac.dap.out.notify.update\";\n    MessageType[\"config\"] = \"ccac.dap.in.notify.config\";\n    MessageType[\"showShare\"] = \"ccac.dap.out.notify.showShare\";\n    MessageType[\"requestAction\"] = \"ccac.libraries.out.request.action\";\n    MessageType[\"requestUpdate\"] = \"ccac.libraries.in.request.update\";\n    MessageType[\"applyElements\"] = \"ccac.libraries.out.request.apply\";\n})(MessageType || (MessageType = {}));\n/**\n * Action types for 'ccac.libraries.out.request.action' message type\n */\nexport var RequestActionTypes;\n(function (RequestActionTypes) {\n    RequestActionTypes[\"openPicker\"] = \"openPicker\";\n    RequestActionTypes[\"openShareSheet\"] = \"openShareSheet\";\n    RequestActionTypes[\"openPreview\"] = \"openPreview\";\n})(RequestActionTypes || (RequestActionTypes = {}));\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe\n *  All Rights Reserved.\n *\n *  NOTICE:  All information contained herein is, and remains\n *  the property of Adobe and its suppliers, if any. The intellectual\n *  and technical concepts contained herein are proprietary to Adobe\n *  and its suppliers and are protected by all applicable intellectual\n *  property laws, including trade secret and copyright laws.\n *  Dissemination of this information or reproduction of this material\n *  is strictly forbidden unless prior written permission is obtained\n *  from Adobe.\n **************************************************************************/\n// Types related to the libraries and document assets data models\n/**\n * TODO: Should pull these in from the Libraries API type definitions\n */\nexport var ElementType;\n(function (ElementType) {\n    ElementType[\"animation\"] = \"application/vnd.adobe.element.animation+dcx\";\n    ElementType[\"audio\"] = \"application/vnd.adobe.element.audio+dcx\";\n    ElementType[\"brush\"] = \"application/vnd.adobe.element.brush+dcx\";\n    ElementType[\"characterstyle\"] = \"application/vnd.adobe.element.characterstyle+dcx\";\n    ElementType[\"color\"] = \"application/vnd.adobe.element.color+dcx\";\n    ElementType[\"colortheme\"] = \"application/vnd.adobe.element.colortheme+dcx\";\n    ElementType[\"component\"] = \"application/vnd.adobe.element.component+dcx\";\n    ElementType[\"font\"] = \"application/vnd.adobe.element.font+dcx\";\n    ElementType[\"gradient\"] = \"application/vnd.adobe.element.gradient+dcx\";\n    ElementType[\"graphic\"] = \"application/vnd.adobe.element.image+dcx\";\n    ElementType[\"layerstyle\"] = \"application/vnd.adobe.element.layerstyle+dcx\";\n    ElementType[\"light\"] = \"application/vnd.adobe.element.light+dcx\";\n    ElementType[\"look\"] = \"application/vnd.adobe.element.look+dcx\";\n    ElementType[\"material\"] = \"application/vnd.adobe.element.material+dcx\";\n    ElementType[\"model\"] = \"application/vnd.adobe.element.3d+dcx\";\n    ElementType[\"mogrt\"] = \"application/vnd.adobe.element.graphic+dcx\";\n    ElementType[\"multicolorswatch\"] = \"application/vnd.adobe.element.multicolorswatch+dcx\";\n    ElementType[\"paragraphstyle\"] = \"application/vnd.adobe.element.paragraphstyle+dcx\";\n    ElementType[\"pattern\"] = \"application/vnd.adobe.element.pattern+dcx\";\n    ElementType[\"template\"] = \"application/vnd.adobe.element.template+dcx\";\n    ElementType[\"text\"] = \"application/vnd.adobe.element.text+dcx\";\n    ElementType[\"video\"] = \"application/vnd.adobe.element.video+dcx\";\n    ElementType[\"artifact\"] = \"application/vnd.adobe.element.artifact+dcx\";\n})(ElementType || (ElementType = {}));\n/**\n * TODO: Should pull these in from the Libraries API type definitions\n */\nexport var Relationship;\n(function (Relationship) {\n    Relationship[\"primary\"] = \"primary\";\n    Relationship[\"rendition\"] = \"rendition\";\n})(Relationship || (Relationship = {}));\n","export var AssetSyncStatus;\n(function (AssetSyncStatus) {\n    AssetSyncStatus[AssetSyncStatus[\"InSync\"] = 0] = \"InSync\";\n    AssetSyncStatus[AssetSyncStatus[\"OutOfSync\"] = 1] = \"OutOfSync\";\n    AssetSyncStatus[AssetSyncStatus[\"SyncConflict\"] = 2] = \"SyncConflict\";\n    AssetSyncStatus[AssetSyncStatus[\"SyncError\"] = 3] = \"SyncError\";\n    AssetSyncStatus[AssetSyncStatus[\"Syncing\"] = 4] = \"Syncing\";\n})(AssetSyncStatus || (AssetSyncStatus = {}));\nexport var AssetSyncSuspensionReason;\n(function (AssetSyncSuspensionReason) {\n    AssetSyncSuspensionReason[AssetSyncSuspensionReason[\"None\"] = 0] = \"None\";\n    AssetSyncSuspensionReason[AssetSyncSuspensionReason[\"CloudContentCorrupted\"] = 1] = \"CloudContentCorrupted\";\n    AssetSyncSuspensionReason[AssetSyncSuspensionReason[\"LocalContentCorrupted\"] = 2] = \"LocalContentCorrupted\";\n    AssetSyncSuspensionReason[AssetSyncSuspensionReason[\"HasTooManyComponents\"] = 3] = \"HasTooManyComponents\";\n    AssetSyncSuspensionReason[AssetSyncSuspensionReason[\"HasTooManyChildren\"] = 4] = \"HasTooManyChildren\";\n    AssetSyncSuspensionReason[AssetSyncSuspensionReason[\"MaximumSizeExceeded\"] = 5] = \"MaximumSizeExceeded\";\n    AssetSyncSuspensionReason[AssetSyncSuspensionReason[\"Unknown\"] = 6] = \"Unknown\";\n})(AssetSyncSuspensionReason || (AssetSyncSuspensionReason = {}));\n/**\n * Response from the server for the commit request.\n **/\nexport var CommitStatus;\n(function (CommitStatus) {\n    CommitStatus[CommitStatus[\"NoErr\"] = 0] = \"NoErr\";\n    CommitStatus[CommitStatus[\"Conflict\"] = 1] = \"Conflict\";\n    CommitStatus[CommitStatus[\"DeleteConflict\"] = 2] = \"DeleteConflict\";\n    CommitStatus[CommitStatus[\"ParentDeletedConflict\"] = 3] = \"ParentDeletedConflict\";\n})(CommitStatus || (CommitStatus = {}));\n","export var CloudSyncStatus;\n(function (CloudSyncStatus) {\n    CloudSyncStatus[CloudSyncStatus[\"Initializing\"] = 0] = \"Initializing\";\n    CloudSyncStatus[CloudSyncStatus[\"Offline\"] = 1] = \"Offline\";\n    CloudSyncStatus[CloudSyncStatus[\"NotStarted\"] = 2] = \"NotStarted\";\n    CloudSyncStatus[CloudSyncStatus[\"Disabled\"] = 3] = \"Disabled\";\n    CloudSyncStatus[CloudSyncStatus[\"Synchronized\"] = 4] = \"Synchronized\";\n    CloudSyncStatus[CloudSyncStatus[\"InProgress\"] = 5] = \"InProgress\";\n    CloudSyncStatus[CloudSyncStatus[\"ErrorQuotaExceeded\"] = 6] = \"ErrorQuotaExceeded\";\n    CloudSyncStatus[CloudSyncStatus[\"ErrorSyncDown\"] = 7] = \"ErrorSyncDown\";\n    CloudSyncStatus[CloudSyncStatus[\"ErrorOther\"] = 8] = \"ErrorOther\";\n})(CloudSyncStatus || (CloudSyncStatus = {}));\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n/**\n * Enum for network status currently only used with the Native Bindings\n * so this has been migrated from AssetContext to help avoid importing\n * AssetContext directly instead of by type.\n *\n * @note Must be kept in sync with NetworkStatus in AssetContext.h\n */\nexport var NetworkStatus;\n(function (NetworkStatus) {\n    NetworkStatus[NetworkStatus[\"Offline\"] = 0] = \"Offline\";\n    NetworkStatus[NetworkStatus[\"Wan\"] = 1] = \"Wan\";\n    NetworkStatus[NetworkStatus[\"Cellular\"] = 2] = \"Cellular\";\n    NetworkStatus[NetworkStatus[\"OnlineUnknown\"] = 3] = \"OnlineUnknown\";\n})(NetworkStatus || (NetworkStatus = {}));\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe\n *  All Rights Reserved.\n *\n *  NOTICE:  All information contained herein is, and remains\n *  the property of Adobe and its suppliers, if any. The intellectual\n *  and technical concepts contained herein are proprietary to Adobe\n *  and its suppliers and are protected by all applicable intellectual\n *  property laws, including trade secret and copyright laws.\n *  Dissemination of this information or reproduction of this material\n *  is strictly forbidden unless prior written permission is obtained\n *  from Adobe.\n **************************************************************************/\nexport var PostType;\n(function (PostType) {\n    PostType[\"Text\"] = \"text\";\n    PostType[\"AssetLink\"] = \"assetLink\";\n})(PostType || (PostType = {}));\nexport var BoardMemberRole;\n(function (BoardMemberRole) {\n    BoardMemberRole[\"OWNER\"] = \"OWNER\";\n    BoardMemberRole[\"POSTER\"] = \"POSTER\";\n    BoardMemberRole[\"VIEWER\"] = \"VIEWER\";\n    BoardMemberRole[\"UNKNOWN\"] = \"UNKNOWN\";\n})(BoardMemberRole || (BoardMemberRole = {}));\nexport var BoardType;\n(function (BoardType) {\n    BoardType[\"CLASSROOM\"] = \"classroom\";\n})(BoardType || (BoardType = {}));\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nexport var AvatarSizes;\n(function (AvatarSizes) {\n    AvatarSizes[\"Size50\"] = \"50\";\n    AvatarSizes[\"Size100\"] = \"100\";\n    AvatarSizes[\"Size115\"] = \"115\";\n    AvatarSizes[\"Size230\"] = \"230\";\n    AvatarSizes[\"Size138\"] = \"138\";\n    AvatarSizes[\"Size276\"] = \"276\";\n})(AvatarSizes || (AvatarSizes = {}));\n","export var Env;\n(function (Env) {\n    Env[Env[\"Stage\"] = 0] = \"Stage\";\n    Env[Env[\"Production\"] = 1] = \"Production\";\n})(Env || (Env = {}));\n","export var AssetListStatus;\n(function (AssetListStatus) {\n    AssetListStatus[AssetListStatus[\"NotStarted\"] = 1] = \"NotStarted\";\n    AssetListStatus[AssetListStatus[\"HadLoaderErrors\"] = 2] = \"HadLoaderErrors\";\n    AssetListStatus[AssetListStatus[\"Loading\"] = 3] = \"Loading\";\n    AssetListStatus[AssetListStatus[\"ReadyHasMorePages\"] = 4] = \"ReadyHasMorePages\";\n    AssetListStatus[AssetListStatus[\"ReadyFullyLoaded\"] = 5] = \"ReadyFullyLoaded\";\n})(AssetListStatus || (AssetListStatus = {}));\n","export var OrderDirection;\n(function (OrderDirection) {\n    OrderDirection[OrderDirection[\"Ascending\"] = 0] = \"Ascending\";\n    OrderDirection[OrderDirection[\"Descending\"] = 1] = \"Descending\";\n})(OrderDirection || (OrderDirection = {}));\nexport var OrderField;\n(function (OrderField) {\n    OrderField[OrderField[\"Name\"] = 0] = \"Name\";\n    OrderField[OrderField[\"Modified\"] = 1] = \"Modified\";\n    OrderField[OrderField[\"Created\"] = 2] = \"Created\";\n    OrderField[OrderField[\"Shared\"] = 3] = \"Shared\";\n})(OrderField || (OrderField = {}));\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nexport var LogLevel;\n(function (LogLevel) {\n    LogLevel[LogLevel[\"Off\"] = 0] = \"Off\";\n    LogLevel[LogLevel[\"Err\"] = 1] = \"Err\";\n    LogLevel[LogLevel[\"Warn\"] = 2] = \"Warn\";\n    LogLevel[LogLevel[\"Info\"] = 3] = \"Info\";\n    LogLevel[LogLevel[\"Debug\"] = 4] = \"Debug\";\n})(LogLevel || (LogLevel = {}));\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nexport var SAMErrorCode;\n(function (SAMErrorCode) {\n    SAMErrorCode[SAMErrorCode[\"UNKNOWN\"] = 1] = \"UNKNOWN\";\n    SAMErrorCode[SAMErrorCode[\"FULL_LOCAL_DISK_SPACE\"] = 2] = \"FULL_LOCAL_DISK_SPACE\";\n    SAMErrorCode[SAMErrorCode[\"FULL_CLOUD_STORAGE\"] = 3] = \"FULL_CLOUD_STORAGE\";\n    SAMErrorCode[SAMErrorCode[\"DEVICE_OFFLINE\"] = 4] = \"DEVICE_OFFLINE\";\n    SAMErrorCode[SAMErrorCode[\"NETWORK_ERROR\"] = 5] = \"NETWORK_ERROR\";\n    SAMErrorCode[SAMErrorCode[\"REQUEST_TIMED_OUT\"] = 6] = \"REQUEST_TIMED_OUT\";\n    SAMErrorCode[SAMErrorCode[\"USER_CANCELLED\"] = 7] = \"USER_CANCELLED\";\n    SAMErrorCode[SAMErrorCode[\"CORESYNC_FAILURE\"] = 8] = \"CORESYNC_FAILURE\";\n    /**\n     * CoreSync is in a paused state.\n     */\n    SAMErrorCode[SAMErrorCode[\"SYNC_PAUSED\"] = 9] = \"SYNC_PAUSED\";\n    SAMErrorCode[SAMErrorCode[\"USER_ALREADY_REGISTERED\"] = 10] = \"USER_ALREADY_REGISTERED\";\n    SAMErrorCode[SAMErrorCode[\"PENDING_UNCOMMITTED_CHANGES_FROM_THIS_APP\"] = 11] = \"PENDING_UNCOMMITTED_CHANGES_FROM_THIS_APP\";\n    SAMErrorCode[SAMErrorCode[\"PENDING_UNCOMMITTED_CHANGES_FROM_ANOTHER_APP\"] = 12] = \"PENDING_UNCOMMITTED_CHANGES_FROM_ANOTHER_APP\";\n    SAMErrorCode[SAMErrorCode[\"INTERNAL_ERROR\"] = 13] = \"INTERNAL_ERROR\";\n    SAMErrorCode[SAMErrorCode[\"OPERATION_IGNORED\"] = 14] = \"OPERATION_IGNORED\";\n    /**\n     * Indicates that the request could not be processed because of conflict\n     * in the current state of the resource.\n     * <br>Client Action: Resolve conflict and try again.\n     */\n    SAMErrorCode[SAMErrorCode[\"CONFLICT\"] = 15] = \"CONFLICT\";\n    /**\n     * Happens when interacting with an asset the user no longer has access to.\n     */\n    SAMErrorCode[SAMErrorCode[\"ACCESS_DENIED\"] = 16] = \"ACCESS_DENIED\";\n    SAMErrorCode[SAMErrorCode[\"UNSUPPORTED\"] = 17] = \"UNSUPPORTED\";\n    SAMErrorCode[SAMErrorCode[\"ASSET_NOT_IN_SYNC\"] = 18] = \"ASSET_NOT_IN_SYNC\";\n    SAMErrorCode[SAMErrorCode[\"BAD_REQUEST\"] = 19] = \"BAD_REQUEST\";\n    /**\n     * Happens if asset failed to sync.\n     * There are associated sub-codes relating to this error which may have\n     * more information\n     */\n    SAMErrorCode[SAMErrorCode[\"SYNC_ERROR\"] = 20] = \"SYNC_ERROR\";\n    /**\n     * Happens if requests is made for an asset that cannot be found.\n     */\n    SAMErrorCode[SAMErrorCode[\"NOT_FOUND\"] = 21] = \"NOT_FOUND\";\n    /**\n     * Happens when there is authorization error while performing the request\n     * for e.g. if requests are made which require user to be registered with\n     * ACPL, but user is not registered.\n     */\n    SAMErrorCode[SAMErrorCode[\"AUTHORIZATION_ERROR\"] = 22] = \"AUTHORIZATION_ERROR\";\n    /**\n     * Happens while performing an invalid operation for e.g. when attempting\n     * to migrate an asset to RepoNaming that has already been migrated\n     */\n    SAMErrorCode[SAMErrorCode[\"INVALID_OPERATION\"] = 23] = \"INVALID_OPERATION\";\n    /**\n     * Happens when a method is called on a asset that require that the\n     * asset have a context, but none is present or the asset does not\n     * belong to specified context.\n     */\n    SAMErrorCode[SAMErrorCode[\"INVALID_CONTEXT\"] = 24] = \"INVALID_CONTEXT\";\n    /**\n     * An error occured during committing changes.\n     * Error sub-code may have more information around this\n     */\n    SAMErrorCode[SAMErrorCode[\"COMMIT_ERROR\"] = 25] = \"COMMIT_ERROR\";\n    /**\n     *  Parent not found for the asset\n     */\n    SAMErrorCode[SAMErrorCode[\"PARENT_NOT_FOUND\"] = 26] = \"PARENT_NOT_FOUND\";\n    /**\n     * Parent folder is discarded\n     */\n    SAMErrorCode[SAMErrorCode[\"PARENT_DISCARDED\"] = 27] = \"PARENT_DISCARDED\";\n    /**\n     * Project limit exceeded\n     */\n    SAMErrorCode[SAMErrorCode[\"PROJECT_LIMIT_EXCEEDED\"] = 28] = \"PROJECT_LIMIT_EXCEEDED\";\n    /**\n     * The user or organization is not provisioned\n     * for the requested service access.\n     */\n    SAMErrorCode[SAMErrorCode[\"SERVICE_NOT_PROVISIONED\"] = 29] = \"SERVICE_NOT_PROVISIONED\";\n    /**\n     * Transfer of ownership of assets is disabled.\n     */\n    SAMErrorCode[SAMErrorCode[\"TRANSFER_OF_OWNERSHIP_DISABLED\"] = 30] = \"TRANSFER_OF_OWNERSHIP_DISABLED\";\n    /**\n     * Moves of assets by external users out of the organization are disallowed.\n     */\n    SAMErrorCode[SAMErrorCode[\"MOVES_FROM_ORG_DISALLOWED\"] = 31] = \"MOVES_FROM_ORG_DISALLOWED\";\n})(SAMErrorCode || (SAMErrorCode = {}));\nexport var SAMErrorSubCode;\n(function (SAMErrorSubCode) {\n    SAMErrorSubCode[SAMErrorSubCode[\"NONE\"] = 0] = \"NONE\";\n    SAMErrorSubCode[SAMErrorSubCode[\"CORESYNC_NOT_REACHABLE\"] = 1] = \"CORESYNC_NOT_REACHABLE\";\n    SAMErrorSubCode[SAMErrorSubCode[\"CORESYNC_NOT_COMPATIBLE\"] = 2] = \"CORESYNC_NOT_COMPATIBLE\";\n    /**\n     * Happens if CoreSync binary is not present.  Ask end user install coresync\n     */\n    SAMErrorSubCode[SAMErrorSubCode[\"CORESYNC_BINARY_NOT_FOUND\"] = 3] = \"CORESYNC_BINARY_NOT_FOUND\";\n    /**\n     * Happens if CoreSync is not installed. Ask end user to install/upgrade coresync.\n     */\n    SAMErrorSubCode[SAMErrorSubCode[\"CORESYNC_NOT_INSTALLED\"] = 4] = \"CORESYNC_NOT_INSTALLED\";\n    /**\n     * Happens if asset failed to sync. Sync will be retried by ACPL.\n     * Cient may wait for subsequent sync notification for the asset or retry\n     * the operation.\n     */\n    SAMErrorSubCode[SAMErrorSubCode[\"SYNC_FAILED\"] = 5] = \"SYNC_FAILED\";\n    /**\n     * Syncing the asset failed due to an EditEdit conflict, but the conflict\n     * was resolved\n     */\n    SAMErrorSubCode[SAMErrorSubCode[\"SYNC_FAILED_EDIT_EDIT_RESOLVED\"] = 6] = \"SYNC_FAILED_EDIT_EDIT_RESOLVED\";\n    /**\n     * Syncing the asset failed due to an EditDelete conflict, but the conflict\n     * was resolved\n     */\n    SAMErrorSubCode[SAMErrorSubCode[\"SYNC_FAILED_EDIT_DELETE_RESOLVED\"] = 7] = \"SYNC_FAILED_EDIT_DELETE_RESOLVED\";\n    /**\n     * An error occured while moving an orphan to the root folder.\n     */\n    SAMErrorSubCode[SAMErrorSubCode[\"COMMIT_ON_ORPHAN_ERROR\"] = 8] = \"COMMIT_ON_ORPHAN_ERROR\";\n    /**\n     * Admin disabled creation of Projects\n     * https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=assetscollab&title=Proposal%3A+Project+API+V3+-+Capability\n     */\n    SAMErrorSubCode[SAMErrorSubCode[\"PROJECTS_ADMIN_ONLY\"] = 9] = \"PROJECTS_ADMIN_ONLY\";\n    /**\n     * 404 specific projects errors.\n     * https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=assetscollab&title=Proposal%3A+Project+API+V3+-+Capability\n     */\n    SAMErrorSubCode[SAMErrorSubCode[\"PROJECTS_INVALID_REPOSITORY\"] = 10] = \"PROJECTS_INVALID_REPOSITORY\";\n    SAMErrorSubCode[SAMErrorSubCode[\"PROJECTS_NO_HOME_REPOSITORY\"] = 11] = \"PROJECTS_NO_HOME_REPOSITORY\";\n})(SAMErrorSubCode || (SAMErrorSubCode = {}));\nexport var ProblemType;\n(function (ProblemType) {\n    ProblemType[\"LIMIT_CHANGELOGRETENTION\"] = \"http://ns.adobe.com/adobecloud/problem/limit/changelogretention\";\n    ProblemType[\"OPERATION_FAILED\"] = \"adobecloud/problem/operation_failed\";\n    ProblemType[\"SUBSCRIPTION_COUNT\"] = \"http://ns.adobe.com/adobecloud/problem/limit/subscriptioncount\";\n    ProblemType[\"QUOTA_EXCEEDED\"] = \"http://ns.adobe.com/adobecloud/problem/quotaexceeded\";\n    ProblemType[\"CHILDREN_LIMIT_EXCEEDED\"] = \"http://ns.adobe.com/adobecloud/problem/limit/childrencount\";\n    ProblemType[\"NO_HOME_REPOSITORY\"] = \"http://ns.adobe.com/projects/problem/no-home-repository\";\n    ProblemType[\"INVALID_HOME_REPOSITORY\"] = \"http://ns.adobe.com/projects/problem/invalid-repository\";\n    ProblemType[\"ADMIN_ONLY\"] = \"http://ns.adobe.com/projects/problem/admin-only\";\n    ProblemType[\"ACCESS_DENIED\"] = \"http://ns.adobe.com/adobecloud/problem/accessdenied\";\n})(ProblemType || (ProblemType = {}));\nexport const SAMErrorName = 'SAMError';\n","export var IFrameioAuthenticationStatus;\n(function (IFrameioAuthenticationStatus) {\n    IFrameioAuthenticationStatus[IFrameioAuthenticationStatus[\"authLoggedOut\"] = 0] = \"authLoggedOut\";\n    IFrameioAuthenticationStatus[IFrameioAuthenticationStatus[\"authLoggedIn\"] = 1] = \"authLoggedIn\";\n    IFrameioAuthenticationStatus[IFrameioAuthenticationStatus[\"authExpired\"] = 2] = \"authExpired\";\n})(IFrameioAuthenticationStatus || (IFrameioAuthenticationStatus = {}));\n","export var CustomModelPublishedState;\n(function (CustomModelPublishedState) {\n    CustomModelPublishedState[\"DRAFT\"] = \"draft\";\n    CustomModelPublishedState[\"READY\"] = \"ready\";\n    CustomModelPublishedState[\"PUBLISHED\"] = \"published\";\n    CustomModelPublishedState[\"UNPUBLISHED\"] = \"unpublished\";\n    CustomModelPublishedState[\"QUEUED\"] = \"queued\";\n    CustomModelPublishedState[\"TRAINING\"] = \"training\";\n    CustomModelPublishedState[\"FAILED\"] = \"failed\";\n    CustomModelPublishedState[\"CANCELLED\"] = \"cancelled\";\n    CustomModelPublishedState[\"ALL\"] = \"all\";\n})(CustomModelPublishedState || (CustomModelPublishedState = {}));\nexport var CustomModelOrderBy;\n(function (CustomModelOrderBy) {\n    CustomModelOrderBy[\"MODIFY_DATE\"] = \"modifyDate\";\n    CustomModelOrderBy[\"CREATE_DATE\"] = \"createDate\";\n    CustomModelOrderBy[\"NAME\"] = \"name\";\n})(CustomModelOrderBy || (CustomModelOrderBy = {}));\n","export var CustomModelPublishedState;\n(function (CustomModelPublishedState) {\n    CustomModelPublishedState[\"NEVER\"] = \"never\";\n    CustomModelPublishedState[\"PUBLISHED\"] = \"published\";\n    CustomModelPublishedState[\"UNPUBLISHED\"] = \"unpublished\";\n    /**\n     * @deprecated use {@link PUBLISHED} | {@link UNPUBLISHED} | {@link NEVER}\n     */\n    CustomModelPublishedState[\"DRAFT\"] = \"draft\";\n    /**\n     * @deprecated use {@link PUBLISHED} | {@link UNPUBLISHED} | {@link NEVER}\n     */\n    CustomModelPublishedState[\"READY\"] = \"ready\";\n    /**\n     * @deprecated use {@link PUBLISHED} | {@link UNPUBLISHED} | {@link NEVER}\n     */\n    CustomModelPublishedState[\"QUEUED\"] = \"queued\";\n    /**\n     * @deprecated use {@link PUBLISHED} | {@link UNPUBLISHED} | {@link NEVER}\n     */\n    CustomModelPublishedState[\"TRAINING\"] = \"training\";\n    /**\n     * @deprecated use {@link PUBLISHED} | {@link UNPUBLISHED} | {@link NEVER}\n     */\n    CustomModelPublishedState[\"FAILED\"] = \"failed\";\n    /**\n     * @deprecated use {@link PUBLISHED} | {@link UNPUBLISHED} | {@link NEVER}\n     */\n    CustomModelPublishedState[\"CANCELLED\"] = \"cancelled\";\n    /**\n     * @deprecated use {@link PUBLISHED} | {@link UNPUBLISHED} | {@link NEVER}\n     */\n    CustomModelPublishedState[\"ALL\"] = \"all\";\n})(CustomModelPublishedState || (CustomModelPublishedState = {}));\nexport var CustomModelOrderBy;\n(function (CustomModelOrderBy) {\n    CustomModelOrderBy[\"MODIFY_DATE\"] = \"modified_date\";\n    CustomModelOrderBy[\"CREATE_DATE\"] = \"created_date\";\n    CustomModelOrderBy[\"NAME\"] = \"name\";\n})(CustomModelOrderBy || (CustomModelOrderBy = {}));\n","export var RelType;\n(function (RelType) {\n    RelType[\"PRIMARY\"] = \"http://ns.adobe.com/adobecloud/rel/primary\";\n    RelType[\"ID\"] = \"http://ns.adobe.com/adobecloud/rel/id\";\n    RelType[\"PATH\"] = \"http://ns.adobe.com/adobecloud/rel/path\";\n    RelType[\"RENDITION\"] = \"http://ns.adobe.com/adobecloud/rel/rendition\";\n    RelType[\"COMPONENT_RENDITION\"] = \"http://ns.adobe.com/adobecloud/rel/componentRendition\";\n    RelType[\"MANIFEST\"] = \"http://ns.adobe.com/adobecloud/rel/manifest\";\n    RelType[\"QUOTA\"] = \"http://ns.adobe.com/adobecloud/rel/quota\";\n    RelType[\"COMPONENT\"] = \"http://ns.adobe.com/adobecloud/rel/component\";\n    RelType[\"PAGE\"] = \"http://ns.adobe.com/adobecloud/rel/page\";\n    RelType[\"DISCARD\"] = \"http://ns.adobe.com/adobecloud/rel/discard\";\n    RelType[\"RESTORE\"] = \"http://ns.adobe.com/adobecloud/rel/restore\";\n    RelType[\"DIRECTORY\"] = \"http://ns.adobe.com/adobecloud/rel/directory\";\n    RelType[\"DIRECTORY_BASE\"] = \"http://ns.adobe.com/adobecloud/rel/directory/base\";\n    RelType[\"AC_EFFECTIVE\"] = \"http://ns.adobe.com/adobecloud/rel/ac/effective\";\n    RelType[\"AC_POLICY\"] = \"http://ns.adobe.com/adobecloud/rel/ac/policy\";\n    RelType[\"AC_CHECK\"] = \"http://ns.adobe.com/adobecloud/rel/ac/check\";\n    RelType[\"CREATE\"] = \"http://ns.adobe.com/adobecloud/rel/create\";\n    RelType[\"REPOSITORY\"] = \"http://ns.adobe.com/adobecloud/rel/repository\";\n    RelType[\"RESOLVE_ID\"] = \"http://ns.adobe.com/adobecloud/rel/resolve/id\";\n    RelType[\"RESOLVE_PATH\"] = \"http://ns.adobe.com/adobecloud/rel/resolve/path\";\n    RelType[\"OPS\"] = \"http://ns.adobe.com/adobecloud/rel/ops\";\n    RelType[\"BLOCK_INITIALIZE\"] = \"http://ns.adobe.com/adobecloud/rel/block/init\";\n    RelType[\"BLOCK_TRANSFER\"] = \"http://ns.adobe.com/adobecloud/rel/block/transfer\";\n    RelType[\"BLOCK_FINALIZE\"] = \"http://ns.adobe.com/adobecloud/rel/block/finalize\";\n    RelType[\"REPO_METADATA\"] = \"http://ns.adobe.com/adobecloud/rel/metadata/repository\";\n    RelType[\"APP_METADATA\"] = \"http://ns.adobe.com/adobecloud/rel/metadata/application\";\n    RelType[\"EMBEDDED_METADATA\"] = \"http://ns.adobe.com/adobecloud/rel/metadata/embedded\";\n    RelType[\"PERUSER_METADATA\"] = \"http://ns.adobe.com/adobecloud/rel/metadata/peruser\";\n    RelType[\"ANNOTATIONS\"] = \"http://ns.adobe.com/adobecloud/rel/annotations\";\n    RelType[\"DOWNLOAD\"] = \"http://ns.adobe.com/adobecloud/rel/download\";\n    RelType[\"DESCRIBED_BY\"] = \"describedBy\";\n    RelType[\"VERSION\"] = \"version-history\";\n    RelType[\"SUBSCRIPTION_CREATE\"] = \"subscription/create\";\n    RelType[\"NOTIFICATIONS_LONGPOLL\"] = \"notifications/longpoll\";\n    RelType[\"ONS_CHANGELOG\"] = \"ons/changelog\";\n    RelType[\"REPOSITORIES_PAGE\"] = \"http://ns.adobe.com/repositories/rel/page\";\n    RelType[\"TEAMS_CREATE\"] = \"http://ns.adobe.com/teams/rel/create\";\n    RelType[\"TEAMS_DISCARD\"] = \"http://ns.adobe.com/teams/rel/discard\";\n    RelType[\"TEAMS_RESTORE\"] = \"http://ns.adobe.com/teams/rel/restore\";\n    RelType[\"TEAMS_RENAME\"] = \"http://ns.adobe.com/teams/rel/rename\";\n    RelType[\"TEAMS_PROPERTIES\"] = \"http://ns.adobe.com/teams/rel/properties\";\n    RelType[\"TEAMS_PAGE\"] = \"http://ns.adobe.com/teams/rel/page\";\n    RelType[\"TEAMS_PRIMARY\"] = \"http://ns.adobe.com/teams/rel/primary\";\n    RelType[\"TEAM_PROVISION\"] = \"http://ns.adobe.com/teams/rel/provision\";\n    RelType[\"WORKSPACES_CONTEXT\"] = \"http://ns.adobe.com/ccprojects/rel/context\";\n    RelType[\"WORKSPACES_BOOKMARKS_BATCH\"] = \"http://ns.adobe.com/ccprojects/rel/bookmarks/batch\";\n    RelType[\"WORKSPACES_PRIMARY\"] = \"http://ns.adobe.com/ccprojects/rel/primary\";\n    RelType[\"WORKSPACES_CREATE\"] = \"http://ns.adobe.com/ccprojects/rel/create\";\n    RelType[\"WORKSPACES_PAGE\"] = \"http://ns.adobe.com/ccprojects/rel/page\";\n    RelType[\"PROJECTS_LIBRARIES_PAGE\"] = \"http://ns.adobe.com/ccprojects/rel/libraries/page\";\n    RelType[\"PROJECTS_LIBRARIES_CREATE\"] = \"http://ns.adobe.com/ccprojects/rel/libraries/create\";\n    RelType[\"PROJECTS_LIBRARIES_BATCH\"] = \"http://ns.adobe.com/ccprojects/rel/libraries/batch\";\n    RelType[\"GENERIC_PAGE\"] = \"page\";\n    RelType[\"GENERIC_NEXT\"] = \"next\";\n    RelType[\"ATS_MOVE\"] = \"http://ns.adobe.com/ats/rel/move\";\n    RelType[\"REVIEW_SERVICE_PROVISION\"] = \"http://ns.adobe.com/ccassetreview/rel/provision\";\n    RelType[\"REVIEW_SERVICE_DISCARD\"] = \"http://ns.adobe.com/ccassetreview/rel/discard\";\n    RelType[\"REVIEW_SERVICE_OUTPUTS\"] = \"http://ns.adobe.com/ccassetreview/rel/outputs\";\n    RelType[\"REVIEW_SERIVCE_HAS_OUTPUTS\"] = \"http://ns.adobe.com/ccassetreview/rel/hasoutputs\";\n    RelType[\"PROJECTS_CONTEXT\"] = \"http://ns.adobe.com/projects/rel/context\";\n    RelType[\"PROJECTS_PRIMARY\"] = \"http://ns.adobe.com/projects/rel/primary\";\n    RelType[\"PROJECTS_COLLECTION\"] = \"http://ns.adobe.com/projects/rel/collection\";\n    RelType[\"PROJECTS_CREATE\"] = \"http://ns.adobe.com/projects/rel/create\";\n    RelType[\"PROJECTS_RENAME\"] = \"http://ns.adobe.com/projects/rel/rename\";\n    RelType[\"PROJECTS_CREATOR\"] = \"http://ns.adobe.com/projects/rel/creator\";\n    RelType[\"PROJECTS_GRADIENTS_COLLECTION\"] = \"http://ns.adobe.com/gradients/rel/collection\";\n    RelType[\"PROJECTS_CAPABILITY\"] = \"http://ns.adobe.com/projects/rel/capability\";\n    RelType[\"ORGANIZATIONS_COLLECTION\"] = \"http://ns.adobe.com/organizations/rel/collection\";\n    RelType[\"PROJECTS_RECENT\"] = \"http://ns.adobe.com/projects/rel/recent\";\n    RelType[\"PROJECTS_REFERENCE_CREATE\"] = \"http://ns.adobe.com/projects/rel/references/create\";\n    RelType[\"PROJECTS_REFERENCE_PRIMARY\"] = \"http://ns.adobe.com/projects/rel/references/primary\";\n    RelType[\"ASSIGNMENTS_ASSIGN\"] = \"http://ns.adobe.com/assignments/rel/assign\";\n    RelType[\"ASSIGNMENTS_CODE\"] = \"http://ns.adobe.com/assignments/rel/code\";\n    RelType[\"ASSIGNMENTS_COLLECTION\"] = \"http://ns.adobe.com/assignments/rel/collection\";\n    RelType[\"ASSIGNMENTS_CREATE\"] = \"http://ns.adobe.com/assignments/rel/create\";\n    RelType[\"ASSIGNMENTS_PRIMARY\"] = \"http://ns.adobe.com/assignments/rel/primary\";\n    RelType[\"ASSIGNMENTS_RETURN\"] = \"http://ns.adobe.com/assignments/rel/return\";\n    RelType[\"ASSIGNMENTS_START\"] = \"http://ns.adobe.com/assignments/rel/start\";\n    RelType[\"ASSIGNMENTS_SUBMIT\"] = \"http://ns.adobe.com/assignments/rel/submit\";\n    RelType[\"STUDENT_ASSIGNMENTS_COLLECTION\"] = \"http://ns.adobe.com/studentAssignments/rel/collection\";\n    RelType[\"STUDENT_ASSIGNMENTS_PRIMARY\"] = \"http://ns.adobe.com/studentAssignments/rel/primary\";\n})(RelType || (RelType = {}));\n","import { RelType } from './LinkUtils.js';\nexport var IProjectPatchKeys;\n(function (IProjectPatchKeys) {\n    IProjectPatchKeys[\"GRADIENT_ID\"] = \"/project:rendition/gradientId\";\n})(IProjectPatchKeys || (IProjectPatchKeys = {}));\nexport var ProjectViews;\n(function (ProjectViews) {\n    /**\n     * Combination of Projects returned from yours and sharedWithYou.\n     */\n    ProjectViews[ProjectViews[\"All\"] = 0] = \"All\";\n    /**\n     *  Only the Projects that are considered yours:\n     *  For CCI profile, only the projects within /projects directory are returned.\n     *  For CCT/CCE profile, a combination of projects within the assigned user storage for the profile,\n     *  and the shared storage of Org are returned. If the profile only has access to the\n     *  Project via inheritance or through orgEverybody group, then it will not be included.\n     */\n    ProjectViews[ProjectViews[\"Yours\"] = 1] = \"Yours\";\n    /**\n     * Only the Projects that are shared with the requestor. For both CCI and CCT/CCE profiles,\n     * the collection would be the negation of yours with the exception that the Projects shared\n     * via orgEverybody group are still not included.\n     */\n    ProjectViews[ProjectViews[\"SWY\"] = 2] = \"SWY\";\n    /**\n     * The full list of Projects regardless of how it is accessed. This includes Projects accessible\n     * via inheritance and shared via orgEverybody group.\n     */\n    ProjectViews[ProjectViews[\"Admin\"] = 3] = \"Admin\";\n    /**\n     * All projects that match a particluar organization specified in ProjectFilter.organizationID\n     */\n    ProjectViews[ProjectViews[\"Organization\"] = 4] = \"Organization\";\n    /**\n     * The list of recent projects. This is determined by the lastAccessedDate of the project.\n     */\n    ProjectViews[ProjectViews[\"Recent\"] = 5] = \"Recent\";\n})(ProjectViews || (ProjectViews = {}));\nexport var ProjectCapabilities;\n(function (ProjectCapabilities) {\n    ProjectCapabilities[\"CREATE\"] = \"create\";\n})(ProjectCapabilities || (ProjectCapabilities = {}));\nexport var ProjectLeaveReason;\n(function (ProjectLeaveReason) {\n    ProjectLeaveReason[ProjectLeaveReason[\"PENDING\"] = 0] = \"PENDING\";\n    ProjectLeaveReason[ProjectLeaveReason[\"CAN_LEAVE\"] = 1] = \"CAN_LEAVE\";\n    /**\n     * All false reasons.\n     */\n    ProjectLeaveReason[ProjectLeaveReason[\"CANNOT_LEAVE_NO_COLLABORATORS\"] = 2] = \"CANNOT_LEAVE_NO_COLLABORATORS\";\n    ProjectLeaveReason[ProjectLeaveReason[\"CANNOT_LEAVE_ADDRESS_BOOK_GROUP_MEMBER\"] = 3] = \"CANNOT_LEAVE_ADDRESS_BOOK_GROUP_MEMBER\";\n    ProjectLeaveReason[ProjectLeaveReason[\"CANNOT_LEAVE_LAST_COLLABORATOR\"] = 4] = \"CANNOT_LEAVE_LAST_COLLABORATOR\";\n    /**\n     * @deprecated -- will be and removed on or after 2024-10-01.\n     */\n    ProjectLeaveReason[ProjectLeaveReason[\"CANNOT_LEAVE_LAST_DIRECT_COLLABORATOR\"] = 5] = \"CANNOT_LEAVE_LAST_DIRECT_COLLABORATOR\";\n    ProjectLeaveReason[ProjectLeaveReason[\"CANNOT_LEAVE_IS_ADMIN_OF_PROJECT\"] = 6] = \"CANNOT_LEAVE_IS_ADMIN_OF_PROJECT\";\n    ProjectLeaveReason[ProjectLeaveReason[\"CANNOT_LEAVE_LAST_DIRECT_COLLAB_WITH_SHARE_PERMISSION\"] = 7] = \"CANNOT_LEAVE_LAST_DIRECT_COLLAB_WITH_SHARE_PERMISSION\";\n    ProjectLeaveReason[ProjectLeaveReason[\"CANNOT_LEAVE_IS_OWNER\"] = 8] = \"CANNOT_LEAVE_IS_OWNER\";\n})(ProjectLeaveReason || (ProjectLeaveReason = {}));\n/**\n * Reasons for why the user can or cannot create a project.\n */\nexport var CanCreateProjectReason;\n(function (CanCreateProjectReason) {\n    CanCreateProjectReason[CanCreateProjectReason[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n    CanCreateProjectReason[CanCreateProjectReason[\"ALLOWED\"] = 1] = \"ALLOWED\";\n    CanCreateProjectReason[CanCreateProjectReason[\"ADMIN_DISABLED\"] = 2] = \"ADMIN_DISABLED\";\n    CanCreateProjectReason[CanCreateProjectReason[\"INVALID_REPOSITORY\"] = 3] = \"INVALID_REPOSITORY\";\n    CanCreateProjectReason[CanCreateProjectReason[\"NO_HOME_REPOSITORY\"] = 4] = \"NO_HOME_REPOSITORY\";\n})(CanCreateProjectReason || (CanCreateProjectReason = {}));\n/**\n * The enumerated values for the `project:directorySubType` metadata field.\n */\nexport var ProjectDirectorySubtype;\n(function (ProjectDirectorySubtype) {\n    ProjectDirectorySubtype[\"WF_PORTFOLIO\"] = \"wfPortfolio\";\n    ProjectDirectorySubtype[\"WF_PROGRAM\"] = \"wfProgram\";\n    ProjectDirectorySubtype[\"WF_PROJECT\"] = \"wfProject\";\n    ProjectDirectorySubtype[\"WF_TEMPLATE\"] = \"wfProjectTemplate\";\n    ProjectDirectorySubtype[\"CC_PROJECTS\"] = \"ccProject\";\n})(ProjectDirectorySubtype || (ProjectDirectorySubtype = {}));\n","var Permission;\n(function (Permission) {\n    Permission[Permission[\"None\"] = 0] = \"None\";\n    Permission[Permission[\"Ack\"] = 1] = \"Ack\";\n    Permission[Permission[\"Read\"] = 2] = \"Read\";\n    Permission[Permission[\"Write\"] = 4] = \"Write\";\n    Permission[Permission[\"Delete\"] = 8] = \"Delete\";\n    Permission[Permission[\"Share\"] = 16] = \"Share\";\n    Permission[Permission[\"Rename\"] = 32] = \"Rename\";\n    Permission[Permission[\"Move\"] = 64] = \"Move\";\n    Permission[Permission[\"Discard\"] = 128] = \"Discard\";\n    Permission[Permission[\"Restore\"] = 256] = \"Restore\";\n    Permission[Permission[\"Duplicate\"] = 512] = \"Duplicate\";\n    Permission[Permission[\"ReadAppMetadata\"] = 1024] = \"ReadAppMetadata\";\n    Permission[Permission[\"WriteComment\"] = 2048] = \"WriteComment\";\n})(Permission || (Permission = {}));\nexport { Permission };\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport { RelType } from './LinkUtils.js';\nexport var AssignmentStatus;\n(function (AssignmentStatus) {\n    AssignmentStatus[\"DRAFT\"] = \"DRAFT\";\n    AssignmentStatus[\"ASSIGNED\"] = \"ASSIGNED\";\n})(AssignmentStatus || (AssignmentStatus = {}));\nexport var AssignmentSubmissionOwnershipEnums;\n(function (AssignmentSubmissionOwnershipEnums) {\n    AssignmentSubmissionOwnershipEnums[\"ANY\"] = \"ANY\";\n    AssignmentSubmissionOwnershipEnums[\"NONE\"] = \"NONE\";\n    AssignmentSubmissionOwnershipEnums[\"SELF\"] = \"SELF\";\n})(AssignmentSubmissionOwnershipEnums || (AssignmentSubmissionOwnershipEnums = {}));\nexport var AssignmentTaskIDEnums;\n(function (AssignmentTaskIDEnums) {\n    AssignmentTaskIDEnums[\"albumCover\"] = \"album-cover\";\n    AssignmentTaskIDEnums[\"animatedCharacter\"] = \"animated-character\";\n    AssignmentTaskIDEnums[\"bannerPrint\"] = \"banner-print\";\n    AssignmentTaskIDEnums[\"bannerWeb\"] = \"banner-web\";\n    AssignmentTaskIDEnums[\"blogGraphic\"] = \"blog-graphic\";\n    AssignmentTaskIDEnums[\"blogHeader\"] = \"blog-header\";\n    AssignmentTaskIDEnums[\"bookCover\"] = \"book-cover\";\n    AssignmentTaskIDEnums[\"bookmark\"] = \"bookmark\";\n    AssignmentTaskIDEnums[\"brochure\"] = \"brochure\";\n    AssignmentTaskIDEnums[\"businessCard\"] = \"business-card\";\n    AssignmentTaskIDEnums[\"calendar\"] = \"calendar\";\n    AssignmentTaskIDEnums[\"cardGreeting\"] = \"card-greeting\";\n    AssignmentTaskIDEnums[\"certificate\"] = \"certificate\";\n    AssignmentTaskIDEnums[\"checklist\"] = \"checklist\";\n    AssignmentTaskIDEnums[\"classSchedule\"] = \"class-schedule\";\n    AssignmentTaskIDEnums[\"comicStrip\"] = \"comic-strip\";\n    AssignmentTaskIDEnums[\"conceptMap\"] = \"concept-map\";\n    AssignmentTaskIDEnums[\"couponSheet\"] = \"coupon-sheet\";\n    AssignmentTaskIDEnums[\"coverPage\"] = \"cover-page\";\n    AssignmentTaskIDEnums[\"deviceCameraRecording\"] = \"device-camera-recording\";\n    AssignmentTaskIDEnums[\"displayAd\"] = \"display-ad\";\n    AssignmentTaskIDEnums[\"dividerPage\"] = \"divider-page\";\n    AssignmentTaskIDEnums[\"drawing\"] = \"drawing\";\n    AssignmentTaskIDEnums[\"drawingWorksheet\"] = \"drawing-worksheet\";\n    AssignmentTaskIDEnums[\"ebookCover\"] = \"ebook-cover\";\n    AssignmentTaskIDEnums[\"emailHeader\"] = \"email-header\";\n    AssignmentTaskIDEnums[\"etsyShopBanner\"] = \"etsy-shop-banner\";\n    AssignmentTaskIDEnums[\"etsyShopCover\"] = \"etsy-shop-cover\";\n    AssignmentTaskIDEnums[\"eventbriteHeader\"] = \"eventbrite-header\";\n    AssignmentTaskIDEnums[\"facebookAd\"] = \"facebook-ad\";\n    AssignmentTaskIDEnums[\"facebookEventCover\"] = \"facebook-event-cover\";\n    AssignmentTaskIDEnums[\"facebookGroupCover\"] = \"facebook-group-cover\";\n    AssignmentTaskIDEnums[\"facebookPageCover\"] = \"facebook-page-cover\";\n    AssignmentTaskIDEnums[\"facebookPost\"] = \"facebook-post\";\n    AssignmentTaskIDEnums[\"facebookProfileCover\"] = \"facebook-profile-cover\";\n    AssignmentTaskIDEnums[\"facebookShopCover\"] = \"facebook-shop-cover\";\n    AssignmentTaskIDEnums[\"facebookStory\"] = \"facebook-story\";\n    AssignmentTaskIDEnums[\"flashCard\"] = \"flash-card\";\n    AssignmentTaskIDEnums[\"flashCardSheet\"] = \"flash-card-sheet\";\n    AssignmentTaskIDEnums[\"flyer\"] = \"flyer\";\n    AssignmentTaskIDEnums[\"generatedImage\"] = \"generated-image\";\n    AssignmentTaskIDEnums[\"giftCertificate\"] = \"gift-certificate\";\n    AssignmentTaskIDEnums[\"giftTag\"] = \"gift-tag\";\n    AssignmentTaskIDEnums[\"googleClassroomBanner\"] = \"google-classroom-banner\";\n    AssignmentTaskIDEnums[\"graph\"] = \"graph\";\n    AssignmentTaskIDEnums[\"graphicOrganizer\"] = \"graphic-organizer\";\n    AssignmentTaskIDEnums[\"idCard\"] = \"id-card\";\n    AssignmentTaskIDEnums[\"infographic\"] = \"infographic\";\n    AssignmentTaskIDEnums[\"instagramAd\"] = \"instagram-ad\";\n    AssignmentTaskIDEnums[\"instagramCarousel\"] = \"instagram-carousel\";\n    AssignmentTaskIDEnums[\"instagramLandscapePost\"] = \"instagram-landscape-post\";\n    AssignmentTaskIDEnums[\"instagramPortraitPost\"] = \"instagram-portrait-post\";\n    AssignmentTaskIDEnums[\"instagramReel\"] = \"instagram-reel\";\n    AssignmentTaskIDEnums[\"instagramSquarePost\"] = \"instagram-square-post\";\n    AssignmentTaskIDEnums[\"instagramStory\"] = \"instagram-story\";\n    AssignmentTaskIDEnums[\"instagramStoryAd\"] = \"instagram-story-ad\";\n    AssignmentTaskIDEnums[\"invitation\"] = \"invitation\";\n    AssignmentTaskIDEnums[\"invoice\"] = \"invoice\";\n    AssignmentTaskIDEnums[\"journal\"] = \"journal\";\n    AssignmentTaskIDEnums[\"label\"] = \"label\";\n    AssignmentTaskIDEnums[\"labelSheet\"] = \"label-sheet\";\n    AssignmentTaskIDEnums[\"leafletTrifold\"] = \"leaflet-trifold\";\n    AssignmentTaskIDEnums[\"lessonPlan\"] = \"lesson-plan\";\n    AssignmentTaskIDEnums[\"letter\"] = \"letter\";\n    AssignmentTaskIDEnums[\"letterhead\"] = \"letterhead\";\n    AssignmentTaskIDEnums[\"lineAdSmall\"] = \"line-ad-small\";\n    AssignmentTaskIDEnums[\"lineAdSquare\"] = \"line-ad-square\";\n    AssignmentTaskIDEnums[\"lineAdSquareVideo\"] = \"line-ad-square-video\";\n    AssignmentTaskIDEnums[\"lineAdVertical\"] = \"line-ad-vertical\";\n    AssignmentTaskIDEnums[\"lineRichMenuLarge\"] = \"line-rich-menu-large\";\n    AssignmentTaskIDEnums[\"lineRichMenuSmall\"] = \"line-rich-menu-small\";\n    AssignmentTaskIDEnums[\"lineRichMessage\"] = \"line-rich-message\";\n    AssignmentTaskIDEnums[\"linkedinBlogPost\"] = \"linkedin-blog-post\";\n    AssignmentTaskIDEnums[\"linkedinPost\"] = \"linkedin-post\";\n    AssignmentTaskIDEnums[\"linkedinProfileCover\"] = \"linkedin-profile-cover\";\n    AssignmentTaskIDEnums[\"logo\"] = \"logo\";\n    AssignmentTaskIDEnums[\"magazine\"] = \"magazine\";\n    AssignmentTaskIDEnums[\"mediaKit\"] = \"media-kit\";\n    AssignmentTaskIDEnums[\"meme\"] = \"meme\";\n    AssignmentTaskIDEnums[\"memo\"] = \"memo\";\n    AssignmentTaskIDEnums[\"menu\"] = \"menu\";\n    AssignmentTaskIDEnums[\"mindmap\"] = \"mindmap\";\n    AssignmentTaskIDEnums[\"mobileVideo\"] = \"mobile-video\";\n    AssignmentTaskIDEnums[\"mug\"] = \"mug\";\n    AssignmentTaskIDEnums[\"nameTag\"] = \"name-tag\";\n    AssignmentTaskIDEnums[\"newsletter\"] = \"newsletter\";\n    AssignmentTaskIDEnums[\"noteHeaderImage\"] = \"note-header-image\";\n    AssignmentTaskIDEnums[\"onlineNewsletter\"] = \"online-newsletter\";\n    AssignmentTaskIDEnums[\"onlineReport\"] = \"online-report\";\n    AssignmentTaskIDEnums[\"pamphlet\"] = \"pamphlet\";\n    AssignmentTaskIDEnums[\"photoBook\"] = \"photo-book\";\n    AssignmentTaskIDEnums[\"pinterestIdeaPin\"] = \"pinterest-idea-pin\";\n    AssignmentTaskIDEnums[\"pinterestPost\"] = \"pinterest-post\";\n    AssignmentTaskIDEnums[\"pinterestSquare\"] = \"pinterest-square\";\n    AssignmentTaskIDEnums[\"pinterestVertical\"] = \"pinterest-vertical\";\n    AssignmentTaskIDEnums[\"placeCard\"] = \"place-card\";\n    AssignmentTaskIDEnums[\"planner\"] = \"planner\";\n    AssignmentTaskIDEnums[\"playlistCover\"] = \"playlist-cover\";\n    AssignmentTaskIDEnums[\"podcastCover\"] = \"podcast-cover\";\n    AssignmentTaskIDEnums[\"postcard\"] = \"postcard\";\n    AssignmentTaskIDEnums[\"poster\"] = \"poster\";\n    AssignmentTaskIDEnums[\"presentation\"] = \"presentation\";\n    AssignmentTaskIDEnums[\"printAd\"] = \"print-ad\";\n    AssignmentTaskIDEnums[\"program\"] = \"program\";\n    AssignmentTaskIDEnums[\"proposal\"] = \"proposal\";\n    AssignmentTaskIDEnums[\"recipeCard\"] = \"recipe-card\";\n    AssignmentTaskIDEnums[\"redditCover\"] = \"reddit-cover\";\n    AssignmentTaskIDEnums[\"report\"] = \"report\";\n    AssignmentTaskIDEnums[\"reportCard\"] = \"report-card\";\n    AssignmentTaskIDEnums[\"resume\"] = \"resume\";\n    AssignmentTaskIDEnums[\"rubric\"] = \"rubric\";\n    AssignmentTaskIDEnums[\"snapchatAd\"] = \"snapchat-ad\";\n    AssignmentTaskIDEnums[\"snapchatFilter\"] = \"snapchat-filter\";\n    AssignmentTaskIDEnums[\"soundcloudBanner\"] = \"soundcloud-banner\";\n    AssignmentTaskIDEnums[\"tableOfContents\"] = \"table-of-contents\";\n    AssignmentTaskIDEnums[\"ticket\"] = \"ticket\";\n    AssignmentTaskIDEnums[\"tiktokAd\"] = \"tiktok-ad\";\n    AssignmentTaskIDEnums[\"tiktokVideo\"] = \"tiktok-video\";\n    AssignmentTaskIDEnums[\"tshirt\"] = \"tshirt\";\n    AssignmentTaskIDEnums[\"tumblrBanner\"] = \"tumblr-banner\";\n    AssignmentTaskIDEnums[\"twitchBanner\"] = \"twitch-banner\";\n    AssignmentTaskIDEnums[\"twitchOverlay\"] = \"twitch-overlay\";\n    AssignmentTaskIDEnums[\"twitterHeader\"] = \"twitter-header\";\n    AssignmentTaskIDEnums[\"twitterPost\"] = \"twitter-post\";\n    AssignmentTaskIDEnums[\"twitterVideo\"] = \"twitter-video\";\n    AssignmentTaskIDEnums[\"video\"] = \"video\";\n    AssignmentTaskIDEnums[\"wallpaperDesktop\"] = \"wallpaper-desktop\";\n    AssignmentTaskIDEnums[\"wallpaperMobile\"] = \"wallpaper-mobile\";\n    AssignmentTaskIDEnums[\"webpage\"] = \"webpage\";\n    AssignmentTaskIDEnums[\"webpageJournal\"] = \"webpage-journal\";\n    AssignmentTaskIDEnums[\"worksheet\"] = \"worksheet\";\n    AssignmentTaskIDEnums[\"youtubeBanner\"] = \"youtube-banner\";\n    AssignmentTaskIDEnums[\"youtubeDisplayAds\"] = \"youtube-display-ads\";\n    AssignmentTaskIDEnums[\"youtubeProfilePhoto\"] = \"youtube-profile-photo\";\n    AssignmentTaskIDEnums[\"youtubeShorts\"] = \"youtube-shorts\";\n    AssignmentTaskIDEnums[\"youtubeThumbnail\"] = \"youtube-thumbnail\";\n    AssignmentTaskIDEnums[\"youtubeVideo\"] = \"youtube-video\";\n    AssignmentTaskIDEnums[\"youtubeVideoAd\"] = \"youtube-video-ad\";\n    AssignmentTaskIDEnums[\"zoomBackground\"] = \"zoom-background\";\n})(AssignmentTaskIDEnums || (AssignmentTaskIDEnums = {}));\n","export var ClassroomMemberRole;\n(function (ClassroomMemberRole) {\n    ClassroomMemberRole[\"STUDENT\"] = \"student\";\n    ClassroomMemberRole[\"TEACHER\"] = \"teacher\";\n    ClassroomMemberRole[\"NONE\"] = \"none\";\n})(ClassroomMemberRole || (ClassroomMemberRole = {}));\nexport var ClassroomMemberStatus;\n(function (ClassroomMemberStatus) {\n    ClassroomMemberStatus[\"ACTIVE\"] = \"ACTIVE\";\n    ClassroomMemberStatus[\"DECLINED\"] = \"DECLINED\";\n    ClassroomMemberStatus[\"INACTIVE\"] = \"INACTIVE\";\n    ClassroomMemberStatus[\"INVITED\"] = \"INVITED\";\n    ClassroomMemberStatus[\"IN_REVIEW\"] = \"IN_REVIEW\";\n    ClassroomMemberStatus[\"NOT_A_MEMBER\"] = \"NOT_A_MEMBER\";\n    ClassroomMemberStatus[\"OWNER\"] = \"OWNER\";\n})(ClassroomMemberStatus || (ClassroomMemberStatus = {}));\nexport var ClassroomMemberInviteSource;\n(function (ClassroomMemberInviteSource) {\n    ClassroomMemberInviteSource[\"CLASSLINK\"] = \"CLASSLINK\";\n    ClassroomMemberInviteSource[\"CLEVER\"] = \"CLEVER\";\n    ClassroomMemberInviteSource[\"EMAIL\"] = \"EMAIL\";\n    ClassroomMemberInviteSource[\"GOOGLE_CLASSROOM\"] = \"GOOGLE_CLASSROOM\";\n    ClassroomMemberInviteSource[\"NONE\"] = \"NONE\";\n})(ClassroomMemberInviteSource || (ClassroomMemberInviteSource = {}));\n","export var LearningManagementSystems;\n(function (LearningManagementSystems) {\n    LearningManagementSystems[\"GC\"] = \"GC\";\n})(LearningManagementSystems || (LearningManagementSystems = {}));\nexport var LearningManagementSystemRoles;\n(function (LearningManagementSystemRoles) {\n    LearningManagementSystemRoles[\"STUDENT\"] = \"STUDENT\";\n    LearningManagementSystemRoles[\"TEACHER\"] = \"TEACHER\";\n})(LearningManagementSystemRoles || (LearningManagementSystemRoles = {}));\nexport var RosterImportState;\n(function (RosterImportState) {\n    RosterImportState[\"BLOCKED\"] = \"BLOCKED\";\n    RosterImportState[\"INVITED\"] = \"INVITED\";\n    RosterImportState[\"JOINED\"] = \"JOINED\";\n    RosterImportState[\"NOT_ENROLLED\"] = \"NOT_ENROLLED\";\n    RosterImportState[\"REMOVED\"] = \"REMOVED\";\n})(RosterImportState || (RosterImportState = {}));\nexport var ImportSourceType;\n(function (ImportSourceType) {\n    ImportSourceType[\"CLEVER\"] = \"clever\";\n    ImportSourceType[\"CLASS_LINK\"] = \"classlink\";\n})(ImportSourceType || (ImportSourceType = {}));\nexport var ClassroomStatus;\n(function (ClassroomStatus) {\n    ClassroomStatus[\"ACTIVE\"] = \"ACTIVE\";\n    ClassroomStatus[\"ARCHIVED\"] = \"ARCHIVED\";\n})(ClassroomStatus || (ClassroomStatus = {}));\nexport var ClassroomType;\n(function (ClassroomType) {\n    /** Allowed classrooms for Top Down organization users */\n    ClassroomType[\"TRUE\"] = \"TRUE\";\n    /** Allowed classrooms for Bottom up organization users */\n    ClassroomType[\"RESTRICTED\"] = \"RESTRICTED\";\n    /** Allowed classrooms for users on their personal account */\n    ClassroomType[\"UNRESTRICTED\"] = \"UNRESTRICTED\";\n    /** Not allowed classrooms */\n    ClassroomType[\"NONE\"] = \"NONE\";\n})(ClassroomType || (ClassroomType = {}));\nexport var SubjectTypes;\n(function (SubjectTypes) {\n    SubjectTypes[\"noSubject\"] = \"\";\n    SubjectTypes[\"allsubjects\"] = \"allsubjects\";\n    SubjectTypes[\"careersTechnicalEducation\"] = \"careersTechnicalEducation\";\n    SubjectTypes[\"computerScience\"] = \"computerScience\";\n    SubjectTypes[\"english\"] = \"english\";\n    SubjectTypes[\"math\"] = \"math\";\n    SubjectTypes[\"otherLanguages\"] = \"otherLanguages\";\n    SubjectTypes[\"others\"] = \"others\";\n    SubjectTypes[\"science\"] = \"science\";\n    SubjectTypes[\"socialStudies\"] = \"socialStudies\";\n    SubjectTypes[\"visualPerformingArts\"] = \"visualPerformingArts\";\n})(SubjectTypes || (SubjectTypes = {}));\nexport var ClassroomRole;\n(function (ClassroomRole) {\n    ClassroomRole[\"STUDENT\"] = \"STUDENT\";\n    ClassroomRole[\"TEACHER\"] = \"TEACHER\";\n})(ClassroomRole || (ClassroomRole = {}));\nexport var BlockApiSuccessResponses;\n(function (BlockApiSuccessResponses) {\n    BlockApiSuccessResponses[\"REMOVE_STUDENT_SUCCESS\"] = \"REMOVE_STUDENT_SUCCESS\";\n    BlockApiSuccessResponses[\"BLOCK_STUDENT_SUCCESS\"] = \"BLOCK_STUDENT_SUCCESS\";\n    BlockApiSuccessResponses[\"UNBLOCK_STUDENT_SUCCESS\"] = \"UNBLOCK_STUDENT_SUCCESS\";\n    BlockApiSuccessResponses[\"DELETE_DOMAIN_MAPPING_ACCEPTED\"] = \"DELETE_DOMAIN_MAPPING_ACCEPTED\";\n    BlockApiSuccessResponses[\"REMOVE_TEACHER_SUCCESS\"] = \"REMOVE_TEACHER_SUCCESS\";\n})(BlockApiSuccessResponses || (BlockApiSuccessResponses = {}));\nexport var MembershipStatus;\n(function (MembershipStatus) {\n    MembershipStatus[\"OWNER\"] = \"OWNER\";\n    MembershipStatus[\"ACTIVE\"] = \"ACTIVE\";\n    MembershipStatus[\"INACTIVE\"] = \"INACTIVE\";\n    MembershipStatus[\"INVITED\"] = \"INVITED\";\n    MembershipStatus[\"IN_REVIEW\"] = \"IN_REVIEW\";\n    MembershipStatus[\"DECLINED\"] = \"DECLINED\";\n    MembershipStatus[\"NOT_A_MEMBER\"] = \"NOT_A_MEMBER\";\n})(MembershipStatus || (MembershipStatus = {}));\nexport var CoTeacherEligibilityStatus;\n(function (CoTeacherEligibilityStatus) {\n    CoTeacherEligibilityStatus[\"ALLOWED\"] = \"ALLOWED\";\n    CoTeacherEligibilityStatus[\"NOT_ALLOWED\"] = \"NOT_ALLOWED\";\n})(CoTeacherEligibilityStatus || (CoTeacherEligibilityStatus = {}));\nexport var CoTeacherIneligibilityReason;\n(function (CoTeacherIneligibilityReason) {\n    CoTeacherIneligibilityReason[\"ACCOUNT_NOT_FOUND\"] = \"ACCOUNT_NOT_FOUND\";\n    CoTeacherIneligibilityReason[\"STUDENT_IN_CLASSROOM\"] = \"STUDENT_IN_CLASSROOM\";\n    CoTeacherIneligibilityReason[\"TEACHER_IN_CLASSROOM\"] = \"TEACHER_IN_CLASSROOM\";\n})(CoTeacherIneligibilityReason || (CoTeacherIneligibilityReason = {}));\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nexport var GenerationHistoryAssetType;\n(function (GenerationHistoryAssetType) {\n    GenerationHistoryAssetType[\"IMAGE\"] = \"image\";\n    GenerationHistoryAssetType[\"VIDEO\"] = \"video\";\n    GenerationHistoryAssetType[\"VECTOR\"] = \"vector\";\n    GenerationHistoryAssetType[\"AUDIO\"] = \"audio\";\n})(GenerationHistoryAssetType || (GenerationHistoryAssetType = {}));\nexport var GenerationHistoryAssetOrderBy;\n(function (GenerationHistoryAssetOrderBy) {\n    GenerationHistoryAssetOrderBy[\"CREATE_DATE\"] = \"created_date\";\n})(GenerationHistoryAssetOrderBy || (GenerationHistoryAssetOrderBy = {}));\nexport var GenerationHistoryAssetState;\n(function (GenerationHistoryAssetState) {\n    GenerationHistoryAssetState[\"QUEUED\"] = \"queued\";\n    GenerationHistoryAssetState[\"IN_PROGRESS\"] = \"inProgress\";\n    GenerationHistoryAssetState[\"SUCCESS\"] = \"success\";\n    GenerationHistoryAssetState[\"FAILED\"] = \"failed\";\n    GenerationHistoryAssetState[\"CANCELLED\"] = \"cancelled\";\n})(GenerationHistoryAssetState || (GenerationHistoryAssetState = {}));\n","export var LibraryOrderBy;\n(function (LibraryOrderBy) {\n    LibraryOrderBy[\"MODIFIED_DATE\"] = \"modified_date\";\n    LibraryOrderBy[\"CREATED_DATE\"] = \"created_date\";\n    LibraryOrderBy[\"NAME\"] = \"name\";\n})(LibraryOrderBy || (LibraryOrderBy = {}));\n/**\n * Enum for library owner filter\n * (If you update this list, also update LibraryFilter.matches/getRelationToFilter.)\n * @enum {string}\n */\nexport var LibraryOwnerFilter;\n(function (LibraryOwnerFilter) {\n    /**\n     * Personal libraries created in User Storage that are specifically stored inside the sync group: `/assets/adobe-libraries`\n     * Excludes CCI Project Libraries.\n     */\n    LibraryOwnerFilter[\"Personal\"] = \"private\";\n    /**\n     * Bookmarked public libraries.\n     * Currently will be ignored if combined with other ownership types.\n     */\n    LibraryOwnerFilter[\"Public\"] = \"public\";\n    /**\n     * Bookmarked incoming libraries. This includes:\n     * - Libraries shared directly with the user that the user has accepted the invite to\n     * - CCI Project Libraries which live in User Storage (`/users/{userId}` in ESM, `/` in USM and for unified users)\n     * - Project Libraries the user has followed (After SMU, these will all live in `/projects/{projectName}`)\n     */\n    LibraryOwnerFilter[\"Incoming\"] = \"incoming\";\n    /**\n     * Everything the user has acccess to that is not in User Storage, except public libraries.\n     * Includes: Project libraries, Incoming libraries (except CCI Project Libraries since they are in User Storage)\n     * Excludes: Public libraries, CCI Project Libraries, Private Libraries\n     */\n    LibraryOwnerFilter[\"Discovery\"] = \"discovery\";\n    /**\n     * A subset of 'discovery' that excludes already bookmarked libraries.\n     */\n    /**\n     * All of the above except public libraries currently (until supported by USS).\n     * If combined with other owner types, the others will be ignored.\n     */\n    LibraryOwnerFilter[\"All\"] = \"all\";\n})(LibraryOwnerFilter || (LibraryOwnerFilter = {}));\nexport var LibraryProjectFilterEnum;\n(function (LibraryProjectFilterEnum) {\n    /**\n     * Include all project libraries.\n     */\n    LibraryProjectFilterEnum[\"All\"] = \"all\";\n    /**\n     * Do not include any project libraries.\n     */\n    LibraryProjectFilterEnum[\"None\"] = \"none\";\n})(LibraryProjectFilterEnum || (LibraryProjectFilterEnum = {}));\n/**\n * @experimental API May change.\n *\n * Enum for library reference filter\n * This filter must be used in conjunction with a projectID via the LibraryProjectFilter.\n * @enum {string}\n */\nexport var LibraryReferenceFilter;\n(function (LibraryReferenceFilter) {\n    /**\n     * Return all libraries beneath the project or referenced by the project\n     */\n    LibraryReferenceFilter[\"All\"] = \"all\";\n    /**\n     * Include only libraries referenced by the project\n     */\n    LibraryReferenceFilter[\"Only\"] = \"only\";\n})(LibraryReferenceFilter || (LibraryReferenceFilter = {}));\nexport var LibraryRolesFilter;\n(function (LibraryRolesFilter) {\n    /**\n     * Include libraries that have no roles\n     */\n    LibraryRolesFilter[\"None\"] = \"none\";\n    /**\n     * Include libraries that have at least one role where role.type === 'brand'\n     */\n    LibraryRolesFilter[\"Brand\"] = \"brand\";\n    /**\n     * Include training set libraries. Currently the default, as it is the only option.\n     */\n    LibraryRolesFilter[\"TrainingSet\"] = \"cm_training_set\";\n})(LibraryRolesFilter || (LibraryRolesFilter = {}));\n/**\n * This enum is used for filtering the library list view for brands specifically based on it's publishing related app metadata.\n * This filter is only usable if the brand role is true.\n *\n * There are three types of brands that exist in the data:\n * 1. Published brands -- These are the brands that have brand:publishedFrom in their app metadata.\n * Nobody is able to update these brands directly, they can only be updated by publishing changes from their draft brand counterpart (which is what brand:publishedFrom points to).\n *\n * 2. Draft brands with a published counterpart -- These are the brands that have brand:publishedTo in their app metadata.\n * These brands do NOT show up in the list of brands, but still can be accessed when a user goes to edit a published brand.\n * This is so we can maintain a \"Draft\" state for a published brand so brand creators can make revisions without updating the published copy that is currently in use.\n *\n * 3. Draft brands that are unpublished -- These are brands that are not part of a published brand in any way, and thus have neither brand:publishedFrom nor brand:publishedTo.\n * These brands are editable, and do show up in the brands listing view.\n */\nexport var BrandPublishMetadataFilter;\n(function (BrandPublishMetadataFilter) {\n    /**\n     * Includes: Published brands\n     *\n     * Excludes: Unpublished draft brands, Draft brands with a published counterpart\n     */\n    BrandPublishMetadataFilter[\"PublishedBrands\"] = \"publishedBrands\";\n    /**\n     * Includes: Published brands, Unpublished draft brands\n     *\n     * Excludes: Draft brands with a published counterpart\n     */\n    BrandPublishMetadataFilter[\"AllBrands\"] = \"allBrands\";\n    /**\n     * Includes: Unpublished draft brands, Draft brands with a published counterpart\n     *\n     * Excludes: Published brands\n     */\n    BrandPublishMetadataFilter[\"AllEditableBrands\"] = \"allEditableBrands\";\n})(BrandPublishMetadataFilter || (BrandPublishMetadataFilter = {}));\n","export var MoveWarning;\n(function (MoveWarning) {\n    MoveWarning[MoveWarning[\"None\"] = 0] = \"None\";\n    MoveWarning[MoveWarning[\"CollaboratorMaybeEditing\"] = 1] = \"CollaboratorMaybeEditing\";\n    MoveWarning[MoveWarning[\"OwnerChange\"] = 2] = \"OwnerChange\";\n})(MoveWarning || (MoveWarning = {}));\nexport var CannotMoveReason;\n(function (CannotMoveReason) {\n    CannotMoveReason[CannotMoveReason[\"DifferentOwner\"] = 1] = \"DifferentOwner\";\n    CannotMoveReason[CannotMoveReason[\"PermissionDeniedDestination\"] = 2] = \"PermissionDeniedDestination\";\n    CannotMoveReason[CannotMoveReason[\"PermissionDeniedSource\"] = 3] = \"PermissionDeniedSource\";\n    CannotMoveReason[CannotMoveReason[\"NotAFolder\"] = 4] = \"NotAFolder\";\n    CannotMoveReason[CannotMoveReason[\"CrossBucketMoveDisabled\"] = 5] = \"CrossBucketMoveDisabled\";\n})(CannotMoveReason || (CannotMoveReason = {}));\n","import { RelType } from './LinkUtils.js';\nexport var StudentAssignmentStatus;\n(function (StudentAssignmentStatus) {\n    StudentAssignmentStatus[\"NOT_STARTED\"] = \"NOT_STARTED\";\n    StudentAssignmentStatus[\"IN_PROGRESS\"] = \"IN_PROGRESS\";\n    StudentAssignmentStatus[\"RETURNED\"] = \"RETURNED\";\n    StudentAssignmentStatus[\"SUBMITTED\"] = \"SUBMITTED\";\n})(StudentAssignmentStatus || (StudentAssignmentStatus = {}));\nexport var StudentAssignmentOwner;\n(function (StudentAssignmentOwner) {\n    StudentAssignmentOwner[\"Any\"] = \"ANY\";\n    StudentAssignmentOwner[\"Self\"] = \"SELF\";\n})(StudentAssignmentOwner || (StudentAssignmentOwner = {}));\n","export var RenditionStatus;\n(function (RenditionStatus) {\n    /**\n     * Initial status\n     */\n    RenditionStatus[RenditionStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n    RenditionStatus[RenditionStatus[\"Fetching\"] = 1] = \"Fetching\";\n    RenditionStatus[RenditionStatus[\"Done\"] = 2] = \"Done\";\n    /**\n     * Occurs when there are any errors around fetching the\n     * rendition from the service, AdobeAsset.clearRenditionError can\n     * be used to clear the error and fetch again.\n     */\n    RenditionStatus[RenditionStatus[\"Error\"] = 3] = \"Error\";\n})(RenditionStatus || (RenditionStatus = {}));\nexport var RenditionSize;\n(function (RenditionSize) {\n    RenditionSize[RenditionSize[\"Size64\"] = 64] = \"Size64\";\n    RenditionSize[RenditionSize[\"Size128\"] = 128] = \"Size128\";\n    RenditionSize[RenditionSize[\"Size256\"] = 256] = \"Size256\";\n    RenditionSize[RenditionSize[\"Size512\"] = 512] = \"Size512\";\n    RenditionSize[RenditionSize[\"Size1024\"] = 1024] = \"Size1024\";\n})(RenditionSize || (RenditionSize = {}));\nexport var RenditionType;\n(function (RenditionType) {\n    RenditionType[\"PNG\"] = \"image/png\";\n    RenditionType[\"JPEG\"] = \"image/jpeg\";\n})(RenditionType || (RenditionType = {}));\n","export var Mode;\n(function (Mode) {\n    Mode[\"MOBILE\"] = \"mobile\";\n    Mode[\"DESKTOP\"] = \"desktop\";\n})(Mode || (Mode = {}));\nexport var View;\n(function (View) {\n    View[\"WEB\"] = \"web\";\n    View[\"MOBILE\"] = \"mobile\";\n})(View || (View = {}));\nexport var MessageType;\n(function (MessageType) {\n    MessageType[\"OpenDocumentVersion\"] = \"onOpenDocumentVersion\";\n    MessageType[\"OpenDeepLinkVersion\"] = \"onOpenDeepLinkVersion\";\n    MessageType[\"VersionSelection\"] = \"onVersionSelection\";\n    MessageType[\"RestoreVersion\"] = \"onRestoreVersion\";\n    MessageType[\"Upgrade\"] = \"onUpgrade\";\n    MessageType[\"CreateCopy\"] = \"onCreateCopy\";\n    MessageType[\"Refresh\"] = \"onRefresh\";\n    MessageType[\"ModeChange\"] = \"onModeChange\";\n    MessageType[\"ThemeChange\"] = \"onThemeChange\";\n    MessageType[\"ClosePanel\"] = \"onClosePanel\";\n    MessageType[\"Error\"] = \"onError\";\n    MessageType[\"VersionBookmark\"] = \"onVersionBookmark\";\n    MessageType[\"VersionUnBookmark\"] = \"onVersionUnBookmark\";\n    MessageType[\"VersionBookmarkStart\"] = \"onVersionBookmarkStart\";\n    MessageType[\"VersionUnBookmarkStart\"] = \"onVersionUnBookmarkStart\";\n    MessageType[\"PermanentlyDeleteScreen\"] = \"onPermanentlyDeleteScreen\";\n    MessageType[\"PermanentlyDeleteVersion\"] = \"onPermanentlyDeleteVersion\";\n    MessageType[\"VersioningPanelLoadComplete\"] = \"onVersioningPanelLoadComplete\";\n    MessageType[\"PreviewThumbnailReceived\"] = \"onPreviewThumbnailReceived\";\n})(MessageType || (MessageType = {}));\n/* eslint-enable @typescript-eslint/no-namespace */\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ApolloError, ServerError, ServerParseError } from '@apollo/client';\nimport { SAM } from '@ccx-public/component-types';\nimport type { GraphQLFormattedError } from 'graphql';\n\nexport const SAMErrorCode = SAM.SAMErrorCode;\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type SAMErrorCode = SAM.SAMErrorCode;\n\nexport const SAMErrorSubCode = SAM.SAMErrorSubCode;\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type SAMErrorSubCode = SAM.SAMErrorSubCode;\n\ntype ErrorCodeInfo = {\n    code: SAMErrorCode;\n    message: (href: string) => string;\n    subCode?: SAMErrorSubCode;\n}\n\nconst errorCodeInfos = new Map<number, ErrorCodeInfo>([\n    [ 401, { code: SAMErrorCode.AUTHORIZATION_ERROR, message: (href) => `Authorization error: ${href}` } ],\n    // @note Maybe consider renaming this to FORBIDDEN_OPERATION instead of ACCESS_DENIED since\n    // that more closely aligns with the actual HTTP Status Code for 403\n    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/403\n    [ 403, { code: SAMErrorCode.ACCESS_DENIED, message: (href) => `Access to resource denied: ${href}` } ],\n    [ 404, { code: SAMErrorCode.NOT_FOUND, message: (href) => `Resource not found: ${href}` } ],\n    [ 409, { code: SAMErrorCode.CONFLICT, message: () => `Resource has a naming conflict.` } ],\n    [ 412, { code: SAMErrorCode.CONFLICT, message: () => `Resource has a conflict. Etag mismatch.` } ],\n]);\n\n/**\n * Convert server error codes to regular HTTP number codes.\n * '4041' -> 404\n * '404.1' -> 404\n * 4041 -> 404\n * 404 -> 404\n *\n * @param code from server\n * @returns http error code\n */\nfunction validateRepositoryCode(code: string | number): number {\n    // Repo APIs return string codes instead of numbers. In that case\n    if (typeof code === 'string') {\n        code = parseInt(code);\n    }\n\n    // Remove any extra floating point.\n    code = Math.floor(code);\n\n    // HTTP error codes only use 3 digits, but repo APIs can have even 5 digits.\n    // We only care about the most significant 3 digits though.\n    // https://git.corp.adobe.com/DMA/dcx-lib/blob/729085f1ed77936a1718377ea6cd5e3b16f6aada/lib/dcxlib/src/main/java/com/adobe/dcx/storagesession/StorageErrorCode.java#L12\n    while (code > 999) {\n        code = Math.floor(code / 10);\n    }\n\n    return code;\n}\n\nexport enum ProblemType {\n    LIMIT_CHANGELOGRETENTION = 'http://ns.adobe.com/adobecloud/problem/limit/changelogretention',\n    OPERATION_FAILED = 'adobecloud/problem/operation_failed',\n    SUBSCRIPTION_COUNT = 'http://ns.adobe.com/adobecloud/problem/limit/subscriptioncount',\n    QUOTA_EXCEEDED = 'http://ns.adobe.com/adobecloud/problem/quotaexceeded',\n    CHILDREN_LIMIT_EXCEEDED = 'http://ns.adobe.com/adobecloud/problem/limit/childrencount',\n    NO_HOME_REPOSITORY = 'http://ns.adobe.com/projects/problem/no-home-repository',\n    INVALID_HOME_REPOSITORY = 'http://ns.adobe.com/projects/problem/invalid-repository',\n    ADMIN_ONLY = 'http://ns.adobe.com/projects/problem/admin-only',\n    ACCESS_DENIED = 'http://ns.adobe.com/adobecloud/problem/accessdenied',\n    LAST_VERSION_LEFT = 'http://ns.adobe.com/adobecloud/problem/noversionleft',\n}\n\nfunction formatUnderlyingError(underlyingError: any): String {\n    let errorStr: string = '';\n    if (underlyingError !== null && underlyingError !== undefined) {\n        try {\n            errorStr = ` -> ${String(underlyingError)}`;\n        } catch {\n            // Avoid linter error on empty blocks.\n            void (0);\n        }\n    }\n    return errorStr;\n}\n\n/**\n * This additional info is to be only used for debugging purposes by clients\n * or internally by SAM.js\n */\nexport interface IAdditionalErrorInfo {\n    /**\n     * Response object mainly for HTTP errors created with the help of createWithResponse* API\n     */\n    response?: Response;\n    /**\n     * For services that return RFC 7807 `type` metadata in the body.\n     */\n    problemType?: string;\n    /**\n     * These could be errors thrown from a service or an error thrown while parsing JSON\n     */\n    underlyingError?: any;\n\n    /**\n     * X-Request-Id header extracted from response, if available\n     */\n    reqId?: string;\n\n    /**\n     * X-Breadcrumb-Trail header extracted from response, if available\n     */\n    breadcrumbTrail?: string;\n}\n\nexport const SAMErrorName = 'SAMError';\n\n/**\n * SAM.js would always throw back SAMError even when it is powered via SAM.cpp\n * The clients must rely only on `code` and `subCode` in order to write their business logic.\n * `description` can be used for logging purposes.\n * `_additionalInfo` should only be used for debugging purpose and there should not be any reference\n * to it in the code base.\n */\nexport class SAMError extends Error implements SAM.SAMError {\n    readonly code: SAMErrorCode;\n    readonly subCode?: SAMErrorSubCode;\n    /**\n     * The below fields are to be used by clients only for logging/debugging purposes only.\n     * For fine-grain error-handling, clients should only inspect `code` and `subCode`.\n     * They may be used internally by SAM.js\n     */\n    readonly description: string;\n    readonly _additionalInfo: IAdditionalErrorInfo;\n\n    protected constructor(\n        code: SAMErrorCode,\n        description: string,\n        additionalInfo: IAdditionalErrorInfo = {},\n        subCode?: SAMErrorSubCode\n    ) {\n        // NOTE: clients should not rely on SAMError.message for fine-grain error handling; instead, use `code` and `subcode`.\n        const message = `[${SAMErrorCode[code]}${ subCode === undefined ? '' : '-' + SAMErrorSubCode[subCode]}] ${description}${formatUnderlyingError(additionalInfo.underlyingError)}`;\n\n        if (additionalInfo.underlyingError !== undefined) {\n            // When SAM rethrows errors, it wraps the caught error with\n            // a SAMError, preserving the caught error as underlyingError.\n            //\n            // Unfortunately Sentry isn't aware of underlyingError,\n            // so we loose valuable debugging information. Sentry\n            // is aware of Error.cause ( ES2022 ), which is another\n            // way to specify the caught error when rethrowing.\n            //\n            // So when there's an underlyingError, I'm setting both\n            // to improve debugging in Sentry while preserving legacy\n            // behaviour.\n            super(message, { cause: additionalInfo.underlyingError });\n        } else {\n            super(message);\n        }\n\n        this.code = code;\n        this.subCode = subCode;\n        this.description = description;\n        this._additionalInfo = additionalInfo;\n    }\n\n    get name() {\n        return SAMErrorName;\n    }\n\n    static wrapErrorIfNeeded(code: SAMErrorCode, description: string, underlyingError: any, subCode?: SAMErrorSubCode): SAMError {\n        if (underlyingError instanceof SAMError) {\n            return underlyingError;\n        }\n        return new SAMError(code, description, { underlyingError }, subCode);\n    }\n\n    static create(code: SAMErrorCode, description: string, additionalInfo?: IAdditionalErrorInfo, subCode?: SAMErrorSubCode): SAMError {\n        return new SAMError(code, description, additionalInfo, subCode);\n    }\n\n    static createWithResponse(response: Response, href?: string) {\n        const { status } = response;\n        const info = errorCodeInfos.get(validateRepositoryCode(status));\n        const responseUrl = href ?? response.url;\n        const reqId = response.headers.get('X-Request-Id') || '';\n        const breadcrumbTrail = response.headers.get('X-Breadcrumb-Trail') || '';\n        return new SAMError(\n            info?.code ?? SAMErrorCode.UNKNOWN,\n            (info?.message(href ?? responseUrl) ?? `Unexpected response status: ${status} for ${responseUrl}`)\n                + ` reqId: ${reqId} breadcrumbTrail: ${breadcrumbTrail}`,\n            { response, reqId, breadcrumbTrail },\n            info?.subCode,\n        );\n    }\n\n    static createWithResponseAndDescription(response: Response, description: string) {\n        const info = errorCodeInfos.get(validateRepositoryCode(response.status));\n        return new SAMError(\n            info?.code ?? SAMErrorCode.UNKNOWN,\n            description,\n            { response },\n            info?.subCode,\n        );\n    }\n\n    static createWithRepositoryCode(code: number | string, problemType: string, description: string) {\n        // Look out for Quota Exceeded errors.\n        // RAPI returns 403 with problemType = http://ns.adobe.com/adobecloud/problem/quotaexceeded for such errors.\n        // We want to return a more specific error code for this case.\n        if (problemType === ProblemType.QUOTA_EXCEEDED) {\n            return new SAMError(\n                SAMErrorCode.FULL_CLOUD_STORAGE,\n                description,\n                { problemType },\n            );\n        }\n        const validHTTPCode = validateRepositoryCode(code);\n        const info = code ? errorCodeInfos.get(validHTTPCode) : undefined;\n        return new SAMError(\n            info?.code ?? SAMErrorCode.UNKNOWN,\n            description,\n            { problemType },\n            info?.subCode,\n        );\n    }\n\n    static createWithApolloError(error: ApolloError) {\n        if (error.networkError) {\n            const response = (error.networkError as ServerError | ServerParseError).response;\n            if (response) {\n                return SAMError.createWithResponse(response);\n            }\n        }\n        if (error.graphQLErrors?.length > 0) {\n            return SAMError.createWithGraphQLError(error.graphQLErrors[0]);\n        }\n        return SAMError.create(SAMErrorCode.UNKNOWN, error.message);\n    }\n\n    static createWithGraphQLError(error: GraphQLFormattedError) {\n        // As per the discussion with asset subgraph team, the errors are RAPI compliant and\n        // would be returned in the extensions field of the error\n        // Apollo client returns an array of graphQLErrors but it seems we will only have one error\n        // from the asset subgraph\n        const extensions = error.extensions;\n        if (extensions) {\n            return SAMError.createWithRepositoryCode(extensions.httpErrorCode as number, (extensions.problemType as any)?.type as string, error.message);\n        }\n        return SAMError.create(SAMErrorCode.UNKNOWN, error.message);\n    }\n}\n\n/**\n * Throws SAMAssertionError when `assertedCondition` is false.\n * @param assertedCondition\n * @param message\n */\nexport function assert(assertedCondition: boolean, message: string) {\n    if (!assertedCondition) {\n        throw SAMError.create(SAMErrorCode.UNKNOWN, message);\n    }\n}\n\n/**\n * Helper function used to accurately determine if an error\n * is a SAMError and not a plain Error.\n *\n * @param error An Error type object\n * @returns\n */\nexport function isSAMError(error: any): error is SAMError {\n    return error && error.name === SAMErrorName;\n}\n\n// We've used this as a default in too many places now,\n// this should avoid a huge change just to update the paths.\nexport default SAMError;\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n    extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n    return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n    if (typeof b !== \"function\" && b !== null)\r\n        throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n    extendStatics(d, b);\r\n    function __() { this.constructor = d; }\r\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n    __assign = Object.assign || function __assign(t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    }\r\n    return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        t[p] = s[p];\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                t[p[i]] = s[p[i]];\r\n        }\r\n    return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n    return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n    if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n    return new (P || (P = Promise))(function (resolve, reject) {\r\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n    });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n    function verb(n) { return function (v) { return step([n, v]); }; }\r\n    function step(op) {\r\n        if (f) throw new TypeError(\"Generator is already executing.\");\r\n        while (_) try {\r\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n            if (y = 0, t) op = [op[0] & 2, t.value];\r\n            switch (op[0]) {\r\n                case 0: case 1: t = op; break;\r\n                case 4: _.label++; return { value: op[1], done: false };\r\n                case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                default:\r\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                    if (t[2]) _.ops.pop();\r\n                    _.trys.pop(); continue;\r\n            }\r\n            op = body.call(thisArg, _);\r\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n    }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n    var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n    if (m) return m.call(o);\r\n    if (o && typeof o.length === \"number\") return {\r\n        next: function () {\r\n            if (o && i >= o.length) o = void 0;\r\n            return { value: o && o[i++], done: !o };\r\n        }\r\n    };\r\n    throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n    if (!m) return o;\r\n    var i = m.call(o), r, ar = [], e;\r\n    try {\r\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n    }\r\n    catch (error) { e = { error: error }; }\r\n    finally {\r\n        try {\r\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n        }\r\n        finally { if (e) throw e.error; }\r\n    }\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n    for (var ar = [], i = 0; i < arguments.length; i++)\r\n        ar = ar.concat(__read(arguments[i]));\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n    for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n            r[k] = a[j];\r\n    return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n        if (ar || !(i in from)) {\r\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n            ar[i] = from[i];\r\n        }\r\n    }\r\n    return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n    return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n    return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n    function fulfill(value) { resume(\"next\", value); }\r\n    function reject(value) { resume(\"throw\", value); }\r\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n    var i, p;\r\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var m = o[Symbol.asyncIterator], i;\r\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n    if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n    return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n    o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n    if (mod && mod.__esModule) return mod;\r\n    var result = {};\r\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n    __setModuleDefault(result, mod);\r\n    return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n    return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../SAMError';\n\nexport const KeysProperty = Symbol('@key parameterMap');\nexport interface IHasKeyMap {\n    [KeysProperty]: Map<string, number>\n}\n\n// @key decorator is used to indicate the argument to the @cache and @synchronized decorators\nexport default (target: IHasKeyMap, propertyKey: string, parameterIndex: number) => {\n    const map = target[KeysProperty] = target[KeysProperty] || new Map;\n    if (map.has(propertyKey)) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, '@key cannot be applied to more than one parameter');\n    }\n    map.set(propertyKey, parameterIndex);\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ISAMObject } from '../../indexPrivate';\nimport SAMError, { SAMErrorCode } from '../SAMError';\nimport type { IHasKeyMap } from './key';\nimport { KeysProperty } from './key';\n\ntype CacheableDescriptor<ValueType> = (target: ISAMObject, propertyKey: string, descriptor: TypedPropertyDescriptor<ValueType>) => void;\n\n/**\n * Caches the result of the method, using the argument decorated with '@key' as the key (multiple arguments can also be\n * used, and they will be appended together). This ensures that the result is cached in memory and shared if multiple\n * people call the API at once. Once the value expires, it will be recomputed.\n *\n * Note:\n * 1) Keys are global, so different cached methods should use different key domains unless it's intended to be shared.\n *    We typically use URLs as keys to avoid such conflicts.\n * 2) Decorators are not passed the default value of parameters, so you can't write f(@key x = 'defaultValue') - you need\n *    to make sure the value is always passed in.\n */\nfunction cacheImpl<ValueType extends ISAMObject>(validate?: (value: any) => boolean): CacheableDescriptor<ValueType> {\n    return (target: ISAMObject, propertyKey: string, descriptor: TypedPropertyDescriptor<ValueType>) => {\n        const method = descriptor.value;\n        if (!method) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, '@cache decorator can only be applied to a method');\n        }\n        const newMethod = async function (this: IHasKeyMap & ISAMObject, ...args: any[]) {\n            const keyIndex = this[KeysProperty]?.get(propertyKey);\n            if (keyIndex === undefined) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, '@cache decorator requires one of the parameters to be labelled with @key');\n            }\n            const key: string = args[keyIndex];\n            return this._core._environment.cache.getItem(key, () => (method as any).apply(this, args), validate);\n        };\n        descriptor.value = (newMethod as unknown) as ValueType;\n    };\n}\n\n// Allow both @cache with no parameters, or @cache(validate) with a validation function\nexport default function cache<T1 extends ISAMObject, ValueType>(target: T1, property: string, arg3: TypedPropertyDescriptor<ValueType>): TypedPropertyDescriptor<ValueType>;\nexport default function cache(validate?: (value: any) => boolean): CacheableDescriptor<any>;\n\nexport default function cache(arg1: any, arg2?: string, arg3?: any): any {\n    if (!arg2) {\n        return cacheImpl(arg1);\n    }\n\n    // No parameter - invoke without validation\n    // (allows using @cache without any parameters)\n    return cacheImpl()(arg1, arg2, arg3);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n// Memoize the value of a getter or method - this just caches the return value\n// forever, so it doesn't get recomputed each time it's called\nexport default (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n    const memo = Symbol(`@memoize ${propertyKey}`);\n    const property = descriptor.get ? 'get' : 'value';\n    const method = descriptor[property];\n    descriptor[property] = function (this: { [memo]: ReturnType<typeof method> }, ...args: any[]) {\n        if (!Object.prototype.hasOwnProperty.call(this, memo)) {\n            this[memo] = method.call(this, ...args);\n        }\n        return this[memo];\n    };\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type IEvent from './IEvent';\n\n/**\n * Base class for all events sent out from SAMJS.\n */\nexport default class SAMEvent implements IEvent {\n    constructor(private _type: string) {\n    }\n\n    get type(): string {\n        return this._type;\n    }\n\n    toString(): string {\n        return `SAMEvent(${this._type})`;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMEvent from './SAMEvent';\n\nexport const CHANGE = 'change';\n\nexport default class ChangeEvent extends SAMEvent {\n    constructor() {\n        super(CHANGE);\n    }\n}\n\nexport const SharedChangeEvent = new ChangeEvent();\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type IEvent from '../IEvent';\nimport { SharedChangeEvent } from '../ChangeEvent';\nimport type {\n    SAMObjectEventEmitter,\n    SAMObjectUntypedEventEmitter\n} from '../SAMObjectEventEmitter';\n\n\nconst $OBSERVABLE_MAP = Symbol('$OBSERVABLE_MAP');\n\ntype ObservableMap = Map<string, IEvent>;\ntype ITarget = SAMObjectUntypedEventEmitter | SAMObjectEventEmitter;\n\nexport function getEventForProp(obj: any, prop: string): IEvent | undefined {\n    return (obj[$OBSERVABLE_MAP] as ObservableMap || undefined)?.get(prop);\n}\n\nexport function getPropsForEvent(obj: any, event: IEvent): string[] {\n    return [ ...(obj[$OBSERVABLE_MAP] as ObservableMap || new Map()).entries() ]\n        .filter(([ , mappedEvent ]) => mappedEvent === event)\n        .map(([ prop ]) => prop);\n}\n\nfunction setEventForProp(obj: any, prop: string, event: IEvent) {\n    let map: ObservableMap;\n    // Detect if a map exists and whether or not it is inherited\n    if (Object.getOwnPropertyDescriptor(obj, $OBSERVABLE_MAP)) {\n        // not inherited, and it already exists\n        map = obj[$OBSERVABLE_MAP];\n    } else if (obj[$OBSERVABLE_MAP]) {\n        // Inherited, and it exists on the parent. The properties of the child class should not be mapped in the parent\n        // class, but the child class should have all the mapped properties of the parent class. So create a new map\n        // for the child that is a copy of the parent's map.\n        map = new Map(obj[$OBSERVABLE_MAP]);\n        obj[$OBSERVABLE_MAP] = map;\n    } else {\n        // Not inherited, and it does not exist\n        map = new Map();\n        obj[$OBSERVABLE_MAP] = map;\n    }\n\n    // TODO: warn if event is changed for a prop?\n    map.set(prop, event);\n}\n\nexport function observableImpl(event: IEvent, privatePropNames?: string[]) {\n    return (target: ITarget, key: string, descriptor: PropertyDescriptor): void => {\n        if (descriptor.get || descriptor.value) {\n            privatePropNames?.forEach(prop => setEventForProp(target, prop, event));\n        }\n        if (descriptor.get) {\n            const getter = descriptor.get;\n            descriptor.get = function (this: ITarget) {\n                this._core._environment.mobx.reportObserved(this, event.type);\n                return getter.call(this);\n            };\n        } else if (descriptor.value) {\n            const method = descriptor.value;\n            const newMethod = function (this: ITarget, ...args: any[]): any {\n                this._core._environment.mobx.reportObserved(this, event.type);\n                return (method as any).apply(this, args);\n            };\n            descriptor.value = newMethod;\n        } else {\n            throw new Error('@observable decorator can only be used with `getters` or `methods`.');\n        }\n    };\n}\n\n// With `@observable` (no parens), observable is called with target, key, descriptor\nfunction observable(target: ITarget, key: string, descriptor: PropertyDescriptor): void;\n// @observable(SomeEvent)\n// @observable(SomeEvent, '_prop1')\n// @observable(SomeEvent, ['_prop1', '_prop2'])\nfunction observable(event: IEvent, privatePropNames?: string | string[]): ReturnType<typeof observableImpl>;\nfunction observable(arg1: IEvent | ITarget, arg2?: string | string[], arg3?: PropertyDescriptor): ReturnType<typeof observableImpl> | void {\n    // @observable without parens\n    if (arg1 && arg2 && arg3) {\n        return observableImpl(SharedChangeEvent)(arg1 as ITarget, arg2 as string, arg3);\n    }\n    // @observable(SomeEvent)\n    // @observable(SomeEvent, '_prop1')\n    // @observable(SomeEvent, ['_prop1', '_prop2'])\n    if (typeof (arg1 as IEvent).type === 'string' && (typeof arg2 === 'string' || typeof arg2 === 'undefined' || Array.isArray(arg2))) {\n        arg2 = arg2 ? [].concat(arg2 as any) : undefined;\n        return observableImpl(arg1 as IEvent, arg2);\n    }\n    throw new Error('Invalid arguments for @observable');\n}\n\nexport default observable;\n","(function (global, factory) {\n\tif (typeof define === 'function' && define.amd) {\n\t\tdefine('uri-templates', [], factory);\n\t} else if (typeof module !== 'undefined' && module.exports){\n\t\tmodule.exports = factory();\n\t} else {\n\t\tglobal.UriTemplate = factory();\n\t}\n})(this, function () {\n\tvar uriTemplateGlobalModifiers = {\n\t\t\"+\": true,\n\t\t\"#\": true,\n\t\t\".\": true,\n\t\t\"/\": true,\n\t\t\";\": true,\n\t\t\"?\": true,\n\t\t\"&\": true\n\t};\n\tvar uriTemplateSuffices = {\n\t\t\"*\": true\n\t};\n\tvar urlEscapedChars = /[:/&?#]/;\n\n\tfunction notReallyPercentEncode(string) {\n\t\treturn encodeURI(string).replace(/%25[0-9][0-9]/g, function (doubleEncoded) {\n\t\t\treturn \"%\" + doubleEncoded.substring(3);\n\t\t});\n\t}\n\n\tfunction isPercentEncoded(string) {\n\t\tstring = string.replace(/%../g, '');\n\t\treturn encodeURIComponent(string) === string;\n\t}\n\n\tfunction uriTemplateSubstitution(spec) {\n\t\tvar modifier = \"\";\n\t\tif (uriTemplateGlobalModifiers[spec.charAt(0)]) {\n\t\t\tmodifier = spec.charAt(0);\n\t\t\tspec = spec.substring(1);\n\t\t}\n\t\tvar separator = \"\";\n\t\tvar prefix = \"\";\n\t\tvar shouldEscape = true;\n\t\tvar showVariables = false;\n\t\tvar trimEmptyString = false;\n\t\tif (modifier == '+') {\n\t\t\tshouldEscape = false;\n\t\t} else if (modifier == \".\") {\n\t\t\tprefix = \".\";\n\t\t\tseparator = \".\";\n\t\t} else if (modifier == \"/\") {\n\t\t\tprefix = \"/\";\n\t\t\tseparator = \"/\";\n\t\t} else if (modifier == '#') {\n\t\t\tprefix = \"#\";\n\t\t\tshouldEscape = false;\n\t\t} else if (modifier == ';') {\n\t\t\tprefix = \";\";\n\t\t\tseparator = \";\",\n\t\t\tshowVariables = true;\n\t\t\ttrimEmptyString = true;\n\t\t} else if (modifier == '?') {\n\t\t\tprefix = \"?\";\n\t\t\tseparator = \"&\",\n\t\t\tshowVariables = true;\n\t\t} else if (modifier == '&') {\n\t\t\tprefix = \"&\";\n\t\t\tseparator = \"&\",\n\t\t\tshowVariables = true;\n\t\t}\n\n\t\tvar varNames = [];\n\t\tvar varList = spec.split(\",\");\n\t\tvar varSpecs = [];\n\t\tvar varSpecMap = {};\n\t\tfor (var i = 0; i < varList.length; i++) {\n\t\t\tvar varName = varList[i];\n\t\t\tvar truncate = null;\n\t\t\tif (varName.indexOf(\":\") != -1) {\n\t\t\t\tvar parts = varName.split(\":\");\n\t\t\t\tvarName = parts[0];\n\t\t\t\ttruncate = parseInt(parts[1]);\n\t\t\t}\n\t\t\tvar suffices = {};\n\t\t\twhile (uriTemplateSuffices[varName.charAt(varName.length - 1)]) {\n\t\t\t\tsuffices[varName.charAt(varName.length - 1)] = true;\n\t\t\t\tvarName = varName.substring(0, varName.length - 1);\n\t\t\t}\n\t\t\tvar varSpec = {\n\t\t\t\ttruncate: truncate,\n\t\t\t\tname: varName,\n\t\t\t\tsuffices: suffices\n\t\t\t};\n\t\t\tvarSpecs.push(varSpec);\n\t\t\tvarSpecMap[varName] = varSpec;\n\t\t\tvarNames.push(varName);\n\t\t}\n\t\tvar subFunction = function (valueFunction) {\n\t\t\tvar result = \"\";\n\t\t\tvar startIndex = 0;\n\t\t\tfor (var i = 0; i < varSpecs.length; i++) {\n\t\t\t\tvar varSpec = varSpecs[i];\n\t\t\t\tvar value = valueFunction(varSpec.name);\n\t\t\t\tif (value == null || (Array.isArray(value) && value.length == 0) || (typeof value == 'object' && Object.keys(value).length == 0)) {\n\t\t\t\t\tstartIndex++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (i == startIndex) {\n\t\t\t\t\tresult += prefix;\n\t\t\t\t} else {\n\t\t\t\t\tresult += (separator || \",\");\n\t\t\t\t}\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\tif (showVariables) {\n\t\t\t\t\t\tresult += varSpec.name + \"=\";\n\t\t\t\t\t}\n\t\t\t\t\tfor (var j = 0; j < value.length; j++) {\n\t\t\t\t\t\tif (j > 0) {\n\t\t\t\t\t\t\tresult += varSpec.suffices['*'] ? (separator || \",\") : \",\";\n\t\t\t\t\t\t\tif (varSpec.suffices['*'] && showVariables) {\n\t\t\t\t\t\t\t\tresult += varSpec.name + \"=\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(value[j]).replace(/!/g, \"%21\") : notReallyPercentEncode(value[j]);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof value == \"object\") {\n\t\t\t\t\tif (showVariables && !varSpec.suffices['*']) {\n\t\t\t\t\t\tresult += varSpec.name + \"=\";\n\t\t\t\t\t}\n\t\t\t\t\tvar first = true;\n\t\t\t\t\tfor (var key in value) {\n\t\t\t\t\t\tif (!first) {\n\t\t\t\t\t\t\tresult += varSpec.suffices['*'] ? (separator || \",\") : \",\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfirst = false;\n\t\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(key).replace(/!/g, \"%21\") : notReallyPercentEncode(key);\n\t\t\t\t\t\tresult += varSpec.suffices['*'] ? '=' : \",\";\n\t\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(value[key]).replace(/!/g, \"%21\") : notReallyPercentEncode(value[key]);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (showVariables) {\n\t\t\t\t\t\tresult += varSpec.name;\n\t\t\t\t\t\tif (!trimEmptyString || value != \"\") {\n\t\t\t\t\t\t\tresult += \"=\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (varSpec.truncate != null) {\n\t\t\t\t\t\tvalue = value.substring(0, varSpec.truncate);\n\t\t\t\t\t}\n\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(value).replace(/!/g, \"%21\"): notReallyPercentEncode(value);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\t\tvar guessFunction = function (stringValue, resultObj, strict) {\n\t\t\tif (prefix) {\n\t\t\t\tstringValue = stringValue.substring(prefix.length);\n\t\t\t}\n\t\t\tif (varSpecs.length == 1 && varSpecs[0].suffices['*']) {\n\t\t\t\tvar varSpec = varSpecs[0];\n\t\t\t\tvar varName = varSpec.name;\n\t\t\t\tvar arrayValue = varSpec.suffices['*'] ? stringValue.split(separator || \",\") : [stringValue];\n\t\t\t\tvar hasEquals = (shouldEscape && stringValue.indexOf('=') != -1);\t// There's otherwise no way to distinguish between \"{value*}\" for arrays and objects\n\t\t\t\tfor (var i = 1; i < arrayValue.length; i++) {\n\t\t\t\t\tvar stringValue = arrayValue[i];\n\t\t\t\t\tif (hasEquals && stringValue.indexOf('=') == -1) {\n\t\t\t\t\t\t// Bit of a hack - if we're expecting \"=\" for key/value pairs, and values can't contain \"=\", then assume a value has been accidentally split\n\t\t\t\t\t\tarrayValue[i - 1] += (separator || \",\") + stringValue;\n\t\t\t\t\t\tarrayValue.splice(i, 1);\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (var i = 0; i < arrayValue.length; i++) {\n\t\t\t\t\tvar stringValue = arrayValue[i];\n\t\t\t\t\tif (shouldEscape && stringValue.indexOf('=') != -1) {\n\t\t\t\t\t\thasEquals = true;\n\t\t\t\t\t}\n\t\t\t\t\tvar innerArrayValue = stringValue.split(\",\");\n\t\t\t\t\tif (innerArrayValue.length == 1) {\n\t\t\t\t\t\tarrayValue[i] = innerArrayValue[0];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tarrayValue[i] = innerArrayValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (showVariables || hasEquals) {\n\t\t\t\t\tvar objectValue = resultObj[varName] || {};\n\t\t\t\t\tfor (var j = 0; j < arrayValue.length; j++) {\n\t\t\t\t\t\tvar innerValue = stringValue;\n\t\t\t\t\t\tif (showVariables && !innerValue) {\n\t\t\t\t\t\t\t// The empty string isn't a valid variable, so if our value is zero-length we have nothing\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof arrayValue[j] == \"string\") {\n\t\t\t\t\t\t\tvar stringValue = arrayValue[j];\n\t\t\t\t\t\t\tvar innerVarName = stringValue.split(\"=\", 1)[0];\n\t\t\t\t\t\t\tvar stringValue = stringValue.substring(innerVarName.length + 1);\n\t\t\t\t\t\t\tif (shouldEscape) {\n\t\t\t\t\t\t\t\tif (strict && !isPercentEncoded(stringValue)) {\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tstringValue = decodeURIComponent(stringValue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tinnerValue = stringValue;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar stringValue = arrayValue[j][0];\n\t\t\t\t\t\t\tvar innerVarName = stringValue.split(\"=\", 1)[0];\n\t\t\t\t\t\t\tvar stringValue = stringValue.substring(innerVarName.length + 1);\n\t\t\t\t\t\t\tif (shouldEscape) {\n\t\t\t\t\t\t\t\tif (strict && !isPercentEncoded(stringValue)) {\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tstringValue = decodeURIComponent(stringValue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tarrayValue[j][0] = stringValue;\n\t\t\t\t\t\t\tinnerValue = arrayValue[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (shouldEscape) {\n\t\t\t\t\t\t\tif (strict && !isPercentEncoded(innerVarName)) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tinnerVarName = decodeURIComponent(innerVarName);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (objectValue[innerVarName] !== undefined) {\n\t\t\t\t\t\t\tif (Array.isArray(objectValue[innerVarName])) {\n\t\t\t\t\t\t\t\tobjectValue[innerVarName].push(innerValue);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tobjectValue[innerVarName] = [objectValue[innerVarName], innerValue];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tobjectValue[innerVarName] = innerValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (Object.keys(objectValue).length == 1 && objectValue[varName] !== undefined) {\n\t\t\t\t\t\tresultObj[varName] = objectValue[varName];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresultObj[varName] = objectValue;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (shouldEscape) {\n\t\t\t\t\t\tfor (var j = 0; j < arrayValue.length; j++) {\n\t\t\t\t\t\t\tvar innerArrayValue = arrayValue[j];\n\t\t\t\t\t\t\tif (Array.isArray(innerArrayValue)) {\n\t\t\t\t\t\t\t\tfor (var k = 0; k < innerArrayValue.length; k++) {\n\t\t\t\t\t\t\t\t\tif (strict && !isPercentEncoded(innerArrayValue[k])) {\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tinnerArrayValue[k] = decodeURIComponent(innerArrayValue[k]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (strict && !isPercentEncoded(innerArrayValue)) {\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tarrayValue[j] = decodeURIComponent(innerArrayValue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (resultObj[varName] !== undefined) {\n\t\t\t\t\t\tif (Array.isArray(resultObj[varName])) {\n\t\t\t\t\t\t\tresultObj[varName] = resultObj[varName].concat(arrayValue);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresultObj[varName] = [resultObj[varName]].concat(arrayValue);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (arrayValue.length == 1 && !varSpec.suffices['*']) {\n\t\t\t\t\t\t\tresultObj[varName] = arrayValue[0];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresultObj[varName] = arrayValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar arrayValue = (varSpecs.length == 1) ? [stringValue] : stringValue.split(separator || \",\");\n\t\t\t\tvar specIndexMap = {};\n\t\t\t\tfor (var i = 0; i < arrayValue.length; i++) {\n\t\t\t\t\t// Try from beginning\n\t\t\t\t\tvar firstStarred = 0;\n\t\t\t\t\tfor (; firstStarred < varSpecs.length - 1 && firstStarred < i; firstStarred++) {\n\t\t\t\t\t\tif (varSpecs[firstStarred].suffices['*']) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (firstStarred == i) {\n\t\t\t\t\t\t// The first [i] of them have no \"*\" suffix\n\t\t\t\t\t\tspecIndexMap[i] = i;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Try from the end\n\t\t\t\t\t\tfor (var lastStarred = varSpecs.length - 1; lastStarred > 0 && (varSpecs.length - lastStarred) < (arrayValue.length - i); lastStarred--) {\n\t\t\t\t\t\t\tif (varSpecs[lastStarred].suffices['*']) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((varSpecs.length - lastStarred) == (arrayValue.length - i)) {\n\t\t\t\t\t\t\t// The last [length - i] of them have no \"*\" suffix\n\t\t\t\t\t\t\tspecIndexMap[i] = lastStarred;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Just give up and use the first one\n\t\t\t\t\tspecIndexMap[i] = firstStarred;\n\t\t\t\t}\n\t\t\t\tfor (var i = 0; i < arrayValue.length; i++) {\n\t\t\t\t\tvar stringValue = arrayValue[i];\n\t\t\t\t\tif (!stringValue && showVariables) {\n\t\t\t\t\t\t// The empty string isn't a valid variable, so if our value is zero-length we have nothing\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tvar innerArrayValue = stringValue.split(\",\");\n\t\t\t\t\tvar hasEquals = false;\n\n\t\t\t\t\tif (showVariables) {\n\t\t\t\t\t\tvar stringValue = innerArrayValue[0]; // using innerArrayValue\n\t\t\t\t\t\tvar varName = stringValue.split(\"=\", 1)[0];\n\t\t\t\t\t\tvar stringValue = stringValue.substring(varName.length + 1);\n\t\t\t\t\t\tinnerArrayValue[0] = stringValue;\n\t\t\t\t\t\tvar varSpec = varSpecMap[varName] || varSpecs[0];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar varSpec = varSpecs[specIndexMap[i]];\n\t\t\t\t\t\tvar varName = varSpec.name;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (var j = 0; j < innerArrayValue.length; j++) {\n\t\t\t\t\t\tif (shouldEscape) {\n\t\t\t\t\t\t\tif (strict && !isPercentEncoded(innerArrayValue[j])) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tinnerArrayValue[j] = decodeURIComponent(innerArrayValue[j]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((showVariables || varSpec.suffices['*'])&& resultObj[varName] !== undefined) {\n\t\t\t\t\t\tif (Array.isArray(resultObj[varName])) {\n\t\t\t\t\t\t\tresultObj[varName] = resultObj[varName].concat(innerArrayValue);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresultObj[varName] = [resultObj[varName]].concat(innerArrayValue);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (innerArrayValue.length == 1 && !varSpec.suffices['*']) {\n\t\t\t\t\t\t\tresultObj[varName] = innerArrayValue[0];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresultObj[varName] = innerArrayValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 1;\n\t\t};\n\t\treturn {\n\t\t\tvarNames: varNames,\n\t\t\tprefix: prefix,\n\t\t\tsubstitution: subFunction,\n\t\t\tunSubstitution: guessFunction\n\t\t};\n\t}\n\n\tfunction UriTemplate(template) {\n\t\tif (!(this instanceof UriTemplate)) {\n\t\t\treturn new UriTemplate(template);\n\t\t}\n\t\tvar parts = template.split(\"{\");\n\t\tvar textParts = [parts.shift()];\n\t\tvar prefixes = [];\n\t\tvar substitutions = [];\n\t\tvar unSubstitutions = [];\n\t\tvar varNames = [];\n\t\twhile (parts.length > 0) {\n\t\t\tvar part = parts.shift();\n\t\t\tvar spec = part.split(\"}\")[0];\n\t\t\tvar remainder = part.substring(spec.length + 1);\n\t\t\tvar funcs = uriTemplateSubstitution(spec);\n\t\t\tsubstitutions.push(funcs.substitution);\n\t\t\tunSubstitutions.push(funcs.unSubstitution);\n\t\t\tprefixes.push(funcs.prefix);\n\t\t\ttextParts.push(remainder);\n\t\t\tvarNames = varNames.concat(funcs.varNames);\n\t\t}\n\t\tthis.fill = function (valueFunction) {\n\t\t\tif (valueFunction && typeof valueFunction !== 'function') {\n\t\t\t\tvar value = valueFunction;\n\t\t\t\tvalueFunction = function (varName) {\n\t\t\t\t\treturn value[varName];\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tvar result = textParts[0];\n\t\t\tfor (var i = 0; i < substitutions.length; i++) {\n\t\t\t\tvar substitution = substitutions[i];\n\t\t\t\tresult += substitution(valueFunction);\n\t\t\t\tresult += textParts[i + 1];\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\t\tthis.fromUri = function (substituted, options) {\n\t\t\toptions = options || {};\n\t\t\tvar result = {};\n\t\t\tfor (var i = 0; i < textParts.length; i++) {\n\t\t\t\tvar part = textParts[i];\n\t\t\t\tif (substituted.substring(0, part.length) !== part) {\n\t\t\t\t\treturn /*undefined*/;\n\t\t\t\t}\n\t\t\t\tsubstituted = substituted.substring(part.length);\n\t\t\t\tif (i >= textParts.length - 1) {\n\t\t\t\t\t// We've run out of input - is there any template left?\n\t\t\t\t\tif (substituted == \"\") {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn /*undefined*/;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar prefix = prefixes[i];\n\t\t\t\tif (prefix && substituted.substring(0, prefix.length) !== prefix) {\n\t\t\t\t\t// All values are optional - if we have a prefix and it doesn't match, move along\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Find the next part to un-substitute\n\t\t\t\tvar nextPart = textParts[i + 1];\n\t\t\t\tvar offset = i;\n\t\t\t\twhile (true) {\n\t\t\t\t\tif (offset == textParts.length - 2) {\n\t\t\t\t\t\tvar endPart = substituted.substring(substituted.length - nextPart.length);\n\t\t\t\t\t\tif (endPart !== nextPart) {\n\t\t\t\t\t\t\treturn /*undefined*/;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvar stringValue = substituted.substring(0, substituted.length - nextPart.length);\n\t\t\t\t\t\tsubstituted = endPart;\n\t\t\t\t\t} else if (nextPart) {\n\t\t\t\t\t\tvar nextPartPos = substituted.indexOf(nextPart);\n\t\t\t\t\t\tvar stringValue = substituted.substring(0, nextPartPos);\n\t\t\t\t\t\tsubstituted = substituted.substring(nextPartPos);\n\t\t\t\t\t} else if (prefixes[offset + 1]) {\n\t\t\t\t\t\tvar nextPartPos = substituted.indexOf(prefixes[offset + 1]);\n\t\t\t\t\t\tif (nextPartPos === -1) nextPartPos = substituted.length;\n\t\t\t\t\t\tvar stringValue = substituted.substring(0, nextPartPos);\n\t\t\t\t\t\tsubstituted = substituted.substring(nextPartPos);\n\t\t\t\t\t} else if (textParts.length > offset + 2) {\n\t\t\t\t\t\t// If the separator between this variable and the next is blank (with no prefix), continue onwards\n\t\t\t\t\t\toffset++;\n\t\t\t\t\t\tnextPart = textParts[offset + 1];\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar stringValue = substituted;\n\t\t\t\t\t\tsubstituted = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!unSubstitutions[i](stringValue, result, options.strict)) {\n\t\t\t\t\treturn /*undefined*/;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tthis.varNames = varNames;\n\t\tthis.template = template;\n\t}\n\tUriTemplate.prototype = {\n\t\ttoString: function () {\n\t\t\treturn this.template;\n\t\t},\n\t\tfillFromObject: function (obj) {\n\t\t\treturn this.fill(obj);\n\t\t},\n\t\ttest: function (uri, options) {\n\t\t\treturn !!this.fromUri(uri, options)\n\t\t}\n\t};\n\n\treturn UriTemplate;\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport UriTemplate from 'uri-templates';\n\nexport type HeaderMap = {[s: string]: string | undefined };\n\nexport const JSON_MIME_TYPE = 'application/json';\nexport const JSON_PATCH_MIME_TYPE = 'application/json-patch+json';\n\nexport enum RelType {\n    // Repository API\n    PRIMARY = 'http://ns.adobe.com/adobecloud/rel/primary',\n    // @deprecated - Not required\n    ID = 'http://ns.adobe.com/adobecloud/rel/id',\n    // @deprecated - Not required\n    PATH = 'http://ns.adobe.com/adobecloud/rel/path',\n    RENDITION = 'http://ns.adobe.com/adobecloud/rel/rendition',\n    COMPONENT_RENDITION = 'http://ns.adobe.com/adobecloud/rel/componentRendition',\n    MANIFEST = 'http://ns.adobe.com/adobecloud/rel/manifest',\n    QUOTA = 'http://ns.adobe.com/adobecloud/rel/quota',\n    COMPONENT = 'http://ns.adobe.com/adobecloud/rel/component',\n    PAGE = 'http://ns.adobe.com/adobecloud/rel/page',\n    DISCARD = 'http://ns.adobe.com/adobecloud/rel/discard',\n    RESTORE = 'http://ns.adobe.com/adobecloud/rel/restore',\n    DIRECTORY = 'http://ns.adobe.com/adobecloud/rel/directory',\n    // @deprecated - Not required\n    DIRECTORY_BASE = 'http://ns.adobe.com/adobecloud/rel/directory/base',\n    AC_EFFECTIVE = 'http://ns.adobe.com/adobecloud/rel/ac/effective',\n    AC_POLICY = 'http://ns.adobe.com/adobecloud/rel/ac/policy',\n    // @deprecated -- Not required\n    AC_CHECK = 'http://ns.adobe.com/adobecloud/rel/ac/check',\n    CREATE = 'http://ns.adobe.com/adobecloud/rel/create',\n    REPOSITORY = 'http://ns.adobe.com/adobecloud/rel/repository',\n    RESOLVE_ID = 'http://ns.adobe.com/adobecloud/rel/resolve/id',\n    RESOLVE_PATH = 'http://ns.adobe.com/adobecloud/rel/resolve/path',\n    OPS = 'http://ns.adobe.com/adobecloud/rel/ops',\n    BLOCK_INITIALIZE = 'http://ns.adobe.com/adobecloud/rel/block/init',\n    BLOCK_TRANSFER = 'http://ns.adobe.com/adobecloud/rel/block/transfer',\n    BLOCK_FINALIZE = 'http://ns.adobe.com/adobecloud/rel/block/finalize',\n    BLOCK_EXTEND = 'http://ns.adobe.com/adobecloud/rel/block/extend',\n    REPO_METADATA = 'http://ns.adobe.com/adobecloud/rel/metadata/repository',\n    APP_METADATA = 'http://ns.adobe.com/adobecloud/rel/metadata/application',\n    EMBEDDED_METADATA = 'http://ns.adobe.com/adobecloud/rel/metadata/embedded',\n    PERUSER_METADATA = 'http://ns.adobe.com/adobecloud/rel/metadata/peruser',\n    ANNOTATIONS = 'http://ns.adobe.com/adobecloud/rel/annotations',\n    DOWNLOAD = 'http://ns.adobe.com/adobecloud/rel/download',\n    DESCRIBED_BY = 'describedBy',\n    // Versions\n    VERSION = 'version-history',\n\n    // ONS\n    SUBSCRIPTION_CREATE = 'subscription/create',\n    NOTIFICATIONS_LONGPOLL = 'notifications/longpoll',\n    ONS_CHANGELOG = 'ons/changelog',\n\n    // Projects API\n    REPOSITORIES_PAGE = 'http://ns.adobe.com/repositories/rel/page',\n    TEAMS_CREATE = 'http://ns.adobe.com/teams/rel/create',\n    TEAMS_DISCARD = 'http://ns.adobe.com/teams/rel/discard',\n    TEAMS_RESTORE = 'http://ns.adobe.com/teams/rel/restore',\n    TEAMS_RENAME = 'http://ns.adobe.com/teams/rel/rename',\n    TEAMS_PROPERTIES = 'http://ns.adobe.com/teams/rel/properties',\n    TEAMS_PAGE = 'http://ns.adobe.com/teams/rel/page',\n    TEAMS_PRIMARY = 'http://ns.adobe.com/teams/rel/primary',\n    TEAM_PROVISION = 'http://ns.adobe.com/teams/rel/provision',\n\n    WORKSPACES_CONTEXT = 'http://ns.adobe.com/ccprojects/rel/context',\n    WORKSPACES_BOOKMARKS_BATCH = 'http://ns.adobe.com/ccprojects/rel/bookmarks/batch',\n    WORKSPACES_PRIMARY = 'http://ns.adobe.com/ccprojects/rel/primary',\n    WORKSPACES_CREATE = 'http://ns.adobe.com/ccprojects/rel/create',\n    WORKSPACES_PAGE = 'http://ns.adobe.com/ccprojects/rel/page',\n\n    PROJECTS_LIBRARIES_PAGE = 'http://ns.adobe.com/ccprojects/rel/libraries/page',\n    PROJECTS_LIBRARIES_CREATE = 'http://ns.adobe.com/ccprojects/rel/libraries/create',\n    PROJECTS_LIBRARIES_BATCH = 'http://ns.adobe.com/ccprojects/rel/libraries/batch',\n\n    GENERIC_PAGE = 'page',\n    GENERIC_NEXT = 'next',\n\n    // Asset Transfer Service\n\n    ATS_MOVE = 'http://ns.adobe.com/ats/rel/move',\n\n    // Review Service\n    REVIEW_SERVICE_PROVISION = 'http://ns.adobe.com/ccassetreview/rel/provision',\n    REVIEW_SERVICE_DISCARD = 'http://ns.adobe.com/ccassetreview/rel/discard',\n    REVIEW_SERVICE_OUTPUTS = 'http://ns.adobe.com/ccassetreview/rel/outputs',\n    REVIEW_SERIVCE_HAS_OUTPUTS = 'http://ns.adobe.com/ccassetreview/rel/hasoutputs',\n\n    // Projects service v3\n    PROJECTS_CONTEXT = 'http://ns.adobe.com/projects/rel/context',\n    PROJECTS_PRIMARY = 'http://ns.adobe.com/projects/rel/primary',\n    PROJECTS_COLLECTION = 'http://ns.adobe.com/projects/rel/collection',\n    PROJECTS_CREATE = 'http://ns.adobe.com/projects/rel/create',\n    PROJECTS_RENAME = 'http://ns.adobe.com/projects/rel/rename',\n    PROJECTS_CREATOR = 'http://ns.adobe.com/projects/rel/creator',\n    PROJECTS_GRADIENTS_COLLECTION = 'http://ns.adobe.com/gradients/rel/collection',\n    PROJECTS_CAPABILITY = 'http://ns.adobe.com/projects/rel/capability',\n    ORGANIZATIONS_COLLECTION = 'http://ns.adobe.com/organizations/rel/collection',\n    PROJECTS_RECENT = 'http://ns.adobe.com/projects/rel/recent',\n    PROJECTS_MOVE = 'http://ns.adobe.com/projects/rel/move',\n    PROJECTS_REFERENCE_CREATE = 'http://ns.adobe.com/projects/rel/references/create',\n    PROJECTS_REFERENCE_PRIMARY = 'http://ns.adobe.com/projects/rel/references/primary',\n    // Assignment service\n    ASSIGNMENTS_ASSIGN = 'http://ns.adobe.com/assignments/rel/assign',\n    ASSIGNMENTS_CODE = 'http://ns.adobe.com/assignments/rel/code',\n    ASSIGNMENTS_COLLECTION = 'http://ns.adobe.com/assignments/rel/collection',\n    ASSIGNMENTS_CREATE = 'http://ns.adobe.com/assignments/rel/create',\n    ASSIGNMENTS_PRIMARY = 'http://ns.adobe.com/assignments/rel/primary',\n    ASSIGNMENTS_RETURN = 'http://ns.adobe.com/assignments/rel/return',\n    ASSIGNMENTS_START = 'http://ns.adobe.com/assignments/rel/start',\n    ASSIGNMENTS_SUBMIT = 'http://ns.adobe.com/assignments/rel/submit',\n\n    // Boards service\n    BOARDS_COLLECTION = 'http://ns.adobe.com/boards/rel/collection',\n    BOARDS_CREATE = 'http://ns.adobe.com/boards/rel/create',\n    BOARDS_PRIMARY = 'http://ns.adobe.com/boards/rel/primary',\n    BOARDS_DISCARD = 'http://ns.adobe.com/boards/rel/discard',\n    BOARDS_PUBLISH = 'http://ns.adobe.com/boards/rel/publish',\n    BOARDS_UNPUBLISH = 'http://ns.adobe.com/boards/rel/unpublish',\n\n    // StudentAssignment Service\n    STUDENT_ASSIGNMENTS_COLLECTION = 'http://ns.adobe.com/studentAssignments/rel/collection',\n    STUDENT_ASSIGNMENTS_PRIMARY = 'http://ns.adobe.com/studentAssignments/rel/primary',\n\n    // Mellville\n    MELVILLE_FIREFLY_GENERATION_CANCEL = 'http://ns.adobe.com/firefly/rel/cancel',\n    MELVILLE_FIREFLY_GENERATION_RESULT = 'http://ns.adobe.com/firefly/rel/result',\n}\n\nexport interface IServiceLink {\n    href: string;\n    templated?: boolean;\n    mode?: string;\n    type?: string;\n}\n\nexport type LinkRequirements = Partial<{ [key in RelType]: string[] }>;\n\nexport function validateLinkParameters(links: any, key: RelType, params: string[]): boolean {\n    try {\n        const templateString = getTemplateFromLinks(links, key);\n        const template = UriTemplate(templateString);\n\n        // Check that required arguments are available.\n        return params.every((param) => template.varNames.indexOf(param) !== -1);\n    } catch {\n        // We only care if the link is valid. If it is not valid, then we will return false,\n        // so that our caches could be invalidated correctly.\n        return false;\n    }\n}\n\nexport function validateLinks(links: any, requirements?: LinkRequirements): boolean {\n    if (links === undefined) {\n        return true;\n    }\n\n    if (Object(links) !== links) {\n        return false;\n    }\n\n    // All links should have an href\n    const hasMissingHrefs = Object.keys(links).some(key => {\n        const link = links[key];\n\n        if (!Array.isArray(link)) {\n            return typeof link.href !== 'string';\n        }\n\n        return link.some(({ href }) => typeof href !== 'string');\n    });\n    if (hasMissingHrefs) {\n        return false;\n    }\n\n    if (requirements) {\n        const keys = Object.keys(requirements) as RelType[];\n        const hasAllParameters = keys.every((key) => validateLinkParameters(links, key, requirements[key]!));\n        if (!hasAllParameters) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nexport function getLink(links: any, key: RelType): IServiceLink {\n\n    let link = links && links[key];\n\n    if (!link || (Array.isArray(link) && link.length === 0)) {\n        // The callers of these methods would fail without an actual URL.\n        // It is better to fail early by throwing a proper exception.\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Missing link for relationship type: ${key}.`);\n    }\n\n    if (Array.isArray(link)) {\n        link = link[0];\n    }\n\n    return link;\n}\n\nexport function getTemplateFromLinks(links: any, key: RelType): string {\n    return getLink(links, key).href;\n}\ntype PrimtiveValue = string | boolean | number;\nexport function getURLFromLinks(links: any, key: RelType, params: {[s: string]: string | string[] | boolean | Record<string, PrimtiveValue>} = {}): string {\n    const templateString = getTemplateFromLinks(links, key);\n\n    const template = UriTemplate(templateString);\n\n    const preparedParams: { [s: string]: string | string[] } = JSON.parse(\n        JSON.stringify(params, (key, val) => (typeof val === 'boolean') ? val.toString() : val)\n    );\n\n    return template && template.fill(preparedParams);\n}\n\nconst RETRY_RANDOM_SECONDS = 30; // Choose random seconds between [0,x] for retry-after as a date\n\nexport function getRetryAfterHeader(headers?: Headers): number {\n    const retryAfterHeader = headers && headers.get('Retry-After');\n    if (retryAfterHeader) {\n        try {\n            // First, try to parse it as a number (retry time in seconds)\n            const retryTime = parseInt(retryAfterHeader, 10);\n            if (retryTime) {\n                return Math.max(0, retryTime);\n            }\n\n            // If that fails, try to parse it as a date\n            const retryDate = Date.parse(retryAfterHeader);\n            if (retryDate) {\n                // Need to add a randomised element to ensure requests don't all come back at the same time\n                const now = Date.now();\n                const retrySeconds = Math.max(0, retryDate - now) / 1000;\n                const retryRandom = Math.floor(Math.random() * RETRY_RANDOM_SECONDS);\n                return retrySeconds + retryRandom;\n            }\n        } catch (e) {\n            // ignore\n        }\n    }\n\n    return 0;\n}\n\n/**\n * Add query parameters to a url from an object.\n * @param url\n * @param queryParams\n * @returns encoded url with query params\n */\nexport function fillURLTemplate(url: string, queryParams: Record<string, any>): string {\n    const template = UriTemplate(`${url}{?queryParams*}`);\n    return template.fillFromObject({ queryParams });\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport const VALID_HTTP_RESPONSE_CODES = [ 200 ];\n\nexport type ValidHttpResponseCodes = number[] | 'any';\n\n// See https://git.corp.adobe.com/pages/caf/api-spec/chapters/responses/service_responses.html\nexport const RETRY_HTTP_RESPONSE_CODES = [\n    429, // Too many requests -- request is valid but should be retried later\n    500, // Internal service error -- may be transient, client can retry\n    // 501 -- Not implemented -- client must not retry\n    502, 503, 504 // Upstream service (gateways/proxies) errors -- may be transient, client can retry\n    // >=505 -- other non-retryable errors\n];\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ISAMObject } from '../../indexPrivate';\nimport { getRetryAfterHeader } from '../../interface/LinkUtils';\nimport { RETRY_HTTP_RESPONSE_CODES } from '../../interface/ResponseCodes';\n\n// Support retrying an asynchronous method on failure, with a backoff\nexport default (target: ISAMObject, propertyKey: string, descriptor: PropertyDescriptor) => {\n    const timeout = Symbol(`@retry ${propertyKey}`);\n    const method = descriptor.value;\n    descriptor.value = async function (this: ISAMObject & { [timeout]?: ReturnType<typeof setTimeout> }, attempt: number = 0) {\n        const timeoutId = this[timeout];\n        if (timeoutId) {\n            clearTimeout(timeoutId);\n            this[timeout] = undefined;\n        }\n\n        try {\n            await method.call(this);\n        } catch (e) {\n            let interval: number = 0;\n            const response = (e as any)._additionalInfo?.response;\n            if (RETRY_HTTP_RESPONSE_CODES.includes(response?.status)) {\n                // InterfaceBase already auto-retried, so back off using the maximum retry interval.\n                interval = this._core._environment.getValue('MAX_RETRY_INTERVAL') || 20000;\n            } else {\n                // Retry all other errors, but at a different interval\n                const retryAfter = (e as any)._additionalInfo?.response ? getRetryAfterHeader((e as any)._additionalInfo.response.headers) * 1000 : 0;\n                // If we're unable to resolve (unable to connect to services or unexpected response), we schedule a retry\n                interval = Math.max(this._core._environment.getRetryInterval(attempt), retryAfter);\n            }\n\n            this._core._environment.log(`Retrying ${propertyKey} in ${interval}ms`);\n            this[timeout] = setTimeout(() => descriptor.value.call(this, attempt + 1), interval);\n        }\n    };\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../SAMError';\nimport type { IHasKeyMap } from './key';\nimport { KeysProperty } from './key';\n\n/**\n * The synchronized decorator ensures that only one caller can be executing the method at once,\n * similar to the synchronized keyword in Java for critical blocks. This only makes sense\n * to apply to asynchronous methods, since JavaScript is single-threaded.\n *\n * If an @synchronized method is called while another caller is already executing it, the second\n * caller will wait until the first caller finishes (regardless of whether the promise rejects or succeeds),\n * before executing.\n *\n * A parameter can be marked as @key, allowing multiple concurrent calls so long as the keys are different\n * (this is similar to passing a value to synchronized() in Java).\n */\nexport default (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n    const promisesMapProperty = Symbol(`@synchronized ${propertyKey}`);\n    const method = descriptor.value;\n    if (!method) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, '@synchronized decorator can only be applied to a method');\n    }\n    descriptor.value = async function (this: IHasKeyMap & { [promisesMapProperty]: Map<string, ReturnType<typeof method>> }, ...args: any[]) {\n        const keyIndex = this[KeysProperty]?.get(propertyKey);\n        const key: string = keyIndex === undefined ? 'default' : args[keyIndex];\n\n        const map = this[promisesMapProperty] || (this[promisesMapProperty] = new Map);\n\n        let promise;\n        do {\n            promise = map.get(key);\n            if (promise) {\n                // Somebody else was already executing, so we wait for that to finish first\n                try {\n                    await promise;\n                } catch (e) {\n                    // Ignore any errors - we'll execute after the existing caller resolves or rejects\n                }\n            }\n        } while (promise);\n\n        // Now enter the critical block ourself - record the promise so others need to wait.\n        // Note that we use different promise so that we ensure other callers continue only after\n        // we've deleted the previous promise.\n        // eslint-disable-next-line\n        let outerResolve = (value: any) => {};\n        map.set(key, new Promise(resolve => outerResolve = resolve));\n        try {\n            return await method.apply(this, args);\n        } finally {\n            // Always delete the promise even if we reject, to allow others to continue\n            map.delete(key);\n            outerResolve(undefined);\n        }\n    };\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport { KeysProperty } from './key';\n\nconst $WeakCacheProperty = Symbol('WeakCacheProperty');\n\nfunction stringifyWithSortedKeys(input: string | number | Date | Record<string, any>): string {\n    if (typeof input === 'string' || typeof input === 'number' || input instanceof Date || typeof input === 'boolean') {\n        return JSON.stringify(input);\n    } else if (typeof input === 'object' && input !== null) {\n        const sortedObject = Object.keys(input).sort().reduce((newObj, key) => {\n            newObj[key] = input[key];\n            return newObj;\n        }, {} as Record<string, any>);\n        return JSON.stringify(sortedObject);\n    }\n    throw new Error(`Unsupported input type (${input})`);\n}\n\nfunction isPrimitive(value: any): boolean {\n    return value === null || (typeof value !== 'object' && typeof value !== 'function');\n}\n\n/**\n * Cache the result of the method given a set of arguments. The cache is weak, meaning that the object will be garbage collected.\n * Therefore, it's recommended to use @keepAlive decorator to keep the object alive in memory.\n * This decorator will not work with method that returns primitive types (e.g. string, number, boolean, etc).\n * A parameter of the target function can be marked as @key to use as the key for the cache. If no parameter is marked as @key, the default key is 'default'.\n *\n * If the parameter, which is attached with @key, is explicitly set to null or undefined, the decorator will throw an error.\n * For example:\n *   @weakCache\n *   exampleFunction(@key value?: string) {}\n *   exampleFunction(null); // This would throw an error\n *\n */\nexport default (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n    const originalFn = descriptor.value;\n    if (!originalFn) {\n        throw new Error('@weakCache decorator can only be applied to a method');\n    }\n    // this is to avoid unexpected side-effects between unrelated target objects with the same property name (i.e. propertyKey)\n    const cache = target[$WeakCacheProperty] ??= new Map<string, WeakRef<any>>();\n    descriptor.value = function (this: any, ...args: any[]) {\n        const keyIndex = this[KeysProperty]?.get(propertyKey);\n        const keyArgs = keyIndex === undefined || args.length === 0 ? 'default' : args[keyIndex];\n        // we need to sort the keys of keyArgs in case it is an object to ensure that the cache key is consistent\n        // For example, do(@key {a: 1, b: 2}) and do(@key {b: 2, a: 1}) should have the same cache key\n        const key = `${propertyKey} (${stringifyWithSortedKeys(keyArgs)})`;\n        let result: any = cache.get(key)?.deref();\n        if (result) {\n            return result;\n        }\n        result = originalFn.call(this, ...args);\n        if (isPrimitive(result)) {\n            throw new Error('Cannot cache primitive types');\n        }\n        cache.set(key, new WeakRef(result));\n        return result;\n    };\n};\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../SAMError';\n\nconst DEFAULT_CACHE_KEEP_ALIVE_TTL = 10 * 60 * 1000; // 10 minutes\nexport { DEFAULT_CACHE_KEEP_ALIVE_TTL };\n\n/**\n * @description KeepAliveManager -- a singleton class that will keep a hard reference to objects passed to it.\n * This decorator should be used on all public context methods that return an AdobAsset.\n */\nexport default class KeepAliveManager {\n    private static _instance: KeepAliveManager;\n    private _keepAliveMap: Map<any, ReturnType<typeof setTimeout>> = new Map();\n    private constructor(private _ttl: number = DEFAULT_CACHE_KEEP_ALIVE_TTL) {}\n\n    /**\n     * @description Get the singleton instance of the KeepAliveManager.\n     */\n    static getInstance(): KeepAliveManager {\n        if (!KeepAliveManager._instance) {\n            KeepAliveManager._instance = new KeepAliveManager(DEFAULT_CACHE_KEEP_ALIVE_TTL);\n        }\n        return KeepAliveManager._instance;\n    }\n\n    /**\n     * @description Set the time to live for objects in the KeepAliveManager.\n     * @param ttl The time to live in milliseconds as a non-zero integer.\n     * @throws Error if ttl is less than 0.\n     */\n    static setTTL(ttl: number): void {\n        if (ttl < 0) {\n            throw SAMError.create(SAMErrorCode.UNKNOWN, 'TTL must be greater than or equal to 0');\n        }\n        KeepAliveManager.getInstance()._ttl = ttl;\n    }\n\n    /**\n     * @description Add an object to the KeepAliveManager.\n     * @param obj The object to keep alive.\n     */\n    add(obj: any): void {\n        if (this._ttl === 0) {\n            return;  // Not enabled by config\n        }\n        const existingTimer = this._keepAliveMap.get(obj);\n        if (existingTimer) {\n            clearTimeout(existingTimer);\n        }\n        this._keepAliveMap.set(obj, setTimeout(() => {\n            this._keepAliveMap.delete(obj);\n        }, this._ttl));\n    }\n}\n\n/**\n * @description decorator to prevent garbage collection of a returned object for a certain amount of time.\n */\nexport function keepAlive(target: any, propertyKey: string, descriptor: PropertyDescriptor): void {\n    const originalMethod = descriptor.value;\n    descriptor.value = function (this: any, ...args: any[]) {\n        const value = originalMethod.apply(this, args);\n        if (value instanceof Promise) {\n            value.then(\n                (v) => KeepAliveManager.getInstance().add(v)\n            ).catch(() => {\n                // Do not re-throw.  The error will still bubble up through the decorated function\n            });\n        } else if ((value ?? null) !== null) {\n            KeepAliveManager.getInstance().add(value);\n        }\n        return value;\n    };\n}\n","/**\n * @author Toru Nagashima <https://github.com/mysticatea>\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap<Event, PrivateData>}\n * @private\n */\nconst privateData = new WeakMap();\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap<Object, Function>}\n * @private\n */\nconst wrappers = new WeakMap();\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n    const retv = privateData.get(event);\n    console.assert(\n        retv != null,\n        \"'this' is expected an Event object, but got\",\n        event\n    );\n    return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n    if (data.passiveListener != null) {\n        if (\n            typeof console !== \"undefined\" &&\n            typeof console.error === \"function\"\n        ) {\n            console.error(\n                \"Unable to preventDefault inside passive event listener invocation.\",\n                data.passiveListener\n            );\n        }\n        return\n    }\n    if (!data.event.cancelable) {\n        return\n    }\n\n    data.canceled = true;\n    if (typeof data.event.preventDefault === \"function\") {\n        data.event.preventDefault();\n    }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n    privateData.set(this, {\n        eventTarget,\n        event,\n        eventPhase: 2,\n        currentTarget: eventTarget,\n        canceled: false,\n        stopped: false,\n        immediateStopped: false,\n        passiveListener: null,\n        timeStamp: event.timeStamp || Date.now(),\n    });\n\n    // https://heycam.github.io/webidl/#Unforgeable\n    Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true });\n\n    // Define accessors\n    const keys = Object.keys(event);\n    for (let i = 0; i < keys.length; ++i) {\n        const key = keys[i];\n        if (!(key in this)) {\n            Object.defineProperty(this, key, defineRedirectDescriptor(key));\n        }\n    }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n    /**\n     * The type of this event.\n     * @type {string}\n     */\n    get type() {\n        return pd(this).event.type\n    },\n\n    /**\n     * The target of this event.\n     * @type {EventTarget}\n     */\n    get target() {\n        return pd(this).eventTarget\n    },\n\n    /**\n     * The target of this event.\n     * @type {EventTarget}\n     */\n    get currentTarget() {\n        return pd(this).currentTarget\n    },\n\n    /**\n     * @returns {EventTarget[]} The composed path of this event.\n     */\n    composedPath() {\n        const currentTarget = pd(this).currentTarget;\n        if (currentTarget == null) {\n            return []\n        }\n        return [currentTarget]\n    },\n\n    /**\n     * Constant of NONE.\n     * @type {number}\n     */\n    get NONE() {\n        return 0\n    },\n\n    /**\n     * Constant of CAPTURING_PHASE.\n     * @type {number}\n     */\n    get CAPTURING_PHASE() {\n        return 1\n    },\n\n    /**\n     * Constant of AT_TARGET.\n     * @type {number}\n     */\n    get AT_TARGET() {\n        return 2\n    },\n\n    /**\n     * Constant of BUBBLING_PHASE.\n     * @type {number}\n     */\n    get BUBBLING_PHASE() {\n        return 3\n    },\n\n    /**\n     * The target of this event.\n     * @type {number}\n     */\n    get eventPhase() {\n        return pd(this).eventPhase\n    },\n\n    /**\n     * Stop event bubbling.\n     * @returns {void}\n     */\n    stopPropagation() {\n        const data = pd(this);\n\n        data.stopped = true;\n        if (typeof data.event.stopPropagation === \"function\") {\n            data.event.stopPropagation();\n        }\n    },\n\n    /**\n     * Stop event bubbling.\n     * @returns {void}\n     */\n    stopImmediatePropagation() {\n        const data = pd(this);\n\n        data.stopped = true;\n        data.immediateStopped = true;\n        if (typeof data.event.stopImmediatePropagation === \"function\") {\n            data.event.stopImmediatePropagation();\n        }\n    },\n\n    /**\n     * The flag to be bubbling.\n     * @type {boolean}\n     */\n    get bubbles() {\n        return Boolean(pd(this).event.bubbles)\n    },\n\n    /**\n     * The flag to be cancelable.\n     * @type {boolean}\n     */\n    get cancelable() {\n        return Boolean(pd(this).event.cancelable)\n    },\n\n    /**\n     * Cancel this event.\n     * @returns {void}\n     */\n    preventDefault() {\n        setCancelFlag(pd(this));\n    },\n\n    /**\n     * The flag to indicate cancellation state.\n     * @type {boolean}\n     */\n    get defaultPrevented() {\n        return pd(this).canceled\n    },\n\n    /**\n     * The flag to be composed.\n     * @type {boolean}\n     */\n    get composed() {\n        return Boolean(pd(this).event.composed)\n    },\n\n    /**\n     * The unix time of this event.\n     * @type {number}\n     */\n    get timeStamp() {\n        return pd(this).timeStamp\n    },\n\n    /**\n     * The target of this event.\n     * @type {EventTarget}\n     * @deprecated\n     */\n    get srcElement() {\n        return pd(this).eventTarget\n    },\n\n    /**\n     * The flag to stop event bubbling.\n     * @type {boolean}\n     * @deprecated\n     */\n    get cancelBubble() {\n        return pd(this).stopped\n    },\n    set cancelBubble(value) {\n        if (!value) {\n            return\n        }\n        const data = pd(this);\n\n        data.stopped = true;\n        if (typeof data.event.cancelBubble === \"boolean\") {\n            data.event.cancelBubble = true;\n        }\n    },\n\n    /**\n     * The flag to indicate cancellation state.\n     * @type {boolean}\n     * @deprecated\n     */\n    get returnValue() {\n        return !pd(this).canceled\n    },\n    set returnValue(value) {\n        if (!value) {\n            setCancelFlag(pd(this));\n        }\n    },\n\n    /**\n     * Initialize this event object. But do nothing under event dispatching.\n     * @param {string} type The event type.\n     * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n     * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n     * @deprecated\n     */\n    initEvent() {\n        // Do nothing.\n    },\n};\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n    value: Event,\n    configurable: true,\n    writable: true,\n});\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n    Object.setPrototypeOf(Event.prototype, window.Event.prototype);\n\n    // Make association for wrappers.\n    wrappers.set(window.Event.prototype, Event);\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n    return {\n        get() {\n            return pd(this).event[key]\n        },\n        set(value) {\n            pd(this).event[key] = value;\n        },\n        configurable: true,\n        enumerable: true,\n    }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n    return {\n        value() {\n            const event = pd(this).event;\n            return event[key].apply(event, arguments)\n        },\n        configurable: true,\n        enumerable: true,\n    }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n    const keys = Object.keys(proto);\n    if (keys.length === 0) {\n        return BaseEvent\n    }\n\n    /** CustomEvent */\n    function CustomEvent(eventTarget, event) {\n        BaseEvent.call(this, eventTarget, event);\n    }\n\n    CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n        constructor: { value: CustomEvent, configurable: true, writable: true },\n    });\n\n    // Define accessors.\n    for (let i = 0; i < keys.length; ++i) {\n        const key = keys[i];\n        if (!(key in BaseEvent.prototype)) {\n            const descriptor = Object.getOwnPropertyDescriptor(proto, key);\n            const isFunc = typeof descriptor.value === \"function\";\n            Object.defineProperty(\n                CustomEvent.prototype,\n                key,\n                isFunc\n                    ? defineCallDescriptor(key)\n                    : defineRedirectDescriptor(key)\n            );\n        }\n    }\n\n    return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n    if (proto == null || proto === Object.prototype) {\n        return Event\n    }\n\n    let wrapper = wrappers.get(proto);\n    if (wrapper == null) {\n        wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);\n        wrappers.set(proto, wrapper);\n    }\n    return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nfunction wrapEvent(eventTarget, event) {\n    const Wrapper = getWrapper(Object.getPrototypeOf(event));\n    return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nfunction isStopped(event) {\n    return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nfunction setEventPhase(event, eventPhase) {\n    pd(event).eventPhase = eventPhase;\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nfunction setCurrentTarget(event, currentTarget) {\n    pd(event).currentTarget = currentTarget;\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nfunction setPassiveListener(event, passiveListener) {\n    pd(event).passiveListener = passiveListener;\n}\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap<object, Map<string, ListenerNode>>}\n * @private\n */\nconst listenersMap = new WeakMap();\n\n// Listener types\nconst CAPTURE = 1;\nconst BUBBLE = 2;\nconst ATTRIBUTE = 3;\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n    return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map<string, ListenerNode>} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n    const listeners = listenersMap.get(eventTarget);\n    if (listeners == null) {\n        throw new TypeError(\n            \"'this' is expected an EventTarget object, but got another value.\"\n        )\n    }\n    return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n    return {\n        get() {\n            const listeners = getListeners(this);\n            let node = listeners.get(eventName);\n            while (node != null) {\n                if (node.listenerType === ATTRIBUTE) {\n                    return node.listener\n                }\n                node = node.next;\n            }\n            return null\n        },\n\n        set(listener) {\n            if (typeof listener !== \"function\" && !isObject(listener)) {\n                listener = null; // eslint-disable-line no-param-reassign\n            }\n            const listeners = getListeners(this);\n\n            // Traverse to the tail while removing old value.\n            let prev = null;\n            let node = listeners.get(eventName);\n            while (node != null) {\n                if (node.listenerType === ATTRIBUTE) {\n                    // Remove old value.\n                    if (prev !== null) {\n                        prev.next = node.next;\n                    } else if (node.next !== null) {\n                        listeners.set(eventName, node.next);\n                    } else {\n                        listeners.delete(eventName);\n                    }\n                } else {\n                    prev = node;\n                }\n\n                node = node.next;\n            }\n\n            // Add new value.\n            if (listener !== null) {\n                const newNode = {\n                    listener,\n                    listenerType: ATTRIBUTE,\n                    passive: false,\n                    once: false,\n                    next: null,\n                };\n                if (prev === null) {\n                    listeners.set(eventName, newNode);\n                } else {\n                    prev.next = newNode;\n                }\n            }\n        },\n        configurable: true,\n        enumerable: true,\n    }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n    Object.defineProperty(\n        eventTargetPrototype,\n        `on${eventName}`,\n        defineEventAttributeDescriptor(eventName)\n    );\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n    /** CustomEventTarget */\n    function CustomEventTarget() {\n        EventTarget.call(this);\n    }\n\n    CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n        constructor: {\n            value: CustomEventTarget,\n            configurable: true,\n            writable: true,\n        },\n    });\n\n    for (let i = 0; i < eventNames.length; ++i) {\n        defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);\n    }\n\n    return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n *     class A extends EventTarget {}\n *     class B extends EventTarget(\"message\") {}\n *     class C extends EventTarget(\"message\", \"error\") {}\n *     class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n    /*eslint-disable consistent-return */\n    if (this instanceof EventTarget) {\n        listenersMap.set(this, new Map());\n        return\n    }\n    if (arguments.length === 1 && Array.isArray(arguments[0])) {\n        return defineCustomEventTarget(arguments[0])\n    }\n    if (arguments.length > 0) {\n        const types = new Array(arguments.length);\n        for (let i = 0; i < arguments.length; ++i) {\n            types[i] = arguments[i];\n        }\n        return defineCustomEventTarget(types)\n    }\n    throw new TypeError(\"Cannot call a class as a function\")\n    /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n    /**\n     * Add a given listener to this event target.\n     * @param {string} eventName The event name to add.\n     * @param {Function} listener The listener to add.\n     * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n     * @returns {void}\n     */\n    addEventListener(eventName, listener, options) {\n        if (listener == null) {\n            return\n        }\n        if (typeof listener !== \"function\" && !isObject(listener)) {\n            throw new TypeError(\"'listener' should be a function or an object.\")\n        }\n\n        const listeners = getListeners(this);\n        const optionsIsObj = isObject(options);\n        const capture = optionsIsObj\n            ? Boolean(options.capture)\n            : Boolean(options);\n        const listenerType = capture ? CAPTURE : BUBBLE;\n        const newNode = {\n            listener,\n            listenerType,\n            passive: optionsIsObj && Boolean(options.passive),\n            once: optionsIsObj && Boolean(options.once),\n            next: null,\n        };\n\n        // Set it as the first node if the first node is null.\n        let node = listeners.get(eventName);\n        if (node === undefined) {\n            listeners.set(eventName, newNode);\n            return\n        }\n\n        // Traverse to the tail while checking duplication..\n        let prev = null;\n        while (node != null) {\n            if (\n                node.listener === listener &&\n                node.listenerType === listenerType\n            ) {\n                // Should ignore duplication.\n                return\n            }\n            prev = node;\n            node = node.next;\n        }\n\n        // Add it.\n        prev.next = newNode;\n    },\n\n    /**\n     * Remove a given listener from this event target.\n     * @param {string} eventName The event name to remove.\n     * @param {Function} listener The listener to remove.\n     * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n     * @returns {void}\n     */\n    removeEventListener(eventName, listener, options) {\n        if (listener == null) {\n            return\n        }\n\n        const listeners = getListeners(this);\n        const capture = isObject(options)\n            ? Boolean(options.capture)\n            : Boolean(options);\n        const listenerType = capture ? CAPTURE : BUBBLE;\n\n        let prev = null;\n        let node = listeners.get(eventName);\n        while (node != null) {\n            if (\n                node.listener === listener &&\n                node.listenerType === listenerType\n            ) {\n                if (prev !== null) {\n                    prev.next = node.next;\n                } else if (node.next !== null) {\n                    listeners.set(eventName, node.next);\n                } else {\n                    listeners.delete(eventName);\n                }\n                return\n            }\n\n            prev = node;\n            node = node.next;\n        }\n    },\n\n    /**\n     * Dispatch a given event.\n     * @param {Event|{type:string}} event The event to dispatch.\n     * @returns {boolean} `false` if canceled.\n     */\n    dispatchEvent(event) {\n        if (event == null || typeof event.type !== \"string\") {\n            throw new TypeError('\"event.type\" should be a string.')\n        }\n\n        // If listeners aren't registered, terminate.\n        const listeners = getListeners(this);\n        const eventName = event.type;\n        let node = listeners.get(eventName);\n        if (node == null) {\n            return true\n        }\n\n        // Since we cannot rewrite several properties, so wrap object.\n        const wrappedEvent = wrapEvent(this, event);\n\n        // This doesn't process capturing phase and bubbling phase.\n        // This isn't participating in a tree.\n        let prev = null;\n        while (node != null) {\n            // Remove this listener if it's once\n            if (node.once) {\n                if (prev !== null) {\n                    prev.next = node.next;\n                } else if (node.next !== null) {\n                    listeners.set(eventName, node.next);\n                } else {\n                    listeners.delete(eventName);\n                }\n            } else {\n                prev = node;\n            }\n\n            // Call this listener\n            setPassiveListener(\n                wrappedEvent,\n                node.passive ? node.listener : null\n            );\n            if (typeof node.listener === \"function\") {\n                try {\n                    node.listener.call(this, wrappedEvent);\n                } catch (err) {\n                    if (\n                        typeof console !== \"undefined\" &&\n                        typeof console.error === \"function\"\n                    ) {\n                        console.error(err);\n                    }\n                }\n            } else if (\n                node.listenerType !== ATTRIBUTE &&\n                typeof node.listener.handleEvent === \"function\"\n            ) {\n                node.listener.handleEvent(wrappedEvent);\n            }\n\n            // Break if `event.stopImmediatePropagation` was called.\n            if (isStopped(wrappedEvent)) {\n                break\n            }\n\n            node = node.next;\n        }\n        setPassiveListener(wrappedEvent, null);\n        setEventPhase(wrappedEvent, 0);\n        setCurrentTarget(wrappedEvent, null);\n\n        return !wrappedEvent.defaultPrevented\n    },\n};\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n    value: EventTarget,\n    configurable: true,\n    writable: true,\n});\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n    typeof window !== \"undefined\" &&\n    typeof window.EventTarget !== \"undefined\"\n) {\n    Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);\n}\n\nexport default EventTarget;\nexport { defineEventAttribute, EventTarget };\n//# sourceMappingURL=event-target-shim.mjs.map\n","/**\n * @author Toru Nagashima <https://github.com/mysticatea>\n * See LICENSE file in root directory for full license.\n */\nimport { EventTarget, defineEventAttribute } from 'event-target-shim';\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nclass AbortSignal extends EventTarget {\n    /**\n     * AbortSignal cannot be constructed directly.\n     */\n    constructor() {\n        super();\n        throw new TypeError(\"AbortSignal cannot be constructed directly\");\n    }\n    /**\n     * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n     */\n    get aborted() {\n        const aborted = abortedFlags.get(this);\n        if (typeof aborted !== \"boolean\") {\n            throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? \"null\" : typeof this}`);\n        }\n        return aborted;\n    }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\");\n/**\n * Create an AbortSignal object.\n */\nfunction createAbortSignal() {\n    const signal = Object.create(AbortSignal.prototype);\n    EventTarget.call(signal);\n    abortedFlags.set(signal, false);\n    return signal;\n}\n/**\n * Abort a given signal.\n */\nfunction abortSignal(signal) {\n    if (abortedFlags.get(signal) !== false) {\n        return;\n    }\n    abortedFlags.set(signal, true);\n    signal.dispatchEvent({ type: \"abort\" });\n}\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap();\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n    aborted: { enumerable: true },\n});\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n    Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n        configurable: true,\n        value: \"AbortSignal\",\n    });\n}\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nclass AbortController {\n    /**\n     * Initialize this controller.\n     */\n    constructor() {\n        signals.set(this, createAbortSignal());\n    }\n    /**\n     * Returns the `AbortSignal` object associated with this object.\n     */\n    get signal() {\n        return getSignal(this);\n    }\n    /**\n     * Abort and signal to any observers that the associated activity is to be aborted.\n     */\n    abort() {\n        abortSignal(getSignal(this));\n    }\n}\n/**\n * Associated signals.\n */\nconst signals = new WeakMap();\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller) {\n    const signal = signals.get(controller);\n    if (signal == null) {\n        throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? \"null\" : typeof controller}`);\n    }\n    return signal;\n}\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n    signal: { enumerable: true },\n    abort: { enumerable: true },\n});\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n    Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n        configurable: true,\n        value: \"AbortController\",\n    });\n}\n\nexport default AbortController;\nexport { AbortController, AbortSignal };\n//# sourceMappingURL=abort-controller.mjs.map\n","/*globals self, window */\nimport * as ac from \"./dist/abort-controller\"\n\n/*eslint-disable @mysticatea/prettier */\nconst g =\n    typeof self !== \"undefined\" ? self :\n    typeof window !== \"undefined\" ? window :\n    typeof global !== \"undefined\" ? global :\n    /* otherwise */ undefined\n/*eslint-enable @mysticatea/prettier */\n\nif (g) {\n    if (typeof g.AbortController === \"undefined\") {\n        g.AbortController = ac.AbortController\n    }\n    if (typeof g.AbortSignal === \"undefined\") {\n        g.AbortSignal = ac.AbortSignal\n    }\n}\n","// Unique ID creation requires a high quality random # generator.  In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API.  We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto\n// implementation. Also, find the complete implementation of crypto on IE11.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||\n                      (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));\n\nif (getRandomValues) {\n  // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n  var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n  module.exports = function whatwgRNG() {\n    getRandomValues(rnds8);\n    return rnds8;\n  };\n} else {\n  // Math.random()-based (RNG)\n  //\n  // If all else fails, use Math.random().  It's fast, but is of unspecified\n  // quality.\n  var rnds = new Array(16);\n\n  module.exports = function mathRNG() {\n    for (var i = 0, r; i < 16; i++) {\n      if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n      rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n    }\n\n    return rnds;\n  };\n}\n","/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n  byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n  var i = offset || 0;\n  var bth = byteToHex;\n  // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4\n  return ([bth[buf[i++]], bth[buf[i++]], \n\tbth[buf[i++]], bth[buf[i++]], '-',\n\tbth[buf[i++]], bth[buf[i++]], '-',\n\tbth[buf[i++]], bth[buf[i++]], '-',\n\tbth[buf[i++]], bth[buf[i++]], '-',\n\tbth[buf[i++]], bth[buf[i++]],\n\tbth[buf[i++]], bth[buf[i++]],\n\tbth[buf[i++]], bth[buf[i++]]]).join('');\n}\n\nmodule.exports = bytesToUuid;\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\nvar _clockseq;\n\n// Previous uuid creation time\nvar _lastMSecs = 0;\nvar _lastNSecs = 0;\n\n// See https://github.com/broofa/node-uuid for API details\nfunction v1(options, buf, offset) {\n  var i = buf && offset || 0;\n  var b = buf || [];\n\n  options = options || {};\n  var node = options.node || _nodeId;\n  var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;\n\n  // node and clockseq need to be initialized to random values if they're not\n  // specified.  We do this lazily to minimize issues related to insufficient\n  // system entropy.  See #189\n  if (node == null || clockseq == null) {\n    var seedBytes = rng();\n    if (node == null) {\n      // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n      node = _nodeId = [\n        seedBytes[0] | 0x01,\n        seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]\n      ];\n    }\n    if (clockseq == null) {\n      // Per 4.2.2, randomize (14 bit) clockseq\n      clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n    }\n  }\n\n  // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n  // (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so\n  // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n  // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n  var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();\n\n  // Per 4.2.1.2, use count of uuid's generated during the current clock\n  // cycle to simulate higher resolution clock\n  var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n  // Time since last uuid creation (in msecs)\n  var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n  // Per 4.2.1.2, Bump clockseq on clock regression\n  if (dt < 0 && options.clockseq === undefined) {\n    clockseq = clockseq + 1 & 0x3fff;\n  }\n\n  // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n  // time interval\n  if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n    nsecs = 0;\n  }\n\n  // Per 4.2.1.2 Throw error if too many uuids are requested\n  if (nsecs >= 10000) {\n    throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n  }\n\n  _lastMSecs = msecs;\n  _lastNSecs = nsecs;\n  _clockseq = clockseq;\n\n  // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n  msecs += 12219292800000;\n\n  // `time_low`\n  var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n  b[i++] = tl >>> 24 & 0xff;\n  b[i++] = tl >>> 16 & 0xff;\n  b[i++] = tl >>> 8 & 0xff;\n  b[i++] = tl & 0xff;\n\n  // `time_mid`\n  var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n  b[i++] = tmh >>> 8 & 0xff;\n  b[i++] = tmh & 0xff;\n\n  // `time_high_and_version`\n  b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n  b[i++] = tmh >>> 16 & 0xff;\n\n  // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n  b[i++] = clockseq >>> 8 | 0x80;\n\n  // `clock_seq_low`\n  b[i++] = clockseq & 0xff;\n\n  // `node`\n  for (var n = 0; n < 6; ++n) {\n    b[i + n] = node[n];\n  }\n\n  return buf ? buf : bytesToUuid(b);\n}\n\nmodule.exports = v1;\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n  var i = buf && offset || 0;\n\n  if (typeof(options) == 'string') {\n    buf = options === 'binary' ? new Array(16) : null;\n    options = null;\n  }\n  options = options || {};\n\n  var rnds = options.random || (options.rng || rng)();\n\n  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n  rnds[6] = (rnds[6] & 0x0f) | 0x40;\n  rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n  // Copy bytes to buffer, if provided\n  if (buf) {\n    for (var ii = 0; ii < 16; ++ii) {\n      buf[i + ii] = rnds[ii];\n    }\n  }\n\n  return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n","var v1 = require('./v1');\nvar v4 = require('./v4');\n\nvar uuid = v4;\nuuid.v1 = v1;\nuuid.v4 = v4;\n\nmodule.exports = uuid;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { v4 } from 'uuid';\n\ndeclare global {\n    interface Crypto {\n        randomUUID(): `${string}-${string}-${string}-${string}-${string}`\n    }\n}\n\n// NOTE: since UXP doesn't provide `window.crypto` (https://jira.corp.adobe.com/browse/UXP-12909), SAM.js must include\n// an old version of uuid (3.3.2) that does not require `window.crypto` at all. Otherwise, each host app has to\n// inject the crypto API, which is not ideal, as it then becomes a hidden dependency for SAM.js. Host apps may still\n// choose to provide the crypto API for more cryptographically secure uuid, but there does not appear to be any\n// security holes in SAM.js using the older algorithm.\nexport default function samJsUuid(): string {\n    if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n        return crypto.randomUUID();\n    }\n    return v4();\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { default as uuid } from './uuid';\n\nexport type CreateAtomFn = (name: string, onBecomeObservedHandler: () => void, onBecomeUnobservedHandler: () => void) => any;\n\ntype MobXInstanceInfo = {\n    id: string,\n    references: Set<string>\n}\n\n/**\n * Manager for observability via MobX - classes should call reportObserved\n * for any getters or methods that should be observable if used in the context\n * of MobX. Since SAM.js does not include MobX, clients need to makeObservable()\n * with their MobX instance\n */\nexport default class MobX {\n\n    private _contexts: Map<CreateAtomFn, MobXInstanceInfo> = new Map();\n\n    /**\n     * Register a MobX instance to make SAM.js observable.\n     * Returns a function that can be called to unregister.\n     */\n    register(createAtom: CreateAtomFn): () => void {\n        // It can be the case the register is called multiple times with the same createAtom function,\n        // which can happen if multiple components are using SAM.js but sharing the same MobX instance.\n        // In this case, we don't want to create more atoms than necessary since that would cause performance\n        // problems - instead, we detect if the createAtom was already registered, and just keep a reference\n        // count instead of registering it multiple times.\n        let instanceInfo = this._contexts.get(createAtom);\n        if (!instanceInfo) {\n            instanceInfo = { id: uuid(), references: new Set() };\n            this._contexts.set(createAtom, instanceInfo);\n        }\n        const refId = uuid();\n        instanceInfo.references.add(refId);\n\n        return () => {\n            const instanceInfo = this._contexts.get(createAtom);\n            if (instanceInfo) {\n                instanceInfo.references.delete(refId);\n                if (instanceInfo.references.size === 0) {\n                    this._contexts.delete(createAtom);\n                }\n            }\n        };\n    }\n\n    /**\n     * Called to report an observation on an object. Any reaction that observes this\n     * will be triggered whenever the given change event on the object triggers.\n     * In the simple case where we only have one change event for an object ('change'),\n     * getters and methods can be instrumented with just _environment.mobx.reportObserved(this).\n     */\n    reportObserved(object: any, event: string = 'change') {\n        for (const [ createAtom, { id } ] of this._contexts) {\n            const key = `_atom_${id}_${event}`;\n            let atom = object[key];\n            if (!atom) {\n                const onChange = () => atom.reportChanged();\n                atom = createAtom(`${object.constructor.name}_${event}`,\n                    () => {\n                        object.on(event, onChange);\n                    },\n                    () => {\n                        object.off(event, onChange);\n                    }\n                );\n                object[key] = atom;\n            }\n            atom.reportObserved();\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { synchronized, key } from './decorators';\nimport SAMError, { SAMErrorCode } from './SAMError';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\n\ntype TransactionType = 'readonly' | 'readwrite';\ntype RequestsFn = (objectStore: IDBObjectStore) => Promise<any> | any;\n\nexport type CachedValue = {\n    value?: any,\n    expiry?: Date\n};\n\nexport const NotFound = Symbol('NotFound');\n\nexport interface IPersistentCache {\n    getItem(itemKey: string): Promise<CachedValue | undefined>;\n    setItem(itemKey: string, value: any, expiry?: Date): Promise<void>;\n    deleteItem(itemKey: string): Promise<void>;\n}\n\n// Persistent cache based on indexedDB\nclass IndexedDBCache implements IPersistentCache {\n\n    constructor(protected _name: string, protected _core: ISAMCorePrivate) {}\n\n    private _database?: IDBDatabase;\n\n    static isSupported(): boolean {\n        if (typeof window === 'undefined' || !window.indexedDB) {\n            return false;\n        }\n\n        try {\n            const request = window.indexedDB.open('sam_indexeddb_test', 1);\n            request.onsuccess = () => request.result.close();\n            return true;\n        } catch (error) {\n            return false;\n        }\n    }\n\n    private async _transaction(transactionType: TransactionType, requestsFn: RequestsFn): Promise<any> {\n        const database = await this._connect();\n        if (!database) {\n            return;\n        }\n\n        return new Promise((resolve) => {\n            try {\n                const transaction = database.transaction(this._name, transactionType);\n                const objectStore = transaction.objectStore(this._name);\n                const promResult = requestsFn(objectStore);\n                transaction.onerror = (err) => {\n                    this._core._environment.error(`transaction error: ${err}`);\n                    resolve(undefined);\n                };\n                transaction.oncomplete = () => {\n                    resolve(promResult);\n                };\n            } catch (ex) {\n                // this can happens due to version upgrade when we close db.\n                this._core._environment.error(`transaction exception: ${ex}`);\n                resolve(undefined);\n            }\n        });\n    }\n\n    async getItem(itemKey: string): Promise<CachedValue | undefined> {\n        return this._transaction('readonly', async (objectStore: IDBObjectStore) => {\n            return new Promise((resolve) => {\n                const request = objectStore.get(itemKey);\n                request.onsuccess = () => {\n                    resolve(request.result ? {\n                        value: request.result.value,\n                        expiry: request.result.expiry as Date\n                    } : undefined);\n                };\n            });\n        });\n    }\n\n    async setItem(itemKey: string, value: any, expiry?: Date): Promise<void> {\n        return this._transaction('readwrite', (objectStore: IDBObjectStore) => {\n            objectStore.put({ id: itemKey, expiry, value });\n            return;\n        });\n    }\n\n    async deleteItem(itemKey: string): Promise<void> {\n        return this._transaction('readwrite', (objectStore: IDBObjectStore) => {\n            objectStore.delete(itemKey);\n            return;\n        });\n    }\n\n    private async _connect(): Promise<IDBDatabase | undefined> {\n        if (this._database) {\n            return this._database;\n        }\n        const version = this._core._environment.getValue('INDEXED_DB_VERSION');\n        const request = window.indexedDB.open(this._name, version);\n\n        return new Promise((resolve) => {\n            request.onerror = (err) => {\n                this._core._environment.error(`CONNECTION_FAILED Unable to connect to IndexedDB: ${this._name}, error: ${err}`);\n                resolve(undefined);\n            };\n\n            request.onupgradeneeded = () => {\n                const database = request.result;\n                if (database.objectStoreNames.contains(this._name)) {\n                    database.deleteObjectStore(this._name);\n                }\n                database.createObjectStore(this._name, { keyPath: 'id' });\n            };\n\n            request.onsuccess = () => {\n                const database = this._database = request.result;\n                database.onversionchange = (evt) => {\n                    this._core._environment.error(`IndexedDb version changed detected ${this._name}.${version}, ${evt}`);\n                    // close current db connection allowing the other client to upgrade a version\n                    database.close();\n                    database.onversionchange = null;\n                    this._database = undefined;\n                };\n                resolve(database);\n            };\n        });\n    }\n\n    // @ts-expect-error -- for use in console debugging\n    private async _clear(): Promise<void> {\n        return this._transaction('readwrite', async (objectStore: IDBObjectStore) => {\n            return new Promise((resolve) => {\n                const request = objectStore.clear();\n                request.onsuccess = () => {\n                    // eslint-disable-next-line no-console\n                    console.log('localDB cleared for', objectStore.name);\n                    resolve(undefined);\n                };\n            });\n        });\n    }\n}\n\n// Persistent cache based on localStorage\nclass LocalStorageCache implements IPersistentCache {\n\n    constructor(protected _name: string, protected _core: ISAMCorePrivate) {}\n\n    static isSupported(): boolean {\n        try {\n            return typeof window !== 'undefined' && !!window.localStorage;\n        } catch (e) {\n            // Firefox throws an exception when accessing localStorage in private mode\n            return false;\n        }\n    }\n\n    private _getKey(itemKey: string): string {\n        return `${this._name}#${itemKey}`;\n    }\n\n    async getItem(itemKey: string): Promise<CachedValue | undefined> {\n        const storedValue = window.localStorage.getItem(this._getKey(itemKey));\n        if (storedValue) {\n            try {\n                const { value, expiry } = JSON.parse(storedValue);\n                return {\n                    value,\n                    expiry: expiry ? new Date(expiry as string) : undefined\n                };\n            } catch (e) {\n                // ignore\n            }\n        }\n        return undefined;\n    }\n\n    async setItem(itemKey: string, value: any, expiry?: Date): Promise<void> {\n        const storedValue = JSON.stringify({ expiry, value });\n        window.localStorage.setItem(this._getKey(itemKey), storedValue);\n    }\n\n    async deleteItem(itemKey: string): Promise<void> {\n        window.localStorage.removeItem(this._getKey(itemKey));\n    }\n}\n\ninterface InMemoryCachedValue extends CachedValue {\n    cleanupTimeout: ReturnType<typeof setTimeout>;\n}\n\n/**\n * An in-memory cache that automatically expires items after a certain time,\n * so as to avoid memory growing unbounded. Items will be evicted after\n * MAX_TIME_IN_MEMORY_MS or the expiry time, whichever is sooner.\n * In the implementation in SAM, this is mostly just a performance optimization,\n * because entries will still be included in the persistent cache.\n */\nexport class InMemoryCache {\n    static MAX_TIME_IN_MEMORY_MS = 60 * 1000; // 1 minute\n    items: Map<string, InMemoryCachedValue> = new Map<string, InMemoryCachedValue>();\n\n    getItem(itemKey: string) {\n        return this.items.get(itemKey);\n    }\n\n    setItem(itemKey: string, value: any, expiry?: Date) {\n        const existingItem = this.items.get(itemKey);\n        if (existingItem) {\n            clearTimeout(existingItem.cleanupTimeout);\n        }\n\n        const requestedExpiry = expiry?.getTime() ?? Date.now() + InMemoryCache.MAX_TIME_IN_MEMORY_MS;\n        const cleanupTime = Math.min(InMemoryCache.MAX_TIME_IN_MEMORY_MS, requestedExpiry - Date.now());\n        const cleanupTimeout = setTimeout(() => {\n            this.deleteItem(itemKey);\n        }, cleanupTime);\n        this.items.set(itemKey, { value, expiry, cleanupTimeout });\n    }\n\n    deleteItem(itemKey: string) {\n        const item = this.items.get(itemKey);\n        if (item) {\n            clearTimeout(item.cleanupTimeout);\n        }\n        this.items.delete(itemKey);\n    }\n}\n\n/**\n * Persistent cache of values using indexedDB - if the browser doesn't support indexedDB it falls back to localStorage,\n * and if neither is supported it'll just use a local in-memory cache that doesn't persist between sessions.\n */\nexport default class Cache implements ISAMObject {\n\n    private _name: string;\n\n    // Persistent cache layer - either indexedDB, localStorage, or neither if none are supported (e.g. in private browsing)\n    private _persistentCache?: IPersistentCache;\n\n    // Local cache layer - this is an optimization if there's no persistent cache layer\n    private _localCache = new InMemoryCache();\n\n    constructor(private _userId: string, readonly _core: ISAMCorePrivate, _persistentCache?: IPersistentCache) {\n        this._name = 'SAM.js-' + this._userId;\n\n        if (_persistentCache) {\n            // Clients can override SAM.js to use their own caching layer if required\n            this._persistentCache = _persistentCache;\n        } else if (IndexedDBCache.isSupported()) {\n            this._persistentCache = new IndexedDBCache(this._name, _core);\n        } else if (LocalStorageCache.isSupported()) {\n            this._persistentCache = new LocalStorageCache(this._name, _core);\n        }\n    }\n\n    get name(): string {\n        return this._name;\n    }\n\n    @synchronized\n    async getItem(@key itemKey: string, computeValue?: () => Promise<any>, validateValue?: (value: any) => boolean, expiryMs?: number): Promise<any> {\n        let cachedItem: CachedValue | undefined = this._localCache.getItem(itemKey);\n\n        if (!cachedItem && this._persistentCache) {\n            cachedItem = await this._persistentCache.getItem(itemKey);\n        }\n\n        // Check if the cached item expired or invalid - if so, ignore it\n        const isInvalid = validateValue && cachedItem && !validateValue(cachedItem.value);\n        const isExpired = cachedItem?.expiry && cachedItem.expiry <= new Date(Date.now());\n        if (isInvalid || isExpired) {\n            await this.deleteItem(itemKey);\n            cachedItem = undefined;\n        }\n\n        // If we're passed in a computeValue function, use it to update the cache if there's no\n        // cached value (or it expired)\n        if (!cachedItem && computeValue) {\n            const value = await computeValue();\n            if (validateValue && !validateValue(value)) {\n                throw SAMError.create(SAMErrorCode.UNKNOWN, `Value for cache key ${itemKey} is invalid: ${JSON.stringify(value)}`);\n            }\n            await this.setItem(itemKey, value, expiryMs);\n            return value;\n        }\n\n        return cachedItem ? cachedItem.value : NotFound;\n    }\n\n    async setItem(itemKey: string, value: any, expirationDurMsec: number = this._core._environment.getValue('CACHE_DEFAULT_TTL')): Promise<void> {\n        const expiry = expirationDurMsec ? new Date(Date.now() + expirationDurMsec) : undefined;\n        // NOTE: _localCache has its own eviction policy that takes priority if it is < expiry. This\n        // keeps _localCache from growing unbounded during a session, while still optimizing reads\n        // from persistent cache.\n        this._localCache.setItem(itemKey, value, expiry);\n\n        if (this._persistentCache) {\n            await this._persistentCache.setItem(itemKey, value, expiry);\n        }\n    }\n\n    async deleteItem(itemKey: string): Promise<void> {\n        this._localCache.deleteItem(itemKey);\n        if (this._persistentCache) {\n            await this._persistentCache.deleteItem(itemKey);\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IEventMap } from './ITypedEventEmitter';\nimport type { IItemListBase } from './ItemList';\nimport type { LogLevel } from './SAMCore';\n\nexport const ITEM_LIST_STATE_CHANGED = 'itemListStateChanged';\nexport const MESSAGE_LOGGED = 'messageLogged';\nexport const CONFIG_CHANGE = 'configChanged';\n\nexport class ConfigChangeEvent extends Event {\n    constructor() {\n        super(CONFIG_CHANGE);\n    }\n}\n\nexport class ItemListStateChangedEvent extends Event {\n    constructor(readonly list: IItemListBase) {\n        super(ITEM_LIST_STATE_CHANGED);\n    }\n}\n\nexport class MessageLoggedEvent extends Event {\n    constructor(readonly message: string, readonly logLevel: LogLevel) {\n        super(MESSAGE_LOGGED);\n    }\n}\n\ninterface ISAMCoreEvents extends IEventMap {\n    [ITEM_LIST_STATE_CHANGED]: ItemListStateChangedEvent;\n    [MESSAGE_LOGGED]: MessageLoggedEvent;\n    [CONFIG_CHANGE]: ConfigChangeEvent;\n}\n\nexport default ISAMCoreEvents;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport const FOLDER_CONTENT_CHANGED = 'folderContentChanged';\n\nexport class FolderContentChangedEvent extends Event {\n    constructor() {\n        super(FOLDER_CONTENT_CHANGED);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMEvent from '../core/SAMEvent';\n\nexport const COLLABORATOR_CHANGED = 'collaborator_changed';\n\nexport default class CollaboratorChangedEvent extends SAMEvent {\n\n    constructor() {\n        super(COLLABORATOR_CHANGED);\n    }\n}\n\nexport const SharedCollaboratorChangedEvent = new CollaboratorChangedEvent();\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport { SAM } from '@ccx-public/component-types';\nimport { RelType } from './LinkUtils';\nimport type {\n    IEffectivePermissions,\n    PermissionType\n} from './RepositoryModel';\nimport type { LastAccessedOrderField } from './USSModel';\nimport type AdobeAssetFilter from '../assets/AdobeAssetFilter';\nimport type AdobeAssetOrder from '../assets/AdobeAssetOrder';\nimport type { ILoadOptions } from '../core/ItemList';\n\nexport interface IAssetsPageSpec {\n    orderBy: string;\n    next?: string;\n    count: number;\n}\n\nexport type IUSSAdobeAssetOrderBy =\n    | 'asset_name'\n    | 'create_date'\n    | 'modify_date'\n    | typeof LastAccessedOrderField;\n\nexport type ISWYAdobeAssetOrderBy = IUSSAdobeAssetOrderBy | 'shared_date';\nexport type ISBMAdobeAssetOrderBy = IUSSAdobeAssetOrderBy | 'shared_date';\n\nexport type IAdobeAssetOrderBy =\n    | 'repo:name'\n    | 'storage:deviceCreateDate'\n    | 'storage:deviceModifyDate';\n\nexport type IAssetVersionOrderBy = 'created'\n\n\n// See https://git.corp.adobe.com/SharedCloud/servicecontainer/blob/master/asr-svc/modules/hierarchy/model/src/main/java/com/adobe/hierarchyservice/hierarchy/model/PlatformAssetType.java\nexport type AssetType = SAM.AssetType;\n\n// See https://git.corp.adobe.com/SharedCloud/servicecontainer/blob/master/asr-svc/modules/hierarchy/model/src/main/java/com/adobe/hierarchyservice/hierarchy/model/PlatformAssetType.java\nexport type AssetSubType = SAM.AssetSubType;\n\n// Top-level application metadata fields that should be embedded in all R-API and USS listings\nexport const AppMetadataField = {\n    SHELL_VISIBILITY: 'shell:visibility',       // for filtering out hidden files client-side\n    CC_INHERITED: 'cc:inherited',               // project and workspace children\n    REVIEW_SOURCE_ASSET: 'review:sourceAsset',  // artifact source info\n    CONVERTED_TO: 'convertedTo',                // Project X (temporary support for legacy files)\n    NON_AUTO_MIGRATABLE: 'ccx:nonAutoMigratableCopiedFromId',  // Project X (temporary support for legacy files)\n    COPIED_IN_LEGACY_SPARK_TO: 'ccx:copiedLegacySparkId', // Project X (temporary support for legacy files)\n    CC_INHERITABLE: 'cc:inheritable',            // specfic to projects and workspaces\n    PROJECT_RENDITION: 'project:rendition',      // required for Projects showing up in USS listings,\n    FIREFLY: 'firefly'                           // Firefly boards\n} as const;\n\nconst RapiAppMetadataWildcardNamespaces = {\n    CC: 'cc',\n    CLASSROOM_ASSIGNMENTS: 'assignment',\n    CCX: 'ccx',\n    HZ: 'hz'\n};\n\n// This should be fix once https://jira.corp.adobe.com/browse/SEARCH-45142 is done\nconst NewFormatAppMetadataField = {\n    HZ_DOCUMENT_METADATA: 'hz:documentMetadata',  // Express metadata\n    CC_CREATED_FROM_UPLOAD: 'cc:createdFromUpload'\n};\n\n// The following fields must be escaped as-is to get all fields in the namespace\n// See: https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=CA&title=Proposal%3A+Enhanced+Filtering+and+Embedding+Support+for+JSON+Resources#Proposal:EnhancedFilteringandEmbeddingSupportforJSONResources-Selectors\n// eslint-disable-next-line no-useless-escape\nconst AppMetadataNamespacesRapiFormat = Object.values(RapiAppMetadataWildcardNamespaces).map((element) => `\\\"${element}:\\\"*`);\n\n// Rapi and USS have different formats for these core AppMetadataFields\nconst EmbedAppMetadataFieldsRapiFormat = (Object.values(AppMetadataField) as string[])\n    .concat(Object.values(NewFormatAppMetadataField))\n    .filter((element) => {\n        // Filter out all single field selectors that will be included by a wildcard selector\n        const ns = element.split(':')[0];\n        return !Object.values(RapiAppMetadataWildcardNamespaces).includes(ns);\n    })\n    .map((element) => '\"' + element + '\"')\n    .concat(AppMetadataNamespacesRapiFormat);\n\nconst EmbedAppMetadataFieldsUSSFormat = Object.values(AppMetadataField).map((element) => {\n    return ('app_metadata$$' + element);\n}).concat(Object.values(NewFormatAppMetadataField).map((element) => {\n    return ('api:metadata/application$$' + element);\n}));\n\n// Unified type for AppMetadataFields regardless of service origin eg. 'app_metadata$$shell:visibility' | '\"shell:visibility\"' | ...\nexport type IAppMetadataFieldTypeRapi = typeof EmbedAppMetadataFieldsRapiFormat[number];\nexport type IAppMetadataFieldTypeUSS = typeof EmbedAppMetadataFieldsUSSFormat[number];\nexport type IAppMetadataFieldType = IAppMetadataFieldTypeRapi | IAppMetadataFieldTypeUSS;\n\nexport function getRapiAppMetadataSelectors(): IAppMetadataFieldTypeRapi[] {\n    return EmbedAppMetadataFieldsRapiFormat;\n}\n\n// USSFetchFields should be embedded in USS calls only\nexport const USSFetchField = {\n    COLLABORATION_METADATA: 'collaboration_metadata',\n    COLLABMETADATA_MINE: 'collab_metadata#mine',\n    REPO_CREATED_BY_CLIENT_ID: 'repo:createdByClientId',\n    CUSTOM_MODEL_METADATA: 'firefly#ffmodel'\n} as const;\n\nconst USSFetchFields = Array.from(Object.values(USSFetchField));\nexport type IUSSFetchFieldType = typeof USSFetchFields[number] | IAppMetadataFieldTypeUSS;\n\n\n// Include all fields from AppMetadataFields and FetchFields in USS search results.\nexport function getUSSFetchFields(): IUSSFetchFieldType[] {\n    return [ ...EmbedAppMetadataFieldsUSSFormat, ...USSFetchFields ];\n}\n\n\nexport type Permission = SAM.Permission;\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport const Permission = SAM.Permission;\n\n// All permissions except Ack\nexport const PERMISSION_ALL = Object.entries(SAM.Permission).reduce(\n    // Note: the keys that are the reverse-lookup entries for the values get accumulated, while the keys that are\n    //           the enum keys do not, because `n | NaN` returns `n`.\n    (acc, [ key ]) => (key === Permission.Ack.toString(10)) ? acc : acc | parseInt(key, 10),\n    Permission.None\n);\n\n\n// Currently only exists in SAM.cpp\nexport interface ITransferStatus {\n    readonly started: boolean;\n    readonly hadError: boolean;\n    readonly bytesTransferred: number;\n    readonly bytesTotal: number;\n    readonly errorReason: string;\n    readonly errorType: string;\n}\n\nexport function parseEffectivePermissions(permissions: IEffectivePermissions): Permission {\n    // https://git.corp.adobe.com/pages/caf/api-spec/chapters/concepts/access.html#privileges\n\n    // Each permission type should look for its relevant key first, then fall back to \"*\" entry.\n    const primary = permissions[RelType.PRIMARY] || permissions['*'] || [];       // permissions directly on this obj\n    const policy = permissions[RelType.AC_POLICY] || permissions['*'] || [];      // contains \"share\" permission\n    const directory = permissions[RelType.DIRECTORY] || permissions['*'] || [];   // parent folder's permissions\n    const appMetadata = permissions[RelType.APP_METADATA] || permissions['*'] || []; // application metadata's permissions\n    const annotations = permissions[RelType.ANNOTATIONS] || permissions['*'] || [];   // contains commenting permissions\n\n    let mask = Permission.None;\n    primary.forEach((perm: PermissionType) => {\n        switch (perm) {\n        case 'ack':\n            mask |= Permission.Ack;\n            break;\n        case 'read':\n            mask |= Permission.Read;\n            if (directory.includes('write')) {\n                // Can duplicate this file in its current directory\n                mask |= Permission.Duplicate;\n            }\n            break;\n        case 'write':\n            // Clients need 'write' permission to edit the contents of a file, and they\n            // need 'write' permission on the parent folder to rename, discard, or restore\n            mask |= Permission.Write;\n            if (directory.includes('write')) {\n                mask |= Permission.Discard;\n                mask |= Permission.Restore;\n            }\n            break;\n        case 'delete':\n            // Clients need Delete permission on the asset and Write permission on the\n            // parent directory in order to delete an asset.\n            if (directory.includes('write')) {\n                mask |= Permission.Delete;\n            }\n            break;\n        }\n    });\n\n    // synthetic permission\n    if (policy.includes('write')) {\n        mask |= Permission.Share;\n    }\n\n    // appmetadata permission\n    if (appMetadata.includes('read')) {\n        mask |= Permission.ReadAppMetadata;\n    }\n\n    if (annotations.includes('write')) {\n        mask |= Permission.WriteComment;\n    }\n\n    if (directory.includes('write') && primary.includes('read') && primary.includes('write')) {\n        mask |= Permission.Rename;      // Rename requires read and write permissions on primary and write permission on the parent directory\n        if (primary.includes('delete')) {\n            mask |= Permission.Move;    // Move requires read, write and delete permissions on primary and write permission on the parent directory\n        }\n    }\n\n    return mask;\n}\n\n// NOTE: this isn't what Projects UI expects from XDCE service, but this is what it returns.\nexport interface IXDCEDocument {\n    id: string;\n    name: string;\n    thumbnail: {\n        assetID: string;\n        format: string;\n        scale: string;\n        url: string;\n    };\n    publisher: {\n        displayName: string;\n    };\n    artboardcount: number;\n    artboards: {\n        id: string;\n        name: string;\n        // A url like https://xdce-stage.adobe.io/v2/document/{urn}/artboard/{guid}?version=0\n        resourceAPI: string;\n        thumbnail: {\n            assetID: string;\n            format: string;\n            scale: string;\n            // A url like https://cdn-sharing-stage.adobecc.com/content/storage/id/{urn};revision=0?component_id={guid}&access_token={token}&api_key={key}\n            url: string;\n        };\n        bounds: {\n            x: number;\n            y: number;\n            width: number;\n            height: number;\n        };\n        viewportBounds: {\n            height: number;\n        };\n        triggers: any[];\n        parent: {\n            // A url like \"https://xdce-stage.adobe.io/v2/document/{urn}?version=0\"\n            resourceAPI: string;\n        }\n    }[];\n    homeArtboardId: string;\n    version: {\n        version: string;\n        // A url like https://xdce-stage.adobe.io/v2/document/{urn}?version=0\n        resourceAPI: string;\n    };\n    history: {\n        version: string;\n        // A url like https://xdce-stage.adobe.io/v2/document/{urn}?version=0\n        resourceAPI: string;\n    }[];\n    assetID: string;\n    includesDevelopmentData: boolean;\n}\n\nexport interface IPerUserMetadata {\n    'shell:favorite'?: boolean;\n    'shell:lastAccessDate'?: string | null; // null to clear\n}\n\nexport const CLOUD_CONTENT_ROOT_FOLDER = '/cloud-content';\n\n// We wanted to make sure that the clients have a consistent way to get the listing data, so this mimics\n// ItemSource.getList()\nexport type AssetListingHints = {\n    /**\n     * some fields like orderField.shared will be disregarded for now as they are not supported in the supergraph.\n     */\n    order: AdobeAssetOrder;\n    /**\n     * some fields like excludeMediaTypes will be disregarded for now as they are not supported in the supergraph.\n     */\n    filter?: AdobeAssetFilter;\n    /**\n     * only loadOptions.limit will be used for now.\n     */\n    loadOptions?: ILoadOptions;\n\n    /**\n     * BELOW FIELDS ARE IGNORED FOR CLIENTS RIGHT NOW.\n     * They are used internally by SAM.js to optimize the query.\n     */\n\n    /**\n     * effective permissions for the children.\n     * we can set it to false internally in SAM.js for user storage folders where we know that user has all permissions.\n     */\n    effectivePermissions?: boolean;\n};\n\n/**\n * @experimental\n */\nexport type AssetLoadHints = {\n    listingHints?: AssetListingHints[];\n\n    /**\n     * BELOW FIELDS ARE IGNORED FOR CLIENTS RIGHT NOW.\n     * They are used internally by SAM.js to optimize the query.\n     */\n\n    /**\n     * shell:visibilty will be part of repoMetadata. There is a proposal for it: https://jira.corp.adobe.com/browse/CA-1396.\n     * isChildOfProject? Perhaps we can evaluate it from the asset repo:path?\n     * undefined means load all the appMetadata fields that SAM.js requires eagerly for now (i.e. shell:visibility).\n     * false means load no appMetadata fields in the query.\n     * at least we can set it to false internally in SAM.js for top level folders.\n     */\n    appMetadata?: string[] | false;\n\n    /**\n     * we will just make effective permissions be deferred for now.\n     * false means don't load the effective permissions in this query. They can be lazily loaded later by the clients. undefined is equal to false.\n     * true means load the effective permissions deferred.\n     * we can set it to false internally in SAM.js for user storage folders where we know that user has all permissions.\n     */\n    effectivePermissions?: boolean;\n\n    /**\n     * false means we don't load the per user specific metadata for this asset. Clients can lazily load it later. undefined is equal to false.\n     * true means load the per user specific metadata deferred.\n     * we can set it to false internally in SAM.js for top level folders where we know there won't be any per user specific metadata.\n     */\n    perUserMetadata?: boolean;\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { SAM } from '@ccx-public/component-types';\nimport type { ProblemType } from '../core/SAMError';\nimport { Permission } from './AssetModel';\nimport type { IServiceLink, LinkRequirements } from './LinkUtils';\nimport { RelType } from './LinkUtils';\nimport type { ActionLinks, Assignee, IEffectivePermissions, PermissionType } from './RepositoryModel';\n\nexport interface IProjectsIndexResponse {\n    _links: IProjectsIndexLinks\n}\n\nexport type IProjectView = 'all' | 'yours' | 'sharedWithYou' | 'admin';\n\nexport interface IProjectsIndexLinks {\n    [RelType.PROJECTS_PRIMARY]: IServiceLink,\n    [RelType.PROJECTS_COLLECTION]: IServiceLink,\n    [RelType.PROJECTS_CREATE]: IServiceLink,\n    [RelType.RESOLVE_PATH]: IServiceLink,\n    [RelType.PROJECTS_CONTEXT]: IServiceLink,\n    [RelType.PROJECTS_CAPABILITY]: IServiceLink,\n    [RelType.ORGANIZATIONS_COLLECTION]: IServiceLink,\n    [RelType.PROJECTS_RECENT]: IServiceLink,\n    [RelType.PROJECTS_REFERENCE_PRIMARY]: IServiceLink,\n    [RelType.PROJECTS_REFERENCE_CREATE]: IServiceLink,\n}\n\n\nexport const PROJECTS_INDEX_LINKS: LinkRequirements = {\n    [RelType.PROJECTS_PRIMARY]: [ 'assetId', 'embed' ],\n    [RelType.PROJECTS_COLLECTION]: [ 'embed', 'limit', 'orderBy', 'start', 'view' ],\n    [RelType.PROJECTS_CREATE]: [ 'embed' ],\n    [RelType.RESOLVE_PATH]: [ 'path' ],\n    [RelType.PROJECTS_GRADIENTS_COLLECTION]: [],\n    [RelType.PROJECTS_CONTEXT]: [],\n    [RelType.PROJECTS_CAPABILITY]: [ 'privilege' ],\n    [RelType.ORGANIZATIONS_COLLECTION]: [],\n    [RelType.PROJECTS_RECENT]: [ 'embed', 'after', 'first' ],\n    [RelType.PROJECTS_REFERENCE_PRIMARY]: [ 'assetId', 'referenceId' ],\n    [RelType.PROJECTS_REFERENCE_CREATE]: [ 'assetId' ],\n};\n\nexport type IProjectResourceTypes = RelType.AC_EFFECTIVE | RelType.APP_METADATA | RelType.PROJECTS_CREATOR | RelType.REPOSITORY;\nexport type IProjectsEmbeddableResource = IProjectResourceTypes[];\n\nexport type IProjectsOrderBy =\n    | 'repo:name'\n    | 'repo:createDate'\n    | 'api:metadata/peruser#mine$$shell:lastAccessDate';\n\n\nexport interface IProjectsAppMetadata {\n    'project:rendition': {\n        'gradientId': string;\n    }\n}\n\nexport enum IProjectPatchKeys {\n    GRADIENT_ID = '/project:rendition/gradientId'\n}\n\nexport interface IProjectPatchData {\n    gradientID?: string;\n}\n\nexport interface IProjectsRepoMetadata {\n    'repo:owner': Assignee; // repo:owner has same shape as repo:assignee\n    'repo:repositoryId': string;\n}\n\n\nexport type IProjectsCreatorType = 'user' | 'org';\n\nexport interface IProjectsCreatorData {\n    id: string;\n    type: IProjectsCreatorType;\n    displayName: string;\n    firstName?: string;\n    lastName?: string;\n}\n\n// We get special permissions for projects apart from the ones coming from RAPI\n// More info: https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=assetscollab&title=Proposal%3A+Project+API+V3+-+Get+Project#Proposal:ProjectAPIV3GetProject-api:ac/effective.1\nexport interface IProjectsEffectivePermissions extends IEffectivePermissions {\n    [RelType.PROJECTS_PRIMARY]?: PermissionType[];\n}\n\nexport interface IProjectsResponseEmbeddedData {\n    [RelType.APP_METADATA]?: IProjectsAppMetadata;\n    [RelType.AC_EFFECTIVE]?: IProjectsEffectivePermissions;\n    [RelType.PROJECTS_CREATOR]?: IProjectsCreatorData;\n    [RelType.REPOSITORY]?: IProjectsRepoMetadata;\n}\n\nexport interface IProject {\n    _embedded?: IProjectsResponseEmbeddedData;\n    // @TODO@PROJECT We need to define a type for project links in later milestone when we have more ops\n    _links: IProjectLinks;\n    'repo:assetId': string;\n    'repo:repositoryId': string;\n    'repo:path': string;\n    'repo:createDate': string;\n    'repo:etag': string;\n    'repo:name': string;\n    'repo:state': string;\n    'storage:assignee': Assignee;\n    'project:view'?: IProjectView;\n    'project:directorySubtype'?: string;\n}\n\nexport interface IProjectsPageSpec {\n    start: number;\n    limit: number;\n    orderBy: string;\n    count: number;\n    total: number;\n}\n\nexport interface IProjectsLinks {\n    [RelType.PROJECTS_CREATE]: IServiceLink;\n    [RelType.PROJECTS_COLLECTION]: IServiceLink;\n    next: IServiceLink;\n}\n\nexport interface IRecentProjectsLinks {\n    next?: IServiceLink;\n}\n\n// @TODO@PROJECT Should have all the links from the service represented.\nexport interface IProjectActions {\n    [RelType.PROJECTS_RENAME]: IServiceLink;\n    [RelType.APP_METADATA]: IServiceLink;\n    [RelType.PROJECTS_REFERENCE_PRIMARY]: IServiceLink;\n    [RelType.PROJECTS_REFERENCE_CREATE]: IServiceLink;\n}\n\nexport interface IProjectNavigationLinks {\n    [RelType.PAGE]?: IServiceLink;\n}\n\nexport type IProjectLinks = ActionLinks & IProjectActions & IProjectNavigationLinks;\n\nexport function _projectLinkKeys(): string[] {\n    return [ RelType.CREATE, RelType.RESTORE, RelType.DISCARD, RelType.PROJECTS_RENAME, RelType.PAGE, RelType.PROJECTS_REFERENCE_CREATE, RelType.PROJECTS_REFERENCE_PRIMARY ];\n}\n\nexport interface IProjectsResponse {\n    children: IProject[];\n    _page: IProjectsPageSpec,\n    _links: IProjectsLinks\n}\n\nexport interface IRecentProjectsResponse {\n    children: IProject[];\n    _page: never;\n    _links?: IRecentProjectsLinks;\n}\n\nexport interface IProjectsCreateData {\n    'repo:name': string;\n    [RelType.APP_METADATA]: IProjectsAppMetadata;\n}\n\nexport type ProjectViews = SAM.ProjectViews;\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport const ProjectViews = SAM.ProjectViews;\n\nexport const PROJECT_VIEW_TO_SERVICE_MAP: { [key in ProjectViews]: IProjectView } = {\n    [ProjectViews.All]: 'all',\n    [ProjectViews.Yours]: 'yours',\n    [ProjectViews.SWY]: 'sharedWithYou',\n    [ProjectViews.Admin]: 'admin',\n    [ProjectViews.Organization]: 'all',\n    [ProjectViews.Recent]: 'all'\n};\n\nexport function parseProjectEffectivePermissions(permissions: IProjectsEffectivePermissions): Permission {\n    // We get special permissions for projects which are present in the project primary relation\n    const projectPrimary = permissions[RelType.PROJECTS_PRIMARY] || permissions['*'] || [];       // permissions on the project\n    const primary = permissions[RelType.PRIMARY] || permissions['*'] || [];       // permissions on the folder representing the project\n    const directory = permissions[RelType.DIRECTORY] || permissions['*'] || [];   // parent folder's permissions\n    const annotations = permissions[RelType.ANNOTATIONS] || permissions['*'] || [];   // contains commenting permissions\n    const policy = permissions[RelType.AC_POLICY] || permissions['*'] || [];      // contains \"share\" permission\n\n    let mask = Permission.None;\n\n    // We get the 'ack', 'read', 'rename', 'discard', 'restore' permissions from the project primary relation\n    projectPrimary.forEach((perm: PermissionType) => {\n        switch (perm) {\n        case 'ack':\n            mask |= Permission.Ack;\n            break;\n        case 'read':\n            mask |= Permission.Read;\n            break;\n        case 'rename':\n            mask |= Permission.Rename;\n            break;\n        case 'discard':\n            mask |= Permission.Discard;\n            break;\n        case 'restore':\n            mask |= Permission.Restore;\n            break;\n        }\n    });\n\n    // We get the 'write' and 'delete' permissions from the folder representing the project and the parent folder\n    primary.forEach((perm: PermissionType) => {\n        switch (perm) {\n        case 'write':\n            mask |= Permission.Write;\n            break;\n        case 'delete':\n            if (directory.includes('write')) {\n                mask |= Permission.Delete;\n            }\n            break;\n        }\n    });\n\n    if (policy.includes('write')) {\n        mask |= Permission.Share;\n    }\n\n    if (annotations.includes('write')) {\n        mask |= Permission.WriteComment;\n    }\n\n    return mask;\n}\n\nexport enum ProjectCapabilities {\n    CREATE = 'create'\n}\n\nexport enum ProjectLeaveReason {\n    PENDING,\n    CAN_LEAVE,\n    /**\n     * All false reasons.\n     */\n    CANNOT_LEAVE_NO_COLLABORATORS,\n    CANNOT_LEAVE_ADDRESS_BOOK_GROUP_MEMBER,\n    CANNOT_LEAVE_LAST_COLLABORATOR,\n    /**\n     * @deprecated -- will be and removed on or after 2024-10-01.\n     */\n    CANNOT_LEAVE_LAST_DIRECT_COLLABORATOR,\n    CANNOT_LEAVE_IS_ADMIN_OF_PROJECT,\n    CANNOT_LEAVE_LAST_DIRECT_COLLAB_WITH_SHARE_PERMISSION,\n    CANNOT_LEAVE_IS_OWNER\n}\n\n/**\n * Reasons for why the user can or cannot create a project.\n */\nexport enum CanCreateProjectReason {\n    UNKNOWN,\n    ALLOWED,\n    ADMIN_DISABLED,\n    INVALID_REPOSITORY,\n    NO_HOME_REPOSITORY\n}\n\n/**\n * The interface for projects specific errors.\n */\nexport interface IProjectsServiceErrorResponse {\n    type: ProblemType;\n    title: string;\n    status: number;\n    detail?: string;\n    description?: string;\n}\n\nexport type ProjectDirectorySubtype = SAM.ProjectDirectorySubtype;\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport const ProjectDirectorySubtype = SAM.ProjectDirectorySubtype;\n\ntype ProjectDirectorySubtypeValues = `${ProjectDirectorySubtype}`;\nexport const projectDirectorySubTypes: ProjectDirectorySubtypeValues[] = [\n    'wfPortfolio',\n    'wfProgram',\n    'wfProject',\n    'wfProjectTemplate',\n    'ccProject'\n];\n\nexport interface IProjectCreateReferenceResponse {\n    'project:referenceId': string;\n    'dc:format': string;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { OpPatch } from 'json-patch';\nimport { SAM } from '@ccx-public/component-types';\nimport type { USSMetadata, ISearchQuery } from './USSModel';\nimport type { IEffectivePermissions } from './RepositoryModel';\n\nexport const CUSTOM_MODEL_MEDIA_TYPE = 'application/vnd.adobe.ffmodel+dcx';\n\nexport const CUSTOM_MODEL_RESTRICTED_METADATA_KEYS = [ 'cme:training' ] as const;\nexport type CustomModelRestrictedMetadataKey = typeof CUSTOM_MODEL_RESTRICTED_METADATA_KEYS[number];\ntype CustomModelAppMetadataPatchPath = `/${CustomModelRestrictedMetadataKey}`;\n\nexport type CustomModelPublishedState = SAM.CustomModelPublishedState;\n\n// Due to CustomModelPublishedState type alias, we need to maintain TS behavior of exporting enum as a runtime value\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport const CustomModelPublishedState = SAM.CustomModelPublishedState;\n\nexport type CreateTrainingSetOptions = {\n    name: string;\n    projectId: string;\n    // @deprecated - use the `firefly#cme` key\n    'firefly#ffmodel'?: {\n        schemaVersion: string;\n        [key: string]: any;\n    },\n    'firefly#cme': CustomModelTrainingConfiguration\n};\n\nexport type CustomModelTrainingConfiguration = {\n    contentType?: string;\n    samplePrompt?: string;\n    trainingMode: CustomModelTrainingMode;\n    // @deprecated - use schemaVersion\n    version?: string;\n    schemaVersion: string;\n    baseModelSuperclass?: string;\n    conceptId?: string;\n    classDescriptors?: string[];\n}\n\nexport type CustomModelTrainingMode = 'style' | 'subject' | 'product';\n\nexport type CustomModelTrainingState = 'inProgress' | 'success' | 'failed' | 'cancelled';\n\nexport type CustomModelMetadata = Partial<USSMetadata['app_metadata']> & {\n    'cme:inferenceReady'?: boolean;\n    'cme:signature'?: string;\n    'cme:category'?: string;\n    'cme:publishedState'?: CustomModelPublishedState;\n    'cme:samplePrompt': string;\n    'cme:baseModel'?: {\n        name: string;\n        version: string;\n    }\n    'cme:trainingSet': {\n        'repo:assetId': string;\n        'repo:version': string;\n    }\n    'cme:training': {\n        state: CustomModelTrainingState;\n        progress?: number;\n        jobId: string;\n        errorMessage?: string;\n        errorCode?: string;\n        links?: Record<string, any>,\n    }\n}\n\nexport interface ISearchQueryCustomModel extends ISearchQuery {\n    'app_metadata$$cme:publishedState'?: CustomModelPublishedState\n}\n\ntype CustomModelManifestData = {\n    classDescriptors?: string[];\n    // String representing the assessment of the training images for different archetypes (photo, vector, etc)\n    contentType: string;\n    // Specifies how the model is trained - style | subject | product\n    trainingMode: CustomModelTrainingMode;\n    // Schema version used by Firefly team to manage new fields with backward compatibility\n    schemaVersion: string;\n    // A word that describes what are the images about. e.g. dog, cat, etc. This is deduced from all the images during the training and added to the prompt during inference\n    baseModelSuperclass: string;\n    // Identifies the new concept this training will add\n    conceptId?: string;\n    // Firefly ID for the weights\n    deltaWeightsID?: string;\n    // Compression mechanism\n    compression?: string;\n};\n\n\nexport type CustomModelInfoUSS = USSMetadata & {\n    type: typeof CUSTOM_MODEL_MEDIA_TYPE;\n    original_path: string;\n    'storage:assignee': string;\n    app_metadata: CustomModelMetadata;\n    'firefly#ffmodel': CustomModelManifestData;\n}\n\n// describes the shape of CustomModelInfo as returned from Melville\n// https://git.corp.adobe.com/pages/Stormcloud/apidocs/?urls.primaryName=melville#/Custom%20Models/getCustomModel\nexport type CustomModelInfoMelville = {\n    type: typeof CUSTOM_MODEL_MEDIA_TYPE;\n    // boolean indicating if the custom model data was served from Melville's cache\n    _fc: boolean;\n    _links: any;\n    asset_acl: IEffectivePermissions;\n    'repo:assetId': string;\n    'repo:createDate': number;\n    'repo:modifyDate': number;\n    'repo:name': string;\n    'repo:createdBy': string;\n    'repo:version': string;\n    'repo:size': number;\n    'repo:path': string;\n    'repo:etag': string;\n    'storage:region': string;\n    'storage:assignee': string;\n    application_metadata: CustomModelMetadata;\n    'firefly#ffmodel': CustomModelManifestData\n}\n\ntype CustomModelUpdateInfoApplicationMetadata = Pick<\nCustomModelInfoMelville['application_metadata'],\n'cme:baseModel' | 'cme:signature' | 'cme:samplePrompt' | 'cme:category'\n>;\ntype CustomModelUpdateInfoComponent = {\n    id: string;\n    name?: string;\n    path: string;\n    type: string;\n    rel?: string;\n    etag: string;\n    version: string;\n    md5: string;\n    length: 0;\n    width?: 0;\n    height?: 0;\n}\n\n/**\n * describes the shape of request body for updating a custom model in Melville\n * https://git.corp.adobe.com/pages/Stormcloud/apidocs/?urls.primaryName=melville#/Custom%20Models/updateCustomModel\n */\nexport type CustomModelUpdateInfoMelville = Partial<\nCustomModelUpdateInfoApplicationMetadata &\nPick<CustomModelInfoMelville, 'firefly#ffmodel'> & {\n    components: CustomModelUpdateInfoComponent[];\n}>;\n\n/**\n * For most cases, Custom Models should be updated with the CustomModel.update method.\n * There are exceptions where the application metadata can be updated directly, though.\n */\nexport type CustomModelAppMetadataPatch = OpPatch & {\n    path: CustomModelAppMetadataPatchPath;\n}\n\nexport type CustomModelsResponseMelville = {\n    total_count: number;\n    custom_models: CustomModelInfoMelville[];\n    _links: any\n}\n\nexport type CustomModelCreateOptions = {\n    'firefly#ffmodel': {\n        trainingMode: string,\n        baseModelSuperclass?: string,\n        deltaWeightsID?: string,\n        classDescriptors?: string[],\n        conceptId?: string,\n        contentType: string,\n        schemaVersion: string\n    },\n    'cme:trainingSet': {\n        'repo:assetId': string,\n        'repo:version': string\n    },\n    'cme:baseModel'?: {\n        name: string,\n        version: string\n    },\n    'cme:signature'?: string,\n    'cme:samplePrompt': string,\n    'cme:category'?: string\n}\n\nexport enum CustomModelOrderBy {\n    MODIFY_DATE = 'modified_date',\n    CREATE_DATE = 'created_date',\n    NAME = 'name'\n}\n\ntype MelvilleOrderBy = CustomModelOrderBy.NAME | CustomModelOrderBy.MODIFY_DATE | CustomModelOrderBy.CREATE_DATE | '-name' | '-created_date' | '-modified_date' | string;\n\n// When adding values here which take an array of strings, write tests against LibraryInterface.sortParameters to ensure\n// we are are getting the same order of strings each time. This prevents unnecessary cache misses Melville side\nexport type MelvilleCustomModelListParameters = {\n    start?: number;\n    limit?: number;\n    orderBy?: MelvilleOrderBy;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { CustomModelListingOptions } from './LegacyCustomModelInterface';\nimport type { AssetLinks } from '../../interface/RepositoryModel';\n\nexport enum CustomModelPublishedState {\n    DRAFT = 'draft',\n    READY = 'ready',\n    PUBLISHED = 'published',\n    UNPUBLISHED = 'unpublished',\n    QUEUED = 'queued',\n    TRAINING = 'training',\n    FAILED = 'failed',\n    CANCELLED = 'cancelled',\n    ALL = 'all'\n}\n\nexport enum CustomModelOrderBy {\n    MODIFY_DATE = 'modifyDate',\n    CREATE_DATE = 'createDate',\n    NAME = 'name'\n}\n\nexport type LegacyCreateTrainingSetOptions = {\n    name: string;\n    projectId: string;\n    'firefly#ffmodel': {\n        schemaVersion: string;\n        [key: string]: any;\n    }\n};\n\nexport type CustomModelTrainingConfiguration = {\n    contentType?: string;\n    samplePrompt?: string;\n    trainingMode?: 'style' | 'subject' | 'product';\n    // version soon to be deprecated\n    version?: string;\n    schemaVersion: string;\n    baseModelSuperclass?: string;\n    conceptId?: string;\n}\n\n\nexport type CustomModelData = {\n    assetId: string,\n    type: string,\n    createdBy: string,\n    createDate: string,\n    modifyDate: string,\n    assetName: string,\n    displayName: string,\n    publishedState: CustomModelPublishedState,\n    inferenceReady: boolean,\n    path: string,\n    version: string\n    etag: string\n    region: string,\n    size: number,\n    samplePrompt: string,\n    _links: AssetLinks,\n    renditionUrl?: string,\n    baseModelVersion: string,\n    basemodelName: string,\n    conceptId: string,\n    trainingMode: string,\n}\n\nexport type CustomModelsResponse = {\n    items: CustomModelData[],\n    nextPage?: CustomModelListingOptions,\n    total?: number\n}\n\nexport type LegacyCustomModelCreateOptions = {\n    trainingSetId: string\n}\n\nexport type CustomModelsMelvilleResponse = {\n    id: string\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n// TODO: Remove after all clients have upgraded to UXP 6.2\n// https://jira.corp.adobe.com/browse/UXP-19257\nimport 'abort-controller/polyfill';\n\nimport { default as uuid } from './uuid';\nimport { memoize, synchronized } from './decorators';\nimport SAMError, { SAMErrorCode } from './SAMError';\nimport MobX from './MobX';\nimport type { IPersistentCache } from '../core/Cache';\nimport Cache from '../core/Cache';\nimport { DEFAULT_CACHE_KEEP_ALIVE_TTL } from '../core/decorators/KeepAliveManager';\nimport { LogLevel } from './SAMCore';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport { MESSAGE_LOGGED, MessageLoggedEvent } from '../indexPrivate';\nimport type IEvent from './IEvent';\nimport { CONFIG_CHANGE } from './SAMCoreEvents';\nimport { deepClone } from './ObjectUtils';\nimport type { HeaderMap } from '../interface/LinkUtils';\nimport ResponseCache from '../interface/ResponseCache';\nimport type { LogSink } from '../sync-services/Logging';\n\n// Utility for combining multiple signals:\nconst combineSignals = (options: {[s: string]: any}, ...signals: AbortSignal[]) => {\n    const controller = new AbortController();\n    const removeListeners = () => {\n        signals.forEach(signal => signal.removeEventListener('abort', onAbort));\n    };\n    const onAbort = () => {\n        controller.abort();\n        removeListeners();\n    };\n    if (signals.some(signal => signal.aborted)) {\n        onAbort();\n    } else {\n        signals.forEach(signal => signal.addEventListener('abort', onAbort));\n    }\n    options.signal = controller.signal;\n    return removeListeners;\n};\n\nexport enum Env {\n    Stage,\n    Production\n}\n\nexport type HostProductData = {\n    /**\n     * The name of the user-facing product, with version number. E.g. Photoshop/22.0\n     *  https://git.corp.adobe.com/pages/adobesearch/search-services-docs/uss/getting-started/\n     */\n    PRODUCT_ID: string,\n    /**\n     * The feature within the user-facing product, with version number. E.g., CDO/1.125.0\n     * https://git.corp.adobe.com/pages/adobesearch/search-services-docs/uss/getting-started/\n     *\n     * @TODO_Deprecation To be marked as deprecated on or after 2024-10-01. SAM.js is now providing\n     * this header, so there is no need for clients to configure it.\n     */\n    PRODUCT_LOCATION: string,\n}\n\nconst DEFAULT_HOST_PRODUCT_DATA: HostProductData = {\n    PRODUCT_ID: '',\n    PRODUCT_LOCATION: ''\n};\n\n// Define as required: everything that is necessary as either client-supplied config or default config.\n// Define as optional: anything optional for both client-supplied config and default config.\ntype InternalConfiguration = {\n    ENVIRONMENT: Env,\n    // Required for USS searches\n    HOST_PRODUCT_DATA: HostProductData,\n    USER_ID: string,\n    USER_EMAIL?: string,\n    CLIENT_ID: string,\n    ACCOUNT_TYPE?: string,\n    ACCESS_TOKEN: string,\n    DEVICE_ID?: string,\n    FETCH_REQUEST_TIMEOUT: number,\n    GRAPHQL_WATCH_QUERY_TTL: number,\n    ASYNC_DEFAULT_DELAY: number,\n    CACHE_DEFAULT_TTL: number,\n    CACHE_KEEP_ALIVE_TTL?: number,\n    MIN_RETRY_INTERVAL: number,\n    MAX_RETRY_INTERVAL: number,\n    ONS_DOCUMENT_VISIBILITY_TIMEOUT: number,\n    ONS_DEFAULT_MAX_SUBSCRIPTIONS: number,\n    ONS_DEFAULT_MAX_ASSETS_PER_SUBSCRIPTION: number,\n    ONS_SUBSCRIPTION_TIME_TO_LIVE: number,\n    ONS_SUBSCRIPTION_RENEW_TIME: number,\n    INDEXED_DB_VERSION: number,\n    PROJECTS_LIST_UPDATE_LATENCY: number,\n    PROJECTS_ITEM_UPDATE_LATENCY: number,\n    CLASSROOMS_LIST_UPDATE_LATENCY: number,\n    ASSETS_LIST_UPDATE_LATENCY: number,\n    USS_LIST_UPDATE_LATENCY: number,\n    VERSIONS_LIST_UPDATE_LATENCY: number,\n    GQL_LIST_UPDATE_LATENCY: number,\n    ASSET_COPY_NAME_FORMAT: string,\n    ASSET_CONFLICT_NAME_FORMAT: string,\n    FEATURE_FLAGS: {\n        'enable-x-bucket-move'?: boolean;\n        'enable-response-cache'?: boolean;\n        'use-graphql-cache'?: boolean;\n        'enable-acpl-next-polyfills'?: boolean;\n        'disable-sam-cpp-models'?: boolean;\n        'move-capabilities'?: {\n            'enable-CCI-CCI-move'?: boolean;\n        };\n        'use-graphql'?: boolean;\n        'use-pls-recents'?: boolean;\n        'use-pls-swy'?: boolean;\n        'generation-history-vectors'?: boolean;\n        'generation-history-audio'?: boolean;\n    };\n    /**\n     * @deprecated -- this flag is no longer functional and will be removed on or after 2024-10-01\n     */\n    USE_SAM_CPP?: boolean,\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _DISABLE_SAM_CPP?: boolean,\n    DISABLE_ONS: boolean,\n    /**\n     * @deprecated -- this flag is no longer functional and will be removed on or after 2024-10-01\n     */\n    COPY_RESOURCES?: boolean,\n    ENABLE_ONS_CACHE: boolean,\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _VERSION_OVERRIDE_FOR_TEST: string,\n    HIGH_PRIORITY_RAPI_REQUESTS: boolean,\n    LOCALE?: string,\n    // Allow for the client to change the default Frameio token expiration.\n    // Value is number of minutes to expire after.\n    FRAMEIO_EXPIRE_AUTH_TOKEN?: number,\n    FRAMEIO_EXPIRE_REFRESH_TOKEN?: number,\n    /**\n     * @package -- only for use in SAM.js\n     */\n\n    /*\n     * Our services typically require an Authorization header\n     * with a valid Bearer token because the user must be\n     * logged into the Creative Cloud.\n     *\n     * But the Commenting UI lets users without a Creative Cloud\n     * account view assets when they've been shared with a public\n     * link, and they are allowed to comment on such assets\n     * if they create a temporary Guest session with the commenting\n     * service.\n     *\n     * So to support commenting, SESSION_TYPE can be\n     *   { 'logged-out', 'guest', 'logged-in' }\n     *\n     * where the default value is 'logged-in'.\n     */\n    SESSION_TYPE: string,\n    ONS_OVER_AXON: boolean,\n    /*\n     * As part of Storage Model Unification (SMU) support, we need to\n     * enable a way for the Admin Console to indicate to services\n     * that project listings need to include all projects in the\n     * ownership of the org, not just the user.\n     *\n     * When ADMIN_MODE_ORG_ID is set to an OrgID, SAM will include the\n     * `X-ACP-ADMIN-PRIVILEGES` header in all service requests,\n     * with the header value set to the supplied OrgID.\n     *\n     * The default value is undefined, which prevents the\n     * `X-ACP-ADMIN-PRIVILEGES` header from being included in service requests.\n     *\n     * See https://wiki.corp.adobe.com/display/CA/Proposal%3A+Storage+Model+Unification+Detailed+Design#Proposal:StorageModelUnificationDetailedDesign-ListingofProjects\n     */\n    ADMIN_MODE_ORG_ID?: string,\n    /*\n     * Curated Collections are publicly available showcases of the Knowledge Workspace functionality.\n     * To ensure that these collections are served from the edge network for performance reasons, we\n     * will expose a new config option, REQUEST_EDGE_BASED_PUBLISHED_LINKS, to be used by Acrobat DC on Web.\n     *\n     * When REQUEST_EDGE_BASED_PUBLISHED_LINKS is set to true, SAM will include the\n     * `acpc-published-links` header in all service requests, which\n     * will cause RAPI to generate edge based links with publicId for published content,\n     * even when incoming endpoint is not edge-based.\n     *\n     * The default value is false, which prevents the\n     * `acpc-published-links` header from being included in service requests.\n     *\n     * See https://wiki.corp.adobe.com/display/CA/Support+scalability+in+serving+public+content+in+alignment+with+Community+Platform+Advancement#SupportscalabilityinservingpubliccontentinalignmentwithCommunityPlatformAdvancement-DetailedDesign\n     */\n    REQUEST_EDGE_BASED_PUBLISHED_LINKS?: boolean,\n\n    /**\n     * When set, all requests will include a User-Id header with the value of REQUEST_AS_USER_ID.\n     * This is primarily used for services who are acting on behalf of a user, such as\n     * Workfront.\n     */\n    REQUEST_AS_USER_ID?: string,\n\n    /**\n     * Lazy load SAMCore context\n     * @default true\n     */\n    LAZY_CONTEXT?: boolean\n\n    /**\n     * When set, all requests will include a Request-Id header with the value of REQUEST_ID:<UUID>.\n     * This is primarily used to track requests orginating outside AUP systems. We append a UUID to the end of the\n     * request ID to help create a unique request ID for each request.\n     *\n     * For example if the request ID is \"1234\" and the UUID is \"5678\" then the Request-Id header will be \"1234:5678\".\n     *\n     * @note - This is a global setting so using this in an environment where others could set this asynchronously\n     * could lead to unexpected behavior and override the value set by another client. This is primarily designed for services\n     * in isolated environments like Workfront.\n     */\n    REQUEST_ID?: string,\n\n    /**\n     * When set, all requests will include a Breadcrumb-Trail header with the value of BREADCRUMB_TRAIL with\n     * SAMJS_<UUID> appended to the end of it.\n     *\n     * For example if the breadcrumb trail is \"WF_1234\" and the UUID is \"5678\" then the Breadcrumb-Trail\n     * header will be \"WF_1234-SAMJS_5678\".\n     *\n     * @note - This is a global setting so using this in an environment where others could set this asynchronously\n     * could lead to unexpected behavior and override the value set by another client. This is primarily designed for services\n     * in isolated environments like Workfront.\n     */\n    BREADCRUMB_TRAIL?: string,\n    /**\n     * When set, all requests will include Client-Agent header with the value of EXECUTION_CONTEXT_CLIENT_AGENT.\n     * Each property is converted to a key-value pair in the Client-Agent header.\n     *\n     * | Property | Description | Example | Notes |\n     * |----------|-------------|---------|-------|\n     * | v | version | 2 | 2 for now |\n     * | app | app name and version | Adobe Express 3.0 | App name/version or \"na\" if unavailable |\n     * | os | OS name and version | Windows 11 | OS name/version or \"na\" if unavailable |\n     * | device | Device details | Macbook Pro | device details or \"na\" if unavailable |\n     * | surface | web/mobile/desktop | mobile | web/mobile/desktop |\n     *\n     * @example\n     * {\n     *     v: '2',\n     *     app: 'Workfront',\n     *     os: 'Windows',\n     *     device: 'Macbook Pro',\n     *     surface: 'mobile'\n     * }\n     *  Will be converted to:\n     *  Client-Agent: v=2; app=Workfront; os=Windows; device=Macbook Pro; surface=mobile\n     *\n     */\n    EXECUTION_CONTEXT_CLIENT_AGENT?: {\n        v: '2',\n        app?: string,\n        os?: string;\n        device?: string;\n        surface?: 'web' | 'desktop' | 'mobile';\n    }\n}\n\n/**\n * SAM.js Configuration passed in from the client.\n * @param ACCESS_TOKEN {string} (optional, discouraged) Access token for the current user. NOTE: clients should use\n *          refreshAccessToken hook instead, as it is not possible to re-initialize SAM when the token expires.\n * @param CLIENT_ID {string} API key used for service requests. See SAM.js README for the list of services for which\n *          this API key must be white-listed for SAM.js to be fully functional.\n * @param HOST_PRODUCT_DATA {HostProductData} Used for USS queries to allow USS team to track usage patterns.\n * @param USER_ID {string} Adobe user id for the current user\n * @param HIGH_PRIORITY_RAPI_REQUESTS {boolean} (optional) User-facing web apps should set this to true,\n *          otherwise leave it as the default.\n * @param ONS_OVER_AXON {boolean} (optional) Client apps should set this to true for enabling ONS\n *          notification over Axon WebSocket technology, as opposed to HTTP Long Poll method.\n * Clients can override other SAM.js defaults, but it is discouraged unless directed by the SAM.js team.\n */\nexport type Configuration = Pick<InternalConfiguration,\n    | 'CACHE_KEEP_ALIVE_TTL'\n    | 'CLIENT_ID'\n    | 'HOST_PRODUCT_DATA'\n    | 'USER_ID'\n    | 'REQUEST_AS_USER_ID'\n    | 'REQUEST_ID'\n    | 'BREADCRUMB_TRAIL'\n    | 'EXECUTION_CONTEXT_CLIENT_AGENT'\n> & Partial<InternalConfiguration>\n\ntype EnvironmentConfig = {\n    LABEL: string,\n    ACP_CS_HOST: string,\n    SYNC_SERVICE_HOST: string,\n    PROJECTS_HOST: string,\n    ASSIGNMENTS_HOST: string,\n    INVITATIONS_HOST: string,\n    TRANSFER_SERVICE_HOST: string,\n    USS_HOST: string,\n    XDCE_HOST: string,\n    REVIEW_SERVICE_HOST: string,\n    MELVILLE_HOST: string,\n    MELVILLE_EDGE_HOST: string,\n    USSv3_HOST: string,\n    PPS_HOST: string,\n    BEHANCE_HOST: string,\n    CLASSROOMS_HOST: string,\n    COMMENT_HOST: string,\n    AXON_HOST: string,\n    ACPC_SUPERGRAPH_HOST: string,\n    ACPC_SUPERGRAPH_EDGE_HOST: string,\n    ABS_HOST: string,\n    WORKFRONT_HOST: string,\n};\n\ntype EnvironmentConfigMap = {\n    [k in Env]: EnvironmentConfig\n};\n\nexport type UpdatableConfiguration = Pick<Configuration, 'LOCALE' | 'ONS_OVER_AXON' | 'REQUEST_AS_USER_ID' | 'REQUEST_ID' | 'BREADCRUMB_TRAIL' | 'EXECUTION_CONTEXT_CLIENT_AGENT'>;\nexport type UpdatableKey = keyof UpdatableConfiguration;\n\n// Default settings\nconst DEFAULT_CONFIG: InternalConfiguration = {\n    USER_ID: '',\n    USER_EMAIL: '',\n    CLIENT_ID: '',\n    ACCESS_TOKEN: '',\n    ENVIRONMENT: Env.Production,\n    HOST_PRODUCT_DATA: DEFAULT_HOST_PRODUCT_DATA,\n    FETCH_REQUEST_TIMEOUT: 60 * 1000, // 1 minute timeout on requests\n    ASYNC_DEFAULT_DELAY: 1 * 1000, // 1 second to wait for monitor results. This default is matching DCX.JS.\n    CACHE_DEFAULT_TTL: 30 * 24 * 60 * 60 * 1000, // 30 days in msec\n    CACHE_KEEP_ALIVE_TTL: DEFAULT_CACHE_KEEP_ALIVE_TTL, // 10 minutes\n    MIN_RETRY_INTERVAL: 1 * 1000, // 1 second is default interval between retries\n    MAX_RETRY_INTERVAL: 2 * 60 * 1000, // 2 minutes is a maximum interval between retries\n    ONS_DOCUMENT_VISIBILITY_TIMEOUT: 10 * 1000, // 10 seconds is default timeout for stopping ONS for invisible document\n    ONS_DEFAULT_MAX_SUBSCRIPTIONS: 5, // These are default values - the ONS root document returns the actual values for max subscriptions and assets per subscription\n    ONS_DEFAULT_MAX_ASSETS_PER_SUBSCRIPTION: 100,\n    GRAPHQL_WATCH_QUERY_TTL: 1000 * 30, // How long to wait for deferred GQL data to arrive for a given query\n\n    // @TODO Since we are creating more subscriptions more often due to\n    // us no longer caching subscriptions we will need to set\n    // the TTL to a more recent time in order for subscriptions\n    // to get garbage collected faster. We should update this once\n    // SAM-2845 is done. Generally, web clients should leave it at the default. Clients like the Library\n    // Process need longer timeouts since it stays open longer, thus reducing the frequency of\n    // renewing subscriptions.\n    ONS_SUBSCRIPTION_TIME_TO_LIVE: 1000 * 60 * 60 * 6, // 6 hours in msec for ONS Subscription TTL default\n    ONS_SUBSCRIPTION_RENEW_TIME: 1000 * 60 * 5, // 5 mins in msec as minimum time before TTL is renewed\n    INDEXED_DB_VERSION: 1, // Version for indexedDB database\n    PROJECTS_LIST_UPDATE_LATENCY: 3000, // 3s delay that we wait between mutations and new requests to projects listings.\n    PROJECTS_ITEM_UPDATE_LATENCY: 1000, // 1s delay that we wait between mutations and new requests to projects items.\n    CLASSROOMS_LIST_UPDATE_LATENCY: 3000, // 3s delay that we wait between mutations and new requests to classroon listings.\n    ASSETS_LIST_UPDATE_LATENCY: 100, // 100ms delay that we wait between mutations and new requests to assets listings.\n    USS_LIST_UPDATE_LATENCY: 3000, // USS has a delay on indexing\n    VERSIONS_LIST_UPDATE_LATENCY: 100, // 100ms delay that we wait between mutations and new requests to assets listings.\n    GQL_LIST_UPDATE_LATENCY: 100, // GraphQL delay\n    ASSET_COPY_NAME_FORMAT: '%@ copy (%d)', // FORMAT to use when duplicating an asset\n    ASSET_CONFLICT_NAME_FORMAT: '%@ (%d)', // FORMAT to use when asset name conflicts in copy/move operation\n    DISABLE_ONS: false, // can set to true to disable ONS - this could be used if a client is doing a one-time operation and doesn't need change notifications\n    ENABLE_ONS_CACHE: false,\n    _VERSION_OVERRIDE_FOR_TEST: '',\n    HIGH_PRIORITY_RAPI_REQUESTS: false,\n    LOCALE: 'en-US',\n    SESSION_TYPE: 'logged-in',\n    ONS_OVER_AXON: false,\n    FEATURE_FLAGS: {\n        'enable-x-bucket-move': false, // This will add the enable-x-bucket-move header to RAPI move requests.\n        'enable-response-cache': false, // Enables the local response cache (Resource).\n        'use-graphql-cache': false, // Enables the local GraphQL response cache\n        'move-capabilities': {\n            'enable-CCI-CCI-move': false\n        },\n        'use-graphql': false,\n        'use-pls-recents': false,\n        'use-pls-swy': false,\n        'enable-acpl-next-polyfills': false,\n        'disable-sam-cpp-models': false\n    },\n    REQUEST_EDGE_BASED_PUBLISHED_LINKS: false,\n    EXECUTION_CONTEXT_CLIENT_AGENT: undefined\n};\n\nexport const ENVIRONMENTS: EnvironmentConfigMap = {\n    [Env.Stage]: {\n        LABEL: 'Staging',\n        ACP_CS_HOST: 'platform-cs-stage.adobe.io',\n        SYNC_SERVICE_HOST: 'acp-ss-stage.adobe.io',\n        PROJECTS_HOST: 'ccprojects-stage.adobe.io',\n        ASSIGNMENTS_HOST: 'hume-stage.adobe.io',\n        INVITATIONS_HOST: 'invitations-stage.adobe.io',\n        TRANSFER_SERVICE_HOST: 'ats-stage.adobe.io',\n        USS_HOST: 'adobesearch-stage.adobe.io',\n        XDCE_HOST: 'xdce-stage.adobe.io',\n        REVIEW_SERVICE_HOST: 'ccassetreview-stage.adobe.io',\n        MELVILLE_HOST: 'ccx-melville-stage.adobe.io',\n        MELVILLE_EDGE_HOST: 'platform-cs-edge-stage.adobe.io',\n        USSv3_HOST: 'acp-asset-ussv3-stage.adobe.io',\n        PPS_HOST: 'pps-stage.adobe.io',\n        BEHANCE_HOST: 'cc-api-behance-stage.adobe.io',\n        CLASSROOMS_HOST: 'edu-classrooms-stage.adobe.io',\n        COMMENT_HOST: 'comments-stage.adobe.io',\n        AXON_HOST: 'axon.stg.aws.adobess.com',\n        ACPC_SUPERGRAPH_HOST: 'platform-cs-stage.adobe.io/graphql',\n        ACPC_SUPERGRAPH_EDGE_HOST: 'platform-cs-edge-stage.adobe.io/graphql',\n        ABS_HOST: 'ab-stg.adobe-identity.com',\n        WORKFRONT_HOST: 'workfront-stage.adobe.io'\n    },\n    [Env.Production]: {\n        LABEL: 'Production',\n        ACP_CS_HOST: 'platform-cs.adobe.io',\n        SYNC_SERVICE_HOST: 'acp-ss.adobe.io',\n        PROJECTS_HOST: 'ccprojects.adobe.io',\n        ASSIGNMENTS_HOST: 'hume.adobe.io',\n        INVITATIONS_HOST: 'invitations.adobe.io',\n        TRANSFER_SERVICE_HOST: 'ats.adobe.io',\n        USS_HOST: 'adobesearch.adobe.io',\n        XDCE_HOST: 'xdce.adobe.io',\n        REVIEW_SERVICE_HOST: 'ccassetreview.adobe.io',\n        MELVILLE_HOST: 'libraries.adobe.io',\n        MELVILLE_EDGE_HOST: 'platform-cs-edge.adobe.io',\n        USSv3_HOST: 'acp-asset-ussv3.adobe.io',\n        PPS_HOST: 'pps.adobe.io',\n        BEHANCE_HOST: 'cc-api-behance.adobe.io',\n        CLASSROOMS_HOST: 'edu-classrooms.adobe.io',\n        COMMENT_HOST: 'comments.adobe.io',\n        AXON_HOST: 'axon.adobess.com',\n        ACPC_SUPERGRAPH_HOST: 'platform-cs.adobe.io/graphql',\n        ACPC_SUPERGRAPH_EDGE_HOST: 'platform-cs-edge.adobe.io/graphql',\n        ABS_HOST: 'ab.adobe-identity.com',\n        WORKFRONT_HOST: 'workfront.adobe.io'\n    }\n};\n\nconst isNonEmptyString = (x: any) => (typeof x === 'string') && Boolean(x);\nconst isNumber = (x: any) => (typeof x === 'number');\ntype ConfigItemValidator = {\n    key: keyof InternalConfiguration;\n    validator: (x: any) => boolean;\n}\n\nconst configItemValidators: Array<ConfigItemValidator> = [ {\n    key: 'CLIENT_ID',\n    validator: isNonEmptyString\n}, {\n    key: 'USER_ID',\n    validator: isNonEmptyString\n}, {\n    key: 'ENVIRONMENT',\n    validator: (x: any) => isNumber(x) && (x in Env)\n}, {\n    key: 'HOST_PRODUCT_DATA',\n    validator(hostProductData?: HostProductData) {\n        if (!hostProductData) {\n            return false;\n        }\n        const { PRODUCT_ID } = hostProductData;\n        // required for USS queries\n        return isNonEmptyString(PRODUCT_ID);\n    }\n} ];\n\nexport type Hooks = {\n    fetch?: typeof fetch,\n    refreshAccessToken?: (failedToken: string) => Promise<string>\n    persistentCache?: IPersistentCache\n}\n\nexport type ConfigurationPayload = {\n    configurationKeyName: keyof Configuration;\n};\n\n// Only allow one retry on a 401 response to avoid getting into an infinite loop if we keep being given an invalid access token\nconst MAX_401_RETRIES = 1;\n\nexport type IFetchOptions = Omit<RequestInit, 'headers'> & {\n    headers?: HeaderMap;\n    authHeader?: string;\n    noOtherHeaders?: boolean;\n    requestTimeoutMs?: number;\n    noApiKeyHeader?: boolean;\n}\n\nexport default class Environment implements ISAMObject {\n    private _config: InternalConfiguration;\n    private _cache: Cache;\n    /**\n     * @package -- for use in SAM.js only\n     */\n    public _isTokenInvalid = true;\n    readonly mobx = new MobX;\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _responseCache: ResponseCache | undefined;\n\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        userConfig: Configuration,\n        readonly _hooks: Hooks\n    ) {\n        const featureFlagsConfig = Object.assign({}, DEFAULT_CONFIG.FEATURE_FLAGS, userConfig.FEATURE_FLAGS);\n        const config: InternalConfiguration = Object.assign({}, DEFAULT_CONFIG, userConfig);\n        config.FEATURE_FLAGS = featureFlagsConfig;\n        const invalidOptions = configItemValidators.filter(({ key, validator }) => !validator(config[key]));\n\n        if (invalidOptions.length) {\n            const invalidKeys = invalidOptions.map(({ key }) => key).join(', ');\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Invalid required options: ${invalidKeys}`);\n        }\n\n        if (config.ACCESS_TOKEN) {\n            this._isTokenInvalid = false;\n        } else if (!_hooks.refreshAccessToken) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `refreshAccessToken hook must be provided if ACCESS_TOKEN is not set`);\n        }\n\n        this._config = config;\n        this._cache = new Cache(config.USER_ID, _core, _hooks.persistentCache);\n\n        if (this.getValue('FEATURE_FLAGS')['enable-response-cache']) {\n            this._responseCache = new ResponseCache(this._core);\n        }\n    }\n\n    get cache(): Cache {\n        return this._cache;\n    }\n\n    getValue<K extends keyof InternalConfiguration>(key: K): InternalConfiguration[K] {\n        return this._config[key];\n    }\n\n    /**\n     * Set the _environment global configuration value.\n     *\n     * @param key Configuration KeyName\n     * @param value The value of the Configuration.\n     * @event IEvent Dispatches an event when a particular key has changed.\n     */\n    setValue<K extends keyof InternalConfiguration>(key: K, value: InternalConfiguration[K]) {\n        this._config[key] = value;\n        const event: IEvent = {\n            type: CONFIG_CHANGE\n        };\n        const eventPayload: ConfigurationPayload = {\n            configurationKeyName: key\n        };\n        this._core.dispatch(event, eventPayload);\n    }\n\n    get endpoints(): EnvironmentConfig {\n        const env: Env = this._config.ENVIRONMENT;\n        return ENVIRONMENTS[env];\n    }\n\n    // Returns a unique device id for the client - this can be provided as a config option, or a guid can\n    // be generated (which will be cached across instances for the same user). Note that if a value is passed in,\n    // this takes precedence even if there's a cached device id.\n    @memoize\n    async getDeviceId(): Promise<string> {\n        return this._config['DEVICE_ID'] || await this.cache.getItem('DEVICE_ID', async () => uuid(), (value: any) => typeof value === 'string');\n    }\n\n    getUserId(): string {\n        return this.getValue('USER_ID');\n    }\n\n    /**\n     * The maximum number of retries for any network operation.\n     * @internal\n     */\n    get _maxNumberOfRetries(): number {\n        return MAX_401_RETRIES;\n    }\n\n    // This is a convenience method for clients to use the SAM.js logger, which will handle\n    // logging messages at different levels.\n    // TODO: [SHARED-4061] Refactor to avoid bind() calls in a getter as this, as it could affect memory consumption if accessed many times.\n    get logSink(): LogSink {\n        return {\n            error: this.error.bind(this),\n            warn: this.warn.bind(this),\n            info: this.log.bind(this),\n            debug: this.debug.bind(this)\n        };\n    }\n\n    private _loggerEvent(message: string, level: LogLevel) {\n        if (this._core.listenerCount(MESSAGE_LOGGED) > 0) {\n            this._core.emit(MESSAGE_LOGGED, new MessageLoggedEvent(message, level));\n        }\n    }\n\n    // Reserve for informational messages that may be useful in debugging infrequent but major\n    // SAM.js system events, such as initializing, or refreshing auth token.\n    log(message: string) {\n        this._loggerEvent(message, LogLevel.Info);\n    }\n\n    // Reserve for detailed messages about complex coordinated async processes, such as List loading, that\n    // are difficult to trace without log messages, but are too noisy to include in regular production apps.\n    debug(message: string) {\n        this._loggerEvent(message, LogLevel.Debug);\n    }\n\n    // For error conditions that do not warrant throwing an exception that bubbles to the client, but could be\n    // useful for debugging purposes. E.g., an ItemUpdater failing to parse a field from a service response --\n    // devs should see and fix these errors immediately and have unit tests to validate it, but the same error\n    // in a production system should not necessarily be raised to the user.\n    error(message: string) {\n        this._loggerEvent(message, LogLevel.Err);\n    }\n\n    // For deprecation notices and possibly (but not definitively) bad configuration options, etc. These sorts of\n    // messages should include instructions on how to resolve the issue. E.g. how React treats warnings about missing\n    // `key` on children -- this isn't necessarily a breaking condition but often can cause bugs; since they are\n    // entirely avoidable, devs should work to eradicate the warnings so they do not become red herrings that must\n    // be investigated when an unrelated bug emerges.\n    warn(message: string) {\n        this._loggerEvent(message, LogLevel.Warn);\n    }\n\n    /**\n     * @internal\n     */\n    @synchronized\n    async _refreshAccessToken() {\n        if (this._config.SESSION_TYPE !== 'logged-out' && this._isTokenInvalid) {\n            if (!this._hooks.refreshAccessToken) {\n                // If a refresh hook wasn't provided, we just clear the token so we don't keep on\n                // attempting requests with an invalid token\n                return '';\n            }\n            this.log(`Refreshing access token from host...`);\n            try {\n                this._config.ACCESS_TOKEN = await this._hooks.refreshAccessToken(this._config.ACCESS_TOKEN);\n            } catch (e) {\n                // The error could already be a SAM error due to the recursive fetch calls above.\n                throw SAMError.wrapErrorIfNeeded(SAMErrorCode.AUTHORIZATION_ERROR, 'Failed to refresh access token', e);\n            }\n            if (this._config.ACCESS_TOKEN) {\n                this._isTokenInvalid = false;\n            }\n            this.log(`Refreshing access token ${this._config.ACCESS_TOKEN ? 'successful' : 'unsuccessful'}`);\n        }\n        return this._config.ACCESS_TOKEN;\n    }\n\n    async fetch(url: string, options: IFetchOptions = {}, numRetries: number = 0): Promise<Response> {\n        if (this._hooks?.fetch) {\n            return this._hooks.fetch(url, options as Parameters<typeof fetch>[1]);\n        }\n\n        const session = this._config.SESSION_TYPE;\n\n        // If the access token is invalid, we wait for it to be refreshed:\n        const token = this._isTokenInvalid ? await this._refreshAccessToken() : this._config.ACCESS_TOKEN;\n        if ((session !== 'logged-out') && !token) {\n            throw SAMError.create(SAMErrorCode.AUTHORIZATION_ERROR, `Unable to obtain access token - did you provide a refreshAccessToken hook?`);\n        }\n\n        // Extract parameters that won't be passed to `fetch`, and clone the ones that will so that a) there are no\n        // side-effects to the caller, and b) 401 retries can use the same `options` as the original request.\n        const { headers = {}, authHeader, noOtherHeaders, requestTimeoutMs, noApiKeyHeader, ...requestInit } = options;\n\n        // ONS uses a different auth header from other services, so this needs to be configurable\n        const authorizationHeader = 'Authorization';\n\n        const auth = (session !== 'logged-out')\n            ? { [authHeader || authorizationHeader]: `${(session === 'guest') ? 'AnonBearer' : 'Bearer'} ${token}` }\n            : { };\n\n        // After this line, `requestHeaders` and `headers` should not be modified to avoid side-effects for the caller.\n        // deepClone removes headers with undefined values -- this makes it easier to assemble Headers where some\n        // headers could be optional.\n        const requestHeaders = noOtherHeaders ? deepClone(headers) : {\n            ...deepClone(headers),\n            ...auth,\n            ... (noApiKeyHeader) ? {} : { 'X-Api-Key': this._config.CLIENT_ID }\n        };\n\n        // Include a timeout on the request (fetch doesn't have a timeout, so it will never resolve if the socket hangs up)\n        const abortController = new AbortController();\n        let uncombineSignals = () => {};\n        if (requestInit.signal) {\n            uncombineSignals = combineSignals(requestInit, requestInit.signal, abortController.signal);\n        } else {\n            requestInit.signal = abortController.signal;\n        }\n        const timeoutLength = requestTimeoutMs || this.getValue('FETCH_REQUEST_TIMEOUT');\n        const timeout = setTimeout(() => abortController.abort(), timeoutLength);\n\n        const startTime = Date.now();\n\n        try {\n            const response = await fetch(url, { ...requestInit, headers: requestHeaders });\n            const requestId = response.headers.get('X-Request-Id');\n            const requestIdString = requestId || `no requestId`;\n            this.debug(`[${requestIdString}] ${options.method || 'GET'} ${url} ${response.status} (${Date.now() - startTime}ms)`);\n\n            clearTimeout(timeout);\n\n            if (response.status === 401) {\n                // If we get a 401 response it usually means that access token has expired.\n                if (token !== this._config.ACCESS_TOKEN) {\n                    // If the access token was already refreshed during the request, just retry and\n                    // it will pick up the new token.\n                    // NOTE: We are not using await here to avoid capturing the errors in the parent try block.\n                    // NOTE: using `options` instead of `requestInit` so the retry will use the same settings as the original request.\n                    return this.fetch(url, options, numRetries + 1);\n                } else {\n                    // Otherwise it means we discovered the current token is invalid. We need to invalidate the token and retry. The retry\n                    // will detect that the token is invalid and refresh it (if the host has provided a hook).\n                    this._isTokenInvalid = true;\n                    if (numRetries < this._maxNumberOfRetries) {\n                        // NOTE: We are not using await here to avoid capturing the errors in the parent try block.\n                        // NOTE: using `options` instead of `requestInit` so the retry will use the same settings as the original request.\n                        return this.fetch(url, options, numRetries + 1);\n                    }\n                }\n            }\n\n            return response;\n        } catch (e) {\n            this.debug(`Error - ${e} (${Date.now() - startTime}ms)`);\n            throw SAMError.wrapErrorIfNeeded(SAMErrorCode.NETWORK_ERROR, `Failed network request when fetching: ${url}`, e);\n        } finally {\n            // If we combined signals, we need to uncombine after the request is done, otherwise we'll continue to add\n            // event listeners to the original signal and hit the maximum limit. This would both be a memory leak and\n            // result in some aborts not being handled.\n            uncombineSignals();\n        }\n    }\n\n    // Returns a retry time based on the retry attempt number.\n    // For now, this uses the minimum retry interval a few times, before jumping to the maximum interval.\n    // We may want to change this to an exponential or Fibonacci backoff in future.\n    getRetryInterval(attempt: number): number {\n        // We retry quickly a few times on failure, before backing off to a slower interval:\n        return this.getValue(attempt < 3 ? 'MIN_RETRY_INTERVAL' : 'MAX_RETRY_INTERVAL');\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nexport type IsEqualFn = (a: any, b: any) => boolean;\n\nexport function isStrictEqual(a: any, b: any) {\n    return a === b;\n}\n\nexport function deepClone(value: any) {\n    return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Compares two items, including all their iterable properties, and all their nested properties.\n *\n * @note isDeepEqual(a, b) is O(n)\n * @note isDeepEqual(a, b, true) is O(n log n)\n * @note isDeepEqual(a, b, false, true) is O(n^2) -- use sparingly!\n * @note isDeepEqual(a, b, true, true) is O(n^3) -- use sparingly!\n *\n * @param {any} a is compared to b\n * @param {any} b is compared to a\n * @param {boolean} ignoreArrayOrder (optional) when true, order of arrays does not matter.\n * @param {boolean} partialMatch (optional) when true, all properties of `a` must match `b`, but `b`\n *      can contain additional properties not in `a`.\n * @return {boolean} true if they match\n */\nexport function isDeepEqual(a: any, b: any, ignoreArrayOrder: boolean = false, partialMatch: boolean = false): boolean {\n    if (a === b) {\n        return true;\n    }\n\n    if (typeof a !== typeof b || a.constructor !== b.constructor) {\n        return false;\n    }\n\n    if (a instanceof Date) {\n        return a.toISOString() === b.toISOString();\n    }\n\n    if (Array.isArray(a)) {\n        if (!partialMatch && a.length !== b.length) {\n            return false;\n        }\n        if (partialMatch && a.length > b.length) {\n            return false;\n        }\n\n        let arry1: any[] = a;\n        let arry2: any[] = b;\n        if (ignoreArrayOrder) {\n            // copy array to avoid mutating the original arrays\n            // .slice(0) is fastest, even faster than .slice()\n            // Note: this only works on sortable values (not Maps, Sets, Objects, or Arrays)\n            arry1 = a.slice(0).sort();\n            arry2 = b.slice(0).sort();\n        }\n\n        let i: number = 0;\n        let j: number = 0;\n        for (;;) {\n            // we've matched everything in a\n            if (i === arry1.length) { return true; }\n\n            // we've run out of b before matching everything in a\n            if (j === arry2.length) {\n                return false;\n            }\n\n            if (isDeepEqual(arry1[i], arry2[j], ignoreArrayOrder, partialMatch)) {\n                // advance our index in a and b after a match\n                i = i + 1;\n                j = j + 1;\n\n                continue;\n            }\n\n            if (partialMatch) {\n                // advance our index in b, and try again\n                j = j + 1;\n\n                continue;\n            }\n\n            // when not partialMatch, the first mismatch is a failure to match.\n            return false;\n        }\n    }\n\n    if (a instanceof Set) {\n        if (!partialMatch && a.size !== b.size) {\n            return false;\n        }\n        if (partialMatch && a.size > b.size) {\n            return false;\n        }\n        // Note: only works for strings/numbers/booleans, not objects\n        for (const key of a.keys()) {\n            if (!b.has(key)) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    if (a instanceof Map) {\n        if (!partialMatch && a.size !== b.size) {\n            return false;\n        }\n        if (partialMatch && a.size > b.size) {\n            return false;\n        }\n        for (const key of a.keys()) {\n            if (!b.has(key)) {\n                return false;\n            }\n            if (!isDeepEqual(a.get(key), b.get(key), ignoreArrayOrder, partialMatch)) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    if (typeof a === 'object') {\n        const keysA = new Set(Object.keys(a));\n        const keysB = new Set(Object.keys(b));\n        if (!partialMatch && keysA.size !== keysB.size) {\n            return false;\n        }\n        if (partialMatch && keysA.size > keysB.size) {\n            return false;\n        }\n        for (const key of keysA) {\n            if (!keysB.has(key)) {\n                return false;\n            }\n            if (!isDeepEqual(a[key], b[key], ignoreArrayOrder, partialMatch)) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    // We don't support other types.\n    return false;\n}\n\nexport const secondsPerHour = 60 * 60;\n\nexport const millisecondsPerHour = secondsPerHour * 1000;\n\nexport function firstInSet<T>(s?: Set<T>): T | undefined {\n    if (s?.size) {\n        return s.entries().next().value[0];\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { arrayBufferToUtf8, utf8ToArrayBuffer } from '../utils/encoding';\n\n\nexport interface CachedResponseData {\n    url: string;\n    status: number;\n    statusText: string;\n    headers: Record<string, string>;\n    body: string;\n}\n\n/**\n * A CacheableResponse is a Response that can be serialized and deserialized.\n * It is useful for caching responses in a persistent cache, and for passing\n * responses around, where we may want to read the response body more than once.\n */\nexport default class CacheableResponse implements Response {\n\n    private _body: ArrayBuffer;\n\n    constructor(\n        readonly url: string,\n        readonly headers: Headers,\n        readonly status: number,\n        readonly statusText: string,\n        body: ArrayBuffer | string\n    ) {\n        this._body = typeof body === 'string' ? utf8ToArrayBuffer(body) : body;\n    }\n\n    static async fromResponse(response: Response): Promise<CacheableResponse> {\n        if (response instanceof CacheableResponse) {\n            return response;\n        }\n        let body: ArrayBuffer;\n        // We must take care to not read `arrayBuffer()` if body is null, because UXP throws an error in that case.\n        if (response.body) {\n            body = await response.arrayBuffer();\n        } else {\n            body = new ArrayBuffer(0);\n        }\n        return new CacheableResponse(response.url, response.headers, response.status, response.statusText, body);\n    }\n\n    static async deserialize(json: CachedResponseData): Promise<CacheableResponse> {\n        return new CacheableResponse(json.url, new Headers(json.headers), json.status, json.statusText, base64ToBytes(json.body).buffer);\n    }\n\n    /**\n     * Serialize the CachedResponse to a JSON object that can be stored in a PersistentCache.\n     * The body is currently stored as a base64-encoded string, which is not the most efficient,\n     * but it allows us to use the Cache API as-is. A future enhancement could store these bodies\n     * in a separate binary IndexedDB store, for instance.\n     */\n    serialize(): CachedResponseData {\n        return {\n            url: this.url,\n            status: this.status,\n            statusText: this.statusText,\n            headers: headersToObject(this.headers),\n            body: bytesToBase64(new Uint8Array(this._body))\n        };\n    }\n\n    async matches(other: Response | undefined): Promise<boolean> {\n        if (!other) {\n            return false;\n        } else if (this.headers.has('etag') && other.headers.has('etag')) {\n            return this.headers.get('etag') === other.headers.get('etag');\n        } else {\n            const [ buffer1, buffer2 ] = await Promise.all([ this.arrayBuffer(), other.arrayBuffer() ]);\n            const array1 = new Uint8Array(buffer1);\n            const array2 = new Uint8Array(buffer2);\n            return array1.byteLength === array2.byteLength && array1.every((value, index) => value === array2[index]);\n        }\n    }\n\n    get ok(): boolean {\n        const { status } = this;\n        return status >= 200 && status <= 299;\n    }\n\n    get redirected(): boolean {\n        return false;\n    }\n\n    get type(): ResponseType {\n        return 'basic';\n    }\n\n    async json(): Promise<any> {\n        try {\n            return JSON.parse(await this.text());\n        } catch (err: any) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR,\n                `Failed to parse JSON response from '${this.url}' async request.`,\n                { underlyingError: err }\n            );\n        }\n    }\n\n    async bytes(): Promise<Uint8Array> {\n        return new Uint8Array(this._body);\n    }\n\n    async text(): Promise<string> {\n        return arrayBufferToUtf8(this._body);\n    }\n\n    clone(): CacheableResponse {\n        const clonedHeaders = new Headers();\n        this.headers.forEach((value, key) => clonedHeaders.set(key, value));\n        return new CacheableResponse(this.url,\n            clonedHeaders,\n            this.status,\n            this.statusText,\n            this._body);\n    }\n\n    get bodyUsed(): boolean {\n        return false; // The body can always be read from a CacheableResponse.\n    }\n\n    get body(): ReadableStream<Uint8Array> | null {\n        throw SAMError.create(SAMErrorCode.UNSUPPORTED, 'AsyncResponse.body not implemented.');\n    }\n\n    async arrayBuffer(): Promise<ArrayBuffer> {\n        return this._body;\n    }\n\n    async blob(): Promise<Blob> {\n        return new Blob([ this._body ], { type: this.headers.get('content-type') ?? undefined });\n    }\n\n    async formData(): Promise<FormData> {\n        throw SAMError.create(SAMErrorCode.UNSUPPORTED, 'AsyncResponse.formData not implemented.');\n    }\n\n}\n\n// TS is configured with ES2015, which doesn't define Header's iterators,\n// so this function does the job:\nfunction headersToObject(headers: Headers): Record<string, string> {\n    const responseHeaders: Record<string, string> = {};\n    headers.forEach((value, key) => {\n        responseHeaders[key] = value;\n    });\n    return responseHeaders;\n}\n\n// Sample implementation from https://developer.mozilla.org/en-US/docs/Glossary/Base64\nfunction base64ToBytes(base64: string) {\n    const binString = atob(base64);\n    return Uint8Array.from(binString, (m) => m.codePointAt(0) ?? 0);\n}\n\nfunction bytesToBase64(bytes: Uint8Array) {\n    const binString = Array.from(bytes, (byte) =>\n        String.fromCodePoint(byte),\n    ).join('');\n    return btoa(binString);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Converts a UTF-8 string to an ArrayBuffer.\n * This function uses TextEncoder if available, otherwise it falls back\n * to a custom implementation to support UXP environments.\n *\n * Request for UXP TextEncoder support: https://jira.corp.adobe.com/browse/UXP-23190\n */\nexport function utf8ToArrayBuffer(str: string): ArrayBuffer {\n    if (typeof TextEncoder !== 'undefined') {\n        return new TextEncoder().encode(str).buffer as ArrayBuffer;\n    } else {\n        return utf8ToArrayBufferWithoutTextEncoder(str);\n    }\n}\n\n/**\n * Converts an ArrayBuffer to a UTF-8 string.\n * This function uses TextDecoder if available, otherwise it falls back\n * to a custom implementation to support UXP environments. For that reason, this version is async.\n */\nexport async function arrayBufferToUtf8(buffer: ArrayBuffer): Promise<string> {\n    if (typeof TextDecoder !== 'undefined') {\n        return new TextDecoder().decode(buffer);\n    } else {\n        return arrayBufferToStringWithoutTextDecoder(buffer);\n    }\n}\n\n/**\n * Converts a UTF-8 string to an ArrayBuffer without using TextEncoder,\n * which UXP doesn't support.\n */\nexport function utf8ToArrayBufferWithoutTextEncoder(str: string) {\n    // Implementation of UTF-8 encoding as described in this algorithm:\n    // https://encoding.spec.whatwg.org/#utf-8-encoder\n    // See public domain example: https://gist.github.com/Yaffle/5458286\n    const octets = [];\n    const length = str.length;\n    let i = 0;\n    while (i < length) {\n        const codePoint = str.codePointAt(i)!;\n        let c = 0;\n        let bits = 0;\n        if (codePoint <= 0x0000007f) {\n            c = 0;\n            bits = 0x00;\n        } else if (codePoint <= 0x000007ff) {\n            c = 6;\n            bits = 0xc0;\n        } else if (codePoint <= 0x0000ffff) {\n            c = 12;\n            bits = 0xe0;\n        } else if (codePoint <= 0x001fffff) {\n            c = 18;\n            bits = 0xf0;\n        }\n        octets.push(bits | (codePoint >> c));\n        c -= 6;\n        while (c >= 0) {\n            octets.push(0x80 | ((codePoint >> c) & 0x3f));\n            c -= 6;\n        }\n        i += codePoint >= 0x10000 ? 2 : 1;\n    }\n    return new Uint8Array(octets).buffer;\n}\n\n/**\n * Converts an ArrayBuffer to a UTF-8 string without using TextDecoder,\n * which UXP doesn't support. See public domain example:\n * https://gist.github.com/Yaffle/5458286#file-textencodertextdecoder-js-L55-L90\n */\nexport function arrayBufferToStringWithoutTextDecoder(buffer: ArrayBuffer): string {\n    const octets = new Uint8Array(buffer);\n    let string = '';\n    let i = 0;\n    while (i < octets.length) {\n        let octet = octets[i];\n        let bytesNeeded = 0;\n        let codePoint = 0;\n        if (octet <= 0x7F) {\n            bytesNeeded = 0;\n            codePoint = octet & 0xFF;\n        } else if (octet <= 0xDF) {\n            bytesNeeded = 1;\n            codePoint = octet & 0x1F;\n        } else if (octet <= 0xEF) {\n            bytesNeeded = 2;\n            codePoint = octet & 0x0F;\n        } else if (octet <= 0xF4) {\n            bytesNeeded = 3;\n            codePoint = octet & 0x07;\n        }\n        if (octets.length - i - bytesNeeded > 0) {\n            let k = 0;\n            while (k < bytesNeeded) {\n                octet = octets[i + k + 1];\n                codePoint = (codePoint << 6) | (octet & 0x3F);\n                k += 1;\n            }\n        } else {\n            codePoint = 0xFFFD;\n            bytesNeeded = octets.length - i;\n        }\n        string += String.fromCodePoint(codePoint);\n        i += bytesNeeded + 1;\n    }\n    return string;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { NotFound } from '../core/Cache';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport type { CachedResponseData } from './CacheableResponse';\nimport CacheableResponse from './CacheableResponse';\n\nexport default class ResponseCache implements ISAMObject {\n\n    constructor(public _core: ISAMCorePrivate) {\n    }\n\n    getCacheKey(key: string) {\n        return `InterfaceBase-cache-${key}`;\n    }\n\n    async getCachedResponse(key: string): Promise<CacheableResponse | undefined> {\n        const cachedResponseData = await this._core._environment.cache.getItem(this.getCacheKey(key));\n        if (cachedResponseData === NotFound) {\n            return undefined;\n        }\n        return CacheableResponse.deserialize(cachedResponseData as CachedResponseData);\n    }\n\n    async saveResponseToCache(key: string, response: CacheableResponse) {\n        // If the value changed, save the new value to the cache and notify the caller.\n        await this._core._environment.cache.setItem(this.getCacheKey(key), response.serialize());\n    }\n\n    async deleteCachedResponse(key: string) {\n        await this._core._environment.cache.deleteItem(this.getCacheKey(key));\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport EventEmitter from 'events';\nimport type IEvent from './IEvent';\nimport type { IEventMap, GetEventNames } from './ITypedEventEmitter';\n\nexport * from './ITypedEventEmitter';\n\nexport const BECOME_OBSERVED = 'observed';\nexport const BECOME_UNOBSERVED = 'unobserved';\n\n/**\n * Base class that can be used to create Typed SAMEvent Emitters.\n * @example:\n * class ClickEvent extends SAMEvent {\n *     myClickProp: string;\n *     constructor() {\n *         super('click');\n *     }\n * }\n *\n * class MyClass extends TypedEventEmitter<{ click: ClickEvent }>() {\n *     baseProp : string;\n * }\n *\n * const obj = new MyClass();\n * obj.on('click', (ev, sender, payload) => {\n *     // The ev object is typed based on the 'click' event.\n *     ev.myClickProp;\n * });\n *\n * subClass.dispatch(new ClickEvent());\n */\nexport default class TypedEventEmitter<EventMap extends IEventMap> extends EventEmitter {\n    dispatch(ev: IEvent, payload?: any): boolean {\n        return super.emit(ev.type, ev, this, payload);\n    }\n    once<AnEventType extends GetEventNames<EventMap>>(\n        type: AnEventType,\n        callback: (event: EventMap[AnEventType], sender: this, payload?: any) => void\n    ): this {\n        const result = super.once(type, callback);\n        this._onEventListenerAdded();\n        return result;\n    }\n    on<AnEventType extends GetEventNames<EventMap>>(\n        type: AnEventType,\n        callback: (event: EventMap[AnEventType], sender: this, payload?: any) => void\n    ): this {\n        // Prevent adding duplicate listeners\n        if (this.listeners(type).includes(callback)) {\n            return this;\n        }\n        const result = super.on(type, callback);\n        if (type !== BECOME_OBSERVED && type !== BECOME_UNOBSERVED) {\n            this._onEventListenerAdded();\n            if (this.listenerCount(type) === 1) {\n                this.emit(BECOME_OBSERVED, type);\n            }\n        }\n        return result;\n    }\n    off<AnEventType extends GetEventNames<EventMap>>(\n        type: AnEventType,\n        callback: (event: EventMap[AnEventType], sender: this, payload?: any) => void\n    ): this {\n        const result = super.off(type, callback);\n        if (type !== BECOME_OBSERVED && type !== BECOME_UNOBSERVED) {\n            this._onEventListenerRemoved();\n            if (this.listenerCount(type) === 0) {\n                this.emit(BECOME_UNOBSERVED, type);\n            }\n        }\n        return result;\n    }\n    // Called when a new event listener is added on the object.\n    protected _onEventListenerAdded() {\n    }\n\n    protected _onEventListenerRemoved() {\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport EventEmitter from 'events';\nimport type { ISAMCorePrivate } from '../indexPrivate';\n\ntype Extension = {[key: string]: PropertyDescriptor | Function}\n\n// NOTE: since previous versions of SAM.js used override_map, this cannot be changed to override_set,\n//       or it would defeat the purpose of tracking overrides applied by different versions of SAM.js.\nconst $OVERRIDE_SET = Symbol.for('com.adobe.ccac.samjs.extendclass.override_map');\nconst $EXTENSION_SET = Symbol.for('com.adobe.ccac.samjs.extendclass.extension_set');\nconst $OBSERVABLE_SET = Symbol.for('com.adobe.ccac.samjs.extendclass.observable_set');\nconst $EMITTER = Symbol.for('com.adobe.ccac.samjs.extendclass.emitter');\nexport const $OVERRIDDEN_GETTERS = Symbol.for('com.adobe.ccac.samjs.extendclass.overridden_getters');\n\ninterface IExtendClassOptions<T> {\n    /**\n     * The target class to be extended\n     */\n    klass: T;\n    /**\n     * The instance of SAMCore\n     */\n    core: ISAMCorePrivate;\n    /**\n     * Properties that will extend the target class if they are not defined\n     */\n    extensions?: Extension;\n    /**\n     * Properties that will override the target class, whether or not they are defined.\n     */\n    overrides?: Extension;\n    /**\n     * Some SAM.js classes emit a single event for a topic while SAM.cpp emits multiple. Sometimes only the event names\n     * differ. This map will allow the client code to subscribe to the SAM.js event (key) and the extended class will\n     * subscribe to all of the SAM.cpp events (values). It will add EventEmitter APIs to classes that do not have them.\n     */\n    eventMap?: { [key: string]: string[] };\n    /**\n     * If provided, it will make all of the getter properties of the target class observable, bound to this event.\n     * It will not make observable any property defined in `extensions` nor `overrides` nor `observableMap`.\n     */\n    defaultObservableEvent?: string;\n    /**\n     * If provided, it will make just the getter properties specified in the values observable. It will not add\n     * observability to properties defined in `extensions` nor `overrides`. The keys represent the event that\n     * the observable properties will be bound to.\n     */\n    observableMap?: { [event: string]: string[]; };\n}\n\n\n/**\n * Extends the provided `klass` with the properties with new behaviors, and ensures it supports the\n * EventEmitter interface. Optionally, it will make all getter properties observable.\n *\n * @param options: IExtendClassOptions\n * @example\n *     class MyClass {\n *         private _foo = 32;\n *         private _bar = 99;\n *         private _baz = {};\n *         refreshBaz(x) { some impl }\n *         get foo() { return this._foo; }\n *         get bar() { return this._bar; }\n *         get baz() { return this.baz; }\n *     }\n *     ExtendClass({\n *         klass: MyClass,\n *         extensions: {\n *             refreshBaz(x) { return x * 2; },       // ignored because it exists on MyClass\n *             newFn() { return this._foo; }          // Added\n *             // Getters/setters must use PropertyDescriptor syntax\n *             // NOTE: won't be automatically made observable\n *             aliasForFoo: {\n *                 get() {\n *                     // make this getter alias observable\n *                     this._core._environment.mobx.reportObserved('change');\n *                     return this._foo;\n *                 }\n *             }\n *         },\n *         overrides: {\n *             // replaces original refreshBaz\n *             refreshBaz(x) {\n *                 // Use the added TypedEventEmitter.dispatch()\n *                 this.dispatch({ type: 'bazRefresh' });\n *                 // invoke original oldFn\n *                 return this.oldFn.original(x);\n *             }\n *         },\n *         // When client subscribes to 'change' event, the extended class will proxy that event handler to the\n *         // 'incrementFoo' and 'incrementBar' events that the native implementation emits.\n *         eventMap: { change: [ 'incrementFoo', 'incrementBar' ] },\n *         observableMap: {\n *             // the `baz` getter will be made observable, bound to the 'bazRefresh' event\n *             'bazRefresh': [ 'baz' ]\n *         }\n *         // `foo` and `bar` getter will be made observable, bound to the 'change' event;\n *         defaultObservableEvent: 'change',\n *     });\n */\nexport default function ExtendClass<T extends { prototype: { [key: string]: any } }>(\n    {\n        klass,\n        core,\n        extensions = {},\n        overrides = {},\n        eventMap = {},\n        defaultObservableEvent,\n        observableMap = {}\n    }: IExtendClassOptions<T>\n) {\n    const originalProps = Object.getOwnPropertyDescriptors(klass.prototype);\n    // SAM.cpp EventEmitter-ish interface is on the prototype's prototype\n    let emitterProps = originalProps;\n    if (typeof emitterProps.on === 'undefined') {\n        emitterProps = Object.getOwnPropertyDescriptors(Object.getPrototypeOf(klass.prototype));\n    }\n\n    // Add reference to shared core if not already defined\n    if (!originalProps._core) {\n        Object.defineProperty(klass.prototype, '_core', { value: core });\n    }\n\n    // When overriding a getter, patch code may need access to the original using\n    //    this[$OVERRIDDEN_GETTERS]['someProp'].call(this)\n    if (!Object.getOwnPropertyDescriptor(klass.prototype, $OVERRIDDEN_GETTERS)) {\n        Object.defineProperty(klass.prototype, $OVERRIDDEN_GETTERS, { value: {} });\n    }\n\n\n    // Some SAM.cpp classes (AssetList) have an event handling API similar to EventEmitter, and some don't\n    // (Asset). Meanwhile, most SAM.js classes implement TypedEventEmitter. This section patches the\n    // prototype to match the TypedEventEmitter API. If the SAM.cpp class doesn't have an event-handling\n    // API, an actual instance of EventEmitter is used instead.\n    if (!Object.getOwnPropertyDescriptor(klass.prototype, $EMITTER)) {\n        Object.defineProperties(klass.prototype, {\n            [$EMITTER]: {\n                get() {\n                    // Redefine the $EMITTER getter property for `this` instance to an actual EventEmitter, or an\n                    // adapter to the SAM.cpp equivalent. The $EMITTER getter on the prototype remains unchanged\n                    // so the next instance will get its own properly bound $EMITTER.\n                    let emitter: EventEmitter;\n                    if (typeof emitterProps.on?.value === 'function') {\n                        // SAM.cpp class has an event handling API already, so create an adapter bound\n                        // to the SAM.cpp implementation\n                        emitter = {\n                            on: emitterProps.on.value.bind(this),\n                            off: emitterProps.off.value.bind(this),\n                            emit: emitterProps.trigger.value.bind(this),\n                            addListener: emitterProps.on.value.bind(this),\n                            removeListener: emitterProps.off.value.bind(this)\n                        } as EventEmitter;\n                    } else {\n                        // SAM.cpp class has no event handling API, so use an actual EventEmitter\n                        emitter = new EventEmitter();\n                    }\n                    Object.defineProperty(this, $EMITTER, { value: emitter });\n                    return this[$EMITTER];\n                }\n            },\n            on: {\n                value(eventName: string, ...rest: any[]) {\n                    // Some SAM.cpp events map to multiple SAM.js events. If there's no mapping, then subscribe\n                    // to `eventName` only.\n                    const mappedEvents = eventMap[eventName] ?? [ eventName ];\n                    mappedEvents.forEach(mappedEventName => this[$EMITTER].on(mappedEventName, ...rest));\n                    return this;\n                }\n            },\n            addListener: {\n                value(...args: any[]) { return this.on(...args); }\n            },\n            off: {\n                value(eventName: string, ...rest: any[]) {\n                    // Some SAM.cpp events map to multiple SAM.js events. If there's no mapping, then unsubscribe\n                    // from `eventName` only.\n                    const mappedEvents = eventMap[eventName] ?? [ eventName ];\n                    mappedEvents.forEach(mappedEventName => this[$EMITTER].off(mappedEventName, ...rest));\n                    return this;\n                }\n            },\n            removeListener: {\n                value(...args: any[]) { return this.off(...args); }\n            },\n            emit: {\n                value(...args: any[]) {\n                    return this[$EMITTER].emit(...args);\n                }\n            },\n            // SAM.js TypedEventEmitter behavior\n            dispatch: {\n                value(event: Event) { return this.emit(event.type, event, this); }\n            }\n        });\n\n    }\n\n    // Allow shortcut of { someMethod(): {} } instead of { someMethod: { value: function() {} } }\n    function makePropertyDesc(\n        map: { [key: string]: Function | PropertyDescriptor },\n        key: string\n    ): PropertyDescriptor {\n        const propertyDesc = map[key];\n        if (typeof map[key] === 'function') {\n            return { value: propertyDesc };\n        } else if ([ 'string', 'boolean', 'number' ].includes(typeof map[key])) {\n            // TypeScript doesn't block clients from passing a primitive, and\n            // Object.defineProperty(obj, key, primitive) is a no-op.\n            throw new Error('Cannot use primitives for PropertyDescriptor');\n        } else {\n            // An object. TypeScript will verify that it is a valid PropertyDescriptor.\n            return propertyDesc as PropertyDescriptor;\n        }\n    }\n\n    // Track which properties have been handled in this call to ExtendClass\n    const handledProps: Set<string> = new Set();\n\n    // Extensions should handle their own observability, thus should not be made observable automatically,\n    // so extensions must be tracked across calls to ExtendClass.\n    const extendedProps: Set<string> = klass.prototype[$EXTENSION_SET as any] || new Set();\n\n    Object.keys(extensions).forEach(propertyName => {\n        // cannot override existing properties with extensions\n        if (originalProps[propertyName]) { return; }\n\n        const propertyDesc = makePropertyDesc(extensions, propertyName);\n        Object.defineProperty(klass.prototype, propertyName, propertyDesc);\n        handledProps.add(propertyName);\n        extendedProps.add(propertyName);\n    });\n    klass.prototype[$EXTENSION_SET as any] = extendedProps;\n\n    const overriddenProps = klass.prototype[$OVERRIDE_SET as any] || new Set();\n    Object.keys(overrides).forEach(propertyName => {\n        if (overriddenProps.has(propertyName)) {\n            // Overrides from a previous call to ExtendClass should not be overridden again, but this\n            // is not an error.\n            return;\n        }\n        if (handledProps.has(propertyName) || extendedProps.has(propertyName)) {\n            throw new Error(`[ExtendClass] cannot override property '${propertyName}' because it is an extension.`);\n        }\n        // Since overridden functions might expect to use `this.originalFn.original()`, it's not safe to treat the\n        // override as an extension. Different hosts could have different versions of SAM.cpp, so patching code should\n        // be aware of what is needed.\n        if (!originalProps[propertyName]) {\n            throw new Error(`[ExtendClass] target class does not have property '${propertyName}' so it cannot `\n                + 'be overridden.');\n        }\n        const propertyDesc = makePropertyDesc(overrides, propertyName);\n        const original = originalProps[propertyName].value;\n        if (typeof original === 'function') {\n            // Replace the the original method with the override, then attach the original\n            // to the override so you can call it with `this.override.original()`\n            Object.defineProperty(klass.prototype, propertyName, {\n                get() {\n                    // Ensure `original` is bound to correct `this`\n                    propertyDesc.value.original = original.bind(this);\n                    return propertyDesc.value;\n                }\n            });\n        } else {\n            if (originalProps[propertyName].get) {\n                klass.prototype[$OVERRIDDEN_GETTERS as any][propertyName] = originalProps[propertyName].get;\n            }\n            Object.defineProperty(klass.prototype, propertyName, propertyDesc);\n        }\n        overriddenProps.add(propertyName);\n        handledProps.add(propertyName);\n    });\n    klass.prototype[$OVERRIDE_SET as any] = overriddenProps;\n\n    // Validate the passed-in observableMap config does not contain coding errors. If a config defines\n    // two events for the same property, or defines an event for an extension/override, that is likely\n    // a bug.\n    const propToEventMap: { [key: string]: string } = {};\n    Object.keys(observableMap).reduce((seenPropNames, eventName) => {\n        observableMap[eventName].forEach(propName => {\n            // If a property is mapped multiple times, or was extended/overwritten, treat as a coding error,\n            // otherwise the result would be difficult to debug\n            if (seenPropNames.has(propName)) {\n                throw new Error(`[ExtendClass] cannot have the same property (${propName}) appear multiple times in observableMap`);\n            }\n            if (handledProps.has(propName)) {\n                throw new Error(`[ExtendClass] cannot make property (${propName}) observable as it was defined in extensions/overrides`);\n            }\n            seenPropNames.add(propName);\n            propToEventMap[propName] = eventName;\n        });\n        return seenPropNames;\n    }, new Set());\n\n    // Add properties to be observed using the defaultObservableEvent to propToEventMap\n    if (defaultObservableEvent) {\n        Object.keys(originalProps)\n            // only collect getter properties\n            .filter(propName => !!originalProps[propName].get)\n            .forEach(propName => propToEventMap[propName] = defaultObservableEvent);\n    }\n\n    // Get already-wrapped properties that were made observable by previous calls to ExtendClass, if any,\n    // so that they won't be wrapped again.\n    const observedProps: Set<string> = klass.prototype[$OBSERVABLE_SET as any] || new Set<string>();\n\n    // merge all extended/overridden/observed props (including from previous calls to ExtendClass) into handledProps\n    [ ...extendedProps, ...overriddenProps, ...observedProps ].forEach(propName => handledProps.add(propName));\n\n    Object.entries(propToEventMap).forEach(([ propName, eventName ]) => {\n        // Only wrap getters, and properties that have not already been patched, either from this\n        // call to ExtendClass, or a previous call. If it is from a previous call, then this is not\n        // error.\n        if (!originalProps[propName]?.get || handledProps.has(propName)) {\n            return;\n        }\n\n        Object.defineProperty(klass.prototype, propName, {\n            get() {\n                this._core._environment.mobx.reportObserved(this, eventName);\n                return originalProps[propName].get!.call(this);\n            }\n        });\n        observedProps.add(propName);\n    });\n    klass.prototype[$OBSERVABLE_SET as any] = observedProps;\n}\n","// 'path' module extracted from Node.js v8.11.1 (only the posix part)\n// transplited with Babel\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nfunction assertPath(path) {\n  if (typeof path !== 'string') {\n    throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));\n  }\n}\n\n// Resolves . and .. elements in a path with directory names\nfunction normalizeStringPosix(path, allowAboveRoot) {\n  var res = '';\n  var lastSegmentLength = 0;\n  var lastSlash = -1;\n  var dots = 0;\n  var code;\n  for (var i = 0; i <= path.length; ++i) {\n    if (i < path.length)\n      code = path.charCodeAt(i);\n    else if (code === 47 /*/*/)\n      break;\n    else\n      code = 47 /*/*/;\n    if (code === 47 /*/*/) {\n      if (lastSlash === i - 1 || dots === 1) {\n        // NOOP\n      } else if (lastSlash !== i - 1 && dots === 2) {\n        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {\n          if (res.length > 2) {\n            var lastSlashIndex = res.lastIndexOf('/');\n            if (lastSlashIndex !== res.length - 1) {\n              if (lastSlashIndex === -1) {\n                res = '';\n                lastSegmentLength = 0;\n              } else {\n                res = res.slice(0, lastSlashIndex);\n                lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n              }\n              lastSlash = i;\n              dots = 0;\n              continue;\n            }\n          } else if (res.length === 2 || res.length === 1) {\n            res = '';\n            lastSegmentLength = 0;\n            lastSlash = i;\n            dots = 0;\n            continue;\n          }\n        }\n        if (allowAboveRoot) {\n          if (res.length > 0)\n            res += '/..';\n          else\n            res = '..';\n          lastSegmentLength = 2;\n        }\n      } else {\n        if (res.length > 0)\n          res += '/' + path.slice(lastSlash + 1, i);\n        else\n          res = path.slice(lastSlash + 1, i);\n        lastSegmentLength = i - lastSlash - 1;\n      }\n      lastSlash = i;\n      dots = 0;\n    } else if (code === 46 /*.*/ && dots !== -1) {\n      ++dots;\n    } else {\n      dots = -1;\n    }\n  }\n  return res;\n}\n\nfunction _format(sep, pathObject) {\n  var dir = pathObject.dir || pathObject.root;\n  var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');\n  if (!dir) {\n    return base;\n  }\n  if (dir === pathObject.root) {\n    return dir + base;\n  }\n  return dir + sep + base;\n}\n\nvar posix = {\n  // path.resolve([from ...], to)\n  resolve: function resolve() {\n    var resolvedPath = '';\n    var resolvedAbsolute = false;\n    var cwd;\n\n    for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n      var path;\n      if (i >= 0)\n        path = arguments[i];\n      else {\n        if (cwd === undefined)\n          cwd = process.cwd();\n        path = cwd;\n      }\n\n      assertPath(path);\n\n      // Skip empty entries\n      if (path.length === 0) {\n        continue;\n      }\n\n      resolvedPath = path + '/' + resolvedPath;\n      resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;\n    }\n\n    // At this point the path should be resolved to a full absolute path, but\n    // handle relative paths to be safe (might happen when process.cwd() fails)\n\n    // Normalize the path\n    resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n\n    if (resolvedAbsolute) {\n      if (resolvedPath.length > 0)\n        return '/' + resolvedPath;\n      else\n        return '/';\n    } else if (resolvedPath.length > 0) {\n      return resolvedPath;\n    } else {\n      return '.';\n    }\n  },\n\n  normalize: function normalize(path) {\n    assertPath(path);\n\n    if (path.length === 0) return '.';\n\n    var isAbsolute = path.charCodeAt(0) === 47 /*/*/;\n    var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;\n\n    // Normalize the path\n    path = normalizeStringPosix(path, !isAbsolute);\n\n    if (path.length === 0 && !isAbsolute) path = '.';\n    if (path.length > 0 && trailingSeparator) path += '/';\n\n    if (isAbsolute) return '/' + path;\n    return path;\n  },\n\n  isAbsolute: function isAbsolute(path) {\n    assertPath(path);\n    return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;\n  },\n\n  join: function join() {\n    if (arguments.length === 0)\n      return '.';\n    var joined;\n    for (var i = 0; i < arguments.length; ++i) {\n      var arg = arguments[i];\n      assertPath(arg);\n      if (arg.length > 0) {\n        if (joined === undefined)\n          joined = arg;\n        else\n          joined += '/' + arg;\n      }\n    }\n    if (joined === undefined)\n      return '.';\n    return posix.normalize(joined);\n  },\n\n  relative: function relative(from, to) {\n    assertPath(from);\n    assertPath(to);\n\n    if (from === to) return '';\n\n    from = posix.resolve(from);\n    to = posix.resolve(to);\n\n    if (from === to) return '';\n\n    // Trim any leading backslashes\n    var fromStart = 1;\n    for (; fromStart < from.length; ++fromStart) {\n      if (from.charCodeAt(fromStart) !== 47 /*/*/)\n        break;\n    }\n    var fromEnd = from.length;\n    var fromLen = fromEnd - fromStart;\n\n    // Trim any leading backslashes\n    var toStart = 1;\n    for (; toStart < to.length; ++toStart) {\n      if (to.charCodeAt(toStart) !== 47 /*/*/)\n        break;\n    }\n    var toEnd = to.length;\n    var toLen = toEnd - toStart;\n\n    // Compare paths to find the longest common path from root\n    var length = fromLen < toLen ? fromLen : toLen;\n    var lastCommonSep = -1;\n    var i = 0;\n    for (; i <= length; ++i) {\n      if (i === length) {\n        if (toLen > length) {\n          if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n            // We get here if `from` is the exact base path for `to`.\n            // For example: from='/foo/bar'; to='/foo/bar/baz'\n            return to.slice(toStart + i + 1);\n          } else if (i === 0) {\n            // We get here if `from` is the root\n            // For example: from='/'; to='/foo'\n            return to.slice(toStart + i);\n          }\n        } else if (fromLen > length) {\n          if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n            // We get here if `to` is the exact base path for `from`.\n            // For example: from='/foo/bar/baz'; to='/foo/bar'\n            lastCommonSep = i;\n          } else if (i === 0) {\n            // We get here if `to` is the root.\n            // For example: from='/foo'; to='/'\n            lastCommonSep = 0;\n          }\n        }\n        break;\n      }\n      var fromCode = from.charCodeAt(fromStart + i);\n      var toCode = to.charCodeAt(toStart + i);\n      if (fromCode !== toCode)\n        break;\n      else if (fromCode === 47 /*/*/)\n        lastCommonSep = i;\n    }\n\n    var out = '';\n    // Generate the relative path based on the path difference between `to`\n    // and `from`\n    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n      if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n        if (out.length === 0)\n          out += '..';\n        else\n          out += '/..';\n      }\n    }\n\n    // Lastly, append the rest of the destination (`to`) path that comes after\n    // the common path parts\n    if (out.length > 0)\n      return out + to.slice(toStart + lastCommonSep);\n    else {\n      toStart += lastCommonSep;\n      if (to.charCodeAt(toStart) === 47 /*/*/)\n        ++toStart;\n      return to.slice(toStart);\n    }\n  },\n\n  _makeLong: function _makeLong(path) {\n    return path;\n  },\n\n  dirname: function dirname(path) {\n    assertPath(path);\n    if (path.length === 0) return '.';\n    var code = path.charCodeAt(0);\n    var hasRoot = code === 47 /*/*/;\n    var end = -1;\n    var matchedSlash = true;\n    for (var i = path.length - 1; i >= 1; --i) {\n      code = path.charCodeAt(i);\n      if (code === 47 /*/*/) {\n          if (!matchedSlash) {\n            end = i;\n            break;\n          }\n        } else {\n        // We saw the first non-path separator\n        matchedSlash = false;\n      }\n    }\n\n    if (end === -1) return hasRoot ? '/' : '.';\n    if (hasRoot && end === 1) return '//';\n    return path.slice(0, end);\n  },\n\n  basename: function basename(path, ext) {\n    if (ext !== undefined && typeof ext !== 'string') throw new TypeError('\"ext\" argument must be a string');\n    assertPath(path);\n\n    var start = 0;\n    var end = -1;\n    var matchedSlash = true;\n    var i;\n\n    if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n      if (ext.length === path.length && ext === path) return '';\n      var extIdx = ext.length - 1;\n      var firstNonSlashEnd = -1;\n      for (i = path.length - 1; i >= 0; --i) {\n        var code = path.charCodeAt(i);\n        if (code === 47 /*/*/) {\n            // If we reached a path separator that was not part of a set of path\n            // separators at the end of the string, stop now\n            if (!matchedSlash) {\n              start = i + 1;\n              break;\n            }\n          } else {\n          if (firstNonSlashEnd === -1) {\n            // We saw the first non-path separator, remember this index in case\n            // we need it if the extension ends up not matching\n            matchedSlash = false;\n            firstNonSlashEnd = i + 1;\n          }\n          if (extIdx >= 0) {\n            // Try to match the explicit extension\n            if (code === ext.charCodeAt(extIdx)) {\n              if (--extIdx === -1) {\n                // We matched the extension, so mark this as the end of our path\n                // component\n                end = i;\n              }\n            } else {\n              // Extension does not match, so our result is the entire path\n              // component\n              extIdx = -1;\n              end = firstNonSlashEnd;\n            }\n          }\n        }\n      }\n\n      if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;\n      return path.slice(start, end);\n    } else {\n      for (i = path.length - 1; i >= 0; --i) {\n        if (path.charCodeAt(i) === 47 /*/*/) {\n            // If we reached a path separator that was not part of a set of path\n            // separators at the end of the string, stop now\n            if (!matchedSlash) {\n              start = i + 1;\n              break;\n            }\n          } else if (end === -1) {\n          // We saw the first non-path separator, mark this as the end of our\n          // path component\n          matchedSlash = false;\n          end = i + 1;\n        }\n      }\n\n      if (end === -1) return '';\n      return path.slice(start, end);\n    }\n  },\n\n  extname: function extname(path) {\n    assertPath(path);\n    var startDot = -1;\n    var startPart = 0;\n    var end = -1;\n    var matchedSlash = true;\n    // Track the state of characters (if any) we see before our first dot and\n    // after any path separator we find\n    var preDotState = 0;\n    for (var i = path.length - 1; i >= 0; --i) {\n      var code = path.charCodeAt(i);\n      if (code === 47 /*/*/) {\n          // If we reached a path separator that was not part of a set of path\n          // separators at the end of the string, stop now\n          if (!matchedSlash) {\n            startPart = i + 1;\n            break;\n          }\n          continue;\n        }\n      if (end === -1) {\n        // We saw the first non-path separator, mark this as the end of our\n        // extension\n        matchedSlash = false;\n        end = i + 1;\n      }\n      if (code === 46 /*.*/) {\n          // If this is our first dot, mark it as the start of our extension\n          if (startDot === -1)\n            startDot = i;\n          else if (preDotState !== 1)\n            preDotState = 1;\n      } else if (startDot !== -1) {\n        // We saw a non-dot and non-path separator before our dot, so we should\n        // have a good chance at having a non-empty extension\n        preDotState = -1;\n      }\n    }\n\n    if (startDot === -1 || end === -1 ||\n        // We saw a non-dot character immediately before the dot\n        preDotState === 0 ||\n        // The (right-most) trimmed path component is exactly '..'\n        preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n      return '';\n    }\n    return path.slice(startDot, end);\n  },\n\n  format: function format(pathObject) {\n    if (pathObject === null || typeof pathObject !== 'object') {\n      throw new TypeError('The \"pathObject\" argument must be of type Object. Received type ' + typeof pathObject);\n    }\n    return _format('/', pathObject);\n  },\n\n  parse: function parse(path) {\n    assertPath(path);\n\n    var ret = { root: '', dir: '', base: '', ext: '', name: '' };\n    if (path.length === 0) return ret;\n    var code = path.charCodeAt(0);\n    var isAbsolute = code === 47 /*/*/;\n    var start;\n    if (isAbsolute) {\n      ret.root = '/';\n      start = 1;\n    } else {\n      start = 0;\n    }\n    var startDot = -1;\n    var startPart = 0;\n    var end = -1;\n    var matchedSlash = true;\n    var i = path.length - 1;\n\n    // Track the state of characters (if any) we see before our first dot and\n    // after any path separator we find\n    var preDotState = 0;\n\n    // Get non-dir info\n    for (; i >= start; --i) {\n      code = path.charCodeAt(i);\n      if (code === 47 /*/*/) {\n          // If we reached a path separator that was not part of a set of path\n          // separators at the end of the string, stop now\n          if (!matchedSlash) {\n            startPart = i + 1;\n            break;\n          }\n          continue;\n        }\n      if (end === -1) {\n        // We saw the first non-path separator, mark this as the end of our\n        // extension\n        matchedSlash = false;\n        end = i + 1;\n      }\n      if (code === 46 /*.*/) {\n          // If this is our first dot, mark it as the start of our extension\n          if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;\n        } else if (startDot !== -1) {\n        // We saw a non-dot and non-path separator before our dot, so we should\n        // have a good chance at having a non-empty extension\n        preDotState = -1;\n      }\n    }\n\n    if (startDot === -1 || end === -1 ||\n    // We saw a non-dot character immediately before the dot\n    preDotState === 0 ||\n    // The (right-most) trimmed path component is exactly '..'\n    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n      if (end !== -1) {\n        if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);\n      }\n    } else {\n      if (startPart === 0 && isAbsolute) {\n        ret.name = path.slice(1, startDot);\n        ret.base = path.slice(1, end);\n      } else {\n        ret.name = path.slice(startPart, startDot);\n        ret.base = path.slice(startPart, end);\n      }\n      ret.ext = path.slice(startDot, end);\n    }\n\n    if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';\n\n    return ret;\n  },\n\n  sep: '/',\n  delimiter: ':',\n  win32: null,\n  posix: null\n};\n\nposix.posix = posix;\n\nmodule.exports = posix;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IEventMap } from './TypedEventEmitter';\nimport TypedEventEmitter from './TypedEventEmitter';\nimport type ChangeEvent from './ChangeEvent';\nimport { SharedChangeEvent } from './ChangeEvent';\nimport { observable } from './decorators';\nimport type  { ISAMObject, ISAMCorePrivate } from '../indexPrivate';\n\nexport type ItemId = string;\n\nexport interface ItemBaseEvents extends IEventMap {\n    change: ChangeEvent;\n}\n\nexport type TaskName =\n    | 'archive'\n    | 'bookmark'\n    | 'copy'\n    | 'delete'\n    | 'move'\n    | 'rename'\n    | 'restore'\n    | 'update';\n\n/**\n * Each ItemBase can be assigned a single task at a time.\n * Different objects have different instances of this object.\n */\nexport interface ExclusiveTask {\n    readonly name: TaskName;\n    readonly items: ItemBase<ItemBaseEvents>[];\n}\n\nexport class ItemExclusiveTaskChain {\n    next?: ItemExclusiveTaskChain;\n\n    constructor(\n        readonly task: ExclusiveTask,\n        readonly onGotOwnership: () => void) {\n    }\n\n    // Add the task at the end of the linked list.\n    registerNewTask(newTask: ItemExclusiveTaskChain) {\n        let itemTask: ItemExclusiveTaskChain = this;\n        while (itemTask) {\n            const next: ItemExclusiveTaskChain | undefined = itemTask.next;\n            if (!next) {\n                // We've found the first empty slot.\n                itemTask.next = newTask;\n                return;\n            }\n            // Keep going till the end.\n            itemTask = next;\n        }\n    }\n}\n\n/**\n * Base object used for all assets, teams, spaces etc.\n */\nexport default abstract class ItemBase<Events extends ItemBaseEvents = ItemBaseEvents> extends TypedEventEmitter<Events> implements ISAMObject {\n    protected _exclusiveTaskChain?: ItemExclusiveTaskChain;\n\n    // Timestamp of the last known mutation that this client executed.\n    // The servers have to replicate this mutation between each other and sometimes the\n    // fetches do not include changes for up to a specific amount of seconds.\n    // The timestamp will be used to compare against the expected update\n    // windows of each request.\n    protected _lastKnownClientMutation?: number;\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly id: ItemId) {\n        super();\n    }\n\n    get lastKnownClientMutation(): number | undefined {\n        return this._lastKnownClientMutation;\n    }\n\n    updateLastKnownClientMutation() {\n        this._lastKnownClientMutation = Date.now();\n    }\n\n    /**\n     * Waits for at least `delay` ms since the last known asset mutation.\n     * @param delay\n     */\n    async waitForMutationPropagationIfNeeded(delay: number) {\n        const mutation = this._lastKnownClientMutation;\n        if (mutation) {\n            const waitTime = mutation + delay - Date.now();\n            if (waitTime > 0) {\n                // We still have some time left before the asset change is propagated for sure.\n                await new Promise((resolve) => setTimeout(resolve, waitTime));\n            }\n        }\n    }\n\n    @observable\n    get exclusiveTask(): ExclusiveTask | undefined {\n        return this._exclusiveTaskChain?.task;\n    }\n\n    private _setExclusiveTaskChain(itemTaskChain: ItemExclusiveTaskChain | undefined) {\n        this._exclusiveTaskChain = itemTaskChain;\n        this.dispatch(SharedChangeEvent);\n    }\n\n    /**\n     * @package -- only for use by UpdateSession\n     */\n    _setId(newId: string) {\n        // @ts-expect-error -- this is the only place where ID can be changed.\n        this.id = newId;\n    }\n\n    /**\n     * Locks exclusive ownership for a subset of items during execution of the `schedule`.\n     * It is guaranteed that the `schedule` method will receive ownership of the items\n     * before it starts execution and all the way up to the point when the returned promise\n     * gets resolved.\n     *\n     * Multiple tasks can run at the same time as long as they do not share any of their items.\n     * For example, task A working with assets (i1, i2) will be scheduled to run in parallel with\n     * task B with assets (i3, i4).\n     *\n     * If multiple tasks are registered on same items, the tasks will be executed in their\n     * order of scheduling. For example, task C working with assets (i1, i2) will not be allowed\n     * to run at the same time with task D that needs assets (i2, i3). Task D will only schedule\n     * once all the previously scheduled tasks have released ownership of i2 and i3.\n     *\n     * Recursivity is not supported, a task should not lock same items again while it holds ownership.\n     *\n     * A single item can only be part of a single exclusive task at any moment of time.\n     *\n     * @param name Name of the task to schedule. Useful for debugging.\n     * @param items The items to lock during the execution of the task.\n     * @param schedule The function to execute once the task has ownership of the items.\n     * @returns A promise resolved once the task is complete. The value of the returned promise\n     * is propagated from the promise returned by the `schedule` function.\n     */\n    static runExclusiveTask<T>(name: TaskName, items: ItemBase[], schedule: (task: ExclusiveTask) => Promise<T>): Promise<T> {\n        return new Promise<T>((resolve) => {\n            const task: ExclusiveTask = { name, items };\n\n            const runTask = () => resolve(schedule(task).finally(() => {\n                // Make sure all the items pick up their next task\n                // before we give up ownership.\n                for (const item of items) {\n                    // We know the item must have a task. We just finished it.\n                    const next = item._exclusiveTaskChain!.next;\n\n                    // Assign ownership to the next waiting task.\n                    // If tasks are still pending, then there should\n                    // never be a gap of of ownership on the item,\n                    // to avoid letting other tasks inject themselves\n                    //in the middle. The tasks needs to execute in the order\n                    // of scheduling to avoid interlacing issues.\n                    item._setExclusiveTaskChain(next);\n\n                    // Let the next task know it received the ownership now.\n                    // Once the next task acquires all the locks, then it will\n                    // continue with its own execution.\n                    // Note that the callback uses use a timer once the execution\n                    // actually starts to avoid crashing this promise chain.\n                    next?.onGotOwnership();\n                }\n            }));\n\n            // We don't want to schedule the task until all the items are ready to execute the task.\n            let waitCount = 0;\n            const onGotOwnership = () => {\n                // Wait for all other task to finish first.\n                if (--waitCount === 0) {\n                    // Using a separate stack to avoid crashing the previous task\n                    // that might have invoked the `onGotOwnership` method.\n                    setTimeout(runTask, 0);\n                }\n            };\n\n            for (const item of items) {\n                // Each item gets its own task object. We cannot share the objects as\n                // we require strict task ordering for each individual item.\n                const newTask = new ItemExclusiveTaskChain(task, onGotOwnership);\n\n                const itemTask = item._exclusiveTaskChain;\n                if (!itemTask) {\n                    // Assign the new task right away. The task will maintain\n                    // owneship until it gets scheduled.\n                    item._setExclusiveTaskChain(newTask);\n                    continue;\n                }\n\n                // Increment the number of items that we are still waiting ownership for.\n                ++waitCount;\n\n                // Register the task to be executed immediately after the last task in this item's task chain.\n                itemTask.registerNewTask(newTask);\n            }\n\n            if (waitCount === 0) {\n                // We've got owernship of all the required assets already,\n                // we can proceed with running the task.\n                runTask();\n            }\n        });\n    }\n\n}\n","'use strict'\n\nvar COMPATIBLE_ENCODING_PATTERN = /^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i\nvar WS_TRIM_PATTERN = /^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g\nvar WS_CHAR_PATTERN = /\\s|\\uFEFF|\\xA0/\nvar WS_FOLD_PATTERN = /\\r?\\n[\\x20\\x09]+/g\nvar DELIMITER_PATTERN = /[;,\"]/\nvar WS_DELIMITER_PATTERN = /[;,\"]|\\s/\n\n/**\n * Token character pattern\n * @type {RegExp}\n * @see https://tools.ietf.org/html/rfc7230#section-3.2.6\n */\nvar TOKEN_PATTERN = /^[!#$%&'*+\\-\\.^_`|~\\da-zA-Z]+$/\n\nvar STATE = {\n  IDLE: 1 << 0,\n  URI: 1 << 1,\n  ATTR: 1 << 2,\n}\n\nfunction trim( value ) {\n  return value.replace( WS_TRIM_PATTERN, '' )\n}\n\nfunction hasWhitespace( value ) {\n  return WS_CHAR_PATTERN.test( value )\n}\n\nfunction skipWhitespace( value, offset ) {\n  while( hasWhitespace( value[offset] ) ) {\n    offset++\n  }\n  return offset\n}\n\nfunction needsQuotes( value ) {\n  return WS_DELIMITER_PATTERN.test( value ) ||\n    !TOKEN_PATTERN.test( value )\n}\n\n/**\n * Shallow compares two objects to check if their properties match.\n * @param {object} object1 First object to compare.\n * @param {object} object2 Second object to compare.\n * @returns {boolean} Do the objects have matching properties.\n */\nfunction shallowCompareObjects( object1, object2 ) {\n  return (\n    Object.keys( object1 ).length === Object.keys( object2 ).length &&\n    Object.keys( object1 ).every(\n      ( key ) => key in object2 && object1[ key ] === object2[ key ]\n    )\n  );\n}\n\nclass Link {\n\n  /**\n   * Link\n   * @constructor\n   * @param {String} [value]\n   * @returns {Link}\n   */\n  constructor( value ) {\n\n    /** @type {Array} URI references */\n    this.refs = []\n\n    if( value ) {\n      this.parse( value )\n    }\n\n  }\n\n  /**\n   * Get refs with given relation type\n   * @param {String} value\n   * @returns {Array<Object>}\n   */\n  rel( value ) {\n\n    var links = []\n    var type = value.toLowerCase()\n\n    for( var i = 0; i < this.refs.length; i++ ) {\n      if( this.refs[ i ].rel.toLowerCase() === type ) {\n        links.push( this.refs[ i ] )\n      }\n    }\n\n    return links\n\n  }\n\n  /**\n   * Get refs where given attribute has a given value\n   * @param {String} attr\n   * @param {String} value\n   * @returns {Array<Object>}\n   */\n  get( attr, value ) {\n\n    attr = attr.toLowerCase()\n\n    var links = []\n\n    for( var i = 0; i < this.refs.length; i++ ) {\n      if( this.refs[ i ][ attr ] === value ) {\n        links.push( this.refs[ i ] )\n      }\n    }\n\n    return links\n\n  }\n\n  /** Sets a reference. */\n  set( link ) {\n    this.refs.push( link )\n    return this\n  }\n\n  /**\n   * Sets a reference if a reference with similar properties isn’t already set.\n   */\n  setUnique( link ) {\n\n    if( !this.refs.some(( ref ) => shallowCompareObjects( ref, link )) ) {\n      this.refs.push( link )\n    }\n\n    return this\n\n  }\n\n  has( attr, value ) {\n\n    attr = attr.toLowerCase()\n\n    for( var i = 0; i < this.refs.length; i++ ) {\n      if( this.refs[ i ][ attr ] === value ) {\n        return true\n      }\n    }\n\n    return false\n\n  }\n\n  parse( value, offset ) {\n\n    offset = offset || 0\n    value = offset ? value.slice( offset ) : value\n\n    // Trim & unfold folded lines\n    value = trim( value ).replace( WS_FOLD_PATTERN, '' )\n\n    var state = STATE.IDLE\n    var length = value.length\n    var offset = 0\n    var ref = null\n\n    while( offset < length ) {\n      if( state === STATE.IDLE ) {\n        if( hasWhitespace( value[offset] ) ) {\n          offset++\n          continue\n        } else if( value[offset] === '<' ) {\n          if( ref != null ) {\n            ref.rel != null ?\n              this.refs.push( ...Link.expandRelations( ref ) ) :\n              this.refs.push( ref )\n          }\n          var end = value.indexOf( '>', offset )\n          if( end === -1 ) throw new Error( 'Expected end of URI delimiter at offset ' + offset )\n          ref = { uri: value.slice( offset + 1, end ) }\n          // this.refs.push( ref )\n          offset = end\n          state = STATE.URI\n        } else {\n          throw new Error( 'Unexpected character \"' + value[offset] + '\" at offset ' + offset )\n        }\n        offset++\n      } else if( state === STATE.URI ) {\n        if( hasWhitespace( value[offset] ) ) {\n          offset++\n          continue\n        } else if( value[offset] === ';' ) {\n          state = STATE.ATTR\n          offset++\n        } else if( value[offset] === ',' ) {\n          state = STATE.IDLE\n          offset++\n        } else {\n          throw new Error( 'Unexpected character \"' + value[offset] + '\" at offset ' + offset )\n        }\n      } else if( state === STATE.ATTR ) {\n        if( value[offset] ===';' || hasWhitespace( value[offset] ) ) {\n          offset++\n          continue\n        }\n        var end = value.indexOf( '=', offset )\n        if( end === -1 ) throw new Error( 'Expected attribute delimiter at offset ' + offset )\n        var attr = trim( value.slice( offset, end ) ).toLowerCase()\n        var attrValue = ''\n        offset = end + 1\n        offset = skipWhitespace( value, offset )\n        if( value[offset] === '\"' ) {\n          offset++\n          while( offset < length ) {\n            if( value[offset] === '\"' ) {\n              offset++; break\n            }\n            if( value[offset] === '\\\\' ) {\n              offset++\n            }\n            attrValue += value[offset]\n            offset++\n          }\n        } else {\n          var end = offset + 1\n          while( !DELIMITER_PATTERN.test( value[end] ) && end < length ) {\n            end++\n          }\n          attrValue = value.slice( offset, end )\n          offset = end\n        }\n        if( ref[ attr ] && Link.isSingleOccurenceAttr( attr ) ) {\n          // Ignore multiples of attributes which may only appear once\n        } else if( attr[ attr.length - 1 ] === '*' ) {\n          ref[ attr ] = Link.parseExtendedValue( attrValue )\n        } else {\n          attrValue = attr === 'type' ?\n            attrValue.toLowerCase() : attrValue\n          if( ref[ attr ] != null ) {\n            if( Array.isArray( ref[ attr ] ) ) {\n              ref[ attr ].push( attrValue )\n            } else {\n              ref[ attr ] = [ ref[ attr ], attrValue ]\n            }\n          } else {\n            ref[ attr ] = attrValue\n          }\n        }\n        switch( value[offset] ) {\n          case ',': state = STATE.IDLE; break\n          case ';': state = STATE.ATTR; break\n        }\n        offset++\n      } else {\n        throw new Error( 'Unknown parser state \"' + state + '\"' )\n      }\n    }\n\n    if( ref != null ) {\n      ref.rel != null ?\n        this.refs.push( ...Link.expandRelations( ref ) ) :\n        this.refs.push( ref )\n    }\n\n    ref = null\n\n    return this\n\n  }\n\n  toString() {\n\n    var refs = []\n    var link = ''\n    var ref = null\n\n    for( var i = 0; i < this.refs.length; i++ ) {\n      ref = this.refs[i]\n      link = Object.keys( this.refs[i] ).reduce( function( link, attr ) {\n        if( attr === 'uri' ) return link\n        return link + '; ' + Link.formatAttribute( attr, ref[ attr ] )\n      }, '<' + ref.uri + '>' )\n      refs.push( link )\n    }\n\n    return refs.join( ', ' )\n\n  }\n\n}\n\n/**\n * Determines whether an encoding can be\n * natively handled with a `Buffer`\n * @param {String} value\n * @returns {Boolean}\n */\nLink.isCompatibleEncoding = function( value ) {\n  return COMPATIBLE_ENCODING_PATTERN.test( value )\n}\n\nLink.parse = function( value, offset ) {\n  return new Link().parse( value, offset )\n}\n\nLink.isSingleOccurenceAttr = function( attr ) {\n  return attr === 'rel' || attr === 'type' || attr === 'media' ||\n    attr === 'title' || attr === 'title*'\n}\n\nLink.isTokenAttr = function( attr ) {\n  return attr === 'rel' || attr === 'type' || attr === 'anchor'\n}\n\nLink.escapeQuotes = function( value ) {\n  return value.replace( /\"/g, '\\\\\"' )\n}\n\nLink.expandRelations = function( ref ) {\n  var rels = ref.rel.split( ' ' )\n  return rels.map( function( rel ) {\n    var value = Object.assign( {}, ref )\n    value.rel = rel\n    return value\n  })\n}\n\n/**\n * Parses an extended value and attempts to decode it\n * @internal\n * @param {String} value\n * @return {Object}\n */\nLink.parseExtendedValue = function( value ) {\n  var parts = /([^']+)?(?:'([^']*)')?(.+)/.exec( value )\n  return {\n    language: parts[2].toLowerCase(),\n    encoding: Link.isCompatibleEncoding( parts[1] ) ?\n      null : parts[1].toLowerCase(),\n    value: Link.isCompatibleEncoding( parts[1] ) ?\n      decodeURIComponent( parts[3] ) : parts[3]\n  }\n}\n\n/**\n * Format a given extended attribute and it's value\n * @param {String} attr\n * @param {Object} data\n * @return {String}\n */\nLink.formatExtendedAttribute = function( attr, data ) {\n\n  var encoding = ( data.encoding || 'utf-8' ).toUpperCase()\n  var language = data.language || 'en'\n\n  var encodedValue = ''\n\n  if( Buffer.isBuffer( data.value ) && Link.isCompatibleEncoding( encoding ) ) {\n    encodedValue = data.value.toString( encoding )\n  } else if( Buffer.isBuffer( data.value ) ) {\n    encodedValue = data.value.toString( 'hex' )\n      .replace( /[0-9a-f]{2}/gi, '%$1' )\n  } else {\n    encodedValue = encodeURIComponent( data.value )\n  }\n\n  return attr + '=' + encoding + '\\'' +\n    language + '\\'' + encodedValue\n\n}\n\n/**\n * Format a given attribute and it's value\n * @param {String} attr\n * @param {String|Object} value\n * @return {String}\n */\nLink.formatAttribute = function( attr, value ) {\n\n  if( Array.isArray( value ) ) {\n    return value.map(( item ) => {\n      return Link.formatAttribute( attr, item )\n    }).join( '; ' )\n  }\n\n  if( attr[ attr.length - 1 ] === '*' || typeof value !== 'string' ) {\n    return Link.formatExtendedAttribute( attr, value )\n  }\n\n  if( Link.isTokenAttr( attr ) ) {\n    value = needsQuotes( value ) ?\n      '\"' + Link.escapeQuotes( value ) + '\"' :\n      Link.escapeQuotes( value )\n  } else if( needsQuotes( value ) ) {\n    value = encodeURIComponent( value )\n    // We don't need to escape <SP> <,> <;> within quotes\n    value = value\n      .replace( /%20/g, ' ' )\n      .replace( /%2C/g, ',' )\n      .replace( /%3B/g, ';' )\n\n    value = '\"' + value + '\"'\n  }\n\n  return attr + '=' + value\n\n}\n\nmodule.exports = Link\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport CacheableResponse from './CacheableResponse';\n\n\n// https://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.1\n\n// OCTET          = <any 8-bit sequence of data>\n// CHAR           = <any US-ASCII character (octets 0 - 127)>\n// CTL            = <any US-ASCII control character\n//                  (octets 0 - 31) and DEL (127)>\n// SP             = <US-ASCII SP, space (32)>\n// HT             = <US-ASCII HT, horizontal-tab (9)>\n// separators     = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n//                | \",\" | \";\" | \":\" | \"\\\" | <\">\n//                | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n//                | \"{\" | \"}\" | SP | HT\n// token          = 1*<any CHAR except CTLs or separators>\n\n// A header is just a <token>, the char ':' and the value.\nfunction createHeaderRegexp() {\n    const separators = '()<@,;:\"/[]={}';\n\n    // Start from the first character that is accepted by the <token>.\n    let start = 33;\n    const regexp = [ '^([' ];\n\n    for (let i = 34; i <= 127; ++i) {\n        // We know 127 is not accepted, so we use it as a terminator for our regexp segments.\n        // None of the separators are allowed.\n        if (i === 127 || separators.indexOf(String.fromCharCode(i)) !== -1) {\n            regexp.push('\\\\' + start.toString(8));\n            if (start < i - 1) {\n                regexp.push('-\\\\' + (i - 1).toString(8));\n            }\n            start = i + 1;\n        }\n    }\n    regexp.push(']+):(.*)$');\n    return new RegExp(regexp.join(''));\n}\n\nconst END_OF_LINE = '\\n';\nconst CR = '\\r';\nconst headerRegexp = createHeaderRegexp();\nconst statusRegexp = /^[^\\s]+\\s+(\\d+)\\s*(.*)$/;\n\nclass HttpResponseParser {\n\n    private _index: number = 0;\n\n    constructor(private _text: string) {\n    }\n\n    readLine(): string | undefined {\n        const { _index, _text } = this;\n\n        // The standard expects lines to end with CRLF by default.\n        // However, it recommends to accept a single LF as well,\n        // just in case some implementations do not implement the\n        // standard correctly.\n        // Async responses only use LF.\n        const endOfLine = _text.indexOf(END_OF_LINE, _index);\n        if (endOfLine === -1) {\n            // We're done.\n            return;\n        }\n        this._index = endOfLine + END_OF_LINE.length;\n\n        let line = _text.slice(_index, endOfLine);\n        if (line.endsWith(CR)) {\n            // If we have the CR just before the LF, then we want to skip it too.\n            line = line.slice(0, -1);\n        }\n        return line;\n    }\n\n    get remainderText(): string {\n        return this._text.slice(this._index);\n    }\n\n}\n\n/**\n * Implements parsing of the async response body.\n * https://git.corp.adobe.com/pages/caf/api-spec/chapters/advanced/asynchronous_invocation.html\n *\n * The caller should check for status code 202 then call this method to extract the contents\n * of final async result. The actual result is very similar to a nested HTTP reply inside the body\n * of the initial request.\n *\n */\nexport function parseAsyncResponse(originalUrl: string, body: string): Response {\n    if (!body) {\n        throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Invalid async response body.');\n    }\n\n    const parser = new HttpResponseParser(body);\n\n    let status: number;\n    let statusText: string;\n\n    const statusLine = parser.readLine();\n    if (!statusLine) {\n        // throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Could not find async response status line.');\n        // TODO: R-API does not return the status line for operations api. Any errors are reported in data section.\n        // When this is fixed, then missing status line should be an error.\n        // https://developers.corp.adobe.com/supplemental-resources/docs/async-invocation.md/#operations-api-exception\n        status = 200;\n        statusText = '';\n    } else {\n        // The status line has 3 parts separated by spaces.\n        // Example status line: HTTP/1.1 200 Status text\n        const statusMatch = statusLine.match(statusRegexp);\n        if (!statusMatch) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Invalid status line for async response.');\n        }\n\n        // The status code is the second element\n        status = parseInt(statusMatch[1], 10);\n        if (!status) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Could not find status code for async response.');\n        }\n\n        statusText = statusMatch[2];\n    }\n\n    // Now we extract the headers line by line.\n    const headers: HeadersInit = [];\n    let headerName: string | undefined;\n\n    for (;;) {\n        const headerLine = parser.readLine();\n        if (!headerLine) {\n            break;\n        }\n\n        const match = headerLine.match(headerRegexp);\n        if (!match) {\n            if (headerName) {\n                // If this is not a token, then we just continue with the value.\n                headers.push([ headerName, headerLine ]);\n            }\n            continue;\n        }\n\n        headerName = match[1];\n        headers.push([ headerName, match[2] ]);\n    }\n\n    // 1. The last `readLine()` call above will actually jump over the empty\n    // line that separates the headers from the data section.\n    // 2. The Headers constructor below takes care of multiple headers with the\n    // same name and concatenates them as necessary.\n    return new CacheableResponse(originalUrl, new Headers(headers), status, statusText, parser.remainderText);\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2023 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\n/**\n * Clamps a value to a minimum, maximum, or range\n *  @example <caption>Clamp to minimum of 4</caption>\n *  clamp(5, 4); // returns 4\n *  @example <caption>Clamp to a maximum of 3</caption>\n *  clamp(5, undefined, 3); // returns 3\n *  @example <caption>Clamp to a range 3 - 6</caption>\n *  clamp(5, 3, 6); // returns 5\n *\n * @param value {number} Value to be clamped\n * @param min {number|undefined} Minimum value\n * @param max {number|undefined} Maximum value\n * @return {number} Value that is clamped to be >= min (if provided) and <= max (if provided), or value if it is\n *          within range\n */\n\nfunction clamp(value: number, min: undefined, max: number): number;\nfunction clamp(value: number, min: number, max?: number): number;\nfunction clamp(value: number, min?: number, max?: number): number {\n    if (min !== undefined && value < min) { return min; }\n    if (max !== undefined && value > max) { return max; }\n    return value;\n}\n\nexport default clamp;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport TypedEventEmitter from './TypedEventEmitter';\nimport type { ISAMObject, ISAMCorePrivate } from '../indexPrivate';\nimport type { ItemBaseEvents } from './ItemBase';\nimport EventEmitter from 'events';\n\n\nexport class SAMObjectEventEmitter<Events extends ItemBaseEvents = ItemBaseEvents> extends TypedEventEmitter<Events> implements ISAMObject {\n    constructor(readonly _core: ISAMCorePrivate) {\n        super();\n    }\n}\n\nexport class SAMObjectUntypedEventEmitter extends EventEmitter implements ISAMObject {\n    constructor(readonly _core: ISAMCorePrivate) {\n        super();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { observable } from '../core/decorators';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { SAMObjectEventEmitter } from '../core/SAMObjectEventEmitter';\nimport type CacheableResponse from '../interface/CacheableResponse';\nimport type { ApolloQueryResult } from '@apollo/client';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\n\nexport interface ChangeDetails {\n    /** If true, the response is from cache, and a subsequent response (or error) WILL follow. */\n    loading?: boolean;\n    /**\n     * If true, the async response differed from the cache, and any lists that consumed the\n     * previous response should be refreshed.\n     * If false, the async response matched the cache, so no further action is required.\n     * If undefined, the response cache was not used, so it behaves like a normal one-off response.\n     */\n    changed?: boolean;\n    /** The etag of the object, having just been updated. (May not be present on all resource types.) */\n    etag?: string | null;\n}\n\nexport interface IResourceOptions<ParsedResponse> {\n    /** An error callback, called when a request fails. */\n    onError?: (error: any) => Promise<void>;\n    /** Parse a response into this resource's data. */\n    parseResponse?: (response: Response) => Promise<ParsedResponse>;\n    /** Parse a response into this resource's data. */\n    parseGraphQLResult?: (response: ApolloQueryResult<any>) => Promise<ParsedResponse>;\n    /**\n     * Called when the resource changes, even if it is unloaded (note that the value may be undefined).\n     * ResponseFlags indicate whether this response is still loading, and whether the data changed,\n     * allowing consumers to know whether the previous response was stale.\n     */\n    onChange?: (value: ParsedResponse | undefined, details?: ChangeDetails) => Promise<void>;\n    /**\n     * Load the data for the resource. This callback should trigger a request and set the data,\n     * typically by passing this Resource class as a parameter to fetch().\n     * (The return value of this method is not used.)\n     *\n     * A subclass can override _loadData() to have the same effect.\n     */\n    loadData?: () => Promise<void>;\n    /**\n     * A resource should revalidate if it isn't sure if its value is outdated.\n     * We'll use the cache, but check the server in the background. Typically\n     * when resource is watched with ONS, we don't need to revalidate, because\n     * we'll mark the resource dirty instead.\n     */\n    skipRevalidation?: () => boolean;\n    skipCache?: () => boolean;\n    getCacheKey?: (method: string, href: string, body?: BodyInit | null | undefined) => string;\n}\n\nexport function isResponse(response: any): response is Response {\n    return response && typeof response.json === 'function';\n}\n\nexport function isGraphQLResult(response: any): response is ApolloQueryResult<any> {\n    return ('data' in response) || ('errors' in response);\n}\n\n/**\n * A resource wraps a response that can be loaded from the server. It can be observed for changes.\n * It can either be configured to fetch its own data (with `loadData`), or its data can be set\n * externally (with a fetch request, or via _setData).\n *\n * Resource works in tandem with the ResponseCache, if enabled, to support requests that may resolve\n * with more than one response:\n *\n *   (1) the initial response from cache\n *   (2) the updated response from the server, *if* it has changed.\n *\n * Consumers should use `.get()` to fetch the data, which will load it if necessary.\n */\nexport default class Resource<T = any> extends SAMObjectEventEmitter {\n\n    private _isLoaded: boolean = false;\n    private _parserOverride?: ((response: Response | ApolloQueryResult<any>) => any) | undefined;\n    private _data: T | undefined;\n    protected _error: any;\n    private _cacheKey: string | undefined;\n    protected _etag: string = '';\n\n    constructor(\n        /** @package */\n        readonly _core: ISAMCorePrivate,\n        private readonly _options: IResourceOptions<T> = {}\n    ) {\n        super(_core);\n    }\n\n    /**\n     * A resource should be marked dirty if its value is _known_ to be outdated.\n     * This will force the next load to fetch the data from the server, ignoring the cache.\n     * The next successful response will mark the resource as clean.\n     */\n    public isDirty = false;\n\n    protected async _loadData(): Promise<void> {\n        // Resources could be loaded from an external source, via onResponse.\n        // Subclasses might want to have a way to load data here.\n        return this._options.loadData?.();\n    }\n\n    protected async _onChange(details?: ChangeDetails) {\n        await this._options.onChange?.(this.data, details);\n        this.emit('change');\n    }\n\n    /**\n     * Load the resource, even if it has already been loaded.\n     * If an error occurs right away, it will be thrown.\n     */\n    async load(): Promise<void> {\n        await this._loadData();\n    }\n\n    /**\n     * Get the data for the resource. The data will be fetched if one of the following is true:\n     *   - it hasn't been loaded yet\n     *   - it has been marked isDirty\n     *   - forceRefresh is true\n     */\n    async get(options: { forceRefresh?: boolean }): Promise<T> {\n        if (options.forceRefresh || !this.isLoaded || this.isDirty) {\n            await this.load();\n        }\n        return this.data!;\n    }\n\n    /**\n     * TODO_Deprecation: To be marked deprecated on or after 2025-03-01. When there are multiple\n     * clients of a SAM instance, some wanting a Resource loaded and others wanting to unload, then that\n     * creates an unresolvable conflict. SAM can use its lazy-loading pattern to ensures Resources are\n     * only refreshed when there are clients that need it. For resources with large payloads, the data\n     * should be stored as a WeakRef with `@keepAlive` decorator.\n     */\n    async unload() {\n        this._data = undefined;\n        this._etag = '';\n        this._error = undefined;\n        this._isLoaded = false;\n        await this._onChange();\n    }\n\n    /**\n     * Returns true if the data has been loaded. (Excludes updates from _mergeData.)\n     */\n    @observable\n    get isLoaded(): boolean {\n        return this._isLoaded;\n    }\n\n    /** The data for the resource. Accessing this does not fetch it; prefer .get() if needed. */\n    @observable\n    get data(): T {\n        return this._data!;\n    }\n\n    /** The etag of the most recent Response (from its headers), otherwise an empty string. */\n    @observable\n    get etag(): string {\n        return this._etag || '';\n    }\n\n    @observable\n    get error(): any {\n        return this._error;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    async _setData(data: T, details: ChangeDetails = {}): Promise<void> {\n        this._data = data;\n        this._etag = details.etag || '';\n        this._error = undefined;\n        this._isLoaded = true;\n        await this._onChange(details);\n    }\n\n    /**\n     * Merge new data into existing. Supports cases where data sources might not include all fields,\n     * such as for appMetadata in listings, typically called by ItemUpdaters. This does not affect the load\n     * status or dirty status, because it's not known whether the data is stale after merging possibly incomplete data.\n     * @package -- for use in SAM.js only\n     */\n    async _mergeData(data: any) {\n        this._data = { ...(this._data || {}), ...(data || {}) };\n        this._etag = ''; // Assume the etag is not valid if we've changed the data elsewhere\n        await this._onChange();\n    }\n\n    /**\n     * Parse the given response. If the parseResponse or parseGraphQLResult options are provided,\n     * they will be used to parse the response. Otherwise, it will default to calling `response.json()`.\n     * If the response is a GraphQL result, it will check for errors and throw a SAMError if any are present.\n     *\n     * @package -- for use in SAM.js only\n     */\n    async _parse(response: Response | ApolloQueryResult<any>) {\n        if (this._parserOverride) {\n            return this._parserOverride(response);\n        }\n\n        if (isResponse(response)) {\n            return this._options.parseResponse?.(response) ?? response.json();\n        } else if (isGraphQLResult(response)) {\n            if (response.errors?.[0]) {\n                if (!response.data) {\n                    throw SAMError.createWithGraphQLError(response.errors[0]);\n                } else {\n                    this._core._environment.error('GraphQL response contained errors but also data; ignoring partial errors: ' + JSON.stringify(response.errors));\n                }\n            }\n            return this._options.parseGraphQLResult?.(response) ?? response.data;\n        } else {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Resource.parse() received an unexpected response type: ' + response);\n        }\n    }\n\n    /**\n     * Used to override the default parser for the resource. This is useful for cases where we want custom parse logic which contains special error handling.\n     *\n     * @package -- for use in SAM.js only\n     */\n    public set parser(parser: (response: Response | ApolloQueryResult<any>) => any) {\n        this._parserOverride = parser;\n    }\n\n    /** @package */\n    public get skipRevalidation(): boolean {\n        return this._options.skipRevalidation?.() ?? false;\n    }\n\n    /** @package */\n    public get skipCache(): boolean {\n        return this._options.skipCache?.() ?? false;\n    }\n\n    /**\n     * Complement to _setData() for internal SAM use; sets the error state on the resource,\n     * calling the onError callback if provided.\n     *\n     * @package -- for use in SAM.js only\n     */\n    public async _setError(error: any): Promise<void> {\n        try {\n            // Set the error state on the resource first, whether or not we have an onError handler.\n            // If the onError handler wants to treat this as a successful response,\n            // it can call _setData() to clear the error on the resource.\n            this._error = error;\n            await this._options.onError?.(error);\n        } catch (e) {\n            // If the error handler throws an error, store that one as the resource's error.\n            this._error = e;\n        }\n    }\n\n    static getDefaultCacheKey(method: string, href: string, body?: BodyInit | null | undefined): string | undefined {\n        if (body && typeof body !== 'string') {\n            // Non-string bodies (such as Streams, if we ever use them) are not currently cacheable.\n            return undefined;\n        }\n        return `${method}-${href}-${body ?? ''}`;\n    }\n\n    /**\n     * Deletes the response from the cache.\n     */\n    async deleteCachedResponse(): Promise<void> {\n        if (this._cacheKey) {\n            const responseCache = this._core._environment._responseCache;\n            if (responseCache) {\n                await responseCache.deleteCachedResponse(this._cacheKey);\n                this._cacheKey = undefined;\n            }\n        }\n    }\n\n    /** Track active revalidations to ensure we don't revalidate the same page concurrently. */\n    private _activeRevalidations = new Map<string, Promise<any>>();\n\n    /**\n     * Perform a fetch request, intercepting the response to handle caching and revalidation.\n     * If a cached response is available, it will be returned immediately. Unless the Resource\n     * uses skipRevalidation(), the request will be revalidated in the background, and the Resource\n     * will be updated with the new response when it arrives.\n     *\n     * @package\n     */\n    async _interceptFetch(\n        method: string,\n        href: string,\n        body: BodyInit | null | undefined,\n        performFetch: () => Promise<CacheableResponse>\n    ): Promise<Response> {\n        // NOTE: Environment._responseCache will be undefined if ResponseCache is disabled.\n        const responseCache = this._core._environment._responseCache;\n        let cachedResponse: CacheableResponse | undefined;\n        if (!this._options.skipCache?.()) {\n            this._cacheKey = this._options.getCacheKey?.(method, href, body) ?? Resource.getDefaultCacheKey(method, href, body);\n            cachedResponse = (this.isDirty || !this._cacheKey) ? undefined : await responseCache?.getCachedResponse(this._cacheKey);\n        }\n\n        const subsequentResponseExpected = cachedResponse && !this._options.skipRevalidation?.();\n\n        const performRevalidation = async (): Promise<Response> => {\n            let response: CacheableResponse;\n            try {\n                response = await performFetch();\n                // Save the response to the cache whether it matches or not, to ensure the TTL gets extended.\n                if (this._cacheKey && responseCache) {\n                    await responseCache?.saveResponseToCache(this._cacheKey, response);\n                }\n                const matches = await response.matches(cachedResponse);\n                await this._setData(await this._parse(response), {\n                    etag: response.headers.get('ETag') || '',\n                    changed: subsequentResponseExpected && !matches,\n                    loading: false\n                });\n                return response;\n            } catch (error) {\n                await this._setError(error);\n                // The error handler could have cleared the error (e.g. with `this._setData()`),\n                // such as in cases where a 404 is expected and handled as a successful response.\n                if (!this._error) {\n                    // A fetch might've returned a SAMError but then been handled as a successful response.\n                    return new Response();\n                } else {\n                    throw this._error;\n                }\n            }\n        };\n\n        // Track revalidations to prevent multiple concurrent revalidations for the same cache key.\n        const revalidate = async () => {\n            const existingPromise = this._cacheKey && this._activeRevalidations.get(this._cacheKey);\n            if (existingPromise) {\n                return await existingPromise;\n            }\n            try {\n                const promise = performRevalidation();\n                if (this._cacheKey) {\n                    this._activeRevalidations.set(this._cacheKey, promise);\n                }\n                return await promise;\n            } finally {\n                if (this._cacheKey) {\n                    this._activeRevalidations.delete(this._cacheKey);\n                }\n            }\n        };\n\n        if (cachedResponse) {\n            // If we're going to revalidate, kick it off in the background, and return the cached response in the meantime.\n            if (subsequentResponseExpected) {\n                void revalidate();\n            }\n            await this._setData(await this._parse(cachedResponse), {\n                etag: cachedResponse.headers.get('ETag') || '',\n                changed: false, // The first cached response is not changed, for the purposes of list refreshing.\n                loading: subsequentResponseExpected\n            });\n            return cachedResponse;\n        } else {\n            return revalidate();\n        }\n    }\n}\n\n/**\n * A Passthrough Resource doesn't cache responses.\n * It is used for requests that do not provide their own Resource,\n * where we haven't explicitly set up a Resource to handle a cached response.\n * Providing a Resource allows us to handle requests with the same codepath whether attached to a Resource or not.\n */\nexport class PassthroughResource extends Resource<Response> {\n    constructor(readonly _core: ISAMCorePrivate) {\n        super(_core, {\n            parseResponse: async (response: Response) => response,\n            skipCache: () => true,\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport UriTemplate from 'uri-templates';\nimport LinkHeader from 'http-link-header';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport type { HeaderMap } from './LinkUtils';\nimport { RelType, getRetryAfterHeader } from './LinkUtils';\nimport { parseAsyncResponse } from './AsyncResponse';\nimport type { IFetchOptions } from '../core/Environment';\nimport clamp from '../utils/clamp';\nimport type Resource from '../assets/Resource';\nimport { PassthroughResource } from '../assets/Resource';\nimport type { ValidHttpResponseCodes } from './ResponseCodes';\nimport { RETRY_HTTP_RESPONSE_CODES, VALID_HTTP_RESPONSE_CODES } from './ResponseCodes';\nimport CacheableResponse from './CacheableResponse';\nimport samJsUuid from '../core/uuid';\n\n// Make 1 request, then MAX_ERROR_RETRIES retries\nconst MAX_ERROR_RETRIES = 5;\n\ntype PaginatedResponse = { result: any, next?: () => Promise<PaginatedResponse> };\n\nexport type InterfaceBaseFetchOptions<ParsedResponse> = IFetchOptions & {\n    additionalRetryErrorCodes?: number[];\n    successResponseCodes?: ValidHttpResponseCodes;\n    headers?: HeaderMap;\n    resource?: Resource<ParsedResponse>;\n    handleError?: (response: Response) => Promise<void>;\n};\n\n/**\n * InterfaceBase and its subclasses are abstractions around calling into a service (not to be confused with typescript\n * interfaces). It extends fetch to provide retry and error handling logic.\n */\nexport default class InterfaceBase implements ISAMObject {\n    protected _useHighPriorityRequestsIfEnabled: boolean = false;\n\n    constructor(\n        readonly _core: ISAMCorePrivate\n    ) {}\n\n    protected async _fetch<ParsedResponse>(\n        href: string,\n        options: InterfaceBaseFetchOptions<ParsedResponse> = {\n            successResponseCodes: VALID_HTTP_RESPONSE_CODES\n        }\n    ): Promise<Response> {\n        // Ensure we remove any non-fetch-related options before passing to fetch,\n        // as the nock library will hold references to these (and cause GC tests to fail).\n        const {\n            resource = new PassthroughResource(this._core) as unknown as Resource<ParsedResponse>,\n            ...fetchOptions\n        } = options;\n\n        const performFetch = () => this._fetchImpl(href, fetchOptions, 0).then(CacheableResponse.fromResponse);\n        return await resource._interceptFetch(options.method ?? 'GET', href, options.body, performFetch);\n    }\n\n    private async _fetchImpl(\n        href: string,\n        options: InterfaceBaseFetchOptions<unknown>,\n        retryCount: number\n    ): Promise<Response> {\n        const {\n            additionalRetryErrorCodes,\n            successResponseCodes = VALID_HTTP_RESPONSE_CODES,\n            // fetchOptions should only contain IFetchOptions\n            ...fetchOptions\n        } = options;\n        const retryErrorCodes = [ ...RETRY_HTTP_RESPONSE_CODES, ...(additionalRetryErrorCodes || []) ];\n        const overrides = await this._getFetchOptionOverrides(href, fetchOptions);\n        let response = await this._core._environment.fetch(overrides.href, overrides.options);\n        const { status } = response;\n        if (status === 202) {\n            response = await this._monitorResponse(response);\n        }\n\n        // Handle any custom error cases\n        if (options.handleError && status >= 400) {\n            await options.handleError(response.clone());\n        }\n\n        // Retry if any of these conditions are met:\n        // 1. Response has a Retry-After header\n        // 2. Status code is in retryErrorCodes\n        if (status >= 400 && (\n            getRetryAfterHeader(response.headers)\n            || retryErrorCodes.includes(status)\n        )) {\n            if (retryCount < MAX_ERROR_RETRIES) {\n                const delay = this._getRetryErrorDelay(response, retryCount);\n                this._core._environment.log(\n                    `Retryable error ${status} retrying in ${delay}ms, ${retryCount} retries so far`);\n                await new Promise(resolve => setTimeout(resolve, delay));\n                return await this._fetchImpl(href, options, retryCount + 1);\n            } else {\n                this._core._environment.log(\n                    `Retryable error ${status} attempt ${retryCount} exceeded ${MAX_ERROR_RETRIES} retries`);\n            }\n        }\n        if (successResponseCodes !== 'any') {\n            this._checkResponseStatus(response, href, successResponseCodes);\n        }\n        return response;\n    }\n\n    protected _checkResponseStatus(response: Response, href: string, successResponseCodes: number[]) {\n        if (!successResponseCodes.includes(response.status)) {\n            const error = SAMError.createWithResponse(response, href);\n            this._core._environment.error(`InterfaceBase error ${error}`);\n            throw error;\n        }\n    }\n\n    protected async _monitorResponse(response: Response): Promise<Response> {\n        let href: string | null = response.headers.get('location');\n\n        if (!href) {\n            const json = await response.json();\n            if (!json) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Failed to parse content for 202 monitor response.');\n            }\n            href = json.href;\n            if (!href) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Missing href property for 202 monitor response.');\n            }\n        }\n\n        const delay = this._getMonitorRetryAfter(response.headers);\n        return this._fetchMonitorResponse(response.url, href, delay);\n    }\n\n    private async _fetchMonitorResponse(originalUrl: string, asyncUrl: string, delay: number): Promise<Response> {\n        if (delay) {\n            // Wait before trying again.\n            await new Promise((resolve) => setTimeout(resolve, delay));\n        }\n        const asyncResponse = await this._core._environment.fetch(asyncUrl);\n        const body = await asyncResponse.text();\n\n        const shouldRetry = this._shouldRetryMonitorResponse(asyncResponse, body);\n        if (shouldRetry) {\n            // Try again later.\n            const newDelay = this._getMonitorRetryAfter(asyncResponse.headers);\n            return this._fetchMonitorResponse(originalUrl, asyncUrl, newDelay);\n        }\n\n        // If the response was recently returned and it's now a JSON response\n        // let's just parse it and return the result, otherwise it's not going to\n        // have a standard response body that parseAsyncResponse can handle.\n        if (asyncResponse.headers.get('content-type')?.includes('application/json')) {\n            return new CacheableResponse(\n                originalUrl,\n                new Headers(asyncResponse.headers),\n                asyncResponse.status,\n                asyncResponse.statusText,\n                body\n            );\n        }\n\n        // Parse the response from the async call.\n        return parseAsyncResponse(originalUrl, body);\n    }\n\n    /**\n     * Determines whether or not the response indicates the server-side async process is still underway.\n     */\n    // Overrides can use `body`\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    protected _shouldRetryMonitorResponse(asyncResponse: Response, body: string): boolean {\n        return asyncResponse.status === 202;\n    }\n\n    /**\n     * Calculate how long of a delay before re-requesting the status of a server-side async process.\n     */\n    private _getMonitorRetryAfter(headers: Headers): number {\n        return getRetryAfterHeader(headers) * 1000 || this._core._environment.getValue('ASYNC_DEFAULT_DELAY');\n    }\n\n    /**\n     * Calculate how long of a delay before retrying a request that failed\n     */\n    protected _getRetryErrorDelay(response: Response | undefined, retryCount: number): number {\n        const min = this._core._environment.getValue('MIN_RETRY_INTERVAL');\n        const max = this._core._environment.getValue('MAX_RETRY_INTERVAL');\n        const delay = (response && getRetryAfterHeader(response.headers) || Math.pow(2, retryCount)) * 1000;\n        return clamp(delay, min, max);\n    }\n\n    /**\n     * Make a GET request to the Platform API.\n     * @param href for request\n     * @param additionalFetchOptions {InterfaceBaseFetchOptions} (optional)\n     */\n    protected async _doGet<ParsedResponse>(href: string, additionalFetchOptions?: InterfaceBaseFetchOptions<ParsedResponse>) {\n        return this._fetch(\n            href,\n            {\n                method: 'GET',\n                successResponseCodes: VALID_HTTP_RESPONSE_CODES,\n                ...additionalFetchOptions\n            });\n    }\n\n    /**\n     * Make a HEAD request to the Platform API.\n     * @param href for request\n     * @param headers for request\n     */\n    protected async _doHead(href: string, headers: HeaderMap = {}) {\n        return this._fetch(href, { method: 'HEAD', headers });\n    }\n\n    /**\n     * Make a POST request to the Platform API.\n     * @param href for request\n     * @param headers for request\n     * @param body for request\n     * @param successResponseCodes for request. Most POST requests that create something will return a 201 success\n     *     code, but sometimes a different success code is used (e.g. 204 for discard/restore).\n     */\n    protected async _doPost(href: string, headers: HeaderMap = {}, body?: string | Blob, successResponseCodes: ValidHttpResponseCodes = [ 201 ], noOtherHeaders: boolean = false, resource?: Resource) {\n        return this._fetch(href, { method: 'POST', headers, noOtherHeaders, body, successResponseCodes, resource });\n    }\n\n    /**\n     * Make a PATCH request to the Platform API.\n     * @param href for request\n     * @param headers for request\n     * @param body for request\n     * @param successResponseCodes for request.\n     */\n    protected async _doPatch(href: string, headers: HeaderMap = {}, body?: string, successResponseCodes: ValidHttpResponseCodes = [ 200 ]) {\n        return this._fetch(href, { method: 'PATCH', headers, body, successResponseCodes });\n    }\n\n    /**\n     * Make a PUT request to the Platform API.\n     * @param href for request\n     * @param headers for request\n     * @param body for request\n     * @param successResponseCodes for request\n     * @param noOtherHeaders whether to skip adding other headers\n     * @param options Additional options for the request, including handleError callback to determine if an error should be thrown\n     */\n    protected async _doPut(href: string, headers: HeaderMap = {}, body?: string | Blob, successResponseCodes: ValidHttpResponseCodes = [ 201 ], noOtherHeaders: boolean = false, options?: InterfaceBaseFetchOptions<Response>) {\n        return this._fetch(href, { method: 'PUT', headers, body, noOtherHeaders, successResponseCodes, ...options });\n    }\n\n    /**\n     * Make a DELETE request to the Platform API.\n     * @param href for request\n     * @param headers for request\n     * @param successResponseCodes for request.\n     */\n    protected async _doDelete(href: string, headers: HeaderMap = {}, successResponseCodes: ValidHttpResponseCodes = [ 200 ], noOtherHeaders: boolean = false) {\n        return this._fetch(href, { method: 'DELETE', headers, noOtherHeaders, successResponseCodes });\n    }\n\n    /**\n     * Get a JSON resource from the platform API - handles parsing the response as JSON\n     * @param href for request\n     * @param additionalFetchOptions {InterfaceBaseFetchOptions} (optional)\n     */\n    protected async _getResponse<ParsedResponse extends object>(href: string, additionalFetchOptions?: InterfaceBaseFetchOptions<Response>): Promise<ParsedResponse> {\n        const response = await this._doGet(\n            href,\n            additionalFetchOptions\n        );\n        return response.json() as ParsedResponse;\n    }\n\n    private _sharedResponses: Map<string, Promise<any>> = new Map;\n\n    /**\n     * The same as _getResponse, except that it allows piggybacking on a request if it's\n     * already in-flight. This is useful when we have multiple places in the code that\n     * depend on data from the same request (e.g. getting both collaborators and invitations\n     * from the same API), and we want to avoid making repeated requests.\n     *\n     * @param href for request\n     * @param headers for request\n     */\n    protected async _getSharedResponse(href: string, headers: HeaderMap = {}) {\n        let response = this._sharedResponses.get(href);\n        if (!response) {\n            response = this._getResponse(href, { headers });\n            this._sharedResponses.set(href, response);\n            response.finally(() => this._sharedResponses.delete(href));\n        }\n        return response;\n    }\n\n    /**\n     * Make a request to the Platform API. If it is paged, provide a next callback\n     * @param href for page\n     * @param headers to send with request\n     */\n    protected async _getPagedResponse(href: string, headers: HeaderMap = {}): Promise<PaginatedResponse> {\n        const result = await this._getResponse<any>(href, headers);\n        if (result?._page?.next && result?._links?.[RelType.PAGE]) {\n            const template = UriTemplate(result._links[RelType.PAGE].href);\n            const nextHref = template.fill({\n                ...result._page,\n                start: result._page.next,\n                resource: RelType.PRIMARY\n            });\n            const next = () => this._getPagedResponse(nextHref, headers);\n            return { result, next };\n        }\n\n        return { result };\n    }\n\n    /**\n     * Get all of the pages of a page (or not) Platform API request\n     * @param href starting href\n     * @param headers to send along with the requests\n     */\n    protected _getAllPages(href: string, headers: HeaderMap = {}): Promise<any> {\n        let fullResult: any;\n\n        const readPages: (requestFn: () => Promise<PaginatedResponse>) => Promise<any> = async requestFn => {\n            const result = await requestFn();\n            const children = result && result.result && result.result.children;\n            if (!children) {\n                return fullResult;\n            }\n\n            if (!fullResult) {\n                fullResult = result.result;\n            } else {\n                fullResult.children = fullResult.children.concat(children);\n            }\n\n            return result.next ? readPages(result.next) : fullResult;\n        };\n\n        return readPages(() => this._getPagedResponse(href, headers));\n    }\n\n    /**\n     * Get and parse the links header for an object in the Platform API\n     * @param href of the object\n     */\n    protected _getLinksFromHeaders(headers: Headers) {\n        const linkHeader = headers && headers.get('Link');\n        if (!linkHeader) {\n            throw SAMError.create(SAMErrorCode.UNKNOWN, 'HEAD request did not return link header');\n        }\n\n        const link = LinkHeader.parse(linkHeader);\n\n        return (\n            link\n            && link.refs.reduce(\n                (memo: any, { rel, uri, ...otherData }) => {\n                    if (rel) {\n                        memo[rel] = memo[rel] || [];\n                        memo[rel].push({ href: uri, ...otherData });\n                    }\n\n                    return memo;\n                },\n                {}\n            )\n        );\n    }\n\n    // Sub-classes can refine requests if needed\n    protected async _getFetchOptionOverrides(\n        href: string,\n        options: IFetchOptions\n    ): Promise<{\n            href: string;\n            options: IFetchOptions\n        }> {\n        if (this._useHighPriorityRequestsIfEnabled && this._core._environment.getValue('HIGH_PRIORITY_RAPI_REQUESTS')) {\n            // See https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=CA&title=Proposal%3A+Priority+Header#Proposal:PriorityHeader-UrgencySummary\n            //\n            // If enabled, R-API requests will be made using with Priority u=1 header to enable HTTP/2 and HTTP/3, and\n            // to direct R-API to optimize calls for response time. HTTP/2+ reduces delays caused by too many\n            // connections open on the same domain. Currently, this can only be done on the edge network (CDN), which\n            // incurs some cost, but will likely be brought in-house.\n            //\n            // User-facing web clients SHOULD typically enable this to optimize user experience, but is off by default\n            // so that clients take responsibility for determining what priority to use.\n            href = !href.includes('platform-cs-edge')\n                ? href.replace('platform-cs', 'platform-cs-edge')\n                : href;\n            options.headers = {\n                ...(options.headers || {}),\n                'Priority': 'u=1'\n            };\n        }\n\n        // See https://wiki.corp.adobe.com/display/CA/Proposal%3A+Storage+Model+Unification+Detailed+Design#Proposal:StorageModelUnificationDetailedDesign-AdministratorACEs\n        // If ADMIN_MODE_ORG_ID is set, we need to add a header value to all service requests\n        // that contains the orgID provided by the Admin Console.\n        const adminModeOrgID = this._core._environment.getValue('ADMIN_MODE_ORG_ID');\n        if (adminModeOrgID) {\n            options.headers = {\n                ...(options.headers || {}),\n                'X-ACP-ADMIN-PRIVILEGES': adminModeOrgID\n            };\n        }\n\n        // See https://wiki.corp.adobe.com/display/CA/Support+scalability+in+serving+public+content+in+alignment+with+Community+Platform+Advancement#SupportscalabilityinservingpubliccontentinalignmentwithCommunityPlatformAdvancement-DetailedDesign\n        // If REQUEST_EDGE_BASED_PUBLISHED_LINKS is true and we're making a R-API request, we need to\n        // add a header value to all service requests so that RAPI returns edge-accelerated links for\n        // public assets,even when the originating service endpoint is not edge-accelerated.\n        if (this._core._environment.getValue('REQUEST_EDGE_BASED_PUBLISHED_LINKS') && href.startsWith('https://platform-cs')) {\n            options.headers = {\n                ...(options.headers || {}),\n                'acpc-published-links': 'true'\n            };\n        }\n\n        // When set, all requests will include a User-Id header with the value of REQUEST_AS_USER_ID.\n        // This is primarily used for services who are acting on behalf of a user, such as\n        // Workfront.\n        const requestAsUserID = this._core._environment.getValue('REQUEST_AS_USER_ID');\n        if (requestAsUserID) {\n            options.headers = {\n                ...(options.headers || {}),\n                'User-Id': requestAsUserID\n            };\n        }\n\n        const requestID = this._core._environment.getValue('REQUEST_ID');\n        const breadcrumbTrail = this._core._environment.getValue('BREADCRUMB_TRAIL');\n        const uuid = samJsUuid();\n        if (requestID) {\n            options.headers = {\n                ...(options.headers || {}),\n                'x-request-id': `${requestID}:${uuid}`,\n            };\n        }\n\n        if (breadcrumbTrail) {\n            options.headers = {\n                ...(options.headers || {}),\n                'x-breadcrumb-trail': `${breadcrumbTrail}-SAMJS_${uuid}`\n            };\n        }\n\n        const executionContextClientAgent = this._core._environment.getValue('EXECUTION_CONTEXT_CLIENT_AGENT');\n        if (executionContextClientAgent) {\n            options.headers = {\n                ...(options.headers || {}),\n                'Client-Agent': Object.entries(executionContextClientAgent).map(([ key, value ]) => `${key}=${value ? value : 'na'}`).join('; ')\n            };\n        }\n\n        return { href, options };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport TypedEventEmitter from '../core/TypedEventEmitter';\nimport type { ItemBaseEvents } from '../core/ItemBase';\nimport { isDeepEqual } from '../core/ObjectUtils';\nimport type { ISAMCorePrivate } from '../indexPrivate';\n\n// @TODO Verify this solution and address the following task.\n// We should also write unit tests precisely verifying this behavior.\n// https://jira.corp.adobe.com/browse/SAM-2677\nconst finalizationRegistry = new FinalizationRegistry(objUrl => {\n    URL.revokeObjectURL(objUrl as string);\n});\n\nexport enum RenditionStatus {\n    /**\n     * Initial status\n     */\n    NotStarted = 0,\n    Fetching = 1,\n    Done = 2,\n    /**\n     * Occurs when there are any errors around fetching the\n     * rendition from the service, AdobeAsset.clearRenditionError can\n     * be used to clear the error and fetch again.\n     */\n    Error = 3\n}\n\nexport enum RenditionSize {\n    Size64 = 64,\n    Size128 = 128,\n    Size256 = 256,\n    Size512 = 512,\n    Size1024 = 1024,\n}\n\nexport enum RenditionType {\n    PNG = 'image/png',\n    JPEG = 'image/jpeg'\n}\n\nexport const THUMBNAIL_SIZE: number = RenditionSize.Size512; // matches ACPL/SAM.cpp thumbnail size\n\nexport const SUPPORTED_SIZES = [\n    RenditionSize.Size64,\n    RenditionSize.Size128,\n    RenditionSize.Size256,\n    RenditionSize.Size512,\n    RenditionSize.Size1024\n];\n\ntype RenditionSizeEntry = {\n    type: string;\n    url: string;\n    size: number;\n    status: RenditionStatus;\n    versionToken: string; //Either an etag or a rendition url (in the case of Library element renditions)\n}\n\nexport class RenditionFetcher extends TypedEventEmitter<ItemBaseEvents>  {\n    private _entries: RenditionSizeEntry[] = [];\n    private _versionToken: string = '';\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        private _availableSizes: number[],\n        private _fetchRenditionBlob: (size: number, mediaType: string) => Promise<Blob>\n    ) {\n        super();\n    }\n\n    /**\n     * Given any number, this method will return a predefined\n     * size that is greater than or equal to the target size.\n     * You may also specify an existing sizes array.\n     *\n     * @param targetSize The preferred or target size.\n     * @param sizes An array of sizes to sort and find.\n     * @returns\n     */\n    private _getStandardSize(targetSize: number, sizes: number[] = this._availableSizes) {\n        // Clone the provided array so we don't alter it.\n        const sortedArray = [ ...sizes ].sort((a, b) => a - b);\n        const index = sortedArray.findIndex((s) => s >= targetSize);\n\n        // If no sizes are large enough, return the largest\n        if (index === -1) {\n            return sortedArray[sortedArray.length - 1];\n        }\n\n        return sortedArray[index];\n    }\n\n    private _findURLEntry(size: number, type: string): RenditionSizeEntry | undefined {\n        const clampedSize = this._getStandardSize(size);\n        if (this._entries.length > 0) {\n            return this._entries.find((u) => u.size === clampedSize && u.type === type && u.status !== RenditionStatus.Error);\n        }\n        return undefined;\n    }\n\n    /**\n     * Removes all entries matching the provided outdated\n     * versionToken.\n     *\n     * @param outdatedVersionToken\n     */\n    private _clearStaleEntries(outdatedVersionToken: string) {\n        const filteredEntries = this._entries.filter((entry) => {\n            if (entry.versionToken === outdatedVersionToken) {\n                URL.revokeObjectURL(entry.url);\n                return false;\n            }\n            return true;\n        });\n        this._entries = filteredEntries;\n    }\n\n    /**\n     * Finds an entry based on the provided size/type and returns\n     * a fallback size that is greater than the target, if available.\n     *\n     * @param size\n     * @param type\n     * @returns {IURLEntry}\n     */\n    private _getEntryWithFallback(size: number, type: string): RenditionSizeEntry | undefined {\n        const foundEntry = this._findURLEntry(size, type);\n        if (foundEntry) {\n            return foundEntry;\n        }\n\n        // If the exact size is not available and there\n        // are other sizes and types, return the size\n        // that is at-least greater than or equal to the current size.\n        const sizesArray =  this._entries.map((entry) => entry.size);\n        if (this._entries.length > 0) {\n            // Since we are passing in our own sizes array\n            // this should return the closest size already\n            // available.\n            const foundSize = this._getStandardSize(size, sizesArray);\n            return this._entries.find(s => s.size === foundSize);\n        }\n        return undefined;\n    }\n\n    /**\n     * Returns the download status of the requested rendition.\n     *\n     * @param size\n     * @param type\n     * @param versionToken // Either an etag or a rendition url (in the case of Library element renditions)\n     * @returns\n     */\n    public renditionURLStatus(size: number, type: string, versionToken: string): RenditionStatus {\n        const clampedSize = this._getStandardSize(size);\n        const urlStatus = this._entries.find(\n            e => e.versionToken === versionToken\n            && e.size >= clampedSize\n            && e.type === type\n        );\n        return (urlStatus && urlStatus.status) ?? RenditionStatus.NotStarted;\n    }\n\n    public get versionToken(): string {\n        return this._versionToken;\n    }\n\n    /**\n     *\n     * @param size Target size for the rendition\n     * @param type String type for example image/png.\n     * @param versionToken Either an etag or a rendition url (in the case of Library element renditions)\n     * @returns {string} The URL for the rendition.\n     */\n    public getURL(\n        size: number,\n        type: string,\n        versionToken: string\n    ): string {\n        const versionTokenChanged = versionToken !== this.versionToken;\n        const renditionEntry = this._getEntryWithFallback(size, type);\n        const clampedSize = this._getStandardSize(size);\n\n        // If we do have a rendition wether it be exact or a fallback\n        // we could return it but if the requested size is larger\n        // than the one we have in the cache we will need to add a new entry\n        // and start fetching.\n        if (renditionEntry && renditionEntry.size >= clampedSize && !versionTokenChanged) {\n            return renditionEntry.url;\n        }\n\n        const newEntry = {\n            size: clampedSize,\n            status: RenditionStatus.Fetching,\n            url: '',\n            type,\n            versionToken\n        };\n\n        // If we find an existing entry that exactly matches our new\n        // entry then we wont need to fetch again.\n        const recentlyAddedEntry = this._entries.find(e =>\n            isDeepEqual(e, newEntry)\n            // We also want to check if there is an identical entry\n            // but with an error so that we don't keep fetching over and\n            // over again in case of a thumbnail fetching error.\n            || isDeepEqual(e, { ...newEntry, status: RenditionStatus.Error })\n        );\n\n        // If we know we have an existing entry and we have\n        // a new entry that was recently added but it's state\n        // is loading then we need to just return the existing url\n        // until this is no longer true.\n        // @note Without this logic, the ui will go into an infinite\n        // loop causing the browser to crash because we are fetching\n        // and pushing change notifications over and over again.\n        if (renditionEntry && recentlyAddedEntry) {\n            return renditionEntry.url;\n        }\n\n        this._entries.push(newEntry);\n\n        this._fetch(\n            newEntry\n        );\n\n        // If we have a rendition entry after starting to fetch\n        // it means that we have a new size requested with a fallback.\n        // Return the fallback while the new size is fetching.\n        if (renditionEntry) {\n            return renditionEntry.url;\n        }\n\n        // If the versionToken hasn't changed and we have an entry we should\n        // return the existing entry while waiting for the new one.\n        return newEntry.url;\n    }\n\n    // First we find if there is an existing entry\n    // then if there isn't, we create one\n    // if there is, we update the existing entry\n    private async _fetch(\n        entry: RenditionSizeEntry\n    ): Promise<void> {\n        const { size, type, versionToken } = entry;\n\n        this.dispatch({ type: 'change' });\n\n        // We want to fetch the URL contents and create an objectURL and return the path\n        // to clients instead of the raw URL because services in future will not\n        // allow the authorization token to be passed directly in the rendition URL\n        try {\n            const renditionBlob = await this._fetchRenditionBlob(size, type);\n\n            // If there is a new versionToken all the old URLS that are now\n            // out of date so let's remove the existing ones.\n            if (versionToken && versionToken !== this._versionToken) {\n                this._clearStaleEntries(this._versionToken);\n                this._versionToken = versionToken;\n            }\n\n            entry.size = size;\n            entry.type = type;\n            entry.url = URL.createObjectURL(renditionBlob);\n            finalizationRegistry.register(this, entry.url, entry);\n            entry.status = RenditionStatus.Done;\n            entry.versionToken = versionToken;\n\n            this.dispatch({ type: 'change' });\n        } catch (e) {\n            // IF there was an error fetching the thumbnail, we don't\n            // want clients stuck in a bad state so we set the rendition\n            // to an error dispatch a change event.\n            entry.status = RenditionStatus.Error;\n            this.dispatch({ type: 'change' });\n        }\n\n    }\n\n    /**\n     * Resets the rendition status on the requested rendition to RenditionStatus.NotStarted\n     */\n    public clearRenditionError(size: number, type: string, versionToken: string): void {\n        const clampedSize = this._getStandardSize(size);\n        // Find an entry that has all the properties\n        // of the request one including the error status.\n        // Leaving out the URL case if for some reason it has a value\n        // but we still want to reset the error.\n        const foundErrorEntryIndex = this._entries.findIndex(e =>\n            e.size >= clampedSize\n            && e.type === type\n            && e.versionToken === versionToken\n            && e.status === RenditionStatus.Error\n        );\n\n        if (foundErrorEntryIndex === -1) {\n            return;\n        }\n\n        // Remove the entry so that when getURL is called again\n        // it will add a new entry and begin the fetch process\n        // again.\n        this._entries.splice(foundErrorEntryIndex, 1);\n        this.dispatch({ type: 'change' });\n    }\n\n    public release(): void {\n        if (this._entries.length === 0) {\n            return;\n        }\n\n        this._entries.forEach((value) => {\n            URL.revokeObjectURL(value.url);\n            finalizationRegistry.unregister(this);\n        });\n        this._entries = [];\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport type ItemPool from '../core/ItemPool';\nimport type AdobeAsset from './AdobeAsset';\nimport type Project from '../projects/Project';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type Space from '../workspaces/Space';\nimport type AssetContext from './AssetContext';\nimport { VersionPatchTypes } from '../interface/AssetInterface';\nimport { SAMError, SAMErrorCode } from '../core/SAMError';\n\nconst MAX_LENGTH = 255;\nconst RESERVED_NAME_REGEX = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;\nconst RESERVED_CHAR_REGEX = /[\\\\/:*?\"|><]/;\n\nexport interface IFormatFileNameResult {\n    newName: string;\n    countUsed: number;\n}\n\nexport type NameConflictMap = Map<string, IFormatFileNameResult>;\n\n/** A map of asset IDs to their new names */\nexport type AssetRenameMap<T extends AdobeAsset | Space> = Map<T['id'], T['name']>;\n\ninterface CleanAssetNameOptions {\n    /** The name of the asset */\n    name: string;\n    /** The maximum length of the name, defaults to {@link MAX_LENGTH} */\n    maxLength?: number;\n    /** Whether to validate the name after cleaning. Defaults to false. If true and the name is invalid then an error will be thrown. */\n    shouldValidate?: boolean;\n}\n\nexport function validatePlatformRepoName(name: string) {\n    return (name.length > 0\n        && name.length <= MAX_LENGTH\n        && !RESERVED_NAME_REGEX.test(name)\n        && !RESERVED_CHAR_REGEX.test(name));\n}\n\nexport type ValidateAssetNameOptions = {\n    /** The name to validate */\n    name: string;\n    /** The asset ID of the asset to validate */\n    assetId?: string;\n    /** The list of assets to validate against */\n    assetList?: AdobeAsset[];\n    /** The locale to use for validation */\n    locale?: string;\n    /** Function to get the name of other assets to validate against */\n    getOtherAssetName?: (asset: AdobeAsset) => string;\n};\n\nconst PATH_REGEX = /^(.*\\/)?(.*?)(?:[\\u00A0][^.]*)?(\\.[^.]*)?$/;\n\n/**\n * Called by SAM to get new name according to the specified format and counter\n * @param fullPath path of the asset, it can be full path/relative path/filename\n * @param format format should contain %@ and %d\n *      %@ to be replace with filename\n *      %d to be replace with supplied counter. counter value will change in following cases:\n *          - filename matches the format and counter supplied. counter will increment by 1\n *          - filename matches the formatWithoutCount and counter = 0. counter will be made 1\n *            e.g name = test copy, format = %@ copy %d, counter = 0 -> newName = test copy 1, countUsed = 1\n * @param counter count to be used in newName\n * @returns the IFormatFileNameResult object which contains new name and count used in new name\n */\nexport function formatFileName(fullPath: string, format: string, counter: number): IFormatFileNameResult {\n    // create regex from client passed format\n    function getRegexFormat(format: string, extPresent: boolean) {\n        // replace '(', ')' with backspace '\\(', '\\)'\n        let regexFormat = format.replace(/[()]/g, '\\\\$&');\n        // insert match patern for %d and %@\n        regexFormat = regexFormat.replace('%d', '([0-9]+)');\n        regexFormat = regexFormat.replace('%@', '(.*)?');\n        // if extPresent is true, we expect to find extension, otherwise it is optional\n        regexFormat = regexFormat + (extPresent ? '(\\\\.[^.]*)$' : '(\\\\.[^.]*)?$');\n        return regexFormat;\n    }\n    const extPresent = fullPath.lastIndexOf('.') > fullPath.lastIndexOf('/');\n    const regexFormat = getRegexFormat(format, extPresent);\n\n    // remove count from string\n    const formatWithoutCount = format.replace(/ [^ ]*$/, '');\n    const regexFormatWithoutCount = getRegexFormat(formatWithoutCount, extPresent);\n\n    // get parsed result\n    let result = fullPath.match(regexFormat);\n    let resultMatchedRegexWithoutCount: boolean = false;\n    if (result === null) {\n        result = fullPath.match(regexFormatWithoutCount);\n        resultMatchedRegexWithoutCount = result !== null;\n    }\n    let newPath: string = '';\n    let fileExtension: string = '';\n    if (result) {\n        let path: string = '';\n        let extension: string = '';\n        let currentCount: string = '';\n        if (resultMatchedRegexWithoutCount) {\n            [ , path, extension ] = result;\n        } else {\n            [ , path, currentCount, extension ] = result;\n        }\n        newPath = path;\n        fileExtension = extension;\n        if (resultMatchedRegexWithoutCount && counter === 0) {\n            // since the name does not contain the count\n            // but matches the regex without count, so\n            // if counter=0, next name in iteration is with counter=1\n            counter = 1;\n        } else if (!resultMatchedRegexWithoutCount && parseInt(currentCount) === counter) {\n            // since the name matches the format with count\n            // we should skip the counter that matches the current name\n            counter += 1;\n        }\n    } else {\n        const [ , directory, filename, extension ] = fullPath.match(PATH_REGEX)!; // All strings match the regexp above\n        newPath = `${directory || ''}${filename || ''}`;\n        fileExtension = extension;\n    }\n    let newName = '';\n    if (counter !== 0) {\n        newName = format.replace('%@', `${newPath || ''}`);\n        newName = newName.replace('%d', counter.toString());\n    } else {\n        newName = formatWithoutCount.replace('%@', `${newPath || ''}`);\n    }\n    return {\n        newName: `${newName || ''}${fileExtension || ''}`,\n        countUsed: counter\n    } as IFormatFileNameResult;\n}\n\n/**\n * Called to get newName as per format in case of batch ops. It considers name of other files as well in the operation for finding conflicts\n * @param core SAMCore\n * @param assetId Asset Id\n * @param newName FileName\n * @param sameFolder true if copying in same folder\n * @param assetConflictMap It saves the newName and count used for all files in batch\n */\nexport function batchFormatFileName(\n    core: ISAMCorePrivate,\n    assetId: string,\n    newName: string,\n    sameFolder: boolean,\n    assetConflictMap: NameConflictMap\n): string {\n    let localCounter = assetConflictMap.get(assetId)?.countUsed || 0;\n    let conflictWithOtherFilesInBatch: boolean = false;\n    const conflictedAssetIds: string[] = [];\n    // check if we are copying in the same folder\n    // if yes, then it should follow ASSET_COPY_NAME_FORMAT i.e. %@ copy (%d)\n    // if no and conflict, then it should follow ASSET_CONFLICT_NAME_FORMAT i.e. %@ (%d)\n    do {\n        const formatFileResult = sameFolder ? formatFileName(newName, core._environment.getValue('ASSET_COPY_NAME_FORMAT'), localCounter)\n            : (localCounter > 0 ? formatFileName(newName, core._environment.getValue('ASSET_CONFLICT_NAME_FORMAT'), localCounter) : { newName, countUsed: localCounter });\n        newName = formatFileResult.newName;\n        localCounter = formatFileResult.countUsed;\n\n        conflictWithOtherFilesInBatch = false;\n        for (const [ key, value ] of assetConflictMap) {\n            if (value.newName === newName) {\n                conflictWithOtherFilesInBatch = true;\n                conflictedAssetIds.push(key);\n                break;\n            }\n        }\n\n        if (conflictWithOtherFilesInBatch) {\n            localCounter++;\n        } else {\n            assetConflictMap.set(assetId, formatFileResult);\n        }\n    } while (conflictWithOtherFilesInBatch);\n\n    for (const id of conflictedAssetIds) {\n        // we should update count of all files which this file conflicted with\n        // so that they also start with the new count next time\n        const currentValue = assetConflictMap.get(id);\n        assetConflictMap.set(id, { newName: currentValue!.newName, countUsed: localCounter });\n    }\n    return newName;\n}\n\nconst ARCHIVE_GUID_REGEX = /^(.*)\\^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[12345][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;\n\n// Archived assets get a guid suffix appended, so need to remove it when restoring\nexport function removeArchiveGuidFromName(name: string) {\n    const match = name.match(ARCHIVE_GUID_REGEX);\n    return match ? match[1] : name;\n}\n\n// Clients that haven't yet migrated to R-API still use the old archive locations when deleting assets (as a 2-step delete).\n// These locations are treated as discarded by SAM.js, but to implement recover() we need to know where to move the assets back to.\n// This is a mapping from the archive location to the restore location.\nconst ARCHIVE_TO_RESTORE_LOCATION: { [s: string]: string } = {\n    'cloud-content-archive': 'cloud-content',\n    'assets-archive': 'assets',\n    'archive': 'files'\n};\n\nexport function getRestorePath(path: string, newName?: string): string | undefined {\n    const newPath = path.split('/');\n\n    // Paths always start with \"/\" so newPath[0] is ''\n    // ESM paths are of the form /users/<userid>/...\n    const archiveIndex = newPath[1] === 'users' ? 3 : 1;\n    const restoreFolder = ARCHIVE_TO_RESTORE_LOCATION[newPath[archiveIndex]];\n    if (!restoreFolder) {\n        // Not archived, so no restore location\n        return undefined;\n    }\n\n    newPath[archiveIndex] = restoreFolder;\n    newPath[newPath.length - 1] = newName || removeArchiveGuidFromName(newPath[newPath.length - 1]);\n    return newPath.join('/');\n}\n\n/**\n * Replaces the ending filename in a path with the newName\n * and returns the result as a single string.\n *\n * @param newName\n * @param asset\n * @returns\n */\nexport function renameFileInPath(newName: string, asset: AdobeAsset | Project): string {\n    const path = asset.repoPath.split('/').slice(0, -1);\n    path.push(newName);\n    return path.join('/');\n}\n\n/**\n * Updates the cached descendents of the provided asset.\n *\n * @param param.assetPool Asset pool where items are to be udpated\n * @param param.asset The target asset to check for descendants.\n * @param param.session The update session\n * @param param.basePath The new base path string.\n * @returns\n */\ntype UpdateCachedDescendentsOperation =\n  | { type: 'discard' }\n  | { type: 'restore'; newPath?: string }\n  | { type: 'rename'; newPath: string }\n  | { type: 'move'; newPath: string };\n\nexport function updateCachedDescendents(params: {\n    operation: UpdateCachedDescendentsOperation,\n    assetPool: ItemPool<AdobeAsset>,\n    asset: AdobeAsset,\n    session: IUpdateSession<AdobeAsset>,\n    assetContext: AssetContext\n}) {\n    const { assetPool, asset, session, operation, assetContext } = params;\n    if (!asset.isFolder || !asset.repoPath.trim()) {\n        // The asset must be a folder with a non-empty path\n        return;\n    }\n\n    // make sure we update the repo:path of all the descendants of this folder\n    assetPool.forEach(item => {\n        if (\n            item.repoPath.startsWith(asset.repoPath + '/') // make sure the item is a descendant of the asset\n        ) {\n            switch (operation.type) {\n            case 'move':\n            case 'rename': {\n                // Used by both rename and move operations.\n                // Checking if the item's repoPath starts with the folder's repo:path with '/' appended\n                // this also rules out the folder itself.\n                if (!item.repoPath.startsWith(operation.newPath)) {\n                    // We need to take care of recursive folders with the same name as well\n                    const newChildPath = item.repoPath.replace(asset.repoPath, operation.newPath);\n                    assetContext._adobeAssetUpdater.updateLocalItem(session, item, { 'repo:path': newChildPath });\n\n                    // @note - RE Project Moves: It would be ideal to update the ancestor ids here but the Projects service does not\n                    // return ancestor ids in any of it's results. So if we move a project into another project,\n                    // we have no idea what the original ancestor ids were and what they are now so we can't update them.\n                }\n                break;\n            }\n            case 'discard': {\n                // If item is a descendant of the asset and it is ACTIVE, set repo:state to DISCARDED_PARENT.\n                // We do not want to modify the repo:state of assets that were directly discarded (DISCARDED),\n                // and we don't need to update the repo:state of assets that are already discarded with parent (DISCARDED_PARENT).\n                if (item.ancestorIDs?.includes(asset.id) && !item.isDiscarded) {\n                    assetContext._adobeAssetUpdater.updateLocalItem(session, item, { 'repo:state': 'DISCARDED_PARENT' });\n                }\n                break;\n            }\n            case 'restore': {\n                // Restore operations for assets may include a new path to restore to,\n                // due to unarchiving the parent folder or a name conflict upon parent folder restore.\n                if (operation.newPath) {\n                    assetContext._adobeAssetUpdater.updateLocalItem(session, item, { 'repo:path': item.repoPath.replace(asset.repoPath, operation.newPath) });\n                }\n                // If any children were originally discarded along with the parent folder ('repo:state': 'DISCARDED_PARENT'),\n                // update their repo:state to 'ACTIVE'. Children that were directly discarded should remain 'DISCARDED'.\n                if (item._isDiscardedWithParent()) {\n                    assetContext._adobeAssetUpdater.updateLocalItem(session, item, { 'repo:state': 'ACTIVE' });\n                }\n                break;\n            }\n            }\n        }\n    });\n}\n\nexport const getBatchRenamedAssetName = <Item extends AdobeAsset | Space>(item: Item, map: AssetRenameMap<Item>): Item['name'] => {\n    return map.has(item.id) ? map.get(item.id)! : item.name;\n};\n\n/**\n     * Creates the jsonParams array for milestone operations\n     * @param versionId The version ID to set the milestone on\n     * @param hasExistingMilestone Whether the version already has a milestone\n     * @param label The milestone label\n     * @param description The milestone description\n     * @returns The jsonParams array for the patch operation\n     * @package -- only for use in SAM.js\n     */\nexport function createMilestoneJsonParams(versionId: string, hasExistingMilestone: boolean, label: string, description: string) {\n    return [ {\n        op: hasExistingMilestone ? VersionPatchTypes.replace : VersionPatchTypes.add,\n        path: `/children/version=${versionId}/milestone`,\n        value: { label, description }\n    } ];\n}\n\n/**\n * Determine if the given name is valid\n *  - Name cannot contain only whitespace\n *  - Name must adhere to asset naming rules\n *  - Name cannot end in a period\n *  - The name must be unique within the parent asset\n *  - If the name is a duplicate of an asset with the same given assetId, it is valid\n *  - If the name is a duplicate of an asset with a different given assetId, it is invalid\n *  - If assetList is not provided, it does not throw an error unless the name is malformed\n * @param param.name The name to validate. Name can include extensions.\n * @param param.assetId The ID of the asset to validate against\n * @param param.assetList The list of assets to validate against\n * @param param.locale The locale to use for validation\n * @param param.getOtherAssetName A function to get the name of the asset to validate against\n * @throws {SAMError} if the name is invalid or not unique\n * @package -- only for use in SAM.js\n */\nexport function validateAssetName({ name, assetId, assetList, locale, getOtherAssetName }: ValidateAssetNameOptions): void {\n    // Name cannot have leading or trailing whitespace\n    const trimmedName = name.trim();\n    if (trimmedName.length === 0) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The asset name cannot be blank.');\n    }\n    // Name must adhere to asset naming rules\n    if (!validatePlatformRepoName(trimmedName)) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The asset name is an invalid platform repo name.');\n    }\n    // Name cannot end in a period\n    if (trimmedName.endsWith('.')) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The asset name cannot end with a period.');\n    }\n\n    // if assetList is not provided, we can't validate uniqueness. So it does not throw an error\n    const matchingAsset = assetList?.find((asset: AdobeAsset) => {\n        const assetName = (getOtherAssetName?.(asset) || asset.name);\n        return assetName.toLocaleLowerCase(locale) === trimmedName.toLocaleLowerCase(locale);\n    });\n    if (matchingAsset) {\n        if (!assetId || matchingAsset.id !== assetId) {\n            throw SAMError.create(SAMErrorCode.CONFLICT, 'The asset name must be unique within the parent asset.');\n        }\n    }\n}\n\n/**\n * Cleans an asset name by removing reserved characters and truncating the name to the specified length.\n * @throws {SAMError} When {@link shouldValidate} is true and if the name is invalid\n */\nexport const cleanAssetName = ({ name, maxLength = MAX_LENGTH, shouldValidate = false }: CleanAssetNameOptions) => {\n    // RESERVED_NAME_REGEX is not used here since replacing it would result in an empty string\n    const cleanedName = name.replaceAll(new RegExp(RESERVED_CHAR_REGEX, 'g'), '')\n        .substring(0, maxLength)\n        // eslint-disable-next-line no-control-regex\n        .replace(/[\\u{0000}-\\u{001F}|\\u{007F}]+/gu, '') // Replace invalid unicode characters\n        .replace(/[\\s|.]+$/g, ''); // Replace trailing periods and whitespace\n\n    if (shouldValidate) {\n        validateAssetName({ name: cleanedName });\n    }\n\n    return cleanedName;\n};\n\n/**\n * Checks if a path is a top-level folder\n * @param path The path to check\n * @returns true if the path matches /, /xyz, /users/xyz, or /users/xyz/xyz\n */\nexport function isTopLevelFolder(path: string): boolean {\n    return /^(\\/|\\/users\\/[^/]+|\\/users\\/[^/]+\\/[^/]+|\\/[^/]+)$/.test(path);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * In UXP `url.searchParams` does not save parameters correctly.\n * This function applies the search parameters to the URL in a UXP-safe way.\n * @see https://jira.corp.adobe.com/browse/UXP-19246\n */\nexport default function setURLSearchParams(url: URL, params: Record<string, string>) {\n    // UXP's .searchParams doesn't save when the URL points to an external resource,\n    // but we can create URLSearchParams unattached to a URL, and then apply it.\n    const searchParams = new URLSearchParams(url.search);\n    for (const [ key, value ] of Object.entries(params)) {\n        searchParams.set(key, value);\n    }\n    url.search = searchParams.toString();\n    return url;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type jsonpatch from 'json-patch';\n\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport InterfaceBase from './InterfaceBase';\nimport type {\n    HeaderMap,\n    IServiceLink } from './LinkUtils';\nimport {\n    getLink,\n    getURLFromLinks,\n    JSON_MIME_TYPE,\n    JSON_PATCH_MIME_TYPE,\n    RelType\n} from './LinkUtils';\nimport type RepositoryInterface from './RepositoryInterface';\nimport type {\n    AssetLinks,\n    DirectoryListingRepoMetadata,\n    EmbedSpecifier,\n    IACPolicyResponse,\n    IAppMetadata,\n    IDiscardOperation,\n    IOperation,\n    IRestoreOperation,\n    ISAMOperationResult,\n    RepositoryMetadata\n} from './RepositoryModel';\nimport type {\n    AssetSubType,\n    AssetType,\n    IAdobeAssetOrderBy,\n    IAssetVersionOrderBy,\n} from './AssetModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { RenditionType, THUMBNAIL_SIZE } from '../utils/RenditionFetcher';\nimport type { IAssetVersionResponse } from '../assets/AssetVersionLoader';\nimport { formatFileName } from '../assets/AssetUtils';\nimport { isDeepEqual } from '../core/ObjectUtils';\nimport type Resource from '../assets/Resource';\nimport type { SAM } from '@ccx-public/component-types';\nimport type PerUserMetadataResource from '../assets/PerUserMetadataResource';\nimport setURLSearchParams from '../utils/searchParams';\nimport clamp from '../utils/clamp';\nimport type AdobeACE from '@sam-js-src/access-control/AdobeACE';\nimport type { AdobeACEMetadata, IAccessControlResponse } from '@sam-js-src/access-control/AccessControlModel';\nimport { DEFAULT_MAX_SINGLE_TRANSFER_SIZE, DEFAULT_MIN_SINGLE_TRANSFER_SIZE, type MilestoneProperties } from '../assets/AdobeAsset';\nimport type RenditionResource from '../assets/RenditionResource';\n\nexport function getBlockTransferThreshold(links: AssetLinks, preferredThreshold?: number): number {\n    // Get min and max single transfer sizes from links to use as limits.\n    const blockInitLink = links[RelType.BLOCK_INITIALIZE] ? getLink(links, RelType.BLOCK_INITIALIZE) as AssetLinks[RelType.BLOCK_INITIALIZE] : undefined;\n    const lowerLimit = blockInitLink ? blockInitLink['repo:minsingletransfersize'] : DEFAULT_MIN_SINGLE_TRANSFER_SIZE;\n    const upperLimit = blockInitLink ? blockInitLink['repo:maxsingletransfersize'] : DEFAULT_MAX_SINGLE_TRANSFER_SIZE;\n    // If provided, clamp preferred size to platform-defined limits to ensure a valid transfer size,\n    // else return platform-defined upper limit.\n    return preferredThreshold ? clamp(preferredThreshold, lowerLimit, upperLimit) : upperLimit;\n}\n\nexport const FOLDER_TYPE = 'application/vnd.adobecloud.directory+json';\nexport const FOLDER_ALTERNATE_TYPE = 'application/x-sharedcloud-collection+json';\n\nconst BLOCK_SIZE = 6000000;\nconst BULK_TRANSFER_MIME_TYPE = 'application/vnd.adobecloud.bulk-transfer+json';\n\nexport const DENY_SHARE_ACE = {\n    'repo:principal': 'all',\n    'repo:modifier': 'deny',\n    'repo:privileges': [\n        'write'\n    ],\n    'repo:relations': [ RelType.AC_POLICY ],\n    'repo:inheritance': 'deep'\n};\nexport const DENY_EDIT_ACE = {\n    'repo:principal': 'all',\n    'repo:modifier': 'deny',\n    'repo:privileges': [ 'write', 'delete' ],\n    'repo:relations': [\n        RelType.ANNOTATIONS,\n        RelType.APP_METADATA,\n        RelType.EMBEDDED_METADATA,\n        RelType.REPO_METADATA,\n        RelType.PRIMARY,\n        RelType.RENDITION\n    ],\n    'repo:inheritance': 'deep'\n};\nexport function getRestrictEditUserGrantACEs(userId: string) {\n    return [ {\n        'repo:principal': {\n            'xdm:provider': { '@id': 'https://ims-na1.adobelogin.com/' },\n            '@id': userId,\n            '@type': 'https://ns.adobe.com/adobecloudplatform/ims/user'\n        },\n        'repo:modifier': 'grant',\n        'repo:privileges': [ 'read', 'write' ],\n        'repo:relations': [ 'http://ns.adobe.com/adobecloud/rel/ac/policy' ],\n        'repo:inheritance': 'deep'\n    },\n    {\n        'repo:principal': {\n            'xdm:provider': { '@id': 'https://ims-na1.adobelogin.com/' },\n            '@id': userId,\n            '@type': 'https://ns.adobe.com/adobecloudplatform/ims/user'\n        },\n        'repo:modifier': 'grant',\n        'repo:privileges': [ 'read', 'write', 'delete' ],\n        'repo:relations': [\n            'http://ns.adobe.com/adobecloud/rel/annotations',\n            'http://ns.adobe.com/adobecloud/rel/metadata/application',\n            'http://ns.adobe.com/adobecloud/rel/metadata/embedded',\n            'http://ns.adobe.com/adobecloud/rel/metadata/repository',\n            'http://ns.adobe.com/adobecloud/rel/primary',\n            'http://ns.adobe.com/adobecloud/rel/rendition'\n        ],\n        'repo:inheritance': 'deep'\n    } ];\n}\n\n\nexport interface IBlockUploadInfo {\n    'repo:blocksize': number;\n    _links: {\n        [RelType.BLOCK_TRANSFER]: IServiceLink[];\n        [RelType.BLOCK_FINALIZE]: IServiceLink;\n        [RelType.BLOCK_EXTEND]: IServiceLink;\n    };\n}\n\ntype IPageOptions = {\n    limit: number;\n    start?: string;\n    version?: string;\n}\n\nexport interface IVersionPatchOperation {\n    op: VersionPatchTypes,\n    path: string,\n    jsonParams?: {\n        name?: string\n        description?: string\n    }\n}\n\nexport enum VersionPatchTypes {\n    add = 'add',\n    remove = 'remove',\n    replace = 'replace'\n}\n\ninterface IListingOptions<IOrderField> extends IPageOptions {\n    orderDirection: IOrderDirection;\n    orderBy: IOrderField;\n}\n\nexport interface AssetsListingOptions extends IListingOptions<IAdobeAssetOrderBy> {\n    type?: string[]; // If type is empty array, RAPI returns all type in response\n    filters?: {\n        assetTypes?: AssetType[];\n        excludeAssetTypes?: AssetType[];\n        assetSubTypes?: AssetSubType[];\n    };\n    embed?: EmbedSpecifier[];\n}\n\nexport interface ICustomRenditionURLTemplateOpts {\n    component_id?: string;\n    fragment?: string;\n    /** SHARED-3493 -- this parameter is undocumented and may not be available on all Assets. It is up to the client\n     * to know whether or not passing these parameters is appropriate, and whether or not it will have the desired\n     * effect.\n     */\n    transparentBackground?: string;\n    /** SHARED-3493 -- this parameter is undocumented and may not be available on all Assets. It is up to the client\n     * to know whether or not passing these parameters is appropriate, and whether or not it will have the desired\n     * effect.\n     */\n    c2paSign?: string;\n    version?: string;\n}\n\nexport interface ICustomRenditionHeaders {\n    [key: string]: string;\n}\n\nexport interface VersionsListingOptions extends IListingOptions<IAssetVersionOrderBy> { }\n\n/**\n * The object returned by getBlockUploadInfo().\n **/\nexport interface IBlockUploadInfoResult {\n    transferInfo: { url: IServiceLink, start: number, end: number }[];\n    finalizeHref: string;\n    blockSize: number;\n    initResponse: IBlockUploadInfo;\n}\n\nconst DefaultAssetsListingOptions: AssetsListingOptions = {\n    orderDirection: 'descending',\n    orderBy: 'storage:deviceModifyDate',\n    start: '',\n    limit: 0\n};\n\nconst DefaultVersionsListingOptions: VersionsListingOptions = {\n    orderDirection: 'descending',\n    orderBy: 'created',\n    start: '',\n    limit: 0,\n    version: ''\n};\n\nfunction createVersionTemplate(options?: Partial<VersionsListingOptions>) {\n    const userOptions: Partial<VersionsListingOptions> = { ...DefaultVersionsListingOptions, ...options };\n    const templateValues: any = createPageTemplate(userOptions);\n\n    templateValues.orderBy = getDirectionValue(userOptions);\n    templateValues.resource = RelType.VERSION;\n    return templateValues;\n}\n\nfunction createPageTemplate(options: Partial<AssetsListingOptions | VersionsListingOptions>) {\n    const templateValues: any = {};\n    const { start, limit, version } = options;\n    if (start) {\n        templateValues.start = start;\n    }\n    if (limit) {\n        templateValues.limit = limit;\n    }\n    if (version) {\n        templateValues.version = version;\n    }\n    return templateValues;\n}\n\nexport function getDirectionValue<IOrderField>(userOptions: Partial<IListingOptions<IOrderField>>) {\n    const directionFlag = userOptions.orderDirection === 'ascending' ? '+' : '-';\n    return directionFlag + userOptions.orderBy;\n}\n\nexport function getAssetsListingURL(links: any, options?: Partial<AssetsListingOptions>): string {\n    const userOptions: Partial<AssetsListingOptions> = { ...DefaultAssetsListingOptions, ...options };\n    const templateValues: any = createPageTemplate(userOptions);\n    templateValues.orderBy = getDirectionValue(userOptions);\n    templateValues.type = userOptions.type;\n    templateValues.embed = JSON.stringify(userOptions.embed);\n\n    // Currently service can only support one filter. Where possible, it will use server-side filtering so long as it\n    // is compatible with client-side filtering. USS/PLS should support multiple filters, and R-API might in the future.\n    const { assetTypes, excludeAssetTypes, assetSubTypes } = userOptions.filters || {};\n    // Note: Clients cannot provide both exclude and include assetTypes. Exclude filter matches the most items.\n    if (excludeAssetTypes?.length) {\n        // exclude the first item from the first result, any additional excludes will be handled client-side\n        templateValues.filter = `\"repo:assetType\"!=\"${excludeAssetTypes[0]}\"`;\n    } else if (assetTypes?.length === 1) {\n        // prefer assetType filter over assetSubType filter, as assetType is a superset of assetSubType\n        templateValues.filter = `\"repo:assetType\"==\"${assetTypes[0]}\"`;\n    } else if (!assetTypes?.length && assetSubTypes?.length === 1) {\n        templateValues.filter = `\"repo:assetSubType\"==\"${assetSubTypes[0]}\"`;\n    }\n\n    return getURLFromLinks(links, RelType.PAGE, templateValues);\n}\n\nexport function getAssetVersionsListingURL(links: any, options?: Partial<VersionsListingOptions>): string {\n    const templateValues = createVersionTemplate(options);\n    return getURLFromLinks(links, RelType.PAGE, templateValues);\n}\n\nexport type AssetRGNRelType = RelType.PRIMARY | RelType.REPO_METADATA | RelType.APP_METADATA;\n\nexport class TransferURLExpiredError extends Error {}\n\nexport default class AssetInterface extends InterfaceBase {\n    protected _useHighPriorityRequestsIfEnabled = true;\n\n    constructor(\n        private _rapi: RepositoryInterface,\n        private _assetId: string,\n        private _links: AssetLinks,\n        private _etag: string,\n        private _version?: string\n    ) {\n        super(_rapi._core);\n    }\n\n    get assetID(): string {\n        return this._assetId;\n    }\n\n    get links(): AssetLinks {\n        return this._links;\n    }\n\n    get etag(): string {\n        return this._etag;\n    }\n\n    async getChildAssets(options?: Partial<AssetsListingOptions>, resource?: Resource<Response>): Promise<DirectoryListingRepoMetadata> {\n        const href = getAssetsListingURL(this._links, options);\n        const response = await this._doGet(href, {\n            // Ensure browser doesn't automatically add If-None-Match, otherwise\n            // service may respond with cached data FROM ANOTHER USER.\n            // https://jira.corp.adobe.com/browse/ACPCSS-5544\n            // Also causes SAM-1813, SAM-2066\n            headers: { ['Cache-Control']: 'no-cache, no-store, max-age=0' },\n            resource\n        });\n\n        return response.json();\n    }\n\n    async getRepoMetadata(resource: Resource<RepositoryMetadata>): Promise<void> {\n        const href = getURLFromLinks(this._links, RelType.REPO_METADATA);\n        await this._doGet(href, { resource });\n\n        // Note: Do NOT use the ETag header in the repo metadata response, because that's the ETag for the repo metadata\n        // resource, not the asset itself. The ETag of the asset itself is inside the repo metadata response:\n        this._etag = resource.data['repo:etag'];\n    }\n\n    async getEmbeddedMetadata(resource: Resource<object>): Promise<void> {\n        const href = this.getURLWithVersion(this._links, RelType.EMBEDDED_METADATA);\n        // Embedded metadata is returned as application/rdf+xml by default - switch to JSON-LD\n        await this._doGet(href, { headers: { Accept: JSON_MIME_TYPE }, resource });\n    }\n\n    async getAppMetadata(resource: Resource<IAppMetadata>): Promise<void> {\n        const href = this.getURLWithVersion(this._links, RelType.APP_METADATA);\n        await this._doGet(href, { resource });\n    }\n\n    async patchAppMetadata(body: jsonpatch.OpPatch[]): Promise<Response> {\n        const href = getURLFromLinks(this._links, RelType.APP_METADATA);\n        return await this._doPatch(\n            href,\n            {\n                'Content-Type': JSON_PATCH_MIME_TYPE\n            },\n            JSON.stringify(body),\n            [ 204 ]\n        );\n    }\n\n    async getEffectivePermissions(resource: Resource<SAM.Permission>): Promise<void> {\n        const href = getURLFromLinks(this._links, RelType.AC_EFFECTIVE);\n        await this._doGet(href, { resource });\n    }\n\n    async getAssetPolicy(): Promise<Response> {\n        const href = getURLFromLinks(this._links, RelType.AC_POLICY);\n        return await this._doGet(href);\n    }\n\n    async getManifest(resource: Resource<any>): Promise<void> {\n        const href = this.getURLWithVersion(this._links, RelType.MANIFEST);\n        const headers: { [s: string]: string } = {};\n\n        await this._doGet(href, {\n            headers,\n            resource\n        });\n    }\n\n    async getVersions(options?: Partial<VersionsListingOptions>): Promise<IAssetVersionResponse> {\n        const href = getAssetVersionsListingURL(this._links, options);\n        const response = await this._doGet(href);\n        return response.json();\n    }\n\n    async getPerUserMetadata(resource: PerUserMetadataResource): Promise<void> {\n        const href = getURLFromLinks(this._links, RelType.PERUSER_METADATA);\n        await this._doGet(href, { headers: { 'Content-Type': JSON_MIME_TYPE }, resource });\n    }\n\n    async restoreVersionManifest(versionManifestLink: string) {\n        // first fetch the version manifest\n        const response = await this._doGet(versionManifestLink, {});\n        const versionManifest = await response.json();\n\n        //doput to current asset manifest url\n        const assetManifest = getURLFromLinks(this.links, RelType.MANIFEST);\n        await this._doPut(assetManifest, {\n            'Content-Type': 'application/vnd.adobe.dcx-manifest+json',\n            'If-Match': '*'\n        }, JSON.stringify(versionManifest), [ 204 ]);\n    }\n\n    async getVersion(versionId: string): Promise<IAssetVersionResponse> {\n        const href = getAssetVersionsListingURL(this._links, { version: versionId });\n        const response = await this._doGet(href);\n        return response.json();\n    }\n\n    async patchVersion(body?: IVersionPatchOperation[]): Promise<Response> {\n        const href = getURLFromLinks(this.links, RelType.VERSION);\n        const response = await this._doPatch(href, {\n            'Content-Type': JSON_PATCH_MIME_TYPE\n        }, JSON.stringify(body), [ 204 ]);\n        return response;\n    }\n\n    async createFolder(relativePath: string, renameOnConflict: boolean = false): Promise<RepositoryMetadata | undefined> {\n        const href = getURLFromLinks(this._links, RelType.CREATE, {\n            path: relativePath,\n            intermediates: 'true',\n            respondWith: RelType.REPO_METADATA,\n            nameConflictPolicy: renameOnConflict ? 'rename' : 'cancel'\n        });\n        const response = await this._doPost(href, {\n            'Content-Type': FOLDER_TYPE\n        }, undefined, [ 200, 201 ]);\n\n        // when 200 that means asset created, but error while fetching metadata\n        return response.status === 201 ? await response.json() : undefined;\n    }\n\n    private async extendTransferUrls(extendLink: string, useBlockStore: boolean = false): Promise<IBlockUploadInfo> {\n        const headers: HeaderMap = {};\n        if (useBlockStore) {\n            headers['directive'] = 'use-block-store';\n        }\n        const response = await this._doPost(extendLink, headers, undefined, [ 200 ]);\n        return await response.json();\n    }\n\n    private async _uploadIndividualBlock(href: string, file: Blob, start: number, end: number, useBlockStore?: boolean): Promise<Response> {\n        const headers: HeaderMap = {};\n        return await this._doPut(href, headers, file.slice(start, end),\n            useBlockStore ? [ 200, 412 ] : [ 200 ],\n            true, {\n                handleError: async (response) => {\n                    if (response.status === 403) {\n                        const errorText = await response.text();\n                        if (errorText.includes('<Message>Request has expired</Message>')) {\n                            // Throw a unique error to handle the expired transfer url in _blockUpload\n                            throw new TransferURLExpiredError('Transfer URL has expired');\n                        }\n                    }\n                }\n            });\n    }\n\n    async _blockUpload(\n        file: Blob,\n        relativePath: string,\n        mediaType: string,\n        renameOnConflict: boolean = false,\n        isUpdate: boolean,\n        useBlockStore?: boolean,\n        milestoneProperties?: MilestoneProperties\n    ): Promise<RepositoryMetadata | undefined> {\n        const uploadInfoResult = await this.getBlockUploadInfo(relativePath, file.size, isUpdate, mediaType, useBlockStore, renameOnConflict, milestoneProperties);\n        const blockSize = uploadInfoResult.initResponse['repo:blocksize'];\n        const size = file.size;\n        const totalBlocks = Math.ceil(size / blockSize);\n        let blockIndex = 0;\n\n        // Only send a max of 3 blocks simultaneously, so the browser's request queue doesn't get\n        // over-saturated, and intermittent outages (like wifi blips) will only cause up to 3 requests to\n        // need retries.\n        const MAX_SIMULTANEOUS_BLOCKS = 3;\n        const MAX_RETRIES = 3; // Add maximum retry count\n        let retryCount = 0;\n\n        while (blockIndex < totalBlocks) {\n            try {\n                // Calculate how many blocks to upload in this batch\n                const blocksInBatch = Math.min(MAX_SIMULTANEOUS_BLOCKS, totalBlocks - blockIndex);\n\n                // Create and execute promises for this batch of blocks\n                const blockPromises = Array.from({ length: blocksInBatch }, (_, index) => {\n                    const currentBlockIndex = blockIndex + index;\n                    return this._uploadIndividualBlock(\n                        uploadInfoResult.transferInfo[currentBlockIndex].url.href,\n                        file,\n                        currentBlockIndex * blockSize,\n                        Math.min((currentBlockIndex + 1) * blockSize, size),\n                        useBlockStore\n                    );\n                });\n\n                // Wait for all blocks in this batch to complete\n                await Promise.all(blockPromises);\n                blockIndex += blocksInBatch;\n                retryCount = 0; // Reset retry count on successful batch\n            } catch (e) {\n                // If any block in the batch failed due to expired URLs\n                if (e instanceof TransferURLExpiredError) {\n                    retryCount++;\n                    if (retryCount > MAX_RETRIES) {\n                        throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Maximum retry attempts exceeded for block upload');\n                    }\n\n                    // Get new URLs for all remaining blocks\n                    const url = getURLFromLinks(uploadInfoResult.initResponse._links, RelType.BLOCK_EXTEND, { size: String(size) });\n                    const newBlockInfo = await this.extendTransferUrls(url, useBlockStore);\n\n                    // Update the transfer info with new URLs\n                    uploadInfoResult.transferInfo = newBlockInfo._links[RelType.BLOCK_TRANSFER].map((link, index) => {\n                        const start = index * blockSize;\n                        const end = Math.min(size, start + blockSize);\n                        return { url: link, start, end };\n                    });\n\n                    // Resume the current batch with new URLs\n                    continue;\n                } else {\n                    throw e;\n                }\n            }\n        }\n\n        return await this.finalizeBlockUpload(uploadInfoResult.finalizeHref, uploadInfoResult.initResponse, isUpdate, useBlockStore);\n    }\n\n    /**\n     * Imports a file into the repository.\n     *\n     * @param file - The file blob or URL to import\n     * @param relativePath - The name to give the imported file\n     * @param renameOnConflict - Specifies if name conflict resolution should be handled by ACP\n     * @param mediaType - Optional media type of the file\n     * @param preferredBlockTransferThreshold - Size threshold for block transfer (defaults to DEFAULT_MAX_SINGLE_TRANSFER_SIZE)\n     * @param useBlockStore - If true, uses block store for upload\n     * @returns Promise resolving to the repository metadata of the imported file\n     */\n    async importFile(\n        file: Blob,\n        relativePath: string,\n        renameOnConflict: boolean,\n        mediaType?: string,\n        preferredBlockTransferThreshold: number = DEFAULT_MAX_SINGLE_TRANSFER_SIZE,\n        useBlockStore?: boolean,\n        milestoneProperties?: MilestoneProperties\n    ): Promise<RepositoryMetadata | undefined> {\n        // check if the size of the file to be imported is greater than maximum allowed transfer size.\n        const blockUploadTransferThreshold = getBlockTransferThreshold(this._links, preferredBlockTransferThreshold);\n\n        if (file.size >= blockUploadTransferThreshold) {\n            // The platform requires a block upload for components greater than threshold.\n            // See https://git.corp.adobe.com/pages/CAF/api-spec/#block-upload\n            return this._blockUpload(file, relativePath, mediaType ?? file.type, renameOnConflict, false, useBlockStore, milestoneProperties);\n        }\n\n        const versionHistoryPatch = milestoneProperties ? {\n            'milestone:label': milestoneProperties.label,\n            ...(milestoneProperties.description ? { 'milestone:description': milestoneProperties.description } : {})\n        } : {};\n\n        const href = getURLFromLinks(this._links, RelType.CREATE, {\n            path: relativePath,\n            respondWith: RelType.REPO_METADATA,\n            nameConflictPolicy: renameOnConflict ? 'rename' : 'cancel',\n            ...(milestoneProperties ? { versionHistoryPatch } : {})\n        });\n        const response = await this._doPost(href, {\n            'Content-Type': mediaType ?? file.type\n        }, file, [ 200, 201 ]);\n\n        // when 200 that means asset created, but error while fetching metadata\n        return response.status === 201 ? await response.json() : undefined;\n    }\n\n    async updateFile(\n        file: Blob,\n        mediaType?: string,\n        preferredBlockTransferThreshold: number = DEFAULT_MAX_SINGLE_TRANSFER_SIZE,\n        useBlockStore: boolean = false\n    ): Promise<RepositoryMetadata | undefined> {\n        // check if the size of the file to be imported is greater than maximum allowed transfer size.\n        const blockUploadTransferThreshold = getBlockTransferThreshold(this._links, preferredBlockTransferThreshold);\n\n        if (file.size >= blockUploadTransferThreshold) {\n            // The platform requires a block upload for components greater than threshold.\n            // See https://git.corp.adobe.com/pages/CAF/api-spec/#block-upload\n            return this._blockUpload(file, '', mediaType ?? file.type, true, useBlockStore);\n        } else {\n            const { metaData } = await this.commitFileChanges(file, this.etag);\n            if (!metaData) {\n                // If we didn't get metadata in the response, fetch it\n                const href = getURLFromLinks(this._links, RelType.REPO_METADATA);\n                const response = await this._doGet(href);\n                return response.json();\n            }\n            return metaData;\n        }\n    }\n\n    async getBlockUploadInfo(\n        name: string,\n        size: number,\n        isUpdate: boolean,\n        mediaType?: string,\n        useBlockStore?: boolean,\n        renameOnConflict?: boolean,\n        /**\n         * When included this file will be created with the latest version as a milestone.\n         */\n        milestoneProperties?: MilestoneProperties\n    ): Promise<IBlockUploadInfoResult> {\n        const initialBlockUploadHref = getURLFromLinks(this._links, RelType.BLOCK_INITIALIZE);\n        const initBody: any = {\n            'repo:size': size,\n            'repo:blocksize': BLOCK_SIZE,\n            'repo:reltype': RelType.PRIMARY,\n            'dc:format': mediaType // Required for updates, optional for new uploads\n        };\n\n        const headers: HeaderMap = {\n            'Content-Type': BULK_TRANSFER_MIME_TYPE\n        };\n\n        if (useBlockStore) {\n\n            // Remove the repo:blocksize prop when using block store, otherwise the service will throw an error.\n            delete initBody['repo:blocksize'];\n            headers['directive'] = 'use-block-store';\n        }\n\n        const initResponse = await this._doPost(initialBlockUploadHref, headers, JSON.stringify(initBody), [ 200 ]);\n        const blockUploadInfo: IBlockUploadInfo = await initResponse.json();\n        const { 'repo:blocksize': blockSize, _links } = blockUploadInfo;\n\n        // Calculate the start and end of each block.\n        const transferInfo = _links[RelType.BLOCK_TRANSFER].map((link, index) => {\n            const start = index * (useBlockStore ? blockSize : BLOCK_SIZE);\n            const end = Math.min(size, start + (useBlockStore ? blockSize : BLOCK_SIZE));\n            return { url: link, start, end };\n        });\n\n        const versionHistoryPatch = milestoneProperties ? {\n            'milestone:label': milestoneProperties.label,\n            ...(milestoneProperties.description ? { 'milestone:description': milestoneProperties.description } : {})\n        } : {};\n\n        const finalizeHref = getURLFromLinks(_links, RelType.BLOCK_FINALIZE, {\n            respondWith: RelType.REPO_METADATA,\n            nameConflictPolicy: renameOnConflict ? 'rename' : 'cancel',\n            ...(!isUpdate ? { path: name } : {}),\n            ...(milestoneProperties ? { versionHistoryPatch } : {})\n        });\n\n        return {\n            transferInfo,\n            finalizeHref,\n            blockSize,\n            initResponse: blockUploadInfo\n        };\n    }\n\n    /**\n     * Finalizes a block upload operation by sending the finalize request to the server.\n     * This is an internal method used by _blockUpload to complete the upload process.\n     *\n     * @param finalizeHref - The URL to send the finalize request to\n     * @param initResponse - The initial block upload info response containing block size and links\n     * @param isUpdate - Whether this is an update operation (true) or a new file upload (false)\n     * @param useBlockStore - If true, uses \"block store\" variant of block uploads and includes the use-block-store directive\n     * @returns Promise resolving to the repository metadata of the uploaded file, or undefined for updates\n     */\n    async finalizeBlockUpload(finalizeHref: string, initResponse: IBlockUploadInfo, isUpdate: boolean, useBlockStore?: boolean): Promise<RepositoryMetadata | undefined> {\n        const headers: HeaderMap = {\n            'Content-Type': BULK_TRANSFER_MIME_TYPE\n        };\n\n        // Add directive when useBlockStore is true\n        if (useBlockStore) {\n            headers['directive'] = 'use-block-store';\n        }\n\n        const response = await this._doPost(finalizeHref, headers, JSON.stringify(initResponse), [ 200, 201 ]);\n\n        return isUpdate ? undefined : response.json();\n    }\n\n    /**\n     * Gets a presigned URL for downloading a block of the asset.\n     * @param url - The URL to get the presigned URL from\n     * @param presignedUrlExpirationSeconds - Time-to-live for the presigned URL in seconds. If not provided, uses service default.\n     * @returns Promise resolving to the presigned URL\n     */\n    async getBlockDownloadURL(url: string, presignedUrlExpirationSeconds?: number): Promise<string> {\n        const headers: HeaderMap = {};\n        if (presignedUrlExpirationSeconds !== undefined) {\n            headers['Presigned-URL-TTL'] = presignedUrlExpirationSeconds.toString();\n        }\n        const response = await this._doGet(url, { headers });\n        const json = await response.json();\n        if (!json?.href) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Cannot get block download URL');\n        }\n        return json.href;\n    }\n\n    async getContent(resource: Resource<Blob>): Promise<void> {\n        const href = this.getURLWithVersion(this._links, RelType.PRIMARY);\n        await this._doGet(href, { resource });\n    }\n\n    async getResourceGenerationNumber(relType: AssetRGNRelType): Promise<string | undefined> {\n        const href = getURLFromLinks(this._links, relType);\n        const response = await this._doHead(href);\n        return response.headers.get('resource-generation') ?? undefined;\n    }\n\n    async commitFileChanges(file: Blob, localETag?: string): Promise<{ metaData: RepositoryMetadata, eTag: string | null}> {\n        const href = getURLFromLinks(this._links, RelType.PRIMARY);\n        const headers: HeaderMap = {\n            'Content-type': file.type\n        };\n        localETag && (headers['If-Match'] = localETag);\n        const response = await this._doPut(href, headers, file, [ 200, 201, 204 ]);\n        return { metaData: response.status === 201 ? await response.json() : undefined, eTag: response.headers.get('ETag') };\n    }\n\n    async restore(name: string, _counter: number = 0): Promise<RepositoryMetadata> {\n        const operation: IRestoreOperation = {\n            op: 'restore',\n            target: { 'repo:assetId': this.assetID },\n            name\n        };\n        try {\n            const repoMetadata = (await this.runOperation(operation)).asset!;\n            return repoMetadata;\n        } catch (error) {\n            if ((error as SAMError).code === SAMErrorCode.CONFLICT) {\n                const { newName, countUsed } = formatFileName(\n                    name,\n                    this._core._environment.getValue('ASSET_CONFLICT_NAME_FORMAT'),\n                    _counter\n                );\n                return this.restore(newName, countUsed);\n            }\n            throw error;\n        }\n    }\n\n    async discard(): Promise<RepositoryMetadata> {\n        const operation: IDiscardOperation = {\n            op: 'discard',\n            target: { 'repo:assetId': this.assetID }\n        };\n        const { asset } = await this.runOperation(operation);\n        return asset!;\n    }\n\n    async runOperation(op: IOperation): Promise<ISAMOperationResult> {\n        const response = await this._rapi.runOperation(op);\n        const { asset, error } = response[0];\n        if (!(asset || error)) {\n            throw SAMError.wrapErrorIfNeeded(SAMErrorCode.UNKNOWN, 'Missing Asset metadata in operation response', error);\n        } else if (error) {\n            throw error;\n        }\n        return response[0];\n    }\n\n    async runOperationWithEmptyResponse(op: IOperation): Promise<void> {\n        await this._rapi.runOperation(op);\n    }\n\n    async getRendition(resource: RenditionResource): Promise<void> {\n        const renditionURL = getURLFromLinks(\n            this._links,\n            RelType.RENDITION, {\n                size: String(resource.size),\n                type: resource.type\n            }\n        );\n\n        const newURL = new URL(renditionURL);\n        setURLSearchParams(newURL, { etag: this.etag });\n        // Since we have an etag, the resource is supposed to be immutable, so specifying 'force-cache'\n        // ensures that the browser will always use the cached version of the rendition if it exists.\n        // The service specifies \"max-age\"/\"immutable\" in its cache-control headers, but some\n        // browsers (perhaps older ones) don't appear to consistently respect those headers. See SAMJS-956.\n        await this._doGet(newURL.toString(), { resource, cache: 'force-cache' });\n    }\n\n    /**\n     * Use case: When clients need to fine tune the rendition requests for cases other than the lazy-load and cache\n     * mechanism in SAM. Clients are responsible for\n     *   1. Determining when these requests should be made – SAM will not attempt to automatically download renditions\n     *      requested with this method when etag or whatnot changes\n     *   2. Ensuring efficient use of server resources – clients should only make requests as needed and avoid papering\n     *      over issues with repeated calls\n     *   3. Parsing the Response – the image in the Response.body and any additional metadata embedded by the server\n     *   4. Caching the response – clients will need to use URL.createObjectURL() to make the response usable to render\n     *      in DOM. This causes the browser to keep the rendition in memory until they call URL.releaseObjectURL(url).\n     *      Failing to do so could cause memory leaks. To fine-tune the browser caching behavior, clients will need to\n     *      set explicit caching headers in the `additionalHeaders` parameter rather than relying on adding\n     *      cache-busting fake parameters to the URL.\n     *\n     * SAM.js will\n     *   1. Get the correct URL template for the AdobeAsset or AssetVersion and fill it with metadata from the\n     *      Asset/Version, plus additional data from `urlTemplateOptions`\n     *   2. Add the API key and auth token headers, as well as additional headers specified in `additionalHeaders`\n     *   3. Handle some auto-retries for error responses\n     *   4. Reject with SAMError if there is a service error that can't be resolved with retry\n     *\n     * @param size\n     * @param type\n     * @param urlTemplateOptions\n     * @param additionalHeaders\n     */\n    async getCustomRendition({\n        size = THUMBNAIL_SIZE,\n        type = RenditionType.PNG,\n        urlTemplateOptions = {},\n        additionalHeaders\n    }: {\n        size?: number;\n        type?: string;\n        urlTemplateOptions?: ICustomRenditionURLTemplateOpts;\n        additionalHeaders?: ICustomRenditionHeaders;\n    }): Promise<Response> {\n        const url = getURLFromLinks(\n            this._links,\n            RelType.RENDITION, {\n                size: String(size),\n                type,\n                ...urlTemplateOptions\n            }\n        );\n        return await this._doGet(url, { headers: additionalHeaders });\n    }\n\n    /**\n     * Clients may have a requirement to get the JSON object describing all the available sizes, rather than returning\n     * a JSON object describing only the specified size. Especially useful in case of fetching rendition resource of\n     * type \"application/vnd.adobe.ccv.videometadata\" for video assets\n     * @param type\n     * @param urlTemplateOptions\n     * @param additionalHeaders\n     */\n    async getAllCustomRenditions({\n        type,\n        urlTemplateOptions = {},\n        additionalHeaders\n    }: {\n        type?: string;\n        urlTemplateOptions?: ICustomRenditionURLTemplateOpts;\n        additionalHeaders?: ICustomRenditionHeaders;\n    }): Promise<Response> {\n        const url = type ? getURLFromLinks(\n            this._links,\n            RelType.RENDITION, {\n                type,\n                ...urlTemplateOptions\n            }\n        ) : getURLFromLinks(this._links, RelType.RENDITION, { ...urlTemplateOptions });\n        return await this._doGet(url, { headers: additionalHeaders });\n    }\n\n    async getAccessControlList(): Promise<IAccessControlResponse> {\n        const accessControlHref = getURLFromLinks(this._links, RelType.AC_POLICY);\n        const response = await this._doGet(accessControlHref, {\n            headers: {\n                'Content-Type': 'application/vnd.adobecloud.policy+json',\n                'If-Match': '*'\n            }\n        });\n        const responseJson = await response.json();\n        const accessControlResponse: IAccessControlResponse = {\n            'etag': response.headers.get('ETag') || '',\n            'repo:acl': responseJson['repo:acl']\n        };\n        return accessControlResponse;\n    }\n\n    /**\n     * @pacakge - used internally\n     */\n    public _getACPatchData(ace: AdobeACE | AdobeACEMetadata): {} {\n        return {\n            'repo:principal': ace.principal,\n            'repo:privileges': ace.privileges,\n            'repo:modifier': ace.modifier,\n            'repo:inheritance': ace.inheritance,\n            'repo:relations': ace.relations\n        };\n    }\n\n    async addAccessControlEntries(aces: AdobeACEMetadata[], aclEtag: string): Promise<void> {\n        const acesJSONPatch: jsonpatch.AddPatch[] = aces.map((ace: AdobeACEMetadata) => {\n            return {\n                op: 'add',\n                path: `/repo:acl/-`,\n                value: this._getACPatchData(ace)\n            };\n        });\n\n        await this._patchACL(acesJSONPatch, aclEtag);\n    }\n\n    async updateAccessControlList(aces: AdobeACE[], aclEtag: string): Promise<void> {\n        const acesJSONPatch: jsonpatch.ReplacePatch[]  = aces.map((ace: AdobeACE) => {\n            return {\n                op: 'replace',\n                path: `/repo:acl/${ace.id}`,\n                value: this._getACPatchData(ace)\n            };\n        });\n\n        await this._patchACL(acesJSONPatch, aclEtag);\n    }\n\n    async deleteAccessControlEntries(aces: AdobeACE[], aclEtag: string): Promise<void> {\n        const acesJSONPatch: jsonpatch.RemovePatch[] = aces.map((ace: AdobeACE) => {\n            return {\n                op: 'remove',\n                path: `/repo:acl/${ace.id}`,\n                value: this._getACPatchData(ace)\n            };\n        });\n\n        await this._patchACL(acesJSONPatch, aclEtag);\n    }\n\n    async setEditingInheritanceRestricted(restrictEdit: boolean, addCurrentUserAsEditor?: boolean): Promise<void> {\n        // API documentation: https://developers.corp.adobe.com/acp/acl-front-service/documentation/src/main/docs/swagger.json#operation/jsonPatchPolicy\n        const userId = this._core._environment.getValue('USER_ID');\n        if (restrictEdit) {\n            // NOTE: attempting to add these ACEs when they are already set has no effect\n            const addPatches: jsonpatch.AddPatch[] = [ {\n                op: 'add',\n                // Index for 'add' probably doesn't matter\n                path: '/repo:acl/0',\n                value: DENY_EDIT_ACE\n            }, {\n                op: 'add',\n                path: '/repo:acl/1',\n                value: DENY_SHARE_ACE\n            } ];\n            if (addCurrentUserAsEditor) {\n                const userACEs = getRestrictEditUserGrantACEs(userId);\n                addPatches.push({ op: 'add', path: '/repo:acl/2', value: userACEs[0] });\n                addPatches.push({ op: 'add', path: '/repo:acl/3', value: userACEs[1] });\n            }\n            await this._patchACL(addPatches);\n        } else {\n            // Find the index of the deny ACEs. This is critical to ensure only the desired ACEs get removed.\n            const { policyResponse, denyEditAceIndex, denyShareAceIndex } = await this._getEditingInheritanceRestrictedInfo();\n            // If either or both ACE is missing, the toggle is not on\n            if (denyEditAceIndex < 0 || denyShareAceIndex < 0) {\n                return;\n            }\n            const removePatches: jsonpatch.RemovePatch[] = [ {\n                op: 'remove',\n                path: `/repo:acl/${denyShareAceIndex}`\n            }, {\n                op: 'remove',\n                path: `/repo:acl/${denyEditAceIndex}`\n            } ];\n            // The patches must be sorted by index descending or else the wrong items will be removed, because they\n            // are applied in order. If we have acl = [A, B, C] and try to remove index 0 before 1, it will first remove\n            // A, making B be index 0; removing index 1 after that will erroneously remove C. Instead, removing 1 first\n            // will result in [A, C] and then removing index 0 will leave the desired [C] remaining.\n            removePatches.sort((ace1, ace2) => ace1.path < ace2.path ? 0 : -1);\n            await this._patchACL(removePatches, policyResponse.headers.get('etag') || undefined);\n        }\n    }\n\n    private async _patchACL(patches: jsonpatch.OpPatch[], etag?: string): Promise<void> {\n        const url = getURLFromLinks(this._links, RelType.AC_POLICY);\n        await this._doPatch(url,\n            {\n                'Content-Type': 'application/json-patch+json',\n                'If-Match': etag\n            },\n            JSON.stringify(patches),\n            [ 200 ]\n        );\n    }\n\n    async getEditingInheritanceRestricted(): Promise<boolean> {\n        const { denyEditAceIndex, denyShareAceIndex } = await this._getEditingInheritanceRestrictedInfo();\n        // both must be present for the toggle to be on\n        return denyEditAceIndex >= 0 && denyShareAceIndex >= 0;\n    }\n\n    private async _getEditingInheritanceRestrictedInfo() {\n        const policyResponse = await this.getAssetPolicy();\n        const acl = (await policyResponse.json() as IACPolicyResponse)['repo:acl'];\n        // Note: array order does not matter. To count as being on, all properties in DENY_EDIT_ACE and DENY_SHARE_ACE\n        // must be present, but additional properties can be present that are not in the constants.\n        const denyEditAce = acl.find(ace => isDeepEqual(DENY_EDIT_ACE, ace, true, true));\n        const denyShareAce = acl.find(ace => isDeepEqual(DENY_SHARE_ACE, ace, true, true));\n        return {\n            policyResponse,\n            denyEditAceIndex: acl.indexOf(denyEditAce as any),\n            denyShareAceIndex: acl.indexOf(denyShareAce as any)\n        };\n    }\n\n    /**\n     * Helper method to get URL from links with version parameter if available\n     */\n    private getURLWithVersion(links: any, key: RelType): string {\n        return getURLFromLinks(links, key, {\n            ...(this._version && { version: this._version })\n        });\n    }\n\n    // update last access date is taken care of by the PLS API\n    // this is only used for clearing the last access date\n    async removeLastAccessed(): Promise<Response> {\n        const href = getURLFromLinks(this._links, RelType.PERUSER_METADATA);\n        const bodyData: jsonpatch.OpPatch[] = [];\n        bodyData.push({\n            op: 'remove',\n            path: '/shell:lastAccessDate'\n        });\n\n        return await this._doPatch(\n            href,\n            {\n                'Content-Type': JSON_PATCH_MIME_TYPE,\n                // Required for making future migration of these calls to Label Service smoother\n                // https://wiki.corp.adobe.com/display/CSA/Proposal%3A+Personalized+Listing+Service+interaction+with+PUPA+Service\n                // We need to notify clients to add the header in access-control-request-headers header\n                'X-Metadata-Field': 'lastAccessDate'\n            },\n            JSON.stringify(bodyData),\n            [ 204 ]);\n\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nconst shownWarnings: Set<string> = new Set();\n\n/**\n * A utility logging function that warns a client once per page load using\n * the params provided by the caller.\n * @param topic\n * @param message\n */\nexport default function oneTimeWarning(topic: string, message: string) {\n    if (shownWarnings.has(topic)) { return; }\n    console.warn('One time warning (%s): %s', topic, message);\n    shownWarnings.add(topic);\n}\n\nexport function missingImplementationWarning(topic: string) {\n    oneTimeWarning(topic, 'Not implemented yet, but this method is safe to call.');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Simplfies cases where a Promise needs to be resolved or rejected externally from the Promise itself.\n */\nexport class ManagedPromise<T> {\n    promise: Promise<T>;\n    resolve!: (result: T) => void;\n    reject!: (error?: any) => void;\n\n    constructor() {\n        this.promise = new Promise((resolve, reject) => {\n            this.resolve = resolve;\n            this.reject = reject;\n        });\n    }\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type { ISAMObject } from '../ISAMObject';\nimport type IEvent from '../IEvent';\nimport { observableImpl } from './observable';\nimport type TypedEventEmitter from '../TypedEventEmitter';\nimport { BECOME_UNOBSERVED } from '../TypedEventEmitter';\nimport type { SAMObjectEventEmitter } from '../SAMObjectEventEmitter';\nimport { ManagedPromise } from '../../utils/ManagedPromise';\n\nconst $LAZY_LOAD_MANAGERS = Symbol('$LAZY_LOAD_MANAGERS');\n\ntype ILazyLoaded = ISAMObject & TypedEventEmitter<any> & {\n    [$LAZY_LOAD_MANAGERS]: Map<IEvent, LazyLoadManager>;\n}\n\nexport enum LoadStatus {\n    NotLoaded = 1,\n    Pending,\n    Loading,\n    Loaded,\n    Error\n}\n\ninterface ILazyLoadConfig {\n    /**\n     * The Event being used to notify lazy-loading state changes. This should be the shared instance\n     * of the Event, so that ItemUpdater can use @lazyLoaded annotation to determine which event to\n     * use automatically.\n     */\n    event: IEvent;\n    /**\n     * The callback that will fetch the lazily-loaded data. It should also update the cached property,\n     * typically the private _property(ies) used for the getter(s).\n     * @returns {Promise<void>}\n     */\n    fetchData: () => Promise<void>;\n    /**\n     * To prevent unnecessary fetching of data, the amount of ms to delay lazy-loading. Default is 50ms.\n     * Especially helpful for cases where the user might scroll quickly through a list, where some items\n     * will be off-screen before the lazy-loading starts.\n     *\n     * @note Use 0 when lazy-loading is managed by BatchOperationQueue, which has its own delay.\n     * @note Use 0 when lazy-loading is required and shouldn't be cancelled\n     */\n    prefetchTimeout?: number;\n    /**\n     * If the {@link fetchData} throws an exception, LLM.status will be Error. If retryErrorTimeout is set,\n     * it will wait that many ms before changing the status back to NotLoaded, which will notify clients to\n     * check the lazy-loaded properties again, triggering another load. Since most lazy-loading is handled by\n     * InterfaceBase descendents, which will already automatically retrying errors appropriately, this\n     * property should be typically left unset. Misuse of this setting can cause cascading service outages if\n     * the service is failing due to load, so use sparingly.\n     */\n    retryErrorTimeout?: number;\n    /**\n     * If a {@link fetchData} request is in-flight but can be cancelled, pass this callback. It should\n     * return true if it was able to successfully cancel the request, false otherwise. This is useful\n     * for BatchOperationQueue, to remove items from the queue before it makes the next batch call.\n     * @returns {boolean}\n     */\n    cancelFetchData?: () => boolean;\n}\n\ntype LLMConstructorConfig = ILazyLoadConfig & {\n    target: ILazyLoaded;\n}\n\nconst MAX_RETRIES = 5;\nconst FETCH_START_DELAY_MS = 100;\n\n/**\n * For managing lazy loading of data throughout SAM.js in a consistent manner. This involves\n *\n * 1. A new custom event for the data that is lazily fetched should be created. While it can work with the default\n *    'change' event, using a custom event will allow SAM.js to track what lazy-loaded data is actively being\n *    monitored by clients so that it only fetches when necessary.\n * 2. The class that has lazy-loaded data should call static method LazyLoadManager.manageLazyLoading() to instantiate\n *    the LazyLoadManager(s) and annotate the getters for the lazy-loaded data with @lazyLoaded\n *\n * @package -- only for use in SAM.js\n */\nexport class LazyLoadManager {\n    // config\n    private readonly _target: ILazyLoaded;\n    private _event: IEvent;\n    private _loadStatus: LoadStatus = LoadStatus.NotLoaded;\n    private _fetchData: () => Promise<void>;\n    private _prefetchTimeout: number = FETCH_START_DELAY_MS;\n    private _retryErrorTimeout: number = Number.POSITIVE_INFINITY;\n    private _cancelFetchData?: () => boolean;\n\n    // state\n    private _prefetchResolve?: (cancelled: boolean) => void;\n    private _retriesRemaining: number = MAX_RETRIES;\n    private _pendingFetchPromise?: ManagedPromise<void>;\n\n\n    constructor({\n        target,\n        event,\n        fetchData,\n        prefetchTimeout = FETCH_START_DELAY_MS,\n        retryErrorTimeout = Number.POSITIVE_INFINITY,\n        cancelFetchData,\n    }: LLMConstructorConfig) {\n        this._target = target;\n        this._event = event;\n        this._fetchData = fetchData;\n        this._prefetchTimeout = prefetchTimeout;\n        this._retryErrorTimeout = retryErrorTimeout;\n        this._cancelFetchData = cancelFetchData;\n\n        this._target.on(BECOME_UNOBSERVED, this._onBecomeUnobserved);\n    }\n\n    /**\n     * Ideal way for client classes to instantiate LazyLoadManager(s)\n     *\n     * @example```ts\n     * class MyClass extends SAMObjectEventEmitter {\n     *    private _lazyLoadVal?: number;\n     *\n     *    constructor() {\n     *        LazyLoadManager.manageLazyLoading(this, [{\n     *            event: MyEventInstance,\n     *            fetchData: this._fetchData\n     *        }]);\n     *    }\n     *\n     *    @lazyLoaded(MyEventInstance, '_lazyLoadVal')\n     *    get lazyLoadVal(): number | undefined {\n     *        return this._lazyLoadVal;\n     *    }\n     *\n     *    private async _fetchData(): void {\n     *        this._lazyLoadValue = await this._core.someContext.fetchData();\n     *    }\n     * }\n     *```\n     * @param {SAMObjectEventEmitter} target  the class instance that has lazy-loaded data to manage\n     * @param {ILazyLoadConfig[]} configs the config for each LazyLoadManager\n     */\n    static manageLazyLoading(target: SAMObjectEventEmitter, configs: ILazyLoadConfig[]): void {\n        const instance = target as unknown as ILazyLoaded;\n        instance[$LAZY_LOAD_MANAGERS] = instance[$LAZY_LOAD_MANAGERS] || new Map();\n\n        configs.forEach((cfg) => {\n            const manager = new LazyLoadManager({\n                target: instance,\n                ...cfg\n            });\n            instance[$LAZY_LOAD_MANAGERS].set(cfg.event, manager);\n        });\n    }\n\n    /**\n     * Primarily for internal use/testing. Finds the relevant LazyLoadManager for a specific event (by name or\n     * by shared SAMEvent instance).\n     *\n     * @param target {SAMObjectEventEmitter} the class instance that has lazy-loaded data to manage\n     * @param event {IEvent|string} the SAMEvent instance or name\n     */\n    static getManager(target: SAMObjectEventEmitter, event: IEvent | string): LazyLoadManager {\n        const map = (target as unknown as ILazyLoaded)[$LAZY_LOAD_MANAGERS];\n\n        let foundEvent: IEvent | undefined;\n        if (typeof event === 'string') {\n            foundEvent = [ ...map.keys() ].find(e => e.type === event);\n        } else {\n            foundEvent = event;\n        }\n\n        const manager = map.get(foundEvent!);\n        if (!manager) {\n            throw new Error(`Target does not have a LazyLoadManager for event ${event}`);\n        }\n\n        return manager;\n    }\n\n    /**\n     * For external code to check if a LazyLoadManager exists for a specific event.\n     * @param target {SAMObjectEventEmitter} the class instance that has lazy-loaded data to manage\n     * @param event {IEvent|string} the SAMEvent instance or name\n     */\n    static hasManager(target: SAMObjectEventEmitter, event: IEvent | string): boolean {\n        try {\n            return LazyLoadManager.getManager(target, event) !== undefined;\n        } catch (e) {\n            return false;\n        }\n    }\n\n    /**\n     * Used by code outside the _fetchData method that needs to modify the loadStatus.\n     *\n     * @param target {SAMObjectEventEmitter} the target instance that has lazy-loaded data\n     * @param event {string | IEvent} the event name or instance tied to the lazy-loaded data\n     * @param loadStatus {LoadStatus} the new LoadStatus\n     */\n    static setLoadStatus(target: SAMObjectEventEmitter, event: string | IEvent, loadStatus: LoadStatus): void {\n        const manager = LazyLoadManager.getManager(target, event);\n        manager.setLoadStatus(loadStatus);\n    }\n\n    /**\n     * For external code to check load status.\n     *\n     * @param target {SAMObjectEventEmitter} the target instance that has lazy-loaded data\n     * @param event {string | IEvent} the event name tied to the lazy-loaded data\n     * @return LoadStatus\n     */\n    static getLoadStatus(target: SAMObjectEventEmitter, event: string | IEvent): LoadStatus {\n        const manager = LazyLoadManager.getManager(target, event);\n        return manager.loadStatus;\n    }\n\n    static fetchIfNeeded(target: SAMObjectEventEmitter, event: string | IEvent): Promise<void> {\n        const manager = LazyLoadManager.getManager(target, event);\n        return manager.fetchIfNeeded();\n    }\n\n    /**\n     * For cases where code modifies the lazy-load data outside of fetching. Ensures the correct LoadStatus is set and\n     * the appropriate event is fired.\n     *\n     * @param target {SAMObjectEventEmitter} the target instance that has lazy-loaded data\n     * @param event {string | IEvent} the event name or instance tied to the lazy-loaded data\n     */\n    static updatedExternally(target: SAMObjectEventEmitter, event: string | IEvent): void {\n        const manager = LazyLoadManager.getManager(target, event);\n        manager.updatedExternally();\n    }\n\n\n    /**\n     * For cases where an ItemUpdater is used where it is guaranteed that the lazy-loaded data is\n     * now up-to-date, so only the load status needs updating, and no events need to be fired\n     * because UpdateSession.commit() was just called or will soon be called.\n     *\n     * @param target {SAMObjectEventEmitter} the target instance that has lazy-loaded data\n     * @param event {string | IEvent} the event name or instance tied to the lazy-loaded data\n     */\n    static updatedByItemUpdater(target: SAMObjectEventEmitter, event: string | IEvent): void {\n        const manager = LazyLoadManager.getManager(target, event);\n        manager.updatedByItemUpdater();\n    }\n\n    get loadStatus(): LoadStatus {\n        return this._loadStatus;\n    }\n\n    private _onBecomeUnobserved = (eventName: string) => {\n        if (eventName !== this._event.type) { return; }\n\n        if (this._loadStatus === LoadStatus.Pending) {\n            this._prefetchResolve!(true);\n            return;\n        }\n\n        // Only cancel fetching if it is loading and there is a way to do it\n        if (this._loadStatus === LoadStatus.Loading && this._cancelFetchData) {\n            // _cancelFetchData returns true if cancel succeeds\n            if (this._cancelFetchData.call(this._target)) {\n                this.setLoadStatus(LoadStatus.NotLoaded);\n            }\n        }\n    };\n\n    private async _prefetchDelay(): Promise<boolean> {\n        return new Promise((resolve) => {\n            this._prefetchResolve = resolve;\n            this.setLoadStatus(LoadStatus.Pending);\n            setTimeout(() => {\n                resolve(false);\n                this._prefetchResolve = undefined;\n            }, this._prefetchTimeout);\n        });\n    }\n\n    onPropertyAccess(): void {\n        this.fetchIfNeeded();\n    }\n\n    // Fetch data, set load status, and emit event\n    async fetchIfNeeded(): Promise<void> {\n        if (this._loadStatus === LoadStatus.NotLoaded) {\n            this._pendingFetchPromise = new ManagedPromise();\n            if (this._prefetchTimeout) {\n                const cancelled = await this._prefetchDelay();\n                if (cancelled) {\n                    this.setLoadStatus(LoadStatus.NotLoaded);\n                    this._pendingFetchPromise.resolve();\n                    return;\n                }\n            }\n            try {\n                this._loadStatus = LoadStatus.Loading;\n\n                // Note: uses `call` for better memory footprint. That way, the _fetchData implementation can be a\n                // single instance of a function on the class prototype, rather than a method bound (via `=>` or\n                // `.bind()`) on each instance of the class.\n                await this._fetchData.call(this._target);\n                // Don't transition to Loaded if it was cancelled\n                if (this._loadStatus === LoadStatus.Loading) {\n                    this.setLoadStatus(LoadStatus.Loaded);\n                    this._pendingFetchPromise.resolve();\n                }\n            } catch (e) {\n                this.setLoadStatus(LoadStatus.Error);\n                // Rejecting here seems to cause an unhandled error that prevents tests from working,\n                // but might cause runtime issues as well. For now, it's up to the client to check\n                // for error status if they're expecting that the fetch succeeded.\n                this._pendingFetchPromise.resolve();\n            }\n        }\n        await this._pendingFetchPromise?.promise;\n    }\n\n    // Set load status and emit event\n    setLoadStatus(loadStatus: LoadStatus) {\n        if (this._loadStatus === loadStatus) { return; }\n\n        this._loadStatus = loadStatus;\n        // Transitioning to NotLoaded means the data still needs to be loaded, so listeners should be notified so\n        // they can trigger lazy-loading if they want.\n        if (loadStatus === LoadStatus.NotLoaded || loadStatus === LoadStatus.Loaded) {\n            // Reset remaining retries on successful load\n            if (loadStatus === LoadStatus.Loaded) {\n                this._retriesRemaining = MAX_RETRIES;\n            }\n\n            this._target.dispatch(this._event);\n        } else if (loadStatus === LoadStatus.Error\n            && this._retryErrorTimeout < Number.POSITIVE_INFINITY\n            && this._retriesRemaining > 0\n        ) {\n            // If retry-able, wait the designated time and then set back to NotLoaded, which will notify clients\n            // so they can kick-off lazy loading again if desired\n            setTimeout(() => {\n                this._retriesRemaining--;\n                if (this._loadStatus === LoadStatus.Error) {\n                    this.setLoadStatus(LoadStatus.NotLoaded);\n                }\n            }, this._retryErrorTimeout);\n        }\n    }\n\n    /**\n     * For cases when something updates lazy-loaded data outside of a lazy-load fetch (such as mutating the value of a\n     * field as part of a service operation), where the event must be fired and the loadStatus should be set to Loaded\n     */\n    updatedExternally() {\n        if (this._loadStatus !== LoadStatus.Loaded) {\n            // setLoadStatus will fire the event\n            this.setLoadStatus(LoadStatus.Loaded);\n        } else {\n            this._target.dispatch(this._event);\n        }\n    }\n\n    /**\n     *  @see LazyLoadManager.updateByItemUpdater\n     */\n    updatedByItemUpdater() {\n        if (this._loadStatus === LoadStatus.Pending) {\n            this._prefetchResolve!(true); // cancel fetch\n        }\n        // It should now be safe to change to Loaded:\n        // LoadStatus.Pending -- the prefetchDelay was cancelled above\n        // LoadStatus.NotLoaded -- nothing is happening asynchronously\n        // LoadStatus.Error -- if a retry timer is pending, it will not retry b/c the status\n        //      will be Loaded\n        // LoadStatus.Loading -- when the fetch completes, it will not fire a duplicate event\n        //      b/c the status will already be Loaded\n        this._loadStatus = LoadStatus.Loaded;\n    }\n}\n\n/**\n * Annotation for marking a getter as the entry point for clients to access lazy-loaded fields, which\n * makes them observed and starts lazy-loading if needed.\n *\n * @param event {IEvent} the event instance that will be fired when the lazy-loaded data changes\n * @param privatePropNames {string[]} an array of the private property names that the annotated getter references.\n *        When ItemUpdater modifies one of these private fields, it will fire the event specified, rather than the\n *        default event for the ItemUpdater.\n */\nexport function lazyLoaded(event: IEvent, privatePropNames: string | string[]) {\n    return function (target: SAMObjectEventEmitter, key: string, descriptor: PropertyDescriptor) {\n        if (descriptor.get) {\n            const getter = descriptor.get;\n            descriptor.get = function (this: SAMObjectEventEmitter) {\n                const manager = LazyLoadManager.getManager(this, event);\n                if (!manager) {\n                    throw new Error(`@lazyLoaded target is missing LazyLoadManager for event ${event.type}. Use`\n                        + ' LazyLoadManager.manageLazyLoading() in constructor to configure');\n                }\n                manager.onPropertyAccess();\n                return getter.call(this);\n            };\n        } else if (typeof descriptor.value === 'function') {\n            const method = descriptor.value;\n            const newMethod = function (this: SAMObjectEventEmitter, ...args: any[]): any {\n                const manager = LazyLoadManager.getManager(this, event);\n                if (!manager) {\n                    throw new Error(`@lazyLoaded target is missing LazyLoadManager for event ${event.type}. Use`\n                        + ' LazyLoadManager.manageLazyLoading() in constructor to configure');\n                }\n                manager.onPropertyAccess();\n                return (method as any).apply(this, args);\n            };\n            descriptor.value = newMethod;\n        } else {\n            throw new Error('@lazyLoaded only works with getters and methods');\n        }\n        // layer @observable on top of @lazyLoaded\n        privatePropNames = [].concat(privatePropNames as any);\n        observableImpl(event, privatePropNames)(target, key, descriptor);\n    };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { memoize, observable } from '../core/decorators';\nimport ItemBase from '../core/ItemBase';\nimport type { CollaboratorSource } from './CollaboratorSource';\nimport type { InvitedCollaboratorSource } from './InvitedCollaboratorSource';\nimport type Collaborator from './Collaborator';\nimport type InvitedCollaborator from './InvitedCollaborator';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { SharedCollaboratorChangedEvent, COLLABORATOR_CHANGED } from '../indexPrivate';\nimport type { ICollaboratorSources } from './CollaborationContext';\nimport type { IItemPoolDelegate } from '../core/ItemPool';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport { lazyLoaded, LazyLoadManager, LoadStatus } from '../core/decorators/LazyLoadManager';\nimport type { IInvitationRecipient } from '../interface/InvitationModel';\nimport { SAMError } from '../core/SAMError';\n\nexport default class ShareableItem extends ItemBase {\n    private _collaboratorsArray: Collaborator[] = [];\n    private _collaboratorSources?: ICollaboratorSources;\n    /**\n     * Used when this asset is created through USS and\n     * the metadata collab_metadata#mine with a missing \"type\" property\n     * indicates that this asset is shared with the current\n     * user through a group and not individually.\n     */\n    protected _isSWYGroup: boolean | undefined;\n    protected _isSharedWithYouAsset: boolean | undefined;\n    protected _isShared: boolean | undefined;\n    private _directCollaboratorCount: number | undefined;\n    private _isPublicLink: boolean | undefined;\n    protected _shareFlagsAreDirty: boolean = true;\n\n    constructor(core: ISAMCorePrivate, id: string) {\n        super(core, id);\n        LazyLoadManager.manageLazyLoading(this, [ {\n            event: SharedCollaboratorChangedEvent,\n            fetchData: this._queueCollaborators,\n            prefetchTimeout: 0,\n            cancelFetchData: this._dequeueCollaborators\n        } ]);\n    }\n\n    @observable(SharedCollaboratorChangedEvent, '_isShared')\n    get isShared(): boolean | undefined {\n        this._fetchShareFlagsIfNeeded();\n        return this._isShared;\n    }\n\n    @observable(SharedCollaboratorChangedEvent, '_isSharedWithYouAsset')\n    get isSharedWithYouAsset(): boolean | undefined {\n        this._fetchShareFlagsIfNeeded();\n        return this._isSharedWithYouAsset;\n    }\n\n    @observable(SharedCollaboratorChangedEvent, '_directCollaboratorCount')\n    get directCollaboratorCount(): number | undefined {\n        this._fetchShareFlagsIfNeeded();\n        return this._directCollaboratorCount;\n    }\n\n    @observable(SharedCollaboratorChangedEvent, '_isPublicLink')\n    get isPublicLink(): boolean | undefined {\n        this._fetchShareFlagsIfNeeded();\n        return this._isPublicLink;\n    }\n\n    /**\n     * @package, used internally by filters, tests, etc.\n     */\n    get _isSWYAsset_NoLazyLoad(): boolean | undefined {\n        return this._isSharedWithYouAsset;\n    }\n\n    /**\n     * @package, used internally by filters, tests, etc.\n     */\n    get _isShared_NoLazyLoad(): boolean | undefined {\n        return this._isShared;\n    }\n\n    /**\n     * @package, used internally by filters, tests, etc.\n     */\n    get _directCollaboratorCount_NoLazyLoad(): number | undefined {\n        return this._directCollaboratorCount;\n    }\n\n    /**\n     * @package, used internally by filters, tests, etc.\n     */\n    get _isPublicLink_NoLazyLoad(): boolean | undefined {\n        return this._isPublicLink;\n    }\n\n    /**\n     * @deprecated Please use isSharedWithYouAsset -- will be removed on or after 2024-10-01\n     */\n    get isSharedWithMe(): boolean | undefined {\n        oneTimeWarning('isSharedWithMe', 'isSharedWithMe is deprecated and will be removed on or after'\n            + ' 2024-10-01. Please use isSharedWithYouAsset instead.');\n        return this.isSharedWithYouAsset;\n    }\n\n    /**\n     * @package -- used internally to check if collaborator data has been lazy-loaded without triggering lazy-loading.\n     */\n    get _isCollaboratorDataLoaded(): boolean {\n        return LazyLoadManager.getLoadStatus(this, SharedCollaboratorChangedEvent.type) === LoadStatus.Loaded;\n    }\n\n    private _fetchShareFlagsIfNeeded() {\n        if (this._shareFlagsAreDirty) {\n            LazyLoadManager.fetchIfNeeded(this, SharedCollaboratorChangedEvent);\n        }\n    }\n\n    /**\n     * @package used internally.\n     */\n    _queueCollaborators(): Promise<void> {\n        return this._core.collaborationContext._collaboratorRequestQueue.enqueue(this);\n    }\n\n    private _dequeueCollaborators(): boolean {\n        return this._core.collaborationContext._collaboratorRequestQueue.dequeue(this);\n    }\n\n    @lazyLoaded(SharedCollaboratorChangedEvent, '_collaboratorsArray')\n    get collaboratorArray(): Collaborator[] {\n        return this._collaboratorsArray;\n    }\n\n    @memoize\n    get collaborators(): CollaboratorSource {\n        if (!this._collaboratorSources) {\n            this._collaboratorSources = this._core.collaborationContext._getCollaboratorSources(this.id);\n            this._collaboratorSources.collaboratorPool.addDelegate(this._itemPoolDelegate, 'context');\n        }\n        return this._collaboratorSources.collaboratorSource;\n    }\n\n    async removeCollaborator(collaborator: Collaborator): Promise<void> {\n        await this._core.collaborationContext._removeCollaborator(this.id, collaborator);\n    }\n\n    async removeCurrentUserFromCollaborationList(): Promise<void> {\n        return this._core.collaborationContext._removeCurrentUserFromCollaborationList(this);\n    }\n\n    async createPublicLink(canComment: boolean = true): Promise<void> {\n        const publicLinkCollaborator: IInvitationRecipient = {\n            recipient: 'all',\n            role: 'viewer',\n            canShare: false,\n            canComment\n        };\n\n        this._core.collaborationContext._addCollaborators(this.id, [ publicLinkCollaborator ]);\n    }\n\n    async removePublicLink(): Promise<void> {\n        if (!this._isCollaboratorDataLoaded) {\n            // Queue up fetching collaborators\n            await this._queueCollaborators();\n            await new Promise<void>((resolve) => {\n                this.on(COLLABORATOR_CHANGED, () => {\n                    // check that the data has loaded again in case there is some other\n                    // field loading that finished first and fired this event.\n                    if (this._isCollaboratorDataLoaded) {\n                        resolve();\n                    }\n                });\n            });\n        }\n\n        const predefinedPrincipal = this.collaboratorArray.find(collaborator => collaborator.id === 'all');\n\n        if (predefinedPrincipal) {\n            this._core.collaborationContext._removeCollaborator(this.id, predefinedPrincipal);\n        }\n    }\n\n    /**\n     * Shares this item with the entire organization so that all members can access this item. This method adds\n     * the predefined principal 'orgEverybody' as a viewer with commenting permissions but without sharing permissions.\n     *\n     * @throws {SAMError} if adding the organization collaborator fails (409 if already a collaborator, 403 if insufficient permissions, 500 if downstream errors occur)\n     *\n     * @returns {Promise<void>} Resolves when the organization has been successfully added as a collaborator\n     */\n    async shareWithOwnerOrganization(): Promise<void> {\n        const orgEverybodyCollaborator: IInvitationRecipient = {\n            recipient: 'orgEverybody',\n            role: 'viewer',\n            canComment: true,\n            canShare: false,\n        };\n\n        const result = await this._core.collaborationContext._addCollaborators(this.id, [ orgEverybodyCollaborator ]);\n        const orgEverybody = result.failedCollaborators.find(c => c.recipient === 'orgEverybody');\n        if (orgEverybody) {\n            throw SAMError.create(orgEverybody.error.code, orgEverybody.error.message);\n        }\n    }\n\n    /**\n     * @TODO_Deprecation -- will be marked deprecated on or after 2024-10-01, and removed on or after 2025-01-01.\n     *   Only used in admin console for managing Teams, which is already deprecated.\n     *\n     * @returns {InvitedCollaboratorSource}\n     */\n    @memoize\n    get invitedCollaborators(): InvitedCollaboratorSource {\n        if (!this._collaboratorSources) {\n            this._collaboratorSources = this._core.collaborationContext._getCollaboratorSources(this.id);\n        }\n        return this._collaboratorSources.invitedCollaboratorSource;\n    }\n\n    /**\n     * @TODO_Deprecation -- will be marked deprecated on or after 2024-10-01, and removed on or after 2025-01-01.\n     *   Only used in admin console for managing Teams, which is already deprecated.\n     *\n     * @param {InvitedCollaborator} invitedCollaborator\n     * @returns {Promise<void>}\n     */\n    removeInvitedCollaborator(invitedCollaborator: InvitedCollaborator) {\n        return this._core.collaborationContext.removeInvitedCollaborator(this.id, invitedCollaborator);\n    }\n\n    /**\n     * @package Internal use only\n     *\n     * @param sources\n     * @param collaborators\n     */\n    _setCollaboratorData(collaborators?: Collaborator[]) {\n        this._collaboratorSources = this._core.collaborationContext._getCollaboratorSources(this.id);\n        const collaboratorItemPool = this._collaboratorSources.collaboratorPool;\n        this._collaboratorsArray = collaborators ?? collaboratorItemPool.toArray();\n        this._shareFlagsAreDirty = false;\n\n        // set the isShared flag. The collaborators array contains the owner of the asset\n        // as well the organization that owns the asset.\n        // We use the isDirect flag to determine if the asset is explicitly shared or not.\n        this._isShared = this._collaboratorsArray.some((collaborator) => {\n            return collaborator.isDirect;\n        });\n\n        // set the isSharedWithYouAsset flag\n        const isCurrentUserDirectCollaborator = this._collaboratorsArray.some((collaborator) => {\n            return collaborator.isDirect && collaborator.isCurrentUser;\n        });\n\n        this._isSharedWithYouAsset = this._isSWYGroup || isCurrentUserDirectCollaborator;\n\n        // set the isPublicLink flag\n        this._isPublicLink = this._collaboratorsArray.some((collaborator) => {\n            return collaborator.id === 'all';\n        });\n\n        // calculate the number of direct collaborators\n        this._directCollaboratorCount = this._collaboratorsArray.filter(collaborator => collaborator.isDirect).length;\n    }\n\n    private _itemPoolDelegate: IItemPoolDelegate<Collaborator> = {\n        onItemsUpdated: () => {\n            this._setCollaboratorData();\n            // This code path is not governed by LazyLoadManager, but LLM still needs to be informed of the update.\n            LazyLoadManager.updatedExternally(this, SharedCollaboratorChangedEvent);\n        }\n    };\n}\n","import type { ISAMCorePrivate } from '../indexPrivate';\nimport type AdobeAsset from './AdobeAsset';\nimport type { IResourceOptions } from './Resource';\nimport Resource from './Resource';\n\n/**\n * A Resource for a specific AdobeAsset, which only revalidates requests if ONS is inactive.\n * The resource's associated asset may be set after initialization.\n */\nexport default class AdobeAssetResource<T> extends Resource<T> {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        protected _parent?: AdobeAsset,\n        options: IResourceOptions<T> = {},\n    ) {\n        super(_core, {\n            ...options,\n            // If ONS is active and this resource is attached to a parent asset,\n            // we can skip revalidation because ONS will notify us of any changes.\n            // Any assets in the pool should either be monitored directly with ONS\n            // or through the watch on their parent directory.\n            skipRevalidation: () => Boolean(this._parent && this._core.hostAssetContext.onsContext?.isActive),\n        });\n\n        this._parent = _parent;\n    }\n\n    /** Set the parent asset for this resource. */\n    setParent(parentAsset: AdobeAsset) {\n        this._parent = parentAsset;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { RelType } from '../interface/LinkUtils';\nimport type AdobeAsset from './AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type SAMError from '../core/SAMError';\nimport { SAMErrorCode } from '../core/SAMError';\nimport AdobeAssetResource from './AdobeAssetResource';\n\nexport default class EmbeddedMetadataResource extends AdobeAssetResource<any> {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _parent: AdobeAsset,\n    ) {\n        super(_core, _parent, {\n            onError: async (error) => {\n                if ((error as SAMError).code === SAMErrorCode.NOT_FOUND) {\n                    // If an asset doesn't have embedded metadata, just return empty metadata rather than\n                    // treating it as a failure.\n                    await this._setData({});\n                }\n            }\n        });\n    }\n\n    protected async _loadData() {\n        await this._parent._ensureLink(RelType.EMBEDDED_METADATA);\n        const assetInterface = await this._parent._getAssetInterface();\n        await assetInterface.getEmbeddedMetadata(this);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type jsonpatch from 'json-patch';\n\nimport { RelType } from '../interface/LinkUtils';\nimport type AdobeAsset from './AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type SAMError from '../core/SAMError';\nimport { SAMErrorCode } from '../core/SAMError';\nimport AdobeAssetResource from './AdobeAssetResource';\n\nexport default class AppMetadataResource extends AdobeAssetResource<any> {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        _parent?: AdobeAsset,\n    ) {\n        super(_core, _parent, {\n            onError: async (error) => {\n                if ((error as SAMError).code === SAMErrorCode.NOT_FOUND) {\n                    // If an asset doesn't have app metadata, just return empty metadata rather than\n                    // treating it as a failure. (Setting the data here clears the error.)\n                    await this._setData({});\n                }\n            }\n        });\n    }\n\n    /*\n        A note regarding the following commented code:\n\n        While the code below is what we want, the issue is that, at the time load() is being called,\n        the parent's permissions have not been set yet.\n\n        In AdobeAsset _load(), the permissions are updated by AdobeAssetUpdater.updateLocalItem at the end,\n        but AppMetadataResource/load() is being called by await Promise.all(resourcesToReload.map(resource => resource.load()));\n        that happens before.\n\n        As long as we do not have a better mechanism to handle the permissions, we have to unsatisfy this request from\n        https://jira.corp.adobe.com/browse/SAM-3326:\n\n        6. Update `AppMetadataResource._loadData()` to check the permission on the parent, and if it does not have Permission.ReadAppMetadata, throw ACCESS_DENIED error instead of making the call.\n    */\n\n    // async load() {\n    //     if (this._parent.hasPermission(Permission.ReadAppMetadata)) {\n    //         await super.load();\n    //     } else {\n    //         throw SAMErrorCode.ACCESS_DENIED;\n    //     }\n    // }\n\n    protected async _loadData() {\n        await this._parent?._ensureLink(RelType.APP_METADATA);\n        const assetInterface = await this._parent?._getAssetInterface();\n        await assetInterface?.getAppMetadata(this);\n    }\n\n    /**\n     * @package to be used internally by SAM.js\n     */\n    async _patch(patches: jsonpatch.OpPatch[]): Promise<void> {\n        // TODO: check for graphQL\n        await this._parent?._ensureLink(RelType.APP_METADATA);\n        const assetInterface = await this._parent?._getAssetInterface();\n        await assetInterface?.patchAppMetadata(patches);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AssetVersion from './AssetVersion';\nimport type AdobeAsset from './AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport Resource from './Resource';\n\n// ManifestResource is a Resource that represents the manifest of an AdobeAsset or AssetVersion.\nexport default class ManifestResource extends Resource<any> {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _parent: AdobeAsset | AssetVersion,\n    ) {\n        super(_core);\n    }\n\n    protected async _loadData() {\n        // TODO: check for graphQL\n        const assetInterface = await this._parent._getAssetInterface();\n        await assetInterface.getManifest(this);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type SAMError from '../core/SAMError';\nimport type { RelType, IServiceLink } from './LinkUtils';\nimport type { AssetSubType, AssetType, IAssetsPageSpec } from './AssetModel';\nimport type { IRemoteAssignmentAppMetadata } from './AssignmentModel';\nimport type { IRemoteStudentAssignmentFileMetadata } from './StudentAssignmentFileModel';\nimport type { IBrandsAssetAppMetadata } from './LibraryModel';\nimport type { GenerationHistoryAssetAppMetadata } from './GenerationHistoryAssetModel';\nimport type RequiredProps from '../utils/RequiredProps';\n\n/**\n * The Operation Document describes requests that manipulate Assets within a Repository.\n */\nexport type IOperationQuery = IOperation | IOperation[];\n\nexport type IOperation =\n    | ICopyOperation\n    | IPublishOperation\n    | IRemixOperation\n    | ICopyResourcesOperation\n    | IMoveOperation\n    | IDeleteOperation\n    | IDiscardOperation\n    | IRestoreOperation\n    | IPackageOperation;\n\nexport type AssetRef =\n    | IAssetRefRepoPath\n    | IAssetRefRepoAssetId\n    | IAssetRefPath\n    | IAssetRefRepoId\n    | IAssetRefHref;\n\nexport type AssetRefWithoutVersion =\n    | Omit<IAssetRefRepoPath, 'repo:version'>\n    | Omit<IAssetRefRepoAssetId, 'repo:version'>\n    | Omit<IAssetRefPath, 'repo:version'>\n    | Omit<IAssetRefRepoId, 'repo:version'>\n    | Omit<IAssetRefHref, 'repo:version'>;\n\ninterface IAssetRefBase {\n    'if-match'?: string;\n    'if-none-match'?: string;\n    'repo:version'?: string;\n}\n\nexport interface IAssetRefRepoPath extends IAssetRefBase {\n    'repo:path': string;\n    'repo:baseAssetId'?: string;\n    'repo:repositoryId': string;\n}\n\nexport interface IAssetRefRepoAssetId extends IAssetRefBase {\n    'repo:assetId': string;\n    'repo:repositoryId'?: string;\n}\n\nexport interface IAssetRefPath extends IAssetRefBase {\n    path: string;\n}\n\nexport interface IAssetRefRepoId extends IAssetRefBase {\n    'repo:id': string;\n}\n\nexport interface IAssetRefHref extends IAssetRefBase {\n    href: string;\n}\n\n/**\n * If the resource is a component in a composite, component_id identifies the exact component referenced\n */\nexport type ComponentId = string;\n\n/**\n * If the resource is a component in a composite, the revision provides identifies the exact revision of the component\n */\nexport type Revision = string;\n\n/**\n * If an individual resource is being identified, this property represents that resource's entity tag\n */\nexport type EntityTag = string;\n\n\nexport interface IResourceDesignator {\n    reltype: RelType;\n    component_id?: ComponentId;\n    revision?: Revision;\n    etag?: EntityTag;\n    selectionType?: 'include' | 'exclude';\n    selectors?: string[];\n}\n\nexport type ResourceSourceTarget = {\n    source: IResourceDesignator;\n    target: IResourceDesignator;\n};\n\nexport type ResourceCopy = IResourceDesignator | ResourceSourceTarget;\n\nexport type OneOrMoreAssetRef = AssetRef | AssetRef[];\n\n/**\n * The physical or digital manifestation of the resource. Typically, Format should include the media-type of the resource.\n * Format may be used to determine the software, hardware or other equipment needed to display or operate the resource.\n * Recommended best practice is to select a value from a controlled vocabulary (for example, the list of\n * [Internet Media Types](http://www.iana.org/assignments/media-types/) defining computer media formats).\n */\nexport type Format = string;\n\nexport type Assignee = {\n    // ID of the owner e.g. IMS user-id or IMS org-id\n    id: string,\n\n    // the name to show in the UI\n    displayName?: string,\n\n    // The type of owner e.g. org or user\n    type: 'user' | 'org'\n}\n\nexport type Representations = {\n    // file representation availability\n    file?: boolean,\n    // composite representation availability\n    composite?: boolean,\n    // directory representation availability\n    directory?: boolean\n}\n\n// NOTE: R-API uses 'file', 'composite', 'directory'\n//       USS uses 'element' to identify Library Elements\n//       'entity' is not implemented yet\nexport type AssetClass = 'file' | 'composite' | 'directory' | 'entity' | 'element';\nexport type AssetState = 'ACTIVE' | 'DISCARDED' | 'DISCARDED_PARENT';\nexport type DirectoryType = 'system' | 'assigned' | 'content' | 'syncgroup';\nexport type ShellVisibility = 'hiddenSelf' | 'hiddenRecursive' | '';\n\n// We get discard, restore, and rename privileges from the projects service\nexport type PermissionType = 'ack' | 'read' | 'write' | 'delete' | 'discard' | 'restore' | 'rename';\n\nexport const AssetClassChoices: AssetClass[] = [ 'file', 'composite', 'directory', 'entity', 'element' ];\nexport const AssetStateChoices: AssetState[] = [ 'ACTIVE', 'DISCARDED', 'DISCARDED_PARENT' ];\nexport const DirectoryTypeChoices: DirectoryType[] = [ 'system', 'assigned', 'content', 'syncgroup' ];\nexport const ShellVisibilityChoices: ShellVisibility[] = [ 'hiddenSelf', 'hiddenRecursive', '' ];\n\nexport type AclLinks = {\n    [RelType.AC_POLICY]: IServiceLink,\n    // @deprecated -- Not required\n    [RelType.AC_CHECK]: IServiceLink,\n    [RelType.AC_EFFECTIVE]: IServiceLink,\n}\n\nexport type NavigationLinks = {\n    // @deprecated -- Not required\n    [RelType.DIRECTORY]: IServiceLink,\n    // @deprecated -- Not required\n    [RelType.DIRECTORY_BASE]: IServiceLink,\n    [RelType.PATH]: IServiceLink,\n    [RelType.ID]: IServiceLink,\n    [RelType.PAGE]: IServiceLink,\n    [RelType.REPOSITORY]: IServiceLink\n}\n\nexport type AssociatedLinks = {\n    [RelType.PRIMARY]: IServiceLink,\n    [RelType.REPO_METADATA]: IServiceLink,\n    [RelType.APP_METADATA]: IServiceLink,\n    [RelType.EMBEDDED_METADATA]: IServiceLink,\n    [RelType.PERUSER_METADATA]: IServiceLink,\n    [RelType.AC_POLICY]: IServiceLink,\n    [RelType.VERSION]: IServiceLink,\n    [RelType.RENDITION]: IServiceLink,\n    [RelType.BLOCK_INITIALIZE]: IServiceLink & {\n        'repo:maxsingletransfersize': number;\n        'repo:minsingletransfersize': number;\n    }\n    // Component Rendition may only come from USS?\n    [RelType.COMPONENT_RENDITION]: IServiceLink,\n    [RelType.MANIFEST]: IServiceLink,\n    [RelType.QUOTA]: IServiceLink,\n    [RelType.COMPONENT]: IServiceLink,\n}\n\nexport type ActionLinks = {\n    [RelType.CREATE]: IServiceLink,\n    [RelType.RESTORE]: IServiceLink,\n    [RelType.DISCARD]: IServiceLink,\n    [RelType.DOWNLOAD]: IServiceLink,\n}\n\ninterface IRootChildLinks {\n    [RelType.PRIMARY]: IServiceLink,\n    [RelType.PAGE]?: IServiceLink,\n}\n\nexport type AssetLinks = AclLinks & NavigationLinks & AssociatedLinks & ActionLinks;\n\n// Used for client-provided set of links, where all but REPO_METADATA are optional.\nexport type MinimalAssetLinks =  RequiredProps<Partial<AssetLinks>, RelType.REPO_METADATA>;\n\nexport interface IEffectivePermissions {\n    '*'?: PermissionType[];\n    [RelType.PRIMARY]?: PermissionType[];\n    [RelType.AC_POLICY]?: PermissionType[];\n    [RelType.DIRECTORY]?: PermissionType[];\n    [RelType.APP_METADATA]?: PermissionType[];\n    [RelType.ANNOTATIONS]?: PermissionType[];\n}\n\n/**\n * The SAM.js representation of a repository.\n * For now it's simply an interface until we have requirements for\n * state or methods directly on the repository object.\n */\nexport interface IRepository {\n    id: string,\n    path: string,\n    name: string,\n    links: AssetLinks\n}\n\n/**\n * The response from the repository API for a particular repository.\n */\nexport interface IRepositoryResponse {\n    'repo:repositoryId': string,\n    'repo:repositoryType': string,\n    'repo:owner': {\n        'id': string,\n        'type': 'user' | 'org',\n    },\n    'repo:storageModel': string;\n    'repo:availableRegions': string[];\n    'repo:createDate': string;\n    'dc:title': {\n        '@type': string,\n        'rdf:_1': {\n            '@language': string,\n            '@value': string\n        }\n    }\n}\n\n/**\n * The response from the repository API for the Workfront index.\n */\nexport type IWorkfrontRepositoryIndexResponse = {\n    newWorkfrontParentDir: {\n        _embedded: {\n            [RelType.REPO_METADATA]: RepositoryMetadata,\n            [RelType.REPOSITORY]: IRepository\n        }\n    }\n}\n\nexport type RepositoryMetadata = {\n    'dc:format': Format,\n    'repo:name': string,\n    'repo:path': string,\n\n    // The server date and time the asset was created. This time may precede the date\n    // of the first version if it was created without a Primary Resource.\n    // The Date Time property conforms to the RFC 3339 standard.\n    'repo:createDate': string,\n\n    // The server date and time the Primary Resource of this Asset was last modified.\n    // The behavior may differ by Asset Class, as described in the specification.\n    // The Date Time property conforms to the RFC 3339 standard.\n    'repo:modifyDate': string,\n\n    // The Repository ID of the Repository storing this Asset.\n    'repo:repositoryId': string,\n\n    // A globally unique identifier for this Asset.\n    'repo:assetId': string,\n\n    // The class of this Asset (folder, composite, etc).\n    'repo:assetClass': AssetClass,\n\n    'repo:assetType': AssetType | undefined;\n    'repo:assetSubType': AssetSubType | undefined;\n\n    // @deprecated -- use repo:assetId\n    // 'repo:id': string,\n\n    // Size of the Primary Resource in bytes. Not applicable for directories\n    'repo:size': number,\n\n    // The HTTP entity tag of the Asset's Primary Resource.\n    'repo:etag': EntityTag,\n\n    // Identifier of the head version of the Asset. Applicable only to assets that support versioning and have a primary resource.\n    'repo:version': string,\n\n    // IMS User Id of the user who created this Asset.\n    'repo:createdBy': string,\n\n    // 'IMS User Id of the user who caused the last Asset modification, as defined in repo:modifyDate'\n    'repo:modifiedBy': string,\n\n    // 'Indicates whether an Asset is active, or if it has been directly or indirectly discarded.'\n    'repo:state': AssetState,\n\n    // The time the Asset was discarded, either directly or by inheritance. The Date Time property conforms to the RFC 3339 standard.\n    'repo:discardDate': string,\n\n    // IMS User Id of the user who discarded the Asset directly or by inheritance.\n    'repo:discardedBy': string,\n\n    // The date and time an Asset is scheduled for deletion, either directly or by inheritance.\n    'repo:scheduledDeletionDate': string,\n\n    // A policy set on Directories, to decide after how many hours the direct children shall be scheduled for deletion.\n    'repo:defaultScheduledDeletionDuration': string,\n\n    // IMS Client ID of the client that created this Asset.\n    'repo:createdByClientId': string,\n\n    // IMS Client ID of the client that last modified the Primary Resource of this Asset.\n    'repo:modifiedByClientId': string,\n\n    // IP address(es) received in x-forwarded-for header with request that created this Asset.\n    'repo:createdByIpAddress': string[],\n\n    // IP address(es) received in x-forwarded-for header with request that last modified the Asset.\n    'repo:modifiedByIpAddress': string[],\n\n    // assetId of asset's ancestors, root starts from index 0\n    'repo:ancestors': string[],\n\n    // Available asset class representations\n    'repo:representations': Representations,\n\n    // An opaque, unique identifier of the device associated with the most recent update to this Asset,\n    // if any. This property is removed when a request creates a new version of the Asset and does not\n    // specify a new value for this property.\n    'storage:deviceId': string,\n\n    // A timestamp capturing the time at which this Asset was created on the client, and which may\n    // therefore precede the time at which it was created in the Repository. (It can also be later,\n    // due to clock skew.).\n    // Can be set only at the time of Asset creation and, if not set, defaults to repo:createDate.\n    'storage:deviceCreateDate': string,\n\n    // A timestamp capturing the time at which this Asset was last modified on the client,\n    // and which may therefore precede the time at which the corresponding modification was\n    // uploaded to the Repository. (It can also be later, due to clock skew.).\n    // If not specified with any request that creates a new version of the Asset, it will\n    // be updated to repo:modifyDate.\n    'storage:deviceModifyDate': string,\n\n    'storage:assignee': Assignee,\n\n    'storage:directoryType': DirectoryType,\n\n    'storage:region': string,\n\n    // For image and video Assets, width in pixels. Otherwise, not present.\n    'tiff:imageWidth': number,\n\n    // For image and video Assets, height in pixels, Otherwise, not present.\n    'tiff:imageLength': number,\n\n    // For document Assets, number of pages or artboards. Otherwise, not present.\n    'xmpTPg:NPages': number,\n\n    // The pinned version of the asset, if any.\n    'repo:pinnedVersion'?: string,\n\n    // The date and time the pinned version was created, and is converted to a date object for AdobeAsset._pinnedVersionModifyDate.\n    'repo:pinnedVersionModifyDate'?: string,\n\n    _links: AssetLinks,\n\n    // If requested, listings can contain application metadata\n    _embedded?: RepoResponseEmbeddedData\n};\n\nexport interface IRepositoryData {\n    _embedded: {\n        [RelType.PRIMARY]: {\n            'dc:title'?: {\n                '@type': string,\n                'rdf:_1'?: {\n                    '@language': string,\n                    '@value': string\n                }\n            },\n            'storage:assignee': Assignee,\n            'repo:repositoryId': string,\n            'repo:owner': {\n                'id': string,\n                'type': 'user' | 'org',\n            }\n        }\n    }\n}\n\nexport interface IRepositoriesDataResponse {\n    children: IRepositoryData[];\n}\n\n\nexport type DirectoryListingRepoMetadata = {\n    children: RepositoryMetadata[];\n    _page: IAssetsPageSpec;\n    'repo:ancestors'?: string[];\n}\n\nexport type IOperationError = {\n    status: number | string;\n    title: string;\n    type: string;\n}\n\nexport type IOperationResultProps = {\n    error?: IOperationError;\n    asset?: RepositoryMetadata;\n}\nexport type IOperationResult = IOperation & IOperationResultProps;\n\n// In some cases the operation API returns a single error entry.\nexport type IOperationSingleError = {\n    code: string;\n    message: string;\n}\n\nexport type IOperationResults =  IOperationSingleError | IOperationResult | IOperationResult[];\n\n// The repository interface updates the return values to use SAM errors instead.\nexport type ISAMOperationResultProps = {\n    error?: SAMError;\n    asset?: RepositoryMetadata;\n}\nexport type ISAMOperationResult = IOperation & ISAMOperationResultProps;\nexport type ISAMOperationResults = ISAMOperationResult[];\n\n// The return obj inteface when one operation fails for any context\nexport interface IFailedOperation<LocalType> {\n    model: LocalType;\n    error: SAMError\n}\n\n// result for batch operations\n// failedResults contains failed list of items\n// newModels contains list of new assets which are added,\n// newModels will be populated with items for ops like copy/duplicate and will be empty in case of ops like move\nexport interface IBatchOperationResult<LocalType> {\n    failedResults: IFailedOperation<LocalType>[];\n    newModels: LocalType[];\n}\n\nexport interface ICopyOperation {\n    op: 'copy';\n    id?: string;\n    source: AssetRef;\n    target: AssetRefWithoutVersion;\n    intermediates?: boolean;\n    includeResources?: IResourceDesignator[];\n    excludeResources?: IResourceDesignator[];\n}\n\nexport interface IPublishOperation {\n    op: 'publish';\n    id?: string;\n    source: AssetRef;\n    target: AssetRefWithoutVersion;\n    intermediates?: boolean;\n    includeResources?: IResourceDesignator[];\n    excludeResources?: IResourceDesignator[];\n    rights?: {\n        [k: string]: unknown;\n    };\n    marked?: boolean;\n    usage_terms?: {\n        [k: string]: unknown;\n    };\n    web_statement?: string;\n    manage_ui?: string;\n    manage_to?: string;\n    license?: string;\n    attribution_url?: string;\n    attribution_name?: string;\n}\n\nexport interface IRemixOperation {\n    op: 'remix';\n    id?: string;\n    source: AssetRef;\n    target: AssetRefWithoutVersion;\n    intermediates?: boolean;\n    includeResources?: IResourceDesignator[];\n    excludeResources?: IResourceDesignator[];\n    creator_tool?: string;\n}\n\nexport interface ICopyResourcesOperation {\n    op: 'copy_resources';\n    id?: string;\n    source: AssetRef;\n    target: AssetRefWithoutVersion;\n    intermediates?: boolean;\n    resources: ResourceCopy[];\n}\n\nexport interface IMoveOperation {\n    op: 'move';\n    id?: string;\n    source: AssetRefWithoutVersion;\n    target: AssetRefWithoutVersion;\n    intermediates?: boolean;\n}\n\nexport interface IDeleteOperation {\n    op: 'delete';\n    id?: string;\n    target: AssetRefWithoutVersion;\n    recursive?: boolean;\n}\n\nexport interface IDiscardOperation {\n    op: 'discard';\n    id?: string;\n    target: AssetRefWithoutVersion;\n}\n\nexport interface IRestoreOperation {\n    op: 'restore';\n    id?: string;\n    target: AssetRefWithoutVersion;\n    name?: string;\n}\n\nexport interface IPackageOperation {\n    op: 'package';\n    id?: string;\n    source: OneOrMoreAssetRef;\n    target: AssetRefWithoutVersion;\n    max_package_size?: number;\n    'dc:format'?: Format;\n}\n\nexport interface IRootChild {\n    'repo:name': string;\n    'repo:path': string;\n    'dc:format': string;\n    _links: IRootChildLinks;\n}\n\n// Spec: https://wiki.corp.adobe.com/display/assetscollab/Proposal%3A+CCAC+Inherited+Metadata#Proposal:CCACInheritedMetadata-TeamFoldersandSpaces\nexport type IAppMetadata =  Partial<IRemoteStudentAssignmentFileMetadata> & Partial<IRemoteAssignmentAppMetadata> & Partial<IBrandsAssetAppMetadata> & Partial<GenerationHistoryAssetAppMetadata> & {\n    'shell:visibility'?: ShellVisibility;\n    'convertedTo'?: string;\n    'cc:inherited'?: { // contains any inheritable data from ancestors\n        'cc:team'?: {\n            'repo:assetId'?: string;\n        }\n        'cc:assignment'?: {\n            'repo:assetId'?: string;\n            'repo:name'?: string;\n        }\n        'cc:space'?: {\n            'repo:assetId'?: string;\n        };\n        'cc:studentAssignment'?: {\n            'repo:assetId'?: string;\n            'repo:name'?: string;\n        };\n        'cc:classroom'?: {\n            'repo:assetId'?: string;\n            'repo:name'?: string;\n        };\n        'cc:assignmentMaterials'?: {\n            'repo:assetId'?: string;\n            'repo:name'?: string;\n        };\n    };\n    'cc:inheritable'?: {\n        'cc:team'?: {\n            'repo:assetId'?: string;\n        },\n        'cc:assignment'?: {\n            'repo:assetId'?: string;\n            'repo:name'?: string;\n        },\n        'cc:studentAssignment'?: {\n            'repo:assetId'?: string;\n            'repo:name'?: string;\n        },\n        'cc:assignmentMaterials'?: {\n            'repo:assetId'?: string;\n            'repo:name'?: string;\n        };\n    };\n    'project:rendition'?: {\n        'gradientId': string;\n    };\n    'cc:createdFromUpload'?: boolean;\n}\n\nexport type RepoResponseEmbeddedData = {\n    [RelType.APP_METADATA]?: IAppMetadata;\n    [RelType.AC_EFFECTIVE]?: IEffectivePermissions;\n}\n\nexport type EmbedSpecifier = {\n    resource: {reltype: string}\n    selectors?: string[];\n}\n\nexport type RepositoryLinks = {\n    [RelType.RESOLVE_ID]: IServiceLink;\n    [RelType.RESOLVE_PATH]: IServiceLink;\n    [RelType.OPS]: IServiceLink;\n}\n\nexport interface IRepositoryIndex {\n    _links: RepositoryLinks;\n    // SAMJS-467: SAM.js sends a header to R-API to skip the repo:regions calculation,\n    // so this is always an empty array.\n    // 'repo:regions': string[],\n    children: { _embedded: { [RelType.REPO_METADATA]: RepositoryMetadata} }[];\n}\n\n// Currently, the Owner and Assignee have the same shape, but that could change.\n// Also, they're logically distinct entities.\nexport type Owner = Assignee;\n\nexport enum MoveWarning {\n    None,\n    CollaboratorMaybeEditing,\n    OwnerChange\n}\n\nexport enum CannotMoveReason {\n    DifferentOwner = 1,\n    PermissionDeniedDestination = 2,\n    PermissionDeniedSource = 3,\n    NotAFolder = 4,\n    CrossBucketMoveDisabled = 5,\n}\n\nexport type MoveCapability =\n    {\n        canMove: true;\n        /** @deprecated use {@link warnings} instead */\n        warning: MoveWarning;\n        warnings: MoveWarning[];\n    } |\n    { canMove: false; reason: CannotMoveReason; };\n\n// Note: this just describes the schema we've encountered in SAM.js,\n// and does not include all possible options.\n// https://git.corp.adobe.com/pages/caf/api-spec/schemas/accesscontrol/accesscontrolpolicy.html\nexport interface IACPolicyResponse {\n    'repo:acl': {\n        'repo:discoverable'?: boolean;\n        'repo:principal': 'all' | 'authenticated' | 'unauthenticated' |\n            // XDM principals, such as IMS users\n            {\n                'xdm:provider': { '@id': string };\n                '@id': string;\n                '@type': string;\n            };\n        'repo:modifier': 'grant' | 'deny';\n        'repo:privileges': ('read' | 'write' | 'delete')[];\n        'repo:relations': (\n            RelType.AC_POLICY |\n            RelType.ANNOTATIONS |\n            RelType.APP_METADATA |\n            RelType.EMBEDDED_METADATA |\n            RelType.REPO_METADATA |\n            RelType.PRIMARY |\n            RelType.RENDITION\n        )[];\n        'repo:inheritance': 'self' | 'deep' | 'deep_override';\n    }[];\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IUpdateSession } from './UpdateSession';\nimport { SharedChangeEvent } from './ChangeEvent';\nimport type SAMEvent from './SAMEvent';\nimport type { ItemId } from './ItemBase';\nimport type ItemBase from './ItemBase';\nimport type PropertyUpdater from './PropertyUpdater';\nimport SAMError, { SAMErrorCode } from './SAMError';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { getEventForProp } from './decorators/observable';\n\ntype ItemConstructor<LocalType extends ItemBase> = { new (core: ISAMCorePrivate, id: ItemId, ...args: any[]): LocalType };\n\nexport interface ILocalItemUpdaterOptions {\n    /**\n     * The property updater used to apply the changes.\n     */\n    propertyUpdater: PropertyUpdater;\n\n    /**\n     * The default event scheduled when a change is detected.\n     * @default value is the 'change' event.\n     */\n    changeEvent?: SAMEvent;\n\n    /**\n     * A mapping of properties to events to allow\n     * events to be sent for specific properties that\n     * have changed and override the default event.\n     */\n    changeEventMap?: Map<string, SAMEvent>\n}\n\nexport class LocalItemUpdater<LocalType extends ItemBase, RemoteType> {\n\n    protected _propertyUpdater: PropertyUpdater;\n    protected _changeEvent: SAMEvent;\n    protected _changeEventsMap?:  Map<string, SAMEvent>;\n\n    constructor(options: ILocalItemUpdaterOptions) {\n        this._propertyUpdater = options.propertyUpdater;\n        this._changeEvent = options.changeEvent || SharedChangeEvent;\n        this._changeEventsMap = options.changeEventMap;\n    }\n\n    /**\n     * Update the local item with values from the remote item.\n     * @param localItem\n     * @param remoteItem\n     */\n    updateLocalItem(updateSession: IUpdateSession<LocalType>, localItem: LocalType, remoteItem: RemoteType): void {\n        if (!updateSession.checkIfItemAllowsMutations(localItem)) {\n            // The item had local changes that we don't want to overwrite because\n            // the server might not yet be consistent with the change.\n            return;\n        }\n\n        // If the item is not already added, add it to the list.\n        updateSession.ensureItemIsAdded(localItem);\n        const changedFields = this._propertyUpdater.update(localItem, remoteItem);\n        const changeEvents = new Set(changedFields\n            .map(\n                changedProperty =>\n                    this._changeEventsMap?.get(changedProperty)\n                        ?? getEventForProp(localItem, changedProperty)\n                        ?? this._changeEvent\n            )\n        );\n        if (changedFields.length) {\n            updateSession.queueChangedItem(localItem, [ ...changeEvents ]);\n        }\n    }\n}\n\nexport interface IItemUpdaterBaseOptions<LocalType extends ItemBase, RemoteType> extends ILocalItemUpdaterOptions {\n    /**\n     * The constructor of the local object.\n     */\n    localItemType: ItemConstructor<LocalType>;\n\n    /**\n     * Returns the alternate ID, if any, for the value received from the local cache or server side.\n     * This is a placeholder until the primary ID is received.\n     * @param remoteItem\n     */\n    getAlternateId?: (remoteItem: RemoteType) => string | undefined;\n\n    /**\n     * Returns the ID for the value received from the server side.\n     * @param remoteItem\n     */\n    getRemoteId(remoteItem: RemoteType): string | undefined;\n}\n\n// Adds on remote id and placeholder (\"alternate\") id handling to the LocalItemUpdater\nexport class ItemUpdaterBase<LocalType extends ItemBase, RemoteType> extends LocalItemUpdater<LocalType, RemoteType> {\n\n    /**\n     * The constructor of the local object.\n     */\n    protected _localItemType: ItemConstructor<LocalType>;\n\n    protected _getRemoteId: (remoteItem: RemoteType) => string | undefined;\n    protected _getAlternateId: (remoteItem: RemoteType) => string | undefined;\n\n    constructor(options: IItemUpdaterBaseOptions<LocalType, RemoteType>) {\n        super(options);\n        this._localItemType = options.localItemType;\n        this._getRemoteId = options.getRemoteId;\n        this._getAlternateId = options.getAlternateId || (() => undefined);\n    }\n\n    /**\n     * If you have an instance of the item already (such `this` in the item class), use updateLocalItem directly.\n     * If you don't, use this method to create a new instance of the item from the remote data and update it locally.\n     */\n    updateRemoteItem(\n        updateSession: IUpdateSession<LocalType>,\n        remoteItem: RemoteType // server response data\n    ): LocalType {\n        const id = this._getRemoteId(remoteItem);\n        const altId = this._getAlternateId(remoteItem);\n        if (!id && !altId) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'An ID or alternate ID must exist on the remote item structure.');\n        }\n        let localItem = id ? updateSession.getItemById(id) : undefined;\n        // Item is not cached by primary ID so check if it has been cached by an alt ID\n        if (!localItem && altId) {\n            localItem = updateSession.getItemById(altId);\n            if (localItem) {\n                if (id) {\n                    // Re-index cached item with its new preferred ID (altId was a placeholder)\n                    updateSession.reindexItem(localItem, altId, id);\n                }\n\n            }\n\n        }\n\n        // Item is not cached at all so create a new instance\n        if (!localItem) {\n            const LocalItemType = this._localItemType;\n            // The primary altId is the first ID in the array\n            localItem = new LocalItemType(updateSession._core, id || altId!);\n        }\n\n        // Inject remote data.\n        this.updateLocalItem(updateSession, localItem, remoteItem);\n\n        return localItem;\n    }\n\n    updateRemoteItems(\n        updateSession: IUpdateSession<LocalType>,\n        remoteItems: RemoteType[]\n    ): LocalType[] {\n        if (!Array.isArray(remoteItems)) {\n            // Invalid remote data provided.\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid data received, expected list of items.');\n        }\n        return remoteItems.map((remoteItem) => this.updateRemoteItem(updateSession, remoteItem));\n    }\n}\n\nexport interface IItemUpdaterOptions<LocalType extends ItemBase, RemoteType>\n    // Removing the `getRemoteId` requirement as we are going to implement it in the `ItemUpdater` constructor\n    // based on the remoteIdProperty passed via this interface.\n    extends Omit<IItemUpdaterBaseOptions<LocalType, RemoteType>, 'getRemoteId'>\n{\n    /**\n     * Can be used to customize the property of the remote id that is used for the hash lookup.\n     *\n     * @see If the `id` is more complicated to reach and is not an immediate property of the RemoteType,\n     * then you can use the `ItemUpdaterBase` instead and override the `getRemoteId` method instead\n     * of using the `remotePropertyId` name in this class.\n     */\n    remoteIdProperty: string;\n}\n\n// Adds the ability to customize the remote id property that is used to get the remote id to ItemUpdaterBase\nexport default class ItemUpdater<LocalType extends ItemBase, RemoteType> extends ItemUpdaterBase<LocalType, RemoteType> {\n    public changeEventMap?: Map<string, SAMEvent>;\n    constructor(options: IItemUpdaterOptions<LocalType, RemoteType>) {\n        super(Object.assign({\n            getRemoteId(remoteItem: RemoteType): string | undefined {\n                // The generic types in TS are not lazy evaluated, so TS will try to resolve this based entirely\n                // on the constraints added to the generic type. Maybe one day TS will be able to evaluate\n                // based on the actual interface that is passed as the `RemoteType` and we could fix this model.\n                // As a result, we have use `any` because TS doesn't know the type of the generic RemoteType.\n                return (remoteItem as any)[options.remoteIdProperty];\n            },\n        }, options));\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ISAMObject } from '../indexPrivate';\nimport type { IsEqualFn } from './ObjectUtils';\nimport { deepClone, isDeepEqual, isStrictEqual } from './ObjectUtils';\nimport SAMError, { SAMErrorCode } from './SAMError';\n\nexport const NotFound = Symbol('NotFound');\n\ntype ParseFn = (a: any) => any;\n\nexport type PropertyFormatType = {\n    parse: ParseFn,\n    isEqual: IsEqualFn\n}\n\ntype GetFn = (source: any, dest: ISAMObject) => any;\ntype SetFn = (parsedSource: any, dest: ISAMObject) => any;\n\ntype BuiltinPropertyFormats = 'string' | 'boolean' | 'number' | 'date' | 'date_as_number' | 'object' | 'object_subset';\ntype PropertyFormat = BuiltinPropertyFormats | PropertyFormatType;\n\ntype IPropertyType = {\n    name: string,\n    format: PropertyFormatType,\n    choices?: any[],\n    isArray: boolean,\n    mapByKey?: string,\n    // \"get\" from the source data\n    get: GetFn,\n    // \"set\" on the dest object\n    set: SetFn\n}\n\ntype IUserPropertyType = string | {\n    name?: string,\n    format?: PropertyFormat,\n    choices?: any[],\n    isArray?: boolean,\n    mapByKey?: string,\n    get?: GetFn,\n    set?: SetFn\n};\n\nexport type IPropertyTypeMap = {\n    [key: string]: IUserPropertyType\n}\n\ntype IPropertyUpdater = (dest: ISAMObject, source: any) => boolean;\n\nconst formats: { [ key in BuiltinPropertyFormats ]: PropertyFormatType } = {\n    string: {\n        // In general, parse strings as strings, but special case null's as undefined, and undefined's as undefined since String() will convert them to \"undefined\".\n        parse: (value: any) => (value === null) || (value === undefined) ? undefined : String(value),\n        isEqual: isStrictEqual\n    },\n    number: {\n        parse: Number,\n        isEqual: isStrictEqual\n    },\n    date: {\n        parse: (value: any) => {\n            if (value === null) {return undefined;}\n            if (value === undefined || value instanceof Date) { return value; }\n            return new Date(String(value));\n        },\n        isEqual: (a?: Date, b?: Date) => a?.toISOString() === b?.toISOString()\n    },\n    // Some APIs like the invitation service return dates as a number (Unix epoch time) rather than a string\n    // These still map onto the JS Date object, but need to be parsed differently.\n    date_as_number: {\n        parse: (value: any) => value === undefined ? undefined : new Date(Number(value)),\n        isEqual: (a?: Date, b?: Date) => a?.toISOString() === b?.toISOString()\n    },\n\n    // Support actual booleans, the string 'true', or non-zero numbers.\n    boolean: {\n        parse: (value: any) => value === true\n            || (typeof value === 'string' && value.toLowerCase() === 'true')\n            || (typeof value === 'number' && Boolean(value)),\n        isEqual: isStrictEqual\n    },\n    object: {\n        // Make a deep copy of the object if it is defined.\n        parse: (value: any) => value !== undefined ? deepClone(value) : undefined,\n        isEqual: isDeepEqual\n    },\n    // Sometimes the source data is only going to be merged into the destination property, so\n    // comparison only needs to happen among the top-level keys that are present in the source.\n    object_subset: {\n        parse: deepClone,\n        isEqual(destObj: any, sourceObj: any): boolean {\n            // if both are undefined, then they are equal\n            if (destObj === sourceObj) { return true; }\n            // if destObj is undefined, then it can be overwritten with sourceObj\n            // NOTE: sourceObj is expected to not be undefined because JSON doesn't support undefined properties,\n            // and so will get skipped since the sourceObj will be NotFound.\n            if (destObj === undefined) {\n                return false;\n            }\n\n            // Fix for https://jira.corp.adobe.com/browse/SHARED-2096\n            //\n            // Although we don't expect our servers to return null's,\n            // we are receiving repometadata with :\n            //   \"_embedded\": {\n            //      \"http://ns.adobe.com/adobecloud/rel/metadata/application\": null\n            //   }\n            //\n            // which reaches this code as (sourceObj === null),\n            // which causes Object.keys(null) to throw\n            //   TypeError: Cannot convert undefined or null to object\n            //\n            // The code below would return true for sourceObj = {},\n            // so it makes sense to have an early return of true for sourceObj = null.\n            //\n            // NOTE: At the moment, the only client of 'object_subset' is '_appMetadata._data',\n            // which would work with returning true ( the setter isn't invoked because sourceObj\n            // isEqual() to the existing data ) or false ( the setter is invoked, but _mergeData(null)\n            // is the same as _mergeData( {} ), which doesn't add anything to data ). The difference\n            // is the setter would also emit('change') despite nothing changing.\n            //\n            // ALSO NOTE: Some servers might meaningfully provide (sourceObj === null) to have us\n            // delete local data, but our server's don't, and if they did, our use of 'object_subset'\n            // would have to be re-written to handle this as _mergeData(null) doesn't. But if they\n            // did, we'd need to return false for this case. Until then, we're returning true\n            // to avoid the unnecessary change event.\n\n            if (!sourceObj) {\n                return true;\n            }\n\n            const sourceKeys =  Object.keys(sourceObj);\n            const destObjSubset = sourceKeys.reduce((result: any, key: string) => {\n                result[key] = destObj[key];\n                return result;\n            }, {});\n            return isDeepEqual(destObjSubset, sourceObj);\n        }\n    }\n};\n\nconst KEY_REGEXP = /([^.[]+)|(\\[[^\\]]+\\])/g;\nfunction getKeys(name: string): string[] {\n    const keys = name.match(KEY_REGEXP) || [];\n    if (!keys.length) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Un-parseable key ${name}`);\n    }\n    const newKeys = keys.map(key => {\n        // Remove brackets\n        if (key[0] === '[' && key.slice(-1) === ']') {\n            return key.slice(1, -1);\n        }\n        return key;\n    });\n    return newKeys;\n}\n\nfunction makeGetFn(name: string) {\n    const keys = getKeys(name);\n    return (source: any) => {\n        let value = source;\n        for (const key of keys) {\n            if (!Object.prototype.hasOwnProperty.call(value, key)) {\n                return NotFound;\n            }\n            value = value[key];\n        }\n        return value;\n    };\n}\n\nfunction makeSetFn(name: string) {\n    if (name.includes('.')) {\n        // For complex properties of the Item being updated, assumptions can't be made about how to set them,\n        // because some might be a class instance.\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Cannot use dot delimiter (${name}) without a custom setter`);\n    }\n    return (parsedSource: any, dest: any): void => {\n        dest[name] = parsedSource;\n    };\n}\n\nfunction makeMergeSetFn(name: string) {\n    if (name.includes('.')) {\n        // For complex properties of the Item being updated, assumptions can't be made about how to set them,\n        // because some might be a class instance.\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Cannot use dot delimiter (${name}) without a custom setter`);\n    }\n    return (parsedSource: any, dest: any): void => {\n        dest[name] = {\n            ...(dest[name] ?? {}),\n            ...(parsedSource ?? {})\n        };\n    };\n}\n\nfunction normalizeFormat(name: string, format?: PropertyFormat, mapByKey?: string): PropertyFormatType {\n    if (!format) {\n        // When we use mapByKey, the format is always an object as needs to have the actual mapByKey property.\n        return mapByKey ? formats.object : formats.string;\n    }\n    if (typeof format === 'string') {\n        if (!Object.prototype.hasOwnProperty.call(formats, format)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Unexpected type format ${format} for ${name} property updater.`);\n        }\n        return formats[format];\n    }\n    return format as PropertyFormatType;\n}\n\nfunction normalizeType(key: string, type: IUserPropertyType): IPropertyType {\n    // When the property type is a simple string, then the source property is a simple\n    // string parameter\n    if (typeof type === 'string') {\n        return {\n            name: key,\n            format: formats.string,\n            get: makeGetFn(type),\n            set: makeSetFn(key),\n            isArray: false\n        };\n    }\n\n    const { name, format, choices, get, set, isArray, mapByKey } = type;\n    const sourceName = name ?? key;\n    return {\n        name: sourceName,\n        format: normalizeFormat(sourceName, format, mapByKey),\n        choices,\n        mapByKey,\n        isArray: isArray ?? false,\n        get: get ?? makeGetFn(name ?? key),\n        set: set ?? (format === 'object_subset' ? makeMergeSetFn(key) : makeSetFn(key))\n    };\n}\n\nfunction validateValue(dest: ISAMObject, name: string, choices: any[] | undefined, value: any): boolean {\n    if (choices && !choices.includes(value)) {\n        dest._core._environment.error(`Invalid value ${value} passed for the ${name} property. Expected one of ${ choices.join(', ') }.`);\n        return false;\n    }\n    return true;\n}\n\nfunction createPropertyUpdater(key: string, userType: IUserPropertyType): IPropertyUpdater {\n    const type = normalizeType(key, userType);\n    const { name, format, choices, get, set, isArray, mapByKey } = type;\n\n    return (dest: ISAMObject, source: any): boolean => {\n        const anyDest: any = dest;\n        const destValGetter = makeGetFn(key);\n        // If the dest property does not exist, treat it as undefined so it can be updated\n        // This prevents the `a.toISOString is not a function` error for date fields\n        const destVal = (destValGetter(anyDest) === NotFound ? undefined : destValGetter(anyDest));\n\n        let value = get(source, dest);\n        if (value === NotFound) {\n            return false;\n        }\n\n        if (mapByKey) {\n            /**\n             * The input value is just an array like the following example:\n             *\n             * [\n             *     {\n             *         name: 'working_files',\n             *         id: 'urn:1'\n             *     },\n             *     {\n             *         name: 'canvases',\n             *         id: 'urn:2'\n             *     }\n             * ]\n             *\n             * The result will be a Map object like the following:\n             *\n             *  'working_files' => {\n             *      name: 'working_files',\n             *      id: 'urn:1'\n             *  },\n             *  'canvases' => {\n             *      name: 'canvases',\n             *      id: 'urn:1'\n             *  },\n             *\n             * - In this case the 'name' property becomes the key of the map. The caller can change the key using the\n             * `mapByKey` variable.\n             * - The actual value of the map entries is just the object itself.\n             * - This value can be customized using the `format.parse` function provided by the caller.\n             * - The parsed value can be validated against a predefined list of `choices` provided by the caller.\n             */\n            if (!Array.isArray(value)) {\n                dest._core._environment.error(`Invalid value ${value} passed for the ${name} property. Expected an array.`);\n                return false;\n            }\n\n            const map = new Map();\n            for (const item of value) {\n                if (!Object.prototype.hasOwnProperty.call(item, mapByKey)) {\n                    dest._core._environment.error(`Invalid item passed for the ${name} array property. Missing ${mapByKey} property on the item of the array.`);\n                    continue;\n                }\n                const key = item[mapByKey];\n                const parsedItem = format.parse(item);\n                if (!validateValue(dest, name, choices, parsedItem)) {\n                    continue;\n                }\n                map.set(key, parsedItem);\n            }\n\n            if (isDeepEqual(destVal, map)) {\n                return false;\n            }\n\n            value = map;\n\n        } else if (isArray) {\n            if (!Array.isArray(value)) {\n                dest._core._environment.error(`Invalid value ${value} passed for the ${name} property. Expected an array.`);\n                return false;\n            }\n            // Arrays must make a copy of their initial content to avoid mutations\n            // of the original array after the value is stored inside the object.\n            const array = [];\n            for (const item of value) {\n                const parsedItem = format.parse(item);\n                if (validateValue(dest, name, choices, parsedItem)) {\n                    array.push(parsedItem);\n                }\n            }\n            if (isDeepEqual(destVal, value)) {\n                return false;\n            }\n\n            value = array;\n\n        } else {\n            value = format.parse(value);\n            if (!validateValue(dest, name, choices, value)) {\n                return false;\n            }\n            if (format.isEqual(destVal, value)) {\n                return false;\n            }\n        }\n\n        set(value, anyDest);\n        return true;\n    };\n}\n\nexport default class PropertyUpdater {\n\n    private _updaters: { updater: IPropertyUpdater; key: string}[];\n\n    constructor(map: IPropertyTypeMap) {\n        this._updaters = Object.keys(map).map(\n            (key) => {\n                return {\n                    updater: createPropertyUpdater(key, map[key]),\n                    key\n                };\n            }\n        );\n    }\n\n    update(dest: ISAMObject, source: any): string[] {\n        const propertyChanges = [];\n        for (const updateObj of this._updaters) {\n            const { updater, key } = updateObj;\n            if (updater(dest, source)) {\n                propertyChanges.push(key);\n            }\n        }\n        return propertyChanges;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type {\n    Format,\n    Assignee,\n    AssetLinks,\n    ShellVisibility,\n    IAppMetadata,\n    PermissionType,\n    RepoResponseEmbeddedData,\n    Representations\n} from './RepositoryModel';\nimport type { AdobeAssetOrderField } from '../assets/AdobeAssetOrder';\nimport type { USSAdobeAssetOrderField } from '../assets/USSAdobeAssetOrder';\nimport type { IUSSFetchFieldType, IPerUserMetadata } from './AssetModel';\nimport type { RelType } from './LinkUtils';\n\nexport enum SearchProps {\n    STORAGE_ASSIGNEE_TYPE = 'storage:assignee$$type',\n    VISIBILITY = 'app_metadata$$shell:visibility',\n    CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME = 'creative_cloud_toplevel_collection_name',\n    FIELD_EXISTS = 'op_field_exists',\n    FIELD_MATCHES = 'op_field_matches',\n    INCLUDES = 'includes',\n    TYPE = 'type',\n    STORAGE_ASSIGNEE_ID = 'storage:assignee$$id',\n    SHARED_VIA_INVITE = 'shared_via_invite',\n    OP_AND = 'op_and',\n    OP_OR = 'op_or',\n    REPO_ACL_MODIFIER = 'repo:acl$$repo:modifier',\n    REPO_ACL_PRIVILEGES = 'repo:acl$$repo:privileges',\n    REPO_ACL_RELATIONS = 'repo:acl$$repo:relations',\n    CREATED_FROM_UPLOAD = 'app_metadata$$cc:createdFromUpload',\n    CREATED_BY_CLIENT_ID = 'repo:createdByClientId'\n}\n\nexport const USS_ARTIFACT_MEDIATYPE = 'app_metadata$$review:sourceAsset$$dc:format';\n\nexport const LastAccessedOrderField = 'api:metadata/peruser#mine$$shell:lastAccessDate';\n\nexport type IStorageAssigneeType =\n    | 'user'\n    | 'org';\n\nexport type ISearchSortOrderDirection =\n    | 'asc'\n    | 'desc';\n\nexport type ISearchSortOrderBy =\n    | 'asset_name'\n    | 'create_date'\n    | 'modify_date'\n    | 'shared_date'\n    | typeof LastAccessedOrderField;\n\nexport type ISearchVisibility = ShellVisibility;\n\nexport const OrderByToUSSOrderBy: { [key in AdobeAssetOrderField | USSAdobeAssetOrderField]: ISearchSortOrderBy } = {\n    name: 'asset_name',\n    created: 'create_date',\n    modified: 'modify_date',\n    shared: 'shared_date',\n    lastAccessed: LastAccessedOrderField\n};\n\nexport interface IHintsACPPlatform {\n    acp_platform_v2: boolean;\n    creative_cloud_rendition_v2?: boolean;\n}\n\nexport type IHint = IHintsACPPlatform;\n\ntype IncludeFields =\n    | 'app_metadata'\n    | 'collaboration_metadata'\n    | '_embedded'\n    | 'collab_metadata$$collaborators'\n    | typeof LastAccessedOrderField\n    | IUSSFetchFieldType;\n\nexport interface IFetchFieldsInclude {\n    [SearchProps.INCLUDES]: IncludeFields[];\n}\n\nexport interface IContainer {\n    asset_id: string[];\n}\n\n// These are a subset of fields USS supports for `op_field_exists`\n// Others are available.\ntype FieldExists =\n    | 'app_metadata$$review:sourceAsset$$dc:format'\n    | 'app_metadata$$cc:inheritable$$cc:team$$repo:assetId'\n    | 'app_metadata$$cc:inherited$$cc:team$$repo:assetId'\n    | 'app_metadata$$cc:inheritable$$cc:space$$repo:assetId'\n    | 'app_metadata$$cc:inherited$$cc:space$$repo:assetId'\n    | 'app_metadata$$cc:createdFromUpload'\n    | typeof LastAccessedOrderField;\n\ntype FieldMatches = {\n    'app_metadata$$project:directoryType'?: 'team';\n    [USS_ARTIFACT_MEDIATYPE]?: string;\n}\n\nexport interface IOpFieldExists {\n    [SearchProps.FIELD_EXISTS]: FieldExists[];\n}\n\nexport interface IOpFieldMatches {\n    [SearchProps.FIELD_MATCHES]: FieldMatches;\n}\n\nexport interface IOpAnd {\n    [SearchProps.OP_AND]: IOp;\n}\n\nexport interface IOpOr {\n    [SearchProps.OP_OR]: IOp;\n}\n\nexport interface IOpVisibility {\n    [SearchProps.VISIBILITY]: ISearchVisibility | ISearchVisibility[];\n}\n\n// \"assets\" and \"archive\" = /assets and /archive folders, respectively\ntype TopLevelCollectionName = 'archive' | 'appdata' | 'assets' | 'cloud-content' | 'pubs' | 'files';\nexport interface IOpTopLevelCollection {\n    [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: TopLevelCollectionName | TopLevelCollectionName[];\n}\n\nexport interface IOpType {\n    [SearchProps.TYPE]: string[];\n}\n\nexport interface IOpStorageAssigneeId {\n    [SearchProps.STORAGE_ASSIGNEE_ID]: string | string[];\n}\n\nexport interface IOpStorageAssigneeType {\n    [SearchProps.STORAGE_ASSIGNEE_TYPE]: IStorageAssigneeType;\n}\n\nexport interface IOpCreatedFromUpload {\n    [SearchProps.CREATED_FROM_UPLOAD]: boolean;\n}\n\nexport interface IOpCreatedByClientId {\n    [SearchProps.CREATED_BY_CLIENT_ID]: string;\n}\n\nexport interface IOpHasPermission {\n    [SearchProps.REPO_ACL_MODIFIER]: 'grant';\n    [SearchProps.REPO_ACL_PRIVILEGES]: PermissionType[];\n    [SearchProps.REPO_ACL_RELATIONS]: RelType[];\n}\n\nexport interface IOpSharedViaInvite {\n    [SearchProps.SHARED_VIA_INVITE]: boolean;\n}\n\nexport type IOp = (\n    | IOpFieldExists\n    | IOpVisibility\n    | IOpTopLevelCollection\n    | IOpType\n    | IOpStorageAssigneeId\n    | IOpSharedViaInvite\n    | IOpAnd\n    | IOpOr\n    | IOpStorageAssigneeType\n    | IOpHasPermission\n    | IOpCreatedFromUpload\n    | IOpCreatedByClientId\n    | IOpFieldMatches\n)[];\n\n/**\n * USS API Docs\n * https://git.corp.adobe.com/pages/adobesearch/search-services-docs/uss/cc/response/\n */\nexport interface ISearchQuery {\n    [SearchProps.STORAGE_ASSIGNEE_TYPE]?: IStorageAssigneeType[];\n    [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]?: TopLevelCollectionName[];\n    asset_id_opacity?: boolean;\n    creative_cloud_archive?: boolean;\n    creative_cloud_discarded_directly?: boolean;\n    container?: IContainer;\n    fetch_fields?: IFetchFieldsInclude;\n    hints?: IHint | IHint[];\n    limit?: number;\n    op_and?: IOp;\n    op_none_of?: IOp;\n    op_or?: IOp;\n    op_field_exists?: FieldExists[];\n    op_field_matches?: FieldMatches;\n    scope?: string[];\n    shared_by_me?: boolean;\n    parent_id?: string[];\n    shared_via_invite?: boolean;\n    sort_order?: ISearchSortOrderDirection;\n    sort_orderby?: ISearchSortOrderBy;\n    start_index?: number;\n    [SearchProps.TYPE]?: string[];\n    q?: string;\n    [SearchProps.STORAGE_ASSIGNEE_ID]?: string | string[];\n    creative_cloud_asset_type?: 'asset' | 'collection' | 'mount' | 'dcx';\n    asset_name?: string,\n    asset_id?: string,\n    sync_created_date?: { range: { min?: string, max?: string } };\n    sync_updated_date?: { range: { min?: string, max?: string } };\n}\n\ntype USSResponseResultSet = {\n    items: Partial<USSMetadata>[]\n    total_items: number,\n}\n\ntype USSResponseStatus = {\n    scope: string;\n    status: number;\n}\n\nexport type USSResponse = {\n    result_sets: USSResponseResultSet[];\n    status: USSResponseStatus[];\n}\n\ntype IUSSColaborationPermissions = 'canShare' | 'canComment';\n\ninterface IUSSCollaborationMetadata {\n    collaborator_id: string;\n    inviter_id: string;\n    shared_date: number;\n    role: 'viewer' | 'editor';\n    permissions: IUSSColaborationPermissions[];\n    type?: 'individual' | 'group';\n    modified_date: number;\n}\n\nexport interface IUSSApplicationMetadata {\n    'cc:createdFromUpload'?: boolean;\n}\n\nexport type USSMetadata = {\n    type: Format,\n    asset_name: string,\n    asset_name_path: string,\n\n    create_date: string,\n\n    modify_date: string,\n\n    // A globally unique identifier for this Asset.\n    asset_id: string,\n\n    // the etag equivalent for composites\n    composite_manifest_etag: string,\n    etag: { primary: string },\n\n    // The Repository ID of the Repository storing this Asset.\n    'repo:repositoryId': string\n\n    // As per USS docs, this field is either 'composite' or 'element' when `creative_cloud_asset_type` is 'dcx'\n    // https://git.corp.adobe.com/pages/adobesearch/search-services-docs/uss/cc/response/\n    asset_sub_type: 'composite' | 'element',\n\n    'collab_metadata#mine': IUSSCollaborationMetadata,\n\n    // USS returns one of the following 4 values for this field\n    creative_cloud_asset_type: 'asset' | 'collection' | 'mount' | 'dcx',\n\n    // colortheme & gradient only apply to discarded Library Elements?\n    creative_cloud_colortheme?: any;\n    creative_cloud_gradient?: any;\n\n    // Size of the Primary Resource in bytes. Not applicable for directories\n    size: number,\n\n    // IMS User Id of the user who created this Asset.\n    creative_cloud_creator_id: string,\n\n    // WARNING: do not use. This appears to be populated by the XMP metadata version from the MANIFEST,\n    // not `repo:version` from repo metadata.\n    // 'repo:version': string;\n\n    // This field maps to the repo metadata repo:version field\n    'asset_version_id': string;\n\n    'storage:assignee': Assignee,\n\n    region: string,\n\n    collab_metadata: object,\n\n    collaboration_metadata: IUSSCollaborationMetadata[],\n\n    app_metadata: IAppMetadata,\n\n    // assetId of asset's ancestors, root starts from index 0\n    path: string[],\n\n    _links: AssetLinks,\n\n    // per user metadata\n    'api:metadata/peruser': IPerUserMetadata[],\n    'api:metadata/application': IUSSApplicationMetadata,\n\n    // effective permissions\n    _embedded: RepoResponseEmbeddedData\n\n    // available asset representations\n    'repo:representations': Representations\n};\n","import {\n    type IOpFieldMatches,\n    SearchProps,\n    USS_ARTIFACT_MEDIATYPE\n} from '../interface/USSModel';\n\nexport const EXPRESS_ARTIFACT_TYPE = 'application/vnd.adobe.hz.express+dcx';\n\nexport function excludeExpressArtifacts(): IOpFieldMatches[] {\n    return [ {\n        [SearchProps.FIELD_MATCHES]: { [USS_ARTIFACT_MEDIATYPE]: EXPRESS_ARTIFACT_TYPE }\n    } ];\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport { EXPRESS_ARTIFACT_TYPE } from '../utils/excludeExpressArtifacts';\n\nexport interface IImplicitAdobeAssetFilterBaseOptions {\n    readonly _includeHiddenRecursive?: boolean;\n    readonly _isDiscarded?: boolean;\n    readonly _isPublished?: boolean;\n    readonly _isSharedWithYou?: boolean;\n}\n\n/**\n * Class for handling common filtering for AdobeAsset ItemSources. All implicit filters for AdobeAsset\n * should extend this class.\n */\n\nexport default abstract class ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    private _isDiscarded: boolean = false;\n    private _isPublished: boolean = false;\n    private _isSharedWithYou: boolean = false;\n    private _includeHiddenRecursive: boolean = false;\n\n    constructor(options?: Partial<IImplicitAdobeAssetFilterBaseOptions>) {\n        this._includeHiddenRecursive = !!(options?._includeHiddenRecursive);\n        this._isDiscarded = !!(options?._isDiscarded);\n        this._isPublished = !!(options?._isPublished);\n        this._isSharedWithYou = !!(options?._isSharedWithYou);\n    }\n\n    matches(item: AdobeAsset): boolean {\n        // If a Composite has zero size, it's probably an intermediate that is pending content, so\n        // it should not be visible until the content is available. Client apps are responsible for cleaning\n        // up Composites that never get content. There are two exceptions:\n        //   1. New Libraries always have correct size from Melville, but sometimes the first ONS notification\n        //      does not reflect the Library contents being written yet.\n        //   2. Items populated by ACPL shouldn't be filtered out, because they're likely just in the process of uploading.\n        // In both cases, we don't want the item to flicker in and out while it settles.\n        if (item.isComposite && item.sizeInBytes === 0 && !item.isLibrary && !item.localID) {\n            return false;\n        }\n\n        if (item.isDiscarded !== this._isDiscarded) {\n            return false;\n        }\n\n        if ((item._isSWYAsset_NoLazyLoad) && item._isSWYAsset_NoLazyLoad !== this._isSharedWithYou) {\n            return false;\n        }\n\n        // Do not include children of directly discarded Assets in isDiscarded\n        if (this._isDiscarded && item['_assetState'] === 'DISCARDED_PARENT') {\n            return false;\n        }\n\n        if (item.isPublished !== this._isPublished) {\n            return false;\n        }\n\n        // ONS subscriptions may cause loading of /cloud-content-archive or /archive when monitoring discardSource list\n        // items but these folders should never appear in any list.\n        if (item.repoPath === '/cloud-content-archive' || item.repoPath === '/archive') {\n            return false;\n        }\n\n        // SAMJS-773 Exclude Express artifacts by default. This will likely be temporary.\n        if (item.reviewLinkSourceType === EXPRESS_ARTIFACT_TYPE) {\n            return false;\n        }\n\n        // For all sources of AdobeAsset, the shellVisibility field dictates whether it can be seen in UI,\n        // except for when items in hidden folders (hiddenRecursive) must be included.\n        return !((item.shellVisibility === 'hiddenSelf' || (item.shellVisibility === 'hiddenRecursive' && !this._includeHiddenRecursive)));\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport path from 'path-browserify';\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\n\nexport interface IAdobeAssetSearchFilterOptions {\n    readonly deepSearch?: boolean;\n    readonly query?: string;\n    readonly asset?: AdobeAsset;\n}\n\nexport default class AdobeAssetSearchFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    private _deepSearch?: boolean | undefined;\n    private _asset?: AdobeAsset;\n    _query?: string;\n\n    constructor(options?: Partial<IAdobeAssetSearchFilterOptions>) {\n        super();\n        this._query = options?.query;\n        this._deepSearch = options?.deepSearch;\n        this._asset = options?.asset;\n    }\n\n    get deepSearch(): boolean | undefined {\n        return this._deepSearch;\n    }\n\n    get asset(): AdobeAsset | undefined {\n        return this._asset;\n    }\n\n    get query(): string | undefined {\n        return this._query;\n    }\n\n    // The matching rules USS are deceptively complex, and could change over time. Attempting to\n    // replicate here could result in items being incorrectly filtered out or incorrectly included.\n    // Search Lists should not try to share items from Lists with similar queries, other\n    // than treating the queries as case-insensitve.\n    // TODO: Lists filtered with AdobeAssetSearchFilter currently take on unwanted items:\n    // https://jira.corp.adobe.com/browse/SAM-3118\n    matches(item: AdobeAsset): boolean {\n\n        // USS does not give repository id of an item. So compare repository id\n        // only when it is available on both assets\n        if (this.asset && this.asset.repositoryID && item.repositoryID\n            && this.asset.repositoryID !== item.repositoryID) {\n            return false;\n        }\n\n        // If asset is set, check whether item should belong this search or not based on\n        // deep search. If deep search is true this asset should be container for incoming\n        // item else this asset should be immediate parent of incoming asset\n        if (this.asset && this.asset.repoPath && item.repoPath) {\n            const assetRepoPath = this.asset.repoPath;\n            if (this.deepSearch) {\n                if (!item.repoPath.startsWith(path.join(assetRepoPath, '/'))) {\n                    return false;\n                }\n            } else if (assetRepoPath !== item.repoPath.substring(0, item.repoPath.lastIndexOf('/'))) {\n                return false;\n            }\n        }\n\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ItemBase from './ItemBase';\n\nexport type IOrderDirection =\n    | 'ascending'\n    | 'descending';\n\nexport type IItemOrderHash = string;\n\n/**\n * Structure used to sort the items once loaded.\n */\nexport interface IItemOrder<LocalType extends ItemBase> {\n    /**\n     * Hash that can be used to uniquely identify this sorting order.\n     * This hash is used for caching in the ItemSource implementation.\n     */\n    readonly hash: IItemOrderHash;\n    readonly direction: IOrderDirection;\n\n    /**\n     * Sorts the items inplace using the sorting order.\n     * @param items to be sorted inplace.\n     */\n    sortItems(items: LocalType[]): void;\n}\n\nexport function compareStrings(a: string, b: string): number {\n    return a.localeCompare(b);\n}\n\nexport function compareValues<T>(a: T, b: T): number {\n    if (a === b) {\n        return 0;\n    }\n    return a < b ? -1 : 1;\n}\n\nexport type ComparatorFn<LocalType extends ItemBase> = (a: LocalType, b: LocalType) => number;\n\nexport type IComparatorMap<LocalType extends ItemBase, IOrderField extends string> = {\n    [key in IOrderField]: ComparatorFn<LocalType>;\n}\n\nfunction reverseComparator<LocalType extends ItemBase>(comparator: ComparatorFn<LocalType>) {\n    return (a: LocalType, b: LocalType) => -comparator(a, b);\n}\n\nclass ItemOrder<LocalType extends ItemBase, IOrderField> implements IItemOrder<LocalType> {\n    constructor(\n        readonly direction: IOrderDirection,\n        readonly field: IOrderField,\n        readonly comparator: ComparatorFn<LocalType>) {\n    }\n\n    get hash(): IItemOrderHash {\n        return this.direction + ':' + this.field;\n    }\n\n    sortItems(items: LocalType[]): void {\n        items.sort(this.comparator);\n    }\n}\n\nexport function createItemOrderFactory<LocalType extends ItemBase, IOrderField extends string>(\n    comparatorMap: IComparatorMap<LocalType, IOrderField>) {\n\n    return class extends ItemOrder<LocalType, IOrderField> {\n        constructor(direction: IOrderDirection, field: IOrderField) {\n            let comparator = comparatorMap[field];\n            if (direction === 'descending') {\n                comparator = reverseComparator(comparator);\n            }\n            super(direction, field, comparator);\n        }\n    };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IAdobeAssetOrderBy } from '../interface/AssetModel';\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type AdobeAsset from './AdobeAsset';\n\nexport type AdobeAssetOrderField =\n    | 'name'\n    | 'created'\n    | 'modified'\n    | 'shared';\n\nexport const OrderFieldToIAdobeAssetOrderBy: { [key in AdobeAssetOrderField]: IAdobeAssetOrderBy } = {\n    'name': 'repo:name',\n    'created': 'storage:deviceCreateDate',\n    'modified': 'storage:deviceModifyDate',\n    // R-API doesn't sort on share date\n    'shared': 'storage:deviceModifyDate'\n};\n\nconst OrderFieldToComparator: IComparatorMap<AdobeAsset, AdobeAssetOrderField> = {\n    name(a: AdobeAsset, b: AdobeAsset): number {\n        return compareStrings(a.name, b.name);\n    },\n    created(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.created, b.created);\n    },\n    modified(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.modified, b.modified);\n    },\n    shared(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.shared, b.shared);\n    }\n};\n\nexport default class AdobeAssetOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new AdobeAssetOrder('descending', 'modified');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMEvent from '../core/SAMEvent';\n\nexport const STORAGE_ASSIGNEE_CHANGED = 'storage_assignee_changed';\n\nexport default class StorageAssigneeChangedEvent extends SAMEvent {\n\n    constructor() {\n        super(STORAGE_ASSIGNEE_CHANGED);\n    }\n}\n\nexport const SharedStorageAssigneeChangedEvent = new StorageAssigneeChangedEvent();\n\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\ninterface IModernSet<T> extends Set<T> {\n    isDisjointFrom(other: Set<T>): boolean;\n    isSubsetOf(other: Set<T>): boolean;\n    isSupersetOf(other: Set<T>): boolean\n    intersection(other: Set<T>): Set<T>;\n    union(other: Set<T>): Set<T>;\n    difference(other: Set<T>): Set<T>;\n    symmetricDifference(other: Set<T>): Set<T>;\n}\n\n/**\n * Implements newer methods added to Set in 2024. Temporary until browser usage % that supports\n * these methods is high enough to remove. Currently at 87.6%.\n * https://caniuse.com/?search=isDisjointFrom\n */\nexport class ModernSet<T> extends Set<T> implements IModernSet<T> {\n    isDisjointFrom(other: Set<T>): boolean {\n        return ![ ...this ].some(value => other.has(value));\n    }\n    isSubsetOf(other: Set<T>): boolean {\n        return [ ...this ].every(value => other.has(value));\n    }\n    isSupersetOf(other: Set<T>): boolean {\n        return ModernSet.prototype.isSubsetOf.call(other, this);\n    }\n    intersection(other: Set<T>): ModernSet<T> {\n        return new ModernSet<T>([ ...this ].filter(value => other.has(value)));\n    }\n    union(other: Set<T>): Set<T> {\n        return new ModernSet<T>([ ...this, ...other ]);\n    }\n    difference(other: Set<T>): Set<T> {\n        return new ModernSet<T>([ ...this ].filter(value => !other.has(value)));\n    }\n    symmetricDifference(other: Set<T>): Set<T> {\n        return new ModernSet<T>([ ...this, ...other ].filter(value => this.has(value) !== other.has(value)));\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { IExplicitFilter, IImplicitFilter } from '@sam-js-src/core/ItemFilter';\nimport { ModernSet } from '@sam-js-src/utils/ModernSet';\n\nexport function getMediaTypesFromFilters(implicitFilter?: IImplicitFilter<any>, explicitFilter?: IExplicitFilter<any>): string[] {\n    const implicitFilterMediaTypes = getVariableFromObj('mediaTypes', implicitFilter);\n    if (implicitFilterMediaTypes) {\n        return [ ...<[]>implicitFilterMediaTypes ];\n    }\n\n    const explicitFilterMediaTypes = getVariableFromObj('mediaTypes', explicitFilter);\n    if (explicitFilterMediaTypes) {\n        return [ ...<[]>explicitFilterMediaTypes ];\n    }\n\n    return [];\n}\n\nexport function getExcludeMediaTypesFromFilters(implicitFilter?: IImplicitFilter<any>, explicitFilter?: IExplicitFilter<any>): string[] {\n    const implicitSet: ModernSet<string> = getVariableFromObj('excludeMediaTypes', implicitFilter) ?? new ModernSet([]);\n    const explicitSet: ModernSet<string> = getVariableFromObj('excludeMediaTypes', explicitFilter) ?? new ModernSet([]);\n    return [ ...implicitSet.union(explicitSet) ];\n}\n\nexport function getVariableFromObj(variable: string, obj?: Record<string, any>): any {\n    if (!obj || !(variable in obj)) {\n        return undefined;\n    }\n\n    return obj[variable];\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from './AdobeAsset';\nimport type { AssetSubType, AssetType } from '../interface/AssetModel';\nimport { getRapiAppMetadataSelectors } from '../interface/AssetModel';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { AdobeAssetConfig } from './AdobeAssetSource';\nimport type AdobeAssetFilter from './AdobeAssetFilter';\nimport { OrderFieldToIAdobeAssetOrderBy } from './AdobeAssetOrder';\nimport { RelType } from '../interface/LinkUtils';\nimport type { EmbedSpecifier, RepositoryMetadata } from '../interface/RepositoryModel';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type Library from '../libraries/Library';\nimport type { LibraryData, LibrarySpecificData } from '../interface/LibraryModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { SharedStorageAssigneeChangedEvent } from './AssetEvents';\nimport { LazyLoadManager } from '../core/decorators/LazyLoadManager';\nimport type { AdobeAssetUpdaterMetadata } from './AdobeAsset';\nimport { getMediaTypesFromFilters } from '@sam-js-src/utils/loaderUtils';\n\nexport default class AdobeAssetDirectoryLoader implements IItemLoader<AdobeAssetConfig> {\n\n    constructor(\n        private _assetPool: ItemPool<AdobeAsset>,\n        private _asset: AdobeAsset,\n        private _core: ISAMCorePrivate,\n        private _includePermissions?: boolean,\n        private _loadLibraryData?: boolean\n    ) {\n    }\n\n    supportsFilter(filter?: AdobeAssetFilter): boolean {\n        // TODO: ?? can be undefined but can't be undefined ??\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<AdobeAssetConfig>): Promise<ILoadedPage<AdobeAssetConfig>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<AdobeAssetConfig>, pageCursor?: string): Promise<ILoadedPage<AdobeAssetConfig>> {\n        const { order, filter, implicitFilter, resource } = options;\n        const { limit } = options.loadOptions ?? {};\n        const mediaTypes = getMediaTypesFromFilters(implicitFilter, filter);\n\n        /* Note: re-evaluate this after we have more data about the Project.libraries use case\n         * We're currently calling for melville data for every page load.\n         * We don't think it's a problem because it reduces code complexity and\n         * we predict the standard use case to be just one page of libraries.\n         * If that changes in future, we should re-evaluate this strategy.\n         */\n        let librariesDataPromise = undefined;\n        if (this._loadLibraryData) {\n            if (!this._asset.isProject) {\n                throw SAMError.create(SAMErrorCode.UNSUPPORTED, `Asking for child libraries from non-project asset with id: ${this._asset.id}`);\n            } else {\n                // TODO [SHARED-975]: This doesn't fetch subsequent pages (max list of 50). Needs to go through the LibraryListLoader.\n                librariesDataPromise = this._core.hostAssetContext._libraryInterface.getLibrariesForProject(this._asset.id);\n            }\n        }\n        // We will ignore the update if we had local changes sooner than this timestamp.\n        const latency = this._assetPool._core._environment.getValue('ASSETS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n\n        // A \"mutation\" session is used here to track the time when a change is made to an Asset that is known to be\n        // fresh (since it came from R-API). This helps avoid problems where fresh data from R-API gets overwritten by\n        // stale data (e.g. from USS due to indexing lag). It also should use createLoaderMutationSession\n        // (SAM-2973, SAM-3017).\n        const session = this._assetPool.createLoaderMutationSession();\n\n        let childrenData: AdobeAssetUpdaterMetadata[] | undefined;\n        let nextPageCursor: string | undefined;\n        let ancestors: string[] | undefined;\n\n        const useGraphQL = this._core._environment.getValue('FEATURE_FLAGS')?.['use-graphql'];\n        if (useGraphQL) {\n            const gqlManager = await this._core._getGQLManager();\n            const listData = await gqlManager.getChildren(this._asset.id, {\n                filter,\n                order,\n                loadOptions: {\n                    limit\n                },\n                after: pageCursor\n            }, resource);\n            childrenData = listData.children;\n            ancestors = listData.ancestors;\n            nextPageCursor = listData.pageInfo.hasNextPage ? (listData.pageInfo.endCursor ?? undefined) : undefined;\n        } else {\n            const embed: EmbedSpecifier[] = [ {\n                'resource': {\n                    'reltype': RelType.APP_METADATA\n                },\n                'selectors': getRapiAppMetadataSelectors()\n            } ];\n            if (this._includePermissions) {\n                embed.push(\n                    {\n                        'resource': {\n                            'reltype': RelType.AC_EFFECTIVE\n                        }\n                    }\n                );\n            }\n\n            // SAM-3087: USS doesn't include PAGE link\n            await this._asset._ensureLink(RelType.PAGE);\n            const assetInterface = await this._asset._getAssetInterface();\n            const rapiPage = await assetInterface.getChildAssets({\n                orderBy: OrderFieldToIAdobeAssetOrderBy[order.field],\n                orderDirection: order.direction,\n                start: pageCursor,\n                limit,\n                type: mediaTypes,\n                filters: {\n                    assetTypes: [ ...(filter.assetTypes || []) as AssetType[] ],\n                    excludeAssetTypes: [ ...(filter.excludeAssetTypes || []) as AssetType[] ],\n                    assetSubTypes: [ ...(filter.assetSubTypes || []) as AssetSubType[] ],\n                },\n                embed\n            }, resource);\n\n            ancestors = rapiPage['repo:ancestors'];\n            childrenData = rapiPage.children;\n            nextPageCursor = rapiPage._page.next;\n        }\n\n        if (this._asset.isProject) {\n            // Update the project's children with the repo:ancestors from the parent project. This is to ensure that\n            // the user's root and the project's root are included in the child's repo:ancestors. This is only an issue\n            // for children of Project, so restricting this to only Projects.\n            this._core.hostAssetContext._adobeAssetUpdater.updateLocalItem(session, this._asset, {\n                'repo:ancestors': ancestors\n            });\n        }\n\n        childrenData = childrenData.map((item) => {\n            // Directory listings don't include repo:ancestors, but since we know the parent asset,\n            // we can construct it based on the parent's repo:ancestors\n            if (!item['repo:ancestors']) {\n                item['repo:ancestors'] = [ ...(this._asset.ancestorIDs ?? []), this._asset.id ];\n            }\n            return item;\n        });\n\n        const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters(childrenData as RepositoryMetadata[]);\n        const items = this._core._adobeAssetFactory.assetsFromRepoMetadata(\n            session,\n            (childrenData as RepositoryMetadata[])\n                // RAPI does not support excludeMediaTypes, and only supports 1 value for excluding assetTypes.\n                // [SAM-5188] Filter out items that should be excluded to avoid adding unreferenced items to the pool\n                .filter((item) => {\n                    return !filter.excludeMediaTypes?.has(item['dc:format']) && !filter.excludeAssetTypes?.has(item['repo:assetType'] as AssetType);\n                }),\n            updaters\n        );\n\n        let librariesInPage: Library[];\n        if (this._loadLibraryData) {\n            librariesInPage = items.filter((item): item is Library => item.isLibrary);\n            librariesInPage.forEach(library => library._setLibraryLoadState('LOADING'));\n        }\n        // Notify LLM that storageAssignee is loaded for entries that have it\n        items.forEach(item => {\n            if (item._storageAssignee_NoLazyLoad.id) {\n                LazyLoadManager.updatedByItemUpdater(item, SharedStorageAssigneeChangedEvent);\n            }\n        });\n        session.commit();\n\n        if (this._loadLibraryData) {\n            librariesDataPromise!\n                .then((librariesData) => this._updateLibrariesData(librariesInPage, librariesData));\n        }\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<AdobeAssetConfig> | undefined;\n\n        if (nextPageCursor) {\n            loadNextPage = (options: IItemLoaderOptions<AdobeAssetConfig>) =>\n                this._loadPage(options, nextPageCursor);\n        }\n\n        return {\n            items,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n\n    // Libraries listing may have stale data due to USS indexing delays. Thus, this method\n    // retrieves LibrarySpecificData from LibraryData, which is always safe to use as it will not overwrite RAPI data.\n    // TODO [SHARED-902]: Move to LibraryUtils\n    private _getSafeLibraryData(libraryData: LibraryData): Partial<LibraryData> {\n        if (!libraryData) { return {}; }\n        const { library_urn, id, bookmark, name, ownership, roles, rendition_grid }: LibrarySpecificData = libraryData;\n        return { library_urn, id, bookmark, name, ownership, roles, rendition_grid };\n    }\n\n    /**\n     * Given a set of libraries that have been loading, update their data and loading state with the data from Melville.\n     */\n    private async _updateLibrariesData(librariesToUpdate: Library[], librariesData: LibraryData[]): Promise<void> {\n        const session = this._core.hostAssetContext._assetPool.createUpdateSession<Library>();\n        const libraryContext = await this._core.getLibraryContext();\n\n        librariesToUpdate.forEach(library => {\n            const libraryData = librariesData.find(item => item.library_urn === library.id);\n            if (libraryData) {\n                const librarySpecificData = this._getSafeLibraryData(libraryData);\n                libraryContext._libraryUpdater.updateLocalItem(session, library, librarySpecificData);\n                library._setLibraryLoadState('LOADED');\n            } else {\n                // USS indexing delays may cause Melville non-public libraries listing data to be stale.\n                // Thus it is possible that we have RAPI data for a new library but no matching melville data in the listing.\n                // Setting the library to NOT_LOADED will trigger lazy loading if the library is being used,\n                // which will cause Melville to pull the up-to-date data for this library from platform.\n                library._setLibraryLoadState('NOT_LOADED');\n            }\n        });\n        session.commit();\n    }\n\n}\n\n\n\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2023 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type { IItemSourceConfig } from '../core/ItemList';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type { AdobeAssetUpdaterMetadata } from './AdobeAsset';\nimport type AdobeAsset from './AdobeAsset';\nimport type ItemPool from '../core/ItemPool';\nimport type { USSResponse, USSItemMetadata } from '../interface/USSv3Model';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport { RelType } from '../interface/LinkUtils';\nimport type LibraryContext from '../libraries/LibraryContext';\nimport type USSAdobeAssetFilter from './USSAdobeAssetFilter';\nimport type { UpdaterMap } from './AdobeAssetFactory';\nimport { LazyLoadManager } from '../core/decorators/LazyLoadManager';\nimport { STORAGE_ASSIGNEE_CHANGED } from '../assets/AssetEvents';\n\nexport interface IGetUSSResultsOpts<T extends IItemSourceConfig<AdobeAsset>> extends IItemLoaderOptions<T> {\n    start: number;\n    // NOTE: the parameters below are common to *all* USS Loaders, so are included here to simplify the _getUSSResults()\n    // implementation. Any additional parameters should come from the `filter` prop, which is inherited from\n    // IItemLoaderOptions.\n    mediaTypes: string[];\n    excludeMediaTypes: string[];\n}\n\nexport interface IUSSLoader<T extends IItemSourceConfig<AdobeAsset>> extends IItemLoader<T> {\n    /**\n     * Loaders must implement this method and call from Loader.loadPage(options)\n     */\n    _getUSSResults(opts: IGetUSSResultsOpts<T>): Promise<USSResponse>;\n    /**\n     * Loaders can optionally implement to provide additional metadata that is\n     * implied by the Loader but not included in the USS response.\n     */\n    _getItemData?(item: USSItemMetadata): Partial<AdobeAssetUpdaterMetadata>;\n    /**\n     * Loaders can optionally implement to perform additional internal state management.\n     */\n    _postProcessPage?(loaderPageOpts: IItemLoaderOptions<T>, page: ILoadedPage<T>): void;\n    /**\n     * Loaders can optionally implement to perform additional processing of USS search results.\n     */\n    _extractItems?(session: IUpdateSession<AdobeAsset>, items: USSItemMetadata[], updaters: UpdaterMap): AdobeAsset[];\n    /**\n     * Loaders can optionally preload the library context.\n     */\n    _libraryContext?: LibraryContext;\n}\n\nconst DEFAULT_LIMIT = 50;\n\nexport function getUSSV3ItemData(userId: string, item: USSItemMetadata)  {\n    return {\n        ...item.rm,\n        // cm.sharedBy is an array of user IDs that have shared the asset\n        // assuming that it is an ordered array, the first item is the first sharer\n        // Even after this assumption we can't be sure that first sharer is the owner\n        // We will need more info to figure out whether the asset is sharedViaInvite.\n        // For example consider an asset inside a project that is not owned by the user\n        // and that asset is 1-off shared with some user C by user B.\n        // Now user A does not know whether this asset is shared via invite with him because\n        // he is not the owner of the asset and cm.sharedBy will have user B's ID but it is not\n        // shared via invite with user A.\n        sharedViaInvite: item.cm?.sharedBy.length > 0 && item.cm!.sharedBy[0] !== userId,\n        isShared: item.cm?.sharedBy.length > 0,\n        // Get the app metadata from the item if it exists.\n        ...(item.am && { _embedded: { [RelType.APP_METADATA]: item.am } }),\n        // No need to refresh collaborators for share flags, directCollaboratorCount, since they are computed\n        // above. Not clearing the collaboratorDataIsDirty flag, because we cannot populate collaboratorArray\n        // from USS.\n        shareFlagsAreDirty: false\n    };\n}\n\n\n/**\n * AdobeAsset Loader classes should use this class to do the page loading. Using composition rather\n * than inheritance because a base USSLoader class was causing circular dependencies at runtime that\n * would cause the base USSLoader class to be undefined when the Loader class that was extending it\n * was declared.\n */\nexport default class USSv3LoaderHelper<T extends IItemSourceConfig<AdobeAsset>> {\n    constructor(\n        private _assetPool: ItemPool<AdobeAsset>,\n        protected _core: ISAMCorePrivate,\n        private _loader: IUSSLoader<T>\n    ) {}\n\n    async loadPage(options: IItemLoaderOptions<T>, start?: number): Promise<ILoadedPage<T>> {\n        const { order, filter, implicitFilter, resource } = options;\n        const { limit = DEFAULT_LIMIT } = options.loadOptions ?? {};\n        const latency = this._core._environment.getValue('USS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n        start = start || 0;\n\n        const { mediaTypes, excludeMediaTypes } = filter as USSAdobeAssetFilter;\n\n        const result: USSResponse = await this._loader._getUSSResults({\n            order,\n            loadOptions: { limit, ...options.loadOptions,  },\n            filter,\n            implicitFilter,\n            resource,\n            start,\n            // NOTE: the parameters below are common to *all* USS Loaders, so are normalized here to simplify the\n            // _getUSSResults() implementation. The Loader._getUSSResults() implementation should get any additional\n            // parameters it needs from `filter` or `implicitFilter`.\n            mediaTypes: Array.from(mediaTypes ?? []),\n            excludeMediaTypes: Array.from(excludeMediaTypes ?? []),\n        });\n\n        const queryResult = result.queryResults[0];\n        // TODO: it'd be nice if USS returned empty array when there are no matches\n        const resultItems = queryResult.items || [];\n        const updaters = await this._core._adobeAssetFactory.getUSSV3Updaters(resultItems);\n        const session = this._assetPool.createLoaderUpdateSession(mostRecentValidMutation);\n        const items = this._loader._extractItems\n            ? this._loader._extractItems(session, resultItems, updaters)\n            : this._extractItems(session, resultItems, updaters);\n\n        // All USS sources return storage:assignee, so there is no need to lazy-load it\n        items.forEach(item => LazyLoadManager.updatedByItemUpdater(item, STORAGE_ASSIGNEE_CHANGED));\n\n        let loadNextPage: ILoadNextPage<T> | undefined;\n        const total = queryResult.metadata.totalHits || 0;\n        const pageItemCount = resultItems.length;\n        // [SEARCH-30755] -- May be caused by USS filtering out items due to permissions for the\n        // current user, which aren't subtracted from the total. Try to ensure that the Loader paginates\n        // as though the total_items is correct.\n        const nextStartIndex = (pageItemCount === 0 ? start + limit : start + pageItemCount);\n        if (nextStartIndex < total) {\n            loadNextPage = (options: IItemLoaderOptions<T>) => this.loadPage(options, nextStartIndex);\n        }\n\n        const page: ILoadedPage<T> = {\n            items,\n            total,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n\n        // allow Loader to do additional internal state management (optional)\n        this._loader._postProcessPage?.(options, page);\n\n        session.commit();\n\n        return page;\n    }\n\n    private _getItemData = (item: USSItemMetadata) => {\n        return getUSSV3ItemData(this._core._environment.getUserId(), item);\n    };\n\n    private _extractItems(\n        session: IUpdateSession<AdobeAsset>,\n        items: USSItemMetadata[],\n        updaters: UpdaterMap\n    ): AdobeAsset[] {\n        return this._core._adobeAssetFactory.assetsFromUSSV3Response(\n            session,\n            items,\n            this._loader._getItemData ?? this._getItemData,\n            updaters\n        );\n    }\n}\n","export const USSAssetFilterName = 'USSAdobeAssetFilter';\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2023 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\nimport type {\n    IAppMetadata,\n    RepositoryMetadata\n} from './RepositoryModel';\nimport type { UploadedFromType } from '../assets/USSAdobeAssetFilter';\nimport type { AdobeAssetOrderField } from '../assets/AdobeAssetOrder';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport type { USSAdobeAssetOrderField } from '../assets/USSAdobeAssetOrder';\n\nimport { EXPRESS_ARTIFACT_TYPE } from '../utils/excludeExpressArtifacts';\n\nexport enum USSv3OrderField {\n    Created = 'rm.storage:deviceCreateDate',\n    Modified = 'rm.storage:deviceModifyDate',\n    Name = 'rm.repo:name'\n}\n\nexport const USSv3OrderFieldMap: Record<AdobeAssetOrderField | USSAdobeAssetOrderField, USSv3OrderField> = {\n    'name': USSv3OrderField.Name,\n    'created': USSv3OrderField.Created,\n    'modified': USSv3OrderField.Modified,\n    // TODO: add USSv3 shareDate sorting\n    'shared': USSv3OrderField.Modified,\n    // TODO: add v3 lastAccessed sorting\n    'lastAccessed': USSv3OrderField.Modified\n} as const;\n\nexport enum USSv3OrderDir {\n    Ascending = 'ASC',\n    Descending = 'DESC'\n}\n\nexport const USSv3OrderDirMap: Record<IOrderDirection, USSv3OrderDir> = {\n    'ascending': USSv3OrderDir.Ascending,\n    'descending': USSv3OrderDir.Descending\n} as const;\n\nexport interface ISearchQueryEntrySort {\n    sortOrderBy: USSv3OrderField;\n    sortOrder: USSv3OrderDir;\n}\n\nexport enum USSv3FilterField {\n    MEDIA_TYPE = 'rm.dc:format',\n    DIRECTORY_TYPE = 'am.project:directoryType',\n    REVIEW_SOURCE_TYPE = 'am.review:sourceAsset.dc:format',\n    STORAGE_ASSIGNEE_TYPE = 'rm.storage:assignee.type',\n    PARENT_ID = 'rm.parentDirectoryId',\n    REPO_ANCESTORS = 'rm.repo:ancestors',\n    SHELL_VISIBILITY = 'am.shell:visibility',\n    TOP_LEVEL_COLLECTION_NAME = 'rm.topLevelCollectionName',\n    STORAGE_ASSIGNEE_ID = 'rm.storage:assignee.id',\n    CREATED_FROM_UPLOAD = 'am.cc:createdFromUpload',\n    CREATED_BY_CLIENT_ID = 'rm.repo:createdByClientId',\n    ASSET_TYPE = 'rm.repo:assetType',\n    ASSET_SUB_TYPE = 'rm.repo:assetSubType'\n}\n\nexport enum USSv3Function {\n    MISSING  = 'function:missing',\n    NOT = 'function:not'\n}\n\nexport enum USSv3DirectoryType {\n    PROJECT = 'team'\n}\n\nexport type USSv3InheritanceTypeField = 'am.cc:inherited.cc:studentAssignment.repo:assetId'\n    | 'am.cc:inheritable.cc:studentAssignment.repo:assetId'\n    | 'am.cc:inherited.cc:assignmentMaterials.repo:assetId'\n    | 'am.cc:inheritable.cc:assignmentMaterials.repo:assetId'\n    | 'am.cc:inherited.cc:assignment.repo:assetId'\n    | 'am.cc:inheritable.cc:assignment.repo:assetId'\n    /** old Projects v2 teams ? */\n    | 'am.cc:inheritable.cc:team.repo:assetId'\n    | 'am.cc:inherited.cc:team.repo:assetId'\n;\n\n\n\nexport interface ISearchQueryEntryFilter {\n    [USSv3FilterField.MEDIA_TYPE]?: string[];\n    [USSv3FilterField.DIRECTORY_TYPE]?:  USSv3DirectoryType[];\n    [USSv3FilterField.REVIEW_SOURCE_TYPE]?: string[];\n    [USSv3FilterField.STORAGE_ASSIGNEE_TYPE]?: 'user';\n    [USSv3FilterField.STORAGE_ASSIGNEE_ID]?: string;\n    [USSv3FilterField.PARENT_ID]?: string;\n    [USSv3FilterField.REPO_ANCESTORS]?: string;\n    [USSv3FilterField.SHELL_VISIBILITY]?: ('hiddenSelf' | 'hiddenRecursive')[];\n    [USSv3FilterField.TOP_LEVEL_COLLECTION_NAME]?: 'appdata';\n    [USSv3FilterField.CREATED_FROM_UPLOAD]?: boolean;\n    [USSv3FilterField.CREATED_BY_CLIENT_ID]?: UploadedFromType;\n    [USSv3FilterField.ASSET_TYPE]?: string[];\n    [USSv3FilterField.ASSET_SUB_TYPE]?: string[];\n\n    [USSv3Function.NOT]?: {\n        funcParams: ISearchQueryEntryFilter\n    };\n\n    /** To match a specific Asset, it must be missing the fields specified in `funcParams` */\n    [USSv3Function.MISSING]?: {\n        funcParams: {\n            fields: USSv3InheritanceTypeField[]\n        }\n    }\n}\n\nexport enum FetchFields {\n    SharedBy = 'cm.sharedBy',\n    LastAccessDate = 'am.shell:lastActivity.date',\n    ShellVisibility = 'am.shell:visibility',\n    Collaborator =  'cm.collaborator',\n    PublicCollaborator = 'cm.publicCollaborator',\n    ParentProjectId = 'am.cc:inherited.cc:team.repo:assetId',\n    StudentAssignmentAssetId = 'am.cc:inherited.cc:studentAssignment.repo:assetId',\n    StudentAssignmentDirectoryId = 'am.cc:inheritable.cc:studentAssignment.repo:assetId',\n    // We need both projects and its children to show up in global search\n    CCInherited = 'am.cc:inherited',\n    CCInheritable = 'am.cc:inheritable',\n    // App metadata field required for Express\n    HzDocumentMetadata = 'am.hz:documentMetadata',\n    CreatedFromUpload = 'am.cc:createdFromUpload',\n    CreatedByClientId = 'rm.createdByClientId',\n    ReviewSourceAsset = 'am.review:sourceAsset',\n    ReviewSourceAssetType = 'am.review:sourceAsset.dc:format',\n    ConvertedTo = 'am.convertedTo',\n    NonAutoMigratable = 'am.ccx:nonAutoMigratableCopiedFromId',\n    CopiedLegacySparkId = 'am.ccx:copiedLegacySparkId'\n}\n\nexport interface ISearchQueryEntry {\n    start: number;\n    limit: number;\n    id?: string;\n    textQuery?: string;\n    sorts?: ISearchQueryEntrySort[];\n    scope?: { entities: ('AcpAsset')[] };\n    filters?: ISearchQueryEntryFilter[];\n    fetchFields?: FetchFields[];\n}\n\nexport interface ISearchQuery {\n    experienceId: string;\n    queries: ISearchQueryEntry[];\n}\n\ntype USSQueryResults = {\n    id: string;\n    status: { httpCode: number; };\n    metadata: {\n        totalHits: number;\n        start: number;\n        limit: number;\n    };\n    items?: USSItemMetadata[];\n}\n\nexport type USSResponse = {\n    experienceId: string;\n    status: { httpCode: number; };\n    queryResults: USSQueryResults[];\n}\n\nexport type USSItemMetadata = {\n    id: string;\n    cm: {\n        sharedBy: string[]\n    };\n    rm: RepositoryMetadata;\n    am: IAppMetadata;\n};\n\nexport function excludeExpressArtifacts(): ISearchQueryEntryFilter {\n    return {\n        [USSv3Function.NOT]: { funcParams: { [USSv3FilterField.REVIEW_SOURCE_TYPE]: [ EXPRESS_ARTIFACT_TYPE ] } }\n    };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type ItemBase from './ItemBase';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from './ItemLoader';\nimport type { IExplicitFilter, IImplicitFilter } from './ItemFilter';\nimport TypedEventEmitter from './TypedEventEmitter';\nimport type { IItemOrder } from './ItemOrder';\nimport type { IItemSourceConfig, ILoadOptions } from './ItemList';\nimport SAMEvent from './SAMEvent';\nimport Resource from '../assets/Resource';\nimport type ISAMCorePrivate from './ISAMCorePrivate';\nimport { ManagedPromise } from '../utils/ManagedPromise';\nimport type SAMError from './SAMError';\nimport { SAMErrorCode } from './SAMError';\n\n// Must match GenericListStatus enum from SAM.cpp\nexport enum AssetListStatus {\n    NotStarted = 1,\n    HadLoaderErrors,\n    Loading,\n    ReadyHasMorePages,\n    ReadyFullyLoaded\n}\n\nexport const LOADER_STATE_CHANGED = 'loaderStateChanged';\nexport const LOADER_REFRESH_NEEDED = 'loaderRefreshNeeded';\n\nexport class ItemLoaderStateChangeEvent extends SAMEvent {\n    constructor(readonly hasUpdatedItems: boolean = false) {\n        super(LOADER_STATE_CHANGED);\n    }\n}\n\nexport class ItemLoaderRefreshNeededEvent extends SAMEvent {\n    constructor(readonly revalidateAtPage = 0) {\n        super(LOADER_REFRESH_NEEDED);\n    }\n}\n\nconst SharedEventWithoutItemChanges = new ItemLoaderStateChangeEvent(false);\nconst SharedEventWithItemChanges = new ItemLoaderStateChangeEvent(true);\n\n/**\n * This is the structure of a page in memory.\n */\nclass ItemLoaderPage<LocalType extends ItemBase> {\n    items?: LocalType[];\n    startedGeneration: number = 0;\n    loadedGeneration: number = 0;\n    validatedPromise?: Promise<void>;\n\n    // When a page refreshes it should load the same\n    // page size as the first load.\n    limit?: number;\n}\n\ntype ItemLoaderStateEventMap = {\n    /**\n     * If the status of the loader changes, it will dispatch a 'change' event.\n     */\n    [LOADER_STATE_CHANGED]: ItemLoaderStateChangeEvent,\n    [LOADER_REFRESH_NEEDED]: ItemLoaderRefreshNeededEvent\n};\n\n/**\n * A list can have multiple loaders that provide items.\n * The ItemLoaderState maintains the state of each loader attached in a list:\n * - The loaded pages and their items\n * - The error state if we had one\n * - The next available page if any\n *\n * The Loader can also refresh the items starting with page 0. The items\n * in the pre-loaded pages will only refresh once those pages are fully loaded again.\n *\n * If a previous pending request is finished after we start a refresh cycle, then\n * the items in that page will update if and only if the new cycle didn't fetch that page yet.\n */\nexport default class ItemLoaderState<ItemConfig extends IItemSourceConfig> extends TypedEventEmitter<ItemLoaderStateEventMap> {\n    status: AssetListStatus = AssetListStatus.NotStarted;\n    total: number | undefined;\n    error: any;\n\n    private _pages: ItemLoaderPage<ItemConfig['type']>[] = [];\n\n    /**\n     * Each new refresh of the pages increments the generation index.\n     * We use this to differentiate between async network calls that\n     * might end up providing content after a new refresh has already\n     * been scheduled.\n     */\n    private _generation: number = 0;\n\n    /**\n     * Store the index and link of the next page. Once we reach\n     * the last page, the callback will become null.\n     */\n    private _nextPageIndex: number = 0;\n    private _nextPageCallback?: ILoadNextPage<ItemConfig>;\n\n    /**\n     * When a page load starts, we store the promise it generates,\n     * so that the next calls to load will queue up to receive a notification\n     * once the initial load is finished.\n     */\n    private _pendingLoad?: Promise<void>;\n\n    private _mostRecentValidMutation: number | undefined;\n\n    private _revalidateAtPage: number = 0;\n    private _invalidateCache: boolean = false;\n\n    constructor(\n        public _core: ISAMCorePrivate,\n        private _loader: IItemLoader<ItemConfig>,\n        private _order: IItemOrder<ItemConfig['type']>,\n        private _implicitFilter: IImplicitFilter<ItemConfig['type']>,\n        private _filter: IExplicitFilter<ItemConfig['type']>,\n    ) {\n        super();\n    }\n\n    get mostRecentValidMutation(): number | undefined {\n        return this._mostRecentValidMutation;\n    }\n\n    /**\n     * Triggers a new generation of loading.\n     * @param generation    The generation index. This number must always increment for new loads.\n     * @param loadOptions The load options for this list, includes loadAllPages, limit, and refreshTimeout\n     * @param revalidateAtPage (optional) revalidate pages starting at this index.\n     * @param skipCache (optional) when true, skips the ResponseCache for this load operation\n     * @returns Promise that can be used to know when the entire loading chain finished.\n     */\n    async load(generation: number, loadOptions?: ILoadOptions, revalidateAtPage: number = 0, skipCache?: boolean): Promise<void> {\n\n        // If we were loading something before, we are aborting\n        // that in favor of the new generation.\n\n        // Reset the previous page token.\n        this._generation = generation;\n        this._nextPageCallback = undefined;\n        this._nextPageIndex = 0;\n        this._pendingLoad = undefined;\n        this._revalidateAtPage = revalidateAtPage;\n        this._invalidateCache = skipCache ?? false;\n\n        await this._loadPage(loadOptions);\n    }\n\n    /**\n     * Load the next page.\n     * @returns Promise that can be used to know when the entire loading chain finished.\n     */\n    async loadNextPage(loadOptions?: ILoadOptions): Promise<void> {\n        await this._loadPage(loadOptions);\n    }\n\n    /**\n     * Load all the remaining pages.\n     * @returns Promise that can be used to know when the entire loading chain finished.\n     */\n    async loadAllPages(loadOptions: ILoadOptions = {}): Promise<void> {\n        loadOptions.loadAllPages = true;\n        await this._loadPage(loadOptions);\n    }\n\n    /**\n     * Pushes the items from all the loaded pages into the provided `dest` set.\n     *\n     * @param dest Set object that is populated with items from all the pages.\n     */\n    collectAllItems(dest: Set<ItemConfig['type']>) {\n        for (const page of this._pages) {\n            if (page && page.items) {\n                for (const item of page.items) {\n                    dest.add(item);\n                }\n            }\n        }\n    }\n\n    /**\n     * Loads or creates a page at the specified index.\n     * @param pageIndex\n     * @returns The page at index `pageIndex`.\n     */\n    private _ensurePage(pageIndex: number): ItemLoaderPage<ItemConfig['type']> {\n        let page = this._pages[pageIndex];\n        if (!page) {\n            page = new ItemLoaderPage<ItemConfig['type']>();\n            this._pages[pageIndex] = page;\n        }\n        return page;\n    }\n\n    /**\n     * Handle only one page load at a time by storing the promise and waiting on the same\n     * promise.\n     *\n     * Note that the promise chain can still be restarted via the `load()` method which\n     * starts loading everything from the first page again.\n     */\n    private async _loadPage(loadOptions?: ILoadOptions) {\n        // Check if there is a load already in progress. We wait on that one before making more loads.\n        // This should prevent users from trying to load too many pages ahead of time.\n        let pendingLoad = this._pendingLoad;\n        if (!pendingLoad) {\n            // We don't have anything in progress, we can go ahead and load the page.\n            pendingLoad = this._loadPageImpl(loadOptions);\n\n            // Store the pending load to make sure no requests are executed at the same time.\n            this._pendingLoad = pendingLoad;\n        }\n\n        // Wait for this load to finish.\n        await pendingLoad;\n\n        if (this._pendingLoad === pendingLoad) {\n            // If the load is still relevant for this generation of loading,\n            // then we can go ahead and remove the promise. Note that we will\n            // have to do this for all returning cases, even the paths that didn't\n            // actually trigger a load above. That's because we don't know which path\n            // continues the execution first and we want to make the caller can initiate\n            // another call immediately.\n            this._pendingLoad = undefined;\n        }\n    }\n\n    /**\n     * Loads the next page queued up for the loader.\n     * It will also update the current page and recursively call\n     * itself to load the next page if needed.\n     */\n    private async _loadPageImpl(loadOptions: ILoadOptions = {}) {\n        const nextPageCallback = this._nextPageCallback;\n        const pageIndex = this._nextPageIndex;\n\n        // If this is not the first page and we don't have a callback, then we are out of pages to load.\n        if (pageIndex && !nextPageCallback) {\n            return;\n        }\n\n        // Ensure we have the next page in memory.\n        const page = this._ensurePage(pageIndex);\n\n        // Store the generation that we are in when the loading starts. If the results\n        // come by the time we've already switched to a new generation, then we will\n        // ignore the errors and keep the results only if no other newer generation has\n        // finished loading the same page already.\n        const startGeneration = this._generation;\n\n        if (page.startedGeneration >= startGeneration) {\n            // We've already loaded this or a newer generation in a different loading chain.\n            return;\n        }\n\n        // Make sure the page knows we are about to reload content using the new generation.\n        const previousPageGeneration = page.startedGeneration;\n        page.startedGeneration = startGeneration;\n        page.validatedPromise = undefined;\n\n        // Remove the error state in case we had one before.\n        this.error = null;\n\n        // Update the status to loading state before we start loading.\n        this._updateStatus(AssetListStatus.Loading);\n\n        let result: ILoadedPage<ItemConfig> | undefined;\n        let loaderError: any;\n        let revalidationPromise: ManagedPromise<void> | undefined;\n\n        try {\n            loadOptions.limit ??= page.limit;\n            const resource = new Resource<unknown>(this._core, {\n                parseResponse: async (response) => response,\n                // If we have already revalidated earlier pages, we don't want to revalidate them again\n                // even if they change. Otherwise we could refresh pages infinitely if responses are not stable.\n                skipRevalidation: () => pageIndex < this._revalidateAtPage,\n                // Skip cache when _skipCache is true (e.g., when setNeedsRefresh is called)\n                // When we fetch a page, if the cache is enabled, we may get a cached response immediately,\n                // followed by a subsequent response _if_ the cache was outdated. For instance, we might have\n                // loaded several pages, and one of the pages turns out to differ. If that happens, we want\n                // the list to refresh itself from the beginning. The second time around, the list will quickly\n                // resolve with the cached pages that still match, followed by a new fetch for the page that changed.\n                // To ensure that we don't get stuck in a continuous loop refreshing the list,\n                // we skip revalidating the pages we've already revalidated during this process.\n                onChange: async (_value, flags) => {\n                    if (flags?.loading) {\n                        revalidationPromise = new ManagedPromise<void>();\n                        page.validatedPromise = revalidationPromise.promise;\n                    } else {\n                        revalidationPromise?.resolve();\n                        if (page.startedGeneration !== startGeneration) {\n                            return;\n                        }\n                        // If the real response has changed after we already returned the results,\n                        // we want to refresh the list from the beginning.\n                        if (result && flags?.changed) {\n                            // Start from the beginning. We should fetch the first page again.\n                            // It will hit cache, which has been updated with this response.\n                            // Then we wait for any more pages like normal.\n                            this.dispatch(new ItemLoaderRefreshNeededEvent(pageIndex + 1));\n                        }\n                    }\n                },\n                // If an error occurs during the revalidation fetch:\n                onError: async (error: any) => {\n                    if (revalidationPromise) {\n                        revalidationPromise.reject(error);\n                    } else {\n                        // If there wasn't a revalidationPromise during this error, we haven't pre-emptively\n                        // returned a cached page, so we can let the promise-based exception-handling code handle the error.\n                        return;\n                    }\n                    if (page.startedGeneration !== startGeneration) {\n                        return;\n                    }\n                    // If we were loading other pages (e.g. later cached pages), we want to stop loading them.\n                    this._nextPageCallback = undefined;\n                    this.error = error;\n                    this.status = AssetListStatus.HadLoaderErrors;\n\n                    if ((error as SAMError).code === SAMErrorCode.NOT_FOUND) {\n                        // Clear the list, as we would've been loading pages that are no longer valid.\n                        this._pages = [];\n                        this.dispatch(SharedEventWithItemChanges);\n                    } else {\n                        this.status = AssetListStatus.HadLoaderErrors;\n                        this.dispatch(SharedEventWithoutItemChanges);\n                    }\n                },\n            });\n            // We don't want to use skipCache() here because the result will not be persisted in the cache.\n            // therefore mark the resource as dirty to force a fresh fetch and persist the result in the cache.\n            resource.isDirty = this._invalidateCache;\n            const options: IItemLoaderOptions<ItemConfig> = {\n                order: this._order,\n                implicitFilter: this._implicitFilter,\n                filter: this._filter,\n                loadOptions,\n                resource\n            };\n            if (nextPageCallback) {\n                result = await nextPageCallback(options);\n\n                // We delete the callback only after the page fully loaded.\n                // That's so that we can retry the load if the first try fails.\n                this._nextPageCallback = undefined;\n            } else {\n                // Load the first page.\n                result = await this._loader.loadPage(options);\n\n                // We can update the window of valid changes at this point.\n                // Note that we don't want to update the value for the rest of the pages\n                // as we would still have items from the first page that might not be included yet.\n                // For example, if a new asset is created and it shows up on the first page,\n                // but the server didn't know about it just yet, then follow up pages\n                // are not allowed to change this value until we do another reload cycle.\n                this._mostRecentValidMutation = result.mostRecentValidMutation;\n            }\n\n            // Once the page is loaded, save the limit we've used for that particular page.\n            // If we refresh the page we want to run it with the same page limit.\n            page.limit = loadOptions.limit;\n        } catch (err) {\n            loaderError = err;\n        }\n\n        if (page.loadedGeneration >= startGeneration) {\n            // Ignore the results as a newer loader generation already finished loading this page.\n            return;\n        }\n\n        if (loaderError) {\n            if (page.startedGeneration !== startGeneration) {\n                // Note that we only revert if this load is still the most recent generation\n                // that started the load. Otherwise, we let the newer loader handle it eventually.\n                // Note that we return early in here to avoid bubbling up the error state while\n                // the newer loader is still in progress.\n                return;\n            }\n\n            // Revert the status of the page back to the original generation before we've started.\n            // This is needed so that we can retry loading this page again next time.\n            page.startedGeneration = previousPageGeneration;\n\n        } else if (result) {\n            // Note that we still use the results of the page even if the client started a new generation of loading.\n            // If we've reached this point, it means that the newer generation of loading has not yet reached this page.\n            // In that case, the result we just received is still new enough to considering it better than what we had before.\n\n            page.items = result.items.filter(item => this._implicitFilter.matches(item) && this._filter.matches(item));\n            this.total = result.total;\n            page.loadedGeneration = startGeneration;\n        }\n\n        // Update the state before sending any events.\n        const loadMorePages = await this._updateStatusAndLinkToNextPage(startGeneration, pageIndex, result, loadOptions, loaderError);\n\n        // If we decided to load more pages, this is a good time to make that recursive async call.\n        if (loadMorePages) {\n            await this._loadPageImpl(loadOptions);\n        }\n    }\n\n    /**\n     * Checks if the loader result can be used to load the next page.\n     * @param startGeneration   The generation that started this loader session.\n     * @param pageIndex         The index of the loaded page.\n     * @param result            The result received from the loader.\n     * @param loadOptions       The options used to load this page\n     * @param loaderError       The error caught during the execution of the loader, if any.\n     * @returns true if the caller should continue loading the next page automatically.\n     */\n    private async _updateStatusAndLinkToNextPage(startGeneration: number, pageIndex: number,\n        result: ILoadedPage<ItemConfig> | undefined, loadOptions: ILoadOptions, loaderError: any): Promise<boolean> {\n        if (this._generation !== startGeneration || this._nextPageIndex !== pageIndex) {\n            // If the result is from a previous generation, we cannot update the `next page` link because we\n            // reserve the page chaining only to the current generation of the loader. We don't want to keep\n            // loading pages using the previous generation anyway, so this is where we bail out\n            // that previous generation.\n            if (result) {\n                // If we had a result and we got as far as this point, then we have new items\n                // already injected. However, there's a newer load already in progress, so there's no actual\n                // state change here. We only want to inform of the possibility of new items\n                // being added to the page, so we dispatch an event to let the ItemList update its 'items' contents\n                // to the most recent version loaded in this load chain.\n                this.dispatch(SharedEventWithItemChanges);\n            }\n            return false;\n        }\n\n        if (!result) {\n            // This page failed to load, so loading any other pages is compromised too.\n            this.error = loaderError;\n            this._updateStatus(AssetListStatus.HadLoaderErrors);\n            return false;\n        }\n\n        // Increment the page index and store the link to the next page that we've received from the loader.\n        this._nextPageIndex = pageIndex + 1;\n        this._nextPageCallback = result.loadNextPage;\n\n        if (result.loadNextPage) {\n            // If we have a `loadNextPage` callback available then it means there are more pages to load.\n            this._updateStatus(AssetListStatus.ReadyHasMorePages);\n        } else {\n            // There are no other pages left. If we had any pages beyond this point\n            // before, this is a good time to remove them.\n            this._pages.splice(this._nextPageIndex);\n\n            try {\n                // If any pages are waiting for validation, we want to wait for them to finish\n                // before we're truly ReadyFullyLoaded. If we will be waiting, though, we should\n                // emit SharedEventWithItemChanges so that the ItemList can update its items.\n                // Otherwise we can skip right to ReadyFullyLoaded.\n                // Some use cases call for waiting on a list to fully load in a multi-step process.\n                // Before ResponseCache, that would mean the list is up-to-date with fresh info,\n                // so to maintain backward-compatibility, the ReadyFullyLoaded state shouldn't\n                // be broadcast until the cache is validated.\n                const pagesAwaitingValidation = this._pages.map(page => page.validatedPromise).filter(Boolean);\n                if (pagesAwaitingValidation.length) {\n                    this.dispatch(SharedEventWithItemChanges);\n                    await Promise.all(pagesAwaitingValidation);\n                }\n                this._updateStatus(AssetListStatus.ReadyFullyLoaded);\n            } catch (error) {\n                this.error = error;\n                this._updateStatus(AssetListStatus.HadLoaderErrors);\n                return false;\n            }\n        }\n\n        // There are two cases when we want to automatically load the next pages:\n        // 1) If the client requested to load all pages automatically via the `this._loadAllPages` flag.\n        // 2) If the client already requested these pages before in a previous generation, we will keep reloading\n        //    the pages automatically. This is the use-case when the client already scrolled past the first page and\n        //    the client triggers a refresh of the list in the background. In that case the list must automatically\n        //    update up-to the last scroll position. The pages will refresh one-by-one until all new items are available.\n\n        // If the page was loaded before (case #2 above), then the page must be in the list of pages already.\n        // That means the page index is lower than the size of the pages array.\n        const didLoadNextPageBefore = this._nextPageIndex < this._pages.length;\n\n        return loadOptions.loadAllPages || didLoadNextPageBefore;\n    }\n\n    /**\n     * Triggers a status update event.\n     * @param newStatus\n     */\n\n    private _updateStatus(newStatus: AssetListStatus) {\n        // We always want to send an event when we have item changes,\n        // so that the ItemList can update the item list even if the status didn't change.\n        const hasItemChanges = newStatus === AssetListStatus.ReadyFullyLoaded || newStatus === AssetListStatus.ReadyHasMorePages;\n        if (hasItemChanges || newStatus !== this.status) {\n            this.status = newStatus;\n            this.dispatch(hasItemChanges ? SharedEventWithItemChanges : SharedEventWithoutItemChanges);\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from './AdobeAsset';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { AdobeAssetSearchConfig } from './AdobeAssetSource';\nimport type AdobeAssetSearchFilter from './AdobeAssetSearchFilter';\nimport type AdobeAssetSearchInterface from '../interface/AdobeAssetSearchInterface';\nimport USSv3LoaderHelper, {\n    type IGetUSSResultsOpts,\n    type IUSSLoader\n} from './USSv3LoaderHelper';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { USSAssetFilterName } from './USSAssetFilterName';\nimport type USSAdobeAssetFilter from './USSAdobeAssetFilter';\nimport type { AssetsListingSearchOptions } from '../interface/AdobeAssetSearchInterface';\nimport {\n    type USSResponse,\n    USSv3OrderDirMap,\n    USSv3OrderFieldMap\n} from '../interface/USSv3Model';\n\nexport default class AdobeAssetDirectorySearchLoader implements IUSSLoader<AdobeAssetSearchConfig> {\n    private _ussLoaderHelper: USSv3LoaderHelper<AdobeAssetSearchConfig>;\n\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        core: ISAMCorePrivate,\n        private _adobeAssetSearchInterface: AdobeAssetSearchInterface,\n        private _asset: AdobeAsset,\n        private _implicitFilter: AdobeAssetSearchFilter\n    ) {\n        this._ussLoaderHelper = new USSv3LoaderHelper(assetPool, core, this);\n    }\n\n    supportsFilter(filter?: any): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<AdobeAssetSearchConfig>): Promise<ILoadedPage<AdobeAssetSearchConfig>> {\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- only for use by USSLoaderHelper\n     */\n    async _getUSSResults({\n        start,\n        loadOptions,\n        order,\n        mediaTypes,\n        excludeMediaTypes,\n        filter\n    }: IGetUSSResultsOpts<AdobeAssetSearchConfig>): Promise<USSResponse> {\n        const query = this._implicitFilter?._query;\n        const deepSearch = Boolean(this._implicitFilter.deepSearch);\n\n        const options: Partial<AssetsListingSearchOptions> = {\n            orderBy: USSv3OrderFieldMap[order.field],\n            orderDirection: USSv3OrderDirMap[order.direction],\n            start,\n            limit: loadOptions?.limit,\n            mediaTypes,\n            excludeMediaTypes,\n            query,\n            deepSearch,\n            assetId: this._asset.cloudID\n        };\n\n        if (filter.name === USSAssetFilterName) {\n            const ussFilter = filter as USSAdobeAssetFilter;\n            options.userId = ussFilter.userId;\n            options.uploadedFrom = ussFilter.uploadedFrom;\n        }\n\n        return this._adobeAssetSearchInterface.getFilteredAssets(options);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ItemBase from './ItemBase';\nimport { ModernSet } from '../utils/ModernSet';\n\nexport type IItemFilterHash = string;\n\nexport type ItemFilterRelation =\n    // There are no known shared elements between lists using the two filters.\n    | 'disjoint'\n\n    // Some items can be borrowed from a list filtered with the other filter,\n    // however there might be other items that were not in the other list.\n    | 'unknown'\n\n    // The other filter has a sufficient list of items that the new filter\n    // can create its entire list just by using the in-memory items from the previous\n    // filter.\n    | 'subset';\n\nexport interface IExplicitFilter<LocalType extends ItemBase> extends IItemFilter<LocalType>{\n    /**\n     * This mechanism allows to process items on the client side while the\n     * server fetch executes in the background. We can create new lists based\n     * on items that are already loaded in memory. For example, switching the\n     * sorting order of a list that is fully loaded will do so entirely on\n     * the client side. In that case the filter is a perfect match.\n     *\n     * Another example is when a filter narrows down the results. In that case,\n     * if a list has the wider list of items, then we can create a new list\n     * by applying the filter entirely on the client side.\n     *\n     * This should return `disjoint` in cases where the lists would be entirely disjoint.\n     * For example, if the filter returns only Spaces inside a specific teamID, then there's\n     * no reason to reuse the Spaces from a different teamID.\n     * In that case, it would be a waste of time to grab items from the other list.\n     *\n     * In case `other` filter would be a good starting point to start populating a list,\n     * the method returns 'unknown'. The new list would be incomplete and will require\n     * a reload from the server in order to fully download all resources.\n     *\n     * In case `other` filter contains a sufficiently large list of items that the new\n     * filter would generate a complete list, this method will return `subset`.\n     * In theory, no server requests are necessary to create an entire list of items\n     * using the `this` filter.\n     *\n     * @param other filter of the source list.\n     */\n    getRelationToFilter(other: IItemFilter<LocalType>): ItemFilterRelation;\n\n    /**\n     * Hash that can be used to uniqueuly identify the filter.\n     * This hash is used for caching in the ItemSource implementation.\n     */\n    readonly hash: IItemFilterHash;\n}\n\nexport interface IImplicitFilter<LocalType extends ItemBase> extends IItemFilter<LocalType>{}\n\nexport interface IItemFilter<LocalType extends ItemBase> {\n    /**\n     * Returns true if the provided item matches the filter.\n     * @param item\n     */\n    matches(item: LocalType): boolean;\n}\n\nexport function getFiltersRelation<LocalType extends ItemBase>(\n    requestedFilter?: IExplicitFilter<LocalType>, other?: IExplicitFilter<LocalType>) {\n    if (requestedFilter === other) {\n        // If the exact same filter is given, then it must be a complete list.\n        return 'subset';\n    }\n\n    if (requestedFilter && other) {\n        // If the hash is the same, then we have the same filter.\n        if (requestedFilter.hash === other.hash) {\n            return 'subset';\n        }\n\n        // Since the hashes don't match, they aren't both EverythingFilter. So if `other`\n        // is everything filter, then the requested filter is a subset.\n        if (other.hash === 'everything') {\n            return 'subset';\n        }\n        // If requested filter is the EverythingFilter, then it is a superset\n        if (requestedFilter.hash === 'everything') {\n            return 'unknown';\n        }\n\n        return requestedFilter.getRelationToFilter(other);\n    }\n\n    // If we have a filter, it means the other list had no filter, so this is a complete subset of an unfiltered list.\n    if (requestedFilter) {\n        return 'subset';\n    }\n\n    // If the other list had a filter and this new list doesn't have a filter, then this new list will be incomplete.\n    return 'unknown';\n}\n\n/** Determine whether two date ranges overlap and return their filter relation\n * Default values chosen to functionally represent -Inf and Inf if any param is undefined\n * @param startThis\n * @param endThis\n * @param startOther\n * @param endOther\n */\nexport function getDateRangeRelation(\n    startThis: Date = new Date(-9999, 0, 1),\n    endThis: Date = new Date(9999, 0, 1),\n    startOther: Date = new Date(-9999, 0, 1),\n    endOther: Date = new Date(9999, 0, 1)\n): ItemFilterRelation {\n\n    //  startOther ---- startThis ---- endThis --- endOther\n    //  A is completely within B\n    if (startThis >= startOther && endThis <= endOther) { return 'subset'; }\n\n    // startThis --- endThis --- startOther ---- endOther\n    // or\n    // startOther --- endOther --- startThis --- endThis\n    // A and B have no overlap\n    if (startThis > endOther || endThis < startOther) { return 'disjoint'; }\n\n    // startThis --- startOther --- endThis --- startOther\n    // or\n    // startOther --- startThis --- endOther --- endThis\n    // or\n    // startThis --- startOther --- endOther --- endThis\n    // A and B have some overlap, but A is not a subset\n    return 'unknown';\n}\n\n\ntype MultiVal<T> = T[] | Set<T> | undefined;\n\n/**\n * Determines relationship between two filter properties that accept multiple values (Set or Array). By convention,\n * SAM.js treats undefined/empty properties as matching all values.\n *\n * Note that direction is important. If `thisVal` = [1] and `otherVal` = [1, 2], the relation from `thisVal` to\n * `otherVal` is 'subset', because `otherVal` completely overlaps `thisVal`. If `thisVal` = [1, 2] and `otherVal` = [1],\n * the relation is 'unknown', because `otherVal` only partially overlaps `thisVal`.\n *\n * @param {MultiVal<T>} thisVal The value from `this` filter in `ItemFilter.getRelationToFilter(other)`\n * @param {MultiVal<T>} otherVal The value from `other` filter parameter in `ItemFilter.getRelationToFilter(other)`\n * @returns {ItemFilterRelation}\n *    'disjoint' if `other` does not overlap `this`\n *    'unknown' if `other` partially overlaps `this`\n *    'subset' if `other` fully overlaps `this`\n */\nexport function getMultiValueFilterRelation<T>(\n    thisVal: MultiVal<T>,\n    otherVal: MultiVal<T>\n): ItemFilterRelation {\n    // These are equivalent: new Set(), new Set(undefined), new Set([])\n    // As are these: new Set([1, 2]), new Set(new Set([1, 2]))\n    const thisValM = new ModernSet<T>(thisVal);\n    const otherValM = new ModernSet<T>(otherVal);\n\n    // Empty set = match everything.\n    // If `other` is empty, it overlaps `this` fully.\n    if (!otherValM.size) { return 'subset'; }\n    // `other` matches some items, `this` matches all items, so overlap is partial\n    if (otherValM.size && !thisValM.size) { return 'unknown'; }\n\n    // Both values are non-empty at this point.\n    if (thisValM.isDisjointFrom(otherValM)) { return 'disjoint'; }\n    if (thisValM.isSubsetOf(otherValM)) { return 'subset'; }\n    return 'unknown';\n}\n\nexport function getSingleValueFilterRelation<T extends string | number | boolean | undefined | null>(\n    thisVal?: T,\n    otherVal?: T): ItemFilterRelation {\n    // if values are defined and different, no overlap\n    if (thisVal && otherVal && thisVal !== otherVal) {\n        return 'disjoint';\n    }\n\n    // if we filtered the old list and we're not filtering the new list, we need to fetch more items\n    if (otherVal && !thisVal) {\n        return 'unknown';\n    }\n\n    // either they're the same, the old one was unfiltered and either way we can generate the new list entirely from the old\n    return 'subset';\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ItemBase from '../core/ItemBase';\nimport type { IItemFilter, ItemFilterRelation } from '../core/ItemFilter';\n\n/**\n* A special filter used as a default to simplify logic around filtering rather than having special cases\n* for filter being undefined.\n*/\n\nexport default class EverythingFilter<Item extends ItemBase> implements IItemFilter<Item> {\n\n    constructor() {\n    }\n\n    get hash(): string {\n        return 'everything';\n    }\n\n    matches(item: Item): boolean {\n        return item !== undefined;\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    getRelationToFilter(other: IItemFilter<Item>): ItemFilterRelation {\n        return 'subset';\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { default as uuid } from './uuid';\nimport SAMEvent from './SAMEvent';\n\nimport type ItemBase from './ItemBase';\nimport type { ItemId } from './ItemBase';\nimport type { IItemLoader } from './ItemLoader';\nimport type { IExplicitFilter, IImplicitFilter } from './ItemFilter';\nimport { getFiltersRelation } from './ItemFilter';\nimport type { IItemPoolDelegate, ItemsChangedEvent, ItemType } from './ItemPool';\nimport type ItemPool from './ItemPool';\nimport type { ItemLoaderRefreshNeededEvent, ItemLoaderStateChangeEvent } from './ItemLoaderState';\nimport ItemLoaderState, { AssetListStatus, LOADER_REFRESH_NEEDED, LOADER_STATE_CHANGED } from './ItemLoaderState';\nimport { observable } from './decorators';\nimport type { IEventMap } from './ITypedEventEmitter';\nimport type ITypedEventEmitter from './ITypedEventEmitter';\nimport TypedEventEmitter from './TypedEventEmitter';\nimport type { IItemOrder } from './ItemOrder';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { ItemListStateChangedEvent } from '../indexPrivate';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport EverythingFilter from './EverythingFilter';\nimport SAMError, { SAMErrorCode } from './SAMError';\n\n// STATE_CHANGED must be a different than the SAM.cpp equivalent so that patchAssetList can throttle\n// the SAM.cpp notifications, and map the SAM.js event listeners to the throttled pseudo-events.\nexport const STATE_CHANGED = 'status_changed';\nexport const LIST_CHANGED = 'listChanged';\n// NOTE: listFullyLoaded should only be fired when its loaders completed a page and no more pages are available.\n//       It should *not* be fired for any other reason that list status changes to ReadyFullyLoaded.\nexport const LIST_FULLY_LOADED = 'listFullyLoaded';\n\n// For identifying updates of ItemList that originate from ItemLoaders. ONLY ItemLoaders should\n// use this updateContext.\nexport const LOADER_UPDATE_CONTEXT = 'LoaderUpdateContext';\n\nexport class StateChangedEvent extends SAMEvent {\n    constructor() {\n        super(STATE_CHANGED);\n    }\n}\n\nexport class ListChangedEvent extends SAMEvent {\n    constructor() {\n        super(LIST_CHANGED);\n    }\n}\n\nexport const SharedListChangedEvent = new ListChangedEvent();\nexport const SharedStateChangedEvent = new StateChangedEvent();\n\ninterface IItemListEventMap extends IEventMap {\n    [STATE_CHANGED]: StateChangedEvent,\n    [LIST_CHANGED]: ListChangedEvent\n}\n\nexport interface IItemSourceConfig<\n    LocalType extends ItemBase = ItemBase,\n    ItemOrder extends IItemOrder<LocalType> = IItemOrder<LocalType>,\n    ImplicitItemFilter extends IImplicitFilter<LocalType> = IImplicitFilter<LocalType>,\n    ExplicitItemFilter extends IExplicitFilter<LocalType> = IExplicitFilter<LocalType>> {\n    type: LocalType;\n    order: ItemOrder;\n    implicitFilter: ImplicitItemFilter;\n    filter: ExplicitItemFilter;\n}\n\nexport interface ILoadOptions {\n    loadAllPages?: boolean;\n    /**\n     * Number of milliseconds past the last fetch where a refresh will be required.\n     * Note: Zero/undefined will force immediate refresh.\n     * Note: -1 will never force a refresh\n     */\n    refreshTimeout?: number;\n    limit?: number;\n}\n\nexport interface IItemListBase extends ITypedEventEmitter<IItemListEventMap> {\n    readonly type: ItemType;\n    readonly status: AssetListStatus;\n    readonly total: number | undefined;\n    readonly errors?: any[];\n    readonly generation: number;\n    readonly completedGeneration: number;\n    readonly hasLoaders: boolean;\n    readonly lastFetchTime: number;\n\n    /**\n     * Triggers the refresh of the items in the list.\n     *\n     * If the list already contains items from a previous load, the refresh\n     * doesn't throw away all the items immediately. It will refresh\n     * all preloaded pages one by one. The pages that were already loaded\n     * will be preserved until they had a chance to refresh.\n     */\n    refresh(): void;\n\n    /**\n     * If the initial `load` was started without using the `loadAllPages = true` option,\n     * this method allows the client to grab more items from the loaders as soon as more\n     * items are necessary.\n     *\n     * Note that calling this method again while the current page is still loading will\n     * not queue more pages.\n     */\n    loadNextPage(loadOptions?: ILoadOptions): void;\n\n    /**\n     * Make the list automatically update itself.\n     */\n    setNeedsRefresh(): void;\n}\n\nexport interface IItemList<ItemConfig extends IItemSourceConfig> extends IItemListBase {\n    readonly order: ItemConfig['order'];\n    readonly filter: ItemConfig['filter'];\n    readonly implicitFilter: ItemConfig['implicitFilter'];\n    readonly items: ItemConfig['type'][];\n}\n\ninterface IPendingNotification<LocalType extends ItemBase> {\n    generation: number;\n    event: ItemsChangedEvent<LocalType>;\n}\n\ntype ItemGeneration<LocalType extends ItemBase> = Map<LocalType, boolean>;\n\nlet GlobalGeneration = 0;\n\n/**\n * Make sure we can sort lists based on how recent they've\n * started their server load. The more recent loads will have higher\n * priority over lists that have not been updated in a while.\n */\nfunction allocGenerationIndex(): number {\n    return ++GlobalGeneration;\n}\n\ninterface IPendingLoad {\n    loadOptions?: ILoadOptions;\n    promise: Promise<void>;\n    revalidateAtPage: number;\n    invalidateCache?: boolean;\n}\n\nexport default class ItemList<ItemConfig extends IItemSourceConfig, IdType extends ItemId = ItemId> extends TypedEventEmitter<IItemListEventMap> implements IItemList<ItemConfig> {\n\n    private _status: AssetListStatus = AssetListStatus.NotStarted;\n    private _errors: any;\n    private _items: ItemConfig['type'][] = [];\n    private _total: number | undefined;\n\n    // Every time we refresh the list we increment the generation. This is used\n    // to make sure that older lists are updated once the new pages are loaded.\n    private _generation: number = 0;\n    private _completedGeneration: number = 0;\n\n    private _loaderStates: ItemLoaderState<ItemConfig>[] = [];\n\n    private _lastFetchTime: number = 0;\n    private _previousLoadPromise: Promise<any> | undefined;\n    private _needsRefresh: boolean = false;\n    private _invalidateCacheForNextLoad: boolean = false;\n    private _pendingLoad: IPendingLoad | undefined;\n\n    // We will have to keep the client side items around until we fully fetch again the entire list.\n    // Example: We fetched the latest favorite spaces for the sidebar. Then we add a new space and make it favorite.\n    // The new space will be added to the list automatically without doing another fetch from the server.\n    // This list will refresh in the background eventually. Once the fetch is complete (ie. all pages are loaded),\n    // we can get rid of the assets added in the previous generation. At that point we can know for sure,\n    // that the items added in the previous generation have already been captured in the new generation of loaded pages.\n    // If an item is created after the load started, we have to keep it around until the next generation ends.\n    // That's because the initial pages might have contained the item, but we've started the load too early and the\n    // item might not be captured in the result yet.\n    // NOTE: only external changes, such as ONS refreshes, should cause entries to be made in _itemUpdatesByGeneration.\n    //       Changes from an ItemLoader loading a page should NOT be reflected here. To avoid that, ItemLoader should\n    //       always use `createUpdateSession()` or `createMutationSession()` with an `updateContext`.\n    private _itemUpdatesByGeneration = new Map<number, ItemGeneration<ItemConfig['type']>>();\n    private _pendingNotifications?: IPendingNotification<ItemConfig['type']>[];\n    private _listId: string = uuid();\n\n    constructor(\n        private _itemPool: ItemPool<ItemConfig['type'], IdType>,\n        loaders: IItemLoader<ItemConfig>[],\n        readonly order: ItemConfig['order'],\n        readonly implicitFilter: ItemConfig['implicitFilter'],\n        readonly filter: ItemConfig['filter'] = new EverythingFilter(),\n        similarItemList?: IItemList<ItemConfig>,\n        private _loadOptions?: ILoadOptions\n    ) {\n        super();\n        for (const loader of loaders) {\n            if (loader.supportsFilter && !loader.supportsFilter(filter)) {\n                // We don't want to use loaders that do not support the filters.\n                // Otherwise, we are better off running this list entirely on the client side.\n                // For example, the discarded items are better handled on the client for now.\n                continue;\n            }\n            const state = new ItemLoaderState(this._core, loader, order, implicitFilter, filter);\n            state.on(LOADER_STATE_CHANGED, this._onItemLoaderStateChanged);\n            state.on(LOADER_REFRESH_NEEDED, this._onItemLoaderRefreshNeeded);\n            this._loaderStates.push(state);\n        }\n\n        if (similarItemList) {\n            this._copyInitialItemsFrom(similarItemList);\n        }\n\n        _itemPool.addDelegate(this._itemPoolDelegate, 'list');\n    }\n\n    private _debug(msg: string) {\n        this._core._environment.debug(`[ItemList ${this._itemPool.type} ${this._listId.slice(-4)}] ${msg}`);\n    }\n\n    /**\n     * When client calls `Source.getList()` and an existing List is returned, the existing List's\n     * loadOptions might be different than the loadOptions that were requested. ItemSource calls\n     * this method to allow some adjustments.\n     *\n     * @package -- only to be used internally by SAM.js\n     */\n    _updateLoadOptions(loadOptions: ILoadOptions = {}): void {\n        if (!this._loadOptions) {\n            this._loadOptions = {};\n        }\n\n        // Can only increase the limit if there is a limit set, otherwise keep the default limit\n        // because it's not possible to tell if it is being increased or decreased since it could\n        // be defined on the service and not anywhere in SAM.js.\n        if (this._loadOptions.limit && loadOptions.limit && this._loadOptions.limit < loadOptions.limit) {\n            this._loadOptions.limit = loadOptions.limit;\n        }\n\n        // Can turn on loadAllPages, but cannot turn it off\n        if (!this._loadOptions.loadAllPages && loadOptions.loadAllPages) {\n            this._loadOptions.loadAllPages = loadOptions.loadAllPages;\n        }\n\n        // It can only lower the refreshTimeout duration. Annoyingly, -1 means \"infinite future\", while 0 means \"now\".\n        if (loadOptions.refreshTimeout !== -1\n            && (this._loadOptions.refreshTimeout === -1\n                || (this._loadOptions.refreshTimeout ?? 0) >= (loadOptions.refreshTimeout ?? 0))\n        ) {\n            this._loadOptions.refreshTimeout = loadOptions.refreshTimeout;\n        }\n\n        this._loadAsync({\n            ...this._loadOptions,\n            // if new refreshTimeout is -1, then it shouldn't refresh, but it can still turn on\n            // loadAllPages, which might require loading more pages.\n            refreshTimeout: loadOptions.refreshTimeout === -1 ? -1 : this._loadOptions.refreshTimeout\n        }).catch(this._onUnhandledPromiseError);\n    }\n\n    get type(): ItemType {\n        return this._itemPool.type;\n    }\n\n    get generation(): number {\n        return this._generation;\n    }\n\n    get completedGeneration(): number {\n        return this._completedGeneration;\n    }\n\n    get hasLoaders(): boolean {\n        return this._loaderStates.length > 0;\n    }\n\n    get lastFetchTime(): number {\n        return this._lastFetchTime;\n    }\n\n    get _core(): ISAMCorePrivate {\n        return this._itemPool._core;\n    }\n\n    /**\n     * In many cases the items already exist in a different list,\n     * we just need to reorder the items or just apply a different filter.\n     * In that case, we can bootstrap the list with items borrowed from a different\n     * list until the items are refreshed in the background if necessary.\n     * @package -- only for use in SAM.js\n     * @param other\n     */\n    _copyInitialItemsFrom(other: IItemList<ItemConfig>): void {\n        const itemGeneration: ItemGeneration<ItemConfig['type']> = new Map<ItemConfig['type'], boolean>();\n\n        const filter = this.filter;\n\n        for (const item of other.items) {\n            if (this.implicitFilter.matches(item) && filter.matches(item)) {\n                itemGeneration.set(item, true);\n            }\n        }\n\n        // Inject the items as if they were just new items.\n        // These items will be invalidated once the next generation loads,\n        // which happened when `load()` finishes to load all pages.\n\n        // This list starts with the items from a previously downloaded list,\n        // so it inherits the generation from the other list too.\n        this._generation = other.generation;\n        this._completedGeneration = other.completedGeneration;\n\n        this._itemUpdatesByGeneration.set(this._generation, itemGeneration);\n\n        // Set the status to ready if other list is also set to ready and the other\n        // list matches the filtering of this list.\n        if (other.status === AssetListStatus.ReadyFullyLoaded && getFiltersRelation(filter, other.filter) === 'subset') {\n            this._status = AssetListStatus.ReadyFullyLoaded;\n            // SAM should copy the lastFetchTime from the other list as it is Fully loaded.\n            // Essentially, the same items sorted in a different direction should be just as stale as the source list.\n            this._lastFetchTime = other.lastFetchTime;\n        }\n\n        // Make sure we recompute the items once the user calls the `items` getter.\n        this._updateListItemsFromItemLoaderStates();\n    }\n\n    /**\n     * When a list completely loads, its items can be copied to other compatible lists. E.g., ListA and ListB have the\n     * same filter and both are partially loaded. When ListA finishes loading, all of its items can be copied to\n     * ListB, and ListB can be considered fully loaded.\n     *\n     * @package -- only for use in SAM.js\n     */\n    _applyListItemsFrom(other: IItemList<ItemConfig>): void {\n        if (other.status !== AssetListStatus.ReadyFullyLoaded) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, '_applyListItems other list must be fully loaded');\n        }\n        if (getFiltersRelation(this.filter, other.filter) !== 'subset') {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, '_applyListItems other list must be subset');\n        }\n\n        this._items = other.items.filter(item => this.implicitFilter.matches(item) && this.filter.matches(item));\n        this.order.sortItems(this._items);\n        this._dispatchItemsChangedEvent();\n        if (this._status !== AssetListStatus.ReadyFullyLoaded) {\n            this._status = AssetListStatus.ReadyFullyLoaded;\n            this._dispatchStateChangedEvents();\n        }\n    }\n\n    @observable(SharedStateChangedEvent)\n    get status(): AssetListStatus {\n        if (!this._loaderStates.length) {\n            // If we don't have any loaders, we always use the in-memory data for this list.\n            return AssetListStatus.ReadyFullyLoaded;\n        }\n        return this._status;\n    }\n\n    @observable(SharedStateChangedEvent)\n    get errors(): any[] {\n        return this._errors;\n    }\n\n    @observable(SharedListChangedEvent)\n    get items(): ItemConfig['type'][] {\n        return this._items;\n    }\n\n    @observable(SharedListChangedEvent)\n    get total(): number | undefined {\n        return this._total;\n    }\n\n    private _cleanPreviousGenerationItemsIfNeeded() {\n        // Check if all loaders are fully loaded and trim our previous generations.\n        let globalMostRecentValidMutation: number | undefined;\n\n        for (const loader of this._loaderStates) {\n            const { status, mostRecentValidMutation } = loader;\n            if (status === AssetListStatus.NotStarted || loader.status === AssetListStatus.HadLoaderErrors) {\n                // Ignore loaders that are not available.\n                continue;\n            }\n            if (status === AssetListStatus.Loading || status === AssetListStatus.ReadyHasMorePages) {\n                // We cannot trim any of the local items just yet. There are still more pages to load.\n                return;\n            }\n\n            // This loader is ready to trim some pages.\n\n            if (mostRecentValidMutation) {\n                // We have to take the minimum timestamps of all the loaders.\n                // If we have two loaders that have different latencies, then we have to keep items\n                // in the list until the most latent on has a chance to validate our local changes.\n                // The most recent mutations that we can eliminate from the local\n                // list are the ones outside of any latency window. The minimum is the most recent\n                // timestamp that is known to be valid across all loaders. Anything more recent than that\n                // would remove changes that were not yet replicated on at least one of the loaders.\n                globalMostRecentValidMutation = globalMostRecentValidMutation\n                    ? Math.min(globalMostRecentValidMutation, mostRecentValidMutation)\n                    : mostRecentValidMutation;\n            }\n        }\n\n        // We've loaded the entire set of pages, we are now ready to\n        // throw away the items that were added on the client side in\n        // the previous generations. These items should have been\n        // captured already by the new fetches from the server.\n        this._cleanPreviousGenerationItems(globalMostRecentValidMutation);\n    }\n\n\n    /**\n     * Removes items from the previous generations.\n     */\n    private _cleanPreviousGenerationItems(mostRecentValidMutation?: number): void {\n        // Convert any pending events into actual maps to make the changes available below.\n        this._applyItemsChangedEvents();\n\n        const currentGeneration = this._generation;\n        this._completedGeneration = currentGeneration;\n\n        // Pick all items added in the previous generations. If these items were indeed added, the updated\n        // lists should already contain the new items and we can go ahead and remove them from our in-memory store.\n        // Note that we cannot remove items added in the current generation as those were added\n        // after we've fetched the requests from the server and might not be up-to-date yet.\n        const newState: ItemGeneration<ItemConfig['type']> = new Map<ItemConfig['type'], boolean>();\n\n        let hadChanges = false;\n        let mostRecentDeletedGeneration = 0;\n\n        for (const [ key, generation ] of this._itemUpdatesByGeneration) {\n            if (key >= currentGeneration) {\n                continue;\n            }\n            // Deletes in JS Maps do not break the iterators, so it should be safe to delete generations while reading the map.\n            hadChanges = true;\n            this._itemUpdatesByGeneration.delete(key);\n            mostRecentDeletedGeneration = Math.max(mostRecentDeletedGeneration, key);\n\n            // If we have a most recent valid mutation timeframe, then we need to look for items that\n            // might still be inside that update time window.\n            if (mostRecentValidMutation) {\n                // Consolidate all the pending changes into a single generation.\n                for (const [ item, state ] of generation) {\n                    const { lastKnownClientMutation } = item;\n                    // If the item was already added to the list, then we have to keep updating its final state.\n                    if (newState.has(item) || lastKnownClientMutation && lastKnownClientMutation > mostRecentValidMutation) {\n                        // This item had a mutation too close to the last reload, so we cannot trust\n                        // that the listing returns the most up-to-date values. We have to preserve the item state (added / deleted)\n                        // until a future refresh.\n                        newState.set(item, state);\n                    }\n                }\n            }\n        }\n\n        if (newState.size) {\n            // Inject the new state in place of the most recent deleted generation.\n            this._itemUpdatesByGeneration.set(mostRecentDeletedGeneration, newState);\n        }\n\n        if (hadChanges) {\n            // Let the clients know the list must be recomputed.\n            this._dispatchItemsChangedEvent();\n        }\n    }\n\n    refresh(): void {\n        this._loadAsync(this._loadOptions).catch(this._onUnhandledPromiseError);\n    }\n\n    /**\n     * @deprecated -- Use {@link ItemList.refresh} instead. Will be removed on or after 2024-10-01.\n     */\n    load(options?: ILoadOptions): void {\n        oneTimeWarning('ItemList.load', 'ItemList.load() is deprecated and will be removed on or after'\n            + ' 2024-10-01. Use ItemList.refresh() instead. List load parameters are passed as the 3rd parameter to'\n            + ' ItemSource.getList(), which now automatically starts loading.');\n\n        // Previously, `ItemList.load()` with no parameters would always refresh the list because it implied a default\n        // value for `options.refreshTimeout` of `0` (\"refresh now\"). However, `_updateLoadOptions` assumes a\n        // default value for `options.refreshTimeout` of `-1` (\"never refresh\"). For better backward-compatibility,\n        // force a default for refreshTimeout of `0`. A defined value for refreshTimeout will override.\n        options = { refreshTimeout: 0, ...options };\n        this._updateLoadOptions(options);\n    }\n\n    // In case there is an error in load/loadNextPage that does not come from the Loader,\n    // append the error to the errors list.\n    private _onUnhandledPromiseError = (err: any): void => {\n        this._updateListStatusFromItemLoaderStates();\n        if (!this._errors?.length) {\n            this._errors = [];\n        }\n        this._errors.push(err);\n        this._status = AssetListStatus.HadLoaderErrors;\n        this.emit(STATE_CHANGED);\n    };\n\n    /**\n     * Other internal SAM.js code relies on getting a Promise.\n     * This should only be used inside SAM.js, not by clients.\n     * @package\n     */\n    async _loadAsync(options?: ILoadOptions, revalidateAtPage?: number): Promise<void> {\n        if (!this._loaderStates.length) {\n            // We don't have any loaders.\n            return;\n        }\n\n        const refreshTimeout = options?.refreshTimeout ?? 0;\n\n        // Check if the list needs to be refreshed:\n        // 1. The user didn't provide a refresh timeout, meaning we always load the contents.\n        // 2. There is a need to refresh the contents because the list has changed outside of SAMJS.\n        // 3. There's a refresh timeout and the timeout expired. We can use this mechanism to prevent using\n        //    data that is considered to be too old without forcing a refresh all the times.\n        // 4. refreshTimeout === -1 means the client does NOT want to refresh, only wait for existing\n        //    load requests to finish, possibly for the purpose of modifying other loadOptions like limit\n        //    or loadAllPages.\n        const lastFetchTime = this._lastFetchTime;\n        if (this._needsRefresh || !lastFetchTime || !refreshTimeout || (refreshTimeout !== -1 && lastFetchTime + refreshTimeout < Date.now())) {\n            this._debug(`_loadAsync() calling _load(): _needsRefresh: ${this._needsRefresh}, lastFetchTime: ${lastFetchTime}`\n                + ` refreshTimeout: ${refreshTimeout}`);\n            await this._load(options, revalidateAtPage);\n            return;\n        } else {\n            this._debug(`_loadAsync() not time to refresh: _needsRefresh: ${this._needsRefresh}, lastFetchTime: ${lastFetchTime}`\n                + ` refreshTimeout: ${refreshTimeout}`);\n        }\n\n        // If there's a pending load, wait until it's finished.\n        const previousLoadPromise = this._previousLoadPromise;\n        if (previousLoadPromise) {\n            // Wait until the previous load is complete.\n            this._debug('_loadAsync() awaiting previousLoadPromise');\n            await previousLoadPromise;\n        }\n\n        if (options?.loadAllPages) {\n            // Make sure the previous load didn't load just the first page.\n            await this._ensureAllPagesAreLoaded(options);\n        }\n    }\n\n    private async _load(loadOptions?: ILoadOptions, revalidateAtPage: number = 0): Promise<void> {\n        // Make sure we don't keep refreshing this list.\n        this._needsRefresh = false;\n        const invalidateCache = this._invalidateCacheForNextLoad;\n        // Reset the invalidate cache flag after using it for this load\n        this._invalidateCacheForNextLoad = false;\n\n        // Coalesce multiple load requests into one.\n        let pendingLoad = this._pendingLoad;\n        if (!pendingLoad) {\n            // Since _handlePendingLoad execution is deferred, control is returned to the caller where it\n            // should expect the List to already be loading, even though the Loader hasn't actually\n            // started.\n            this._status = AssetListStatus.Loading;\n            // _lastFetchTime must be defined now, because the _handlePendingLoad execution is deferred, which\n            // causes control to be passed back to the client. If the client then calls getList(), the refreshTimeout\n            // option would not be evaluated properly since _lastFetchTime would be stale.\n            this._lastFetchTime = Date.now();\n\n            // We use the generation to ignore results that are still in-flight.\n            // When a new load is issued, we will slowly cleanup the\n            // results as soon as the prior loading actions finish.\n            this._generation = allocGenerationIndex();\n\n            this._debug('_load() creating _pendingLoad');\n            this._pendingLoad = pendingLoad = {\n                loadOptions,\n                revalidateAtPage,\n                invalidateCache,\n                // Make sure the load executes after the stack unrolls.\n                promise: Promise.resolve().then(this._handlePendingLoad)\n            };\n\n            // Alert clients of state change\n            this._dispatchStateChangedEvents();\n        } else if (loadOptions?.loadAllPages) {\n            // Make sure that the pending load fetches all the pages.\n            if (!pendingLoad.loadOptions) {\n                pendingLoad.loadOptions = {};\n            }\n            pendingLoad.loadOptions.loadAllPages = true;\n        }\n        this._debug('_load() awaiting _pendingLoad');\n        await pendingLoad.promise;\n    }\n\n    private _handlePendingLoad = async () => {\n        const pendingLoad = this._pendingLoad;\n        if (pendingLoad) {\n            const { loadOptions, revalidateAtPage, invalidateCache } = pendingLoad;\n            this._pendingLoad = undefined;\n            this._debug('_handlePendingLoad() awaiting _runLoaders for loaderState.load');\n            await this._runLoaders((loaderState) => loaderState.load(this._generation, loadOptions, revalidateAtPage, invalidateCache));\n        }\n    };\n\n    loadNextPage(loadOptions?: ILoadOptions): void {\n        this._loadNextPageAsync(loadOptions || this._loadOptions).catch(this._onUnhandledPromiseError);\n    }\n\n    /**\n     * Other internal SAM.js code relies on getting a Promise.\n     * This should only be used inside SAM.js, not by clients.\n     * @package\n     */\n    async _loadNextPageAsync(options?: ILoadOptions): Promise<void> {\n        if (!this._loaderStates.length) {\n            // We don't have any loaders.\n            return;\n        }\n        if (this._pendingLoad) {\n            this._debug('_loadNextPageAsync() awaiting _pendingLoad');\n            await this._pendingLoad.promise;\n        } else {\n            // Since _loadAsync doesn't immediately start loading, but it does update its status and broadcast the\n            // status change event, _loadNextPageAsync must do the same. It can't be handled in _runLoaders only,\n            // because without the status event fired in _loadAsync, it'd be fired too late; with the status event\n            // fired in _loadAsync, it'd be fired redundantly.\n            this._status = AssetListStatus.Loading;\n            this._dispatchStateChangedEvents();\n            this._debug('_loadNextPageAsync() awaiting _runLoaders for loaderState.loadNextPage');\n            await this._runLoaders((loaderState) => loaderState.loadNextPage(options));\n        }\n    }\n\n    private async _runLoaders(fn: (loaderState: ItemLoaderState<ItemConfig>) => Promise<void>) {\n        // We need to update this first to avoid multiple calls to load\n        // from trying to load too often.\n        this._lastFetchTime = Date.now();\n\n        // Save the promise that triggered the last load.\n        const promise = Promise.all(this._loaderStates.map(fn));\n        this._previousLoadPromise = promise;\n\n        try {\n            this._debug('_runLoaders() awaiting loaders');\n            await promise;\n        } finally {\n            this._debug('_runLoaders() loaders complete');\n            // Remove the load promise.\n            this._previousLoadPromise = undefined;\n\n            // Notify listeners that the List.status has changed (computed from ItemLoaders). This must be the\n            // last line processed that alters any state in List, so that event listeners can immediately utilize\n            // the List in a completely settled state.\n            this._updateListStatusFromItemLoaderStates();\n            this._dispatchStateChangedEvents();\n\n            // Notify ItemSource that it can copy this list to other compatible lists.\n            // NOTE: this event not intended for clients.\n            if (this._status === AssetListStatus.ReadyFullyLoaded) {\n                this.emit(LIST_FULLY_LOADED);\n            }\n        }\n    }\n\n    setNeedsRefresh(): void {\n        if (this.status === AssetListStatus.NotStarted || !this._loaderStates.length) {\n            // List has never been loaded, so doesn't need refresh\n            return;\n        }\n\n        if (this.listenerCount(LIST_CHANGED)) {\n            // We have listeners waiting for changes, so go ahead and reload this list now.\n            this._needsRefresh = true;\n            this._invalidateCacheForNextLoad = true;\n            this.refresh();\n            return;\n        }\n\n        // There are no listeners, we will keep a note to refresh this list\n        // once the list becomes active again.\n        this._needsRefresh = true;\n        this._invalidateCacheForNextLoad = true;\n    }\n\n    _onEventListenerAdded() {\n        if (this._needsRefresh && this.listenerCount(LIST_CHANGED)) {\n            // Make sure the list is updated once the client\n            // needs to use the items of this list again.\n            this.refresh();\n        }\n    }\n\n    private async _ensureAllPagesAreLoaded(loadOptions?: ILoadOptions): Promise<void> {\n        if (this.status !== AssetListStatus.ReadyHasMorePages) {\n            // No more pages to load. Bail out.\n            return;\n        }\n        // Looks like the previous load didn't finish all the pages.\n        // Note that if another prefetch is issued, we will just wait on the promise\n        // created by the _runLoaders below via `this._previousLoadPromise`.\n        await this._runLoaders((loaderState) => loaderState.loadAllPages(loadOptions));\n    }\n\n    private _onItemLoaderStateChanged = (ev: ItemLoaderStateChangeEvent) => {\n        const { hasUpdatedItems } = ev;\n\n        this._cleanPreviousGenerationItemsIfNeeded();\n\n        // Only dispatch ItemsChanged events in response to ItemLoaderState events. ItemList will broadcast the\n        // StatusChanged event when exiting the load/loadNextPage methods so that all ItemList state is settled\n        // when the StatusChanged event fires.\n        if (hasUpdatedItems) {\n            this._updateListItemsFromItemLoaderStates();\n        }\n    };\n\n    private _onItemLoaderRefreshNeeded = (ev: ItemLoaderRefreshNeededEvent) => {\n        const { revalidateAtPage } = ev;\n\n        this._updateListItemsFromItemLoaderStates();\n\n        this._needsRefresh = true;\n        this._loadAsync(this._loadOptions, revalidateAtPage).catch(this._onUnhandledPromiseError);\n    };\n\n    // Reusable event that we use to avoid creating a new event object all the times.\n    private _globalStateChangedEvent = new ItemListStateChangedEvent(this);\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _dispatchStateChangedEvents() {\n        this._debug(`_dispatchStateChangedEvents status: ${AssetListStatus[this.status]}`);\n        this.dispatch(SharedStateChangedEvent);\n\n        // Dispatch a global event that can be used to handle global\n        // state updates without adding individual events on all the item lists.\n        this._core.dispatch(this._globalStateChangedEvent);\n    }\n\n    private _updateListStatusFromItemLoaderStates() {\n        let newStatus: AssetListStatus = this._pendingLoad ? AssetListStatus.Loading : AssetListStatus.NotStarted;\n\n        // Remove any previous error.\n        this._errors = undefined;\n\n        for (const loaderState of this._loaderStates) {\n            switch (loaderState.status) {\n            case AssetListStatus.HadLoaderErrors:\n                // We only surface the error in cases when there's no loader pending to start.\n                if (this._pendingLoad) {\n                    break;\n                }\n\n                // We surface errors immediately.\n                this._status = AssetListStatus.HadLoaderErrors;\n                this._errors = [ loaderState.error ];\n\n                // Return early to avoid cleaning previous generation items.\n                return;\n\n            case AssetListStatus.ReadyHasMorePages:\n                if (newStatus !== AssetListStatus.Loading && !this._loadOptions?.loadAllPages) {\n                    // If we don't have a loader that is still loading, and we're not loading all pages, then\n                    // change status to ReadyHasMorePages\n                    newStatus = AssetListStatus.ReadyHasMorePages;\n                }\n                break;\n\n            case AssetListStatus.Loading:\n                // We always want to know when a page is still loading.\n                newStatus = AssetListStatus.Loading;\n                break;\n\n            case AssetListStatus.ReadyFullyLoaded:\n                if (newStatus !== AssetListStatus.ReadyHasMorePages && newStatus !== AssetListStatus.Loading) {\n                    // If we don't have a loader that still has pages to load and if we don't actually load something.\n                    newStatus = AssetListStatus.ReadyFullyLoaded;\n                }\n                break;\n            }\n        }\n\n        this._status = newStatus;\n    }\n\n    private _dispatchItemsChangedEvent() {\n        // Let the client know they have to read the item list again.\n        this.dispatch(SharedListChangedEvent);\n    }\n\n    private _updateListItemsFromItemLoaderStates() {\n        this._applyItemsChangedEvents();\n\n        const itemSet = new Set<ItemConfig['type']>();\n\n        let total: number | undefined;\n\n        // Collect the items from all the loaders.\n        for (const loaderState of this._loaderStates) {\n            loaderState.collectAllItems(itemSet);\n\n            if (loaderState.total !== undefined) {\n                total = Math.max(total || 0, loaderState.total);\n            }\n        }\n\n        // Collect any items that were changed on the client\n        // side and might not be captured in the requests from\n        // the server side yet.\n        for (const itemGeneration of this._itemUpdatesByGeneration.values()) {\n            for (const [ item, state ] of itemGeneration.entries()) {\n                if (state) {\n                    itemSet.add(item);\n                } else {\n                    itemSet.delete(item);\n                }\n            }\n        }\n\n        const items = Array.from(itemSet);\n\n        // Sort the items based on the current ordering.\n        this.order.sortItems(items);\n\n        this._items = items;\n        this._total = total;\n\n        this._dispatchItemsChangedEvent();\n    }\n\n    /**\n     * Handles the change notifications from the pool.\n     * This method executes until the GC collects the List reference.\n     * This handler must be as quick as possible and postpone any list\n     * updates until the items are actually needed by the client.\n     * @param ev\n     */\n    private _itemPoolDelegate: IItemPoolDelegate<ItemConfig['type']> = {\n        onItemsUpdated: (event: ItemsChangedEvent<ItemConfig['type']>) => {\n            if (event.updateContext === LOADER_UPDATE_CONTEXT) {\n                // Ignore changes from ItemLoaders, which are handled in _updateListItemsFromItemLoaderStates\n                // but not _applyItemsChangedEvents. This is so partially loaded lists can maintain independence\n                // from other partially loaded lists whose filters intersect. E.g., if listA has items sorted ascending,\n                // and listB has the same filter but sorted descending, loading a page from listA won't add items to\n                // listB, and vice versa. Updates still go through ItemPool, so if both lists have loaded the same item,\n                // there will only be one instance of the item.\n                return;\n            }\n\n            let pendingNotifications = this._pendingNotifications;\n            if (!pendingNotifications) {\n                pendingNotifications = [];\n                this._pendingNotifications = pendingNotifications;\n            }\n\n            pendingNotifications.push({\n                generation: this._generation,\n                event\n            });\n\n            this._updateListItemsFromItemLoaderStates();\n        }\n    };\n\n    /**\n     * Handles changes injected through the item pool. These can be either local changes\n     * made by the user, or changes detected while fetching other lists.\n     *\n     * We use this mechanism to propagate the changes immediately across the entire app.\n     * For example, if a different call detects a Space has been updated, all the active\n     * lists will get the notification and automatically apply the change to their own listing.\n     *\n     * We are only interested about additions and deletions. Note that items\n     * can be added (or removed) to the list if the mutations of the item properties make the\n     * updated item pass (or fail) the filter of the current list.\n     */\n    private _applyItemsChangedEvents(): void {\n        const pendingNotifications = this._pendingNotifications;\n        if (!pendingNotifications) {\n            return;\n        }\n        this._pendingNotifications = undefined;\n\n        // Break down changes into their own generations of added/removed items.\n\n        for (const notification of pendingNotifications) {\n            const { event, generation } = notification;\n            if (generation < this._completedGeneration) {\n                // Ignore changes from completed generations. We already have all\n                // the correct items received from the server.\n                continue;\n            }\n\n            let itemGeneration = this._itemUpdatesByGeneration.get(generation);\n            if (!itemGeneration) {\n                itemGeneration = new Map();\n                this._itemUpdatesByGeneration.set(generation, itemGeneration);\n            }\n\n            if (event.addedItems) {\n                for (const item of event.addedItems) {\n                    if (this.implicitFilter.matches(item) && this.filter.matches(item)) {\n                        itemGeneration.set(item, true);\n                    }\n                }\n            }\n\n            if (event.changedItems) {\n                for (const item of event.changedItems) {\n                    // Check if we have any items that pass the filter test or not.\n                    // We need to store both matching and non-matching, just in case\n                    // an non-matching item was matching before the update and\n                    // we now have to manually remove it from the list fetched from\n                    // the server.\n                    const included = this.implicitFilter.matches(item) && this.filter.matches(item);\n                    itemGeneration.set(item, included);\n                }\n            }\n\n            if (event.discardedItems) {\n                for (const item of event.discardedItems) {\n                    // Any discarded items must be removed entirely.\n                    itemGeneration.set(item, false);\n                }\n            }\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Dummy implementation of the WeakRef interface to be used\n * in browsers that do not support WeakRefs natively.\n * Note that the associated objects will not be reclaimed by the\n * garbage collector. We don't expect this to be an actual issue\n * in practice for SAM though.\n */\nexport default class WeakRefPolyfill<T extends object> implements WeakRef<T> {\n    constructor(private _ref: T) {\n    }\n\n    /**\n     * Needed in order to fully implement the WeakRef interface.\n     * The `Symbol.toStringTag` symbol is a property that\n     * is used by the default implementation of the toString method.\n     */\n    get [Symbol.toStringTag](): 'WeakRef' {\n        return 'WeakRef';\n    }\n\n    /**\n     * Returns the WeakRef target object.\n     * Note that this implementation emulates the API, but cannot\n     * actually keep a weak reference.\n     *\n     * Based on MDN data, most modern browsers support WeakRef.\n     */\n    deref(): T | undefined {\n        return this._ref;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport WeakRefPolyfill from './WeakRefPolyfill';\n\nexport default typeof WeakRef !== 'undefined' ? WeakRef : WeakRefPolyfill;\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2022 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type { IItemList, IItemSourceConfig } from '../core/ItemList';\nimport { LIST_CHANGED, STATE_CHANGED } from '../core/ItemList';\nimport type EventEmitter from 'events';\nimport { AssetListStatus } from '../core/ItemLoaderState';\n\n/**\n * Returns a Promise that resolves when a List is loaded.\n * @param list to monitor for loading\n */\nexport function waitForListLoad(list: IItemList<IItemSourceConfig>): Promise<void> {\n    const listEventSource = list as unknown as EventEmitter;\n\n    return new Promise(resolve => {\n        function onStatusChange(): void {\n            if (list.status !== AssetListStatus.Loading) {\n                listEventSource.off(STATE_CHANGED, onStatusChange);\n                resolve();\n            }\n        }\n\n        listEventSource.on(STATE_CHANGED, onStatusChange);\n        // if List is already loaded, resolve now\n        onStatusChange();\n    });\n}\n\nexport function waitForListChange(list: IItemList<any>): Promise<void> {\n    const listEventSource = list as unknown as EventEmitter;\n\n    return new Promise(resolve => {\n        function onStatusChange(): void {\n            listEventSource.off(LIST_CHANGED, onStatusChange);\n            resolve();\n        }\n\n        listEventSource.on(LIST_CHANGED, onStatusChange);\n    });\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { keepAlive } from './decorators/KeepAliveManager';\nimport type {\n    IItemSourceConfig,\n    IItemList,\n    ILoadOptions } from './ItemList';\nimport ItemList, {\n    LIST_FULLY_LOADED,\n} from './ItemList';\nimport { AssetListStatus } from './ItemLoaderState';\nimport type { IItemLoader } from './ItemLoader';\nimport type { ItemFilterRelation } from './ItemFilter';\nimport { getFiltersRelation } from './ItemFilter';\nimport type ItemPool from './ItemPool';\nimport WeakRef from './WeakRef';\nimport SAMError, { SAMErrorCode } from './SAMError';\nimport EverythingFilter from './EverythingFilter';\nimport { waitForListLoad } from '../utils/waitForListLoad';\nimport type { ItemId } from './ItemBase';\n\ntype IListHash = string;\ntype ListByHash<ItemListType extends object> = Map<IListHash, WeakRef<ItemListType>>;\n\ntype IListCandidate<ItemListType> = {\n    list: ItemListType;\n    filterRelation: ItemFilterRelation | undefined;\n    generation: number;\n    length: number;\n}\n\n// TODO: change OrderDirection/Field to use SAM.cpp enums\n// https://jira.corp.adobe.com/browse/SAM-1644\nexport enum OrderDirection {\n    Ascending,\n    Descending\n}\nexport enum OrderField {\n    Name,\n    Modified,\n    Created,\n    Shared\n}\n\nfunction candidateSort<ItemListType>(a: IListCandidate<ItemListType>, b: IListCandidate<ItemListType>): number {\n    if (a.filterRelation !== b.filterRelation) {\n        // We prefer to start from a list that contains as many items as possible,\n        // so a list that can generate a complete `subset` must be moved to the left.\n        return a.filterRelation === 'subset' ? -1 : 1;\n    }\n\n    if (a.generation !== b.generation) {\n        // Newer generations must be moved to the left.\n        // Return a negative number if a.generation is larger.\n        return b.generation - a.generation;\n    }\n\n    // Lists with more items move left.\n    // Return a negative number if a.length is larger.\n    return b.length - a.length;\n}\n\n/**\n * ItemSource is the primary class and interface for interacting with lists of items\n * throughout SAM.js. It holds the only reference to the cache of lists which allows\n * SAM.js to be much more efficient when applying new filters and fetching new lists.\n *\n * @usage Instances of to this class must be cached so clients can\n * take advantage of shared cached lists.\n */\n\nexport default class ItemSource<ItemConfig extends IItemSourceConfig, IdType extends ItemId = ItemId> {\n\n    private _lists: ListByHash<ItemList<ItemConfig, IdType>> = new Map();\n\n    // To ensure that we always have an implicit filter, we will use the EverythingFilter as a default\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _loaders: IItemLoader<ItemConfig>[];\n\n    constructor(\n        private _itemPool: ItemPool<ItemConfig['type'], IdType>,\n        loaders: IItemLoader<ItemConfig>[],\n        protected _implicitFilter: ItemConfig['implicitFilter'] = new EverythingFilter()\n    ) {\n        this._loaders = loaders;\n    }\n\n    // [SAM-2302] SAMCpp.ts patches SAM.cpp to support two different call signatures. Once CDO has moved to using\n    // SAM.js-style getList and SAM.cpp supports the SAM.js call signature, this can be removed.\n    getList(orderDir: OrderDirection, orderField: OrderField): IItemList<ItemConfig>;\n    // eslint-disable-next-line no-dupe-class-members\n    getList(order: ItemConfig['order'], filter?: ItemConfig['filter'], loadOptions?: ILoadOptions): IItemList<ItemConfig>;\n    // To ensure that we always have an explicit filter, we will use the EverythingFilter as a default\n    // eslint-disable-next-line no-dupe-class-members\n    @keepAlive\n    getList(\n        order: (ItemConfig['order'] | OrderDirection),\n        filter: (ItemConfig['filter'] | OrderField) = new EverythingFilter(),\n        loadOptions?: ILoadOptions\n    ): IItemList<ItemConfig> {\n        if (typeof order === 'number' || typeof filter === 'number') {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'Using OrderDirection and OrderField is not implemented in SAM.js, and will be deprecated in SAM.cpp'\n            );\n        }\n\n        let list: ItemList<ItemConfig, IdType> | undefined = this._getExistingList(order, filter);\n\n        // If the list has been deactivated, then we cannot use the list anymore\n        // and we have to create a new one.\n\n        if (!list) {\n            // If this is an internal list, then we can bootstrap the\n            // contents of the list based on a similar list in the cache.\n            // This way we don't have to reload the contents when changing\n            // sort order.\n            const mostCompleteList = this._getMostCompleteCompatibleList(filter);\n            list = new ItemList<ItemConfig, IdType>(\n                this._itemPool,\n                this._loaders,\n                order,\n                this._implicitFilter,\n                filter,\n                mostCompleteList,\n                loadOptions\n            );\n            // When a list fully loads, copy its items to other compatible lists\n            list.on(LIST_FULLY_LOADED, () => this._onListFullyLoaded(list!));\n            this._lists.set(this._getListHash(order, filter), new WeakRef(list));\n        } else {\n            // The client may be passing in different loadOptions than what was specified for the\n            // existing List. Try to accommodate these new options without negatively impacting\n            // other clients of the same List. If the client did not explicitly specify refreshTimeout, assume\n            // that the existing list should not be refreshed. This is for better backward-compatibility for\n            // cases where clients expected that `getList()` would not automatically load data in order to make use\n            // of a cached List.\n            list._updateLoadOptions({ refreshTimeout: -1, ...loadOptions });\n        }\n\n        if (list.status === AssetListStatus.NotStarted) {\n            // Start loading.\n            list.refresh();\n        }\n\n        return list;\n    }\n\n    /**\n     * @TODO_Deprecation will be marked as deprecated on or after 2024-10-01 and removed on or after 2025-01-01\n     */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    getListWithTypes(orderDir: OrderDirection, orderField: OrderField, types: string[]) {\n        throw SAMError.create(SAMErrorCode.UNSUPPORTED, 'getListWithTypes is not implemented in SAM.js and will be deprecated in SAM.cpp');\n    }\n\n    private _getListHash(order: ItemConfig['order'], filter: ItemConfig['filter']): string {\n        return `${filter.hash}:${order.hash}`;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _getExistingList(order: ItemConfig['order'], filter: ItemConfig['filter']): ItemList<ItemConfig, IdType> | undefined {\n        const existingHash = this._getListHash(order, filter);\n        const listWeakRef = this._lists.get(existingHash);\n        if (listWeakRef) {\n            return listWeakRef.deref();\n        }\n    }\n\n    public setNeedsRefresh() {\n        for (const list of this._getLists()) {\n            list.setNeedsRefresh();\n        }\n    }\n\n    /**\n     * Find an already loaded list that is a good candidate to borrow items for when creating a new list.\n     *\n     * For example, switching the sorting order of a list would have the same filter,\n     * so it should be ok to just run that entirely on the client side.\n     *\n     * Another example is filtering down some items. If we already loaded a list that contained these items,\n     * then we can build the filtered down list by just executing the same filter on the client side.\n     *\n     * @param requestedFilter Filter of the new list.\n     * @returns The best candidate list that could be used as a starting point.\n     */\n    private _getMostCompleteCompatibleList(requestedFilter?: ItemConfig['filter']): IItemList<ItemConfig> | undefined {\n        const candidates: IListCandidate<IItemList<ItemConfig>>[] = [];\n\n        for (const list of this._getLists()) {\n            if (list.status === AssetListStatus.ReadyFullyLoaded) {\n                const filterRelation = getFiltersRelation(requestedFilter, list.filter);\n                if (filterRelation !== 'disjoint') {\n                    candidates.push({ list, filterRelation, generation: list.generation, length: list.items.length });\n                }\n            }\n        }\n\n        // We want to pick the item with the newest items, or the list that has the largest subset of items.\n        candidates.sort(candidateSort);\n\n        // The first item in the list is the best candidate.\n        return candidates[0]?.list;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    *_getLists() {\n        const lists = this._lists;\n        for (const [ hash, listRef ] of lists.entries()) {\n            const list = listRef.deref();\n            if (!list) {\n                // The weak ref has expired, remove it from the map.\n                // Note that JS Maps are ok with deletions during iteration.\n                lists.delete(hash);\n                continue;\n            }\n            yield list;\n        }\n    }\n\n    /**\n     * Copies fully loaded lists to compatible lists when load completes.\n     */\n    private _onListFullyLoaded(loadedList: ItemList<ItemConfig, IdType>) {\n        if (loadedList.status !== AssetListStatus.ReadyFullyLoaded) {\n            return;\n        }\n\n        for (const list of this._getLists()) {\n            // Other lists that are subsets of the loaded list can be inferred to be fully loaded, too.\n            if (list !== loadedList\n                && getFiltersRelation(list.filter, loadedList.filter) === 'subset'\n            ) {\n                // Don't update lists that are loading, as it could interfere with its generation tracking\n                waitForListLoad(list).then(() => {\n                    // Skip lists that are fresher than the loaded list\n                    if (list.completedGeneration >= loadedList.completedGeneration) {\n                        return;\n                    }\n                    list._applyListItemsFrom(loadedList);\n                });\n            }\n        }\n    }\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type Resource from '../assets/Resource';\nimport type RenditionResource from '../assets/RenditionResource';\nimport type RenditionTileResource from '../assets/RenditionTileResource';\n\n/**\n * Helper class that manages fetching and caching of rendition blobs from RenditionResource.\n */\nexport class RenditionBlobHelper<T extends Resource<Blob> = RenditionResource> {\n    protected _resource: T | undefined = undefined;\n\n    protected _shouldDeleteCachedResponse(resource: T): boolean {\n        return Boolean(this._resource && this._resource.etag !== resource.etag);\n    }\n\n    async fetch(resource: T): Promise<Blob> {\n        await resource.load();\n\n        if (this._shouldDeleteCachedResponse(resource)) {\n            this._resource?.deleteCachedResponse();\n        }\n        this._resource = resource;\n        return this._resource.data;\n    }\n}\n\n/**\n * Helper class that manages fetching and caching of rendition blobs from RenditionTileResource.\n */\nexport class RenditionTileBlobHelper extends RenditionBlobHelper<RenditionTileResource> {\n    protected _shouldDeleteCachedResponse(resource: RenditionTileResource): boolean {\n        return Boolean(this._resource && this._resource.renditionUrl !== resource.renditionUrl);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AssetVersion from './AssetVersion';\nimport type AdobeAsset from './AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport Resource from './Resource';\n\n\nexport default class RenditionResource extends Resource<Blob> {\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _parent: AdobeAsset | AssetVersion,\n        private _size: number,\n        private _type: string,\n    ) {\n        super(_core, {\n            parseResponse: async (response: Response) => await response.blob(),\n            /**\n             * Revalidation is not needed because rendition will be either from cache or from a new request:\n             * - AdobeAsset: etag changes when rendition changes\n             * - AssetVersion: rendition never changes\n             */\n            skipRevalidation: () => true,\n            skipCache: () => {\n                // The GraphQL interface provides rendition URLs that better leverage browser caching,\n                // so we only need RenditionResource to cache this response when GraphQL is still disabled.\n                const useGraphQL = this._core._environment.getValue('FEATURE_FLAGS')?.['use-graphql-cache'];\n                return useGraphQL ? true : false;\n            }\n        });\n    }\n\n    get size(): number {\n        return this._size;\n    }\n\n    get type(): string {\n        return this._type;\n    }\n\n    protected async _loadData() {\n        const assetInterface = await this._parent._getAssetInterface();\n        return assetInterface.getRendition(this);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { AssetLinks, ISAMOperationResultProps } from '../interface/RepositoryModel';\nimport ItemBase from '../core/ItemBase';\nimport type { ISAMObject } from '../indexPrivate';\nimport { observable } from '../core/decorators';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport { getURLFromLinks, RelType } from '../interface/LinkUtils';\nimport AssetInterface, { VersionPatchTypes } from '../interface/AssetInterface';\nimport SAMError, { isSAMError, SAMErrorCode } from '../core/SAMError';\nimport type { RenditionStatus } from '../utils/RenditionFetcher';\nimport { RenditionFetcher, RenditionType, SUPPORTED_SIZES } from '../utils/RenditionFetcher';\nimport ManifestResource from './ManifestResource';\nimport { createMilestoneJsonParams } from '../assets/AssetUtils';\nimport { RenditionBlobHelper } from '../utils/RenditionBlobHelper';\nimport RenditionResource from './RenditionResource';\n\nexport interface IAssetVersion {\n    // These fields come from the version history listing\n    version: string;\n    created: string;\n    created_by: string;\n    milestone: IVersionMilestone | undefined;\n    _links: AssetLinks;  // links for this version\n    // These fields are provided from AssetVersionLoader using data from the parent AdobeAsset's AssetInterface\n    assetId: string;\n    assetEtag: string;\n    assetLinks: AssetLinks;\n    'repo:deviceAssetName': string;\n}\n\nexport interface IVersionMilestone {\n    label?: string;\n    description?: string;\n    versionId?: string;\n}\n\n/**\n * Options for getting a presigned URL for an asset version.\n */\nexport interface GetPresignedURLOptions {\n    /**\n     * Time-to-live for the presigned URL in seconds.\n     * If not provided, the service's default expiration time will be used (4 hours as of this writing).\n     */\n    presignedUrlExpirationSeconds?: number;\n}\n\nexport default class AssetVersion extends ItemBase implements ISAMObject, SAM.AssetVersion {\n    // We are intentionally setting a static etag.\n    // Using the HEAD version of the asset's etag will cause unintended side affects.\n    private _etag: string = 'static-etag';\n    // These fields come from the parent Asset\n    private _assetId: string = '';\n    private _assetEtag: string = '';\n    private _assetLinks?: AssetLinks;\n\n    // These fields come from the AssetVersionLoader\n    private _createdAt: Date = new Date();\n    private _createdBy: string = '';\n    private _label?: string;\n    private _description?: string;\n    private __links?: AssetLinks;\n    private _renditionFetcher: RenditionFetcher | undefined;\n    private _renditionBlobHelper: RenditionBlobHelper | undefined;\n    // @ts-expect-error\n    private fr: FinalizationRegistry | undefined;\n\n    private _manifest: ManifestResource = new ManifestResource(this._core, this);\n    private _name: string = '';\n\n    private async _getHeadAssetInterface() {\n        const assetContext = await this._core.getAssetContext();\n        // NOTE: this AssetInterface is tied to the parent AdobeAsset for all AssetVersion instances. Where API\n        // calls are version-specific, the links need to come from this.__links; if the API call is not specific to\n        // a particular version, then the links need to come from `this._assetLinks`.\n        return new AssetInterface(\n            assetContext._rapi,\n            this._assetId,\n            this._assetLinks!,\n            // etag only applies to the head version, and isn't needed\n            // by version history R-API calls, but is required for AssetInterface.\n            this._assetEtag\n        );\n    }\n\n    async _getAssetInterface() {\n        return new AssetInterface(\n            this._core.hostAssetContext._rapi,\n            this._assetId,\n            this.__links!,\n            this._etag\n        );\n    }\n\n    @observable\n    get assetId(): string {\n        return this._assetId;\n    }\n\n    @observable\n    get created(): Date {\n        return this._createdAt;\n    }\n\n    @observable\n    get createdBy(): string {\n        return this._createdBy;\n    }\n\n    @observable\n    get links(): AssetLinks {\n        // Make a copy to avoid the client accidentally manipulating the links\n        return Object.assign({}, this.__links);\n    }\n\n    get manifest(): ManifestResource {\n        return this._manifest;\n    }\n\n    @observable\n    get milestone(): IVersionMilestone | undefined {\n        return this._label ? {\n            label: this._label,\n            description: this._description,\n        } : undefined;\n    }\n\n    @observable\n    get name(): string {\n        return this._name;\n    }\n\n    @observable\n    get versionId(): string {\n        return this.id;\n    }\n\n    private _getRenditionFetcher(): RenditionFetcher {\n        if (!this._renditionFetcher) {\n            this._renditionBlobHelper = new RenditionBlobHelper();\n            this._renditionFetcher = new RenditionFetcher(\n                this._core,\n                SUPPORTED_SIZES,\n                async (size: number, type: string) => {\n                    const resource = new RenditionResource(this._core, this, size, type);\n                    // @ts-expect-error -- Object is possibly 'undefined' even though\n                    // it is initialized in this block\n                    return this._renditionBlobHelper.fetch(resource);\n                }\n            );\n\n            // Forward change events from the rendition fetcher\n            // to this class.\n            this._renditionFetcher.on('change', () => {\n                this.dispatch({ type: 'change' });\n            });\n        }\n        return this._renditionFetcher;\n    }\n\n    @observable\n    getRenditionURL(size: number, type: string = RenditionType.PNG): string {\n        const renditionFetcher = this._getRenditionFetcher();\n        return renditionFetcher.getURL(size, type, this._etag);\n    }\n\n    @observable\n    public renditionURLStatus(size: number, type: string): RenditionStatus {\n        const renditionFetcher = this._getRenditionFetcher();\n        return renditionFetcher.renditionURLStatus(size, type, this._etag);\n    }\n\n    /**\n     * See {@link AssetInterface#getCustomRendition} for usage\n     */\n    async getCustomRendition({\n        size,\n        type,\n        urlTemplateOptions,\n        additionalHeaders\n    }: Parameters<AssetInterface['getCustomRendition']>[0] = {}): Promise<Response> {\n        const assetInterface = await this._getAssetInterface();\n        return assetInterface.getCustomRendition({ size, type, urlTemplateOptions, additionalHeaders });\n    }\n\n    /**\n     * See {@link AssetInterface#getCustomRendition} for usage\n     */\n    async getAllCustomRenditions({\n        type,\n        urlTemplateOptions,\n        additionalHeaders\n    }: Parameters<AssetInterface['getAllCustomRenditions']>[0] = {}): Promise<Response> {\n        const assetInterface = await this._getAssetInterface();\n        return assetInterface.getAllCustomRenditions({ type, urlTemplateOptions, additionalHeaders });\n    }\n\n    /**\n     * Returns a pre-signed rendition url for the given size and type.\n     * @param size The size of the asset version rendition    (e.g. 128, 256, 512, 1024)\n     * @param type The type of the asset version rendition    (e.g. 'image/png', 'image/jpg', etc.)\n     * see {@link https://git.corp.adobe.com/pages/caf/api-spec/chapters/common_resources/renditions_resources.html#media-types} for available types\n     * @returns A pre-signed URL for the asset version rendition\n     */\n    async getPresignedRenditionURL({\n        size,\n        type\n    }: {\n        size: number;\n        type: string;\n    }): Promise<string> {\n\n        const response = await this.getCustomRendition({\n            size,\n            type,\n            additionalHeaders: {\n                'Accept': 'application/vnd.adobecloud.download+json'\n            }\n        });\n\n        const res = await response.json();\n        return res.href;\n    }\n\n    /**\n     * Gets a presigned URL for downloading this version of the asset.\n     * The URL will be valid for the specified duration or the service's default expiration time if not specified.\n     *\n     * @param options - Options for getting the presigned URL\n     * @returns A promise that resolves to the presigned download URL.\n     */\n    async getPresignedURL(options: GetPresignedURLOptions = {}): Promise<string> {\n        const blockDownloadServiceURL = getURLFromLinks(this.__links, RelType.DOWNLOAD);\n        const assetInterface = await this._getAssetInterface();\n        return await assetInterface.getBlockDownloadURL(blockDownloadServiceURL, options.presignedUrlExpirationSeconds);\n    }\n\n    async restore() {\n        const assetContext = await this._core.getAssetContext();\n        const asset = await assetContext.getAssetWithCloudID(this._assetId);\n        const isComposite = asset.isComposite;\n        if (isComposite) {\n            const href = getURLFromLinks(this.__links, RelType.MANIFEST);\n            const headInterface = await this._getHeadAssetInterface();\n            await headInterface.restoreVersionManifest(href);\n            await asset._load();\n        } else {\n            const target = getURLFromLinks(asset.links, RelType.PRIMARY);\n            await this.copy(target);\n        }\n    }\n\n    /**\n     * Copy the asset version to the target asset using the target's asset\n     * RelType.PRIMARY link.\n     *\n     * @deprecated Use {@link AssetVersion#copyPrimaryToAsset} instead.\n     * @see {@link AssetVersion#copyPrimaryToAsset}\n     *\n     * @warning - Not currently functioning.\n     *\n     * @param target - The target HREF of the asset to copy the asset version to.\n     * @returns A promise that resolves to the result of the copy operation.\n     */\n    async copy(target: string) {\n        const assetContext = await this._core.getAssetContext();\n        const asset = await assetContext.getAssetWithCloudID(this._assetId);\n        const isComposite = asset.isComposite;\n        const source = getURLFromLinks(this.__links, RelType.PRIMARY);\n        if (isComposite) {\n            // Copy for composite assets not yet implemented, JIRA: https://jira.corp.adobe.com/browse/ACPCSS-1875\n            throw SAMError.create(SAMErrorCode.UNSUPPORTED, 'AssetVersion.copy not implemented for composite assets');\n        } else {\n            const headInterface = await this._getHeadAssetInterface();\n            const result = await headInterface.runOperation({\n                op: 'copy',\n                id: this._assetId,\n                source: { 'href': source, 'if-match': '*' },\n                target: { 'href': target, 'if-match': '*' }\n            });\n            return result;\n        }\n    }\n\n    /**\n     * Move this version of an asset to an existing asset identified by the targetAssetID.\n     * Currently this is implemented by copying the asset version to the target asset and then\n     * permanently deleting the version from the source asset. In the future we should ask\n     * the platform to support this operation directly.\n     *\n     * @param targetAssetID - The target asset ID of the asset to move the asset version to.\n     * @param deleteHeadAssetIfLastVersion - If true, delete the head asset when this version is the last. RAPI\n     * won't allow the last version to be deleted, so if needed, this will delete the head asset which will\n     * also delete the last version.\n     */\n    async moveToAsset(targetAssetID: string, deleteHeadAssetIfLastVersion: boolean = false): Promise<void> {\n        await this.copyPrimaryToAsset(targetAssetID);\n        await this.permanentlyDelete(deleteHeadAssetIfLastVersion);\n    }\n\n    /**\n     * Permanently delete this version of an asset and it's representation\n     * in the local asset pool (in memory cache).\n     *\n     * @param deleteHeadAssetIfLastVersion - If true, delete the head asset when this version is the last. RAPI\n     * won't allow the last version to be deleted, so if needed, this will delete the head asset which will\n     * also delete the last version.\n     */\n    async permanentlyDelete(deleteHeadAssetIfLastVersion: boolean = false): Promise<void> {\n        const headInterface = await this._getHeadAssetInterface();\n        const assetContext = await this._core.getAssetContext();\n        const headAsset = assetContext._assetPool.getLocalItemById(this._assetId);\n\n        try {\n            await headInterface.patchVersion([ {\n                op: VersionPatchTypes.remove,\n                path: `/children/version=${this.versionId}`\n            } ]);\n        } catch (e) {\n            if (!isSAMError(e)) {\n                throw e;\n            }\n\n            const samError = e as SAMError;\n            /**\n             * @TODO SAMJS-604: Once the actual response body is confirmed from RAPI\n             * we can use that to check for the problem type instead of a blanket\n             * check for ACCESS_DENIED.\n             *\n             * @note Seems odd that we would say it's ACCESS_DENIED when it's really\n             * when it's really FORBIDDEN_OPERATION.\n             */\n            if (samError.code !== SAMErrorCode.ACCESS_DENIED\n                || !deleteHeadAssetIfLastVersion\n            ) {\n                throw e;\n            }\n\n            if (headAsset) {\n                await headAsset.permanentlyDelete();\n            }\n        }\n\n        // If the asset is not found, that means there isn't a version to delete.\n        // since the head asset doesn't exist locally.\n        if (!headAsset) {\n            return;\n        }\n\n        const session = headAsset._versionPool.createUpdateSession();\n        session.queueDiscardedItem(this);\n        session.commit();\n    }\n\n    /**\n     * Copy this version of an asset to an existing asset identified by the targetAssetID.\n    * @deprecated Use {@link AssetVersion#copyPrimaryToAsset} instead.\n     * @see {@link AssetVersion#copyPrimaryToAsset}\n     *\n     * @note this method does not fetch the repository metadata and other data\n     * from the services for the targetAssetID. If the targetAssetID does not\n     * exist the services will throw an error, which will bubble up to the caller.\n     *\n     * @param targetAssetID - The target asset ID of the asset to copy the asset version to.\n     * @returns A promise that resolves to the result of the copy operation.\n     */\n    async copyToAsset(targetAssetID: string): Promise<void> {\n        const headInterface = await this._getHeadAssetInterface();\n        await headInterface.runOperationWithEmptyResponse({\n            op: 'copy_resources',\n            source: {\n                'repo:assetId': this._assetId,\n                'repo:version': this.versionId\n            },\n            target: {\n                'repo:assetId': targetAssetID\n            },\n            resources: [\n                {\n                    reltype: RelType.PRIMARY\n                },\n            ]\n        });\n    }\n\n    /**\n     * Copy this version of an asset to an existing asset identified by the targetAssetID.\n     *\n     * @note this method does not fetch the repository metadata and other data\n     * from the services for the targetAssetID. If the targetAssetID does not\n     * exist the services will throw an error, which will bubble up to the caller.\n     *\n     * @param targetAssetID - The target asset ID of the asset to copy the asset version to.\n     * @returns A promise that resolves to the result of the copy operation.\n     */\n    async copyPrimaryToAsset(targetAssetID: string): Promise<void> {\n        await this.copyToAsset(targetAssetID);\n    }\n\n    /**\n     * Copy this version of an asset to a new asset.\n     *\n     * @param newAssetPath - The path of the new asset.\n     * @param newAssetName - The name of the new asset.\n     * @param repositoryId - The repository ID of the new asset.\n     * @returns A promise that resolves to the new asset as an AdobeAsset instance.\n     */\n    async copyToNewAsset(newAssetPath: string, newAssetName: string, repositoryId: string): Promise<SAM.AdobeAsset> {\n        const headInterface = await this._getHeadAssetInterface();\n        const result = await headInterface.runOperation({\n            op: 'copy',\n            source: {\n                'repo:assetId': this._assetId,\n                'repo:version': this.versionId\n            },\n            target: {\n                'repo:path': newAssetPath + '/' + newAssetName,\n                'repo:repositoryId': repositoryId\n            }\n        }) as ISAMOperationResultProps;\n\n        if (!result.asset) {\n            throw SAMError.create(SAMErrorCode.UNKNOWN, 'Failed to copy asset version');\n        }\n\n        const assetContext = await this._core.getAssetContext();\n        const session = assetContext._assetPool.createUpdateSession();\n        const asset = assetContext._adobeAssetUpdater.updateRemoteItem(session, result.asset);\n        session.commit();\n        return asset;\n    }\n\n    async setMilestone({ label = this.milestone?.label || '', description = this.milestone?.description || '' }: Partial<IVersionMilestone>) {\n        const jsonParams = createMilestoneJsonParams(\n            this.versionId,\n            !!this.milestone,\n            label,\n            description\n        );\n        const headInterface = await this._getHeadAssetInterface();\n        await headInterface.patchVersion(jsonParams);\n        const assetContext = await this._core.getAssetContext();\n        const asset = await assetContext.getAssetWithCloudID(this._assetId);\n        const session = asset._versionPool.createUpdateSession();\n        VersionUpdater.updateLocalItem(session, this, {\n            milestone: {\n                label,\n                description\n            }\n        });\n        session.commit();\n    }\n\n    async removeMilestone() {\n        if (!this.milestone) {\n            return;\n        }\n        const jsonParams = [ {\n            op: VersionPatchTypes.remove,\n            path: `/children/version=${this.versionId}/milestone`,\n        } ];\n\n        const headInterface = await this._getHeadAssetInterface();\n        await headInterface.patchVersion(jsonParams);\n        const assetContext = await this._core.getAssetContext();\n        const asset = await assetContext.getAssetWithCloudID(this._assetId);\n        const session = asset._versionPool.createUpdateSession();\n        VersionUpdater.updateLocalItem(session, this, {\n            milestone: {\n                label: ''\n            } as IVersionMilestone\n        });\n        session.commit();\n    }\n}\n\nexport const VersionUpdater = new ItemUpdater<AssetVersion, Partial<IAssetVersion>>({\n    localItemType: AssetVersion,\n    remoteIdProperty: 'version',\n    propertyUpdater: new PropertyUpdater({\n        '_createdAt': { name: 'created', format: 'date' },\n        '_createdBy': 'created_by',\n        '_label': 'milestone.label',\n        '_description': 'milestone.description',\n        '_assetId': 'assetId',\n        '_assetEtag': 'assetEtag',\n        '_assetLinks': { name: 'assetLinks', format: 'object' },\n        '__links': { name: '_links', format: 'object' },\n        '_name': 'repo:deviceAssetName',\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AssetInterface from '../interface/AssetInterface';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { AssetVersionConfig } from './AdobeAssetSource';\nimport type { IAssetVersion } from './AssetVersion';\nimport type AssetVersion from './AssetVersion';\nimport { VersionUpdater } from './AssetVersion';\nimport type AssetVersionFilter from './AssetVersionFilter';\n\n\nexport interface IAssetVersionResponse {\n    children: IAssetVersion[];\n    total_children: number;\n}\n\nexport default class AssetVersionLoader implements IItemLoader<AssetVersionConfig> {\n\n    constructor(\n        private _versionPool: ItemPool<AssetVersion>,\n        private _assetInterfacePromise: Promise<AssetInterface>\n    ) {}\n\n    async loadPage(options: IItemLoaderOptions<AssetVersionConfig>, start?: string): Promise<ILoadedPage<AssetVersionConfig>> {\n        return await this._loadPage(options, start);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<AssetVersionConfig>, start?: string): Promise<ILoadedPage<AssetVersionConfig>> {\n        const { limit } = options.loadOptions ?? {};\n        // We will ignore the update if we had local changes sooner than this timestamp.\n        const latency = this._versionPool._core._environment.getValue('VERSIONS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n\n        const assetInterface = await this._assetInterfacePromise;\n        const filter = options.filter as AssetVersionFilter;\n        const version = filter?.version || undefined;\n        const result: IAssetVersionResponse = await assetInterface.getVersions({ start, limit, version });\n        const session = this._versionPool.createLoaderUpdateSession(mostRecentValidMutation);\n        const versions: IAssetVersion[] =  result.children.map((version: IAssetVersion) => ({\n            ...version,\n            // assetId, assetEtag, assetLinks are needed to construct the AssetInterface for the AssetVersion\n            assetId: assetInterface.assetID,\n            assetEtag: assetInterface.etag,\n            assetLinks: assetInterface.links\n        }));\n        const items = VersionUpdater.updateRemoteItems(session, versions);\n        session.commit();\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<AssetVersionConfig> | undefined;\n        const currentCount = result.children.length;\n        // TODO: unit test to ensure this doesn't throw an exception if there are 0 pages\n        const nextStart = result.children[currentCount - 1]?.created;\n\n        if (nextStart && limit && currentCount === limit) {\n            loadNextPage = (options: IItemLoaderOptions<AssetVersionConfig>) =>\n                this._loadPage(options, nextStart);\n        }\n\n        return {\n            items,\n            total: result.total_children,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { SharedChangeEvent } from './ChangeEvent';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type IEvent from './IEvent';\nimport type { ItemId } from './ItemBase';\nimport type ItemBase from './ItemBase';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\n\nexport type IUpdateSessionType = 'fetch' | 'mutation';\n\nfunction updateLastKnownClientMutationValues(item: ItemBase) {\n    item.updateLastKnownClientMutation();\n}\n\nfunction updateLastKnownClientMutationKeys(_: any, item: ItemBase) {\n    item.updateLastKnownClientMutation();\n}\n\nexport interface IUpdateSession<LocalType extends ItemBase> extends ISAMObject {\n    readonly hasChanges: boolean;\n    readonly updateContext?: string;\n    readonly mostRecentValidMutation?: number;\n    readonly type: IUpdateSessionType;\n\n    ensureItemIsAdded(item: LocalType): void;\n    reindexItem(item: LocalType, oldId: ItemId, newId: ItemId): void;\n\n    queueAddedItem(item: LocalType): void;\n    queueChangedItem(item: LocalType, event?: IEvent[]): void;\n    queueDiscardedItem(item: LocalType): void;\n\n    readonly addedItems?: LocalType[];\n    readonly changedItems?: LocalType[];\n    readonly discardedItems?: LocalType[];\n    readonly changedItemsWithEvents?: [LocalType, Set<IEvent>][];\n\n    getItemById(id: ItemId): LocalType | undefined;\n    findItem(callback: (item: LocalType) => boolean): LocalType | undefined;\n\n    checkIfItemAllowsMutations(item: LocalType): boolean;\n\n    commit(): void;\n}\n\nexport type IUpdateSessionDelegate<LocalType extends ItemBase> = {\n    getLocalItemById(id: ItemId): LocalType | undefined;\n    isItemDiscarded(item: LocalType): boolean;\n    reindexItem(item: LocalType, oldId: ItemId, newId: ItemId): void;\n    commitUpdateSession(session: UpdateSession<LocalType>): void;\n    findItem(callback: (item: LocalType) => boolean): LocalType | undefined;\n}\n\nexport default class UpdateSession<LocalType extends ItemBase> implements IUpdateSession<LocalType> {\n\n    private _addedItems?: Map<ItemId, LocalType>;\n    private _changedItems?: Map<LocalType, Set<IEvent>>;\n    private _discardedItems?: Set<LocalType>;\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        private _delegate: IUpdateSessionDelegate<LocalType>,\n        readonly updateContext?: string,\n        readonly mostRecentValidMutation?: number,\n        readonly type: IUpdateSessionType = 'fetch'\n    ) {\n    }\n\n    get hasChanges(): boolean {\n        return Boolean(this._addedItems || this._changedItems || this._discardedItems);\n    }\n\n    get addedItems(): LocalType[] | undefined {\n        return this._addedItems && Array.from(this._addedItems.values());\n    }\n\n    get changedItems(): LocalType[] | undefined {\n        return this._changedItems && Array.from(this._changedItems.keys());\n    }\n\n    get discardedItems(): LocalType[] | undefined {\n        return this._discardedItems && Array.from(this._discardedItems);\n    }\n\n    get changedItemsWithEvents(): [LocalType, Set<IEvent>][] | undefined {\n        return this._changedItems && Array.from(this._changedItems);\n    }\n\n    checkIfItemAllowsMutations(item: LocalType): boolean {\n        const { lastKnownClientMutation } = item;\n        const { mostRecentValidMutation } = this;\n        // Return false only when the item has a mutation time that is more recent than the\n        // window of latency that the server APIs can guarantee.\n        return !lastKnownClientMutation || !mostRecentValidMutation || lastKnownClientMutation < mostRecentValidMutation;\n    }\n\n    ensureItemIsAdded(item: LocalType): void {\n        const { id } = item;\n        if (this._addedItems?.get(id) === item) {\n            // It was already part of this session.\n            return;\n        }\n\n        // Check if we already had it in the pool. If it was discarded before,\n        // then we want to recover it by adding it again.\n        const delegate = this._delegate;\n        const existingItem = delegate.getLocalItemById(id);\n        if (existingItem && existingItem !== item) {\n            // Note: This is typically caused by using updateLocalItem in an async function after some `await`\n            //            statement. While waiting, some other process causes the item to be added to the ItemPool\n            //            under the same ID. Using updateRemoteItem ensures that only the current item in the pool\n            //            is updated; however, changing `updateLocalItem(session, this, ...)` to updateRemoteItem could cause\n            //            an instance other than `this` to be updated.\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Item with id ${id} does not match the item with this id in the item pool`);\n        }\n\n        if (existingItem && !delegate.isItemDiscarded(item)) {\n            return;\n        }\n\n        // Finally, let's just add this item again.\n        this.queueAddedItem(item);\n    }\n\n    reindexItem(item: LocalType, oldId: ItemId, newId: ItemId): void {\n        item._setId(newId);\n        this.queueChangedItem(item, [ SharedChangeEvent ]);\n        // Updates the key in the key-item cache\n        this._delegate.reindexItem(item, oldId, newId);\n    }\n\n    queueAddedItem(item: LocalType): void {\n        let addedItems = this._addedItems;\n        if (!addedItems) {\n            addedItems = new Map<ItemId, LocalType>();\n            this._addedItems = addedItems;\n        }\n        addedItems.set(item.id, item);\n\n        // Make sure we don't send any changed events on new items.\n        this._changedItems?.delete(item);\n    }\n\n    queueChangedItem(item: LocalType, events: IEvent[] = [ SharedChangeEvent ]): void {\n        if (this._addedItems?.has(item.id)) {\n            // We don't send any events on new items.\n            return;\n        }\n\n        let changedItems = this._changedItems;\n        if (!changedItems) {\n            changedItems = new Map<LocalType, Set<IEvent>>();\n            this._changedItems = changedItems;\n        }\n\n        let itemEvents = changedItems.get(item);\n        if (!itemEvents) {\n            itemEvents = new Set<IEvent>();\n            changedItems.set(item, itemEvents);\n        }\n\n        events.forEach((event) => itemEvents?.add(event));\n    }\n\n    /**\n     * Marks an item for discard by adding it to a WeakSet holding pen.\n     * - On `commit()`, the item is removed from lists and itemPool.\n     * - The item is garbage collected once no direct references remain.\n     * - Prevents undefined errors while async processes settle.\n     *\n     * **Scenario 1: When Clients Do NOT Need Notification (Standard Removal)**\n     * - Use this when removing an item from a list, **but no explicit client notification is needed**.\n     * - Example: Item no longer belongs in the list.\n     * - The item is removed from lists but stays in the holden pen and pool temporarily for safety.\n     *\n     * **Scenario 2: When Clients DO Need Notification (Permanent Delete or Unshare)**\n     * - If `updateLocal/RemoteItem()` is called first (e.g., setting `Permission.None` to revoke access),\n     *   the item is **not** added to the holding pen and remains in the pool.\n     * - This ensures clients (in 1Up or Editor views) get an event to handle permission loss.\n     * - 🚨 In this case, **manually call `removeLocalItems([item.id])`** after to remove it from the pool.\n     *\n     * Note: If there is a new use case for removing an Item and notifying clients other than AdobeAsset access loss,\n     * we should add a more generalized \"access lost\" status and event in ItemBase. Reach out to SAM.js core team if you run into this need.\n     */\n    queueDiscardedItem(item: LocalType): void {\n        let discardedItems = this._discardedItems;\n        if (!discardedItems) {\n            discardedItems = new Set<LocalType>();\n            this._discardedItems = discardedItems;\n        }\n        discardedItems.add(item);\n    }\n\n    getItemById(id: ItemId): LocalType | undefined {\n        return this._addedItems?.get(id) || this._delegate.getLocalItemById(id);\n    }\n\n    findItem(callback: (item: LocalType) => boolean): LocalType | undefined {\n        return this._delegate.findItem(callback);\n    }\n\n    commit() {\n        // Committing the update session first to make sure the pool is up-to-date\n        // with the latest changes before we move control back to the client code.\n        this._delegate.commitUpdateSession(this);\n\n        // Dispatch all events on the changed items.\n        const changedItems = this._changedItems;\n        if (changedItems) {\n            for (const [ item, events ] of changedItems.entries()) {\n                for (const event of events) {\n                    item.dispatch(event);\n                }\n            }\n        }\n\n        if (this.type === 'mutation') {\n            // If this was the result of a mutation change, then we have to update the timestamps\n            // of all the items that were used.\n            this._addedItems?.forEach(updateLastKnownClientMutationValues);\n            this._discardedItems?.forEach(updateLastKnownClientMutationValues);\n            changedItems?.forEach(updateLastKnownClientMutationKeys);\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IEventMap } from './TypedEventEmitter';\nimport TypedEventEmitter from './TypedEventEmitter';\nimport SAMEvent from './SAMEvent';\nimport type { ItemId } from './ItemBase';\nimport type ItemBase from './ItemBase';\nimport WeakRef from './WeakRef';\nimport type { IUpdateSession, IUpdateSessionDelegate } from './UpdateSession';\nimport UpdateSession from './UpdateSession';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport { LOADER_UPDATE_CONTEXT } from './ItemList';\n\nexport const ITEMS_CHANGED = 'itemsChanged';\n\nexport class ItemsChangedEvent<LocalType extends ItemBase> extends SAMEvent {\n    constructor(\n        readonly addedItems?: LocalType[],\n        readonly changedItems?: LocalType[],\n        readonly discardedItems?: LocalType[],\n        readonly updateContext?: string,\n    ) {\n        super(ITEMS_CHANGED);\n    }\n}\n\ninterface ItemPoolEventMap<LocalType extends ItemBase> extends IEventMap {\n    [ITEMS_CHANGED]: ItemsChangedEvent<LocalType>;\n}\n\nexport interface IItemPoolDelegate<LocalType extends ItemBase> {\n    onItemsUpdated(event: ItemsChangedEvent<LocalType>, sender: ItemPool<LocalType>): void;\n}\n\n// We want to make sure that contexts delegates are added after all the lists,\n// so that they can expect the contents of the lists to be updated already.\ntype PoolDelegatePriority = 'list' | 'context';\n\n// Delegates are like events, but they keep weak references to the callbacks to\n// prevent memory leaks caused by the subscriber forgetting to unsubscribe.\ntype IPoolDelegateRef<LocalType extends ItemBase> = {\n    priority: PoolDelegatePriority;\n    delegate: WeakRef<IItemPoolDelegate<LocalType>>;\n};\n\nfunction compareDelegatesByPriority<LocalType extends ItemBase>(\n    a: IPoolDelegateRef<LocalType>, b: IPoolDelegateRef<LocalType>) {\n    if (a.priority === b.priority) {\n        return 0;\n    }\n    return a.priority === 'list' ? -1 : 1;\n}\n\nexport type ItemType =\n    | 'orgRepository'\n    | 'team'\n    | 'space'\n    | 'asset'\n    | 'collaborator'\n    | 'collaboratorsByAssetID'\n    | 'invitedCollaborator'\n    | 'version'\n    | 'project or adobeasset'\n    | 'customModel'\n    | 'assignment'\n    | 'gradient'\n    | 'frameio'\n    | 'classroom'\n    | 'comment'\n    | 'studentAssignmentFile'\n    | 'classroomMember'\n    | 'studentAssignment'\n    | 'addressBookContact'\n    | 'addressBook'\n    | 'element'\n    | 'post'\n    | 'board';\n\n/**\n * The ItemPool class is used to keep unique references in memory for objects that\n * represent cloud items like assets, teams or spaces.\n * The ItemPool helps with mapping between a remote id and a local reference in memory.\n *\n * On supported browsers the pool uses the WeakRef object to keep the objects alive.\n * only as long as they are used by the application.\n */\nexport default class ItemPool<LocalType extends ItemBase, IdType extends ItemId = ItemId>\n    extends TypedEventEmitter<ItemPoolEventMap<LocalType>> implements ISAMObject {\n\n    private _objectsById = new Map<ItemId, WeakRef<LocalType>>();\n    private _discardedObjects = new WeakSet<LocalType>();\n\n    private _delegates: IPoolDelegateRef<LocalType>[] = [];\n    private _hasUnsortedDelegates: boolean = false;\n\n    constructor(readonly _core: ISAMCorePrivate, readonly type: ItemType) {\n        super();\n    }\n\n    private _getObjectsById<TypeExtendsLocal extends LocalType>() {\n        return this._objectsById as Map<ItemId, WeakRef<TypeExtendsLocal>>;\n    }\n\n    /**\n     * Looks up the item in the local in-memory storage.\n     * The items are stored used WeakRef to avoid leaking. The client of this\n     * method is responsible with keeping these objects alive for as long as\n     * they are needed.\n     * @param id\n     * @returns\n     */\n    getLocalItemById = <TypeExtendsLocal extends LocalType>(id: IdType): TypeExtendsLocal | undefined => {\n        const ref = this._getObjectsById<TypeExtendsLocal>().get(id);\n        return ref?.deref();\n    };\n\n    /**\n     * Fully removes items from the pool when `queueDiscardedItem()` alone is not sufficient.\n     *\n     * Normally, `queueDiscardedItem()` will remove an Item from the ItemPool, but it does not when it has been\n     * modified in the same UpdateSession (using `updateLocalItem()` or `updateRemoteItem()`). When this occurs, you will need to call\n     * `removeLocalItems()` afterwards to ensure the Item is fully removed from the pool.\n     * This scenario typically occurs when an Item is permanently deleted or unshared\n     * because we first need to update the permissions to None before removing in the same session.\n     * Calling `removeLocalItems()` will prevent stale items from remaining in the pool after this update,\n     * and ensure `getAssetWithCloudID()` returns `NOT_FOUND` instead of returning an item that has broken APIs.\n     *\n     * To ensure full removal, use:\n     *     ```\n     *     updateLocalItem(session, item, { effectivePermission: Permission.None });\n     *     queueDiscardedItem(item);\n     *     removeLocalItems([item.id]);  // Ensures full removal from the pool\n     *     ```\n     * If you are NOT updating the item in the same session, you only need to call `queueDiscardedItem()`.\n     * 🚨 ** Calling `removeLocalItems()` without calling `queueDiscardedItem()` will NOT remove the Item from ItemLists. **\n     */\n    removeLocalItems = (ids: ItemId | ItemId[]): void => {\n        if (Array.isArray(ids)) {\n            ids.forEach((id: ItemId) => {\n                this._objectsById.delete(id);\n            });\n            return;\n        }\n        this._objectsById.delete(ids);\n    };\n\n    isItemDiscarded = (item: LocalType): boolean => {\n        return this._discardedObjects.has(item);\n    };\n\n    reindexItem = (item: LocalType, oldId: IdType, newId: IdType): void => {\n        if (oldId !== newId) {\n            this._objectsById.set(newId, new WeakRef(item));\n            this._objectsById.delete(oldId);\n        }\n    };\n\n    /**\n     * Creates an UpdateSession instance for add/update/delete of models in the SAM system, outside of ItemLoaders.\n     * UpdateSessions let you delay firing events until you're ready to notify clients via the commit--typically\n     * right after updating the model with remote data via one or more ItemUpdaters.\n     *\n     * @param updateContext {string} (optional) Useful to identify what is causing a particular change, especially\n     *        in ItemPool delegates.\n     * @param mostRecentValidMutation {number} (optional) Determines if UpdateSession will allow the update (see\n     *        {@link createLoaderUpdateSession})\n     */\n    createUpdateSession<TypeExtendsLocal extends LocalType>(updateContext?: string, mostRecentValidMutation?: number): IUpdateSession<TypeExtendsLocal> {\n        return new UpdateSession(this._core, this._updateSessionDelegate<TypeExtendsLocal>(), updateContext, mostRecentValidMutation);\n    }\n\n    /**\n     * For use in USS-based ItemLoaders.\n     *\n     * @param mostRecentValidMutation {number} UpdateSession only allows changes to items that that have a\n     *        `lastKnownClientMutation` before this timestamp. Since USS index lag can cause data to be 2-3 seconds\n     *        stale, all USS-based ItemLoaders *must* pass `mostRecentValidMutation` of\n     *        `Date.now() - core._environment.getValue('USS_LIST_UPDATE_LATENCY')`\n     */\n    createLoaderUpdateSession<TypeExtendsLocal extends LocalType>(mostRecentValidMutation: number): IUpdateSession<TypeExtendsLocal> {\n        return new UpdateSession(this._core, this._updateSessionDelegate<TypeExtendsLocal>(), LOADER_UPDATE_CONTEXT, mostRecentValidMutation);\n    }\n\n    /**\n     * Creates an UpdateSession for add/update/delete of models in the SAM system that get tracked as\n     * `item.lastKnownClientMutation`. Used when the data source is the \"source of truth\" for this model, in order to\n     * prevent stale data from overwriting it. E.g., for AdobeAsset, it should be used when loading a single Asset\n     * from R-API.\n     */\n    createMutationSession<TypeExtendsLocal extends LocalType>(): IUpdateSession<TypeExtendsLocal> {\n        return new UpdateSession(this._core, this._updateSessionDelegate<TypeExtendsLocal>(), undefined, undefined, 'mutation');\n    }\n\n    /**\n     * Creates an UpdateSession for ItemLoader implementations, as well as updates `item.lastKnownClientMutation`\n     * when models are added/updated/deleted. Used when the data source is the \"source of truth\" for this model,\n     * in order to prevent stale data from overwriting it via `create*UpdateSession()`.\n     */\n    createLoaderMutationSession<TypeExtendsLocal extends LocalType>(): IUpdateSession<TypeExtendsLocal> {\n        return new UpdateSession(this._core, this._updateSessionDelegate<TypeExtendsLocal>(), LOADER_UPDATE_CONTEXT, undefined, 'mutation');\n    }\n\n    private _updateSessionDelegate = <TypeExtendsLocal extends LocalType>(): IUpdateSessionDelegate<TypeExtendsLocal> => {\n        return {\n            getLocalItemById: this.getLocalItemById,\n            isItemDiscarded: this.isItemDiscarded,\n            reindexItem: this.reindexItem,\n            findItem: this.findItem<TypeExtendsLocal>,\n            commitUpdateSession: (session: IUpdateSession<TypeExtendsLocal>): void => {\n                if (!session.hasChanges) {\n                    return;\n                }\n\n                const objectsById = this._objectsById;\n                const discardedObjects = this._discardedObjects;\n\n                // Make a note about discarded objects.\n                const { discardedItems } = session;\n                if (discardedItems) {\n                    for (const item of discardedItems) {\n                        discardedObjects.add(item);\n                    }\n                }\n\n                // Inject the new items in the local map.\n                const { addedItems } = session;\n                if (addedItems) {\n                    for (const item of addedItems) {\n                        objectsById.set(item.id, new WeakRef(item));\n                        discardedObjects.delete(item);\n                    }\n                }\n\n                const event = new ItemsChangedEvent<LocalType>(\n                    session.addedItems,\n                    session.changedItems,\n                    session.discardedItems,\n                    session.updateContext,\n                );\n\n                const delegates = this._delegates;\n                if (this._hasUnsortedDelegates) {\n                    delegates.sort(compareDelegatesByPriority);\n                    this._hasUnsortedDelegates = false;\n                }\n\n                let hasEmptyWeakRefs = false;\n\n                for (const delegateRef of delegates) {\n                    const delegate = delegateRef.delegate.deref();\n                    if (!delegate) {\n                        // Remember to filter out the expired weak refs.\n                        hasEmptyWeakRefs = true;\n                        continue;\n                    }\n\n                    //We wanted to add a custom IdType for type safety for combined id's, which is why there's an IdType on the ItemPool\n                    //  However, to avoid piping the IdType through the entire ItemPool and UpdateSession, we're cutting off the\n                    //  fanout from that change here.  It should be fine because IdType extends string.\n                    //@ts-expect-error\n                    delegate.onItemsUpdated(event, this);\n                }\n\n                if (hasEmptyWeakRefs) {\n                    // Make another pass and keep only the delegates that are still alive.\n                    this._delegates = delegates.filter((ref) => ref.delegate.deref());\n                }\n\n                this.dispatch(event);\n            }\n        };\n    };\n\n    /**\n     * Adds a delegate to receive notifications when items change.\n     * The delegates cannot be removed, so the connection is alive\n     * as long as both the pool and the delegate are still referenced.\n     * The client must ensure the delegate is kept alive until the events\n     * are not necessary anymore.\n     *\n     * Performance: Adding too many delegates can obviously hurt performance.\n     * Make sure that the callbacks on the delegate are as fast as possible.\n     * If the user is not interested in any updates, it is best to make a note\n     * that the list is dirty and return as quick as possible. Make sure to delay\n     * any of the actual work until the data is requested by the client.\n     *\n     * Note that we are not adding this on top of the event dispatcher to avoid\n     * making the weak ref model a wide spread solution across the repo.\n     *\n     * @param delegate\n     */\n    addDelegate(delegate: IItemPoolDelegate<LocalType>, priority: PoolDelegatePriority): void {\n        this._delegates.push({ priority, delegate: new WeakRef(delegate) });\n        this._hasUnsortedDelegates = true;\n    }\n\n    *[Symbol.iterator](): IterableIterator<LocalType> {\n        const objectsById = this._objectsById;\n        for (const [ key, itemRef ] of objectsById) {\n            const item = itemRef.deref();\n            if (!item) {\n                // Clean up stale references while iterating.\n                objectsById.delete(key);\n                continue;\n            }\n            yield item;\n        }\n    }\n\n    forEach(fn: (item: LocalType) => void): void {\n        for (const item of this) {\n            fn(item);\n        }\n    }\n\n    map<T>(fn: (item: LocalType) => T): Array<T> {\n        const results: Array<T> = [];\n        for (const item of this) {\n            results.push(fn(item));\n        }\n        return results;\n    }\n\n    /**\n     * Finds the first item in the ItemPool that matches the given predicate.\n     */\n    findItem = <TypeExtendsLocal extends LocalType>(fn: (item: TypeExtendsLocal) => boolean): TypeExtendsLocal | undefined => {\n        for (const item of this) {\n            if (fn(item as TypeExtendsLocal)) {\n                return item as TypeExtendsLocal;\n            }\n        }\n        return undefined;\n    };\n\n    /**\n     * Returns all items currently in the ItemPool as an Array\n     */\n    toArray<TypeExtendsLocal extends LocalType>(): TypeExtendsLocal[] {\n        return this.map<TypeExtendsLocal>(item => item as TypeExtendsLocal);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from './AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { RelType } from '../interface/LinkUtils';\nimport AdobeAssetResource from './AdobeAssetResource';\n\nexport default class FileContentResource extends AdobeAssetResource<Blob> {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _parent: AdobeAsset,\n    ) {\n        super(_core, _parent, {\n            parseResponse: async (response) => await response.blob()\n        });\n    }\n\n    protected async _loadData() {\n        await this._parent._ensureLink(RelType.PRIMARY);\n        const assetInterface = await this._parent._getAssetInterface();\n        await assetInterface.getContent(this);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport {\n    getDateRangeRelation,\n    getMultiValueFilterRelation,\n    type IExplicitFilter,\n    type ItemFilterRelation\n} from '../core/ItemFilter';\nimport type AssetVersion from './AssetVersion';\n\nexport interface IAssetVersionFilterOptions {\n    readonly isMilestone?: boolean;\n    readonly createdAfter?: Date;\n    readonly createdBefore?: Date;\n    readonly createdBy?: string[];\n    readonly version?: string;\n}\n\nexport default class AssetVersionFilter implements IExplicitFilter<AssetVersion> {\n    private _isMilestone: boolean | undefined;\n    private _createdAfter: Date | undefined;\n    private _createdBefore: Date | undefined;\n    private _createdBy: string[] | undefined;\n    private _version: string | undefined;\n\n    constructor(options?: IAssetVersionFilterOptions) {\n        this._isMilestone = options?.isMilestone;\n        this._createdAfter = options?.createdAfter;\n        this._createdBefore = options?.createdBefore;\n        this._createdBy = options?.createdBy;\n        this._version = options?.version;\n    }\n\n    static BookmarkedVersions = new AssetVersionFilter({\n        isMilestone: true\n    });\n\n    static AssetVersionFilter(isMilestone?: boolean, createdAfter?: Date, createdBefore?: Date, createdBy?: string[], version?: string) {\n        return new AssetVersionFilter({\n            createdBy,\n            createdAfter,\n            createdBefore,\n            isMilestone,\n            version\n        });\n    }\n\n    get isMilestone(): boolean | undefined {\n        return this._isMilestone;\n    }\n\n    get createdBy(): string[] | undefined {\n        return this._createdBy;\n    }\n\n    get createdAfter(): Date | undefined {\n        return this._createdAfter;\n    }\n\n    get createdBefore(): Date | undefined {\n        return this._createdBefore;\n    }\n\n    get version(): string | undefined {\n        return this._version;\n    }\n\n    get hash(): string {\n        const collaborator = this.createdBy?.join(',');\n        const createdAfter =  this.createdAfter?.getTime() || 0;\n        const createdBefore =  this.createdBefore?.getTime() || 0;\n        const version = this.version || undefined;\n        return String(this.isMilestone) + ':'\n            + collaborator + ':'\n            + createdAfter + ':' + createdBefore + ':' + version;\n    }\n\n    matches(item: AssetVersion): boolean {\n        const matchesBookmark = this.isMilestone === undefined || this.isMilestone === Boolean(item.milestone);\n        const matchesCollab = this.createdBy === undefined || this.createdBy.includes(item.createdBy);\n        const matchesDateRange = (!this.createdAfter || item.created >= this.createdAfter) && (!this.createdBefore || item.created <= this.createdBefore);\n        const matchesVersion = this.version === undefined || this.version === item.versionId;\n        return matchesBookmark && matchesCollab && matchesDateRange && matchesVersion;\n    }\n\n    private _getRelationWrtMilestone(other: AssetVersionFilter): ItemFilterRelation {\n        return this.isMilestone === other.isMilestone ? 'subset' : this.isMilestone === undefined || other.isMilestone === undefined ? 'unknown' : 'disjoint';\n    }\n\n    private _getRelationWrtCreatedBy(other: AssetVersionFilter): ItemFilterRelation {\n        return getMultiValueFilterRelation(this._createdBy, other._createdBy);\n    }\n\n    private _getRelationWrtDateRange(other: AssetVersionFilter): ItemFilterRelation {\n        return getDateRangeRelation(this._createdAfter, this._createdBefore, other._createdAfter, other._createdBefore);\n    }\n\n    private _getRelationWrtVersion(other: AssetVersionFilter): ItemFilterRelation {\n        if (this.version === other.version) {\n            return 'subset';\n        }\n        if (this.version === undefined || other.version === undefined) {\n            return 'unknown';\n        }\n        return 'disjoint';\n    }\n\n    getRelationToFilter(other: AssetVersionFilter): ItemFilterRelation {\n        const relations = [\n            this._getRelationWrtMilestone(other),\n            this._getRelationWrtCreatedBy(other),\n            this._getRelationWrtDateRange(other),\n            this._getRelationWrtVersion(other)\n        ];\n        if (relations.includes('disjoint')) {\n            return 'disjoint';\n        }\n        if (relations.includes('unknown')) {\n            return 'unknown';\n        }\n        // only remaining possibility is 'subset'\n        return 'subset';\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter  } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport type { IImplicitAdobeAssetFilterBaseOptions } from './ImplicitAdobeAssetFilterBase';\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\n\nexport interface IImplicitDirectoryListingFilterOptions extends IImplicitAdobeAssetFilterBaseOptions {\n    readonly asset: AdobeAsset;\n}\n\nexport default class ImplicitDirectoryListingFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    private _asset: AdobeAsset;\n\n    constructor(options: IImplicitDirectoryListingFilterOptions) {\n        const { asset, ...superOptions } = options;\n        super(superOptions);\n        this._asset = asset;\n    }\n\n    get asset(): AdobeAsset {\n        return this._asset;\n    }\n\n    matches(item: AdobeAsset): boolean {\n        // Only check repositoryID if defined\n        // TODO: this was to fix a USS bug that doesn't exist anymore, should it always verify repositoryID?\n        if (this._asset.repositoryID && item.repositoryID\n            && this._asset.repositoryID !== item.repositoryID) {\n            return false;\n        }\n\n        // check item is a direct child of current asset\n        const assetRepoPath = this._asset.repoPath;\n        if (assetRepoPath && (assetRepoPath !== item.repoPath.substring(0, item.repoPath.lastIndexOf('/')))) {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { RepositoryMetadata } from '../interface/RepositoryModel';\nimport { RelType } from '../interface/LinkUtils';\n\nexport default function addProjectIdToMetadata(metadata: RepositoryMetadata, parentId: string) {\n    metadata._embedded ||= {};\n    metadata._embedded[RelType.APP_METADATA] ||= {};\n    metadata._embedded[RelType.APP_METADATA]!['cc:inherited'] ||= {};\n    metadata._embedded[RelType.APP_METADATA]!['cc:inherited']!['cc:team'] ||= {};\n    metadata._embedded[RelType.APP_METADATA]!['cc:inherited']!['cc:team']!['repo:assetId'] = parentId;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { RelType } from '../interface/LinkUtils';\nimport type AdobeAsset from './AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { RepositoryMetadata } from '../interface/RepositoryModel';\nimport AdobeAssetResource from './AdobeAssetResource';\n\nexport default class RepoMetadataResource extends AdobeAssetResource<RepositoryMetadata> {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        _parent?: AdobeAsset,\n    ) {\n        super(_core, _parent, {\n            onChange: async (repoMetadata) => {\n                if (repoMetadata) {\n                    try {\n                        const assetId = repoMetadata['repo:assetId'];\n                        const links = repoMetadata._links;\n                        const etag = repoMetadata['repo:etag'];\n                        // Update the persistent cache with the updated links (by ID, because paths change)\n                        const resolveHref = this._core.hostAssetContext._rapi.getAssetResolveByIdHref(assetId);\n                        await this._core._environment.cache.setItem(resolveHref, { links, etag });\n                    } catch (e) {\n                        // it is not a failure if we're unable to update the persistent cache\n                    }\n                }\n                await this._parent?._handleResourceUpdates({ repoMetadata });\n            },\n            onError: async (error) => {\n                await this._parent?._handleResourceUpdates({ error });\n            }\n        });\n    }\n\n    protected async _loadData() {\n        await this._parent?._ensureLink(RelType.REPO_METADATA);\n        const assetInterface = await this._parent?._getAssetInterface();\n        await assetInterface?.getRepoMetadata(this);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { RelType } from '../interface/LinkUtils';\nimport type AdobeAsset from './AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { Permission } from '../interface/AssetModel';\nimport { parseEffectivePermissions } from '../interface/AssetModel';\nimport AdobeAssetResource from './AdobeAssetResource';\n\nexport default class EffectivePermissionsResource extends AdobeAssetResource<Permission> {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        _parent?: AdobeAsset,\n    ) {\n        super(_core, _parent, {\n            parseResponse: async (response) => parseEffectivePermissions(await response.json()),\n            onChange: async (effectivePermission) => {\n                await this._parent?._handleResourceUpdates({ effectivePermission });\n            },\n            onError: async (error) => {\n                await this._parent?._handleResourceUpdates({ error });\n                this._error = undefined; // If we got this far, the error was a 404/403, which is not fatal for permissions.\n            }\n        });\n    }\n\n    protected async _loadData() {\n        await this._parent?._ensureLink(RelType.AC_EFFECTIVE);\n        const assetInterface = await this._parent?._getAssetInterface();\n        await assetInterface?.getEffectivePermissions(this);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport path from 'path-browserify';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport { type LocalAssetMetadata } from '../assets/AdobeAsset';\nimport { getACPLModel } from '../core/patches/SAMCpp';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\n\ninterface ILocalAssetChangeEvent {\n    type: 'add' | 'delete' | 'update';\n    localAsset: LocalAssetMetadata;\n}\n\n/**\n * ACPLModelInterface interface wraps window.acplModel, which is available on some desktop surfaces:\n * - CCD, via SAM.cpp\n * - UXP, via SAM.cpp (or polyfilled in webviews)\n */\nexport default class ACPLModelInterface implements ISAMObject {\n    constructor(readonly _core: ISAMCorePrivate) {}\n\n    acplModel = getACPLModel();\n\n    /**\n     * Get an AdobeAsset from a localID or cloudID, if ACPL contains information about that asset.\n     * On web, or if ACPL is not available, returns undefined.\n     */\n    async getLocalAsset(assetId: string): Promise<AdobeAsset | undefined> {\n        if (!this.acplModel) {\n            return undefined;\n        }\n\n        const localAssets = await this.getLocalAssets();\n        const localAsset = localAssets.find(asset => asset['repo:assetId'] === assetId || asset.localID === assetId);\n        if (localAsset) {\n            const session = this._core._getAssetPool().createUpdateSession();\n            const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ localAsset ]);\n            const asset = this._core._adobeAssetFactory.assetFromLocalMetadata(session, localAsset, updaters);\n            session.commit();\n            return asset;\n        }\n    }\n\n    /**\n     * ACPL may return local assets with a repoID of '~' if the asset is in the user's root folder.\n     * This method expands the repository path to include the home folder's repoPath and repositoryID.\n     * This is necessary to ensure that the asset can be correctly identified and merged with SAM.js models.\n     */\n    private _expandRepositoryPath(homeFolder: AdobeAsset, localAsset: LocalAssetMetadata) {\n        if (localAsset['repo:repositoryId'] === '~' && localAsset['repo:path']) {\n            localAsset['repo:repositoryId'] = homeFolder.repositoryID;\n            localAsset['repo:path'] = path.join(homeFolder.repoPath, localAsset['repo:path']);\n        }\n        return localAsset;\n    }\n\n    // When updating local assets, particularly newly-created assets, we may receive change notifications\n    // before we have a cloudID available (during the sync process). To make sure we match the local asset\n    // with the ONS-updated cloud asset without duplicates, we use repoPath. Here's a typical scenario:\n    //\n    // 1. A new file is created. ACPL emits uploadStatus changes, but we don't have a cloudID yet.\n    //    - UpdateSession stores the item with the alternateID (\"repo:path\").\n    // 2. ONS sends updates for a new cloud asset with cloudID and repoPath.\n    //    - It doesn't find an existing cloudID, so it finds the right item with repoPath as the alternateID.\n    //    - UpdateSession reindexes the item, whose ID is now its cloudID.\n    // 3. More sync events from ACPL, where we still might not have a cloudID, so we still search for repoPath.\n    //    - Eventually, everyone has a reference to the cloudID, and we no longer need the path.\n    subscribeToLocalAssetChanges() {\n        this.acplModel?.on('localAssetChange', async (eventData: string) => {\n            const { type, localAsset } = JSON.parse(eventData) as ILocalAssetChangeEvent;\n            if (!localAsset) {\n                return;\n            }\n            const homeFolder = await this._core.getAssetContext().then(context => context.getHomeFolder());\n            this._expandRepositoryPath(homeFolder, localAsset);\n\n            const pool = this._core._getAssetPool();\n            const assetId = localAsset['repo:assetId'];\n            const session = pool.createUpdateSession();\n            if (type === 'delete') {\n                // Find an existing asset by assetId, if available. However, local assets may not have a cloudID yet,\n                // so we must take care to find a matching service-populated asset if one exists (by repoPath).\n                const asset = (assetId ? session.getItemById(assetId) : undefined)\n                    || session.findItem(item => item.repoPath === localAsset['repo:path']);\n                if (asset) {\n                    session.queueDiscardedItem(asset);\n                }\n            } else if (type === 'add' || type === 'update') {\n                const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ localAsset ]);\n                this._core._adobeAssetFactory.assetFromLocalMetadata(session, localAsset, updaters);\n            }\n            session.commit();\n        });\n    }\n\n    get supportsDownloadComposite(): boolean {\n        return this.acplModel?.downloadComposite !== undefined;\n    }\n\n    get supportsUnpin(): boolean {\n        return this.acplModel?.unpin !== undefined;\n    }\n\n    get supportsLocalAssets(): boolean {\n        return this.acplModel?.getLocalAssets !== undefined;\n    }\n\n    async downloadComposite(cloudID: string): Promise<void> {\n        return this.acplModel?.downloadComposite?.(cloudID);\n    }\n\n    async unpin(cloudID: string): Promise<void> {\n        return this.acplModel?.unpin?.(cloudID);\n    }\n\n    /**\n     * Return a list of local assets populated from ACPL.\n     * On web, or if ACPL is not available, returns an empty array.\n     *\n     * This method also ensures that assets have a\n     * repositoryPath that can be merged with SAM.js models.\n     */\n    async getLocalAssets(): Promise<LocalAssetMetadata[]> {\n        if (!this.acplModel) {\n            return [];\n        }\n        const [ homeFolder, rawAssets = [] ] = await Promise.all([\n            this._core.getAssetContext().then(context => context.getHomeFolder()),\n            this.acplModel?.getLocalAssets?.()\n        ]);\n        return rawAssets.map(asset => this._expandRepositoryPath(homeFolder, asset));\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n\nimport type AdobeAsset from './AdobeAsset';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type AdobeAssetFilter from './AdobeAssetFilter';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { IItemSourceConfig } from '../core/ItemList';\nimport ACPLModelInterface from '../interface/ACPLModelInterface';\nimport KeepAliveManager from '../core/decorators/KeepAliveManager';\n\nexport default class LocalAssetLoader<ItemConfig extends IItemSourceConfig> implements IItemLoader<ItemConfig> {\n\n    constructor(\n        private _assetPool: ItemPool<AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private acplModelInterface = new ACPLModelInterface(_core)\n    ) {\n    }\n\n    supportsFilter(filter?: AdobeAssetFilter): boolean {\n        return filter !== undefined;\n    }\n\n    async loadPage(_options: IItemLoaderOptions<ItemConfig>): Promise<ILoadedPage<ItemConfig>> {\n        const cachedAssets = await this.acplModelInterface.getLocalAssets();\n\n        const mostRecentValidMutation = Date.now();\n        const session = this._assetPool.createLoaderUpdateSession(mostRecentValidMutation);\n        const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters(cachedAssets);\n        const items = this._core._adobeAssetFactory.assetsFromLocalMetadata(session, cachedAssets, updaters);\n        session.commit();\n\n        // Assets with only local data may be filtered out of active lists (e.g. a lack of repoPath in directory filters).\n        // This puts them at risk of being garbage-collected before sibling loaders have a chance to fill out those models\n        // with remote data. To prevent this, we keep a reference to them in memory, which persists until we reload the list.\n        items.map(item => KeepAliveManager.getInstance().add(item));\n\n        return {\n            items\n        };\n    }\n}\n\n\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { MelvilleLinks } from './LibraryModel';\nimport type { RelType } from './LinkUtils';\nimport { SAM } from '@ccx-public/component-types';\n\nexport const FIREFLY_GENERATIONS_DIRECTORY = 'appassets/firefly-generations';\n\nexport const GENERATION_HISTORY_IMAGE_MEDIA_TYPE = 'application/vnd.adobe.firefly-generation-image+dcx';\nexport const GENERATION_HISTORY_VIDEO_MEDIA_TYPE = 'application/vnd.adobe.firefly-generation-video+dcx';\nexport const GENERATION_HISTORY_AUDIO_MEDIA_TYPE = 'application/vnd.adobe.firefly-generation-audio+dcx';\nexport const GENERATION_HISTORY_VECTOR_MEDIA_TYPE = 'application/vnd.adobe.firefly-generation-vector+dcx';\nexport const GENERATION_HISTORY_MEDIA_TYPES = [ GENERATION_HISTORY_IMAGE_MEDIA_TYPE, GENERATION_HISTORY_VIDEO_MEDIA_TYPE, GENERATION_HISTORY_AUDIO_MEDIA_TYPE, GENERATION_HISTORY_VECTOR_MEDIA_TYPE ];\n\nexport const MEDIA_TO_HISTORY_ASSET_TYPE: Record<string, SAM.GenerationHistoryAssetType> = {\n    'application/vnd.adobe.firefly-generation-image+dcx': SAM.GenerationHistoryAssetType.IMAGE,\n    'application/vnd.adobe.firefly-generation-video+dcx': SAM.GenerationHistoryAssetType.VIDEO,\n    'application/vnd.adobe.firefly-generation-audio+dcx': SAM.GenerationHistoryAssetType.AUDIO,\n    'application/vnd.adobe.firefly-generation-vector+dcx': SAM.GenerationHistoryAssetType.VECTOR\n} as const;\n\nexport const HISTORY_ASSET_TYPE_TO_MEDIA_TYPE: Record<SAM.GenerationHistoryAssetType, string> = {\n    [SAM.GenerationHistoryAssetType.IMAGE]: GENERATION_HISTORY_IMAGE_MEDIA_TYPE,\n    [SAM.GenerationHistoryAssetType.VIDEO]: GENERATION_HISTORY_VIDEO_MEDIA_TYPE,\n    [SAM.GenerationHistoryAssetType.AUDIO]: GENERATION_HISTORY_AUDIO_MEDIA_TYPE,\n    [SAM.GenerationHistoryAssetType.VECTOR]: GENERATION_HISTORY_VECTOR_MEDIA_TYPE\n} as const;\n\nexport type GenerationHistoryAssetStatusLinks = {\n    [RelType.MELVILLE_FIREFLY_GENERATION_CANCEL]: string;\n    [RelType.MELVILLE_FIREFLY_GENERATION_RESULT]?: string;\n}\n\ntype MelvilleOrderBy = 'created_date' | '-created_date';\n\nexport type MelvilleGenerationHistoryAssetsParams = {\n    generationGroupId?: string;\n    generationType?: string;\n    start?: number;\n    limit?: number;\n    orderBy?: MelvilleOrderBy;\n}\n\n// TODO: PR in progress to introspect types from graphql server, when that is merged we won't need the below typedef\ntype AssetLabel = {\n    isFavorite: boolean;\n}\n\nexport type MelvilleGenerationHistoryAssetInfo = {\n    type: (typeof GENERATION_HISTORY_MEDIA_TYPES)[number];\n    'repo:createdBy': string;\n    'repo:modifiedBy': string;\n    'repo:name': string;\n    'repo:size': number;\n    'repo:repositoryId': string;\n    asset_id: string;\n    createdDate: string;\n    modifiedDate: string;\n    composite_manifest_etag: string;\n    asset_name_path: string;\n    generationModelDisplayName: string;\n    _links: MelvilleLinks;\n    applicationMetadata: {\n        firefly: {\n            module: string;\n            prompt?: string;\n            generationGroupId?: string;\n            generationModel?: {\n                name: string;\n                customModelId?: string;\n                version: string;\n                detailLevel?: 'preview' | 'full';\n                apiPath?: string;\n            }\n            outputComponents: Array<{\n                type: string;\n                componentId: string;\n                revision: string;\n                length: number;\n                seed: number;\n            }>\n            status: {\n                errorCode?: string;\n                errorMessage?: string;\n                jobId?: string;\n                progress?: number;\n                state: SAM.GenerationHistoryAssetState;\n                links?: GenerationHistoryAssetStatusLinks;\n            }\n        }\n    }\n}\n\nexport type GenerationHistoryAssetData = AssetLabel & MelvilleGenerationHistoryAssetInfo;\n\nexport type GenerationHistoryAssetAppMetadata = GenerationHistoryAssetData['applicationMetadata'] | undefined;\n\nexport type MelvilleGenerationHistoryAssetsResponse = {\n    total_count: number;\n    listings: GenerationHistoryAssetData[];\n    _links: any\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { SAM } from '@ccx-public/component-types';\nimport type { GenerationHistoryAssetAppMetadata, GenerationHistoryAssetData } from '../interface/GenerationHistoryAssetModel';\nimport { GENERATION_HISTORY_MEDIA_TYPES, MEDIA_TO_HISTORY_ASSET_TYPE } from '../interface/GenerationHistoryAssetModel';\nimport type AdobeAssetImplementation from '../assets/AdobeAsset';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport { DEFAULT_MAX_SINGLE_TRANSFER_SIZE } from '../assets/AdobeAsset';\nimport { RelType, getURLFromLinks } from '../interface/LinkUtils';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { getBlockTransferThreshold } from '@sam-js-src/interface/AssetInterface';\n\nexport type ComponentURL = {\n    url: string;\n    isBlockDownload: boolean;\n    componentId: string;\n    rel?: 'primary' | 'auxiliary';\n    name?: string;\n}\n\nexport const isGenerationHistoryAsset = (asset: SAM.AdobeAsset): boolean => {\n    return GENERATION_HISTORY_MEDIA_TYPES.includes(asset.mediaType);\n};\n\nexport const getHistoryAssetType = (asset: SAM.AdobeAsset): SAM.GenerationHistoryAssetType | undefined => {\n    return MEDIA_TO_HISTORY_ASSET_TYPE[asset.mediaType];\n};\n\nexport const makeComponentURL = async (componentData: { id: string, revision: string, length: number }, inputAsset: SAM.AdobeAsset, forceBlockDownload?: boolean) => {\n    const asset = inputAsset as AdobeAssetImplementation;\n    await asset._ensureLink(RelType.COMPONENT);\n\n    if (componentData.length < getBlockTransferThreshold(asset.links, DEFAULT_MAX_SINGLE_TRANSFER_SIZE) && !forceBlockDownload) {\n        return {\n            url: getURLFromLinks(asset.links, RelType.COMPONENT, { 'component_id': componentData.id, 'revision': componentData.revision }),\n            isBlockDownload: false,\n            componentId: componentData.id\n        };\n    }\n\n    // Return block download URL for assets > BlockTransferThreshold, OR when client has requested to force a block download URL (this allow us to\n    // return a presigned URL for assets < BlockTransferThreshold).\n    await asset._ensureLink(RelType.DOWNLOAD);\n    const downloadURL = getURLFromLinks(asset.links, RelType.DOWNLOAD, { resource: JSON.stringify({ 'component_id': componentData.id, 'revision': componentData.revision, reltype: RelType.COMPONENT }) });\n    const assetInterface = await asset._getAssetInterface();\n    return {\n        url: await assetInterface.getBlockDownloadURL(downloadURL),\n        isBlockDownload: true,\n        componentId: componentData.id\n    };\n};\n\nexport const getGenerationModelDisplayName = (inputAsset: SAM.AdobeAsset): string | undefined => {\n    const asset = inputAsset as AdobeAssetImplementation;\n    return asset._getGenerationModelDisplayName();\n};\n\n/******************** from app metadata *******************/\n\nexport const getGenerationGroupId = (asset: SAM.AdobeAsset): string | undefined => {\n    return asset.appMetadata.data?.firefly?.generationGroupId;\n};\n\nexport const getPrompt = (asset: SAM.AdobeAsset): string | undefined => {\n    return asset.appMetadata.data?.firefly?.prompt;\n};\n\n/**\n * Name of the firefly module used to create the history asset.\n */\nexport const getModule = (asset: SAM.AdobeAsset): string | undefined => {\n    return asset.appMetadata.data?.firefly?.module;\n};\n\nexport const isUpscaled = (asset: SAM.AdobeAsset): boolean | undefined => {\n    const { detailLevel } = asset.appMetadata.data?.firefly?.generationModel ?? {};\n    if (!detailLevel) { return; }\n    return detailLevel === 'full';\n};\n\nexport const getCancelUrl = (asset: SAM.AdobeAsset): string | undefined => {\n    return asset.appMetadata.data?.firefly?.status?.links?.[RelType.MELVILLE_FIREFLY_GENERATION_CANCEL];\n};\n\nexport const getResultUrl = (asset: SAM.AdobeAsset): string | undefined => {\n    return asset.appMetadata.data?.firefly?.status?.links?.[RelType.MELVILLE_FIREFLY_GENERATION_RESULT];\n};\n\nexport const getGenerationState = (asset: SAM.AdobeAsset): SAM.GenerationHistoryAssetState | undefined => {\n    return asset.appMetadata.data?.firefly?.status?.state;\n};\n\nexport const getSeedInfo = (asset:  SAM.AdobeAsset): string | undefined => {\n    if (asset.appMetadata.data?.firefly && !asset.appMetadata.data?.firefly?.outputComponents) {\n        // provides a hint for anyone seeing errors for assets created before 2/3 as this data was not being populated\n        // before then, and if this data is missing it will break the interface\n        throw SAMError.create(SAMErrorCode.NOT_FOUND, `Resource for history asset ${asset.id} not found in app-metadata, asset is corrupt.`);\n    }\n\n    return asset.appMetadata.data?.firefly?.outputComponents[0]?.seed;\n};\n\nexport const getGenerationModel = async (asset:  SAM.AdobeAsset) => {\n    return (asset.appMetadata.data as GenerationHistoryAssetData['applicationMetadata'])?.firefly?.generationModel;\n};\n\nexport const getCustomModelId = (asset: SAM.AdobeAsset): string | undefined => {\n    return asset.appMetadata.data?.firefly?.generationModel?.customModelId;\n};\n\nexport const getOutputComponentURLs = async (asset: SAM.AdobeAsset, forceBlockDownload?: boolean): Promise<Record<string, ComponentURL>> => {\n    // TODO: changing this to rely on the presence of firefly app metadata instead of isLoaded, as loading from the platform\n    // doesn't seem to trigger `isLoaded = true` since it uses _mergeData instead of _setData\n    if (!asset.appMetadata.data?.firefly) {\n        return {};\n    }\n\n    const { outputComponents } = (asset.appMetadata.data as GenerationHistoryAssetAppMetadata)?.firefly || {};\n\n    if (!outputComponents) {\n        // provides a hint for anyone seeing errors for assets created before 2/3 as this data was not being populated\n        // before then, and if this data is missing it will break the interface\n        throw SAMError.create(SAMErrorCode.NOT_FOUND, `Resource for history asset ${asset.id} not found in app-metadata, asset is corrupt.`);\n    }\n\n    const componentPromises = outputComponents.map(async (outputComponent: any) => {\n        const componentURL = await makeComponentURL({ ...outputComponent, id: outputComponent.componentId }, asset, forceBlockDownload);\n        return [\n            outputComponent.componentId,\n            {\n                ...componentURL,\n                rel: outputComponent.rel,\n                name: outputComponent.name\n            }\n        ] as const;\n    });\n\n    return Object.fromEntries(await Promise.all(componentPromises));\n};\n\nexport const getOutputComponentDownloadURLs = async (inputAsset: SAM.AdobeAsset, forceBlockDownload?: boolean): Promise<string[] | undefined> => {\n    const asset = inputAsset as AdobeAssetImplementation;\n    const outputComponentURLs = await getOutputComponentURLs(asset, forceBlockDownload);\n\n    if (!outputComponentURLs) {\n        return;\n    }\n\n    const generationHistoryInterface = asset._getGenerationHistoryInterface();\n\n    return generationHistoryInterface.getOutputComponentDownloadURLs(outputComponentURLs);\n};\n\nexport const getOutputComponentURL = (asset: SAM.AdobeAsset, forceBlockDownload?: boolean) => {\n    // TODO: changing this to rely on the presence of firefly app metadata instead of isLoaded, as loading from the platform\n    // doesn't seem to trigger `isLoaded = true` since it uses _mergeData instead of _setData\n    if (!asset.appMetadata.data?.firefly) {\n        return;\n    }\n\n    const { outputComponents } = (asset.appMetadata.data as GenerationHistoryAssetAppMetadata)?.firefly || {};\n\n    if (!outputComponents) {\n        // provides a hint for anyone seeing errors for assets created before 2/3 as this data was not being populated\n        // before then, and if this data is missing it will break the interface\n        throw SAMError.create(SAMErrorCode.NOT_FOUND, `Resource for history asset ${asset.id} not found in app-metadata, asset is corrupt.`);\n    }\n\n    // There is only one output component for history assets for now\n    // If this changes in the future we can update the return type to be Promise<Record<string, ComponentURL>>\n    // to match getInputComponentURLs. We shouldn't do this now because app metadata does not contain the component name\n    // which is what we'd want to use as a key for the response object\n    const outputComponent = outputComponents[0];\n\n    if (!outputComponent) {\n        return;\n    }\n\n    // In the manifest the component id's key name is \"id\", but it is componentId in appMetadata to align with spec\n    // schema definitions\n    return makeComponentURL({ ...outputComponent, id: outputComponent.componentId }, asset, forceBlockDownload);\n};\n\n/**\n * @deprecated - use getOutputComponentDownloadURLs instead\n * Returns the download URL for the output component of a generation history asset.\n * @param inputAsset - The generation history asset to get the output component download URL for.\n * @param forceBlockDownload - Whether to force a block download URL for the output component.\n * @returns The download URL for the output component of the generation history asset.\n */\nexport const getOutputComponentDownloadURL = async (inputAsset: SAM.AdobeAsset, forceBlockDownload?: boolean) => {\n    const asset = inputAsset as AdobeAssetImplementation;\n    const outputComponentURL = await getOutputComponentURL(asset, forceBlockDownload);\n\n    if (!outputComponentURL) {\n        return;\n    }\n\n    const generationHistoryInterface = asset._getGenerationHistoryInterface();\n\n    return generationHistoryInterface.getOutputComponentDownloadURL(outputComponentURL);\n};\n\n/******************** from manifest *************************/\n\n/**\n * Given a manifest, return the input component data.\n */\nconst getInputComponent = async (asset: SAM.AdobeAsset) => {\n    await (asset as AdobeAsset)._ensureLink(RelType.MANIFEST);\n\n    if (!asset.manifest.isLoaded) {\n        await asset.manifest.load();\n    }\n\n    return asset.manifest.data?.children?.find((c: any) => c.path === 'input');\n};\n\n/**\n * Returns the creation payload object FF used to generate this asset, can be found in inputComponent.request\n */\nexport const getGenerationInput = async (asset: SAM.AdobeAsset) => {\n    const inputComponent = await getInputComponent(asset);\n\n    // NOTE: this is intentionally left typed as any as we have no control/contract over the shape of this object\n    // also the consumers (firefly) of this API are also the ones who create/manage the shape of it, this is just an\n    // API to give it back to them for UI reconstruction purposes\n    return inputComponent.request;\n};\n\nexport const getInputComponentURLs = async (asset: SAM.AdobeAsset): Promise<Record<string, ComponentURL>> => {\n    const inputComponent = await getInputComponent(asset);\n    const response: Record<string, ComponentURL> = {};\n\n    if (inputComponent.components) {\n        for (const componentData of inputComponent.components as Array<{ id: string, version: string, name: string, length: number }>) {\n            response[componentData.name] = await makeComponentURL({ ...componentData, revision: componentData.version }, asset);\n        }\n    }\n\n    return response;\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Melville APIs for reading/writing Libraries data.\n * Warning: The libraries listings for non-public libraries returned from GET /libraries, and results for /search, may have stale data due to USS indexing delays.\n * However, Melville will always return the latest data from platform when fetching a specific library from GET /library/:id.\n */\n\nimport InterfaceBase from './InterfaceBase';\nimport { JSON_MIME_TYPE } from './LinkUtils';\nimport type { HeaderMap } from './LinkUtils';\nimport { fillURLTemplate } from './LinkUtils';\nimport type {\n    AccessOption,\n    BookmarkData,\n    BookmarksResponse,\n    CopyLibraryRequest,\n    CreateLibraryOptions,\n    LibraryData,\n    MoveLibraryRequest,\n    LibrariesResponse,\n    LibraryListParameters,\n    MelvilleLink,\n    UpdateLibraryMetadataPayload,\n    SearchLibraryRequest,\n    LibrarySelectors\n} from './LibraryModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type RenditionTileResource from '@sam-js-src/assets/RenditionTileResource';\ninterface IMelvilleRestoreContextQuery {\n    'self': {\n        'id': string;\n        'elements': string[];\n    }\n}\n\nfunction parseLibraryAndElementID(libraryElementID: string): string[] {\n    const parts = libraryElementID.split(':');\n    const elementID = parts.pop() as string;\n    const libraryID = parts.join(':');\n    return [ elementID, libraryID ];\n}\n\nfunction getLibraryAccessOption(restrictEdit?: boolean): AccessOption | '' {\n    if (restrictEdit === true) {\n        return 'team_view';\n    } else if (restrictEdit === false) {\n        return 'team_edit';\n    } else {\n        return '';\n    }\n}\n\n/**\n * Given a libraries or elements listing URL, move the supported query params to headers.\n * This avoids extra CORS preflight OPTIONS requests per unique url.\n * @param melvilleUrl - supports both full url and path only, with query params\n * @returns tuple of [path, headers], with the path truncated of the query params that were moved to headers\n */\nexport function moveUrlQueryParamsToHeaders(melvilleUrl: string): [string, HeaderMap] {\n    // The below query params are supported as headers\n    // Note: 'owner' is supported by libraries list, and 'type' and 'group' is supported for elements list\n    const MelvilleParamsAsHeaders = [ 'start', 'limit', 'selector', 'type', 'orderBy', 'group', 'owner' ];\n\n    const [ path, query ] = melvilleUrl.split('?');\n    const urlParams = new URLSearchParams(query); // create obj from query and encode params if they aren't already\n    const headers: HeaderMap = {};\n\n    MelvilleParamsAsHeaders.forEach(paramAsHeader => {\n        const value = urlParams.get(paramAsHeader);\n        if (value) {\n            headers[paramAsHeader] = value;\n            urlParams.delete(paramAsHeader);\n        }\n    });\n    const urlParamsString = `${urlParams}`;\n    const url = urlParamsString.length > 0 ? `${path}?${urlParamsString}` : path;\n\n    return [ url, headers ];\n}\n\n// Sort parameters so that the query string is stable, preventing unnecessary cache misses.\nconst sortParameters = (parameters: LibraryListParameters): LibraryListParameters => {\n    return Object.fromEntries(\n        Object.entries(parameters)\n            .map(([ key, value ]) => {\n                if (Array.isArray(value)) {\n                    return [ key, value.sort() ];\n                }\n                return [ key, value ];\n            })\n            .sort()\n    );\n};\n\nexport default class LibraryInterface extends InterfaceBase {\n\n    private _getUrl(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.MELVILLE_HOST}${endpoint}`;\n    }\n\n    private _getEdgeUrl(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.MELVILLE_EDGE_HOST}${endpoint}`;\n    }\n\n    async getLibraryData(libraryId: string, options?: { selectors?: LibrarySelectors[], isDiscarded?: boolean}): Promise<LibraryData> {\n        const selectors = options?.selectors ? options.selectors : [];\n        const isDiscarded = options?.isDiscarded || false;\n\n        // dedupes, sorts, and ensures selectors contains rendition grid\n        const sortedSelectors = Array.from(new Set([ 'rendition_grid', 'collaboration', ...selectors ])).sort().join(',');\n        const url = isDiscarded ? this._getUrl(`/api/v1/archive/${libraryId}`) : this._getEdgeUrl(`/api/v1/libraries/${libraryId}`);\n\n        return await this._getResponse(\n            // Sort selectors so that the query string is stable, preventing unnecessary cache misses.\n            `${url}?selector=${sortedSelectors}`,\n            {\n                // Ensure browser doesn't automatically add If-None-Match, otherwise\n                // service may respond with cached data for a library\n                headers: { ['Cache-Control']: 'no-cache, no-store, max-age=0' }\n            }\n        );\n    }\n\n    // Warning: the libraries listing returned from /libraries may have stale data due to USS indexing delays.\n    // The exception to this is public libraries as those are fetched from platform, for now.\n    // (Other calls, such as fetching library data by ID, will always return the latest data from platform.)\n    // Update only LibrarySpecificData to avoid overwriting RAPI data if you are worried about this.\n    async getLibraries(queryParams: LibraryListParameters): Promise<LibrariesResponse> {\n        if (queryParams?.limit && queryParams?.start === undefined) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, '[Melville] If limit is provided, start must also be provided.');\n        }\n        queryParams = sortParameters(queryParams);\n        const urlWithQueryParams = fillURLTemplate(\n            this._getEdgeUrl('/api/v1/libraries'),\n            queryParams\n        );\n        // Pass as many parameters as headers as we can, to avoid extra CORS preflight OPTIONS requests per url.\n        const [ url, headers ] = moveUrlQueryParamsToHeaders(urlWithQueryParams);\n        // Ensure browser doesn't automatically add If-None-Match, otherwise\n        // service may respond with cached data for a library\n        const defaultHeaders: HeaderMap = {\n            ['Cache-Control']: 'no-cache, no-store, max-age=0',\n            // 'public-libraries-list-v2' is Melville's feature flag for durable links.\n            // The main change for SAM.js is that a public library's ID will be the\n            // manifest ID (UUID) instead of the legacy public library ID. This ID is\n            // mapped to `_legacyLibraryId` in the SAM.js' Library asset.\n            directive: 'public-libraries-list-v2'\n        };\n        const finalHeaders = { ...defaultHeaders, ...headers };\n\n        return await this._getResponse(url, { headers: finalHeaders });\n    }\n\n    // TODO[SHARED-975]: This will need to return the json response for pagination.\n    async getLibrariesForProject(projectId: string): Promise<LibraryData[]> {\n        const response = await this.getLibraries({ team: projectId, selector: 'rendition_grid,collaboration,details' });\n        return response.libraries;\n    }\n\n    async getLibrariesWithLink(pageLink: MelvilleLink): Promise<LibrariesResponse> {\n        // The link will not include headers, so we will need switch query params to headers to reduce OPTIONS requests.\n        const [ url, headers ] = moveUrlQueryParamsToHeaders(this._getEdgeUrl(pageLink.href));\n        return await this._getResponse(url, { headers });\n    }\n\n    // The assetId's passed to restoreLibraryElement() and permanentlyDeleteLibraryElement() are in the\n    // form 'LIBRARY_CLOUD_ID:ELEMENT_GUID', i.e:\n    // 'urn:aaid:sc:us:2be71fea-f24b-4c10-a6a9-4f0926bda772:0fad1009-3bc1-4119-9227-5d1889ffcaf2'\n    // I filed https://jira.corp.adobe.com/browse/SAM-2683 to support batch restore/permanentDelete operations which in\n    // this workflow would allow us to make just one request to restore/permanentlyDelete multiple CCLibrary Elements that\n    // belong to the same CCLibrary.\n\n    async restoreLibraryElement(assetId: string): Promise<void> {\n        const [ elementID, libraryID ] = parseLibraryAndElementID(assetId);\n        const body: IMelvilleRestoreContextQuery = { self: { id: libraryID.toString(), elements: [ elementID ] } };\n        await this._doPost(\n            this._getEdgeUrl(`/api/v1/libraries/${libraryID}/archive`),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(body),\n            [ 200 ]);\n    }\n\n    async permanentlyDeleteLibraryElement(assetId: string): Promise<void> {\n        const [ elementID, libraryID ] = parseLibraryAndElementID(assetId);\n        await this._doDelete(\n            this._getEdgeUrl(`/api/v1/libraries/${libraryID}/archive/${elementID}`),\n            { 'Content-Type': 'application/json' },\n            [ 204 ]);\n    }\n\n    async discardLibrary(assetId: string): Promise<void> {\n        await this._doDelete(\n            this._getEdgeUrl(`/api/v1/libraries/${assetId}`),\n            { 'Content-Type': 'application/json' },\n            [ 204 ]);\n    }\n\n    async permanentlyDeleteLibrary(assetId: string): Promise<void> {\n        await this._doDelete(\n            this._getEdgeUrl(`/api/v1/libraries/${assetId}?permanent=true`),\n            { 'Content-Type': 'application/json' },\n            [ 204 ]);\n    }\n\n    async restoreLibrary(assetId: string): Promise<void> {\n        const body: any = { self: `/api/v1/archive/${assetId}` };\n        await this._doPost(\n            this._getEdgeUrl(`/api/v1/libraries`),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(body),\n            [ 201 ]);\n    }\n\n    async copyLibrary(assetId: string, destName?: string, parentAssetID?: string, restrictEdit?: boolean): Promise<LibraryData> {\n        const accessString = getLibraryAccessOption(restrictEdit);\n        const body: CopyLibraryRequest = {\n            source: assetId,\n            // unspecified optionals are omitted from the request body\n            ...(destName && { name: destName }),\n            ...(accessString && { access: accessString }),\n            ...(parentAssetID && { parent_assetId: parentAssetID })\n        };\n\n        const response = await this._doPost(\n            this._getEdgeUrl(`/api/v1/libraries`),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(body),\n            [ 200, 201 ]);\n\n        return await response.json();\n    }\n\n    async moveLibrary(assetId: string, parentAssetID: string, restrictEdit?: boolean): Promise<LibraryData> {\n        const accessString = getLibraryAccessOption(restrictEdit);\n        const body: MoveLibraryRequest = {\n            self: assetId,\n            parent_assetId: parentAssetID,\n            'repo:manifestPatch': [ { 'op': 'replace', 'path': '/id', 'value': assetId } ]\n        };\n        if (accessString !== '') {\n            body['access'] = accessString;\n        }\n\n        const headers: HeaderMap = {\n            'Content-type': 'application/json'\n        };\n\n        // If the client has not set the 'enable-x-bucket-move' feature flag to 'true', add the disable-x-bucket-move\n        // header to the request to ensure that cross bucket moves are disabled in Melville.\n        // Cross-bucket moves occur when the storage-assignee of the source and destination are different.\n        const featureFlags = this._core._environment.getValue('FEATURE_FLAGS');\n        if (!featureFlags?.['enable-x-bucket-move']) {\n            headers['disable-x-bucket-move'] = 'true';\n        }\n\n        const response = await  this._doPost(\n            this._getEdgeUrl(`/api/v1/libraries`),\n            headers,\n            JSON.stringify(body),\n            [ 200, 201 ]);\n\n        return await response.json();\n    }\n\n    /**\n     *\n     * @param nameOrOptions - For backward compatability, this can be a string representing the name of the library to create.\n     *                      If an object is passed, it should be a CreateLibraryOptions object.\n     * @returns LibraryData - The created library data from the response. This will include the ID of the created library.\n     */\n    async createLibrary(nameOrOptions: string | CreateLibraryOptions): Promise<LibraryData> {\n        let options: CreateLibraryOptions;\n        let url: string = `/api/v1/libraries`;\n\n        if (typeof nameOrOptions === 'string') {\n            options = { name: nameOrOptions };\n        } else if (typeof nameOrOptions === 'object') {\n            options = nameOrOptions;\n            url = options.syncCreate ? `/api/v1/libraries?invocation_mode=sync` : `/api/v1/libraries`;\n        } else {\n            throw new Error('Invalid arguments');\n        }\n\n        /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n        const { syncCreate, ...requestOptions } = options;\n        const response = await this._doPost(\n            this._getEdgeUrl(url),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(requestOptions),\n            [ 201, 200 ]);\n\n        return await response.json();\n    }\n\n    /**\n     * Follow aka bookmark one or more libraries.\n     * @param bookmarks - array of BookmarkData objects\n     * Required properties: In each bookmark, besides the id, you must include either urn for collaborated libraries or url for public libraries.\n     * @returns BookmarksResponse - contains all the bookmarks for the user of the same type(s) that were created (public or collab or both)\n     */\n    async bookmarkLibraries(bookmarks: Partial<BookmarkData>[]): Promise<BookmarksResponse> {\n        bookmarks = bookmarks.map(bookmark => {\n            if (!bookmark.id || (!bookmark.urn && !bookmark.url) || (bookmark.type === 'collab' && !bookmark.urn) || (bookmark.type === 'public' && !bookmark.url)) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, '[Melville] BookmarkData must include `id` and either `urn` for collaborated libraries or `url` for public libraries.');\n            }\n\n            bookmark.type = bookmark.type || (bookmark.url ? 'public' : 'collab');\n            return bookmark;\n        });\n\n        const body = { bookmarks };\n\n        // Will return 201 even if the library is already bookmarked\n        const response = await this._doPost(\n            this._getEdgeUrl(`/api/v1/libraries/bookmarks`),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(body),\n            [ 200, 201 ]\n        );\n\n        return await response.json();\n    }\n\n    /**\n     * Get all bookmarks for the user from Melville.\n     */\n    async getBookmarks(): Promise<BookmarkData[]> {\n        const response = await this._getResponse<any>(\n            this._getEdgeUrl(`/api/v1/libraries/bookmarks?useCache=false&ussCache=false`),\n            { headers: { 'Content-Type': JSON_MIME_TYPE, 'Cache-Control': 'no-cache, no-store, max-age=0' } });\n\n        return await response.bookmarks;\n    }\n\n\n    /**\n     * Unfollow aka unbookmark the library. (User can always bookmark again as long as they maintain access.)\n     */\n    async unbookmarkLibrary(bookmarkId: BookmarkData['id']): Promise<void> {\n        await this._doDelete(\n            this._getEdgeUrl(`/api/v1/libraries/bookmarks/${bookmarkId}`),\n            { 'Content-Type': 'application/json' },\n            [ 204 ]);\n    }\n\n    /**\n     * Set metadata on a library - eg setting roles, renaming, etc.\n     */\n    async updateMetadata(libraryId: string, body: Partial<UpdateLibraryMetadataPayload>) {\n        await this._doPut(\n            this._getEdgeUrl(`/api/v1/libraries/${libraryId}/metadata`),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(body),\n            [ 204, 200 ]);\n    }\n\n    /**\n     * Search for Libraries (excluding elements).\n     */\n    async searchLibraries(searchQuery: string): Promise<LibrariesResponse> {\n        const body: SearchLibraryRequest = {\n            query_string: searchQuery,\n            asset_type: [ 'library' ],\n            selector: 'rendition_grid,collaboration,details'\n        };\n        const response = await this._doPost(\n            this._getEdgeUrl(`/api/v1/libraries/search`),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(body),\n            [ 200 ]);\n\n        return await response.json();\n    }\n\n    /**\n     * Search for next page of Libraries using the page link (excluding elements).\n     */\n    async searchLibrariesWithLink(searchQuery: string, pageLink: MelvilleLink): Promise<LibrariesResponse> {\n        // Move the query params to the body to avoid extra preflight requests.\n        const [ url, params ] = moveUrlQueryParamsToHeaders(pageLink.href);\n        const body: SearchLibraryRequest = {\n            query_string: searchQuery,\n            asset_type: [ 'library' ],\n            selector: 'rendition_grid,collaboration,details',\n            start: params['start'],\n            limit: params['limit']\n        };\n        const response = await this._doPost(\n            this._getEdgeUrl(url),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(body),\n            [ 200 ]);\n\n        return await response.json();\n    }\n    async getRenditionTileImage(resource: RenditionTileResource): Promise<void> {\n        const newURL = new URL(resource.renditionUrl);\n        await this._doGet(newURL.toString(), { resource });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type { GenerationHistoryAssetData, MelvilleGenerationHistoryAssetsParams, MelvilleGenerationHistoryAssetsResponse } from './GenerationHistoryAssetModel';\nimport InterfaceBase from './InterfaceBase';\nimport { moveUrlQueryParamsToHeaders } from './LibraryInterface';\nimport type { MelvilleLink } from './LibraryModel';\nimport type { HeaderMap } from './LinkUtils';\nimport { fillURLTemplate } from './LinkUtils';\nimport type { ComponentURL } from '../generation-history/utils';\nimport type Resource from '../assets/Resource';\n\nexport default class GenerationHistoryInterface extends InterfaceBase {\n    private _getUrl(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.MELVILLE_HOST}${endpoint}`;\n    }\n\n    async getGenerationHistoryAssets(queryParams: MelvilleGenerationHistoryAssetsParams, resource?: Resource): Promise<MelvilleGenerationHistoryAssetsResponse> {\n        if (queryParams?.limit && queryParams?.start === undefined) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, '[Melville] If limit is provided, start must also be provided.');\n        }\n        queryParams = sortParameters(queryParams);\n        const urlWithQueryParams = fillURLTemplate(\n            this._getUrl('/api/v1/firefly-generations'),\n            queryParams\n        );\n        // Pass as many parameters as headers as we can, to avoid extra CORS preflight OPTIONS requests per url.\n        const [ url, headers ] = moveUrlQueryParamsToHeaders(urlWithQueryParams);\n        // Ensure browser doesn't automatically add If-None-Match, otherwise\n        // service may respond with cached data for a library\n        const defaultHeaders: HeaderMap = { ['Cache-Control']: 'no-cache, no-store, max-age=0' };\n        const finalHeaders = { ...defaultHeaders, ...headers };\n\n        return await this._getResponse(url, { headers: finalHeaders, resource });\n    }\n\n    /**\n   * @package -- only for use in SAM.js\n   * Fetches the next page of history assets from Melville\n   * @returns a list of history assets along with page information and links to the next page\n   */\n    async getGenerationHistoryAssetsUsingPageLink(pageLink: MelvilleLink, resource?: Resource): Promise<MelvilleGenerationHistoryAssetsResponse> {\n        const [ url, headers ] = moveUrlQueryParamsToHeaders(this._getUrl(pageLink.href));\n        return this._getResponse(url, { headers, resource });\n    }\n\n    /**\n     * Fetches a history asset by ID\n     *\n     * @param assetId ID of custom model to be fetched\n     * @returns the custom model\n     */\n    async getGenerationHistoryAssetById(assetId: string): Promise<GenerationHistoryAssetData> {\n        return await this._getResponse<GenerationHistoryAssetData>(\n            this._getUrl(`/api/v1/firefly-generations/${assetId}`),\n            { headers: { 'Content-Type': 'application/json' } }\n        );\n    }\n\n    async getOutputComponentDownloadURLs(componentURLs: Record<string, ComponentURL>): Promise<string[]> {\n        const downloadURLPromises = Object.values(componentURLs).map(componentURL => this.getOutputComponentDownloadURL(componentURL));\n\n        return Promise.all(downloadURLPromises);\n    }\n\n    async getOutputComponentDownloadURL(componentURL: ComponentURL): Promise<string> {\n        const { isBlockDownload, url } = componentURL;\n\n        if (isBlockDownload) {\n            return url;\n        }\n\n        const componentLinkResponse = await this._doGet(url);\n\n        const blobUrl = URL.createObjectURL(await componentLinkResponse.blob());\n\n        if (!blobUrl?.length) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Cannot convert blob to URL');\n        }\n\n        return blobUrl;\n    }\n}\n\n// Sort parameters so that the query string is stable, preventing unnecessary cache misses.\nexport const sortParameters = (parameters: MelvilleGenerationHistoryAssetsParams): MelvilleGenerationHistoryAssetsParams => {\n    return Object.fromEntries(\n        Object.entries(parameters)\n            .map(([ key, value ]) => {\n                if (Array.isArray(value)) {\n                    return [ key, value.sort() ];\n                }\n                return [ key, value ];\n            })\n            .sort()\n    );\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { RelType } from '../interface/LinkUtils';\nimport type AdobeAsset from './AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport AdobeAssetResource from './AdobeAssetResource';\nimport type { IPerUserMetadata } from '../interface/AssetModel';\n\nexport default class PerUserMetadataResource extends AdobeAssetResource<IPerUserMetadata> {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        _parent?: AdobeAsset,\n    ) {\n        super(_core, _parent, {\n            onChange: async (perUserMetadata) => {\n                await this._parent?._handleResourceUpdates({ perUserMetadata });\n            },\n            onError: async (error) => {\n                await this._parent?._handleResourceUpdates({ error });\n            }\n        });\n    }\n\n    protected async _loadData() {\n        await this._parent?._ensureLink(RelType.PERUSER_METADATA);\n        const assetInterface = await this._parent?._getAssetInterface();\n        await assetInterface?.getPerUserMetadata(this);\n    }\n}\n","import type AdobeAsset from '../assets/AdobeAsset';\nimport packageJSON from '../../package.json';\nimport type { HeaderMap } from '../interface/LinkUtils';\nimport type { USSMetadata } from '../interface/USSModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\n\nexport enum RequestHeaders {\n    PREFER_RAPI = 'X-Prefer-RAPI',\n    SAM_VERSION = 'X-Shared-Asset-Model-Version'\n}\n\nexport function getSAMVersionRequestHeader(): HeaderMap {\n    return { [RequestHeaders.SAM_VERSION]: packageJSON.version };\n}\n\ntype ValidationType = 'string' | 'date' | 'string[]' | 'enum' | 'blob' | 'object';\n\nexport interface ValidationMap<T> {\n    key: keyof T;\n    type: ValidationType;\n    isRequired: boolean;\n    ref?: any;\n}\n\n// This is susceptible to breaking if the nesting of EDU assets change\nconst assignmentPath = '.*/classrooms/[^/]+/assignments/[^/]+$';\nconst assignmentPathRegex = new RegExp(assignmentPath);\n\n// [ACPCEDU-3811] will replace the need for this function\nexport function isAssignmentPath({ repoPath }: {repoPath: string}): boolean {\n    return assignmentPathRegex.test(repoPath);\n}\n\n// This is susceptible to breaking if the nesting of EDU assets change\nconst materialsFilePath = assignmentPath.replace('$', '/materials/[^/]+$');\nconst materialsFilePathRegex = new RegExp(materialsFilePath);\n\n// [ACPCEDU-3811] will replace the need for this function\nexport function isMaterialsFilePath({ repoPath }: {repoPath: string}): boolean {\n    return materialsFilePathRegex.test(repoPath);\n}\n\n// This is susceptible to breaking if the nesting of EDU assets change\nconst studentAssignmentPath = assignmentPath.replace('$', '/students/[^/]+$');\nconst studentAssignmentPathRegex = new RegExp(studentAssignmentPath);\n\n// [ACPCEDU-3811] will replace the need for this function\nexport function isStudentAssignmentPath({ repoPath }: {repoPath: string}): boolean {\n    return studentAssignmentPathRegex.test(repoPath);\n}\n\n// [ACPCEDU-3811] will replace the need for this function\nexport function getClassroomNameFromSAFPath(repoPath: string): string {\n    // Assumes [..., Classroom, Assignments, Assignment, Students, StudentAssignment, StudentAssignmentFile]\n    // Example path: /content/assets/classrooms/${classroomName}/assignments/assignment-name/students/student-name/file-name\n    if (!isStudentAssignmentFilePath({ repoPath })) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'repoPath provided is not a StudentAssignmentFile path');\n    }\n    // Verified expected length of repoPath array through the isStudentAssignmentFilePath check\n    return repoPath.split('/').at(-6)!;\n}\n\n// [ACPCEDU-3811] will replace the need for this function\nexport function getClassroomNameFromMaterialsFilePath(repoPath: string): string {\n    // Assumes [..., Classroom, Assignments, Assignment, Materials, Materials file]\n    // Example path: /content/assets/classrooms/${classroomName}/assignments/assignment-name/materials/file-name\n    if (!isMaterialsFilePath({ repoPath })) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'repoPath provided is not a MaterialsFile path');\n    }\n    // Verified expected length of repoPath array through the isMaterialsFilePath check\n    return repoPath.split('/').at(-5)!;\n}\n\n// This is susceptible to breaking if the nesting of EDU assets change\nconst studentAssignmentFilePath = studentAssignmentPath.replace('$', '/[^/]+$');\nconst studentAssignmentFilePathRegex = new RegExp(studentAssignmentFilePath);\n\n// [ACPCEDU-3811] will replace the need for this function\nexport function isStudentAssignmentFilePath({ repoPath }: {repoPath: string}): boolean {\n    return studentAssignmentFilePathRegex.test(repoPath);\n}\n\n// [ACPCEDU-3811] will replace the need for this function\nexport function ussIsStudentAssignmentFilePath(item: USSMetadata): boolean {\n    return studentAssignmentFilePathRegex.test(`${item.asset_name_path}/${item.asset_name}`);\n}\n\nexport function isAssetAWebsiteTemplate(asset: AdobeAsset): boolean {\n    const doesMediaTypeMatch = asset.mediaType === 'application/vnd.adobe.gneisswebpage.theme.document+dcx';\n    const doesPathMatch = asset.name.endsWith('.webpagetheme');\n\n    return doesMediaTypeMatch || doesPathMatch;\n}\n\n/**\n * Validates a string for type correctness and non-empty.\n * @param value The value to validate.\n * @param name The name of the value, only used when throwing errors.\n * @param shouldThrow True (default) if a specific error should be thrown; false to return a status.\n * @returns True if the value is a string and non-empty; false otherwise.\n */\nexport function validateString(value: any | any[], name: string, shouldThrow: boolean = true): boolean {\n    let result: boolean = true;\n\n    if (Array.isArray(value)) {\n        for (let index = 0; index < value.length; index++) {\n            result = validateString(value[index], name, shouldThrow);\n            if (!result) {\n                break;\n            }\n        }\n\n        return result;\n    }\n\n    if (!validateType(value, 'string', true)) {\n        result = false;\n\n        if (shouldThrow) {\n            throw Error(`${name} is not a valid string`);\n        }\n    }\n\n    if (value as string === '') {\n        result = false;\n\n        if (shouldThrow) {\n            throw Error(`${name} is an empty string`);\n        }\n    }\n\n    return result;\n}\n\n/**\n * Validates that a given piece of data is of the correct type\n * @returns true if the data is of the correct type, false otherwise\n */\nexport function validateType(value: any, type: ValidationType, isRequired: boolean, ref?: any): boolean {\n    if (!isRequired && (value === undefined || value === null)) {\n        return true;\n    }\n\n    switch (type) {\n    case 'string':\n        return typeof value === 'string';\n    case 'date':\n        return typeof value === 'object' && (value as Date).toDateString !== undefined;\n    case 'string[]':\n        return Array.isArray(value) && value.every((item) => validateType(item, 'string', false));\n    case 'enum':\n        return Object.values(ref).some((enumValue) => enumValue === value);\n    case 'blob':\n        return value instanceof Blob;\n    case 'object':\n        return typeof value === 'object' && !Array.isArray(value) && value !== null;\n    }\n\n    // Not reachable through TS, but JS could hit this. Including for completeness.\n    return false;\n}\n\n/**\n * Validates multiple pieces of data against a validation map\n * @returns an array of error messages for each piece of data that failed validation\n */\nexport function validateTypes<T extends any>(validationMap: ValidationMap<T>[], data: T): string[] {\n    return validationMap.reduce((errors: string[], { key, type, ref, isRequired }) => {\n        if (!validateType(data[key], type, isRequired, ref)) {\n            const article = (type === 'enum' || type === 'object') ? 'an' : 'a';\n            let errMsg = `${key.toString()} is not ${article} ${type}`;\n            if (isRequired) {\n                errMsg += ' or is missing';\n            }\n            errors.push(errMsg);\n        }\n\n        return errors;\n    }, [] as string[]);\n}\n\nexport function getMemberComputedKey(classroomId: string, userId: string) {\n    return `${classroomId}-${userId}`;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n\nimport type { IAppMetadata, IEffectivePermissions, RepositoryMetadata } from '../interface/RepositoryModel';\nimport type { USSItemMetadata } from '../interface/USSv3Model';\nimport type { IProject, IProjectsAppMetadata, IProjectsEffectivePermissions } from '../interface/ProjectsModel';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport type { AdobeAssetUpdaterMetadata, LocalAssetMetadata } from './AdobeAsset';\nimport type AdobeAsset from './AdobeAsset';\nimport type Library from '../libraries/Library';\nimport type { LibraryData } from '../interface/LibraryModel';\nimport type { IRemoteAssignment } from '../interface/AssignmentModel';\nimport type Project from '../projects/Project';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { RelType } from '../interface/LinkUtils';\nimport type { USSMetadata } from '../interface/USSModel';\nimport type Board from '../boards/Board';\nimport type { IPerUserMetadata, Permission } from '../interface/AssetModel';\nimport { parseEffectivePermissions } from '../interface/AssetModel';\nimport type StudentAssignmentFile from '../assignments/StudentAssignmentFile';\nimport type { IRemoteStudentAssignmentFile, IRemoteStudentAssignmentFileMetadataWithComputedValues } from '../interface/StudentAssignmentFileModel';\nimport type Assignment from '../assignments/Assignment';\nimport type { IRemoteStudentAssignment } from '../interface/StudentAssignmentModel';\nimport type StudentAssignment from '../assignments/StudentAssignment';\nimport type CustomModel from '../custom-models/CustomModel';\nimport type { CustomModelInfoMelville, CustomModelInfoUSS } from '../interface/CustomModelModel';\nimport { CUSTOM_MODEL_MEDIA_TYPE } from '../interface/CustomModelModel';\nimport { isAssignmentPath, isStudentAssignmentPath, isStudentAssignmentFilePath, ussIsStudentAssignmentFilePath } from '../utils/classroomUtils';\nimport type { GenerationHistoryAssetData } from '../interface/GenerationHistoryAssetModel';\nimport { GENERATION_HISTORY_MEDIA_TYPES } from '../interface/GenerationHistoryAssetModel';\nimport type ItemUpdater from '../core/ItemUpdater';\n\nexport const boardMediaTypeString = 'application/vnd.adobe.board+dcx';\n\nexport function repoMetadataIsBoard(repoMetadata: Partial<RepositoryMetadata>): boolean {\n    return repoMetadata?.['dc:format'] === boardMediaTypeString;\n}\n\nexport const libraryMediaTypeString = 'application/vnd.adobe.library+dcx';\n\nexport function repoMetadataIsLibrary(repoMetadata: Partial<RepositoryMetadata>): boolean {\n    return repoMetadata?.['dc:format'] === libraryMediaTypeString;\n}\n\nexport function repoMetadataIsGenerationHistoryAsset(repoMetadata: Partial<RepositoryMetadata>): boolean {\n    return repoMetadata?.['dc:format'] ? GENERATION_HISTORY_MEDIA_TYPES.includes(repoMetadata?.['dc:format']) : false;\n}\n\nexport function metadataIsAssignment({ repoMetadata, appMetadata }: {repoMetadata: RepositoryMetadata, appMetadata?: IAppMetadata}) {\n    return appMetadataIsAssignment(appMetadata) || isAssignmentPath({ repoPath: repoMetadata['repo:path'] });\n}\n\nexport function appMetadataIsAssignment(app_metadata?: IAppMetadata) {\n    return !!app_metadata?.['cc:inheritable']?.['cc:assignment']?.['repo:assetId'];\n}\n\nexport function appMetadataIsProject(app_metadata?: IAppMetadata) {\n    return !!app_metadata?.['cc:inheritable']?.['cc:team']?.['repo:assetId'];\n}\n\nexport function ussV3ItemMetadataIsProject(item: USSItemMetadata): boolean {\n    return !!item.am?.['cc:inheritable']?.['cc:team']?.['repo:assetId'];\n}\n\nexport function ussV3ItemMetadataIsLibrary(item: USSItemMetadata): boolean {\n    return item.rm?.['dc:format'] === libraryMediaTypeString;\n}\n\nexport function metadataIsStudentAssignment({ repoMetadata, appMetadata }: {repoMetadata: RepositoryMetadata, appMetadata?: IAppMetadata}) {\n    return appMetadataIsStudentAssignment(appMetadata) || isStudentAssignmentPath({ repoPath: repoMetadata['repo:path'] });\n}\n\nexport function appMetadataIsStudentAssignment(app_metadata?: IAppMetadata): boolean {\n    return !!app_metadata?.['cc:inheritable']?.['cc:studentAssignment']?.['repo:assetId'];\n}\n\nexport function ussMetadataIsLibrary(item: Partial<USSMetadata>): boolean {\n    return item.type === libraryMediaTypeString;\n}\n\nexport function ussMetadataIsCustomModel(item: Partial<USSMetadata>): item is CustomModelInfoUSS {\n    return item.type === CUSTOM_MODEL_MEDIA_TYPE;\n}\n\nexport function appMetadataIsStudentAssignmentFile(app_metadata?: IAppMetadata): boolean {\n    return !!app_metadata?.['cc:inherited']?.['cc:studentAssignment']?.['repo:assetId'];\n}\n\nfunction metadataIsStudentAssignmentFile({ repoMetadata, appMetadata }: {repoMetadata: RepositoryMetadata, appMetadata: IAppMetadata}) {\n    return appMetadataIsStudentAssignmentFile(appMetadata) || isStudentAssignmentFilePath({ repoPath: repoMetadata['repo:path'] });\n}\n\nfunction repoToStudentAssignmentFileData(item: Partial<RepositoryMetadata>, appMetadata: IAppMetadata): Partial<IRemoteStudentAssignmentFile> {\n    return {\n        ...item,\n        ...appMetadata,\n    };\n}\n\nfunction repoToStudentAssignmentData(item: Partial<RepositoryMetadata>, appMetadata: IAppMetadata): Partial<IRemoteStudentAssignment> {\n    return {\n        ...item,\n        ...appMetadata,\n        // Student Assignment specific links are not available from an AdobeAsset\n        _links: undefined,\n    };\n}\n\n/* Utils to translate incoming data to the type expected by the subclass's PropertyUpdater: */\n// (This mapping is necessary at minimum to translate the id to the remoteIdProperty expected by the PropertyUpdater,\n// because we use the updaters to indirectly create an instance of the subclass in the call to\n// updater.updateRemoteItems({remoteIdProperty}), regardless of whether the updater supports the incoming data type.)\n\nexport function ussV3ToProjectMetadata(item: Partial<USSItemMetadata>): Partial<IProject> {\n    // TODO: Add more Project attributes here as they become available in USS.\n    // Minimal data needed for ProjectUpdater. When additional Project metadata\n    // is available from the USSv3 query result, add them here.\n    return { 'repo:assetId': item.id };\n}\nexport function ussToProjectData(item: Partial<USSMetadata>): Partial<IProject> {\n    return {\n        'repo:assetId': item.asset_id,\n        'repo:repositoryId': item['repo:repositoryId'],\n        _embedded: {\n            [RelType.AC_EFFECTIVE]: item._embedded?.[RelType.AC_EFFECTIVE] as IProjectsEffectivePermissions,\n            [RelType.APP_METADATA]: item.app_metadata as IProjectsAppMetadata\n        }\n    };\n}\n\nexport function ussToLibraryData(item: Partial<USSMetadata>): Partial<LibraryData> {\n    return { 'library_urn': item.asset_id };\n}\n\nfunction ussToStudentAssignmentFileData(item: Partial<USSMetadata>): Partial<IRemoteStudentAssignmentFileMetadataWithComputedValues> {\n    const ancestors = item.path || [];\n    const studentAssignmentId = item.app_metadata?.['cc:inherited']?.['cc:studentAssignment']?.['repo:assetId'] || ancestors[ancestors.length - 1];\n    return {\n        ...item,\n        'repo:assetId': item['asset_id'],\n        'computedStudentAssignmentId': studentAssignmentId,\n    };\n}\n\nfunction ussV3ToStudentAssignmentFileData(item: Partial<USSItemMetadata>): Partial<IRemoteStudentAssignmentFileMetadataWithComputedValues> {\n    const ancestors = item.rm?.['repo:ancestors'] ?? [];\n    const studentAssignmentId = item.am?.['cc:inherited']?.['cc:studentAssignment']?.['repo:assetId'] || ancestors[ancestors.length - 1];\n    return {\n        ...item.rm,\n        ...item.am,\n        'computedStudentAssignmentId': studentAssignmentId,\n    };\n}\n\nexport function ussToCustomModelData(item: Partial<CustomModelInfoUSS>): Partial<CustomModelInfoMelville> {\n    return {\n        ...item,\n        'repo:assetId': item['asset_id'],\n        'application_metadata': item['app_metadata'],\n        'firefly#ffmodel': item['firefly#ffmodel'],\n        'repo:path': item['original_path'],\n        'repo:createDate': Math.floor((new Date(item['create_date']!)).getTime() / 1000),\n        'repo:modifyDate': Math.floor((new Date(item['modify_date']!)).getTime() / 1000),\n        'repo:version': item['asset_version_id'],\n        'storage:region': item['region'],\n        'repo:size': item['size']\n    };\n}\n\nfunction ussV3ToLibraryData(item: Partial<USSItemMetadata>): Partial<LibraryData> {\n    return { 'library_urn': item.id };\n}\n\nfunction repoToLibraryData(item: Partial<RepositoryMetadata>): Partial<LibraryData> {\n    return { 'library_urn': item['repo:assetId'] };\n}\n\nfunction repoToAssignmentData(item: Partial<RepositoryMetadata>, appMetadata: IAppMetadata): Partial<IRemoteAssignment> {\n    return {\n        ...item,\n        ...appMetadata,\n        // Assignment specific links and correctly structured children assets are not available from an AdobeAsset\n        _links: undefined,\n        children: [],\n    };\n}\n\nexport type UpdaterMap =\n    Map<'project', ItemUpdater<Project, IProject>> &\n    Map<'library', ItemUpdater<Library, LibraryData>> &\n    Map<'asset', ItemUpdater<AdobeAsset, AdobeAssetUpdaterMetadata>> &\n    Map<'assignment', ItemUpdater<Assignment, IRemoteAssignment>> &\n    Map<'board', ItemUpdater<Board, IRemoteAssignment>> &\n    Map<'custom-model', ItemUpdater<CustomModel, CustomModelInfoMelville>> &\n    Map<'student-assignment-file', ItemUpdater<StudentAssignmentFile, IRemoteStudentAssignmentFile>> &\n    Map<'student-assignment', ItemUpdater<StudentAssignment, IRemoteStudentAssignment>> &\n    Map<'generation-history', ItemUpdater<AdobeAsset, GenerationHistoryAssetData>>;\n\nfunction repoToBoardData(item: Partial<RepositoryMetadata>): Partial<IRemoteAssignment> {\n    return {\n        ...item,\n        // Board specific links are not available from an AdobeAsset\n        _links: undefined,\n    };\n}\n\nexport default class AdobeAssetFactory implements ISAMObject {\n    constructor(\n        readonly _core: ISAMCorePrivate\n    ) {}\n\n    // Creates assets from a list of USSItemMetadata returned from USSv3\n    // getItemData maps the repo metadata fields, as well as isShared, sharedViaInvite, and app metadata fields\n    // from USSv3 format to RAPI format\n    // NOTE: Caller is responsible for committing the session after this is called\n    assetsFromUSSV3Response(\n        session: IUpdateSession<AdobeAsset>,\n        ussItemMetadata: USSItemMetadata[],\n        getItemData: (arg: USSItemMetadata) => Partial<AdobeAssetUpdaterMetadata>,\n        updaters: UpdaterMap\n    ): AdobeAsset[] {\n        // If there are no updaters we just return an\n        // empty array since there likley isn't any items.\n        if (updaters.size === 0 || ussItemMetadata.length === 0) {\n            return [];\n        }\n\n        const libraryUpdater = updaters.get('library');\n        if (libraryUpdater) {\n            libraryUpdater.updateRemoteItems(\n                session as IUpdateSession<Library>,\n                ussItemMetadata.filter(ussV3ItemMetadataIsLibrary).map(ussV3ToLibraryData) as LibraryData[]\n            );\n        }\n\n        const studentAssignmentFileUpdater = updaters.get('student-assignment-file');\n        if (studentAssignmentFileUpdater) {\n            studentAssignmentFileUpdater.updateRemoteItems(\n                session as IUpdateSession<StudentAssignmentFile>,\n                ussItemMetadata.filter((itemMetadata) => metadataIsStudentAssignmentFile({ repoMetadata: itemMetadata.rm, appMetadata: itemMetadata.am }))\n                    .map(ussV3ToStudentAssignmentFileData) as IRemoteStudentAssignmentFile[]\n            );\n        }\n\n        const projectUpdater = updaters.get('project');\n        if (projectUpdater) {\n            projectUpdater.updateRemoteItems(\n                session as IUpdateSession<Project>,\n                ussItemMetadata.filter(ussV3ItemMetadataIsProject).map(ussV3ToProjectMetadata) as IProject[]\n            );\n        }\n\n        const assetUpdater = updaters.get('asset')!;\n        return assetUpdater.updateRemoteItems(\n            session,\n            // allow Loader to provide additional item metadata (optional)\n            ussItemMetadata.map((item: USSItemMetadata): Partial<AdobeAssetUpdaterMetadata> => {\n                return getItemData(item);\n            }));\n    }\n\n    async getUSSV3Updaters(resultsItems: USSItemMetadata[]): Promise<UpdaterMap> {\n        const updaters: UpdaterMap = new Map();\n\n        for (const item of resultsItems) {\n            if (ussV3ItemMetadataIsProject(item)) {\n                const projectContext = await this._core.getProjectContext();\n                updaters.set('project', projectContext._projectUpdater);\n            }\n\n            if (ussV3ItemMetadataIsLibrary(item)) {\n                const libraryContext = await this._core.getLibraryContext();\n                updaters.set('library', libraryContext._libraryUpdater);\n            }\n        }\n\n        const assetContext = await this._core.getAssetContext();\n        updaters.set('asset', assetContext._adobeAssetUpdater);\n\n        return updaters;\n    }\n\n    async getUSSUpdaters(resultsItems: USSMetadata[]): Promise<UpdaterMap> {\n        const updaters: UpdaterMap = new Map();\n\n        for (const item of resultsItems) {\n            if (appMetadataIsProject(item.app_metadata)) {\n                const projectContext = await this._core.getProjectContext();\n                updaters.set('project', projectContext._projectUpdater);\n            }\n\n            if (ussMetadataIsLibrary(item)) {\n                const libraryContext = await this._core.getLibraryContext();\n                updaters.set('library', libraryContext._libraryUpdater);\n            }\n\n            if (ussMetadataIsCustomModel(item)) {\n                const customModelContext = await this._core.getCustomModelContext();\n                updaters.set('custom-model', customModelContext._customModelUpdaterMelville);\n            }\n\n            const assetContext = await this._core.getAssetContext();\n            updaters.set('asset', assetContext._ussAdobeAssetUpdater);\n        }\n\n        return updaters;\n    }\n\n    async getRepoMetadataUpdaters(\n        repoMetadatas: RepositoryMetadata[] | LocalAssetMetadata[]\n    ): Promise<UpdaterMap>   {\n        const updaters: UpdaterMap = new Map();\n        for (const item of repoMetadatas) {\n            const appMetadata = item._embedded?.[RelType.APP_METADATA]!;\n            const assetContext = await this._core.getAssetContext();\n            updaters.set('asset', assetContext._adobeAssetUpdater);\n            if (appMetadataIsProject(appMetadata)) {\n                const projectContext = await this._core.getProjectContext();\n                updaters.set('project', projectContext._projectUpdater);\n            } else if (repoMetadataIsLibrary(item)) {\n                const libraryContext = await this._core.getLibraryContext();\n                updaters.set('library', libraryContext._libraryUpdater);\n            } else if (repoMetadataIsBoard(item)) {\n                const boardContext = await this._core.getBoardContext();\n                updaters.set('board', boardContext._boardUpdater);\n            } else if (appMetadata && metadataIsStudentAssignmentFile({ repoMetadata: item as RepositoryMetadata, appMetadata })) {\n                const classroomContext = await this._core.getClassroomContext();\n                updaters.set('student-assignment-file', classroomContext._studentAssignmentFileUpdater);\n            } else if (metadataIsStudentAssignment({ repoMetadata: item as RepositoryMetadata, appMetadata })) {\n                const classroomContext = await this._core.getClassroomContext();\n                updaters.set('student-assignment', classroomContext._studentAssignmentUpdater);\n            } else if (appMetadata && metadataIsAssignment({ repoMetadata: item as RepositoryMetadata, appMetadata })) {\n                const classroomContext = await this._core.getClassroomContext();\n                updaters.set('assignment', classroomContext._assignmentUpdater);\n            } else if (repoMetadataIsGenerationHistoryAsset(item)) {\n                const generationHistoryContext = await this._core.getGenerationHistoryContext();\n                updaters.set('generation-history', generationHistoryContext._generationHistoryAssetUpdater);\n            }\n        }\n\n        return updaters;\n    }\n\n    /**\n     * Create assets from a list of items from USS.\n     * getItemData allows the caller to add additional metadata\n     * @note Caller is responsible for committing the session after this is called.\n     *\n     */\n    assetsFromUSSMetadata(\n        session: IUpdateSession<AdobeAsset>,\n        items: USSMetadata[],\n        getItemData: (arg: USSMetadata) => Partial<AdobeAssetUpdaterMetadata>,\n        updaters: UpdaterMap\n    ) {\n        if (updaters.size === 0 || items.length === 0) {\n            return [];\n        }\n\n        // Ensure that Projects are added to the discarded list as a \"Project\" instance.\n        // ProjectUpdater creates a blank Project instance and relies on the USSAdobeAssetUpdater\n        // to fill in the blanks.\n        const projectUpdater = updaters.get('project');\n        if (projectUpdater) {\n            const projects = projectUpdater.updateRemoteItems(\n                session as IUpdateSession<Project>,\n                items.filter(item => appMetadataIsProject(item.app_metadata)).map(ussToProjectData) as IProject[]);\n\n            // USS won't have all the permissions required for the deleted view\n            // Loaders are responsible for populating the _canRestoreProject cache before it gets here.\n            for (const project of projects) {\n                project._applyRestorePermission(session as IUpdateSession<Project>);\n            }\n        }\n\n        const studentAssignmentFileUpdater = updaters.get('student-assignment-file');\n        if (studentAssignmentFileUpdater) {\n            studentAssignmentFileUpdater.updateRemoteItems(\n                session as IUpdateSession<StudentAssignmentFile>,\n                items.filter((item) => appMetadataIsStudentAssignmentFile(item.app_metadata) || ussIsStudentAssignmentFilePath(item))\n                    .map(ussToStudentAssignmentFileData) as IRemoteStudentAssignmentFile[]\n            );\n        }\n\n        // Ensure that Libraries are added to the discarded list as a \"Library\" instance\n        const libraryUpdater = updaters.get('library');\n        if (libraryUpdater) {\n            libraryUpdater.updateRemoteItems(\n                session as IUpdateSession<Library>,\n                items.filter(ussMetadataIsLibrary).map(ussToLibraryData) as LibraryData[]);\n        }\n\n        const customModelUpdater = updaters.get('custom-model');\n        if (customModelUpdater) {\n            customModelUpdater.updateRemoteItems(\n                session as IUpdateSession<CustomModel>,\n                items.filter(ussMetadataIsCustomModel).map(ussToCustomModelData) as CustomModelInfoMelville[]\n            );\n        }\n        const ussAssetUpdater = updaters.get('asset')!;\n        return ussAssetUpdater.updateRemoteItems(\n            session,\n            // allow Loader to provide additional item metadata (optional)\n            items.map(item => getItemData?.(item) || item)\n        );\n    }\n\n    // Create assets from a list of RepositoryMetadata returned from RAPI\n    // NOTE: Caller is responsible for committing the session after this is called\n    assetsFromRepoMetadata(\n        session: IUpdateSession<AdobeAsset>,\n        repoMetadatas: RepositoryMetadata[],\n        updaters: UpdaterMap\n    ): AdobeAsset[] {\n        if (updaters.size === 0 || repoMetadatas.length === 0) {\n            return [];\n        }\n\n        return repoMetadatas.map(repoMetadata => {\n            let permissions: Permission = {} as Permission;\n            if (repoMetadata._embedded?.[RelType.AC_EFFECTIVE]) {\n                permissions = parseEffectivePermissions(repoMetadata._embedded?.[RelType.AC_EFFECTIVE] as IEffectivePermissions);\n            }\n            return this.assetFromRepoMetadata({\n                session,\n                repoMetadata,\n                updaters,\n                permissions,\n                appMetadata: repoMetadata._embedded?.[RelType.APP_METADATA]!,\n            });\n        });\n    }\n\n    assetFromRepoMetadata({\n        session,\n        repoMetadata,\n        updaters,\n        permissions,\n        appMetadata,\n        projectMetadata,\n        studentAssignmentMetadata,\n        perUserMetadata,\n        generationHistoryMetadata\n    }: {\n        session: IUpdateSession<AdobeAsset>,\n        repoMetadata: RepositoryMetadata,\n        updaters: UpdaterMap,\n        permissions?: Permission,\n        appMetadata?: IAppMetadata,\n        projectMetadata?: IProject,\n        studentAssignmentMetadata?: Partial<IRemoteStudentAssignment>,\n        perUserMetadata?: IPerUserMetadata,\n        generationHistoryMetadata?: Partial<GenerationHistoryAssetData>\n    }): AdobeAsset {\n        let asset: AdobeAsset | undefined;\n        if (appMetadata && Object.keys(appMetadata).length > 0) {\n            // We should have a better way to do this\n            repoMetadata._embedded = { ...repoMetadata._embedded, [RelType.APP_METADATA]: appMetadata };\n        }\n        const assetMetadata: Partial<AdobeAssetUpdaterMetadata> =  repoMetadata || {};\n        if (permissions && Object.keys(permissions).length > 0) {\n            assetMetadata.effectivePermission = permissions;\n        }\n        if (perUserMetadata) {\n            assetMetadata.perUserMetadata = perUserMetadata;\n        }\n\n        const assetUpdater = updaters.get('asset')!;\n        if (appMetadataIsProject(appMetadata)) {\n            const projectUpdater = updaters.get('project')!;\n            const typedProjectMetadata = projectMetadata as IProject;\n            asset = projectUpdater.updateRemoteItem(session as IUpdateSession<Project>, typedProjectMetadata);\n            // Since ProjectUpdater doesn't handle all repo metadata fields, use AdobeAssetUpdater\n            // For example we need the links coming in from the repoMetadata to be used in AdobeAsset\n            assetUpdater.updateLocalItem(session, asset, assetMetadata);\n            // Apply Project-specific metadata and overrides\n            // An example of this is the createdBy field which is different for Projects\n            projectUpdater.updateLocalItem(session as IUpdateSession<Project>, asset as Project, typedProjectMetadata);\n        } else if (repoMetadataIsLibrary(assetMetadata)) {\n            const libraryUpdater = updaters.get('library')!;\n            const libraryData = repoToLibraryData(assetMetadata) as LibraryData;\n            asset = libraryUpdater.updateRemoteItem(session as IUpdateSession<Library>, libraryData);\n            // Update repo metadata fields that are not handled by LibraryUpdater with the AdobeAssetUpdater\n            assetUpdater.updateLocalItem(session, asset, assetMetadata);\n            assetUpdater.updateRemoteItem(session, assetMetadata);\n        } else if (repoMetadataIsBoard(assetMetadata)) {\n            const boardUpdater = updaters.get('board')!;\n            const boardData = repoToBoardData(assetMetadata);\n            asset = boardUpdater.updateRemoteItem(session as IUpdateSession<Board>, boardData as IRemoteAssignment);\n            // Update repo metadata fields that are not handled by BoardUpdater with the AdobeAssetUpdater\n            assetUpdater.updateLocalItem(session, asset, assetMetadata);\n        } else if (appMetadata && metadataIsStudentAssignmentFile({ repoMetadata, appMetadata })) {\n            const studentAssignmentFileUpdater = updaters.get('student-assignment-file')!;\n            const studentAssignmentFileData = repoToStudentAssignmentFileData(assetMetadata, appMetadata || {});\n            const ancestors = repoMetadata['repo:ancestors'];\n            // Last ancestor is the student assignment id. This is susceptible to breaking if the nesting of EDU assets change\n            const studentAssignmentId = appMetadata['cc:inherited']?.['cc:studentAssignment']?.['repo:assetId'] || ancestors[ancestors.length - 1];\n            (studentAssignmentFileData as IRemoteStudentAssignmentFileMetadataWithComputedValues).computedStudentAssignmentId = studentAssignmentId!;\n            asset = studentAssignmentFileUpdater.updateRemoteItem(\n                session as IUpdateSession<StudentAssignmentFile>,\n                studentAssignmentFileData as IRemoteStudentAssignmentFile\n            );\n            assetUpdater.updateLocalItem(session, asset, assetMetadata);\n        } else if (metadataIsStudentAssignment({ repoMetadata, appMetadata }) && studentAssignmentMetadata) {\n            const studentAssignmentUpdater = updaters.get('student-assignment')!;\n            const studentAssignmentData = repoToStudentAssignmentData(assetMetadata, { ...appMetadata || {}, ...studentAssignmentMetadata }) as IRemoteStudentAssignment;\n            asset = studentAssignmentUpdater.updateRemoteItem(session as IUpdateSession<StudentAssignment>, studentAssignmentData);\n            assetUpdater.updateLocalItem(session, asset, assetMetadata);\n        } else if (metadataIsAssignment({ repoMetadata, appMetadata })) {\n            const assignmentUpdater = updaters.get('assignment')!;\n            const assignmentData = repoToAssignmentData(assetMetadata, appMetadata || {}) as IRemoteAssignment;\n            asset = assignmentUpdater.updateRemoteItem(session as IUpdateSession<Assignment>, assignmentData);\n            // Update repo metadata fields that are not handled by AssignmentUpdater with the AdobeAssetUpdater\n            assetUpdater.updateLocalItem(session, asset, assetMetadata);\n        } else if (repoMetadataIsGenerationHistoryAsset(assetMetadata) && generationHistoryMetadata) {\n            const generationHistoryUpdater = updaters.get('generation-history')!;\n            asset = assetUpdater.updateRemoteItem(session, assetMetadata);\n            generationHistoryUpdater.updateLocalItem(session, asset, generationHistoryMetadata as GenerationHistoryAssetData);\n        } else {\n            // Otherwise, this is a normal AdobeAsset.\n            const assetId = assetMetadata['repo:assetId'];\n            const repoPath = assetMetadata['repo:path'];\n            // Find the asset by ID, if possible, otherwise see if a local (ACPL) asset exists by repoPath,\n            // since local assets may not yet have a cloudID when they're syncing for the first time.\n            asset = (assetId ? session.getItemById(assetId) : undefined)\n                || (repoPath ? this._findLocalAssetByRepoPath(session, assetId, repoPath) : undefined);\n            if (asset) {\n                assetUpdater.updateLocalItem(session, asset, assetMetadata);\n            } else {\n                asset = assetUpdater.updateRemoteItem(session, assetMetadata);\n            }\n            // If we have fetched the asset through non-local means (e.g. an ONS refresh or a directory load),\n            // we'll already have the ancestor IDs, which indicates we've fleshed out repoMetadata from a real source.\n            // Otherwise, we need to mark the asset as needing repoMetadata, since ACPL only provides a subset.\n            if (!asset.ancestorIDs) {\n                asset._setNeedsRepoMetadata(true);\n            }\n        }\n        return asset;\n    }\n\n    /**\n     * Find an ACPL-populated asset by repoPath, if it exists.\n     */\n    private _findLocalAssetByRepoPath(session: IUpdateSession<AdobeAsset>, assetId: string | undefined, repoPath: string): AdobeAsset | undefined {\n        const asset = session.findItem(item => Boolean(item.localID) && item.repoPath === repoPath);\n        if (assetId && asset && asset.id !== assetId) {\n            // If we found an asset by repoPath and localID, but the cloudID doesn't match,\n            // we now have enough information to reindex the item by the real ID.\n            session.reindexItem(asset, asset.id, assetId);\n        }\n        return asset;\n    }\n\n    assetsFromLocalMetadata(session: IUpdateSession<AdobeAsset>, localMetadata: LocalAssetMetadata[], updaters: UpdaterMap): AdobeAsset[] {\n        return this.assetsFromRepoMetadata(session, localMetadata as RepositoryMetadata[], updaters);\n    }\n\n    assetFromLocalMetadata(session:  IUpdateSession<AdobeAsset>, localMetadata: LocalAssetMetadata, updaters: UpdaterMap): AdobeAsset {\n        return this.assetFromRepoMetadata({ session, repoMetadata: localMetadata as RepositoryMetadata, updaters });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport path from 'path-browserify';\nimport ItemBase from '../core/ItemBase';\nimport type { IBlockUploadInfo, IBlockUploadInfoResult } from '../interface/AssetInterface';\nimport AssetInterface, { FOLDER_ALTERNATE_TYPE, FOLDER_TYPE, getBlockTransferThreshold } from '../interface/AssetInterface';\nimport ShareableItem from '../collaboration/ShareableItem';\nimport { memoize, observable, retry, synchronized } from '../core/decorators';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport EmbeddedMetadataResource from './EmbeddedMetadataResource';\nimport AppMetadataResource from './AppMetadataResource';\nimport ManifestResource from './ManifestResource';\nimport type Resource from './Resource';\nimport type {\n    AssetRenameMap } from './AssetUtils';\nimport {\n    createMilestoneJsonParams,\n    formatFileName,\n    getRestorePath,\n    isTopLevelFolder,\n    removeArchiveGuidFromName,\n    renameFileInPath,\n    updateCachedDescendents,\n    validatePlatformRepoName\n} from './AssetUtils';\nimport type {\n    AssetClass,\n    AssetLinks,\n    AssetState,\n    Assignee,\n    IAppMetadata,\n    ICopyOperation,\n    IMoveOperation,\n    IResourceDesignator,\n    RepositoryMetadata,\n    Representations,\n    ShellVisibility\n} from '../interface/RepositoryModel';\nimport {\n    AssetClassChoices,\n    AssetStateChoices\n} from '../interface/RepositoryModel';\nimport type {\n    AssetSubType,\n    AssetType,\n    IPerUserMetadata,\n    ITransferStatus\n} from '../interface/AssetModel';\nimport {\n    AppMetadataField,\n    parseEffectivePermissions,\n    Permission,\n    PERMISSION_ALL,\n} from '../interface/AssetModel';\nimport type { IItemUpdaterOptions } from '../core/ItemUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { PropertyFormatType } from '../core/PropertyUpdater';\nimport PropertyUpdater, { NotFound } from '../core/PropertyUpdater';\nimport type { AdobeAssetConfig, AdobeAssetSearchSource, AdobeAssetSource, AssetVersionSource } from './AdobeAssetSource';\nimport AdobeAssetSearchFilter from './AdobeAssetSearchFilter';\nimport AdobeAssetDirectoryLoader from './AdobeAssetDirectoryLoader';\nimport AdobeAssetDirectorySearchLoader from './AdobeAssetDirectorySearchLoader';\nimport ItemSource from '../core/ItemSource';\nimport { getURLFromLinks, RelType } from '../interface/LinkUtils';\nimport type { IVersionMilestone } from './AssetVersion';\nimport type AssetVersion from './AssetVersion';\nimport { VersionUpdater } from './AssetVersion';\nimport AssetVersionLoader from './AssetVersionLoader';\nimport ItemPool from '../core/ItemPool';\nimport type { IBatchOperationAssetResult } from './AssetContext';\nimport type { USSMetadata } from '../interface/USSModel';\nimport type Space from '../workspaces/Space';\nimport FileContentResource from './FileContentResource';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport { RenditionFetcher, RenditionStatus, RenditionType, THUMBNAIL_SIZE, SUPPORTED_SIZES } from '../utils/RenditionFetcher';\nimport type { AssetReviewServiceData } from '../interface/AssetReviewServiceInterface';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { SharedCollaboratorChangedEvent } from '../indexPrivate';\nimport AssetVersionFilter from './AssetVersionFilter';\nimport ImplicitDirectoryListingFilter from './ImplicitDirectoryListingFilter';\nimport addProjectIdToMetadata from '../projects/addProjectIdToMetadata';\nimport type jsonpatch from 'json-patch';\nimport type CommentsResource from '../comments/CommentsResource';\nimport { lazyLoaded, LazyLoadManager, LoadStatus } from '../core/decorators/LazyLoadManager';\nimport type { SAM } from '@ccx-public/component-types';\nimport { SharedStorageAssigneeChangedEvent, STORAGE_ASSIGNEE_CHANGED } from './AssetEvents';\nimport { type Role } from '../interface/InvitationModel';\nimport RepoMetadataResource from './RepoMetadataResource';\nimport EffectivePermissionsResource from './EffectivePermissionsResource';\nimport type AssetContext from '../assets/AssetContext';\nimport LocalAssetLoader from './LocalAssetLoader';\nimport { isGenerationHistoryAsset } from '../generation-history/utils';\nimport GenerationHistoryInterface from '../interface/GenerationHistoryInterface';\nimport type { ONSChangedAssetInfo } from '../sync-services/ONSEvent';\nimport PerUserMetadataResource from './PerUserMetadataResource';\nimport ACPLModelInterface from '../interface/ACPLModelInterface';\nimport {\n    isMaterialsFilePath,\n    isStudentAssignmentFilePath,\n    getClassroomNameFromSAFPath,\n    getClassroomNameFromMaterialsFilePath\n} from '../utils/classroomUtils';\nimport { ProjectDirectorySubtype } from '../interface/ProjectsModel';\nimport { RenditionBlobHelper } from '../utils/RenditionBlobHelper';\nimport RenditionResource from './RenditionResource';\nimport { boardMediaTypeString } from './AdobeAssetFactory';\n\n/**\n * Platform default limits on valid transfer size values.\n *\n * These are the default values for 'repo:minsingletransfersize' and 'repo:maxsingletransfersize'\n * from the RelType.BLOCK_INITIALIZE response. If we are unable to get these values from the\n * platform, we will use these defaults instead.\n *\n * DEFAULT_MAX_SINGLE_TRANSFER_SIZE is the default threshold for switching from direct to block upload,\n * if a custom threshold is not provided by the client.\n */\nexport const DEFAULT_MAX_SINGLE_TRANSFER_SIZE: number = 10485760; // 10 MB\nexport const DEFAULT_MIN_SINGLE_TRANSFER_SIZE: number = 1; // 1 byte\n\n// This must be kept in sync with AdobeAsset.h\nexport enum AssetSyncStatus {\n    InSync,\n    OutOfSync,\n    SyncConflict,\n    SyncError,\n    Syncing\n}\n\n// This must be kept in sync with AdobeAsset.h\nexport enum AssetSyncSuspensionReason {\n    None,\n    CloudContentCorrupted,\n    LocalContentCorrupted,\n    HasTooManyComponents,\n    HasTooManyChildren,\n    MaximumSizeExceeded,\n    Unknown\n}\n\n/**\n * Response from the server for the commit request.\n **/\nexport enum CommitStatus { NoErr, Conflict, DeleteConflict, ParentDeletedConflict }\n\n/**\n * The result of committing a new file.\n **/\nexport interface FileCommitResult {\n    status: CommitStatus;\n    newAsset?: AdobeAsset;\n    committedEtag?: string | null;\n}\n\ninterface InvitationServiceCapabilities {\n    canComment: boolean;\n    canShare: boolean;\n    role: Role\n}\n\n// Do not refresh app metadata for root folders like / or /cloud-content or /cloud-content-archive etc. They do not\n// show up in listings, but they can get loaded due to ONS notifications. Since the Filters prevent them from appearing\n// in listings already, there's no need to load the app metadata to see that they should be hidden due to\n// shell:visibility.\n// TODO: also ignore root folders of ESM stores.\nconst APP_METADATA_REFRESH_IGNORE_REGEX = /^\\/[^/]+$|^\\/$/;\n\n/**\n * Options for uploading an asset\n */\nexport interface ImportFileOptions {\n    /**\n     * The file blob to import\n     */\n    file: Blob | string;\n    /**\n     * The name of the file to be uploaded\n     */\n    name: string;\n    /**\n     * The media type of the file to be uploaded\n     */\n    mediaType?: string;\n    /**\n     * @deprecated Use renameOnConflict instead.\n     */\n    retryOnConflict?: boolean;\n    /**\n     * If true, a new name will be generated for the file (by ACP) if the name already exists, otherwise it will throw an error.\n     */\n    renameOnConflict?: boolean;\n    /**\n     * If true, sets the createdFromUpload property to true\n     */\n    setCreatedFrom?: boolean;\n    /**\n     * @deprecated This property is ignored and will be removed in a future version.\n     */\n    counter?: number;\n    /**\n     * Specifies the preferred block transfer threshold\n     */\n    preferredBlockTransferThreshold?: number;\n    /**\n     * If true, specifies that the file should be uploaded using the \"block store\" variant of block uploads (more efficient for large files)\n     */\n    useBlockStore?: boolean;\n\n    /**\n     * If this option is provided, the asset will be created and immediatley set as a milestone.\n     */\n    milestoneProperties?: MilestoneProperties;\n}\n\n/**\n * Options for getting a download URL for an asset\n */\nexport interface GetDownloadURLOptions {\n    /**\n     * If true, forces block download even for small files\n     */\n    forceBlockDownload?: boolean;\n    /**\n     * Size threshold for block transfer. Defaults to DEFAULT_MAX_SINGLE_TRANSFER_SIZE.\n     */\n    preferredBlockTransferThreshold?: number;\n    /**\n     * Time-to-live for the presigned URL in seconds. If not provided, uses service default (4 hours as of this writing).\n     */\n    presignedUrlExpirationSeconds?: number;\n    /**\n     * If specified, indicates that when the RelType.DOWNLOAD link is not present, the file should be downloaded\n     * using the direct download method, as long as it is under the specified threshold.\n     *\n     * The client is responsible for ensuring that the specified threshold is reasonable for direct download\n     * from both a platform perspective and a browser in-memory storage limit.\n     */\n    fallbackToDirectDownloadThreshold?: number;\n}\n\n/**\n * Options for updating an asset\n */\nexport interface UpdateFileOptions {\n    /**\n     * The file blob to update the asset with\n     */\n    file: Blob | string;\n    /**\n     * The media type of the file to be uploaded\n     */\n    mediaType?: string;\n    /**\n     * Specifies the preferred block transfer threshold\n     */\n    preferredBlockTransferThreshold?: number;\n    /**\n     * If true, specifies that the file should be uploaded using the \"block store\" variant of block uploads (more efficient for large files)\n     */\n    useBlockStore?: boolean;\n}\n\n/**\n * Options for getting block upload info\n */\nexport interface BlockUploadInfoOptions {\n    /**\n     * The media type of the file to be uploaded\n     */\n    mediaType?: string;\n    /**\n     * If true, specifies that the file should be uploaded using the \"block store\" variant of block uploads (more efficient for large files)\n     */\n    useBlockStore?: boolean;\n    /**\n     * If true, a new name will be generated for the file (by ACP) if the name already exists, otherwise it will throw an error.\n     */\n    renameOnConflict?: boolean;\n\n    /**\n     * If this option is provided, the asset will be created and the first version\n     * immediatley set as a milestone.\n     */\n    milestoneProperties?: MilestoneProperties;\n}\n\nexport interface CreateFolderOptions {\n    renameOnConflict?: boolean;\n}\n\nexport interface MilestoneProperties {\n    /**\n     * The label of the milestonem required.\n     */\n    label: string;\n\n    /**\n     * The description of the milestone, not required and can only\n     * be set when a label is provided as well.\n     */\n    description?: string;\n}\n\nexport default class AdobeAsset extends ShareableItem implements SAM.AdobeAsset {\n\n    protected _name: string = ''; // don't change this in subclasses\n    private _isFavorite?: boolean;\n    private _etag: string = '';\n    private _repositoryID: string = '';\n    private _repositoryName?: string;\n    private _path: string = '';\n    private _storageRegion: string = '';\n    protected _type: string = '';\n    private _size: number = 0;\n    private _version: string = '';\n    protected _assetClass: AssetClass = 'file';\n    private _assetType?: AssetType;\n    private _assetSubType?: AssetSubType;\n    private _assetState: AssetState = 'ACTIVE';\n    private _created: Date = new Date();\n    private _modified: Date = new Date();\n    private _lastAccessed?: Date;\n    private _shared?: Date;\n    private _discarded: Date | undefined;\n    private _createdBy: string = '';\n    private _modifiedBy: string = '';\n    private _discardedBy: string | undefined;\n    private _generationModelDisplayName: string | undefined;\n    // Assume user has full permissions for any Asset they run across, as it's better to\n    // err on allowing an action in the UI and have it fail on the service. Sources that\n    // require permission checks are responsible for ensuring the permissions are set\n    // appropriately.\n    private _permissions: Permission = PERMISSION_ALL;\n    protected __links: AssetLinks | undefined;\n    private _isPublished: boolean = false;\n    private _ancestorIDs: string[] | undefined;\n    private _storageAssignee: Assignee = { id: '', type: 'user' };\n    private _embeddedMetadata: EmbeddedMetadataResource;\n    private _appMetadata: AppMetadataResource;\n    private _effectivePermissionsResource = new EffectivePermissionsResource(this._core, this);\n    private _repoMetadataResource = new RepoMetadataResource(this._core, this);\n    /** @package -- only for use in SAM.js */\n    public _perUserMetadataResource: PerUserMetadataResource;\n    private _manifest: ManifestResource;\n    private _fileContent: FileContentResource;\n    private _renditionFetcher: RenditionFetcher;\n    private _renditionBlobHelper: RenditionBlobHelper;\n    private _hasArtifacts: boolean | undefined;\n    // Library Elements in USS discarded results are pseudo-Assets that are not in\n    // /cloud-content-archive and do not have state=DISCARDED. This ensures that these items only appear in discarded\n    // search results. In case Library Elements appear in other collections, we are not inferring that all Library\n    // Elements are discarded just because today the discarded list is the only place they appear.\n    private _isArchivedLibraryElement: boolean = false;\n    private _representations: Representations = { file: undefined, composite: undefined, directory: undefined };\n\n    /**\n     * A flag that prevents Resources from independently triggering logic after updates\n     * while we're explicitly loading via Asset._load().\n     */\n    private _isExplicitlyLoading = false;\n\n    // Base implementation, subclasses should override if they need to return true.\n    protected _needsRepoMetadata: boolean = false;\n\n    private fr: FinalizationRegistry<string>;\n    private _imageLength?: number;\n    private _imageWidth?: number;\n    private _createdByClientId?: string;\n\n    // SAM should never create an AdobeAsset for a project. Therefore isProject should always be false.\n    public isProject: boolean = false;\n    public isLibrary: boolean = false;\n    public isCustomModel: boolean = false;\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _versionPool = new ItemPool<AssetVersion>(this._core, 'version');\n\n    /**\n     * Determines if __links came from resolve API (true) or a listing (false)\n     * @package -- only for use in SAM.js\n     */\n    _linksCameFromResolveAPI: boolean = false;\n\n    /**\n     * If the asset is cached by ACPL, it will have a localID.\n     * (If it is also cloud-synced, it will have a cloudID too.)\n     * \"isAvailableOffline\" is an alias for localID being truthy.\n    */\n    private _localID?: string;\n    private _downloadStatus?: ITransferStatus;\n    private _uploadStatus?: ITransferStatus;\n    private _syncStatus?: AssetSyncStatus;\n    private _syncSuspensionReason?: AssetSyncSuspensionReason;\n    private _xmpNumberOfPages?: number;\n    private _pinnedVersion: string | undefined;\n    private _pinnedVersionModifyDate: Date | undefined;\n\n    /**\n     * A flag that indicates whether the asset is virtual.\n     * Virtual assets are assets that are not actual assets yet either because\n     * they are still offline or in their initial alternate state\n     * (e.g., NOT_STARTED StudentAssignment assets)\n     */\n    get isVirtual(): boolean {\n        return false;\n    }\n\n    get localID() {\n        return this._localID;\n    }\n\n    get isAvailableOffline() {\n        return Boolean(this._localID);\n    }\n\n    get downloadStatus() {\n        return this._downloadStatus;\n    }\n\n    get uploadStatus() {\n        return this._uploadStatus;\n    }\n\n    get syncStatus() {\n        return this._syncStatus;\n    }\n\n    get syncSuspensionReason() {\n        return this._syncSuspensionReason;\n    }\n\n    @observable\n    get xmpNumberOfPages() {\n        return this._xmpNumberOfPages;\n    }\n\n    // This field isn't useful for feature-detection, so hard-coding as false, which is a sensible value for web\n    isUserPinned: boolean = false;\n    // Expecting that a data migration will occur that makes this field obsolete. If that doesn't happen, then\n    // this field will need to be populated with an async call.\n    /**\n     * @deprecated -- will be removed on or after 2024-10-01\n     */\n    isNameDCTitle: boolean = false;\n    purge?(): Promise<void>;\n    pin?(): Promise<void>;\n    archive?(): Promise<void>;\n    /**\n     * SAM.cpp Only - not available on web.\n     * Downloads the  composite to the local cache\n     * but also respects cache clearing policies so it may\n     * be cleared at some point.\n     */\n    // end [SAM-2268][SAM-2494]\n\n    private _acplModelInterface = new ACPLModelInterface(this._core);\n\n    get downloadComposite(): (() => Promise<void>) | undefined {\n        if (this.isComposite && this._acplModelInterface.supportsDownloadComposite) {\n            return () => this._acplModelInterface.downloadComposite(this.cloudID);\n        }\n        return undefined;\n    }\n\n    get unpin(): (() => Promise<void>) | undefined {\n        if (this.isAvailableOffline && this._acplModelInterface.supportsUnpin) {\n            return () => this._acplModelInterface.unpin(this.cloudID);\n        }\n        return undefined;\n    }\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        id: string,\n        metadata?: {\n            links?: AssetLinks,\n            etag?: string\n        }\n    ) {\n        super(_core, id);\n        this._embeddedMetadata = new EmbeddedMetadataResource(_core, this);\n        this._appMetadata = new AppMetadataResource(_core, this);\n        this._perUserMetadataResource = new PerUserMetadataResource(_core, this);\n        this._manifest = new ManifestResource(_core, this);\n        this._effectivePermissionsResource = new EffectivePermissionsResource(this._core, this);\n        this._repoMetadataResource = new RepoMetadataResource(this._core, this);\n        this._fileContent = new FileContentResource(_core, this);\n        this.__links = metadata?.links;\n        this._etag = metadata?.etag || '';\n        this._renditionBlobHelper = new RenditionBlobHelper();\n        this._renditionFetcher = new RenditionFetcher(\n            this._core,\n            SUPPORTED_SIZES,\n            async (size: number, type: string) => {\n                const resource = new RenditionResource(this._core, this, size, type);\n                return this._renditionBlobHelper.fetch(resource);\n            }\n        );\n\n        // Forward change events from the rendition fetcher\n        // to this class.\n        this._renditionFetcher.on('change', () => {\n            this.dispatch({ type: 'change' });\n        });\n\n        // Create a weakReference to track if the\n        // the object has been GC'd\n        // Ensure working per https://jira.corp.adobe.com/browse/SAM-2677\n        this.fr = new FinalizationRegistry(() => {\n            this._finalizer();\n        });\n        this.fr.register(this, 'adobe-asset');\n\n        LazyLoadManager.manageLazyLoading(this, [ {\n            event: SharedStorageAssigneeChangedEvent,\n            fetchData: this._populateStorageAssignee\n        } ]);\n    }\n\n    /**\n     * A property that indicates whether or not a file was created from upload. If it's undefined\n     * that means it has not been set previously and doesn't necessarily mean\n     * that it was not created from an upload action in an application. Only a 'true' value\n     * can guarantee that this file was created from an upload action.\n     */\n    @observable\n    public get createdFromUpload(): boolean | undefined {\n        // If the data was provided by a USS result, return that result.\n        if (this.appMetadata.data?.['cc:createdFromUpload']) {\n            return !!this.appMetadata.data['cc:createdFromUpload'];\n        }\n        return undefined;\n    }\n\n    /**\n     * The ID of the client who created the repository asset.\n     */\n    @observable\n    public get createdByClientId(): string | undefined {\n        return this._createdByClientId;\n    }\n\n    private _getAssetContext(): AssetContext {\n        const assetContext = this._core._getAssetContext();\n        if (!assetContext) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'AdobeAsset was used outside of AssetContext and initializeSharedAssetModel() was not called first.'\n            );\n        }\n\n        // At this point we know for sure AssetContext exists\n        return assetContext!;\n    }\n\n    private _finalizer() {\n        this._renditionFetcher.release();\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    @retry\n    _loadWithRetry(): Promise<void> {\n        return this._load();\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    async _getAssetInterface(): Promise<AssetInterface> {\n        const assetContext = this._getAssetContext();\n        return new AssetInterface(assetContext._rapi, this.id, this.links, this.etag, this.preferredVersion);\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    @memoize\n    _getGenerationHistoryInterface(): GenerationHistoryInterface {\n        return new GenerationHistoryInterface(this._core);\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _getGenerationModelDisplayName(): string | undefined {\n        return this._generationModelDisplayName;\n    }\n\n    // These secondary resources are refreshed after load. (It excludes permissions and repoMetadata.)\n    private get _resources(): Map<keyof AdobeAsset, Resource<any>> {\n        return new Map<keyof AdobeAsset, Resource<any>>([\n            [ 'embeddedMetadata', this._embeddedMetadata ],\n            [ 'appMetadata', this._appMetadata ],\n            [ 'manifest', this._manifest ],\n            [ 'fileContent', this._fileContent ],\n        ]);\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    public _setResources(resources: {\n        repoMetadataResource?: RepoMetadataResource,\n        effectivePermissionsResource?: EffectivePermissionsResource,\n        appMetadataResource?: AppMetadataResource,\n        perUserMetadataResource?: PerUserMetadataResource,\n    }) {\n        if (resources.appMetadataResource) {\n            this._appMetadata = resources.appMetadataResource;\n            this._appMetadata.setParent(this);\n        }\n        if (resources.repoMetadataResource) {\n            this._repoMetadataResource = resources.repoMetadataResource;\n            this._repoMetadataResource.setParent(this);\n        }\n        if (resources.effectivePermissionsResource) {\n            this._effectivePermissionsResource = resources.effectivePermissionsResource;\n            this._effectivePermissionsResource.setParent(this);\n        }\n        if (resources.perUserMetadataResource) {\n            this._perUserMetadataResource = resources.perUserMetadataResource;\n            this._perUserMetadataResource.setParent(this);\n        }\n    }\n\n    async _reloadPermissions() {\n        await this._effectivePermissionsResource.load();\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    @synchronized\n    async _handleResourceUpdates({\n        repoMetadata,\n        effectivePermission,\n        perUserMetadata,\n        appMetadata,\n        error\n    }: {\n        repoMetadata?: Partial<RepositoryMetadata>,\n        effectivePermission?: Permission,\n        perUserMetadata?: IPerUserMetadata,\n        appMetadata?: IAppMetadata,\n        error?: SAMError\n    }) {\n        if (this._isExplicitlyLoading) {\n            return;\n        }\n\n        const assetMetadata: Partial<AdobeAssetUpdaterMetadata> = {\n            ...repoMetadata,\n        };\n\n        if (!error) {\n            if (repoMetadata) {\n                this._linksCameFromResolveAPI = true;\n            }\n\n            if (effectivePermission) {\n                assetMetadata.effectivePermission = effectivePermission;\n            }\n\n            if (appMetadata) {\n                this._appMetadata._setData(appMetadata);\n            }\n        } else {\n            // Check for the asset missing (404) or having restricted access (403)\n            if ([ SAMErrorCode.NOT_FOUND, SAMErrorCode.ACCESS_DENIED ].includes(error.code)) {\n                assetMetadata.effectivePermission = (error.code === SAMErrorCode.ACCESS_DENIED ? Permission.Ack : Permission.None);\n            } else {\n                throw error;\n            }\n        }\n        const assetContext = await this._getAssetContext();\n        const hasLostAccess = [ Permission.Ack, Permission.None ].includes(assetMetadata.effectivePermission!);\n        if (hasLostAccess && assetContext._assetPool.isItemDiscarded(this)) {\n            // The asset has already been removed from the asset pool so we can just\n            // skip any further updates. This typically means it's been permanently deleted.\n            this._isShared = false;\n            this._isSharedWithYouAsset = false;\n            this._shareFlagsAreDirty = false;\n            LazyLoadManager.setLoadStatus(this, SharedCollaboratorChangedEvent, LoadStatus.Loaded);\n            return;\n        }\n\n        const isFolder = assetMetadata['repo:assetClass'] === 'directory' || this.isFolder;\n\n        // A \"mutation\" session is used here to track the time when a change is made to an Asset that is known to be\n        // fresh (since it came from R-API). This helps avoid problems where fresh data from R-API gets overwritten by\n        // stale data (e.g. from USS due to indexing lag).\n        const session = assetContext._assetPool.createMutationSession();\n        if (isFolder && assetMetadata['repo:path'] && assetMetadata['repo:path'] !== this.repoPath) {\n            // If it's a directory, and its path changed, we also need to update the repo:path of all its children!\n            updateCachedDescendents({\n                assetContext,\n                assetPool: assetContext._assetPool,\n                asset: this,\n                session,\n                operation: { type: 'rename', newPath: assetMetadata['repo:path'] }\n            });\n        }\n\n        if (perUserMetadata) {\n            assetMetadata.perUserMetadata = perUserMetadata;\n        }\n\n        // We always update the asset with the new permissions even if it's\n        // been permanently deleted or permissions have been removed. This\n        // ensures subscribers to \"change\" events of AdobeAsset are notified\n        // AssetLink being one example.\n        if (hasLostAccess) {\n            // If the user lost access, it is effectively not shared with them anymore\n            assetMetadata.isShared = false;\n            assetMetadata.sharedViaInvite = false;\n            // Refreshing collaborators will likely fail, so clear the dirty flags to prevent the refresh.\n            assetMetadata.shareFlagsAreDirty = false;\n            LazyLoadManager.setLoadStatus(this, SharedCollaboratorChangedEvent, LoadStatus.Loaded);\n            session.queueDiscardedItem(this);\n        } else if (effectivePermission) {\n            // Since we are explicitly reloading the permissions we want to mark\n            // that the collaboration data is out of date which will\n            // fetch new data when the ShareableItem.collaboratorArray is read.\n            assetMetadata.shareFlagsAreDirty = true;\n            LazyLoadManager.setLoadStatus(this, SharedCollaboratorChangedEvent, LoadStatus.NotLoaded);\n        }\n\n        // Mark storage:assignee as loaded, if it has been set from assetMetadata,\n        // to avoid unnecessary lazy loading\n        if (assetMetadata['storage:assignee'] && this._storageAssignee_NoLazyLoad.id === assetMetadata['storage:assignee']!.id) {\n            LazyLoadManager.updatedByItemUpdater(this, STORAGE_ASSIGNEE_CHANGED);\n        }\n\n        assetContext._adobeAssetUpdater.updateLocalItem(\n            session,\n            this,\n            assetMetadata,\n        );\n\n        session.commit();\n    }\n\n    /**\n     * @param repoMetadata {RepositoryMetadata} If passed in, it will be used instead of loading from the service\n     * @param appMetadata {any} If passed in, it will be used instead of loading from the service\n     * @param effectivePermission {Permission} If passed in, it will be used instead of loading from the service\n     *\n     * @package -- only for use in SAM.js\n     */\n    async _load({\n        repoMetadata,\n        appMetadata,\n        effectivePermission,\n        perUserMetadata\n    }: {\n        repoMetadata?: RepositoryMetadata;\n        appMetadata?: any;\n        effectivePermission?: Permission;\n        perUserMetadata?: IPerUserMetadata;\n    } = {}): Promise<void> {\n        let error: any;\n\n        try {\n            // When we update both repoMetadata and effectivePermission resources together, we don't want them\n            // to independently handle the check for lost access in parallel. Instead, we just update the resources here,\n            // and then handle the results of those updates in one go.\n            this._isExplicitlyLoading = true;\n\n            // In order to make sure that we have the links required to load individual resources,\n            // If both repoMetadata and effectivePermissions are not provided, we will fetch the links first\n            // to make sure we don't make parallel calls for getting the links while loading the resources.\n            // we will use REPO_METADATA relType to ensure that the links are present.\n            if (!repoMetadata && !effectivePermission) {\n                await this._ensureLink(RelType.REPO_METADATA);\n            }\n            await Promise.allSettled([\n                repoMetadata ? this._repoMetadataResource._setData(repoMetadata) : this._repoMetadataResource.load(),\n                effectivePermission ? this._effectivePermissionsResource._setData(effectivePermission) : this._effectivePermissionsResource.load()\n            ]);\n        } catch (e) {\n            error = e;\n        } finally {\n            this._isExplicitlyLoading = false;\n        }\n\n        error = error ?? this._repoMetadataResource.error ?? this._effectivePermissionsResource.error;\n\n        if (!error) {\n            if (![ Permission.Ack, Permission.None ].includes(this._permissions)) {\n                if (!perUserMetadata) {\n                    await this._ensureLink(RelType.PERUSER_METADATA);\n                }\n                if (!isTopLevelFolder(this.repoPath)) {\n                    // For non-top-level folders, do the full parallel loading\n                    await Promise.all([\n                        this._refreshLoadedResources(appMetadata),\n                        perUserMetadata ? this._perUserMetadataResource._setData(perUserMetadata) : this._perUserMetadataResource.load()\n                    ]);\n                }\n            }\n\n            await this._handleResourceUpdates({\n                repoMetadata: this._repoMetadataResource.data,\n                effectivePermission: this._effectivePermissionsResource.data,\n                perUserMetadata: this._perUserMetadataResource.data\n            });\n            // Now that repoMetadata has been fetched directly, we can clear the flag.\n            this._needsRepoMetadata = false;\n        } else {\n            await this._handleResourceUpdates({\n                error,\n            });\n        }\n    }\n\n    /** @package -- only for use in SAM.js */\n    async _loadRepoMetadata(): Promise<void> {\n        await this._repoMetadataResource.load();\n    }\n\n    /** @package -- only for use in SAM.js */\n    _setNeedsRepoMetadata(needsRepoMetadata: boolean): void {\n        this._needsRepoMetadata = needsRepoMetadata;\n    }\n\n    private async _refreshLoadedResources(appMetadata?: any): Promise<void> {\n        // Refresh any resources that are already loaded\n        const resourcesToReload: Resource<any>[] = [ ...this._resources.values() ].filter(resource => resource.isLoaded);\n        // If shellVisibility is undefined, then app metadata must be loaded to ensures hidden Assets do not\n        // appear in lists due to ONS notifications.\n        if (this.shellVisibility === undefined\n            // Root folders don't show up in lists anyway, so no need to check shell:visibility\n            && !APP_METADATA_REFRESH_IGNORE_REGEX.test(this.repoPath)\n            // Already scheduled to reload\n            && !resourcesToReload.includes(this._appMetadata)\n            // Do we have the permission (cannot use hasPermission() because Projects have separate permissions)\n            && (this._permissions & Permission.ReadAppMetadata) === Permission.ReadAppMetadata\n        ) {\n            resourcesToReload.push(this._appMetadata);\n        }\n\n        // If the app metadata is passed in, use it instead of loading it again\n        if (appMetadata) {\n            // setting the data also sets isLoaded to true\n            await this._appMetadata._setData(appMetadata);\n            // Remove the app metadata from the list of resources to reload\n            const index = resourcesToReload.indexOf(this._appMetadata);\n            if (index !== -1) {\n                resourcesToReload.splice(index, 1);\n            }\n        }\n        if (resourcesToReload.length) {\n            // Use APP_METADATA to ensure that the links are present as it is probably the most common resource to load\n            await this._ensureLink(RelType.APP_METADATA);\n            await Promise.all(resourcesToReload.map(resource => resource.load()));\n        }\n    }\n\n    /**\n     * @TODO_Deprecation on or after 2025-01-01. Use {@link getVersions} instead\n     */\n    @memoize\n    get versions(): AssetVersionSource {\n        const loader = new AssetVersionLoader(this._versionPool, this._ensureLink(RelType.PAGE).then(() => this._getAssetInterface()));\n        return new ItemSource(this._versionPool, [ loader ], new AssetVersionFilter());\n    }\n\n    async getVersions(): Promise<AssetVersionSource> {\n        return this.versions;\n    }\n\n    async getVersion(versionId: string): Promise<AssetVersion | undefined> {\n        const localVersion = this._versionPool.getLocalItemById(versionId);\n        if (localVersion) {\n            return localVersion;\n        }\n\n        await this._ensureLink(RelType.PAGE);\n        const assetInterface = await this._getAssetInterface();\n        const versionPageResults = await assetInterface.getVersion(versionId);\n        // Because we are passing the versionId to the getVersion API, it will return\n        // a page with only one version, if that version doesn't exist, it will return an empty\n        // children result.\n        const versionMetadata = versionPageResults.children[0];\n        if (!versionMetadata) {\n            return undefined;\n        }\n\n        const session = this._versionPool.createUpdateSession();\n        const version = await VersionUpdater.updateRemoteItem(session, {\n            ...versionMetadata,\n            assetId: this.id,\n            assetEtag: this.etag,\n            assetLinks: this.links\n        });\n\n        session.commit();\n        return version;\n    }\n\n    /**\n     * Sets a milestone on a specific version of the asset.\n     * A milestone is a way to mark and label important versions of an asset.\n     *\n     * @param options - Configuration options for the milestone.\n     * @param options.label - The label for the milestone (defaults to '').\n     * @param options.description - The description for the milestone (defaults to '').\n     * @param options.versionId - The version ID to set the milestone on (defaults to the current version).\n     * @returns {Promise<void>} A promise that resolves when the milestone is set\n     * @example\n     * // Set milestone on current version with only a label\n     * await asset.setVersionAsMilestone({ label: 'Final Version' });\n     * @example\n     * // Set milestone on specific version with label and description\n     * await asset.setVersionAsMilestone({ label: 'Initial Design', description: 'First draft', versionId: '1' });\n     * @example\n     * // Set milestone on specific version with only a description\n     * await asset.setVersionAsMilestone({ description: 'Approved', versionId: '2' });\n     */\n    async setVersionAsMilestone(options: IVersionMilestone = {}) {\n        const { label = '', description = '', versionId = this.version } = options;\n        const assetInterface = await this._getAssetInterface();\n        const jsonParams = createMilestoneJsonParams(\n            versionId,\n            // Since we don't know if the version is a milestone or not, we set hasExistingMilestone to false\n            // which will cause 'op: add' to be used in the patch. This works for both cases.\n            false,\n            label,\n            description\n        );\n        await assetInterface.patchVersion(jsonParams);\n\n        // Update the local version with the new milestone data it it's there.\n        const existingVersion = this._versionPool.getLocalItemById(versionId);\n        if (existingVersion) {\n            const session = this._versionPool.createUpdateSession();\n            VersionUpdater.updateLocalItem(session, existingVersion, {\n                milestone: {\n                    label,\n                    description\n                }\n            });\n            session.commit();\n        }\n    }\n\n    async getCommentsResource(): Promise<CommentsResource> {\n        const assetContext = this._getAssetContext();\n        return assetContext.getCommentsResource(this.id);\n    }\n\n    @observable\n    get assetType(): AssetType | undefined {\n        return this._assetType;\n    }\n\n    @observable\n    get assetSubType(): AssetSubType | undefined {\n        return this._assetSubType;\n    }\n\n    @observable\n    get isFolder(): boolean {\n        return this._assetClass === 'directory';\n    }\n\n    @observable\n    get isAssignment(): boolean | undefined {\n        // if appMetadata isn't loaded, it's not yet known\n        return this.appMetadata.data ? this.appMetadata.data['project:directoryType'] === 'assignment' : undefined;\n    }\n\n    @observable\n    get isBoard(): boolean {\n        return this._type === boardMediaTypeString;\n    }\n\n    @observable\n    get isFile(): boolean {\n        return this._assetClass === 'file';\n    }\n\n    @observable\n    get isStudentAssignment(): boolean | undefined {\n        // [ACPCEDU-3811] will determine longer-term approach to reliably getting this information\n        return this.appMetadata.data ? !!this.appMetadata.data['cc:inheritable']?.['cc:studentAssignment']?.['repo:assetId'] : undefined;\n    }\n\n    @observable\n    get isComposite(): boolean {\n        return this._assetClass === 'composite';\n    }\n\n    @observable\n    get isLibraryElement(): boolean {\n        return this._assetClass === 'element';\n    }\n\n    @observable\n    get isOwnCreation(): boolean | undefined {\n        return this.createdBy ? this.createdBy === this._core._environment.getUserId() : undefined;\n    }\n\n    @observable\n    get imageLength(): number | undefined {\n        return this._imageLength;\n    }\n\n    @observable\n    get imageWidth(): number | undefined {\n        return this._imageWidth;\n    }\n\n    // Similar to Project, we rely on app metadata to determine if an asset is a child of an assignment.\n    // If app metadata is not loaded, then we don't know if it has a parent assignment id and it is undefined.\n    @observable\n    get parentAssignmentID(): string | undefined {\n        const parentAssignmentID = this.appMetadata.data?.['cc:inherited']?.['cc:assignment']?.['repo:assetId'];\n        if (parentAssignmentID) {\n            return parentAssignmentID;\n        }\n        // If inheritance metadata is missing, fallback to fetching the parent Assignment folder asset ID\n        // This is susceptible to breaking if the nesting of EDU assets change\n        // [ACPCEDU-3811] will determine longer-term approach\n        if (this.ancestorIDs && this.ancestorIDs.length > 0) {\n            if (isMaterialsFilePath({ repoPath: this.repoPath })) {\n                // Assumes assignment material file asset ancestors are: [..., Assignment, Materials]\n                return this.ancestorIDs.at(-2);\n            }\n            if (isStudentAssignmentFilePath({ repoPath: this.repoPath })) {\n                // Assumes ancestors are: [..., Assignment, Students, StudentAssignment]\n                return this.ancestorIDs.at(-3);\n            }\n        }\n        return undefined;\n    }\n\n    // Similar to isChildOfProject\n    @observable\n    get isChildOfAssignment(): boolean {\n        return !!this.parentAssignmentID;\n    }\n\n    @observable\n    get parentClassroomId(): string | undefined {\n        const parentClassroomId = this.appMetadata.data?.['cc:inherited']?.['cc:classroom']?.['repo:assetId'];\n        if (parentClassroomId) {\n            return parentClassroomId;\n        }\n        // If inheritance metadata is missing, fallback to fetching the parent Classroom folder asset ID\n        // This is susceptible to breaking if the nesting of EDU assets change\n        // [ACPCEDU-3811] will determine longer-term approach\n        if (this.ancestorIDs && this.ancestorIDs.length > 0) {\n            if (isStudentAssignmentFilePath({ repoPath: this.repoPath })) {\n                // Assumes StudentAssignment asset ancestors are: [..., Classroom, Assignments, Assignment, Students, StudentAssignment]\n                return this.ancestorIDs.at(-5);\n            }\n            if (isMaterialsFilePath({ repoPath: this.repoPath })) {\n                // Assumes assignment material file asset ancestors are: [..., Classroom, Assignments, Assignment, Materials]\n                return this.ancestorIDs.at(-4);\n            }\n        }\n        return undefined;\n    }\n\n    @observable\n    get parentClassroomName(): string | undefined {\n        const parentClassroomName = this.appMetadata.data?.['cc:inherited']?.['cc:classroom']?.['repo:name'];\n        if (parentClassroomName) {\n            return parentClassroomName;\n        }\n        // If inheritance metadata is missing, fallback to fetching the parent Classroom folder name from the path\n        // This is susceptible to breaking if the nesting of EDU assets change\n        // [ACPCEDU-3811] will determine longer-term approach\n        if (isStudentAssignmentFilePath({ repoPath: this.repoPath })) {\n            return getClassroomNameFromSAFPath(this.repoPath);\n        }\n        if (isMaterialsFilePath({ repoPath: this.repoPath })) {\n            return getClassroomNameFromMaterialsFilePath(this.repoPath);\n        }\n        return undefined;\n    }\n\n    @observable\n    get isChildOfClassroom(): boolean {\n        return !!this.parentClassroomId;\n    }\n\n    @observable\n    get parentAssignmentMaterialsId(): string | undefined {\n        const parentAssignmentMaterialsId = this.appMetadata.data?.['cc:inherited']?.['cc:assignmentMaterials']?.['repo:assetId'];\n        if (parentAssignmentMaterialsId) {\n            return parentAssignmentMaterialsId;\n        }\n        // If inheritance metadata is missing, fallback to fetching the parent Materials folder asset ID\n        // This is susceptible to breaking if the nesting of EDU assets change\n        // This approach assumes that all Materials files live directly in the Materials folder\n        // AND are the only children of a Materials folder\n        // [ACPCEDU-3811] will determine longer-term approach\n        if (this.ancestorIDs && this.ancestorIDs.length > 0 && isMaterialsFilePath({ repoPath: this.repoPath })) {\n            // Assumes materials file asset ancestors are: [..., Materials]\n            return this.ancestorIDs.at(-1);\n        }\n        return undefined;\n    }\n\n    @observable\n    get isChildOfAssignmentMaterials(): boolean {\n        return !!this.parentAssignmentMaterialsId;\n    }\n\n    @observable\n    get parentStudentAssignmentId(): string | undefined {\n        const parentStudentAssignmentId = this.appMetadata.data?.['cc:inherited']?.['cc:studentAssignment']?.['repo:assetId'];\n        if (parentStudentAssignmentId) {\n            return parentStudentAssignmentId;\n        }\n        // If inheritance metadata is missing, fallback to fetching the parent StudentAssignment asset ID\n        // This is susceptible to breaking if the nesting of EDU assets change\n        // This approach assumes that all StudentAssignment files live directly in the StudentAssignment folder\n        // AND are the only children of a StudentAssignment\n        // [ACPCEDU-3811] will determine longer-term approach\n        if (this.ancestorIDs && this.ancestorIDs.length > 0 && isStudentAssignmentFilePath({ repoPath: this.repoPath })) {\n            return this.ancestorIDs.at(-1);\n        }\n        return parentStudentAssignmentId;\n    }\n\n    /**\n     * Assets that are StudentAssignmentFiles may start out cached\n     * as an AdobeAsset when the asset initially exists outside EDU assets.\n     * This getter is equivalent to parentStudentAssignmentId but will be used\n     * when the client is working with a list of StudentAssignmentFiles and AdobeAssets\n     * */\n    @observable\n    get studentAssignmentId(): string | undefined {\n        return this.parentStudentAssignmentId;\n    }\n\n    @observable\n    get isChildOfStudentAssignment(): boolean {\n        return !!this.parentStudentAssignmentId;\n    }\n\n    /**\n     * Returns true if the asset path is inside of a project, otherwise undefined.\n     */\n    private _isPathInsideProject(): boolean {\n\n        // It is assumed that the folder and filenames have already been validated\n        // as these regular expressions allow for invalid characters.\n        const projectChildPatterns = [\n            '/projects/[^/]+/[^/]+',\n            '/content/assets/projects/[^/]+/[^/]+',\n            '/users/[^/]+/projects/[^/]+/[^/]+'\n        ];\n        return projectChildPatterns.some(pattern => new RegExp(pattern).test(this._path));\n    }\n\n    // We rely on app metadata to determine if an asset is a child of a project.\n    // If app metadata is not loaded, then we don't know if it has a parent project id and it is undefined.\n    @observable\n    get parentProjectID(): string | undefined {\n        // EBroker handling will ensure that all descendants have the following, corresponding, application metadata property\n        const parentProjectID = this.appMetadata.data?.['cc:inherited']?.['cc:team']?.['repo:assetId'];\n\n        // [SAM-3590] If the parent project ID is not found in the app metadata or the ancestorIDs array,\n        // and it's inside a project, call the Context API to obtain the parent projet ID.\n        const parentIsMissingFromAncestorIDs = this._ancestorIDs && !this._ancestorIDs.includes(parentProjectID);\n\n        // Don't call fixParentProjectID too early after creating an asset because the appMetadata\n        // might not have loaded yet, using 30 seconds as a threshold.\n        const createTimeAgoMs = Date.now() - (this.created?.getTime() || Date.now());\n\n        if ((!parentProjectID || parentIsMissingFromAncestorIDs) && this._isPathInsideProject() && createTimeAgoMs > 30000) {\n            this._fixParentProjectID();\n        }\n        return parentProjectID;\n    }\n\n    /**\n     * Fix the parentProjectID in appMetadata and then notify clients.\n     */\n    @memoize\n    private async _fixParentProjectID(): Promise<void> {\n        const projectContext = await this._core.getProjectContext();\n        const response = await projectContext._callContextAPI(this.cloudID, this.repositoryID);\n        // Fix app metadata from response.\n        const parentProjectID = response['repo:assetId'];\n        if (parentProjectID) {\n            // Update the app metadata with the parent project ID.\n            this.appMetadata._mergeData({ 'cc:inherited': { 'cc:team': { 'repo:assetId': parentProjectID } } });\n        }\n    }\n\n    @observable\n    get isChildOfProject(): boolean {\n        return !!this.parentProjectID;\n    }\n\n    async isChildOfCSCProject(): Promise<boolean> {\n        if (!this.isChildOfProject) {\n            return false;\n        }\n\n        const projectId = this.parentProjectID;\n        const projectContext = await this._core.getProjectContext();\n        const project = await projectContext.getProjectbyID(projectId!, false);\n\n        return [\n            ProjectDirectorySubtype.WF_PROJECT,\n            ProjectDirectorySubtype.WF_PORTFOLIO,\n            ProjectDirectorySubtype.WF_PROGRAM,\n            ProjectDirectorySubtype.WF_TEMPLATE\n        ].includes(project.directorySubtype);\n    }\n\n    @observable\n    get isArtifact(): boolean | undefined {\n        // if appMetadata isn't loaded, it's not yet known\n        if (!this.appMetadata.data) {\n            return undefined;\n        }\n        // if `review:sourceAsset` is present, then it's an Artifact\n        return !!this.appMetadata.data['review:sourceAsset'];\n    }\n\n    /**\n    * Determines if the repo metadata needs to be loaded.\n    * @TODO_Deprecation - mark deprecated on/after 2025-03-01, remove on/after 2025-06-01\n    * @package -- only for use in SAM.js.\n    */\n    get needsRepoMetadata(): boolean {\n        // We may not have complete repoMetadata for the asset in two cases:\n        // 1. The asset is a specialized subclass that requires the full repoMetadata\n        // 2. The asset was loaded from ACPL and doesn't have full metadata yet.\n        return this._needsRepoMetadata;\n    }\n\n    // NOTE: isReviewLink includes legacy items that are not Artifacts\n    get isReviewLink(): boolean | undefined {\n        // legacy reviews were published in /pubs but might not have review:sourceAsset app metadata\n        if (this.repoPath.startsWith('/pubs/')) { return true; }\n        return this.isArtifact;\n    }\n    /**\n    * Returns the media type of the source document used to generate this Review Link. If not a Review Link, or no\n    * source document can be identified, it will return ''\n    * Hard coding these strings was a conscious decision to avoid enums and the hardening any logic around mediaTypes\n    * because they are still evolving. The ideal solution is for no app-specific logic here, we want to simply reference\n    * appMetadta['review:sourceAsset']['dc:format'] for all artifacts.\n    */\n    get reviewLinkSourceType(): string {\n        if (!this.isReviewLink) { return ''; }\n\n        // current S4R-compliant artifacts store the source type in app metadata\n        const dcFormat: string = this.appMetadata.data?.[AppMetadataField.REVIEW_SOURCE_ASSET]?.['dc:format']; // dcFormat equates to mediaType\n        if (dcFormat) {return dcFormat;}\n\n        // XD review links for \"prototype\" and \"spec\"\n        if ([\n            'application/vnd.adobe.xd.sharedartifact+dcx',\n            'application/vnd.adobe.xd.cloudproject+dcx'\n        ].includes(this.mediaType)) {\n            // Assuming the source was \"cloudproject\" and not \"sharedartifact\" since it doesn't make sense to have an\n            // artifact be the source of an artifact.\n            return 'application/vnd.adobe.xd.cloudproject+dcx';\n        }\n\n        // legacy Aero links are in /pubs/aero/v5/ -- return Aero media type\n        if (this.repoPath.startsWith('/pubs/aero/v5/')) { return 'application/vnd.adobe.real+dcx'; }\n\n        // Legacy InDesign artifacts may be in /pubs/id_review\n        // TODO: not sure what the media type of the source docs for legacy artifacts are\n        if (this.repoPath.startsWith('/pubs/id_review/')) { return 'legacy-INDD'; }\n\n        // legacy 3d scenes are in /pubs/<review creator ID> (to be confirmed) -- return media type (needs research)\n        if (this.repoPath.startsWith('/pubs/')) { return '3d/vnd.adobe.asd+dcx'; }\n\n        return '';\n    }\n\n    // NOTE: this should only ever be the repo:name of the Asset. For user-friendly names, use `displayName`\n    @observable\n    get name(): string {\n        // NOTE: includes file extension\n        return removeArchiveGuidFromName(this._name);\n    }\n\n    // Subclasses should override if the user-facing name is something other than repo:name. Do not return `this.name`\n    // (the repo:name) as displayName, as in some cases, that might be a guid that the client may want to exclude, in\n    // which case the client would have to write a regex to hide guids...but if a user chooses a guid as a file name,\n    // that'd cause the user's legit file name to be hidden. Keeping these concepts distinct will ensure clients can\n    // have full control over their UI.\n    get displayName(): string | undefined {\n        return undefined;\n    }\n\n    // NOTE: when _appMetadata changes, it won't trigger any observers of shellVisibility to update. But since\n    // shellVisibility shouldn't change after initial load (from listing, or getAssetWith*()), this isn't currently\n    // necessary. If it becomes necessary, we'll need to have AdobeAsset fire a change even when _appMetadata changes.\n    @observable\n    get shellVisibility(): ShellVisibility | undefined {\n        // If _appMetadata.data is undefined, then it has not been loaded from listings or\n        // by _appMetadata.load(), so shell visibility is unknown.\n        if (this._appMetadata.data === undefined) { return undefined; }\n        // '' means that the shell:visibility is known to be visible\n        return this._appMetadata.data['shell:visibility'] || '';\n    }\n\n    @observable\n    get ancestorIDs(): string[] | undefined {\n        return this._ancestorIDs;\n    }\n\n    @lazyLoaded(SharedStorageAssigneeChangedEvent, '_storageAssignee')\n    get storageAssignee(): Assignee {\n        return this._storageAssignee;\n    }\n\n    /**\n     * @package, used internally by filters, tests, etc.\n     */\n    get _storageAssignee_NoLazyLoad(): Assignee {\n        return this._storageAssignee;\n    }\n\n    @observable\n    get extension(): string {\n        // To match SAM C++, extension does not include the \".\"\n        // Do not return extension if file name starts with '.'\n        if (this.name.lastIndexOf('.') > 0 && !this.isFolder) {\n            return this.name.substring(this.name.lastIndexOf('.') + 1);\n        } else {\n            return '';\n        }\n    }\n\n    @observable\n    get mediaType(): string {\n        return this._type;\n    }\n\n    @observable\n    get cloudID(): string {\n        return this.id;\n    }\n\n    @observable\n    get repositoryID(): string {\n        return this._repositoryID;\n    }\n\n    @observable\n    get repositoryName(): string | undefined {\n        if (this._repositoryName === undefined) {\n            this._populateRepositoryName();\n        }\n\n        return this._repositoryName;\n    }\n\n    @observable\n    get repoPath(): string {\n        // TODO: Switch to new repo:relativePath once implemented by platform\n        return this._path;\n    }\n\n    @observable\n    get storageRegion(): string {\n        return this._storageRegion;\n    }\n\n    @observable\n    get created(): Date {\n        return this._created;\n    }\n\n    @observable\n    get modified(): Date {\n        return this._modified;\n    }\n\n    // returns the last access date for the user.\n    // returns undefined if last access date is not set or the asset is not\n    // populated via USS.\n    @observable\n    get lastAccessed(): Date | undefined {\n        return this._lastAccessed;\n    }\n\n    @observable\n    get isFavorite(): boolean | undefined {\n        return this._isFavorite;\n    }\n\n    async setIsFavorite(isFavorite: boolean): Promise<void> {\n        const gqlManager = await this._core._getGQLManager();\n        await gqlManager.setFavorite(this.id, isFavorite);\n\n        const assetContext = this._getAssetContext();\n        const assetPool = this._core._getAssetPool();\n        const session = assetPool.createUpdateSession();\n        assetContext._adobeAssetUpdater.updateLocalItem(\n            session,\n            this,\n            { isFavorite }\n        );\n        session.commit();\n    }\n\n    /**\n     * Update lastAccessed Per User Per Asset (PUPA) metadata\n     * @param {boolean} clear (optional) Pass `true` to clear the lastAccessedDate on folders\n     * @returns {Promise<void>}\n     */\n    async updateLastAccessed(clear?: boolean): Promise<void> {\n        if (clear && !this.isFolder) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Can only clear lastAccessed for folders');\n        }\n\n        const accessDate = new Date();\n        // we use the link to clear the last access date\n        // and the PLS API to update the last access date as PLS does not support clearing the last access date\n        // https://jira.corp.adobe.com/browse/SYSE-19734\n        if (clear) {\n            await this._ensureLink(RelType.PERUSER_METADATA);\n            const assetInterface = await this._getAssetInterface();\n            await assetInterface.removeLastAccessed();\n        } else {\n            // Update last access date using the PLS API\n            const gqlManager = await this._core._getGQLManager();\n            await gqlManager.updateLastAccessed(this.id, accessDate.toISOString());\n        }\n\n        const assetContext = this._getAssetContext();\n        const assetPool = this._core._getAssetPool();\n        const session = assetPool.createUpdateSession();\n        assetContext._adobeAssetUpdater.updateLocalItem(\n            session,\n            this,\n            {\n                perUserMetadata: {\n                    'shell:lastAccessDate': clear ? null : accessDate.toISOString(),\n                }\n            }\n        );\n        session.commit();\n    }\n\n    @observable\n    get shared(): Date | undefined {\n        return this._shared;\n    }\n\n    @observable\n    get sizeInBytes(): number {\n        return this._size;\n    }\n\n    @observable\n    get isDiscarded(): boolean {\n        return this._isArchivedLibraryElement\n            || getRestorePath(this.repoPath) !== undefined\n            || [ 'DISCARDED', 'DISCARDED_PARENT' ].includes(this._assetState);\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _isDiscardedWithParent(): boolean {\n        return this._assetState === 'DISCARDED_PARENT';\n    }\n\n    @observable\n    get assetRefString(): string {\n        return JSON.stringify({\n            cloud_id: this.cloudID,\n            path: this.repoPath,\n            display_name: this.name,\n            repository_id: this.repositoryID\n        });\n    }\n\n    @observable\n    get isPublished(): boolean {\n        return this._isPublished;\n    }\n\n    @observable\n    get representations(): Representations {\n        return this._representations;\n    }\n\n    @memoize\n    get children(): AdobeAssetSource | undefined {\n        if (!this.isFolder) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Children list can be fetched only for folder');\n        }\n        // https://jira.corp.adobe.com/browse/SAM-3206\n        // We will embed permissions for projects and children of projects\n        const embedPermissions = this.isProject || this.isChildOfProject;\n        const loader = new AdobeAssetDirectoryLoader(this._core._getAssetPool(), this, this._core, embedPermissions);\n        // Children of Project folders can be SWY items\n        const implicitFilter = new ImplicitDirectoryListingFilter({ asset: this, _isSharedWithYou: true  });\n        const assetPool = this._core._getAssetPool();\n        const localAssetLoader = new LocalAssetLoader<AdobeAssetConfig>(assetPool, this._core);\n        return new ItemSource(assetPool, [ loader, localAssetLoader ], implicitFilter);\n    }\n\n    searchChildren(opts: { deepSearch?: boolean, query?: string}): AdobeAssetSearchSource {\n        if (!this.isFolder) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Children can be searched only in the folder');\n        }\n\n        const { deepSearch, query } = opts;\n        const implicitFilter = new AdobeAssetSearchFilter({ asset: this, deepSearch, query });\n        const assetContext = this._getAssetContext();\n        const loader = new AdobeAssetDirectorySearchLoader(\n            this._core._getAssetPool(),\n            this._core,\n            assetContext._adobeAssetSearchInterface,\n            this,\n            implicitFilter\n        );\n        return new ItemSource(this._core._getAssetPool(), [ loader ], implicitFilter);\n    }\n\n    handleOnsChangedResources(changedResources: ONSChangedAssetInfo['changedResources']) {\n        // NOTE: if overriding this method in subclasses, please make a utility for parsing the\n        // ONSChangedResources to encapsulate in case it changes/reduce errors in implementation.\n        if (changedResources?.includes('api:metadata/repository')) {\n            this._repoMetadataResource.isDirty = true;\n            // TODO: bypass loading app metadata if changedResources includes api:metadata/application\n            // TODO: bypass permission refresh if changedResources includes api:ac/policy\n            // https://jira.corp.adobe.com/browse/SAM-3499\n            this._loadWithRetry();\n        }\n        if (changedResources?.includes('api:metadata/application')) {\n            this._appMetadata.isDirty = true;\n            this.appMetadata.load();\n        }\n        if (changedResources?.includes('api:ac/policy')) {\n            // Load the permissions and set collaborator data dirty flags.\n            this._effectivePermissionsResource.isDirty = true;\n            this._reloadPermissions();\n        }\n    }\n\n    /**\n     * Discard the asset - this changes its repo:state to DISCARDED, but it's still present as an\n     * asset, and can later be restored, or permanently deleted.\n     */\n    async discard(): Promise<void> {\n        if (this.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Asset is already discarded');\n        }\n        const assetInterface = await this._getAssetInterface();\n        const repoMetadata = await assetInterface.discard();\n        const assetContext = this._getAssetContext();\n\n        if (isGenerationHistoryAsset(this)) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'Generation History Assets do not currenlty support discard, use permanentlyDelete()'\n            );\n        }\n\n        // Artifacts are from Share For Review, for assets where you can create a Review artifact via the Share For Review workflow\n        if (this._hasArtifacts) {\n            // NOTE: this is done in the background and if it fails will not count as a failure\n            // for discard. This also means when `discard()` resolves, the output folder may not\n            // be deleted yet.\n            assetContext._deleteAssetOutputsFolder(this);\n        }\n\n        if (repoMetadata) {\n            const assetPool = this._core._getAssetPool();\n            // Use response metadata to reflect the new state of the Asset\n            const session = assetPool.createUpdateSession();\n            assetContext._adobeAssetUpdater.updateLocalItem(session, this, repoMetadata);\n\n            if (this.isFolder) {\n                // If it's a directory, we also need to update the repo:state of all its children.\n                updateCachedDescendents({\n                    assetPool,\n                    asset: this,\n                    session,\n                    operation: { type: 'discard' },\n                    assetContext\n                });\n            }\n\n            session.commit();\n        }\n    }\n\n    /**\n     * Simple getter to see if the flag for the outputs folder has been set\n     * requires calling AssetContext.assetsHaveArtifacts() before reading this value.\n     */\n    @observable\n    get hasArtifacts(): boolean | undefined {\n        return this._hasArtifacts;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _clearRepositoryName() {\n        this._repositoryName = undefined;\n    }\n\n    private async _populateRepositoryName(): Promise<void> {\n        if (this._repositoryName) {\n            return;\n        }\n        const assetContext = this._getAssetContext();\n        const assetPool = this._core._getAssetPool();\n        const repositoryName = await assetContext._repositoryNameFromID(this._repositoryID);\n        if (repositoryName) {\n            const session = assetPool.createUpdateSession();\n            assetContext._adobeAssetUpdater.updateLocalItem(session, this, { repositoryName });\n            session.commit();\n        }\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     *\n     */\n    private async _populateStorageAssignee(): Promise<void> {\n        const storageAssignee = await this._core.hostAssetContext._getStorageAssigneeFromID(this._repositoryID);\n        if (storageAssignee) {\n            this._storageAssignee = storageAssignee;\n        }\n    }\n\n    /**\n     * Creates a folder asset inside this folder.\n     * @param name The name of the new folder.\n     * @param options Configuration options for creating the folder\n     * @param options.renameOnConflict If true, a new name will be generated for the file (by ACP) if the name already exists, otherwise it will throw an error.\n     * @param counter @deprecated This argument is no longer used and will be removed in a future version.\n     * @returns The newly created folder asset.\n     */\n    async createFolder(\n        name: string,\n        options?: CreateFolderOptions | boolean,\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        counter: number = 0\n    ): Promise<AdobeAsset> {\n        if (!this.isFolder) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Asset is not Folder');\n        }\n        if (!validatePlatformRepoName(name)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for asset create folder operation.');\n        }\n\n        const renameOnConflict = (typeof options === 'boolean') ? options : options?.renameOnConflict === true;\n\n        const relativePath = name;\n        await this._ensureLink(RelType.CREATE);\n        const assetInterface = await this._getAssetInterface();\n        const newFolderMetaData = await assetInterface.createFolder(relativePath, renameOnConflict);\n        const assetContext = this._getAssetContext();\n        if (newFolderMetaData) {\n            if (this.isProject || this.isChildOfProject) {\n                addProjectIdToMetadata(newFolderMetaData, this.isChildOfProject ? this.parentProjectID! : this.id);\n            }\n            return assetContext._createAssetFromMetadata(newFolderMetaData);\n        }\n        return await assetContext.getAssetWithRepoPath(`${this.repoPath}/${relativePath}`, this.repositoryID);\n    }\n\n    /**\n     * A small private helper to update the createdFromUpload data and PUPA.\n     * @param uploadedAsset The asset that was newly created.\n     * @package Used only internally.\n     */\n    async _setCreatedFromUploadData() {\n        await this.patchAppMetadata([ { op: 'add', path: '/cc:createdFromUpload', value: true } ]);\n        // Update last accessed to make it easier for clients to sort/filter uploaded files.\n        await this.updateLastAccessed();\n    }\n\n    /**\n     * Imports a file into this folder asset.\n     *\n     * Will automatically choose between direct upload and block upload, depending on file size.\n     *\n     * @param options - Configuration options for importing the file\n     * @param options.file - The file blob to import\n     * @param options.name - The name of the file to be uploaded\n     * @param options.mediaType - The media type of the file to be uploaded\n     * @param options.renameOnConflict - If true, a new name will be generated for the file (by ACP) if the name already exists, otherwise it will throw an error\n     * @param options.setCreatedFrom - If true, sets the createdFromUpload property to true. Defaults to true\n     * @param options.preferredBlockTransferThreshold - Specifies the preferred block transfer threshold. Defaults to DEFAULT_MAX_SINGLE_TRANSFER_SIZE\n     * @param options.useBlockStore - If true, specifies that the file should be uploaded using the \"block store\" variant of block uploads (more efficient for large files)\n     * @param options.retryOnConflict - (deprecated) Use renameOnConflict instead\n     * @param options.counter - (deprecated) This property is ignored and will be removed in a future version\n     *\n     * @example\n     * // Import a file with basic options\n     * await folder.importFile({\n     *   file: myFileBlob,\n     *   name: 'my-file.jpg',\n     *   mediaType: 'image/jpeg'\n     * });\n     *\n     * // Import a file with all options\n     * await folder.importFile({\n     *   file: myFileBlob,\n     *   name: 'my-file.jpg',\n     *   mediaType: 'image/jpeg',\n     *   renameOnConflict: true,\n     *   setCreatedFrom: true,\n     *   preferredBlockTransferThreshold: 5 * 1024 * 1024, // 5MB\n     *   useBlockStore: true\n     * });\n     *\n     * @param _name - (deprecated) The name of the file to be uploaded (used when options is a Blob/string)\n     * @param _mediaType - (deprecated) The media type of the file (used when options is a Blob/string)\n     * @param _retryOnConflict - (deprecated) If true, a new name will be generated if a conflict occurs (used when options is a Blob/string)\n     * @param _counter - (deprecated) Counter for conflict resolution (used when options is a Blob/string)\n     * @param _setCreatedFrom - (deprecated) If true, sets the createdFromUpload property to true (used when options is a Blob/string)\n     * @param _preferredBlockTransferThreshold - (deprecated) Preferred block transfer threshold (used when options is a Blob/string)\n     *\n     * @throws {SAMError} If this asset is not a folder, or if invalid arguments are provided\n     * @returns {Promise<AdobeAsset>} The newly imported file asset\n     */\n    async importFile(\n        options: Blob | string | ImportFileOptions,\n        _name?: string,\n        _mediaType?: string,\n        _retryOnConflict?: boolean,\n        _counter?: number,\n        _setCreatedFrom?: boolean,\n        _preferredBlockTransferThreshold?: number,\n        _milestoneProperties?: MilestoneProperties\n    ): Promise<AdobeAsset> {\n        if (!this.isFolder) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Asset is not Folder');\n        }\n\n        const {\n            file,\n            name,\n            mediaType,\n            retryOnConflict,\n            renameOnConflict: optionsRenameOnConflict,\n            setCreatedFrom = true,\n            preferredBlockTransferThreshold = DEFAULT_MAX_SINGLE_TRANSFER_SIZE,\n            useBlockStore = false,\n            milestoneProperties\n        } = (typeof options === 'string' || options instanceof Blob)\n            ? {\n                file: options,\n                name: _name,\n                mediaType: _mediaType,\n                retryOnConflict: _retryOnConflict,\n                renameOnConflict: undefined,\n                setCreatedFrom: _setCreatedFrom,\n                preferredBlockTransferThreshold: _preferredBlockTransferThreshold,\n                milestoneProperties: _milestoneProperties\n            }\n            : options;\n\n        // Determine the final renameOnConflict value based on priority:\n        // 1. renameOnConflict from options object (new API)\n        // 2. retryOnConflict from options object or old positional argument (deprecated)\n        // 3. Default to false if none provided\n        const renameOnConflict = optionsRenameOnConflict ?? retryOnConflict  ?? false;\n\n        if (typeof file === 'string') {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Unsupported string for file to import');\n        }\n\n        if (!name || !validatePlatformRepoName(name)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for file import operation.');\n        }\n\n        const relativePath = name;\n        await this._ensureLink(RelType.CREATE);\n        await this._ensureLink(RelType.BLOCK_INITIALIZE);\n        const assetInterface = await this._getAssetInterface();\n\n        const newFileMetaData = await assetInterface.importFile(\n            file,\n            relativePath,\n            renameOnConflict,\n            mediaType,\n            preferredBlockTransferThreshold,\n            useBlockStore,\n            milestoneProperties\n        );\n\n        let fileAsset: AdobeAsset;\n        const assetContext = this._getAssetContext();\n        if (newFileMetaData) {\n            if (this.isProject || this.isChildOfProject) {\n                addProjectIdToMetadata(newFileMetaData, this.isChildOfProject ? this.parentProjectID! : this.id);\n            }\n\n            fileAsset = assetContext._createAssetFromMetadata(newFileMetaData);\n        } else {\n            fileAsset = await assetContext.getAssetWithRepoPath(`${this.repoPath}/${relativePath}`, this.repositoryID);\n        }\n\n        // For performance reasons, we don't bother setting the createdFromUpload data for the asset if it's not\n        // expected to be available in search or the Recents list.\n        if (setCreatedFrom) {\n            await fileAsset._setCreatedFromUploadData();\n        }\n        return fileAsset;\n    }\n\n    /**\n     * Updates the primary resource of the asset with the provided file.\n     *\n     * Will automatically choose between direct upload and block upload, depending on file size.\n     *\n     * @deprecated Use the options object pattern instead. This signature will be removed in a future version.\n     * @param file The file blob to update the asset with.\n     * @param mediaType The type of the asset version rendition, required for updates (e.g. 'image/png', 'image/jpg',\n     *     etc.) see\n     *     {@link https://git.corp.adobe.com/pages/caf/api-spec/chapters/common_resources/renditions_resources.html#media-types} for available types\n     * @param preferredBlockTransferThreshold Size threshold for block transfer\n     * @returns A promise containing an AdobeAsset.\n     */\n    async updateFile(\n        file: Blob | string,\n        mediaType?: string,\n        preferredBlockTransferThreshold?: number\n    ): Promise<AdobeAsset>;\n\n    /**\n     * Updates the primary resource of the asset with the provided file.\n     *\n     * Will automatically choose between direct upload and block upload, depending on file size.\n     *\n     * @param options Configuration options for updating the file\n     * @param options.file The file blob to update the asset with\n     * @param options.mediaType The type of the asset version rendition, required for updates (e.g. 'image/png', 'image/jpg',\n     *     etc.) see {@link https://git.corp.adobe.com/pages/caf/api-spec/chapters/common_resources/renditions_resources.html#media-types} for available types\n     * @param options.preferredBlockTransferThreshold Size threshold for block transfer. Defaults to DEFAULT_MAX_SINGLE_TRANSFER_SIZE\n     * @param options.useBlockStore If true, specifies that the file should be uploaded using the \"block store\" variant of block uploads (more efficient for large files)\n     * @returns A promise containing the updated AdobeAsset\n     * @example\n     * // Update a file with basic options\n     * await asset.updateFile({\n     *   file: myFileBlob,\n     *   mediaType: 'image/png'\n     * });\n     *\n     * // Update a file with all options\n     * await asset.updateFile({\n     *   file: myFileBlob,\n     *   mediaType: 'image/png',\n     *   preferredBlockTransferThreshold: 5 * 1024 * 1024, // 5MB\n     *   useBlockStore: true\n     * });\n     */\n    // eslint-disable-next-line no-dupe-class-members\n    async updateFile(\n        options: UpdateFileOptions\n    ): Promise<AdobeAsset>;\n\n    // eslint-disable-next-line no-dupe-class-members\n    async updateFile(\n        fileOrOptions: Blob | string | UpdateFileOptions,\n        mediaTypeOrThreshold?: string | number,\n        preferredBlockTransferThreshold: number = DEFAULT_MAX_SINGLE_TRANSFER_SIZE\n    ): Promise<AdobeAsset> {\n        if (this.isFolder) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Asset is a folder, not a file');\n        }\n\n        let options: UpdateFileOptions;\n\n        if (typeof fileOrOptions === 'object' && 'file' in fileOrOptions) {\n            options = fileOrOptions;\n        } else {\n            if (typeof fileOrOptions === 'string') {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Unsupported string for file to update');\n            }\n            // Handle both old and new parameter patterns\n            const mediaType = typeof mediaTypeOrThreshold === 'string' ? mediaTypeOrThreshold : undefined;\n            const threshold = typeof mediaTypeOrThreshold === 'number' ? mediaTypeOrThreshold : preferredBlockTransferThreshold;\n            options = {\n                file: fileOrOptions,\n                mediaType,\n                preferredBlockTransferThreshold: threshold,\n                useBlockStore: false\n            };\n        }\n\n        if (typeof options.file === 'string') {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Unsupported string for file to update');\n        }\n\n        await this._ensureLink(RelType.BLOCK_INITIALIZE);\n        const assetInterface = await this._getAssetInterface();\n\n        const newFileMetaData = await assetInterface.updateFile(\n            options.file,\n            options.mediaType,\n            options.preferredBlockTransferThreshold ?? DEFAULT_MAX_SINGLE_TRANSFER_SIZE,\n            options.useBlockStore\n        );\n        const assetContext = this._getAssetContext();\n        if (newFileMetaData) {\n            if (this.isProject || this.isChildOfProject) {\n                addProjectIdToMetadata(newFileMetaData, this.isChildOfProject ? this.parentProjectID! : this.id);\n            }\n            return assetContext._createAssetFromMetadata(newFileMetaData);\n        } else {\n            return this;\n        }\n    }\n\n    /**\n     * Retrieves information required to perform a block upload for a new or updated file.\n     *\n     * This method is used to initialize a block upload session, returning the necessary URLs and metadata\n     * for uploading file blocks. For new files, call this on the target parent folder. For updates, call on the file itself.\n     *\n     * @param name - The name of the file to be uploaded. Must be a valid platform repository name.\n     * @param size - The size of the file in bytes.\n     * @param options - (optional) Configuration options for the block upload:\n     *   - `mediaType`: The media type of the file (e.g., 'image/png'). **Required for updates, optional for new uploads.**\n     *   - `useBlockStore`: If true, use the block store variant of block uploads (more efficient for large files).\n     *   - `renameOnConflict`: If true, a new name will be generated if a conflict occurs; otherwise, an error is thrown.\n     *   - If a string is provided, it is interpreted as the media type (legacy signature).\n     * @param _useBlockStore - (deprecated) Use the options object instead. If true, use the block store variant. Will be removed in a future version.\n     *\n     * @throws {SAMError} If the name is invalid or required links are missing.\n     * @returns {Promise<IBlockUploadInfoResult>} An object containing URLs and metadata for the block upload session.\n     *\n     * @example\n     * // Basic usage with options object\n     * const info = await asset.getBlockUploadInfo('myfile.png', 123456, { mediaType: 'image/png', useBlockStore: true });\n     *\n     * // Legacy usage with mediaType as string\n     * const info = await asset.getBlockUploadInfo('myfile.png', 123456, 'image/png');\n     */\n    async getBlockUploadInfo(\n        name: string,\n        size: number,\n        options?: BlockUploadInfoOptions | string,\n        /** @deprecated -- use `options` */\n        _useBlockStore?: boolean,\n        _milestoneProperties?: MilestoneProperties\n    ): Promise<IBlockUploadInfoResult> {\n\n        const { mediaType, renameOnConflict, useBlockStore, milestoneProperties } = (typeof options === 'string')\n            ? { mediaType: options, renameOnConflict: false, useBlockStore: _useBlockStore, milestoneProperties: _milestoneProperties }\n            : options || {};\n\n        if (!validatePlatformRepoName(name)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for file import operation.');\n        }\n\n        await this._ensureLink(RelType.BLOCK_INITIALIZE);\n        const assetInterface = await this._getAssetInterface();\n        return assetInterface.getBlockUploadInfo(name, size, !this.isFolder, mediaType, useBlockStore, renameOnConflict, milestoneProperties);\n    }\n\n    /**\n     * Used by clients to finalize block uploads for updates/first time uploads after calling\n     * getBlockUploadInfo to obtain the transfer urls and performing the uploads.\n     * Creating a new file: call {@link getBlockUploadInfo}` on the target parent folder. Otherwise, to update\n     *  an existing file, call {@link getBlockUploadInfo} on the file.\n     * @param finalizeHref The href to finalize the block upload (returned by {@link getBlockUploadInfo}).\n     * @param initResponse The response from the block upload initialization (returned by {@link getBlockUploadInfo}).\n     * @returns A RepositoryMetadata object for first time uploads, and undefined for updates.\n     */\n    async finalizeBlockUpload(finalizeHref: string, initResponse: IBlockUploadInfo): Promise<RepositoryMetadata | undefined> {\n        const assetInterface = await this._getAssetInterface();\n        return assetInterface.finalizeBlockUpload(finalizeHref, initResponse, !this.isFolder);\n    }\n\n    /**\n     * Gets a download URL for the asset. For small files, returns a blob URL. For large files or when forceBlockDownload is true,\n     * returns a presigned URL from the service.\n     *\n     * @param options - Configuration options for getting the download URL:\n     *   - `forceBlockDownload`: If true, forces block download even for small files\n     *   - `preferredBlockTransferThreshold`: Size threshold for block transfer (defaults to DEFAULT_MAX_SINGLE_TRANSFER_SIZE)\n     *   - `presignedUrlExpirationSeconds`: Time-to-live for the presigned URL in seconds (the service default)\n     *\n     * @example\n     * // Get a download URL with default settings\n     * const url = await asset.getDownloadURL();\n     *\n     * // Force block download for a small file\n     * const url = await asset.getDownloadURL({ forceBlockDownload: true });\n     *\n     * // Set custom expiration time for the presigned URL\n     * const url = await asset.getDownloadURL({ presignedUrlExpirationSeconds: 3600 });\n     *\n     * // Use block download for files larger than 10MB\n     * const url = await asset.getDownloadURL({ preferredBlockTransferThreshold: 10 * 1024 * 1024 });\n     */\n\n    // eslint-disable-next-line no-dupe-class-members\n    async getDownloadURL(options?: GetDownloadURLOptions): Promise<string>;\n\n    /**\n     * @deprecated Use the options object pattern instead. This signature will be removed in a future version.\n     *\n     * @param forceBlockDownload - If true, forces block download even for small files\n     * @param preferredBlockTransferThreshold - Size threshold for block transfer\n     *\n     * @example\n     * // Instead of:\n     * const url = await asset.getDownloadURL(true, 10 * 1024 * 1024);\n     *\n     * // Use:\n     * const url = await asset.getDownloadURL({\n     *   forceBlockDownload: true,\n     *   preferredBlockTransferThreshold: 10 * 1024 * 1024\n     * });\n     */\n\n    // eslint-disable-next-line no-dupe-class-members\n    async getDownloadURL(forceBlockDownload?: boolean, preferredBlockTransferThreshold?: number): Promise<string>;\n    // eslint-disable-next-line no-dupe-class-members\n    async getDownloadURL(optionsOrForceBlockDownload?: GetDownloadURLOptions | boolean, preferredBlockTransferThreshold: number = DEFAULT_MAX_SINGLE_TRANSFER_SIZE): Promise<string> {\n        let forceBlockDownload: boolean | undefined;\n        let threshold: number = DEFAULT_MAX_SINGLE_TRANSFER_SIZE;\n        let expirationSeconds: number | undefined;\n        let fallbackToDirectDownloadThreshold: number | undefined;\n\n        if (optionsOrForceBlockDownload === undefined) {\n            // No parameters provided, use defaults\n        } else if (typeof optionsOrForceBlockDownload === 'object') {\n            forceBlockDownload = optionsOrForceBlockDownload.forceBlockDownload;\n            threshold = optionsOrForceBlockDownload.preferredBlockTransferThreshold ?? DEFAULT_MAX_SINGLE_TRANSFER_SIZE;\n            expirationSeconds = optionsOrForceBlockDownload.presignedUrlExpirationSeconds;\n            fallbackToDirectDownloadThreshold = optionsOrForceBlockDownload.fallbackToDirectDownloadThreshold;\n        } else {\n            forceBlockDownload = optionsOrForceBlockDownload;\n            threshold = preferredBlockTransferThreshold ?? DEFAULT_MAX_SINGLE_TRANSFER_SIZE;\n        }\n\n        await this._ensureLink(RelType.PRIMARY);\n        await this._ensureLink(RelType.BLOCK_INITIALIZE);\n\n        // If client has requested direct download, and we are under a specified file size, and the `RelType.DOWNLOAD`\n        // link is not present, we should fall back to the direct download method.\n        const shouldFallbackToPrimary = !this.__links?.[RelType.DOWNLOAD] && fallbackToDirectDownloadThreshold && this._size <= fallbackToDirectDownloadThreshold;\n\n        const assetInterface = await this._getAssetInterface();\n        if (!forceBlockDownload && (shouldFallbackToPrimary || this._size < getBlockTransferThreshold(assetInterface.links, threshold))) {\n            const blob = await this._fileContent.get({ forceRefresh: true });\n            if (!blob) {\n                throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Cannot fetch blob');\n            }\n\n            // For now we are leaking the memory allocated for the blob url.\n            // Filed this ticket to address: https://jira.corp.adobe.com/browse/SAM-2996\n            const blobUrl = URL.createObjectURL(blob);\n            if (!blobUrl?.length) {\n                throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Cannot convert blob to URL');\n            }\n            return blobUrl;\n        } else {\n            // If the download link is missing, we need to fetch the download link from the service (SAM-3396). This is a no-op if the link is already present.\n            await this._ensureLink(RelType.DOWNLOAD);\n            const blockDownloadServiceURL = getURLFromLinks(this.__links, RelType.DOWNLOAD);\n\n            return await assetInterface.getBlockDownloadURL(blockDownloadServiceURL, expirationSeconds);\n        }\n    }\n\n    /**\n     * Contents of the file as a binary blob.\n     */\n    get fileContent(): FileContentResource {\n        if (!this.isFile) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Cannot get content of an asset that is not a file');\n        }\n        return this._fileContent;\n    }\n\n    /**\n     * Commit the file\n     *\n     * For compatibility reasons, this will always perform a direct upload, regardless of file size.\n     * If you would like block upload functionality, use {@link updateFile} instead.\n     *\n     * content are the changes that needs to be committed.\n     * localETag is the ETag associated with the file on the server\n     * Returns NoErr if successfully committed. Returns Conflict if committing the asset causes a conflict.\n     */\n    async commitFileChanges(file: Blob, localETag?: string): Promise<FileCommitResult> {\n        if (!this.isFile) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Asset is not File');\n        }\n        try {\n            await this._ensureLink(RelType.PRIMARY);\n            const assetInterface = await this._getAssetInterface();\n            const newFileDetails = await assetInterface.commitFileChanges(file, localETag);\n            if (this._fileContent.isLoaded) {\n                await this._fileContent._setData(file, { etag: newFileDetails.eTag });\n            }\n            return { status: CommitStatus.NoErr, committedEtag: newFileDetails.eTag };\n        } catch (error: any) {\n            if (error instanceof SAMError) {\n                if (error.code === SAMErrorCode.CONFLICT) {\n                    return { status: CommitStatus.Conflict } as FileCommitResult;\n                }\n                if (error.code === SAMErrorCode.NOT_FOUND) {\n                    // The file has been deleted. We need to create a new asset and then provide that to the user.\n                    const parentRepoPath = this.repoPath.substring(0, this.repoPath.lastIndexOf('/'));\n                    let parentDeleted = false;\n                    const parentAsset = await this._getAssetContext()\n                        .getAssetWithRepoPath(parentRepoPath, this.repositoryID)\n                        .catch(error => {\n                            const samError = error as SAMError;\n                            if (SAMErrorCode.NOT_FOUND === samError.code) {\n                                parentDeleted = true;\n                                return undefined;\n                            }\n                            throw error;\n                        });\n                    if (parentDeleted) {\n                        return { status: CommitStatus.ParentDeletedConflict };\n                    }\n                    const newFile = await parentAsset?.importFile(file, this.name);\n                    return { status: CommitStatus.DeleteConflict, newAsset: newFile } as FileCommitResult;\n                }\n            }\n            throw error;\n        }\n    }\n\n    /**\n     * Restore the asset - can be given an optional name to restore to, otherwise it\n     * restores to the previous repo:name of the asset.\n     * @param {string} name - name to use when restoring, defaults to current name\n     */\n    async restore(name?: string, _counter?: number): Promise<void> {\n        if (!this.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Cannot restore an asset that is not discarded');\n        }\n        const assetContext = this._getAssetContext();\n        const assetPool = this._core._getAssetPool();\n        if (this.isLibraryElement) {\n            // If asset is a Library Element, we need to use the Melville service to restore\n            await assetContext.restoreLibraryElement(this.cloudID);\n            // We create fake AdobeAssets for Library Elements returned from the DiscardedSource so they can appear\n            // in the discarded list with other Assets. They are not monitored by ONS and do not otherwise exist as Assets in SAM.\n            // So when we restore them, rather than updating the state, we remove it from the assetPool and thereby the discardedSource lists.\n            const session = assetPool.createUpdateSession();\n            session.queueDiscardedItem(this);\n            session.commit();\n        } else {\n            let repoMetadata: RepositoryMetadata | undefined;\n            const restoreLocation = getRestorePath(this.repoPath, name);\n            if (restoreLocation) {\n                // If archived rather than discarded, we need to move to the restore location\n                repoMetadata = await this._move(restoreLocation, true);\n            } else {\n                const assetInterface = await this._getAssetInterface();\n                try {\n                    repoMetadata = await assetInterface.restore(name || this.name);\n                } catch (e) {\n                    const error = e as SAMError;\n                    if (error.code === SAMErrorCode.CONFLICT) {\n                        const { newName, countUsed } = formatFileName(\n                            name || this.name,\n                            this._core._environment.getValue('ASSET_CONFLICT_NAME_FORMAT'),\n                            (_counter || 0) + 1\n                        );\n                        return this.restore(newName, countUsed);\n                    } else if (error.code === SAMErrorCode.ACCESS_DENIED) {\n                        if (this.ancestorIDs?.length) {\n                            const parentId = this.ancestorIDs[this.ancestorIDs.length - 1];\n                            const parentAsset = await assetContext.getAssetWithCloudID(parentId);\n                            if (parentAsset.isDiscarded) {\n                                throw SAMError.create(SAMErrorCode.PARENT_DISCARDED, 'Parent folder is discarded');\n                            }\n                        }\n                    }\n\n                    throw error;\n                }\n            }\n            if (repoMetadata) {\n                // Optimistically update repo state from operation result\n                const session = assetPool.createUpdateSession();\n                assetContext._adobeAssetUpdater.updateLocalItem(session, this, repoMetadata);\n                if (this.isFolder && repoMetadata['repo:path']) {\n                    // If it's a directory, optimistically update the repo state of any children assets.\n                    // If it's a directory that was unarchived or had a naming conflict upon restore, we also need to update the repo:path of all its children.\n                    const path = (restoreLocation || _counter) ? repoMetadata['repo:path'] : undefined;\n                    updateCachedDescendents({\n                        assetPool,\n                        asset: this,\n                        session,\n                        operation: { type: 'restore', newPath: path },\n                        assetContext\n                    });\n                }\n                session.commit();\n            }\n        }\n    }\n\n\n    /**\n     * Permanently delete the asset\n     */\n    async permanentlyDelete(): Promise<void> {\n        const assetContext = this._getAssetContext();\n        const assetPool = this._core._getAssetPool();\n        if (this.isLibraryElement) {\n            await assetContext.permanentlyDeleteLibraryElement(this.cloudID);\n            const session = assetPool.createUpdateSession();\n            session.queueDiscardedItem(this);\n            session.commit();\n        } else {\n            const resultItems = await assetContext.permanentlyDeleteAssets([ this ]);\n            if (resultItems.failedResults.length) {\n                throw resultItems.failedResults[0].error;\n            }\n        }\n    }\n\n    // Note - The APIs below aren't present in SAM-CPP:\n\n    @observable\n    get etag(): string {\n        return this._etag;\n    }\n\n    @observable\n    get version(): string {\n        return this._version;\n    }\n\n    @observable\n    get createdBy(): string {\n        return this._createdBy;\n    }\n\n    @observable\n    get modifiedBy(): string {\n        return this._modifiedBy;\n    }\n\n    @observable\n    get discarded(): Date | undefined {\n        return this._discarded;\n    }\n\n    @observable\n    get discardedBy(): string | undefined {\n        return this._discardedBy;\n    }\n\n    @observable\n    /**\n     * Detect if the user has a specific permission or permissions\n     * @param permissions\n     * @usage\n     *    // single permission check\n     *    asset.hasPermission(Permission.Delete);\n     *    // multiple\n     *    asset.hasPermission(Permission.Write, Permission.Read);\n     *    // multiple via bitwise OR\n     *    asset.hasPermission(Permission.Write | Permission.Read);\n     *    // multiple via spread operator\n     *    asset.hasPermission(...permsToCheck);\n     */\n    hasPermission(...permissions: Permission[]): boolean {\n        return permissions.every((permission) =>\n            (this._permissions & permission) === permission);\n    }\n\n    @observable\n    /**\n     * Returns an object of permissions and role for the current user in a similar format to\n     * the Invitation Service GET /capabilities API.\n     * Currently derived from the effective ACL of the user.\n     * For simplicity, the role is defined very loosely to how Invitation Service does it today and there might be\n     * usecases where this is not accurate. When those usecases arise, we can revisit this by tightening the definition\n     * according to\n     * https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=acp&title=Invitations+Service+V4#InvitationsServiceV4-MappingRoles/PermissionstoACEs\n     * or calling the GET /capabilities API directly.\n     * @returns {InvitationServiceCapabilities}\n     */\n    get invitationServiceCapabilities(): InvitationServiceCapabilities {\n        let role: Role = 'none';\n\n        if (this.hasPermission(Permission.Read)) {\n            if (this.hasPermission(Permission.Write)) {\n                role = this.hasPermission(Permission.Ack) ? 'owner' : 'editor';\n            } else {\n                role = 'viewer';\n            }\n        }\n\n        return {\n            canComment: this.hasPermission(Permission.WriteComment),\n            canShare: this.hasPermission(Permission.Share),\n            role\n        };\n    }\n\n    isReadOnly(): boolean {\n        return this.hasPermission(Permission.Read) && !this.hasPermission(Permission.Write);\n    }\n\n    // SAM-CPP doesn't expose the embedded metadata directly - you need to access it via DCX-CPP. We should port this API\n    // back to SAM. Since not everybody needs to load the embedded metadata, this returns an object that the user can\n    // explicitly load.\n    get embeddedMetadata(): EmbeddedMetadataResource {\n        return this._embeddedMetadata;\n    }\n\n    @observable\n    get appMetadata(): AppMetadataResource {\n        return this._appMetadata;\n    }\n\n    /**\n     * Patches application metadata for an Asset.\n     * CAUTION: SAM does not validate the JSONPatch array. Wherever possible, use a service that is responsible for\n     * maintaining the app metadata fields you want to modify, rather then modifying them directly. E.g., to modify\n     * Project related data, use the Projects Service; for Reviews, use the Review service; allow server-side events\n     * to populate fields as needed; etc.\n     *\n     * @param patches {jsonpatch.OpPatch[]} JSONPatch array of operations (https://jsonpatch.com/).\n     */\n    async patchAppMetadata(patches: jsonpatch.OpPatch[]): Promise<void> {\n        await this._appMetadata._patch(patches);\n    }\n\n    get manifest(): ManifestResource {\n        if (!this.isComposite) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Cannot get manifest of an asset that is not a composite');\n        }\n        return this._manifest;\n    }\n\n    /**\n     * For use internally to release renditions after\n     * the asset has been deleted permanently.\n     * @package\n     */\n    _releaseRenditions() {\n        this._renditionFetcher.release();\n    }\n\n    // NOTE: this is only guaranteed to work as advertised on web. Clients writing for desktop and\n    // web should use `AdobeAsset.thumbnailURL` instead\n    @observable\n    getRenditionURL(size: number, type: string = RenditionType.PNG): string {\n        // Do not try to fetch rendition for folders, or LEs that have no rendition link\n        if (this.isFolder || (this.isLibraryElement && !this.links[RelType.RENDITION])) {\n            return '';\n        }\n        return this._renditionFetcher.getURL(size, type, this.etag);\n    }\n\n    @observable\n    get thumbnailURL(): string {\n        return this.getRenditionURL(THUMBNAIL_SIZE, RenditionType.PNG);\n    }\n\n    @observable\n    get thumbnailStatus(): RenditionStatus {\n        return this.renditionURLStatus(THUMBNAIL_SIZE, RenditionType.PNG);\n    }\n\n    /**\n     * See {@link AssetInterface#getCustomRendition} for usage\n     */\n    async getCustomRendition({\n        size,\n        type,\n        urlTemplateOptions,\n        additionalHeaders\n    }: Parameters<AssetInterface['getCustomRendition']>[0] = {}): Promise<Response> {\n        await this._ensureLink(RelType.RENDITION);\n        const assetInterface = await this._getAssetInterface();\n        return assetInterface.getCustomRendition({ size, type, urlTemplateOptions, additionalHeaders });\n    }\n\n    /**\n     * See {@link AssetInterface#getCustomRendition} for usage\n     */\n    async getAllCustomRenditions({\n        type,\n        urlTemplateOptions,\n        additionalHeaders\n    }: Parameters<AssetInterface['getAllCustomRenditions']>[0] = {}): Promise<Response> {\n        await this._ensureLink(RelType.RENDITION);\n        const assetInterface = await this._getAssetInterface();\n        return assetInterface.getAllCustomRenditions({ type, urlTemplateOptions, additionalHeaders });\n    }\n\n    /**\n     * Clears the error status on the request rendition and sets it\n     * back to RenditionStatus.NotStarted\n     *\n     * @note After attempting to fetch a thumbnail and an error has occurred during\n     * the fetch request, we assign an error status to the rendition. At this\n     * point, we won't try to refetch the thumbnail until this method is called.\n     * It is meant to give clients a means to handle when they attempt to refresh\n     * instead of SAM.js making that decisions internally which could cause thumbnails\n     * to begin loading when that may not be the desired behavior. This is also\n     * not meant to fix every issue with thumbnails fetching so in the case where\n     * the user might be offline or something similar, it's not recommended for\n     * clients to continue to call this indefinitely.\n     *\n     *\n     * @param size Defaults to 512\n     * @param type Defaults to PNG\n     * @returns {void} If the rendition requested is not found or the etag requested is different\n     * than the one that was already fetched, this method will do nothing.\n     */\n    public clearRenditionError(size: number = THUMBNAIL_SIZE, type: string = RenditionType.PNG): void {\n        this._renditionFetcher.clearRenditionError(size, type, this.etag);\n    }\n\n    /**\n     * Returns one the enumeration values of RenditionStatus.\n     *\n     * @returns {RenditionStatus}\n     */\n    @observable\n    public renditionURLStatus(size: number, type: string): RenditionStatus {\n        // Do not try to fetch rendition for folders, or LEs that have no rendition link\n        if (this.isFolder || (this.isLibraryElement && !this.links[RelType.RENDITION])) {\n            return RenditionStatus.Done;\n        }\n        return this._renditionFetcher.renditionURLStatus(size, type, this.etag);\n    }\n\n    /**\n     * @deprecated -- will be removed on or after 2024-10-01\n     */\n    @observable\n    get spaceID(): string | undefined {\n        oneTimeWarning('AdobeAsset.spaceID',\n            'AdobeAsset.spaceID is deprecated and will be removed on or after 2024-10-01.');\n        return this.appMetadata.data?.['cc:inherited']?.['cc:space']?.['repo:assetId'];\n    }\n\n    /**\n     * @deprecated -- will be removed on or after 2024-10-01\n     */\n    get isSpaceAsset(): boolean {\n        oneTimeWarning('AdobeAsset.isSpaceAsset',\n            'AdobeAsset.isSpaceAsset is deprecated and will be removed on or after 2024-10-01.');\n        return !!this.spaceID;\n    }\n\n    /**\n     * @deprecated -- will be removed on or after 2024-10-01\n     */\n    async getSpace(): Promise<Space> {\n        oneTimeWarning('AdobeAsset.getSpace',\n            'AdobeAsset.getSpace is deprecated and will be removed on or after 2024-10-01.');\n        const space = await this._core.spaceContext.getEnclosingSpace(this.cloudID);\n        if (!space) {\n            throw SAMError.create(SAMErrorCode.NOT_FOUND, 'Asset does not belong to a Space');\n        }\n        return space;\n    }\n\n    // Exposes the raw links for the underlying asset. This is so we can share them with clients like Fred, that don't have\n    // access to SAM (since they're running in a web worker). SAM-CPP doesn't expose this.\n    @observable\n    get links(): AssetLinks {\n        // Make a copy to avoid the client accidentally manipulating the links\n        return Object.assign({}, this.__links);\n    }\n\n    /**\n     * Whether or not ONS notifications for children not in the ItemPool cause that child to be loaded\n     * @package -- internal use only\n     */\n    get _canLoadNewChildrenFromONSNotification(): boolean {\n        return true;\n    }\n\n    @observable\n    get pinnedVersion(): string | undefined {\n        return this._pinnedVersion;\n    }\n\n    @observable\n    get pinnedVersionModifyDate(): Date | undefined {\n        return this._pinnedVersionModifyDate;\n    }\n\n    @observable\n    get preferredVersion(): string {\n        // If pinned version is set, return that, otherwise return the current version\n        return this.pinnedVersion || this.version;\n    }\n\n    /**\n     * [SAM-2443] If missing links, then Asset probably came from USS, which doesn't have all R-API links\n     *  (SEARCH-32676). In that case, try to update the links from R-API via the resolve API.\n     * @package -- only for use in SAM.js\n     */\n    async _ensureLink(relType: keyof AssetLinks): Promise<void> {\n        if (this.__links?.[relType]) {\n            return;\n        }\n        const assetContext = this._getAssetContext();\n        const assetPool = this._core._getAssetPool();\n        const links = await assetContext._rapi.getAssetLinks(this.cloudID);\n        const session = assetPool.createUpdateSession();\n        assetContext._adobeAssetUpdater.updateLocalItem(\n            session,\n            this,\n            { '_links': { ...this.__links, ...links } }\n        );\n        session.commit();\n    }\n\n    /**\n     * Move within same repository\n     *\n     * @package -- for use in SAM.js only\n     */\n    async _move(newPath: string, retryOnConflict: boolean = false, counter: number = 0): Promise<RepositoryMetadata | undefined> {\n        try {\n            // In case of Asset created from USS response, repo id is not present\n            // Jira on USS https://jira.corp.adobe.com/browse/SRCH-1989\n            if (!this._repositoryID) {\n                await this._load();\n            }\n\n            const operation: IMoveOperation = {\n                op: 'move',\n                source: {\n                    'repo:assetId': this.id,\n                    'repo:repositoryId': this._repositoryID\n                },\n                target: {\n                    'repo:path': newPath,\n                    'repo:repositoryId': this._repositoryID\n                }\n            };\n\n            const assetInterface = await this._getAssetInterface();\n            const result = await assetInterface.runOperation(operation);\n            return result.asset;\n        } catch (e: any) {\n            if (e.code === SAMErrorCode.CONFLICT && retryOnConflict) {\n                // If we can't restore because an asset already exists with the same name, we append a counter and try again\n                const formatFileResult = formatFileName(newPath, this._core._environment.getValue('ASSET_CONFLICT_NAME_FORMAT'), counter + 1);\n                return this._move(formatFileResult.newName, true, formatFileResult.countUsed);\n            }\n            throw e;\n        }\n    }\n\n    protected async _copy(\n        destFolder: AdobeAsset,\n        destName?: string,\n        retryOnConflict: boolean = true,\n        counter: number = 0,\n        modelUpdater?: (session: IUpdateSession<AdobeAsset>, asset: AdobeAsset, remoteItem?: RepositoryMetadata) => AdobeAsset\n    ): Promise<AdobeAsset> {\n        let resultOps: IBatchOperationAssetResult = { failedResults: [], newModels: [] };\n        await ItemBase.runExclusiveTask('copy', [ this ], async () => {\n            const { path: newPath, counter: currCounter } = this._finalizePath(destFolder.repoPath, destName, counter);\n            counter = currCounter;\n\n            const assetsById = new Map<string, AdobeAsset>();\n            assetsById.set(this.id, this);\n\n            if (!destFolder.repositoryID) {\n                await destFolder._load();\n            }\n\n            const ops: ICopyOperation = this._getCopyOp(destFolder.repositoryID, newPath);\n            const assetContext = this._getAssetContext();\n            resultOps = await assetContext._runOperations(\n                [ ops ],\n                assetsById,\n                modelUpdater ? modelUpdater : (session: IUpdateSession<AdobeAsset>, asset: AdobeAsset, remoteItem?: RepositoryMetadata): AdobeAsset => {\n                    if (!remoteItem) {\n                        throw SAMError.create(SAMErrorCode.UNKNOWN, 'Missing metadata from asset copy operation.');\n                    }\n\n                    const newAsset = assetContext._adobeAssetUpdater.updateRemoteItem(session, remoteItem);\n                    return newAsset;\n                }\n            );\n        });\n\n        if (resultOps.failedResults.length) {\n            if (resultOps.failedResults[0].error.code === SAMErrorCode.CONFLICT && retryOnConflict === true) {\n                return await this._copy(destFolder, destName, retryOnConflict, counter + 1);\n            }\n            throw resultOps.failedResults[0].error;\n        }\n\n        return resultOps.newModels[0];\n    }\n\n    /**\n     * Make a copy of this Asset within the same repository using the dest folder metadata provided, when the dest\n     * folder asset is not on hand.\n     *\n     * @param destFolderRepoId -- The destination folder's repository ID\n     * @param destFolderRepoPath -- The destination folder's repo path\n     * @param destName -- (not available on SAM.cpp) -- preferred name for the copy\n     */\n    async _copyWithDestMetadata(\n        destFolderRepoId: string,\n        destFolderRepoPath: string,\n        destName?: string,\n        retryOnConflict: boolean = true,\n        counter: number = 0,\n        modelUpdater?: (session: IUpdateSession<AdobeAsset>, asset: AdobeAsset, remoteItem?: RepositoryMetadata) => AdobeAsset\n    ): Promise<AdobeAsset> {\n        let resultOps: IBatchOperationAssetResult = { failedResults: [], newModels: [] };\n        const assetContext = await this._getAssetContext();\n        await ItemBase.runExclusiveTask('copy', [ this ], async () => {\n            const { path, counter: currCounter } = this._finalizePath(destFolderRepoPath, destName, counter);\n            counter = currCounter;\n\n            const assetsById = new Map<string, AdobeAsset>();\n            assetsById.set(this.id, this);\n\n            const ops: ICopyOperation = this._getCopyOp(destFolderRepoId, path);\n            resultOps = await assetContext._runOperations(\n                [ ops ],\n                assetsById,\n                modelUpdater ? modelUpdater : (session: IUpdateSession<AdobeAsset>, asset: AdobeAsset, remoteItem?: RepositoryMetadata): AdobeAsset => {\n                    if (!remoteItem) {\n                        throw SAMError.create(SAMErrorCode.UNKNOWN, 'Missing metadata from asset copy operation.');\n                    }\n\n                    const newAsset = assetContext._adobeAssetUpdater.updateRemoteItem(session, remoteItem);\n                    return newAsset;\n                }\n            );\n        });\n\n        if (resultOps.failedResults.length) {\n            if (resultOps.failedResults[0].error.code === SAMErrorCode.CONFLICT && retryOnConflict === true) {\n                return await this._copyWithDestMetadata(destFolderRepoId, destFolderRepoPath, destName, retryOnConflict, counter + 1);\n            }\n            throw resultOps.failedResults[0].error;\n        }\n\n        return resultOps.newModels[0];\n    }\n\n    protected _finalizePath(\n        destFolderRepoPath: string,\n        destName?: string,\n        counter: number = 0,\n    ): {path: string; counter: number} {\n        let targetName: string = this.name;\n        if (destName !== undefined) {\n            if (!validatePlatformRepoName(destName)) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for asset copy operation.');\n            }\n            targetName = destName;\n            if (counter) {\n                const formatFileResult = formatFileName(targetName, this._core._environment.getValue('ASSET_CONFLICT_NAME_FORMAT'), counter);\n                targetName = formatFileResult.newName;\n                counter = formatFileResult.countUsed;\n            }\n        } else {\n            // check if we are copying in the same folder\n            // if yes, then it should follow ASSET_COPY_NAME_FORMAT i.e. %@ copy (%d)\n            // if no and conflict, then it should follow ASSET_CONFLICT_NAME_FORMAT i.e. %@ (%d)\n            const sameFolder = destFolderRepoPath === this.repoPath.substring(0, this.repoPath.lastIndexOf('/'));\n            const formatFileResult = sameFolder ? formatFileName(targetName, this._core._environment.getValue('ASSET_COPY_NAME_FORMAT'), counter)\n                : (counter > 0 ? formatFileName(targetName, this._core._environment.getValue('ASSET_CONFLICT_NAME_FORMAT'), counter) : { newName: targetName, countUsed: counter });\n            targetName = formatFileResult.newName;\n            counter = formatFileResult.countUsed;\n        }\n\n        return { path: `${destFolderRepoPath}/${targetName}`, counter };\n    }\n\n    /** @package -- for use in SAM.js only */\n    _getCopyOp(destFolderRepoId: string, path: string): ICopyOperation {\n        // We only want to copy App metadata for PDFs and no other file format\n        // This is a temporary solution and we will have a better solution on the service side\n        const includeResources: IResourceDesignator[] = [ { 'reltype': RelType.PRIMARY } ];\n        if (this.mediaType === 'application/pdf') {\n            includeResources.push({\n                reltype: RelType.APP_METADATA,\n            });\n        } else if (isGenerationHistoryAsset(this)) {\n            includeResources.push({\n                reltype: RelType.APP_METADATA,\n                selectionType: 'exclude',\n                selectors: [ 'firefly.generationGroupId' ], // Exclude groupId for GHAs while copying to avoid rendering sister assets when a copied GHA is opened.\n            });\n        }\n        const ops: ICopyOperation = {\n            op: 'copy',\n            id: this.id,\n            source: {\n                'repo:assetId': this.id,\n                // If this Asset has a pinnedVersion, copy the pinnedVersion, otherwise copy the head version\n                ...(!this.isFolder ? { 'repo:version': 'v:pinned' } : {}),\n                ...(this.repositoryID ? { 'repo:repositoryId': this.repositoryID } : {}),\n            },\n            target: {\n                'repo:path': path,\n                'repo:repositoryId': destFolderRepoId\n            },\n            // The following copies Content Resources for all formats\n            // and Application Metadata for PDFs only\n            includeResources\n        };\n        return ops;\n    }\n\n    /**\n     * Make a copy of this Asset within the same repository. If you do not have the dest folder asset on hand consider\n     * using _copyWithDestMetadata instead.\n     *\n     * @param destFolder -- AdobeAsset instance representing the folder in which the copy of this AdobeAsset will be\n     *     made. If you do not have the destFolder asset on hand but do have its repo ID and path, consider using\n     *     _copyWithDestMetadata instead to avoid an API call to fetch the dest folder.\n     * @param destName -- (not available on SAM.cpp) -- preferred name for the copy\n     */\n    async copy(destFolder: AdobeAsset, destName?: string): Promise<this> {\n        return await this._copy(destFolder, destName) as this;\n    }\n\n    /**\n     * Duplicate this Asset within the same folder.\n     *\n     * @param destName -- (not available on SAM.cpp) -- preferred name for the duplicate\n     */\n    async duplicate(destName?: string): Promise<this> {\n        const parentId = this.ancestorIDs!.slice(-1)[0];\n        const parentAsset = await this._getAssetContext().getAssetWithCloudID(parentId);\n        return await this._copy(parentAsset, destName) as this;\n    }\n\n    async rename(newName: string): Promise<void> {\n        if (!validatePlatformRepoName(newName)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for asset rename operation.');\n        }\n        const assetContext = this._getAssetContext();\n        const assetPool = this._core._getAssetPool();\n        const newPath = renameFileInPath(newName, this);\n        const newMetadata = await this._move(newPath);\n        if (newMetadata) {\n            // Update the metadata after a rename, since both name and path have changed\n            const session = assetPool.createUpdateSession();\n            if (this.isFolder) {\n                updateCachedDescendents({\n                    assetPool,\n                    asset: this,\n                    session,\n                    operation: { type: 'rename', newPath },\n                    assetContext\n                });\n            }\n            assetContext._adobeAssetUpdater.updateLocalItem(session, this, newMetadata);\n            session.commit();\n        }\n\n        // If this asset has it's latest version already loaded, we should update the versioned name\n        // property opportunistically.\n        const latestVersion = this._versionPool.getLocalItemById(this.version);\n        if (latestVersion) {\n            const historySession = this._versionPool.createUpdateSession();\n            VersionUpdater.updateRemoteItem(historySession, {\n                version: this.version,\n                'repo:deviceAssetName': newName\n            });\n            historySession.commit();\n        }\n    }\n\n    /**\n     * Moves the AdobeAsset to a new folder and/or renames it\n     * @param destFolder AdobeAsset instance representing the folder to which the AdobeAsset will be moved\n     * @param assetRenameMap allows renaming of the asset during the move operation\n     */\n    async move(destFolder: AdobeAsset, newAssetName?: string): Promise<void> {\n        let assetRenameMap: AssetRenameMap<AdobeAsset> | undefined;\n\n        if (newAssetName) {\n            assetRenameMap = new Map([ [ this.id, newAssetName ] ]);\n        }\n\n        const resultItems = await this._getAssetContext().moveAssets([ this ], destFolder, assetRenameMap);\n        if (resultItems.failedResults.length) {\n            throw  resultItems.failedResults[0].error;\n        }\n    }\n\n    /**\n     * @deprecated -- will be removed on or after 2024-10-01\n     */\n    transferToSpace(target: Space | AdobeAsset): Promise<string> {\n        oneTimeWarning('AdobeAsset.transferToSpace',\n            'AdobeAsset.transferToSpace is deprecated and will be removed on or after 2024-10-01.');\n        return this._getAssetContext().transfer(this, target);\n    }\n}\n\n\nfunction getPermission(source: Partial<AdobeAssetUpdaterMetadata>): Permission | typeof NotFound {\n    // from Asset._load()\n    if (source.effectivePermission !== undefined) {\n        return source.effectivePermission;\n    }\n    // From R-API directory listing or USS listings\n    if (source._embedded?.[RelType.AC_EFFECTIVE]) {\n        return parseEffectivePermissions(source._embedded[RelType.AC_EFFECTIVE]!);\n    }\n    // If the permissions are not present in the metadata then maintain the current value\n    return NotFound;\n}\n\nexport const StorageAssigneeFormat: PropertyFormatType = {\n    parse: (value: Assignee): Assignee => {\n        return value;\n    },\n    isEqual: (a: Assignee, b: Assignee): boolean => {\n        return a?.id === b?.id && a?.type === b?.type;\n    }\n};\n\n// For ad hoc properties that are computed or otherwise do not come from R-API repoMetadata, place them here.\n// NOTE: Under no circumstances should RepositoryMetadata have any definitions other than what comes from R-API\n// repoMetadata!\nexport type AdobeAssetUpdaterMetadata = Partial<RepositoryMetadata> & {\n    // values from AdobeAsset._load()\n    effectivePermission?: Permission;\n    perUserMetadata?: IPerUserMetadata;\n\n    // values from USSv3\n    isShared?: boolean;\n    sharedViaInvite?: boolean;\n\n    // value from RepositoryInterface.getRepositoryName()\n    repositoryName?: string;\n\n    // used to control when isShared() and isSharedWithYouAsset() should call queueCollaborators()\n    shareFlagsAreDirty?: boolean;\n\n    isAvailableOffline?: boolean;\n\n    // TODO: add support for these when available from USSv3\n    // published?: boolean;\n    // isArchivedLibraryElement?: boolean;\n\n    // data comes from GQL only\n    isFavorite?: boolean;\n\n    // data comes from GQL, or Melville (in which case the GenerationHistoryAssetUpdater is used)\n    generationModelDisplayName?: string;\n}\n\n// Note: ONLY for data that comes from SAM.cpp, which has RepositoryMetadata plus additional\n// data about cache and sync status.\nexport type LocalAssetMetadata = Partial<RepositoryMetadata> & {\n    localID?: string;\n    downloadStatus?: ITransferStatus;\n    uploadStatus?: ITransferStatus;\n    syncStatus?: AssetSyncStatus;\n    syncSuspensionReason?: AssetSyncSuspensionReason;\n}\n\n// NOTE: LocalAssetMetadata is omitted from  the type definition below even though there are\n// properties from it included in the PropertyUpdater. This is by design.\nexport const AssetItemUpdaterOptions: IItemUpdaterOptions<AdobeAsset, Partial<AdobeAssetUpdaterMetadata | AssetReviewServiceData>> = {\n    localItemType: AdobeAsset,\n    // NOTE: for support of offline creation, where there is no `repo:assetId`, we use \"repo:path\".\n    // See ACPLModelInterface for more details on how this is used.\n    getAlternateId(remoteItem) { return (remoteItem as LocalAssetMetadata)['repo:path']; },\n    remoteIdProperty: 'repo:assetId',\n    // We want the SharedCollaboratorChangedEvent to fire when these properties update\n    // so that internally and externally we can response to this specific event to do\n    // things like update collaborators etc.\n    changeEventMap: new Map([\n        [ '_isShared', SharedCollaboratorChangedEvent ],\n        [ '_isSharedWithYouAsset', SharedCollaboratorChangedEvent ]\n    ]),\n    // Mapping AdobeAssetUpdaterMetadata | AssetReviewServiceData to AdobeAsset\n    propertyUpdater: new PropertyUpdater({\n        '_name': 'repo:name',\n        '_etag': 'repo:etag',\n        '_repositoryID': 'repo:repositoryId',\n        '_repositoryName': 'repositoryName',\n        '_path': 'repo:path',\n        '_storageRegion': 'storage:region',\n        '_type': 'dc:format',\n        '_assetType': 'repo:assetType',\n        '_assetSubType': 'repo:assetSubType',\n        '_size': { name: 'repo:size', format: 'number' },\n        '_version': 'repo:version',\n        '_assetClass': { name: 'repo:assetClass', choices: AssetClassChoices },\n        '_assetState': { name: 'repo:state', choices: AssetStateChoices },\n        '_created': { name: 'storage:deviceCreateDate', format: 'date' },\n        '_modified': { name: 'storage:deviceModifyDate', format: 'date' },\n        '_lastAccessed': { name: 'perUserMetadata[shell:lastAccessDate]', format: 'date' },\n        '_storageAssignee': { name: 'storage:assignee', format: StorageAssigneeFormat },\n        '_discarded': { name: 'repo:discardDate', format: 'date' },\n        '_createdBy': 'repo:createdBy',\n        '_modifiedBy': 'repo:modifiedBy',\n        '_discardedBy': 'repo:discardedBy',\n        '_imageLength': { name: 'tiff:imageLength', format: 'number' },\n        '_imageWidth': { name: 'tiff:imageWidth', format: 'number' },\n        '_permissions': { get: getPermission, format: 'number' },\n        '_isShared': { name: 'isShared', format: 'boolean' },\n        '_generationModelDisplayName': { name: 'generationModelDisplayName', format: 'string' },\n        '_isFavorite': { name: 'isFavorite', format: 'boolean' },\n        '_isSharedWithYouAsset': { name: 'sharedViaInvite', format: 'boolean' },\n        '_shareFlagsAreDirty': { name: 'shareFlagsAreDirty', format: 'boolean' },\n        // NOTE: for LocalAsset use only\n        '_localID': 'localID',\n        '_downloadStatus': { name: 'downloadStatus', format: 'object' },\n        '_uploadStatus': { name: 'uploadStatus', format: 'object' },\n        '_syncStatus': { name: 'syncStatus', format: 'number' },\n        '_syncSuspensionReason': { name: 'syncSuspensionReason', format: 'number' },\n        // PropertyUpdater reads from _appMetadata._data for comparison\n        '_appMetadata._data': {\n            name: `_embedded[${RelType.APP_METADATA}]`,\n            // Use object_subset format to avoid unnecessary change events. E.g., if _appMetadata.data is\n            // `{ 'shell:visibility': 'hiddenSelf', foo: 32 }` and the listing contains\n            // `{ 'shell:visibility': 'hiddenSelf' }` then the _mergeData will cause no change, but using format\n            // 'object', isEqual() will see source and dest aren't equal and thus assume that a change did occur.\n            format: 'object_subset',\n            // Only update the appMetadata properties that are in the listing's embedded appMetadata\n            set: (parsedSource, dest) => {\n                const asset = dest as AdobeAsset;\n                asset.appMetadata._mergeData(parsedSource);\n            }\n        },\n        '_ancestorIDs': { name: 'repo:ancestors', isArray: true, format: 'string' },\n        '__links': { name: '_links', format: 'object_subset' },\n        '_hasArtifacts': { name: 'hasArtifacts', format: 'boolean' },\n        '_createdByClientId': 'repo:createdByClientId',\n        '_representations': { name: 'repo:representations', format: 'object' },\n        '_xmpNumberOfPages': { name: 'xmpTPg:NPages', format: 'number' },\n        '_pinnedVersion': 'repo:pinnedVersion',\n        '_pinnedVersionModifyDate': { name: 'repo:pinnedVersionModifyDate', format: 'date' },\n    })\n};\n\n\nexport const AdobeAssetUpdater = new ItemUpdater<AdobeAsset, Partial<AdobeAssetUpdaterMetadata | AssetReviewServiceData>>(AssetItemUpdaterOptions);\n// Note: Only for use in code that updates SAM.js AdobeAssets from SAM.cpp cached Assets\nexport const LocalAdobeAssetUpdater = new ItemUpdater<AdobeAsset, Partial<AdobeAssetUpdaterMetadata & LocalAssetMetadata>>(AssetItemUpdaterOptions);\n\nfunction getUSSAssetType(source: Partial<USSMetadata>) {\n    // uss type is 'application/x-sharedcloud-collection+json' for directory\n    // changing it to standard mime directory type to abstract it for SAM clients\n    if (source.type === FOLDER_ALTERNATE_TYPE) {\n        return FOLDER_TYPE;\n    }\n    return source.type;\n}\n\nfunction getUSSAssetClass(source: Partial<USSMetadata>) {\n    // for directories, asset_sub_type is not present in USS response\n    if (source.type === FOLDER_ALTERNATE_TYPE || source.type === FOLDER_TYPE) {\n        return 'directory';\n    }\n    // for files, asset_sub_type is not present in USS response\n    // so we assign anything else that is not dcx or directory as file\n    if (source.creative_cloud_asset_type !== 'dcx') {\n        return 'file';\n    }\n    return source.asset_sub_type;\n}\n\nfunction getUSSLastAccessed(source: Partial<USSMetadata>) {\n    const lastAccessedISOString = source['api:metadata/peruser']?.[0]?.['shell:lastAccessDate'];\n    // If the property is not present, the current value should be left alone\n    if (lastAccessedISOString === undefined) {return NotFound;}\n    // If the property is present, but empty, clear the current value\n    if (lastAccessedISOString === '') {return undefined;}\n    return lastAccessedISOString;\n}\n\nfunction getUSSStorageRegion(source: Partial<USSMetadata>): string {\n    // USS stores 'region' as 'US', 'AP', 'EU' for some Assets, and 'va6c2', 'va7' for other Assets. According to USS\n    // team, the US/AP/EU strings can be mapped to VA6/JPN3/IRL1, and the others match the R-API storage:region.\n    switch (source.region?.toLowerCase()) {\n    case 'us':\n        return 'VA6';\n    case 'ap':\n        return 'JPN3';\n    case 'eu':\n        return 'IRL1';\n    default:\n        return source.region?.toUpperCase() || '';\n    }\n}\n\n// USS result item does not contain asset name in path, to keep it sync with repo path\n// received from RAPI, we will add asset name in asset path while creating/updating asset\n// from USS result\nfunction getAssetPath(source: Partial<USSMetadata>): string {\n    if (source.asset_name_path && source.asset_name) {\n        return path.join(source.asset_name_path, source.asset_name);\n    }\n    return source.asset_name_path || source.asset_name || '';\n}\n\nfunction getEtag(source: Partial<USSMetadata>): string {\n    return source.composite_manifest_etag || source.etag?.primary || '';\n}\n\nexport type USSAdobeAssetUpdaterMetadata = Partial<USSMetadata> & {\n    // from SWY/Recent Loader\n    sharedViaInvite?: boolean;\n    isShared?: boolean;\n    // from Published Loader\n    published?: boolean;\n    // from Discarded loader\n    isArchivedLibraryElement?: boolean;\n    isPublicLink?: boolean;\n    directCollaboratorCount?: number;\n    shareFlagsAreDirty?: boolean;\n    /**\n     * Computed property based on presence of \"type\" in the\n     * collab_metadata#mine object from USS.\n     */\n    isSWYGroup?: boolean;\n    pinnedVersion?: string;\n    pinnedVersionModifyDate?: Date;\n}\n\nconst USSAssetItemUpdaterOptions: IItemUpdaterOptions<AdobeAsset, USSAdobeAssetUpdaterMetadata> = {\n    localItemType: AdobeAsset,\n    remoteIdProperty: 'asset_id',\n    // We want the SharedCollaboratorChangedEvent to fire when these properties update\n    // so that internally and externally we can respond to this specific event to do\n    // things like update collaborators etc.\n    changeEventMap: new Map([\n        [ '_isShared', SharedCollaboratorChangedEvent ],\n        [ '_isSharedWithYouAsset', SharedCollaboratorChangedEvent ],\n        [ '_isPublicLink', SharedCollaboratorChangedEvent ],\n        [ '_directCollaboratorCount', SharedCollaboratorChangedEvent ]\n    ]),\n    propertyUpdater: new PropertyUpdater({\n        '_name': 'asset_name',\n        '_etag': { get: getEtag },\n        // NOTE: USS team added this field recently, so only some Assets will have this field until\n        //       re-indexing is finished, which has ETA of Feb 28 2023\n        '_repositoryID': 'repo:repositoryId',\n        '_path': { get: getAssetPath, format: 'string' },\n        '_type': { get: getUSSAssetType, format: 'string' },\n        '_size': { name: 'size', format: 'number' },\n        '_version': 'asset_version_id',\n        '_assetClass': { get: getUSSAssetClass, choices: AssetClassChoices, format: 'string' },\n        '_permissions': { get: getPermission, format: 'number' },\n        '_created': { name: 'create_date', format: 'date' },\n        '_modified': { name: 'modify_date', format: 'date' },\n        '_shared': { name: 'collab_metadata#mine.shared_date', format: 'date_as_number' },\n        '_discarded': { name: 'discarded_date', format: 'date' },\n        '_discardedBy': 'discarded_by',\n        '_assetState': { name: 'repo:state', choices: AssetStateChoices, format: 'string' },\n        '_isArchivedLibraryElement': { name: 'isArchivedLibraryElement', format: 'boolean' },\n        '_lastAccessed': { get: getUSSLastAccessed, format: 'date' },\n        '_storageAssignee': { name: 'storage:assignee', format: StorageAssigneeFormat },\n        '_storageRegion': { name: 'region', get: getUSSStorageRegion, format: 'string' },\n        '_createdBy': 'creative_cloud_creator_id',\n        '_isSharedWithYouAsset': { name: 'sharedViaInvite', format: 'boolean' },\n        '_isSWYGroup': { name: 'isSWYGroup', format: 'boolean' },\n        '_isShared': { name: 'isShared', format: 'boolean' },\n        '_isPublicLink': { name: 'isPublicLink', format: 'boolean' },\n        '_directCollaboratorCount': { name: 'directCollaboratorCount', format: 'number' },\n        '_isPublished': { name: 'published', format: 'boolean' },\n        '_imageLength': { name: 'image_height', format: 'number' },\n        '_imageWidth': { name: 'image_width', format: 'number' },\n        '_shareFlagsAreDirty': { name: 'shareFlagsAreDirty', format: 'boolean' },\n        // See notes in AdobeAssetUpdater. Also, USSv2 is passing appMetadata in 2 different fields, sometimes\n        // both. :/ Hopefully, we'll be on USSv3 soon.\n        '_appMetadata._data': {\n            get(source: Partial<USSMetadata>) {\n                const appMetadata1 = source.app_metadata;\n                const appMetadata2 = source['api:metadata/application'];\n                if (!appMetadata1 && !appMetadata2) { return NotFound; }\n                return { ...(appMetadata1 || {}), ...(appMetadata2 || {}) };\n            },\n            format: 'object_subset',\n            set: (parsedSource: any, dest: any) => {\n                const asset = dest as AdobeAsset;\n                asset.appMetadata._mergeData(parsedSource);\n            }\n        },\n        '_ancestorIDs': { name: 'path', isArray: true, format: 'string' },\n        '__links': { name: '_links', format: 'object_subset' },\n        '_createdByClientId': 'repo:createdByClientId',\n        '_representations': { name: 'repo:representations', format: 'object' },\n        '_assetType': 'repo:assetType',\n        '_assetSubType': 'repo:assetSubType',\n        '_pinnedVersion': 'repo:pinnedVersion',\n        '_pinnedVersionModifyDate': { name: 'repo:pinnedVersionModifyDate', format: 'date' }\n    })\n};\n\nexport const USSAdobeAssetUpdater = new ItemUpdater<AdobeAsset, USSAdobeAssetUpdaterMetadata>(USSAssetItemUpdaterOptions);\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport const reloadSpace = Symbol('reloadSpace');\nexport const clearLastReloadError = Symbol('clearLastReloadError');\n","/*************************************************************************\n *   ADOBE CONFIDENTIAL\n *\n *   Copyright 2022 Adobe\n *   All Rights Reserved.\n *\n *   NOTICE:  All information contained herein is, and remains\n *   the property of Adobe and its suppliers, if any. The intellectual\n *   and technical concepts contained herein are proprietary to Adobe\n *   and its suppliers and are protected by all applicable intellectual\n *   property laws, including trade secret and copyright laws.\n *   Dissemination of this information or reproduction of this material\n *   is strictly forbidden unless prior written permission is obtained\n *   from Adobe.\n **************************************************************************/\nimport type { USSAdobeAssetUpdaterMetadata } from './AdobeAsset';\nimport type AdobeAsset from './AdobeAsset';\nimport type { IItemSourceConfig } from '../core/ItemList';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { USSMetadata, USSResponse } from '../interface/USSModel';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport type LibraryContext from '../libraries/LibraryContext';\nimport { USSAssetFilterName } from './USSAssetFilterName';\nimport type USSAdobeAssetFilter from './USSAdobeAssetFilter';\nimport { LazyLoadManager } from '../core/decorators/LazyLoadManager';\nimport { STORAGE_ASSIGNEE_CHANGED } from './AssetEvents';\nimport type { UpdaterMap } from './AdobeAssetFactory';\nimport type CustomModelContext from '../custom-models/CustomModelContext';\nimport { getExcludeMediaTypesFromFilters, getMediaTypesFromFilters } from '../utils/loaderUtils';\n\ninterface IMediaTypes {\n    mediaTypes: string[];\n    excludeMediaTypes: string[];\n}\n\nexport interface IGetUSSResults<T extends IItemSourceConfig<AdobeAsset>> extends IItemLoaderOptions<T>, IMediaTypes {\n    start: number;\n}\n\nexport function getUSSV2ItemData(item: Partial<USSMetadata>): USSAdobeAssetUpdaterMetadata {\n    let publicLink: boolean | undefined = false;\n    let directCount: number | undefined = 0;\n    const collaboration_metadata = item['collaboration_metadata'];\n    if (collaboration_metadata !== undefined) {\n        publicLink = collaboration_metadata.some((collaborator) => {\n            return collaborator.collaborator_id === 'all';\n        });\n        directCount = collaboration_metadata.length;\n    }\n    const collabMetadataMine = item['collab_metadata#mine'];\n    return {\n        ...item,\n        // Presence of collab_metadata#mine indicates that the item is shared with the user via an invite\n        sharedViaInvite: collabMetadataMine !== undefined,\n        // absence of coallb_metadata#mine.type means the user belongs to a group on this Asset\n        // Invitation service cannot detect this case, so lazy-loading collaborator data should\n        // never override isSWYAsset when isSWYGroup is true.\n        isSWYGroup: collabMetadataMine !== undefined && !collabMetadataMine.type,\n        isShared: directCount > 0,\n        isPublicLink: publicLink,\n        directCollaboratorCount: directCount,\n        // No need to refresh collaborators for share flags, directCollaboratorCount, since they are computed\n        // above. Not clearing the collaboratorDataIsDirty flag, because we cannot populate collaboratorArray\n        // from USS.\n        shareFlagsAreDirty: false\n    };\n}\n\nexport interface IUSSLoader<T extends IItemSourceConfig<AdobeAsset>> extends IItemLoader<T> {\n    /**\n     * Loaders must implement this method and call from Loader.loadPage(options)\n     */\n    _getUSSResults(opts: IGetUSSResults<T>): Promise<USSResponse>;\n    /**\n     * Loaders can optionally implement to provide additional metadata that is\n     * implied by the Loader but not included in the USS response.\n     */\n    _getItemData?(item: Partial<USSMetadata>): USSAdobeAssetUpdaterMetadata;\n    /**\n     * Loaders can optionally implement to perform additional internal state management.\n     */\n    _postProcessPage?(loaderPageOpts: IItemLoaderOptions<T>, page: ILoadedPage<T>): void;\n    /**\n     * Loaders can optionally implement to perform additional processing of USS search results.\n     */\n    _extractItems?(session: IUpdateSession<AdobeAsset>, items: USSMetadata[]): AdobeAsset[];\n    /**\n     * Loaders can optionally preload the library context.\n     */\n    _libraryContext?: LibraryContext;\n    /**\n     * Loaders can optionally pass reference to the CustomModelContext.\n     */\n    _customModelContext?: CustomModelContext;\n}\n\nconst DEFAULT_LIMIT = 50;\n\n/**\n * AdobeAsset Loader classes should use this class to do the page loading. Using composition rather\n * than inheritance because a base USSLoader class was causing circular dependencies at runtime that\n * would cause the base USSLoader class to be undefined when the Loader class that was extending it\n * was declared.\n */\nexport default class USSLoaderHelper<T extends IItemSourceConfig<AdobeAsset>> {\n    constructor(\n        private _assetPool: ItemPool<AdobeAsset>,\n        protected _core: ISAMCorePrivate,\n        private _loader: IUSSLoader<T>\n    ) {}\n\n    async loadPage(options: IItemLoaderOptions<T>, start?: number): Promise<ILoadedPage<T>> {\n        const {  order, filter, implicitFilter, resource } = options;\n        const { limit = DEFAULT_LIMIT } = options.loadOptions ?? {};\n        const latency = this._core._environment.getValue('USS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n        start = start || 0;\n\n        const mediaTypes = getMediaTypesFromFilters(implicitFilter, filter);\n        const excludeMediaTypes = getExcludeMediaTypesFromFilters(implicitFilter, filter);\n\n        let uploadedFrom;\n        let userId;\n        if ('name' in filter && filter.name === USSAssetFilterName) {\n            const ussAssetFilter = filter as USSAdobeAssetFilter;\n            uploadedFrom = ussAssetFilter.uploadedFrom;\n            userId = ussAssetFilter.userId;\n        }\n\n        const result: USSResponse = await this._loader._getUSSResults({\n            order,\n            loadOptions: { limit, ...options.loadOptions,  },\n            filter,\n            implicitFilter,\n            resource,\n            start,\n            mediaTypes: Array.from(mediaTypes ?? []),\n            excludeMediaTypes: Array.from(excludeMediaTypes ?? []),\n            ...(uploadedFrom ? { uploadedFrom } : {}),\n            ...(userId ? { userId } : {})\n        });\n\n        const resultSet = result.result_sets[0];\n\n        const updaters = await this._core._adobeAssetFactory.getUSSUpdaters(resultSet.items as USSMetadata[]);\n        const session = this._assetPool.createLoaderUpdateSession(mostRecentValidMutation);\n        const items = this._extractItems(session, resultSet.items as USSMetadata[], updaters);\n\n        let loadNextPage: ILoadNextPage<T> | undefined;\n        const total = resultSet.total_items || 0;\n        const pageItemCount = resultSet.items.length;\n        // [SEARCH-30755] -- May be caused by USS filtering out items due to permissions for the\n        // current user, which aren't subtracted from the total. Try to ensure that the Loader paginates\n        // as though the total_items is correct.\n        const nextStartIndex = (pageItemCount === 0 ? start + limit : start + pageItemCount);\n        if (nextStartIndex < total) {\n            loadNextPage = (options: IItemLoaderOptions<T>) => this.loadPage(options, nextStartIndex);\n        }\n\n        const page: ILoadedPage<T> = {\n            items,\n            total,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n\n        // allow Loader to do additional internal state management (optional)\n        this._loader._postProcessPage?.(options, page);\n\n        // Mark storage assignee as loaded to prevent lazy loading\n        for (const item of items) {\n            LazyLoadManager.updatedByItemUpdater(item, STORAGE_ASSIGNEE_CHANGED);\n        }\n\n        session.commit();\n\n        return page;\n    }\n\n    private _getItemData(item: Partial<USSMetadata>): USSAdobeAssetUpdaterMetadata {\n        return getUSSV2ItemData(item);\n    }\n\n    /**\n     * @package -- for use by USSLoaderHelper\n     */\n    _extractItems(session: IUpdateSession<AdobeAsset>, items: USSMetadata[], updaters: UpdaterMap): AdobeAsset[] {\n        return this._core._adobeAssetFactory.assetsFromUSSMetadata(session, items, this._loader._getItemData || this._getItemData, updaters);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SpaceSearchConfig } from './SpaceSearchSource';\nimport type ItemPool from '../core/ItemPool';\nimport type AdobeAsset from './AdobeAsset';\nimport type { USSMetadata, USSResponse } from '../interface/USSModel';\nimport { OrderByToUSSOrderBy } from '../interface/USSModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type { ISpaceSearchAssetFilterOptions } from './SpaceSearchAssetFilter';\nimport type SpaceSearchAssetFilter from './SpaceSearchAssetFilter';\nimport type USSInterface from '../interface/USSInterface';\nimport type { IGetUSSResults, IUSSLoader } from './USSLoaderHelper';\nimport USSLoaderHelper from './USSLoaderHelper';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type { ISAMCorePrivate } from '../indexPrivate';\n\nexport default class SpaceSearchAssetLoader implements IUSSLoader<SpaceSearchConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<SpaceSearchConfig>;\n\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        core: ISAMCorePrivate,\n        private _asset: AdobeAsset,\n        private _ussInterface: USSInterface,\n        private _artifactFilter: ISpaceSearchAssetFilterOptions['artifactFilter'],\n        private _embedPermissions: boolean = false\n    ) {\n        this._ussLoaderHelper = new USSLoaderHelper(assetPool, core, this);\n    }\n\n    supportsFilter(filter: any): boolean {\n        const supportedFilters: SpaceSearchAssetFilter[] = [];\n        supportedFilters.push(filter);\n\n        // Client can call getList with SpaceSearchAssetFilter.artifactFilter undefined, but can't pass\n        // SSAF.artifactFilter that doesn't match this._artifactFilter\n        if (!supportedFilters.every(f => (f.artifactFilter === this._artifactFilter || f.artifactFilter === undefined))) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST,\n                'SpaceSearchAssetFilter.artifactFilter does not match SpaceSearchAssetLoader.artifactFilter');\n        }\n        return true;\n    }\n\n    loadPage(options: IItemLoaderOptions<SpaceSearchConfig>): Promise<ILoadedPage<SpaceSearchConfig>> {\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- for use by USSLoaderHelper\n     */\n    async _getUSSResults({\n        start,\n        loadOptions,\n        order,\n        mediaTypes\n    }: IGetUSSResults<SpaceSearchConfig>): Promise<USSResponse> {\n        return this._ussInterface.searchSpace(\n            this._asset.id,\n            this._artifactFilter === 'onlyArtifacts',\n            this._embedPermissions,\n            {\n                type: mediaTypes,\n                sort_orderby: OrderByToUSSOrderBy[order.field],\n                sort_order: order.direction === 'descending' ? 'desc' : 'asc',\n                limit: loadOptions?.limit,\n                start_index: start\n            }\n        );\n    }\n\n    /**\n     * @package -- for use by USSLoaderHelper\n     */\n    _getItemData: (item: Partial<USSMetadata>) => Partial<USSMetadata> = this._getItemDataWithRepoId(this._asset.repositoryID);\n\n    private _getItemDataWithRepoId(repoID: string) {\n        // TODO: Patching should be removed once https://jira.corp.adobe.com/browse/SRCH-1989 is fixed\n        //       and re-indexing is finished, which has ETA of Feb 28 2023\n        return (item: Partial<USSMetadata>) => {\n            return {\n                ...item,\n                'repo:repositoryId': repoID\n            };\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type AdobeAsset from './AdobeAsset';\n\nexport interface ISpaceSearchAssetFilterOptions {\n    // For Space.searchWorkingFiles and Space.searchArtifacts, it needs an implicit filter\n    // so the two sources generate separate lists. Can't use the AdobeAsset of the Space or\n    // the working_files folder, because it isn't known at the time the Source is constructed.\n    readonly asset?: AdobeAsset;\n    readonly artifactFilter?: 'onlyArtifacts' | 'excludeArtifacts';\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _includeHiddenRecursive?: boolean;\n}\n\nexport default class SpaceSearchAssetFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    static default = new SpaceSearchAssetFilter();\n    private _asset?: AdobeAsset;\n    readonly artifactFilter?: ISpaceSearchAssetFilterOptions['artifactFilter'];\n\n    constructor(options?: ISpaceSearchAssetFilterOptions) {\n        super({ _includeHiddenRecursive: options?._includeHiddenRecursive });\n        this._asset = options?.asset;\n        this.artifactFilter = options?.artifactFilter;\n    }\n\n    matches(item: AdobeAsset) {\n        // check if item is a descendant of the space/working Files folder\n        if (this._asset?.repoPath && !item.repoPath.startsWith(`${this._asset.repoPath}/`)) {\n            return false;\n        }\n\n        // check item meets artifactFilter criteria\n        if (item.isArtifact && this.artifactFilter === 'excludeArtifacts') {\n            return false;\n        }\n        if (!item.isArtifact && this.artifactFilter === 'onlyArtifacts') {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ShareableItem from '../collaboration/ShareableItem';\nimport { memoize, observable } from '../core/decorators';\nimport type { IProjectsSpace, IProjectsSpaceChild, IProjectsSpaceChildLinks, IProjectsSpaceChildName, IProjectsSpaceLinks, IProjectsSpaceState } from '../interface/WorkspacesModel';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { PropertyFormatType } from '../core/PropertyUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport { isDeepEqual } from '../core/ObjectUtils';\nimport type { ISpaceUpdate } from './SpaceContext';\nimport { SharedChangeEvent } from '../core/ChangeEvent';\nimport { clearLastReloadError, reloadSpace } from '../core/InternalProperties';\nimport { SAMError, assert, SAMErrorCode } from '../core/SAMError';\nimport ItemSource from '../core/ItemSource';\nimport type { SpaceSearchSource } from '../assets/SpaceSearchSource';\nimport SpaceSearchAssetLoader from '../assets/SpaceSearchAssetLoader';\nimport SpaceSearchAssetFilter from '../assets/SpaceSearchAssetFilter';\nimport type { AdobeAssetSource } from '../assets/AdobeAssetSource';\n\nexport type TeamRole = 'UNKNOWN' | 'NONE' | 'MEMBER';\nconst TeamRoles = [ 'UNKNOWN', 'NONE', 'MEMBER' ];\n\nexport type RGBColor = string;\n\nexport type SpaceAccess =\n    | 'private'\n    | 'team';\n\nexport type SpaceRole =\n    | 'NONE'          // Has no access to the space\n    | 'CONTRIBUTOR'   // Has access to all parts of the space and can edit the contents of a space\n    | 'REVIEWER';     // Has read-only access to the artifacts in a space\n\nconst SpaceAccessChoices: SpaceAccess[] = [ 'private', 'team' ];\nconst SpaceRoleChoices: SpaceRole[]  = [ 'NONE', 'CONTRIBUTOR', 'REVIEWER' ];\n\nexport type SpaceState = IProjectsSpaceState;\nconst SpaceStates: SpaceState[] = [ 'active', 'archived', 'in_progress' ];\n\nexport type ISpaceChild = {\n    id: string;\n    _links: IProjectsSpaceChildLinks;\n};\n\nexport type SpaceChildName = IProjectsSpaceChildName;\n\nexport type ISpaceReloadOptions = {\n    refreshTimeout?: number;\n};\n\ntype SpaceReload = {\n    pending: boolean;\n    promise: Promise<void>;\n    generation: number;\n    requestTime: number;\n    inProgress: boolean;\n    error?: any;\n};\n\n/// Represents the notion of a \"space\" where multiple Adobe account holders collaborate\nexport default class Space extends ShareableItem {\n\n    private _name: string = '';\n    private _repositoryID: string = '';\n    private _repositoryName: string = '';\n    private _pathName: string = '';\n    private _created: Date = new Date();\n    private _modified: Date = new Date();\n    private _contributorCount: number = 0;\n    private _role: SpaceRole = 'NONE';\n    private _color: RGBColor = '';\n    private _isBookmarked: boolean = false;\n    private _teamID: string = '';\n    private _teamName: string = '';\n    private _description?: string;\n    private _thumbnail: string = '';\n    private _access: SpaceAccess = 'private';\n    private _etag: string = '';\n    private _children?: Map<SpaceChildName, ISpaceChild>;\n    private _version: number = 0;\n    private _state: SpaceState = 'active';\n    private __links: IProjectsSpaceLinks | undefined;\n\n    private _lastReload?: SpaceReload;\n    private _loadedGeneration: number = 0;\n\n    // Note that we maintain this flag based on where the item was loaded from.\n    // Spaces loaded via the teamAccess=false API will have teamRole='NONE', all other\n    // spaces will assume a 'UNKNOWN' role until they are updated with the correct role\n    // on the client side.\n    private _teamRole: TeamRole = 'UNKNOWN';\n\n    /// The unique id that represents the space.\n    get spaceID(): string {\n        return this.id;\n    }\n\n    /// The user-visible name assigned to the space.\n    @observable\n    get name(): string {\n        return this._name;\n    }\n\n    @observable\n    get access(): SpaceAccess {\n        return this._access;\n    }\n\n    @observable\n    get etag(): string {\n        return this._etag;\n    }\n\n    @observable\n    get state(): SpaceState {\n        return this._state;\n    }\n\n    /// The unique id of the repository that owns this space.\n    @observable\n    get repositoryID(): string {\n        return this._repositoryID;\n    }\n\n    /// The user-visible name of the repository (i.e. the organization name) that owns this space.\n    @observable\n    get repositoryName(): string {\n        return this._repositoryName;\n    }\n\n    /// The full path name for the space (e.g. \"/content/assets/Everyone/Test Space\").\n    @observable\n    get pathName(): string {\n        return this._pathName;\n    }\n\n    /// The created date of the space, relative to 00:00:00 UTC on Jan 1, 1970.\n    @observable\n    get created(): Date {\n        return this._created;\n    }\n\n    /// The modified date of the space, relative to 00:00:00 UTC on Jan 1, 1970.\n    @observable\n    get modified(): Date {\n        return this._modified;\n    }\n\n    /// Total number of contributors for this space. Any groups that are added as a Contributor\n    /// count as 1 toward this total.\n    @observable\n    get contributorCount(): number {\n        return this._contributorCount;\n    }\n\n    /// Role on the space for the current user.\n    @observable\n    get role(): SpaceRole {\n        return this._role;\n    }\n\n    /// The color assigned to the space.\n    @observable\n    get color(): RGBColor {\n        return this._color;\n    }\n\n    /// Indicates whether the space is bookmarked (i.e. followed) by the current user.\n    @observable\n    get isBookmarked(): boolean {\n        return this._isBookmarked;\n    }\n\n    /// The teamID of the parent team.\n    @observable\n    get teamID(): string {\n        return this._teamID;\n    }\n\n    /// The user-visible name of the parent team.\n    @observable\n    get teamName(): string {\n        return this._teamName;\n    }\n\n    /// Description of the space.\n    @observable\n    get description(): string | undefined {\n        return this._description;\n    }\n\n    /// Thumbnail URL of the space.\n    @observable\n    get thumbnail(): string {\n        return this._thumbnail;\n    }\n\n    @observable\n    get version(): number {\n        return this._version;\n    }\n\n    @observable\n    get teamRole(): TeamRole {\n        return this._teamRole;\n    }\n\n    @observable\n    get _links(): IProjectsSpaceLinks | undefined {\n        return this.__links;\n    }\n\n    async ensureDescription(): Promise<string> {\n        if (this._description === undefined) {\n            await this.load({ refreshTimeout: -1 });\n        }\n        return this.description ?? '';\n    }\n\n    async getChild(name: SpaceChildName): Promise<ISpaceChild | undefined> {\n        if (!this._children) {\n            // Retrieve the children of the space if needed.\n            await this.load({ refreshTimeout: -1 });\n        }\n        return this._children?.get(name);\n    }\n\n    // Only used for 1-Off Invitees.\n    // Memoized so the same Source and its Lists can be reused.\n    @memoize\n    async searchWorkingFiles(): Promise<SpaceSearchSource> {\n        const { _assetPool, _ussInterface } = this._core.hostAssetContext;\n\n        const workingFilesFolder = await this._core.hostAssetContext\n            .getAssetWithRepoPath(`${this.pathName}/working_files`, this.repositoryID);\n\n        const spaceSearchAssetLoader = new SpaceSearchAssetLoader(\n            _assetPool,\n            this._core,\n            workingFilesFolder,\n            _ussInterface,\n            'excludeArtifacts',\n            true // always include permissions for 1-off invitees\n        );\n\n        const implicitFilter = new SpaceSearchAssetFilter({\n            asset: workingFilesFolder,\n            artifactFilter: 'excludeArtifacts'\n        });\n        return new ItemSource(_assetPool, [ spaceSearchAssetLoader ], implicitFilter);\n    }\n\n    // All Space members should use `searchArtifacts(false)`, as the UI can assume the user has\n    // full permissions. For 1-Off Invitees, use `searchArtifacts(true)`\n    // Memoized so the same Source and its Lists can be reused -- note that this means you\n    // cannot switch between embedPermissions = true and = false.\n    @memoize\n    async searchArtifacts(embedPermissions: boolean = false): Promise<SpaceSearchSource> {\n        const { _assetPool, _ussInterface } = this._core.hostAssetContext;\n\n        const spaceAdobeAsset = await this._core.hostAssetContext.getAssetWithCloudID(this.id);\n\n        const spaceSearchAssetLoader = new SpaceSearchAssetLoader(\n            _assetPool,\n            this._core,\n            spaceAdobeAsset,\n            _ussInterface,\n            'onlyArtifacts',\n            embedPermissions\n        );\n\n        const implicitFilter = new SpaceSearchAssetFilter({\n            asset: spaceAdobeAsset,\n            artifactFilter: 'onlyArtifacts',\n            // Some artifacts may be in hidden folders\n            _includeHiddenRecursive: true\n        });\n        return new ItemSource(_assetPool, [ spaceSearchAssetLoader ], implicitFilter);\n    }\n\n    @memoize\n    async getWorkingFiles(): Promise<AdobeAssetSource> {\n        // Assuming repo path of working_files rather than getting it via discovery so it is compatible\n        // with SAM.cpp AssetContext. When all of Spaces can be handled in SAM.cpp, this should switch back\n        // to using discovery.\n        // const workingFiles = await this.getChild('working_files');\n        // if (!workingFiles) {\n        //     throw SAMError.create(SAMErrorCode.NOT_FOUND, 'could not load working_files');\n        // }\n        // const folder = await this._core.hostAssetContext.getAssetWithCloudID(workingFiles.id);\n        const folder = await this._core.hostAssetContext\n            .getAssetWithRepoPath(`${this.pathName}/working_files`, this.repositoryID);\n        return folder.children!;\n    }\n\n    async load(options?: ISpaceReloadOptions): Promise<void> {\n        const refreshTimeout = options?.refreshTimeout;\n        let lastReload = this._lastReload;\n        const canReuseLastReload = lastReload && (\n            // The previous load is still pending execution, so we could reuse the same call.\n            lastReload.pending\n            // Just wanted to do at least one load.\n            || refreshTimeout === -1\n            // Just in case the data didn't expire already.\n            || (refreshTimeout && lastReload.requestTime + refreshTimeout > Date.now()));\n\n        if (!canReuseLastReload) {\n            // Otherwise let's load the space again.\n            // Note that generation of reloads, we want to make sure that only the very last reload\n            // gets a chance to update the space.\n            lastReload = this._lastReload = {\n                pending: true,\n                inProgress: true,\n                generation: (lastReload?.generation ?? this._loadedGeneration) + 1,\n                requestTime: Date.now(),\n                promise: new Promise((resolve, reject) => {\n                    // Wait until the loop ends to avoid multiple queries on the same data.\n                    setTimeout(() => this._executeReload(lastReload!).finally(() =>\n                        lastReload!.error ? reject(lastReload!.error) : resolve()), 0);\n                })\n            };\n\n            // Notify the users we have a new loading session.\n            this.dispatch(SharedChangeEvent);\n        }\n\n        await lastReload!.promise;\n    }\n\n    private async _executeReload(reload: SpaceReload) {\n        if (reload !== this._lastReload) {\n            // The same reload will be used inside the load method up to the point when we actually execute the request.\n            // However, there's a case when the `clearLastReloadError` was used while we were waiting. in the setTimeout above.\n            // In that case we can just avoid fetching the request entirely.\n            assert(!reload.pending, 'The pending flag must be false after the reload was cleared out.');\n            return;\n        }\n\n        // Make a note that the request was executed.\n        reload.pending = false;\n        try {\n            await this._core.spaceContext[reloadSpace](this);\n        } catch (error: any) {\n            reload.error = error;\n        }\n        // Check if the asset was removed. We will want to remove it from the lists.\n        reload.inProgress = false;\n\n        const lastReload = this._lastReload;\n        if (lastReload !== reload && reload.generation <= this._loadedGeneration) {\n            // This result is older than a newer request that was already applied to this object.\n            // Ignore the results. This can happen if a particular request takes longer to execute\n            // and a new reload was already good to go.\n            return;\n        }\n\n        if (reload.error instanceof SAMError && reload.error.code === SAMErrorCode.NOT_FOUND) {\n            const session = this._core.spaceContext.spacePool.createUpdateSession();\n            session.queueDiscardedItem(this);\n            session.commit();\n        }\n\n        // Notify about the end of the load sequence.\n        this.dispatch(SharedChangeEvent);\n    }\n\n    /**\n     * If the item gets updated through the listing API then we need to clear any errors from the previous reload.\n     * This usually happens if the user gets re-invited to a space while the space is still in memory.\n     * At that point, we need to clear the previous error when the listing API detects the new space.\n     */\n    [clearLastReloadError]() {\n        const lastReload = this._lastReload;\n        if (lastReload?.error) {\n            lastReload.error = undefined;\n\n            // Setting pending to false to be able to track it inside `_executeReload` above.\n            lastReload.pending = false;\n\n            this.dispatch(SharedChangeEvent);\n        }\n    }\n\n    @observable\n    get isReloading(): boolean {\n        return this._lastReload?.inProgress ?? false;\n    }\n\n    @observable\n    get lastReloadError(): any {\n        return this._lastReload?.error;\n    }\n\n    async update(data: ISpaceUpdate) {\n        await this._core.spaceContext.updateSpace(this, data);\n    }\n\n    async rename(newName: string) {\n        await this._core.spaceContext.updateSpace(this, { name: newName });\n    }\n\n    async archive() {\n        const resultItems = await this._core.spaceContext.archiveSpaces([ this ]);\n        if (resultItems.failedResults.length) {\n            throw  resultItems.failedResults[0].error;\n        }\n    }\n\n    async restore(name?: string) {\n        let nameMap: Map<Space, string> | undefined;\n        if (name !== undefined) {\n            nameMap = new Map();\n            nameMap.set(this, name);\n        }\n        const resultItems = await this._core.spaceContext.restoreSpaces([ this ], nameMap);\n        if (resultItems.failedResults.length) {\n            throw  resultItems.failedResults[0].error;\n        }\n    }\n}\n\nconst SpaceChildFormat: PropertyFormatType = {\n    parse: (value: IProjectsSpaceChild): ISpaceChild => {\n        return {\n            id: value.id,\n            _links: value._links\n        };\n    },\n    isEqual: (a: ISpaceChild, b: ISpaceChild): boolean => {\n        return a.id === b.id && isDeepEqual(a._links, b._links);\n    }\n};\n\nexport const SpaceUpdater = new ItemUpdater<Space, Partial<IProjectsSpace & { teamRole: TeamRole }>>({\n    localItemType: Space,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_name': 'name',\n        '_access': { name: 'access', choices: SpaceAccessChoices },\n        '_etag': 'etag',\n        '_repositoryID': 'repositoryId',\n        '_repositoryName': 'repositoryName',\n        '_pathName': 'pathName',\n        '_created': { name: 'createdDate', format: 'date' },\n        '_modified': { name: 'modifiedDate', format: 'date' },\n        '_contributorCount': { name: 'contributorCount', format: 'number' },\n        '_role': { name: 'role', choices: SpaceRoleChoices },\n        '_color': { name: 'color' },\n        '_isBookmarked': { name: 'bookmarked', format: 'boolean' },\n        '_teamID': 'teamId',\n        '_teamName': 'teamName',\n        '_description': 'description',\n        '_thumbnail': 'thumbnail',\n        '_children': { name: 'children', mapByKey: 'name', format: SpaceChildFormat },\n        '_version': { name: 'version', format: 'number' },\n        '_teamRole': { name: 'teamRole', choices: TeamRoles },\n        '_state': { name: 'state', choices: SpaceStates },\n        '__links': { name: '_links', format: 'object' }\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport InterfaceBase from './InterfaceBase';\nimport { cache, key } from '../core/decorators';\nimport type {\n    IServiceLink,\n    LinkRequirements,\n    HeaderMap } from './LinkUtils';\nimport {\n    RelType,\n    validateLinks,\n    getURLFromLinks,\n    JSON_MIME_TYPE\n} from './LinkUtils';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type { Either } from '../utils/either';\n\nexport type AssetReviewServiceData = {\n    hasArtifacts: boolean;\n}\n\nconst REVIEW_SERVICE_LINKS: LinkRequirements = {\n    [RelType.REVIEW_SERVICE_PROVISION]: [\n        'documentId',\n        'assetRegion',\n        'repositoryId'\n    ],\n    [RelType.REVIEW_SERVICE_DISCARD]: [ 'assetId', 'assetRegion', 'repositoryId' ],\n    [RelType.REVIEW_SERVICE_OUTPUTS]: [\n        'assetId',\n        'assetRegion',\n        'documentId',\n        'embed',\n        'limit',\n        'orderBy',\n        'outputType',\n        'repositoryId',\n        'start'\n    ],\n    [RelType.REVIEW_SERIVCE_HAS_OUTPUTS]: [ 'assetRegion' ]\n};\n\ninterface IReviewServiceIndexLinks {\n    [RelType.REVIEW_SERIVCE_HAS_OUTPUTS]: IServiceLink,\n    [RelType.REVIEW_SERVICE_DISCARD]: IServiceLink,\n    [RelType.REVIEW_SERVICE_OUTPUTS]: IServiceLink,\n    [RelType.REVIEW_SERVICE_PROVISION]: IServiceLink\n}\n\ninterface IReviewServiceIndexResponse {\n    _links: IReviewServiceIndexLinks\n}\n\nexport interface IReviewServiceAssetIdentifer {\n    ['repo:assetId']: string;\n    ['repo:repositoryId']: string;\n}\n\nexport const mapAssetsToAssetIndentifier = function (assets: AdobeAsset[]): IReviewServiceAssetIdentifer[] {\n    return assets.map((asset: AdobeAsset) => {\n        return {\n            'repo:assetId': asset.id,\n            'repo:repositoryId': asset.repositoryID\n        };\n    });\n};\n\nfunction validateReviewServiceLinks(links: any) {\n    return validateLinks(links, REVIEW_SERVICE_LINKS);\n}\n\n// See https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=CreativeCloudAssets&title=Proposal+v2%3A+CCARS+Frame+S4R+APIs\n//  for schema of a response.\nexport interface IReviewServiceFrameLinkResponse {\n    'repo:assetId': string;         /* a unique identifier for cloud source documents (cloud-id)*/\n    'review:documentId': string;    /* a unique identifier for local source documents (xmpDocumentId) */\n    'frameio:reviewLinkId': string; /* a Frame.io identifier for a review link */\n    'frameio:artifactId': string;   /* a Frame.io identifier for an asset ( file or version_stack ) */\n    'frameio:projectId': string;    /* a Frame.io identifier for the project containing the review link */\n    'repo:createdDate': number;     /* Date Time when the review link was created */\n    'repo:modifiedDate': number;    /* Date Time when the review link was updated */\n    'repo:etag': string;            /* etag of the review link stored */\n}\n\n//--------------------------------------------------------------------\n// Parameters for POST/GET/PUT/DELETE to frameLink endpoint\n//\n// The source document is either a local document, in which case\n// you identify it only with documentId ( the XMP DocumentId ),\n// or it's a cloud document, in which case, you provide it's\n// cloud-id as assetId, and optionally provide an assetRegion.\n\ntype ReviewServiceCloudSource = {\n    assetId: string;\n    assetRegion?: string;\n    repositoryId?: string;\n};\n\ntype ReviewServiceLocalSource = {\n    documentId: string;\n};\n\n// AssetReviewServiceInterface.createReviewLink() parameter\nexport type ReviewServiceCreateReviewLinkParam =  Either<ReviewServiceCloudSource, ReviewServiceLocalSource> & {\n    reviewLinkId: string;\n    artifactId: string;\n    projectId: string;\n};\n\n// AssetReviewServiceInterface.getReviewLinks() parameter\nexport type ReviewServiceGetReviewLinksParam =  Either<ReviewServiceCloudSource, ReviewServiceLocalSource> & {\n    reviewLinkId?: string;\n};\n\n// AssetReviewServiceInterface.updateReviewLink() parameter\nexport type ReviewServiceUpdateReviewLinkParam =  Either<ReviewServiceCloudSource, ReviewServiceLocalSource> & {\n    reviewLinkId: string;\n    artifactId: string;\n    projectId: string;\n    etag?: string;\n};\n\n//--------------------------------------------------------------------\n\n// AssetReviewServiceInterface.deleteReviewLink() parameter\nexport type ReviewServiceDeleteReviewLinkParam =  Either<ReviewServiceCloudSource, ReviewServiceLocalSource> & {\n    reviewLinkId: string;\n    etag?: string;\n};\n\n//  end parameters for frameLink endpoint\n//--------------------------------------------------------------------\n\n\nexport default class AssetReviewServiceInterface extends InterfaceBase {\n    public readonly baseURL = `https://${this._core._environment.endpoints.REVIEW_SERVICE_HOST}`;\n    public readonly baseEndpoint: string = '/api/v1';\n    public readonly indexEndpoint = this.baseEndpoint + '/index';\n\n    public getEndpointURL(endpoint: string): string {\n        return `${this.baseURL}${endpoint}`;\n    }\n\n    @cache(validateReviewServiceLinks)\n    private async _discoverLinks(@key rootHref: string): Promise<IReviewServiceIndexLinks> {\n        const response: IReviewServiceIndexResponse = await this._getResponse(rootHref, this._getHeaders());\n        return response._links;\n    }\n\n    private _getHeaders(contentType?: string): HeaderMap {\n        const headers: HeaderMap = {};\n        if (contentType) {\n            headers['Content-Type'] = contentType;\n        }\n        return headers;\n    }\n\n    async discoverLinks(): Promise<IReviewServiceIndexLinks> {\n        return this._discoverLinks(this.getEndpointURL(this.indexEndpoint));\n    }\n\n    public async discardOutputsForAsset(assetId: string, assetRegion?: string, repositoryID?: string): Promise<void> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(\n            links,\n            RelType.REVIEW_SERVICE_DISCARD,\n            {\n                assetId,\n                ...(assetRegion && { assetRegion }),\n                ...(repositoryID && { repositoryID }),\n            }\n        );\n        await this._doPost(url, this._getHeaders(), undefined, [ 204 ]);\n    }\n\n    async hasOutputs(assets: IReviewServiceAssetIdentifer[], assetRegion?: string): Promise<IReviewServiceAssetIdentifer[]> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(\n            links,\n            RelType.REVIEW_SERIVCE_HAS_OUTPUTS,\n            { ...(assetRegion && { assetRegion }) },\n        );\n        const response = await this._doPost(url, this._getHeaders(JSON_MIME_TYPE), JSON.stringify(assets), [ 200 ]);\n        return await response.json();\n    }\n\n    private _createFrameLinkUrl(params: any) {\n        const url = new URL(`${this.baseURL}/api/v1/frameioLink`);\n        Object.entries(params).forEach(([ key, val ]) => url.searchParams.set(key, val as string));\n        return url.toString();\n    }\n\n    /*\n     * See https://wiki.corp.adobe.com/display/CreativeCloudAssets/Proposal+v2%3A+CCARS+Frame+S4R+APIs\n     *\n     * We use the frameLink endpoint for all four CRUD operations, we just change the method:\n     *  POST -> associate a new review with source document\n     */\n    public async createReviewLink(param: ReviewServiceCreateReviewLinkParam): Promise<IReviewServiceFrameLinkResponse> {\n        const { reviewLinkId, artifactId, projectId, ...query } = param;\n\n        const response = await this._doPost(\n            this._createFrameLinkUrl(query),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({\n                reviewLinkId: `${reviewLinkId}`,\n                artifactId: `${artifactId}`,\n                projectId: `${projectId}`\n            })\n        );\n\n        return await response.json();\n    }\n\n    /*\n     * See https://wiki.corp.adobe.com/display/CreativeCloudAssets/Proposal+v2%3A+CCARS+Frame+S4R+APIs\n     *\n     * We use the frameLink endpoint for all four CRUD operations, we just change the method:\n     *  GET -> return array of all reviews associated with source document\n     */\n    public async getReviewLinks(param: ReviewServiceGetReviewLinksParam): Promise<Array<IReviewServiceFrameLinkResponse>> {\n        const response = await this._doGet(\n            this._createFrameLinkUrl(param),\n        );\n\n        return await response.json();\n    }\n\n    /*\n     * See https://wiki.corp.adobe.com/display/CreativeCloudAssets/Proposal+v2%3A+CCARS+Frame+S4R+APIs\n     *\n     * We use the frameLink endpoint for all four CRUD operations, we just change the method:\n     *  PUT -> update an existing review associated with source document\n     */\n    public async updateReviewLink(param: ReviewServiceUpdateReviewLinkParam): Promise<IReviewServiceFrameLinkResponse> {\n        const { artifactId, projectId, etag = '*', ...query } = param;\n\n        const response = await this._doPut(\n            this._createFrameLinkUrl(query),\n            {\n                'Content-Type': 'application/json',\n                'If-Match': `${etag}`\n            },\n            JSON.stringify({\n                artifactId: `${artifactId}`,\n                projectId: `${projectId}`\n            })\n        );\n\n        return await response.json();\n    }\n\n    /*\n     * See https://wiki.corp.adobe.com/display/CreativeCloudAssets/Proposal+v2%3A+CCARS+Frame+S4R+APIs\n     *\n     * We use the frameLink endpoint for all four CRUD operations, we just change the method:\n     *  DELETE -> update an existing review associated with source document\n     */\n    public async deleteReviewLink(param: ReviewServiceDeleteReviewLinkParam): Promise<void> {\n        const { etag, ...query } = param;\n\n        let headers: HeaderMap = {};\n\n        if (etag) {\n            headers = {\n                'If-Match': `${etag}`\n            };\n        }\n\n        // there is no reponse body to a DELETE returning status 204\n        await this._doDelete(\n            this._createFrameLinkUrl(query),\n            headers,\n            [ 204 ]\n        );\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport InterfaceBase from './InterfaceBase';\nimport type {\n    ICommentDeleteCommentData,\n    ICommentGetCommentData,\n    ICommentEditCommentData,\n    CommentCore,\n    CommentData,\n    ICommentMetadata\n} from './CommentModel';\nimport type { HeaderMap } from './LinkUtils';\nimport type { ISAMCorePrivate } from '../indexPrivate';\n\nexport default class CommentInterface extends InterfaceBase {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _assetId: string\n    ) {\n        super(_core);\n    }\n\n    private _getUrl(endpoint: string): string {\n        // TODO: Should we be using a rel links ?\n        //  const url = getURLFromLinks(links, RelType.ASSIGNMENTS_START, { assignmentId });\n\n        return `https://${this._core._environment.endpoints.COMMENT_HOST}${endpoint}`;\n    }\n    private _getCommonHeaders(etag?: string): HeaderMap {\n        const headers: HeaderMap = {\n            'Content-Type': 'application/ld+json; profile=\"https://www.w3.org/ns/anno.jsonld\"',\n            'Accept': 'application/ld+json; profile=\"https://www.w3.org/ns/anno.jsonld\"',\n            'Prefer': 'return=representation;include=\"https://www.w3.org/ns/oa#PreferContainedDescriptions\"',\n            'x-ccx-workflow': 'true'\n        };\n\n        etag && (headers['If-Match'] = etag);\n\n        return headers;\n    }\n\n    /**\n     * @description Get a list of the comments associated with an asset\n     * from the Red Hawk Commenting Service.\n     * @param etag The etag from the previous request, if available\n     * @returns The server Response object\n     *\n     * A typical interface method would return a strongly typed\n     * response.json() ( in this case, an IAnnotationCollection ).\n     *\n     * But we expect the caller to poll this endpoint, so we also\n     * want to return response.headers.get('etag'), so it can be\n     * used as a parameter in the next use of this endpoint,\n     * which allows the server to provide a 206 response ( nothing changed ).\n     *\n     * So this returns the Response object, which lets the caller\n     * obtain both values.\n     */\n    async getCommentList(etag?: string): Promise<Response> {\n        const url = this._getUrl(`/assets/${this._assetId}/annots/?status=open%2Cresolved`);\n        const headers = this._getCommonHeaders();\n\n        etag && (headers['If-None-Match'] = etag);\n\n        return this._doGet(url,\n            {\n                headers,\n                successResponseCodes: [ 200, 208 ]\n            }\n        );\n    }\n\n    /**\n     * @description Get a comment from the Red Hawk Commenting Service.\n     * @param data The information necessary for calling the create API.\n     * @returns A promise that resolves to the server's response,\n     * a CommentCore corresponding to the comment requested for by id.\n     */\n    async getComment(data: ICommentGetCommentData): Promise<CommentCore> {\n        const { annotationId, etag } = data;\n\n        const url = this._getUrl(`/assets/${this._assetId}/annots/${annotationId}?recursive=true`);\n        return this._getResponse(url,\n            {\n                headers: this._getCommonHeaders(etag)\n            }\n        );\n    }\n\n    /**\n     * @description Creates a comment by POST-ing to the Red Hawk Commenting Service.\n     * @param data The information necessary for calling the create API.\n     * @returns A promise that resolves to the server's response.\n     * a CommentCore corresponding to the comment created.\n     */\n    async createComment(data: CommentData): Promise<CommentCore> {\n        // RE: https://git.corp.adobe.com/redhawk/native_client_sdk/blob/fddd524698ec5ad2cb4df23748c845a3c2129243/EurekaClientSDK/api/WebAnnotationsApi.cpp#L469\n        // NOTE : CPP supports ANONBEARER, but for a first draft, we'll\n        // only support BEARER, which we get for free from InterfaceBase\n        // NOTE : We don't need to include User-Agent either\n        // NOTE : Investigate whether we can get the URL from links\n\n        const url = this._getUrl(`/assets/${this._assetId}/annots`);\n        const response = await this._doPost(url,\n            this._getCommonHeaders(),\n            JSON.stringify(data)\n        );\n\n        return response.json();\n    }\n\n    /**\n     * @description Edit a comment from the Red Hawk Commenting Service.\n     * @param data The information necessary for calling the API.\n     * @returns A promise that resolves to the server's response,\n     * a CommentCore corresponding to the updated comment.\n     */\n    async editComment(data: ICommentEditCommentData): Promise<CommentCore> {\n        const { annotationId, etag, body } = data;\n\n        const url = this._getUrl(`/assets/${this._assetId}/annots/${annotationId}`);\n        const response = await this._doPut(url,\n            this._getCommonHeaders(etag),\n            JSON.stringify(body),\n            [ 200 ]\n        );\n\n        // response should be a new annotation.\n\n        return response.json();\n    }\n\n    /**\n     * @description Delete a comment from the Red Hawk Commenting Service.\n     * @param data The information necessary for calling the delete API.\n     * @returns A promise that resolves to void.\n     */\n    async deleteComment(data: ICommentDeleteCommentData): Promise<void> {\n        const { annotationId, etag } = data;\n\n        const url = this._getUrl(`/assets/${this._assetId}/annots/${annotationId}?recursive=true`);\n        await this._doDelete(url,\n            this._getCommonHeaders(etag),\n            [ 204 ]\n        );\n\n        return;\n    }\n\n    /**\n     * @description Get the collection of ICommentMetadata for an asset\n     * with the Red Hawk Commenting Service.\n     * @returns A promise that resolves to the server's response.\n     */\n    async getMetadata(): Promise<ICommentMetadata[]> {\n        const url = this._getUrl(`/assets/${this._assetId}?operation=fetch_user_comment_metadata`);\n        return this._getResponse(url,\n            {\n                headers: this._getCommonHeaders()\n            }\n        );\n    }\n\n    /**\n     * @description Set the metadata for a comment with the Red Hawk Commenting Service.\n     * @param data The information necessary for calling the API.\n     * @returns A promise that resolves to the server's response.\n     */\n    async updateMetadata(data: Partial<ICommentMetadata>): Promise<ICommentMetadata> {\n        const { annotId, read } = data;\n        const annotationId = annotId || '';\n\n        const url = this._getUrl(`/assets/${this._assetId}/annots/${annotationId}/metadata?recursive=false`);\n        const response = await this._doPut(url,\n            {\n                'Content-Type': 'application/vnd.adobe.dc+json;profile=\"https://comments.adobe.io/schemas/annots_metadata.jsonld\"',\n                'Accept': 'application/vnd.adobe.dc+json;profile=\"https://comments.adobe.io/schemas/annots_metadata.jsonld\"',\n                'x-ccx-workflow': 'true'\n            },\n            JSON.stringify({\n                annotId: `/assets/${this._assetId}/annots/${annotationId}`,\n                read: read || false\n            }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport { observable } from '../core/decorators';\nimport ItemBase from '../core/ItemBase';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type {\n    CommentCore,\n    CommentCreator,\n    CommentMention,\n    CommentTarget,\n    MotivationType,\n    GeneratorType,\n    TypeAnnotation,\n    StatusType,\n    CommentData,\n    CommentMetadata\n} from '../interface/CommentModel';\nimport type CommentsResource from './CommentsResource';\nimport type CommentInterface from '../interface/CommentInterface';\nimport type ItemPool from '../core/ItemPool';\n\n// RE: https://wiki.corp.adobe.com/display/ACPCSDK/Commenting+Service+Integration+Into+SAM\n\n// TODO : Commenting can be used by Guest Users\n// RE: https://git.corp.adobe.com/redhawk/native_client_sdk/blob/f0cd86aa3047c1392403b4444b5338189d7302e5/EurekaClientSDK/api/WebAnnotationsApi.cpp\n//  I haven't researched how it's done, but the native code supports\n//  AnonBearer tokens for guest users.\n\n\n/**\n * Class representing the notion of a comment ( aka annotation ).\n * @extends ItemBase\n *\n * @example\n * // Instantiate list and load contents\n * const classroomsList = core.classroomContext.getClassrooms().getList(...options);\n * await waitForListLoad(classroomsList);\n *\n * // Get a specific classroom\n * const load = useMemo(() => core.classroomContext.getClassroomById(id), [classroomContext, id]);\n * const { value: classroom, error, loading } = useLoading<Classroom | undefined>(undefined, load);\n */\n\nexport default class Comment extends ItemBase implements SAM.Comment {\n    private _commentsResource?: CommentsResource;\n\n    // WARNING: the server response for a comment includes\n    //  \"id\": \"/assets/${assetUrn}/annots/${annotationId}\",\n    //  \"creationId\": \"${annotationId}\",\n    //\n    // so we map \"creationId\" to comment.id\n    // because ItemBase.id is expected to be the object's cloud-id,\n    // and \"id\" to comment.uri to avoid a naming conflict.\n\n    private _creator?: CommentCreator = undefined;\n    private _created: Date = new Date(0);\n    private _bodyValue?: string = undefined;\n    private _motivation?: MotivationType = undefined;\n    private _generator: GeneratorType = 'https://comments.acrobat.com/Comment';\n    private _type: TypeAnnotation = 'Annotation';\n    private _target?: CommentTarget = undefined;\n    private _mentions?: Array<CommentMention> = undefined;\n    private _modified: Date = new Date(0);\n    private _etag?: string = undefined;\n    private _uri?: string = undefined;\n    private _status?: StatusType = undefined;\n    private _replies?: Array<CommentCore> = undefined;\n    private _readStatus: boolean = false;\n\n    //-----------------------------------------------------------------\n    // Simple accessors\n\n    @observable\n    get creator(): any {\n        return this._creator;\n    }\n\n    @observable\n    get created(): Date {\n        return this._created;\n    }\n\n    @observable\n    get bodyValue(): string {\n        return this._bodyValue || '';\n    }\n\n    @observable\n    get motivation(): MotivationType {\n        // Possible values are ('commenting' | 'replying')\n        return this._motivation || 'commenting';\n    }\n\n    @observable\n    get generator(): GeneratorType {\n        // Possible value is 'https://comments.acrobat.com/Comment'\n        return this._generator || 'https://comments.acrobat.com/Comment';\n    }\n\n    @observable\n    get type(): TypeAnnotation {\n        // Possible value is 'Annotation'\n        return this._type || 'Annotation';\n    }\n\n    @observable\n    get target(): CommentTarget | undefined {\n        return this._target;\n    }\n\n    @observable\n    get mentions(): Array<CommentMention> | undefined {\n        return this._mentions;\n    }\n\n    @observable\n    get modified(): Date {\n        return this._modified;\n    }\n\n    @observable\n    get etag(): string {\n        return this._etag || '';\n    }\n\n    @observable\n    get uri(): string {\n        return this._uri || '';\n    }\n\n    @observable\n    get status(): StatusType {\n        // Possible values are ('open' | 'resolved')\n        return this._status || 'open';\n    }\n\n    @observable\n    get replies(): Array<CommentCore> | undefined {\n        // Possible values are ('open' | 'resolved')\n        return this._replies;\n    }\n\n    @observable\n    get readStatus(): boolean {\n        return this._readStatus;\n    }\n\n    toJSON() {\n\n        // When an object implements toJSON()\n        // JSON.stringify(object) serializes object.toJSON()\n        // instead of object, allowing you to control\n        // the keys and values written.\n        //\n        // This method is returning a Partial<CommentCore>\n        // which can be used in a POST or PUT to the server.\n\n        return {\n            '@context': [\n                'https://www.w3.org/ns/anno.jsonld',\n                'https://comments.acrobat.com/ns/anno.jsonld'\n            ],\n            'creator': this._creator,\n            'created': this.created.toISOString(),\n            'bodyValue': this.bodyValue,\n            'motivation': this.motivation,\n            'generator': this.generator,\n            'type': this.type,\n            'target': this.target,\n\n            /* TODO : 'mentions' : this.mentions */\n\n            'modified': this.modified.toISOString(),\n            'etag': this.etag,\n\n            // Map ItemBase.id back to 'creationId',\n            // and Comment.uri back to 'id'.\n\n            'id': this.uri,\n            'creationId': this.id,\n            'status': this.status,\n\n            /* TODO :  'replies': this.replies, */\n        };\n\n    }\n    // Simple accessors\n    //-----------------------------------------------------------------\n\n    get assetUrn(): string {\n        // Split \"/assets/${assetUrn}/annots/${annotationId}\"\n        // into ['', 'assets', assetUrn, 'annots', annotationId]\n        // so we can return assetUrn\n\n        const uri = this.uri;\n        const array = uri.split('/');\n\n        return (array.length > 2) ? array[2] : '';\n    }\n\n    private get _pool(): ItemPool<Comment> {\n        return this._commentsResource!._commentPool!;\n    }\n\n    private get _interface(): CommentInterface {\n        return this._commentsResource!._commentInterface!;\n    }\n\n    //-----------------------------------------------------------------\n    // Public methods\n\n    async edit(changes: Partial<CommentCore>): Promise<Comment> {\n        const commentInterface = this._interface;\n        const commentPool = this._pool;\n\n        // Get our current state as a CommentCore\n        const current: Partial<CommentCore> = this.toJSON();\n\n        // combine current with changes\n        const body: Partial<CommentCore> = { ...current, ...changes };\n\n        // update the server with the edited body\n        const response = await commentInterface.editComment({\n            annotationId: this.id,\n            etag: this.etag,\n            body\n        });\n\n        // update our local object with the server response, triggering notifications\n        const session = commentPool.createUpdateSession<Comment>();\n        CommentUpdater.updateLocalItem(session, this, response);\n        session.commit();\n\n        return this;\n    }\n\n    async updateResolvedStatus(isResolved: boolean): Promise<Comment> {\n        const status = isResolved ? 'resolved' : 'open';\n\n        return this.edit({ status });\n    }\n\n    async updateReadStatus(isRead: boolean): Promise<Comment> {\n        const commentInterface = this._interface;\n        const commentPool = this._pool;\n\n        const response = await commentInterface.updateMetadata({\n            annotId: this.id,\n            read: isRead\n        });\n\n        const session = commentPool.createUpdateSession<Comment>();\n        CommentUpdater.updateLocalItem(session, this, {\n            creationId: this.id,\n            readStatus: response.read\n\n        });\n        session.commit();\n\n        return this;\n    }\n\n    async delete(): Promise<void> {\n        const commentInterface = this._interface;\n        const commentPool = this._pool;\n        const id = this.id;\n\n        await commentInterface.deleteComment({\n            annotationId: id,\n            etag: this.etag\n        });\n\n        // after the server deletes the remote object,\n        // discard our local object which triggers notifications\n        const session = commentPool.createUpdateSession<Comment>();\n        session.queueDiscardedItem(this);\n        session.commit();\n\n        // the session doesn't actually remove the item from the pool\n        commentPool.removeLocalItems([ id ]);\n    }\n\n    /**\n     * @description Create a reply to this comment.\n     * @param data The information necessary for calling the API.\n     * @returns A promise that resolves to the newly created reply.\n     */\n    async reply(data: CommentData): Promise<Comment> {\n        const required: Partial<CommentCore> = {\n            motivation: 'replying',\n            target: {\n                source: this.uri\n            }\n        };\n\n        // overwrite data with the reply required fields\n        return this._commentsResource!.createComment({ ...data, ...required });\n    }\n}\n\nexport const CommentUpdater = new ItemUpdater<Comment, Partial<CommentCore | CommentMetadata>>({\n    localItemType: Comment,\n\n    // NOTE: We are using property 'creationId' in the response as the ItemBase.id\n\n    remoteIdProperty: 'creationId',\n    propertyUpdater: new PropertyUpdater({\n        // TODO : create nested updater for CommentCreator ?\n        _creator: { name: 'creator', format: 'object' },\n\n        // TODO : this is a Date.toISOString(); should this be Date ?\n        _created: { name: 'created', format: 'date' },\n\n        _bodyValue: { name: 'bodyValue', format: 'string' },\n\n        // should be ( 'commenting' | 'replying' ), but allow any string (future proof)\n        _motivation: { name: 'motivation', format: 'string' },\n\n        // should be 'https://comments.acrobat.com/Comment', but allow any string (future proof)\n        _generator: { name: 'generator', format: 'string' },\n\n        // should be 'Annotation', but allow any string (future proof)\n        _type: { name: 'type', format: 'string' },\n\n        // TODO : create nested updater for CommentTarget ?\n        _target: { name: 'target', format: 'object' },\n\n        // TODO : create nested updater for CommentMention[] ?\n        _mentions: { name: 'mentions', format: 'object' },\n\n        // TODO : this is a Date.toISOString(); should this be Date ?\n        _modified: { name: 'modified', format: 'date' },\n\n        _etag: { name: 'etag', format: 'string' },\n\n        // NOTE: 'creationId' is mapped to ItemBase.id,\n        // and 'id' is mapped to comment.uri.\n        _uri: { name: 'id', format: 'string' },\n\n        // should be ( 'open' | 'resolved' ), but allow any string (future proof)\n        _status: { name: 'status', format: 'string' },\n\n        // TODO : create nested updater for Comment[] ?\n        _replies: { name: 'replies', format: 'object' },\n\n        _readStatus: { name: 'readStatus', format: 'boolean' }\n    }),\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type Comment from './Comment';\nimport { CommentUpdater } from './Comment';\nimport type { CommentConfig } from './CommentSource';\nimport type CommentsResource from './CommentsResource';\nimport type ItemPool from '../core/ItemPool';\nimport type CommentInterface from '../interface/CommentInterface';\nimport type { IAnnotationCollection } from '../interface/CommentModel';\n\nexport default class CommentLoader implements IItemLoader<CommentConfig> {\n    private _etag?: string;\n    private _retryAfter?: string;\n\n    constructor(private _commentsResource: CommentsResource) {}\n\n    async loadPage(options: IItemLoaderOptions<CommentConfig>): Promise<ILoadedPage<CommentConfig>> {\n        return await this._loadPage(options);\n    }\n\n    get retryAfter(): number {\n        // convert seconds:string into milliseconds:Number\n        return +(this._retryAfter || '12') * 1000;\n    }\n\n    private get _pool(): ItemPool<Comment> {\n        return this._commentsResource!._commentPool!;\n    }\n\n    private get _interface(): CommentInterface {\n        return this._commentsResource!._commentInterface!;\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<CommentConfig>, start?: number): Promise<ILoadedPage<CommentConfig>> {\n        // Red Hawk doesn't paginate or sort, so parameters are ignored.\n        options; start;\n\n        // For the initial load(), this._etag is undefined.\n        // When polling(), it's the etag from the last call.\n\n        // NOTE: This makes the assumption the loader is only used for one list,\n        // which is true in the CommentsResource case.\n        const response = await this._interface.getCommentList(this._etag);\n\n        // use (get() || undefined) to convert null into undefined\n        this._retryAfter = response.headers.get('retry-after') || undefined;\n        this._etag = response.headers.get('etag') || undefined;\n        const status = response.status;\n\n        // For (status === 200), the body is a list of comments.\n        if (status === 200) {\n            const result = await response.json() as IAnnotationCollection;\n\n            const items = result.first.items;\n\n            const session = this._pool.createLoaderUpdateSession(Date.now());\n            const comments = CommentUpdater.updateRemoteItems(session, items);\n            session.commit();\n\n            comments.forEach((comment) => {\n                comment['_commentsResource'] = this._commentsResource;\n            });\n\n            return {\n                items: comments,\n                total: comments.length,\n                loadNextPage: undefined\n            };\n        }\n\n        // For (status === 208), the body is omitted because our local etag\n        // matches the remote etag ( aka nothing has changed ).\n        //\n        // We are required to return a list of comments, and we've already\n        // assumed CommentsResource has one list for one loader, so we'll\n        // return the existing list of comments.\n        const comments = this._commentsResource.getCommentList()?.items || [];\n\n        return {\n            items: comments,\n            total: comments.length,\n            loadNextPage: undefined\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type Comment from './Comment';\n\nexport type CommentOrderField =\n    | 'created';\n\nconst OrderFieldToComparator: IComparatorMap<Comment, CommentOrderField> = {\n    created(a: Comment, b: Comment): number {\n        return compareValues(a.created.getTime(), b.created.getTime());\n    },\n};\n\nexport default class CommentOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new CommentOrder('ascending', 'created');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMEvent from '../core/SAMEvent';\n\nexport const COMMENTS_CHANGED = 'commentsChanged';\n\nexport default class CommentsResourceChangeEvent extends SAMEvent {\n    constructor(\n        readonly annotationIds: string[]\n    ) {\n        super(COMMENTS_CHANGED);\n    }\n}\n\nexport const CommentsChangedEventInstance = new CommentsResourceChangeEvent([]);\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport ItemPool from '../core/ItemPool';\nimport CommentInterface from '../interface/CommentInterface';\nimport type { IEventMap } from '../core/TypedEventEmitter';\nimport TypedEventEmitter from '../core/TypedEventEmitter';\nimport type Comment from '../comments/Comment';\nimport { CommentUpdater } from '../comments/Comment';\nimport type {\n    CommentData,\n    ICommentGetCommentData,\n    ICommentMetadata\n} from '../interface/CommentModel';\nimport type { CommentConfig, CommentSource } from '../comments/CommentSource';\nimport CommentLoader from '../comments/CommentLoader';\nimport ItemSource from '../core/ItemSource';\nimport type { IItemList } from '../core/ItemList';\nimport CommentOrder from './CommentOrder';\nimport { waitForListLoad } from '../utils/waitForListLoad';\nimport CommentsResourceChangeEvent, { COMMENTS_CHANGED, CommentsChangedEventInstance } from './CommentsResourceChangeEvent';\nimport type { ONSChangedAssetInfo } from '../sync-services/ONSEvent';\nimport { observable } from '@sam-js-src/core/decorators';\n\nexport interface CommentsResourceEvents extends IEventMap {\n    [COMMENTS_CHANGED]: CommentsResourceChangeEvent;\n}\n\n\nexport default class CommentsResource extends TypedEventEmitter<CommentsResourceEvents> implements ISAMObject {\n\n    /**\n     * @package -- for SAM.js internal use only\n     */\n    readonly _commentInterface = new CommentInterface(this._core, this._assetId);\n\n    /**\n     * @package -- for SAM.js internal use only\n     */\n    readonly _commentPool: ItemPool<Comment> = new ItemPool<Comment>(this._core, 'comment');\n\n    private _loader =  new CommentLoader(this);\n\n    private _source: CommentSource =  new ItemSource(this._commentPool, [ this._loader ]);\n\n    private _list?: IItemList<CommentConfig>;\n\n    private _stopTimeout?: ReturnType<typeof setTimeout>;\n\n    private _unreadCount: number = 0;\n\n    constructor(readonly _core: ISAMCorePrivate, readonly _assetId: string) {\n        super();\n    }\n\n    /**\n     * @description Get a list of the comments associated with an asset\n     * from the Red Hawk Commenting Service.\n     * @param data The information necessary for calling the API.\n     * @returns A promise that resolves to the server's response,\n     * an Array of CommentCore's listing the asset's comments.\n     */\n    async createComment(data: CommentData): Promise<Comment> {\n\n        // Update the remote object with our proposed edit\n        const response = await this._commentInterface.createComment(data);\n\n        // The server has successfully updated the remote object,\n        // so update our local object to match the final state.\n        const session = this._commentPool.createUpdateSession<Comment>();\n        const comment = CommentUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        comment['_commentsResource'] = this;\n\n        return comment;\n    }\n\n    /**\n     * @experimental API is not ready and mock data is being used\n     *\n     * @param data creation data (e.g. title, instructions, etc)\n     *\n     * @returns a promise that resolves to the assignment recently and successfully created\n     */\n    async getComment(data: ICommentGetCommentData): Promise<Comment> {\n        let comment = this._commentPool.getLocalItemById(data.annotationId);\n\n        if (!comment) {\n            // fetch remote asset with a server call\n            const response = await this._commentInterface.getComment(data);\n            const session = this._commentPool.createUpdateSession<Comment>();\n            comment = CommentUpdater.updateRemoteItem(session, response);\n            session.commit();\n\n            // @ts-expect-error : bit of a hack\n            comment._commentsResource = this;\n        }\n\n        return comment;\n    }\n\n    getCommentList(): IItemList<CommentConfig> {\n        if (!this._list) {\n            this._list = this._source.getList(CommentOrder.default, undefined, { refreshTimeout: -1 });\n            this._updateMetadata();\n        }\n        return this._list;\n    }\n\n    @observable(CommentsChangedEventInstance)\n    get unreadCount(): number {\n        return this._unreadCount;\n    }\n\n    private async _updateMetadata() {\n        if (!this._list) {\n            return;\n        }\n        await waitForListLoad(this._list);\n\n        // TODO: should this be done when polling? Or every N polls? Typically, read status is always going to be updated\n        //     locally, so shouldn't need to sync with remote except on the first fetch. Maybe a PM question.\n\n        // unfortunately, we'll have to explicitly load the metadata ourselves\n        // to update the readStatus ( as it's per-user data ).\n        const array: ICommentMetadata[] = await this._commentInterface.getMetadata();\n        const readStatuses = new Map(array.map(item => [ item.annotId, item.read ]));\n\n        const session = this._commentPool.createUpdateSession<Comment>();\n        const currentUserId = this._core._environment.getValue('USER_ID');\n        // Only update comments in the pool. If a comment is added/removed between fetching the comment list and\n        // the comment read statuses, there could be a mismatch. If so, it will eventually be consistent with the next\n        // poll.\n        this._commentPool.forEach((comment) => {\n            // The Red Hawk service doesn't save metadata until it's been\n            // explicitly set, so it's expected that a comment doesn't\n            // always have corresponding metadata, in which case it's in\n            // the default (readStatus === false) state.\n\n            // Frustratingly, metadata.creationId looks like\n            //  \"d4bd6758-6234-4e67-aa6e-fcb6712304d9:8CF81E8A5CD449B40A49403E@c62f24cc5b5b7e0e0a494004\"\n            // but comment.creationId looks like\n            //  \"d4bd6758-6234-4e67-aa6e-fcb6712304d9\"\n            // So match using the annotId ( which has been rename uri in the comment ).\n            const readStatus = readStatuses.get(comment.uri) || comment.creator.id.includes(currentUserId) || false;\n\n            if (comment.readStatus !== readStatus) {\n                CommentUpdater.updateRemoteItem(session, {\n                    creationId: comment.id,\n                    readStatus\n                });\n            }\n        });\n        this._unreadCount = this._list.items.filter(item => !item.readStatus).length;\n        session.commit();\n        this.emit(COMMENTS_CHANGED);\n    }\n\n    private async _poll() {\n        const list = this.getCommentList();\n\n        // let the loader re-load the list of comments\n        list.setNeedsRefresh();\n        list.refresh();\n        this._updateMetadata();\n\n        this._stopTimeout = setTimeout(() => this._poll(), this._loader.retryAfter);\n    }\n\n    startShortPoll() {\n        if (!this._stopTimeout) {\n            this._poll();\n        }\n    }\n\n    stopShortPoll(): void {\n        if (this._stopTimeout) {\n            clearTimeout(this._stopTimeout);\n            this._stopTimeout = undefined;\n        }\n    }\n\n    get isShortPollActive(): boolean {\n        return (this._stopTimeout !== undefined);\n    }\n\n    /**\n     * @package -- for SAM.js internal use only\n     */\n    public _onONSNotification(assetInfo: ONSChangedAssetInfo) {\n        this.emit(COMMENTS_CHANGED, new CommentsResourceChangeEvent(assetInfo.annotationIds || []));\n        this._list?.setNeedsRefresh();\n        this._list?.refresh();\n        this._updateMetadata();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Enum for network status currently only used with the Native Bindings\n * so this has been migrated from AssetContext to help avoid importing\n * AssetContext directly instead of by type.\n *\n * @note Must be kept in sync with NetworkStatus in AssetContext.h\n */\nexport enum NetworkStatus {\n    Offline,\n    Wan,\n    Cellular,\n    // on web, it might not be known if the connection is Wan or Cellular\n    OnlineUnknown\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2025 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\ntype AnyFunction = (this: any, ...args: any) => any;\n\n/**\n * Creates a throttled version of the given function that only calls the original function\n * after the specified delay has passed, even if the throttled function is called multiple times.\n *\n * @example\n *   const throttled = throttle(() => console.log('Hello'), 1000);\n *   throttled();\n *   throttled(); // prints 'Hello' after 1 second, only once\n */\nexport default function throttle<T extends AnyFunction>(fn: T, delay: number): T {\n    let timeout: ReturnType<typeof setTimeout> | null = null;\n    return function (this: ThisParameterType<T>, ...args: Parameters<T>) {\n        const self: ThisParameterType<T> = this;\n        if (!timeout) {\n            timeout = setTimeout(() => {\n                fn.apply(self, args);\n                timeout = null;\n            }, delay);\n        }\n    } as T;\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2022 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type { IOrderDirection } from '../ItemOrder';\nimport type { AdobeAssetOrderField } from '../../assets/AdobeAssetOrder';\nimport type AdobeAssetOrder from '../../assets/AdobeAssetOrder';\nimport ExtendClass, { $OVERRIDDEN_GETTERS } from '../ExtendClass';\nimport type AdobeAssetFilter from '../../assets/AdobeAssetFilter';\nimport type { LocalAssetMetadata } from '../../assets/AdobeAsset';\nimport AdobeAsset from '../../assets/AdobeAsset';\nimport oneTimeWarning from '../../utils/oneTimeWarning';\nimport { SharedChangeEvent } from '../ChangeEvent';\nimport { SharedListChangedEvent, SharedStateChangedEvent } from '../ItemList';\nimport SAMEvent from '../SAMEvent';\nimport type { Permission } from '../../interface/AssetModel';\nimport type AssetInterface from '../../interface/AssetInterface';\nimport Space from '../../workspaces/Space';\nimport SAMError, { SAMErrorCode } from '../SAMError';\nimport type { SpaceSearchSource } from '../../assets/SpaceSearchSource';\nimport type AssetVersion from '../../assets/AssetVersion';\nimport AssetVersionLoader from '../../assets/AssetVersionLoader';\nimport ItemSource, { OrderDirection, OrderField } from '../ItemSource';\nimport ItemPool from '../ItemPool';\nimport SpaceSearchAssetLoader from '../../assets/SpaceSearchAssetLoader';\nimport SpaceSearchAssetFilter from '../../assets/SpaceSearchAssetFilter';\nimport type { default as AssetContext } from '../../assets/AssetContext';\nimport type { IReviewServiceAssetIdentifer } from '../../interface/AssetReviewServiceInterface';\nimport AssetReviewServiceInterface, { mapAssetsToAssetIndentifier } from '../../interface/AssetReviewServiceInterface';\nimport { AssetListStatus } from '../ItemLoaderState';\nimport type { RepositoryMetadata } from '../../interface/RepositoryModel';\nimport { RenditionStatus } from '../../utils/RenditionFetcher';\nimport type { ISAMCorePrivate } from '../../indexPrivate';\nimport { SharedCollaboratorChangedEvent } from '../../indexPrivate';\nimport EverythingFilter from '../../core/EverythingFilter';\nimport type Collaborator from '../../collaboration/Collaborator';\nimport { COLLABORATOR_CHANGED } from '../../../src/indexPrivate';\nimport CommentsResource from '../../comments/CommentsResource';\nimport EffectivePermissionsResource from '../../assets/EffectivePermissionsResource';\nimport { NetworkStatus } from '../../assets/NetworkStatus';\nimport type { RecentAdobeAssetSource } from '../../assets/RecentAdobeAssetSource';\nimport throttle from '../../utils/throttle';\nimport setURLSearchParams from '../../utils/searchParams';\n\ninterface IACPLAssetContext {\n    getAssetWithCloudID(assetID: string): AdobeAsset;\n    recentsSource: RecentAdobeAssetSource;\n    rootFolder: AdobeAsset;\n    on(event: string, listener: (data: any) => void): void;\n    off(event: string, listener: (data: any) => void): void;\n\n    /** @package Only used here for the SAM-C++ patches. */\n    _isForwardingAssetChangeEvents?: boolean;\n    /** @deprecated -- will be removed on or after 2024-10-01 */\n    spaceContext: any;\n}\n\nexport const SAM_CPP_ITEM_EVENTS = [ 'refreshed', 'movedAsset', 'addedAsset', 'removedAsset' ];\nexport const LIST_CHANGE_DELAY_MS = 120;\n\nexport interface IACPLModel {\n    waitForApplicationContextReady(): Promise<IACPLAssetContext>;\n    getHostAssetContext(): Promise<IACPLAssetContext>;\n    trigger(event: string, data: any): void;\n    on(event: string, listener: (data: any) => void): void;\n    off(event: string, listener: (data: any) => void): void;\n\n    getLocalAssets?(): Promise<LocalAssetMetadata[]>;\n    /** ACPL.next polyfill */\n    downloadComposite?(assetID: string): Promise<void>;\n    /** ACPL.next polyfill (\"unpin\" is just to remove the composite from cache) */\n    unpin?(assetID: string): Promise<void>;\n\n    applicationAssetContext: IACPLAssetContext;\n    version: string;\n}\n\n/*\nNOTE when testing in UXP SAM Demo app:\n\nWhen using Chrome debugger to refresh the JS source code, it does not destroy and recreate the SAM.cpp\nJS prototypes, so any changes made to this file will not be applied despite appearing in the source\ninspector. You have to quit the SAM.cpp demo app and restart.\n*/\n\n// Use a getter so that unit tests can inject a mock acplModel\nexport function getACPLModel(): IACPLModel | undefined {\n    // NOTE: must use this syntax for accessing properties of `window`, or else it will break NodeJS clients\n    // like Libraries.\n    // @ts-expect-error\n    return typeof window !== 'undefined' ? window?.acplModel : undefined;\n}\n\n// Convert semver into a padded string that can be compared lexically\nfunction parseVersion(version: string = ''): string {\n    // Old SAM.cpp versions looked like 2.0.0-main.1234, where the final number was the\n    // patch version. Current SAM.cpp uses standard semver major.minor.patch.\n    const parts: string[] = version.split('.');\n\n    // Coerce old SAM.cpp version into a standard semver, like 2.0.1234, by\n    // deleting the '0-main' element\n    if (parts[2] === '0-main') {\n        parts.splice(2, 1);\n    }\n    // Ensure each part has some value\n    const [ major = '0', minor = '0', patch = '0' ] = parts;\n    // '2.0.1234' becomes '000200001234'\n    return [ major, minor, patch ].map(part => part.padStart(4, '0')).join('');\n}\n\nfunction isSAMCppVer(comparison: 'lt' | 'gte', version: string) {\n    const aVer = parseVersion(getACPLModel()?.version);\n    const bVer = parseVersion(version);\n    switch (comparison) {\n    case 'lt': return aVer < bVer;\n    case 'gte':return aVer >= bVer;\n    default: return false;\n    }\n}\n\nclass ThumbnailChangeEvent extends SAMEvent {\n    constructor() {\n        super('thumbnailChange');\n    }\n}\nconst SharedThumbnailChangeEvent = new ThumbnailChangeEvent();\n\nclass PermissionsChangeEvent extends SAMEvent {\n    constructor() {\n        super('permissionsChange');\n    }\n}\n\nconst SharedPermissionsChangeEvent = new PermissionsChangeEvent();\n\ninterface IObservableAsset {\n    _onAssetChanged(): void;\n    _onRenditionChanged(): void;\n    _hasArtifacts: boolean | undefined;\n    id: string;\n    isDiscarded: boolean;\n}\ninterface IAssetsChangedEvent {\n    status: IObservableAsset[];\n    properties: IObservableAsset[];\n    previews: IObservableAsset[];\n}\n\n// See note above about testing in UXP SAM demo app\nexport function patchAssetContext(core: ISAMCorePrivate) {\n    const acplModel = getACPLModel()!;\n    // TODO: expose SAM.cpp AssetContext as acplModel.AssetContext\n    // https://jira.corp.adobe.com/browse/SAM-1365\n    const AssetContextJS = acplModel.applicationAssetContext.constructor;\n\n    // TODO: update actual version when the issues below are fixed\n    if (isSAMCppVer('lt', '9999.9999.9999')) {\n        ExtendClass({\n            klass: AssetContextJS,\n            core,\n            overrides: {\n                // SAM.cpp does not support optional param\n                getAssetWithCloudID(this: any, id: string, confirmAccess: boolean = false) {\n                    return this.getAssetWithCloudID.original(id, confirmAccess);\n                },\n                // SAM.cpp does not support optional param\n                getAssetWithAssetRefString(this: any, assetRefString: string, confirmAccess: boolean = false) {\n                    return this.getAssetWithAssetRefString.original(assetRefString, confirmAccess);\n                }\n            },\n            extensions: {\n                // SAM.cpp hasn't implemented AssetContext#getUserRepoId(). This method was added to\n                // address *SAM-1888*. This patch can be removed when SamCpp supports AssetContext#getUserRepoId()\n                getUserRepoID(this: any) {\n                    // Can't use hostAssetContext.getUserRepoID() because it needs hostAssetContext.itemPool,\n                    // which doesn't exist on SAM.cpp hostAssetContext.\n                    if (!this._userRepoID) {\n                        return this._core._AssetContextJS._rapi.getHomeDirectoryMetadata()\n                            .then((homeDirectoryMetadata: RepositoryMetadata) => {\n                                this._userRepoID = homeDirectoryMetadata['repo:repositoryId'];\n                                return this._userRepoID;\n                            });\n                    }\n                    return Promise.resolve(this._userRepoID);\n                },\n\n                transfer(this: any, source: AdobeAsset, target: AdobeAsset | Space): Promise<string> {\n                    return (async () => {\n                        let targetId: string;\n                        if (target instanceof Space) {\n                            const workingFiles = await target.getChild('working_files');\n                            if (!workingFiles) {\n                                throw SAMError.create(SAMErrorCode.NOT_FOUND, 'unable to find working_files for provided space');\n                            }\n                            targetId = workingFiles.id;\n                        } else {\n                            targetId = target.cloudID;\n                        }\n\n                        // ACPL substitutes ~ for user's repoID\n                        let sourceRepoID = source.repositoryID;\n                        let targetRepoID = target.repositoryID;\n                        if (sourceRepoID === '~') {\n                            sourceRepoID = await this.getUserRepoID();\n                        }\n                        if (targetRepoID === '~') {\n                            targetRepoID = await this.getUserRepoID();\n                        }\n\n                        const payload = {\n                            source: { assetId: source.cloudID, repositoryId: sourceRepoID },\n                            target: { assetId: targetId, repositoryId: targetRepoID }\n                        };\n\n                        return this._core._AssetContextJS._assetTransferService.transfer(payload);\n                    })();\n                },\n\n                // For code in SAM.js that needs to use the ItemPool from SAM.js, like SpaceContext.moveSpace()\n                /**\n                 * @deprecated To be removed on or after 2024-10-01.\n                 */\n                assetPool: {\n                    get(this: any) {\n                        oneTimeWarning('SAMCpp.ts _assetPool', 'AssetContext._assetPool is deprecated and will be'\n                            + ' removed on or after 2024-10-01. ItemPools are not for use by clients.');\n                        return this._core._AssetContextJS._assetPool;\n                    }\n                },\n\n                /**\n                 * @package -- for use in SAM.js only\n                 */\n                _assetPool: {\n                    get(this: any) {\n                        return this._core._AssetContextJS._assetPool;\n                    }\n                },\n\n                isOnline: {\n                    get(this: any) {\n                        return this.networkStatus !== undefined ? this.networkStatus !== NetworkStatus.Offline : undefined;\n                    }\n                },\n\n                // Most JS clients never used recentsSource, so use the SAM.js name\n                recentAssetsSource: {\n                    get(this: any) {\n                        return this.recentsSource;\n                    }\n                },\n\n                getRootFolder(this: any): Promise<AdobeAsset> {\n                    return Promise.resolve(this.rootFolder);\n                },\n\n                assetsHaveArtifacts(assets: AdobeAsset[]) {\n                    return (async () => {\n                        // @ts-expect-error\n                        if (assets.some((a: AdobeAsset) => !a.routesToAcplV2)) {\n                            return false;\n                        }\n\n                        const assetReviewServiceInterface = new AssetReviewServiceInterface(core);\n                        const assetIndentifiers: IReviewServiceAssetIdentifer[] = mapAssetsToAssetIndentifier(assets);\n                        const results = await assetReviewServiceInterface.hasOutputs(assetIndentifiers);\n                        if (results.length === 0) {\n                            return false;\n                        }\n\n                        results.forEach((asset) => {\n                            const foundAsset = assets.find((a) => a.id === asset['repo:assetId']);\n                            if (!foundAsset) {\n                                return;\n                            }\n\n                            foundAsset['_hasArtifacts'] = true;\n                            foundAsset.dispatch({ type: 'change' });\n                        });\n\n                        return true;\n                    })();\n                }\n            },\n            observableMap: {\n                'networkChanged': [ 'networkStatus' ],\n                'stateChanged': [ 'cloudSyncStatus' ]\n            }\n        });\n        const onAssetsChanged = ({ properties, status, previews }: IAssetsChangedEvent) => {\n            for (const asset of [ ...properties, ...status ]) {\n                asset._onAssetChanged?.();\n            }\n\n            for (const asset of previews) {\n                asset?._onRenditionChanged?.();\n            }\n        };\n        // only subscribe once\n        if (!acplModel.applicationAssetContext._isForwardingAssetChangeEvents) {\n            acplModel.applicationAssetContext.on('changedAssets', onAssetsChanged);\n            acplModel.applicationAssetContext._isForwardingAssetChangeEvents = true;\n        }\n    }\n}\n\n// See note above about testing in UXP SAM demo app\nexport function patchAssetSource(core: ISAMCorePrivate) {\n    const acplModel = getACPLModel()!;\n\n    const dirMap: { [key in IOrderDirection]: OrderDirection } = {\n        ascending: OrderDirection.Ascending,\n        descending: OrderDirection.Descending\n    };\n\n    const fieldMap: { [key in AdobeAssetOrderField]: OrderField} = {\n        name: OrderField.Name,\n        modified: OrderField.Modified,\n        created: OrderField.Created,\n        shared: OrderField.Shared\n    };\n\n    const AssetSource = acplModel.applicationAssetContext.rootFolder.children!.constructor;\n\n    // TODO: update actual version when the issues below are fixed\n    if (isSAMCppVer('lt', '9999.9999.9999')) {\n        ExtendClass({\n            klass: AssetSource,\n            core,\n            overrides: {\n                // SAM.cpp doesn't support Order/Filter objects that SAM.js clients are using. Meanwhile,\n                // clients like CDO are expecting the SAM.cpp call signature, so both APIs are supported here.\n                getList(this: any, maybeOrder: (AdobeAssetOrder | OrderDirection), maybeFilter?: (AdobeAssetFilter | OrderField)) {\n                    let field: OrderField;\n                    let dir: OrderDirection;\n\n                    // if both `direction` and `field` are defined, then it is an AdobeAssetOrder instance\n                    const order = maybeOrder as AdobeAssetOrder;\n                    if (order.direction ?? order.field ?? true) {\n                        dir = dirMap[order.direction];\n                        field = fieldMap[order.field];\n                    } else {\n                        dir = maybeOrder as OrderDirection;\n                        field = maybeFilter as OrderField;\n                        maybeFilter = undefined;\n                    }\n\n                    // Fallback to safe defaults\n                    dir = (dir in OrderDirection) ? dir : OrderDirection.Descending;\n                    field = (field in OrderField) ? field : OrderField.Modified;\n\n                    const filter = maybeFilter as AdobeAssetFilter;\n                    let list: any;\n                    // Note: if mediaTypes is undefined, it should use the default filter (SAM.cpp only)\n                    // If mediaTypes is an empty array, that means \"show everything\".\n                    if (filter?.mediaTypes) {\n                        list = this.getListWithTypes(dir, field, [ ...filter.mediaTypes ]);\n                    } else {\n                        list = this.getList.original(dir, field);\n                    }\n                    // Note: must patch AssetList before patching AssetSource or else next line will throw an exception\n                    list._addEventInterceptors();\n                    return list;\n                }\n            }\n        });\n    }\n}\n\n// See note above about testing in UXP SAM demo app\nexport function patchAssetList(core: ISAMCorePrivate) {\n    const acplModel = getACPLModel()!;\n\n    const SAM_CPP_ITEM_EVENTS = [ 'refreshed', 'movedAsset', 'addedAsset', 'removedAsset' ];\n    const SAM_CPP_STATUS_EVENT = 'statusChanged';\n\n    // TODO: expose AssetSource, AssetList as acplModel.AssetSource, acplModel.AssetList\n    // https://jira.corp.adobe.com/browse/SAM-1365\n    const assetSource = acplModel.applicationAssetContext.rootFolder.children!;\n    const AssetList = assetSource.getList(OrderDirection.Descending, OrderField.Modified).constructor;\n\n    // TODO: update actual version when the issues below are fixed\n    if (isSAMCppVer('lt', '9999.9999.9999')) {\n        ExtendClass({\n            klass: AssetList,\n            core,\n            extensions: {\n                // SAM.cpp doesn't have loadNextPage, so map to loadMoreItems\n                loadNextPage(this: any) {\n                    return this.loadMoreItems();\n                },\n                // TODO: deprecate SAM.cpp load() and add refresh()\n                //       https://jira.corp.adobe.com/browse/SAM-2099\n                refresh(this: any) {\n                    return this.load();\n                },\n                // patchAssetSource calls this\n                _addEventInterceptors(this: any) {\n                    // only subscribe once\n                    if (!this._onError) {\n                        this._onError = (error: string) => {\n                            this._errors = this._errors || [];\n                            this._errors.push(error);\n                            this.dispatch(SharedStateChangedEvent);\n                        };\n                        this.on('error', this._onError);\n                    }\n\n                    if (!this._onListNotification) {\n                        this._onListNotification = throttle(() => {\n                            // Invoke the SAM.cpp items getter\n                            this._items = this[$OVERRIDDEN_GETTERS]['items'].call(this);\n                            this.dispatch(SharedListChangedEvent);\n                            // Also fire status change so that items list is at the expected contents\n                            // when the status changes. Clients may post-process and cache list items\n                            // from SharedListChangedEvent, so SharedStateChangeEvent must be fired\n                            // afterward to ensure their cache has all expected items when the status changes.\n                            this.dispatch(SharedStateChangedEvent);\n                        }, LIST_CHANGE_DELAY_MS);\n\n                        // SAM.cpp fires 4 different events for list change, but SAM.js clients only expect 1.\n                        SAM_CPP_ITEM_EVENTS.forEach(eventName => this.on(eventName, this._onListNotification));\n                    }\n\n                    if (!this._onStatusChange) {\n                        this._onStatusChange = () => {\n                            // After calling getList, clients should immediately receive the Loading\n                            // status change event\n                            if (this.status === AssetListStatus.Loading) {\n                                this.dispatch(SharedStateChangedEvent);\n                            } else {\n                                this._onListNotification();\n                            }\n                        };\n                        this.on(SAM_CPP_STATUS_EVENT, this._onStatusChange);\n                    }\n                },\n                errors: {\n                    get(this: any) {\n                        // Mobx observes under the SAM.js status event, rather than the CPP events\n                        this._core._environment.mobx.reportObserved(this, SharedStateChangedEvent.type);\n                        return this._errors;\n                    }\n                }\n            },\n            overrides: {\n                load(this: any) {\n                    this._errors = undefined;\n                    this.load.original();\n                    this.dispatch(SharedStateChangedEvent);\n                },\n                loadMoreItems(this: any) {\n                    this.loadMoreItems.original();\n                    this.dispatch(SharedStateChangedEvent);\n                },\n                // SAM.cpp creates a new Array instance and populates it every time clients call `list.items`, which\n                // adds a small (but non-zero) performance hit, and has unexpected behavior like\n                // `list.items !== list.items`. This patch caches the SAM.cpp items Array.\n                items: {\n                    get(this: any) {\n                        this._core._environment.mobx.reportObserved(this, SharedListChangedEvent.type);\n                        if (!this._items) {\n                            // Invoke the SAM.cpp getter\n                            this._items = this[$OVERRIDDEN_GETTERS]['items'].call(this);\n                        }\n                        return this._items;\n                    }\n                }\n            },\n            observableMap: {\n                // This makes 'status' property observable under the SAM.js SharedStateChangedEvent\n                [SharedStateChangedEvent.type]: [ 'status' ]\n                // The 'items' property is made observable in the getter override under the SharedListChangeEvent\n            }\n        });\n    }\n}\n\n// @TODO Will be used once https://jira.corp.adobe.com/browse/SAM-2145 is resolved.\nexport function patchTeamList(core: ISAMCorePrivate): void {\n    const acplModel = getACPLModel()!;\n    if (isSAMCppVer('gte', '9999.9999.9999')) {\n        return;\n    }\n\n    const spacesContext = acplModel.applicationAssetContext.spaceContext;\n    const teamsList = spacesContext.getTeams()\n        .getList(OrderDirection.Descending, OrderField.Name).constructor;\n    ExtendClass({\n        klass: teamsList,\n        core,\n        extensions: {\n            // TODO: deprecate SAM.cpp load() and add refresh()\n            //       https://jira.corp.adobe.com/browse/SAM-2099\n            refresh(this: any) {\n                return this.load();\n            }\n        }\n    });\n}\n\n// See note above about testing in UXP SAM demo app\nexport function patchAdobeAsset(core: ISAMCorePrivate) {\n    const acplModel = getACPLModel()!;\n    const ACPLAsset = acplModel.applicationAssetContext.rootFolder.constructor;\n    // TODO: update actual version when the issues below are fixed\n    if (isSAMCppVer('lt', '9999.9999.9999')) {\n        ExtendClass({\n            klass: ACPLAsset,\n            core,\n            overrides: {\n                restore(this: any, name?: string) {\n                    if (this.isLibraryElement) {\n                        // SAM.cpp doesn't support restoring CCLibrary Elements\n                        return this._core._AssetContextJS.restoreLibraryElement(this.cloudID);\n                    } else {\n                        return this.restore.original(name);\n                    }\n                },\n                permanentlyDelete(this: any) {\n                    if (this.isLibraryElement) {\n                        // SAM.cpp doesn't support permanently deleting CCLibrary Elements\n                        return this._core._AssetContextJS.permanentlyDeleteLibraryElement(this.cloudID);\n                    } else {\n                        return this.permanentlyDelete.original();\n                    }\n                },\n                duplicate(this: any) {\n                    return this.duplicate.original(false /*overWriteExisting*/);\n                }\n            },\n            extensions: {\n                // SAM.cpp doesn't have a `_setCollaboratorData`, which is called when the bulk fetch response is received in _handleBatchRequest.\n                _setCollaboratorData(this: any, updatedCollaborators: Collaborator[]) {\n                    AdobeAsset.prototype._setCollaboratorData.apply(this, [ updatedCollaborators ]);\n                    this._isCollaboratorDataLoaded = true;\n                    this.dispatch(SharedCollaboratorChangedEvent);\n                },\n                _queueCollaborators() {\n                    if (!this._isCollaboratorDataLoaded) {\n                        AdobeAsset.prototype._queueCollaborators.apply(this);\n                    }\n                },\n                // SAM.cpp doesn't have a `isShared` property\n                isShared: {\n                    get(this: any) {\n                        this._core._environment.mobx.reportObserved(this, COLLABORATOR_CHANGED);\n                        // SWY Assets are shared, so no need to load collaborator data\n                        // if isSharedWithYouAsset is false, it might not be known if it is a SWY item\n                        if (this.isSharedWithYouAsset) { return true; }\n                        this._queueCollaborators();\n                        return this._isShared;\n                    }\n                },\n                // SAM.cpp doesn't have a `directCollaboratorCount` property\n                directCollaboratorCount: {\n                    get(this: any) {\n                        this._core._environment.mobx.reportObserved(this, COLLABORATOR_CHANGED);\n                        this._queueCollaborators();\n                        return this._directCollaboratorCount;\n                    }\n                },\n                // SAM.cpp doesn't have a `collaboratorArray` property\n                collaboratorArray: {\n                    get(this: any) {\n                        this._core._environment.mobx.reportObserved(this, COLLABORATOR_CHANGED);\n                        this._queueCollaborators();\n                        return this._collaboratorsArray;\n                    }\n                },\n                // SAM.cpp doesn't have an `isPublicLink` property\n                isPublicLink: {\n                    get(this: any) {\n                        this._core._environment.mobx.reportObserved(this, COLLABORATOR_CHANGED);\n                        this._queueCollaborators();\n                        return this._isPublicLink;\n                    }\n                },\n                // SAM.cpp doesn't have an `id` property\n                id: {\n                    get(this: any) {\n                        // `id` is observable because cloudID and localID are observable\n                        // due to defaultObservableEvent\n                        return this.cloudID || this.localID;\n                    }\n                },\n                // SAM.cpp doesn't expose leave\n                removeCurrentUserFromCollaborationList(this: any): Promise<void> {\n                    return this._core.collaborationContext._removeCurrentUserFromCollaborationList(this);\n                },\n                // SAM.cpp doesn't expose discard\n                discard(this: any) {\n                    // For Projects items, archive() will do a discard\n                    return this.archive().then(() => {\n                        if (!this.routesToAcplV2) {\n                            oneTimeWarning('discardAsArchive',\n                                `Asset.discard(): '${this.repoPath}' will be archived rather than discarded`\n                                + ' because it routes to ACPL v1 rather than V2.');\n                        }\n\n                        // Archive might not be complete in the cloud yet, so monitor via event listener\n                        const discardOutputs = () => {\n                            // If the asset is not discarded or does not have artifacts\n                            // or does not route to ACPLv2 we don't want to attempt to discard\n                            // the outputs folder.\n                            if (!this.isDiscarded || !this._hasArtifacts || !this.routesToAcplV2) { return; }\n\n                            const assetReviewServiceInterface = new AssetReviewServiceInterface(this._core);\n                            assetReviewServiceInterface.discardOutputsForAsset(this.id).then(() => {\n                                this._hasArtifacts = false;\n                                this.off(SharedChangeEvent.type, discardOutputs);\n                            });\n                        };\n\n                        this.on(SharedChangeEvent.type, discardOutputs);\n\n                        // in case it did complete in the cloud\n                        if (this.isDiscarded && this._hasArtifacts) { discardOutputs(); }\n                    });\n                },\n                // SAM.cpp doesn't have `links`\n                links: {\n                    get(this: any) {\n                        // Can't infer the real links because there's no way to know the real region the Asset is\n                        // hosted. Can't use the generalized endpoints, because when the service redirects to the\n                        // regionalized endpoint, it can drop the auth headers, causing the redirect to fail. For\n                        // now, return empty object to prevent `undefined` errors.\n                        return {};\n                    }\n                },\n                hasPermission(this: any, ...permissions: Permission[]): boolean {\n                    this._core._environment.mobx.reportObserved(this, SharedPermissionsChangeEvent.type);\n                    const hasPermissions = !!this._permissions && AdobeAsset.prototype.hasPermission.apply(this, permissions);\n                    if (!this._hasLoadedPermissions) {\n                        // prevent loading when already loading\n                        this._hasLoadedPermissions = true;\n                        this._core._AssetContextJS._rapi.resolveById(this.cloudID)\n                            .then(async (assetInterface: AssetInterface) => {\n                                const resource = new EffectivePermissionsResource(this._core);\n                                await assetInterface.getEffectivePermissions(resource);\n                                return resource.data;\n                            })\n                            .then((permissions: Permission) => {\n                                this._permissions = permissions;\n                                this.dispatch(SharedPermissionsChangeEvent);\n                            });\n                    }\n                    return hasPermissions;\n                },\n                // SAM.cpp doesn't have thumbnailURL\n                thumbnailURL: {\n                    get(this: any) {\n                        this._core._environment.mobx.reportObserved(this, SharedThumbnailChangeEvent.type);\n                        // Library Elements do not work on SAM.cpp at all\n                        if (this.isFolder || this.isLibraryElement) {\n                            return '';\n                        }\n                        if (this._refreshThumbnail || !this._thumbnailInfo) {\n                            // Prevent multiple calls to getThumbnailRendition. ACPLAsset.ts didn't retry\n                            // on reject, so this code shouldn't need to.\n                            this._refreshThumbnail = false;\n                            this._thumbnailStatus = RenditionStatus.Fetching;\n                            this.getThumbnailRendition()\n                                .then(({ file, hash }: { file: string, hash: string }) => {\n                                    this._thumbnailStatus = RenditionStatus.Done;\n                                    if (this._thumbnailInfo?.file === file && this._thumbnailInfo?.hash === hash) {\n                                        return; // no change\n                                    }\n                                    // `#` and `^` must be encoded separately to work in UXP\n                                    file = file.replace('#', '%23').replace('^', '%5E');\n\n                                    const url = new URL(`file://${file}`);\n                                    setURLSearchParams(url, {\n                                        force: hash\n                                    });\n                                    this._thumbnailInfo = {\n                                        file,\n                                        hash,\n                                        url: url.href\n                                    };\n                                    this.dispatch(SharedThumbnailChangeEvent);\n                                })\n                                .catch(() => {\n                                    this._thumbnailStatus = RenditionStatus.Error;\n                                    // Use empty thumbnailInfo so that re-render due to the status change doesn't try to\n                                    // fetch, which will probably still fail, getting stuck in a loop.\n                                    this._thumbnailInfo = {};\n\n                                    this.dispatch(SharedThumbnailChangeEvent);\n                                });\n                        }\n                        // While waiting for thumbnail, return existing thumbnail (if it exists) so the\n                        // UI doesn't go blank while waiting.\n                        return this._thumbnailInfo?.url || '';\n                    }\n                },\n\n                thumbnailStatus: {\n                    get(this: any) { return this._thumbnailStatus ?? RenditionStatus.NotStarted; }\n                },\n\n                getRenditionURL() {\n                    oneTimeWarning(\n                        'getRenditionURL',\n                        'SAM.cpp does not support all options of getRenditionURL. Clients that run on web'\n                        + ' and desktop should use AdobeAsset.thumbnailURL instead.');\n                    return this.thumbnailURL;\n                },\n\n                renditionURLStatus(this: any) { return this.thumbnailStatus; },\n\n                clearRenditionError(this: any) {\n                    if (this._thumbnailStatus === RenditionStatus.Error) {\n                        this._thumbnailStatus = RenditionStatus.NotStarted;\n                        this._thumbnailInfo = undefined;\n                        this._refreshThumbnail = true;\n                        this.dispatch(SharedThumbnailChangeEvent);\n                    }\n                },\n\n                // SAM.cpp fires Asset events via AssetContext, but SAM.js emits them from AdobeAsset\n                _onAssetChanged(this: any) {\n                    this.dispatch(SharedChangeEvent);\n                },\n                _onRenditionChanged(this: any) {\n                    this._refreshThumbnail = true;\n                    // Raise event so only clients that are observing will refresh the thumbnail\n                    this.dispatch(SharedThumbnailChangeEvent);\n                },\n                transferToSpace(this: AdobeAsset, target: Space | AdobeAsset) {\n                    return this._core.hostAssetContext.transfer(this, target);\n                },\n                // SAM.cpp doesn't have versions\n                versions: {\n                    get(this: any) {\n                        if (this._assetVersionSource) { return this._assetVersionSource; } // memoize\n                        const versionPool = new ItemPool<AssetVersion>(this._core, 'version');\n                        const getAssetInterface = this._core._AssetContextJS._rapi.resolveById(this.id);\n                        const loader = new AssetVersionLoader(versionPool, getAssetInterface);\n                        this._assetVersionSource = new ItemSource(versionPool, [ loader ], new EverythingFilter());\n                        return this._assetVersionSource;\n                    }\n                },\n                // SAM.cpp doesn't have getCommentsResource\n                getCommentsResource(this: any): Promise<CommentsResource> {\n                    if (!this._commentsResource) {\n                        // TODO: lazy-load CommentsResource module\n                        this._commentsResource = new CommentsResource(this._core, this.id);\n                    }\n                    return this._commentsResource;\n                },\n                hasArtifacts: {\n                    get(this: any) {\n                        this._core._environment.mobx.reportObserved(this, 'change');\n                        return this._hasArtifacts;\n                    }\n                }\n            },\n            // make all getter properties observable under the standard 'change' event\n            defaultObservableEvent: SharedChangeEvent.type\n        });\n    }\n}\n\n\ninterface IPatchedSpace extends Space {\n    _searchWorkingFilesSource: Promise<SpaceSearchSource>;\n    _searchArtifactsSource: Promise<SpaceSearchSource>;\n}\n\nexport function patchSpaceJS() {\n    const acplModel = getACPLModel()!;\n    const assetContext = acplModel.applicationAssetContext;\n\n    // Prior to version 1524, SAM.cpp space search APIs were not working correctly\n    // https://jira.corp.adobe.com/browse/SAM-1886\n    // https://jira.corp.adobe.com/browse/SAM-2189\n    if (isSAMCppVer('gte', '2.0.0-main.1524') && isSAMCppVer('lt', '9999.9999.9999')) {\n        // Until SAM.cpp can supply everything needed from SpaceContext and Spaces UI is not\n        // dependant on SAM.js internals, patching the Sources for Space contents to use SAM.cpp\n        // Sources so Spaces UI can have caching/badging.\n        Object.defineProperties(Space.prototype, {\n            searchWorkingFiles: {\n                value(this: IPatchedSpace): Promise<SpaceSearchSource> {\n                    if (this._searchWorkingFilesSource) {\n                        return Promise.resolve(this._searchWorkingFilesSource);\n                    }\n                    this._searchWorkingFilesSource = new Promise((resolve, reject) => {\n                        assetContext.spaceContext.lookupSpaceById(this.id)\n                            .then((space: Space) => {\n                                // `space` is the SAM.cpp Space object\n                                if (!space) {\n                                    reject(SAMError.create(SAMErrorCode.NOT_FOUND, `searchWorkingFiles could not find Space ${this.id}`));\n                                }\n                                resolve(space.searchWorkingFiles());\n                            });\n                    });\n                    return this._searchWorkingFilesSource;\n                }\n            },\n\n            searchArtifacts: {\n                value(this: IPatchedSpace, embedPermissions = false): Promise<SpaceSearchSource> {\n                    if (this._searchArtifactsSource) {\n                        return Promise.resolve(this._searchArtifactsSource);\n                    }\n                    this._searchArtifactsSource = new Promise((resolve, reject) => {\n                        assetContext.spaceContext.lookupSpaceById(this.id)\n                            .then((space: Space) => {\n                                // `space` is the SAM.cpp Space object\n                                if (!space) {\n                                    reject(SAMError.create(SAMErrorCode.NOT_FOUND, `searchArtifacts could not find Space ${this.id}`));\n                                }\n                                resolve(space.searchArtifacts(embedPermissions));\n                            });\n                    });\n                    return this._searchArtifactsSource;\n                }\n            }\n        });\n    } else if (isSAMCppVer('lt', '2.0.0-main.1524')) {\n        // For the prior versions of SAM where we don't have space search\n        // support in SAM.cpp we are using the temp code\n        // to use _AssetContextJS for _assetPool, USSInterface;\n        // use hostAssetContext for workingFilesFolder or spaceAdobeAsset\n        Object.defineProperties(Space.prototype, {\n            searchWorkingFiles: {\n                async value(this: Space): Promise<SpaceSearchSource> {\n                    const assetContext: AssetContext = this._core._AssetContextJS!;\n                    const { _assetPool, _ussInterface } = assetContext;\n\n                    // We need to use the hostAssetContext as we need to get updates from SAM.cpp AdobeAsset so that the search\n                    // filter works fine in case of updates to the space.\n                    const workingFilesFolder = await this._core.hostAssetContext\n                        .getAssetWithRepoPath(`${this.pathName}/working_files`, this.repositoryID);\n\n                    const spaceSearchAssetLoader = new SpaceSearchAssetLoader(\n                        _assetPool,\n                        this._core,\n                        workingFilesFolder,\n                        _ussInterface,\n                        'excludeArtifacts',\n                        true // always include permissions for 1-off invitees\n                    );\n\n                    const implicitFilter = new SpaceSearchAssetFilter({\n                        asset: workingFilesFolder,\n                        artifactFilter: 'excludeArtifacts'\n                    });\n                    return new ItemSource(_assetPool, [ spaceSearchAssetLoader ], implicitFilter);\n                }\n            },\n\n            searchArtifacts: {\n                async value(this: Space, embedPermissions = false): Promise<SpaceSearchSource> {\n                    // SAM.cpp AssetContext doesn't expose _assetPool/_ussInterface, so need\n                    // to fall back to the JS impl of AssetContext when present. This is\n                    // required as SAM.cpp space search APIs are not patched for\n                    // SAM versions prior to 1524\n                    const assetContext: AssetContext = this._core._AssetContextJS!;\n                    const { _assetPool, _ussInterface } = assetContext;\n\n                    // We need to use the hostAssetContext as we need to get updates from SAM.cpp AdobeAsset so that the search\n                    // filter works fine in case of updates to the space.\n                    const spaceAdobeAsset = await this._core.hostAssetContext.getAssetWithCloudID(this.id);\n\n                    const spaceSearchAssetLoader = new SpaceSearchAssetLoader(\n                        _assetPool,\n                        this._core,\n                        spaceAdobeAsset,\n                        _ussInterface,\n                        'onlyArtifacts',\n                        embedPermissions\n                    );\n\n                    const implicitFilter = new SpaceSearchAssetFilter({\n                        asset: spaceAdobeAsset,\n                        artifactFilter: 'onlyArtifacts',\n                        // Some artifacts may be in hidden folders\n                        _includeHiddenRecursive: true\n                    });\n                    return new ItemSource(_assetPool, [ spaceSearchAssetLoader ], implicitFilter);\n                }\n            }\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Logger Log Level.\n *\n * Enum representing the levels of logging messages.\n *\n * @enum\n * @property NONE - No logging.\n * @property ERROR - Log only error messages.\n * @property WARN - Log warning and error messages.\n * @property INFO - Log informational, warning, and error messages.\n * @property DEBUG - Log all messages including debug information.\n */\nexport enum LogLevel {\n    NONE,\n    ERROR,\n    WARN,\n    INFO,\n    DEBUG\n}\n\n/**\n * Logger Interface.\n */\nexport interface LogSink {\n    error(message: string): void;\n    warn(message: string): void;\n    info(message: string): void;\n    debug(message: string): void;\n}\n\n/**\n * Loggable Interface.\n * @remarks This interface defines the methods for logging messages.\n * @remarks The logDebug(), logInfo(), logWarn(), and logError() methods log messages at different levels.\n */\nexport interface Loggable {\n    logDebug(message: string, ...optionalParams: any[]): void;\n    logInfo(message: string,  ...optionalParams: any[]): void;\n    logWarn(message: string, ...optionalParams: any[]): void;\n    logError(message: string, ...optionalParams: any[]): void;\n}\n\nconst SOURCE_ID_LENGTH = 16;\n\nfunction replacer(_key: any, value: any) {\n    switch (true) {\n    case value instanceof Map:\n        return { 'Map': Array.from(value.entries()) };\n    case value instanceof Set:\n        return { 'Set': [ ...value ] };\n    default:\n        return value;\n    }\n}\n\n/**\n * Logger class.\n */\nexport class Logger {\n    private readonly _prefix;\n    private readonly _logSink: LogSink = console;\n\n    public includeTimestamp = true;\n    public logLevel: LogLevel = LogLevel.WARN;\n\n    private static _isoTime(): string { return new Date().toISOString().slice(11); }\n\n    public static _epochToIsoTimeString(epoch: number): string { return new Date(epoch).toISOString().slice(11); }\n\n    private _formatMessage(message: string, source: string, ...optionalParams: any[]): string {\n        const timestamp = this.includeTimestamp ? `[${Logger._isoTime()}]` : '';\n        if (optionalParams.length) {\n            message += ' <<<DATA\\n' + JSON.stringify(optionalParams, replacer, 2) +  '\\nDATA;';\n        }\n        source = source.padEnd(SOURCE_ID_LENGTH, ' ');\n        return `[${this._prefix}]${timestamp}[${source}] ${message}`;\n    }\n\n    constructor(prefix: string, logSink: LogSink = console) {\n        this._prefix = prefix;\n        this._logSink = logSink;\n    }\n\n    /**\n     * Logs a debug message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logDebug(message: string, source: string, ...optionalParams: any[]) {\n        if (this.logLevel >= LogLevel.DEBUG) {\n            message = this._formatMessage(message, source, ...optionalParams);\n            this._logSink?.debug(message);\n        }\n    }\n\n    /**\n     * Logs an info message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logInfo(message: string, source: string, ...optionalParams: any[]) {\n        if (this.logLevel >= LogLevel.INFO) {\n            message = this._formatMessage(message, source, ...optionalParams);\n            this._logSink?.info(message);\n        }\n    }\n\n    /**\n     * Logs a warning message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logWarn(message: string, source: string, ...optionalParams: any[]) {\n        if (this.logLevel >= LogLevel.WARN) {\n            message = this._formatMessage(message, source, ...optionalParams);\n            this._logSink?.warn(message);\n        }\n    }\n\n    /**\n     * Logs an error message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     * @remarks If the first optional parameter is an Error object, the message will be appended with the error message.\n     * @remarks If the first optional parameter is a string value, that value will be used as cause in the error message.\n     */\n    logError(message: string, source: string, ...optionalParams: any[]) {\n        if (this.logLevel >= LogLevel.ERROR) {\n            if (optionalParams[0] instanceof Error) {\n                const error = optionalParams[0] as Error;\n                message += `(${error.message}`;\n                if (error.cause) {\n                    message += `: ${error.cause}`;\n                }\n                message += ')';\n                optionalParams.shift();\n            } else if (typeof optionalParams[0] === 'string') {\n                const errorMessage = optionalParams[0] as string;\n                message += `(${errorMessage})`;\n                optionalParams.shift();\n            }\n            message = this._formatMessage(message, source, ...optionalParams);\n            this._logSink?.error(message);\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { LogSink } from './Logging';\nimport { Logger } from './Logging';\n\n/**\n * @module AxonClientConfig\n * @file Adobe Axon Client Config.\n */\n\n\n/**\n * Simplified fetch-like lambda, acting as always-authenticated HTTPS proxy, capable of performing HTTP GET request.\n */\nexport type AxonClientAuthenticatedGet = (url: string) => Promise<Response>;\n\n\n/**\n * Represents Axon Signed URL, which ordinarily will be created automatically, behind the scenes, by AxonClientConig.\n */\nexport interface AxonSignedUrlResponse {\n    code: number;\n    signedUrl?: string;\n    error?: Error;\n}\n\n\n/**\n * Axon Client Configuration class deals with Axon connection, authentication and logging settings.\n * Client must create AxonClientConfig and authenticate it against the Axon service before creating AxonClient.\n */\nexport class AxonClientConfig {\n    private readonly _authenticatedGet: AxonClientAuthenticatedGet;\n    private _authentication: AxonSignedUrlResponse | undefined;\n    private _reconnectSignedUrl: string | undefined;\n    private _sessionId: string | undefined;\n    private _locale: string = 'en-US';\n    private _logger: Logger;\n\n    constructor(\n        public readonly endpoint: string,\n        authGet: AxonClientAuthenticatedGet = fetch,\n        logSink?: LogSink) {\n        this._logger = new Logger('Axon', logSink);\n        this._authenticatedGet = authGet;\n    }\n\n    private _getSignedUrlRequestUrl(): string {\n        if (this._reconnectSignedUrl) {\n            return this._reconnectSignedUrl;\n        }\n        return 'https://' + this.endpoint + '/signed-url' + (this._sessionId ? '?sessionId=' + this._sessionId : '');\n    }\n\n    private async _getSignedUrl(): Promise<AxonSignedUrlResponse> {\n        let response: Response;\n        try {\n            response = await this._authenticatedGet(this._getSignedUrlRequestUrl());\n        } catch (e) {\n            if (e instanceof TypeError) {\n                return { code: 997, error: new Error('Failed to authenticate against Axon server', { cause: e.message }) };\n            } else if (e instanceof Error) {\n                return { code: 998, error: e };\n            } else {\n                return { code: 999, error: new Error('Unknown error while accessing Axon authentication service!') };\n            }\n        }\n\n        try {\n            const result = await response.json();\n            switch (response.status) {\n            case 200:\n                if ('websocketUrl' in result) {\n                    return { code: response.status, signedUrl: result.websocketUrl as string };\n                } else {\n                    return { code: 994, error: new Error('Invalid response from Axon service!') };\n                }\n            default:\n                return { code: response.status, error: new Error(result?.message) };\n            }\n        } catch (e) {\n            if (e instanceof Error) {\n                return { code: 995, error: e };\n            } else {\n                return { code: 996, error: new Error('Unknown error while accessing Axon authentication service!') };\n            }\n        }\n    }\n\n    /**\n     * Sets locale.\n     * @param locale - Locale to use for the Axon service.\n     */\n    set locale(id: string) {\n        this._locale = id;\n    }\n\n    /**\n     * Gets locale.\n     */\n    get locale(): string {\n        return this._locale;\n    }\n\n    /**\n     * Sets the reconnect signed URL.\n     */\n    set reconnectSignedUrl(url: string | undefined) {\n        this._reconnectSignedUrl = url;\n    }\n\n    /**\n     * Gets the reconnect signed URL.\n     */\n    get reconnectSignedUrl(): string | undefined {\n        return this._reconnectSignedUrl;\n    }\n\n    /**\n     * Sets the session ID.\n     */\n    set sessionId(id: string | undefined) {\n        this._sessionId = id;\n    }\n\n    /**\n     * Gets the session ID.\n     */\n    get sessionId(): string | undefined {\n        return this._sessionId;\n    }\n\n    /**\n     * Gets the logger.\n     */\n    get logger(): Logger {\n        return this._logger;\n    }\n\n    /**\n     * Gets the Signed URL.\n     */\n    get signedUrl(): string {\n        return this?._authentication?.signedUrl || '';\n    }\n\n    /**\n     * Resets the session. This is used to clear the session ID and reconnect signed URL.\n     */\n    resetSession() {\n        this._sessionId = undefined;\n        this._reconnectSignedUrl = undefined;\n    }\n\n    /**\n     * Request Axon Signed URL from the service.\n     * @returns Promise resolving to either true, when an authenticated Signed URL was acquird, or false, upon an authentication error.\n     */\n    async authenticate(): Promise<boolean> {\n        // Clear existing authenitcation, if any.\n        this._authentication = undefined;\n\n        // Request Signed URL from the Axon service.\n        this._authentication = await this._getSignedUrl();\n        return this.isAuthenticated();\n    }\n\n    isAuthenticated(): boolean {\n        if (!this._authentication) { return false; }\n        if (this._authentication.code !== 200) { return false; }\n        if (this._authentication.signedUrl === undefined) { return false; }\n        try {\n            new URL(this._authentication.signedUrl);\n            return true;\n        } catch (error) {\n            return false;\n        }\n    }\n}\n","// https://github.com/maxogden/websocket-stream/blob/48dc3ddf943e5ada668c31ccd94e9186f02fafbd/ws-fallback.js\n\nvar ws = null\n\nif (typeof WebSocket !== 'undefined') {\n  ws = WebSocket\n} else if (typeof MozWebSocket !== 'undefined') {\n  ws = MozWebSocket\n} else if (typeof global !== 'undefined') {\n  ws = global.WebSocket || global.MozWebSocket\n} else if (typeof window !== 'undefined') {\n  ws = window.WebSocket || window.MozWebSocket\n} else if (typeof self !== 'undefined') {\n  ws = self.WebSocket || self.MozWebSocket\n}\n\nexport default ws\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n// Based on https://git.corp.adobe.com/sync-service/bifrost/blob/main/documentation/websocketframe/README.md\n\n/**\n * Axon Frame Sender Hook interface.\n */\nexport interface AxonFrameSenderHook {\n    trigger: (frame: Frame) => void;\n}\n\n/**\n * Axon Protocol frame types.\n */\nexport enum FrameType {\n    WsAck          = 'wsack',          // Acknowledges HTTP to WebSocket upgrade.\n    CreateVc       = 'connect',        // Creates virtual connection.\n    CreateVcAck    = 'connectack',     // Acknowledges virtual connection creation.\n    DeleteVc       = 'disconnect',     // Deletes virtual connection.\n    DeleteVcAck    = 'disconnectack',  // Acknowledges virtual connection deletion.\n    Reconnect      = 'reconnect',      // Reconnects virtual connection.\n    Closesession   = 'closesession',   // Closes session.\n    Message        = 'message',        // Sends message.\n    MessageAck     = 'messageack',     // Acknowledges message receipt.\n    Error          = 'error',          // Indicates error.\n}\n\n/**\n * Axon Virtual Connection states.\n */\nexport enum VcStatus {\n    Active           = 'active',            // Virtual connection is active.\n    CreateInprogress = 'create_inprogress', // Virtual connection creation is in progress.\n    DeleteInprogress = 'delete_inprogress', // Virtual connection deletion is in progress.\n    Error            = 'error',             // Virtual connection is in an error state.\n}\n\n\n/**\n * Reasons for requesting a Axon Session reconnection.\n */\nexport enum ReconnectReason {\n    AuthTokenExpired      = 'authTokenExpired',      // Authentication token has expired.\n    InstanceShuttingDown  = 'instanceShuttingDown',  // Instance is shutting down.\n    PeriodicReset         = 'periodicReset',         // Periodic reset is required.\n}\n\n\n/**\n * Represents Virtual Connection identifier.\n */\nexport interface VcId {\n    /**\n     * Virtual connection identifier.\n     */\n    readonly id: string;\n\n    /**\n     * Status of the virtual connection.\n     */\n    readonly status: VcStatus;\n\n    [property: string]: any;\n}\n\n/**\n * Represent an error message.\n */\nexport interface ErrorMessage {\n    /**\n     * Error message, encoded as Base64 string.\n     */\n    readonly message: string;\n\n    /**\n     * HTTP response code.\n     */\n    readonly status: number;\n\n    [property: string]: any;\n}\n\nexport interface Frame {\n    /**\n     * Type of the frame.\n     */\n    readonly frameType: FrameType;\n\n    /**\n     * Frame identifier.\n     */\n    readonly frameId: string;\n\n    [property: string]: any;\n}\n\n/**\n * WsAckFrame represents WebSocket connection acknowledgement (server -> client).\n *\n * Once the HTTP connection is upgraded to WebSocket connection, Axon server responds with\n * an acknowledgement frame containing the SessionId and the list of virtual connections, if any.\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"wsack\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//     \"sessionId\": \"S-223e4567-e89b-12d3-a456-4266141743242\",\n//     \"vcIds\": [\n//       {\n//         \"id\": \"S-223e4567-e89b-12d3-a456-4266141743242:1\",\n//         \"status\": \"active\"\n//       },\n//       {\n//         \"id\": \"S-223e4567-e89b-12d3-a456-4266141743242:2\",\n//         \"status\": \"error\"\n//       }\n//     ]\n// }\nexport interface WsAckFrame extends Frame {\n    /**\n     * Session identifier.\n     */\n    readonly sessionId: string;\n\n    /**\n     * Virtual connection identifiers.\n     */\n    readonly vcIds?: VcId[];\n\n    /**\n     * Reconnect Signed URL.\n     * Signed URL that the Axon Client will use to reconnect to the Axon session.\n     */\n    readonly reconnectUrl?: string;\n\n    /**\n     * Heartbeat interval, in seconds.\n     */\n    readonly heartbeatFrequencyInSec: number;\n}\n\n\n/**\n * CreateVcFrame represents a request to create a virtual connection (client -> server).\n */\n// e.g.:\n//\n// {\n//   \"frameType\": \"connect\",\n//   \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//   \"vcId\": \"S-223e4567-e89b-12d3-a456-4266141743242:1\",\n//   \"serviceName\": \"ANS\",\n//   \"headers\": {\n//     \"Authorization\": \"Bearer token ...\",\n//     \"X-App-Id\": \"acrobat\"\n//   }\n// }\nexport interface CreateVcFrame extends Frame {\n    /**\n     * The name of the upstream service. E.g. \"ANS\".\n     */\n    readonly serviceName: string;\n\n    /**\n     * Virtual connection identifier.\n     */\n    readonly vcId: string;\n\n    /**\n     * Headers that the upstream service might require.\n     */\n    readonly headers?: { [key: string]: string };\n\n    /**\n     * Discovery parameters that the upstream service discovery request might require.\n     */\n    readonly discoveryParams?: { [key: string]: string };\n}\n\n\n/**\n * VcAckFrame represents virtual connection creation acknowledgement (server -> client).\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"connectack\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//     \"vcId\": \"S-223e4567-e89b-12d3-a456-4266141743242:1\"\n// }\nexport interface CreateVcAckFrame extends Frame {\n    /**\n     * Virtual connection identifier.\n     */\n    readonly vcId: string;\n}\n\n\n/**\n * DeleteVcFrame represents virtual connection disconnect signal (client -> server).\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"disconnect\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//     \"vcId\": \"S-223e4567-e89b-12d3-a456-4266141743242:1\"\n// }\nexport interface DeleteVcFrame extends Frame {\n    /**\n     * The identifier of the virtual connection to be closed.\n     */\n    readonly vcId: string;\n}\n\n\n/**\n * DeleteVcAckFrame acknowledges disconnection of the virtual connection (client -> server).\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"disconnectack\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//     \"vcId\": \"S-223e4567-e89b-12d3-a456-4266141743242:1\"\n// }\nexport interface DeleteVcAckFrame extends Frame {\n    /**\n     * The identifier of the virtual connection closed.\n     */\n    readonly vcId: string;\n}\n\n\n/**\n * ReconnectFrame represents a server's request for the client to re-connect (server -> client).\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"reconnect\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//     \"reason\": \"authTokenExpired\",\n//     \"reconnectInTime\" : 40\n// }\nexport interface ReconnectFrame extends Frame {\n    /**\n     * Reason for the reconnect request.\n     */\n    readonly reason: ReconnectReason;\n\n    /**\n     * The maximum amount of time, in seconds, that the client can wait before closing the WebSocket connection.\n     */\n    readonly reconnectInTime: number;\n}\n\n\n/**\n * SessionCloseFrame signals the connection peer the intention of terminating the Axon session.\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"closesession\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\"\n// }\nexport interface CloseSessionFrame extends Frame {}\n\n\n/**\n * MessageFrame represents message to be send over virtual connection (client <-> server).\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"message\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//     \"vcId\": \"S-223e4567-e89b-12d3-a456-4266141743242:1\",\n//     \"payload\": \"ewogICAgICAibWVzc2FnZSI6ICJIZWxsbywgV29ybGQhIgp9\"\n// }\nexport interface MessageFrame extends Frame {\n    /**\n     * Virtual connection identifier.\n     */\n    readonly vcId: string;\n\n    /**\n     * The message to be sent, encoded as Base64 string.\n     */\n    readonly payload: string;\n}\n\n\n/**\n * MessageAckFrame represent acknowledgement of message delivery (client <-> server).\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"messageack\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//     \"vcId\": \"S-223e4567-e89b-12d3-a456-4266141743242:1\"\n// }\nexport interface MessageAckFrame extends Frame {\n    /**\n     * Virtual connection identifier.\n     */\n    readonly vcId: string;\n}\n\n\n/**\n * ErrorFrame represents an error while creating virtual connection or sending a message  (server -> client).\n */\n// e.g.:\n//\n// {\n//     \"frameType\": \"error\",\n//     \"frameId\": \"F-123e4567-e89b-12d3-a456-426614174000\",\n//     \"vcId\": \"S-223e4567-e89b-12d3-a456-4266141743242:1\",\n//     \"failedFrameId\": \"F-123e4567-e89b-12d3-a456-4266141742034\",\n//     \"errorMessage\": {\n//       \"status\": 503,\n//       \"message\": \"eyAKICBzZXJ2aWNlIHVuYXZhaWxhYmxlCn0=\"\n//     }\n// }\nexport interface ErrorFrame extends Frame {\n    /**\n     * The error message.\n     */\n    readonly errorMessage: ErrorMessage;\n\n    /**\n     * The identifier for the related virtual connection.\n     */\n    readonly vcId: string;\n\n    /**\n     * The identifier of a frame for which error has occurred.\n     */\n    readonly failedFrameId?: string;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * @module AxonVirtualConnection\n * @file Adobe Axon Virtual Connection.\n */\n\nimport type { CreateVcFrame, ErrorFrame, MessageFrame, MessageAckFrame, AxonFrameSenderHook } from './AxonFrame.interface';\nimport { FrameType } from './AxonFrame.interface';\nimport type { AxonSession } from './AxonSession';\nimport { AxonUtils } from './AxonUtils';\nimport { StateMachineEventEmitter } from './StateMachineEventEmitter';\n\nconst AXON_VC_CREATION_TIMEOUT_MS = 2000;\n\n/**\n * Enum value representing the internal state of AxonVirtualConnection instance.\n * Values must be equivalent to their respective key names for proper behavior of\n * StateMachineEventEmitter<AxonVirtualConnectionState> class.\n */\nexport enum AxonVirtualConnectionState {\n    CREATE_IN_PROGRESS = 'CREATE_IN_PROGRESS',\n    CREATED = 'CREATED',\n    DELETE_IN_PROGRESS = 'DELETE_IN_PROGRESS',\n    DELETED = 'DELETED',\n}\n\n/**\n * Represents Axon Virtual Connection to specific Adobe service, i.e. ONS, ANS, etc.\n * @extends StateMachineEventEmitter<AxonVirtualConnectionState>\n * @emits AxonVirtualConnection#message\n */\nexport class AxonVirtualConnection extends StateMachineEventEmitter<AxonVirtualConnectionState>  {\n    static VcIdToVcIndex(id: string): number {\n        const ids = id.split(':');\n        if (ids.length !== 2) { return 0; }\n        const idx = parseInt(ids[1]);\n        return isNaN(idx) ? 0 : idx;\n    }\n\n    constructor(\n        private readonly _session: AxonSession,\n        private readonly _frameSenderHook: AxonFrameSenderHook,\n        private readonly _vcIndex: number,\n        public readonly _serviceName: string,\n        public readonly _headers: { [key: string]: string } = {}) {\n        super(AxonVirtualConnectionState.CREATE_IN_PROGRESS, _session.logger, 'VirConn');\n        this.logSourceId = () => this._vcIndex ? `${this._vcIndex} (${this._serviceName})` : '';\n        this.logDebug('Axon Virtual Connection created!', this.id);\n\n        const frame: CreateVcFrame = {\n            ...AxonUtils.CreateFrame(FrameType.CreateVc),\n            'vcId': this.id,\n            'serviceName': this._serviceName,\n            'headers': this._headers\n        };\n        this.logDebug('Sending CreateVc frame', frame);\n        this._frameSenderHook.trigger(frame);\n    }\n\n    get index(): number {\n        return this._vcIndex;\n    }\n\n    get id(): string {\n        return this._session.id + ':' + this._vcIndex;\n    }\n\n    isActive(): boolean {\n        return this.isCreated() && this._session.isEstablished();\n    }\n\n    isCreated(): boolean {\n        return this.state === AxonVirtualConnectionState.CREATED;\n    }\n\n    /**\n     * Waits up to `timeoutMs` ms for the Axon Session to be created by the service and acknowledged to the client.\n     * @param timeoutMs Amount of time to wait before returning resolved promise.\n     * @returns Promise resolving to true if the Axon session was established, or false otherwise.\n     */\n    async ensureActive(timeoutMs: number = AXON_VC_CREATION_TIMEOUT_MS): Promise<boolean> {\n        if (this.isActive()) { return true; }\n        if (this.state === AxonVirtualConnectionState.DELETE_IN_PROGRESS) { return false; }\n        if (this.state === AxonVirtualConnectionState.DELETED) { return false; }\n        this.logDebug('Waiting for Virtual Connection to be active...');\n        await new Promise<void>(resolve => {\n            const timer = setTimeout(() => { resolve(); }, timeoutMs);\n            this.once('active', () => {\n                clearTimeout(timer);\n                resolve();\n            });\n        });\n        return this.isActive();\n    }\n\n    handleAxonErrorFrame(frame: ErrorFrame) {\n        this.logDebug('Received Error frame', frame);\n        switch (this.state) {\n        case AxonVirtualConnectionState.CREATE_IN_PROGRESS:\n        case AxonVirtualConnectionState.DELETE_IN_PROGRESS:\n            this.transitionTo(AxonVirtualConnectionState.DELETED);\n            this.logError(`Virtual Connection creation failed (${frame.errorMessage.message})`);\n            break;\n        default:\n            this.emit('error', frame.errorMessage);\n        }\n    }\n\n    handleAxonMessageFrame(frame: MessageFrame) {\n        try {\n            const messageString = atob(frame.payload);\n            const message = JSON.parse(messageString);\n            this.sendMessageAck(frame.frameId);\n            this.emit('message', message);\n        } catch (error) {\n            this.logError('Failed to decode message payload', error);\n        }\n    }\n\n    handleAxonMessageAckFrame(_frame: MessageAckFrame) {\n    }\n\n    sendMessage(message: string) {\n        if (!this.isActive()) {\n            this.logError('Cannot send Message on non-active Virtual Connection!');\n            return;\n        }\n\n        const payload = btoa(message);\n        const frame: MessageFrame = {\n            ...AxonUtils.CreateFrame(FrameType.Message),\n            'vcId': this.id,\n            payload\n        };\n        this._frameSenderHook.trigger(frame);\n    }\n\n    private sendMessageAck(messageFrameId: string) {\n        if (!this.isActive()) {\n            this.logError('Cannot send MessageAck on non-active Virtual Connection!');\n            return;\n        }\n        const frame: MessageAckFrame = {\n            ...AxonUtils.CreateFrame(FrameType.MessageAck),\n            'vcId': this.id,\n            messageFrameId\n        };\n        this._frameSenderHook.trigger(frame);\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * @module AxonClientSession\n * @file Adobe Axon Client Session.\n */\n\nimport { StateMachineEventEmitter } from './StateMachineEventEmitter';\nimport type {\n    ErrorFrame,\n    CloseSessionFrame,\n    WsAckFrame,\n    CreateVcAckFrame,\n    DeleteVcFrame,\n    ReconnectFrame,\n    MessageAckFrame,\n    MessageFrame,\n    Frame,\n    AxonFrameSenderHook } from './AxonFrame.interface';\nimport {\n    FrameType,\n    VcStatus,\n} from './AxonFrame.interface';\nimport { AxonUtils } from './AxonUtils';\nimport { AxonVirtualConnection, AxonVirtualConnectionState } from './AxonVirtualConnection';\nimport type { AxonClient } from './AxonClient';\n\n/**\n * Enum value representing the internal state of AxonSession instance.\n * Values must be equivalent to their respective key names for proper behavior of\n * StateMachineEventEmitter<AxonSessionState> class.\n */\nexport enum AxonSessionState {\n    CONNECTION_IN_PROGRESS = 'CONNECTION_IN_PROGRESS',\n    DISCONNECTION_IN_PROGRESS = 'DISCONNECTION_IN_PROGRESS',\n    RECONNECTION_IN_PROGRESS = 'RECONNECTION_IN_PROGRESS',\n    ESTABLISHED = 'ESTABLISHED',\n    DISCONNECTED = 'DISCONNECTED',\n    CLOSED = 'CLOSED'\n}\n\nconst AXON_SESSION_CREATION_TIMEOUT_MS = 2000;\nconst AXON_VIRTUAL_CONNECTION_DELETION_TIMEOUT_MS = 2000;\n\n/**\n * Axon Session represent persistent set of active Axon Virtual Connections.\n */\nexport class AxonSession extends StateMachineEventEmitter<AxonSessionState> {\n    static readonly State = AxonSessionState;\n    private _sessionId: string | undefined;\n    private _heartbeatIntervalInSec: number | undefined;\n    private _virtualConnections = new Map<number, AxonVirtualConnection>();\n    private _lastVcMonotonicIndex = 0;  // Valid Virtual Connection Index is a monotonic positive integer.\n\n    constructor(private readonly _axonClient: AxonClient, private readonly _frameSenderHook: AxonFrameSenderHook) {\n        super(AxonSessionState.DISCONNECTED, _axonClient.config.logger, 'Session');\n        this.logSourceId = () => this._sessionId ? this._sessionId.substring(0, 8) : '';\n    }\n\n    /**\n     * Handles acknowledgement message upon establishment of the Axon session\n     * @param frame object representing WebSocket connection acknowledgment frame.\n     * Returns true if the frame was handled successfully and false otherwise.\n     */\n    private _handleWsAckFrame(frame: WsAckFrame) {\n        this.logDebug('Received WsAck frame', frame);\n\n        const existingVirtualConnections = this._virtualConnections;\n        this._virtualConnections = new Map();\n        this._heartbeatIntervalInSec = undefined;\n\n        if (this._sessionId !== frame.sessionId) {\n            for (const vc of existingVirtualConnections.values()) {\n                vc.transitionTo(AxonVirtualConnectionState.DELETED);\n                this.logDebug(`Marking no longer valid Virtual Connection ${vc.id} as DELETED`);\n            }\n            existingVirtualConnections.clear();\n        }\n\n        this._sessionId = undefined;\n\n        if (!frame.sessionId || !frame.heartbeatFrequencyInSec || frame.heartbeatFrequencyInSec <= 0) {\n            this.logError('Rejecting invalid WsAckFrame. Session not established.', frame);\n            this.transitionTo(AxonSessionState.CLOSED);\n            this._notifyVirtualConnectionsAboutStatusChange();\n            return;\n        }\n\n        this._sessionId = frame.sessionId;\n        this._axonClient.config.sessionId = frame.sessionId;\n        this._axonClient.config.reconnectSignedUrl = frame.reconnectUrl;\n\n        this._heartbeatIntervalInSec = frame.heartbeatFrequencyInSec;\n\n        for (const vcId of frame.vcIds ?? []) {\n            const vcIndex = AxonVirtualConnection.VcIdToVcIndex(vcId.id);\n            if (!vcIndex) {\n                this.logError(`Unexpected Virtual Connection with Vc Index (${vcIndex}).`);\n                continue;\n            }\n            const existingVc = existingVirtualConnections.get(vcIndex);\n            if (existingVc?.isCreated() && vcId.status === VcStatus.Active) {\n                this._virtualConnections.set(vcIndex, existingVc);\n                existingVirtualConnections.delete(vcIndex);\n                if (this._lastVcMonotonicIndex < vcIndex) { this._lastVcMonotonicIndex = vcIndex; }\n                this.logInfo(`Re-connected to Virtual Connection with index ${vcIndex}.`);\n            } else {\n                this.logWarn(`Deleting unknown or inactive virtual connection with Vc Id (${vcId.id}).`);\n                if (existingVc?.isCreated()) {\n                    existingVc.transitionTo(AxonVirtualConnectionState.DELETE_IN_PROGRESS);\n                }\n                const frame: DeleteVcFrame = {\n                    ...AxonUtils.CreateFrame(FrameType.DeleteVc),\n                    'vcId': vcId.id\n                };\n                this._frameSenderHook.trigger(frame);\n            }\n        }\n\n        for (const vc of existingVirtualConnections.values()) {\n            vc.transitionTo(AxonVirtualConnectionState.DELETED);\n            this.logDebug(`Marking pre-existing and no longer valid Virtual Connection (${vc.id}) as DELETED`);\n        }\n\n        this.transitionTo(AxonSessionState.ESTABLISHED);\n        this.logDebug(`Axon session ${this._sessionId} established with heartbeat interval of ${this._heartbeatIntervalInSec} seconds.`);\n        this._notifyVirtualConnectionsAboutStatusChange();\n    }\n\n    /**\n     * Handles acknowledgement message upon creating a Virtual Connection.\n    */\n    private _handleCreateVcAckFrame(frame: CreateVcAckFrame) {\n        this.logDebug('Received CreateVcAck frame', frame);\n        const vcIndex = AxonVirtualConnection.VcIdToVcIndex(frame.vcId);\n        if (vcIndex && this._virtualConnections.has(vcIndex)) {\n            const vc = this._virtualConnections.get(vcIndex);\n            if (vc) {\n                vc.transitionTo(AxonVirtualConnectionState.CREATED);\n                this._notifyVirtualConnectionsAboutStatusChange();\n            } else {\n                this.logError(`Failed to handle Virtual Connection Ack Frame (VC with index ${this._sessionId} not found).`);\n            }\n        } else {\n            this.logError(`Ignoring frame for an invalid Vc Id (${frame.vcId}).`);\n        }\n    }\n\n    /**\n     * Handles acknowledgement message upon deleting a Virtual Connection.\n    */\n    private _handleDeleteVcAckFrame(frame: DeleteVcFrame) {\n        this.logDebug('Received DeleteVcAck frame', frame);\n        const vcIndex = AxonVirtualConnection.VcIdToVcIndex(frame.vcId);\n        const vc = this._virtualConnections.get(vcIndex);\n        if (vc) {\n            vc.transitionTo(AxonVirtualConnectionState.DELETED);\n            if (!this._virtualConnections.delete(vcIndex)) {\n                this.logError(`Failed to delete Virtual Connection (VC with index ${vcIndex} not found).`);\n            }\n        } else {\n            this.logError(`Ignoring frame for an invalid Vc Id (${frame.vcId}).`);\n        }\n        if (this._virtualConnections.size === 0) {\n            this.logDebug('All Virtual Connections deleted. Closing Axon Session...');\n            this.close();\n        }\n    }\n\n    /**\n     * Reconnect frame handler.\n     * @param frame - Axon Reconnect frame.\n     */\n    private _handleReconnectFrame(frame: ReconnectFrame) {\n        // TODO: Implement Reconnect frame handling.\n        this.logDebug('Received Reconnect frame', frame);\n    }\n\n    /**\n     * CloseSession frame handler.\n     * @param frame - Axon CloseSession frame.\n     */\n    private _handleCloseSessionFrame(frame: CloseSessionFrame) {\n        // TODO: Implement CloseSession frame handling.\n        this.logDebug('Received CloseSession frame', frame);\n    }\n\n    /**\n     * Virtual Channel frame handler.\n     * Passes the frame to the appropriate Virtual Connection.\n     * @param frame - Axon Error frame.\n     */\n    private _handleVcFrame(frame: ErrorFrame | MessageFrame | MessageAckFrame) {\n        const vcIndex = AxonVirtualConnection.VcIdToVcIndex(frame.vcId);\n        if (vcIndex && this._virtualConnections.has(vcIndex)) {\n            const vc = this._virtualConnections.get(vcIndex);\n            if (vc) {\n                switch (frame.frameType) {\n                case FrameType.Message:\n                    return vc.handleAxonMessageFrame(frame as MessageFrame);\n                case FrameType.MessageAck:\n                    return vc.handleAxonMessageAckFrame(frame as MessageAckFrame);\n                case FrameType.Error:\n                    return vc.handleAxonErrorFrame(frame as ErrorFrame);\n                default:\n                    this.logError(`Ignoring frame for Vc ${frame.vcId} (Unknown frame type: ${frame.frameType}).`);\n                    return;\n                }\n            } else {\n                this.logError(`Failed to access Virtual Connection # ${vcIndex} while handling frame ${frame.vcId}.`);\n            }\n        } else {\n            this.logError(`Ignoring Axon frame for Vc ${frame.vcId} (No such VC exists).`);\n        }\n    }\n\n    /**\n     * Gets the Axon Session Id.\n    */\n    get id(): string {\n        return this._sessionId ?? '';\n    }\n\n    /**\n     * Gets currently configured Axon Heartbeat interval in seconds.\n     */\n    get heartbeatIntervalInSec(): number | undefined {\n        return this._heartbeatIntervalInSec;\n    }\n\n    /**\n     * Handles Axon Frame by passing it to specific protocol handler, or throws an Error otherwise.\n     * Note: An Error is thrown only for unsupported AxonFrame types, while the downstream protocol handlers\n     * are not supposed handle errors via exceptions.\n     * @param frame - JSON-serialized Axon protocol frame.\n     */\n    public handleAxonFrame(frame: unknown): void {\n        switch ((frame as Frame).frameType) {\n        case FrameType.WsAck:\n            return this._handleWsAckFrame(frame as WsAckFrame);\n        case FrameType.CreateVcAck:\n            return this._handleCreateVcAckFrame(frame as CreateVcAckFrame);\n        case FrameType.DeleteVcAck:\n            return this._handleDeleteVcAckFrame(frame as DeleteVcFrame);\n        case FrameType.Reconnect:\n            return this._handleReconnectFrame(frame as ReconnectFrame);\n        case FrameType.Closesession:\n            return this._handleCloseSessionFrame(frame as CloseSessionFrame);\n        case FrameType.Message:\n            return this._handleVcFrame(frame as MessageFrame);\n        case FrameType.MessageAck:\n            return this._handleVcFrame(frame as MessageAckFrame);\n        case FrameType.Error:\n            return this._handleVcFrame(frame as ErrorFrame);\n        default:\n            throw new Error(`Failed to parse data frame; unknown frame type`);\n        }\n    }\n\n    /**\n     * Returns true if the Axon session is established.\n     */\n    isEstablished(): boolean {\n        return this.state === AxonSessionState.ESTABLISHED;\n    }\n\n    /**\n     * Ensures that Axon Client is connected and its session is established.\n     * @param timeoutMs Amount of time to wait before returning resolved promise.\n     * @returns Promise resolving to true if the Axon session was established, or false otherwise.\n     */\n    async ensureEstablished(timeoutMs: number = AXON_SESSION_CREATION_TIMEOUT_MS): Promise<boolean> {\n        const deadline = Date.now() + timeoutMs;\n        if (!await this._axonClient.ensureConnected(timeoutMs)) {\n            this.logError('Axon Client could not be connected!');\n            return false;\n        }\n        if (this.isEstablished()) { return true; } // Session is already established.\n        if (this.state === AxonSessionState.DISCONNECTED) {\n            this.transitionTo(AxonSessionState.CONNECTION_IN_PROGRESS);\n            this._notifyVirtualConnectionsAboutStatusChange();\n        }\n        this.logDebug('Waiting for session to be established...');\n        await new Promise<void>(resolve => {\n            const timer = setTimeout(() => { resolve(); }, deadline - Date.now());\n            this.once('established', () => {\n                clearTimeout(timer);\n                resolve();\n            });\n        });\n        return this.isEstablished();\n    }\n\n    /**\n     * Notifies all Virtual Connections that the Axon Session status has changed.\n     */\n    private _notifyVirtualConnectionsAboutStatusChange() {\n        for (const vc of this._virtualConnections.values()) {\n            vc.emit('session_status_changed');\n        }\n    }\n\n    /**\n     * Marks Axon Session as being reconnected upon the Axon Client's active reconnection workflow.\n     *\n     */\n    expectReconnection() {\n        if (this.state === AxonSessionState.RECONNECTION_IN_PROGRESS) { return; }\n        this.transitionTo(AxonSessionState.RECONNECTION_IN_PROGRESS);\n        this._notifyVirtualConnectionsAboutStatusChange();\n    }\n\n    /**\n     * Marks Axon Session as being disconnected upon the Axon Client's active disconnection workflow.\n     *\n     */\n    expectDisconnection() {\n        if (this.state === AxonSessionState.DISCONNECTION_IN_PROGRESS) { return; }\n        this.transitionTo(AxonSessionState.DISCONNECTION_IN_PROGRESS);\n        this._notifyVirtualConnectionsAboutStatusChange();\n    }\n\n    /**\n     * Disconnects Axon Session.\n     *\n     */\n    disconnect() {\n        if (this.state === AxonSessionState.CLOSED || this.state === AxonSessionState.DISCONNECTED) { return; }\n        this.transitionTo(AxonSessionState.DISCONNECTED);\n        this._notifyVirtualConnectionsAboutStatusChange();\n    }\n\n    /**\n     * Closes Axon Session.\n     */\n    close() {\n        if (this.state === AxonSessionState.CLOSED || this.state === AxonSessionState.DISCONNECTED) { return; }\n        this.logDebug('Closing Axon Session...');\n        this._frameSenderHook.trigger(AxonUtils.CreateFrame(FrameType.Closesession));\n        this.transitionTo(AxonSessionState.CLOSED);\n        this._notifyVirtualConnectionsAboutStatusChange();\n        this._virtualConnections.clear();\n        this._lastVcMonotonicIndex = 0;\n    }\n\n    /**\n     * Creates Virtual Connection.\n     */\n    async createVc(serviceName: string, headers?: Record<string, string>): Promise<AxonVirtualConnection> {\n        if (!this.isEstablished()) { throw new Error('Axon Session is not established!'); }\n        const vcIndex = ++this._lastVcMonotonicIndex;\n        const vc = new AxonVirtualConnection(this, this._frameSenderHook, vcIndex, serviceName, headers);\n        this._virtualConnections.set(vc.index, vc);\n        return vc;\n    }\n\n    /**\n     * Deletes Virtual Connection.\n     */\n    async deleteVc(vc: AxonVirtualConnection): Promise<boolean> {\n        if (!this.isEstablished()) { throw new Error('Axon Session is not established!'); }\n        const frame: DeleteVcFrame = {\n            ...AxonUtils.CreateFrame(FrameType.DeleteVc),\n            'vcId': vc.id\n        };\n        this.logDebug('deleteVc', frame);\n        vc.transitionTo(AxonVirtualConnectionState.DELETE_IN_PROGRESS);\n        this._frameSenderHook.trigger(frame);\n\n        this.logDebug('Waiting for VC to be deleted...');\n        const deadline = Date.now() + AXON_VIRTUAL_CONNECTION_DELETION_TIMEOUT_MS;\n        await new Promise<void>(resolve => {\n            const timer = setTimeout(() => { resolve(); }, deadline - Date.now());\n            vc.once('deleted', () => {\n                clearTimeout(timer);\n                resolve();\n            });\n        });\n        return vc.state as AxonVirtualConnectionState === AxonVirtualConnectionState.DELETED;\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n// Based on https://git.corp.adobe.com/sync-service/bifrost/blob/main/documentation/websocketframe/README.md\n\n/**\n * Axon HTTP Protocol Upgrade Status Codes.\n */\nexport enum AxonHttpStatusCodes {\n    /* HTTP Response Status 101 is the expected code upon successful protocol upgrade from HTTP to WebSocket. */\n    SWITCHING_PROTOCOLS = 101,\n\n    /* Although the HTTP standard specifies \"unauthorized\", semantically this response means \"unauthenticated\".\n     * For Axon connection, this error means that the client presented expired IMS token. */\n    UNAUTHORIZED = 401,\n\n    /* The client does not have access rights to the resource. */\n    FORBIDDEN = 403,\n\n    /* The server cannot find the requested resource. */\n    NOT_FOUND = 404,\n\n    /* The server has encountered an unexpected error.\n     * The client should retry once or create a new session. */\n    INTERNAL_SERVER_ERROR = 500,\n\n    /* Axon service is unavailable. The client should wait and reconnect using back-off algorithm. */\n    SERVICE_UNAVAILABLE = 503,\n}\n\n\n/**\n * Axon WebSocket Connection Status Codes.\n */\nexport enum AxonWebSocketStatusCodes {\n    /* Normal WebSocket disconnection. */\n    DISCONNECTED_NORMAL = 1000,\n\n    /* Server disconnected due to protocol error. */\n    DISCONNECTED_ERROR = 1002,\n\n    /* Server disconnected abnormally. */\n    DISCONNECTED_ABNORMAL = 1006,\n\n    /* Server disconnected. The session has been closed and cannot be reconnected. */\n    DISCONNECTED_SESSION_CLOSED = 4432,\n\n    /* Server disconnected. The client may reconnect to the same session. */\n    DISCONNECTED_SESSION_ACTIVE = 4433,\n}\n\n\n/**\n * Axon Protocol Error Codes.\n */\nexport enum AxonProtocolStatusCodes {\n    /* Server is about to close the web socket connection.\n     * The Axon session will remain active and the client may reconnect. */\n    AXON_SERVER_DISCONNECTING = 425,\n\n    /* Malformed Virtual Connection identifier. */\n    AXON_VC_MALFORMED_ID = 400,\n\n    /* Virtual Connection already exists for this session. */\n    AXON_VC_ALREADY_EXISTS = 4409,\n\n    /* After receiving the following errors, the client must clear the VC at its end. */\n    AXON_VC_INTERNAL_ERROR = 4500,\n\n    /* After receiving the following errors, the client must clear the VC at its end. */\n    AXON_VC_SERVICE_TIMEOUT = 4503,\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * @module AxonClient\n * @file Adobe Axon Client.\n */\n\nimport type { ErrorEvent, CloseEvent, MessageEvent, Event } from 'isomorphic-ws';\nimport WebSocket from 'isomorphic-ws';\nimport type { AxonClientConfig } from './AxonClientConfig';\nimport type { AxonFrameSenderHook, Frame } from './AxonFrame.interface';\nimport { FrameType } from './AxonFrame.interface';\nimport { AxonSession } from './AxonSession';\nimport { AxonWebSocketStatusCodes } from './AxonStatusCodes';\nimport { StateMachineEventEmitter } from './StateMachineEventEmitter';\n\nconst AXON_PROTOCOL_VERSION = 'axon-v1';\nconst AXON_PROTOCOL_HEARTBEAT_MESSAGE = '\\n';\nconst WS_CONNECT_TIMEOUT_MS = 2_000;\nconst WS_DISCONNECT_TIMEOUT_MS = 600;\nconst WS_TERMINATE_TIMEOUT_MS = 300;\nconst CLIENT_HEARTBEAT_INTERVAL_FACTOR = 800;  // 80% of the heartbeat interval x 1000 (for ms to sec conversion).\nconst SERVER_HEARTBEAT_MONITORING_INTERVAL_FACTOR = 1_300;  // 130% of the heartbeat interval x 1000 (for ms to sec conversion).\nconst WS_RECONNECT_WITH_BACKOFF_MAX_ATTEMPTS = 2_880;  // That means 24 hours of attempts with 30 seconds interval.\nconst WS_RECONNECT_BACKOFF_INITIAL_DELAY_MS = 1_000;\nconst WS_RECONNECT_BACKOFF_MAX_DELAY_MS = 30_000;\n\n\n/**\n * Enum value representing the internal state of AxonClient instance.\n * Values must be equivalent to their respective key names for proper behavior of\n * StateMachineEventEmitter<AxonClientState> class.\n */\nenum AxonClientState {\n    CONNECTING = 'CONNECTING',\n    RECONNECTING = 'RECONNECTING',\n    CONNECTED = 'CONNECTED',\n    DISCONNECTING = 'DISCONNECTING',\n    DISCONNECTED = 'DISCONNECTED',\n}\n\n/**\n * Represents a client to Adobe Axon service.\n * @emits AxonClient#connecting\n * @emits AxonClient#reconnecting\n * @emits AxonClient#connected\n * @emits AxonClient#disconnecting\n * @emits AxonClient#disconnected\n */\nexport class AxonClient extends StateMachineEventEmitter<AxonClientState> {\n    static readonly State = AxonClientState;\n    private _txBuffer: string[] = [];\n    private _ws: WebSocket | undefined;\n    private _connectionIteration: number = 0;\n    private _session: AxonSession;\n    private _heartbeatSenderTimeout: ReturnType<typeof setTimeout> | undefined;\n    private _heartbeatMonitorTimeout: ReturnType<typeof setTimeout> | undefined;\n    private _wsIndex: number = 0;\n    private _reconnectAttempt: number = 0;\n    private _reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\n    /**\n     * Creates a sender hook allowing higher level protocols to transmit Axon frames over the WebSocket.\n     */\n    private static _createAxonClientFrameSenderHook(target: AxonClient): AxonFrameSenderHook {\n        return {\n            trigger: (frame: Frame) => {\n                try {\n                    const data = JSON.stringify(frame);\n                    target.send(data, frame.frameType);\n                } catch (error) {\n                    target.logError('Invalid Axon frame passed to the sender hook', error);\n                }\n            },\n        };\n    }\n\n    /**\n     * Creates Axon Client.\n     * @constructor\n     * @param _config Client configuration; @see {@link AxonClientConfig} for details.\n     */\n    constructor(private readonly _config: AxonClientConfig) {\n        super(AxonClientState.DISCONNECTED, _config.logger, 'WebSock');\n        this.logSourceId = () => this._wsIndex.toString();\n        this._session = new AxonSession(this, AxonClient._createAxonClientFrameSenderHook(this));\n    }\n\n    /**\n     * Handles WebSocket open event.\n     * @param _event - WebSocket open event.\n     */\n    private _onWsOpen = (_event: Event) => {\n        this.logDebug(`WebSocket opened for ${this._config.endpoint}.`);\n        if (this.state === AxonClientState.DISCONNECTED || this.state === AxonClientState.DISCONNECTING) {\n            this.logWarn('WebSocket opened for a disconnecting or disconnected Axon client!');\n            return;\n        }\n        if (this.state === AxonClientState.CONNECTING || this.state === AxonClientState.RECONNECTING) {\n            this._clearReconnectTimer();\n            this.transitionTo(AxonClientState.CONNECTED);\n        }\n    };\n\n    /**\n     * Handles WebSocket close event.\n     * @param event - WebSocket close event.\n    */\n    private _onWsClose = (event: CloseEvent) => {\n        this.logDebug(`WebSocket closed (code:${event.code})[reason:${event.reason}].`);\n        if (this.state === AxonClientState.CONNECTING && !event.wasClean) {\n            if (this._config.reconnectSignedUrl && this._reconnectAttempt >= 2) {\n                this.logWarn('Reconnections using the existing reconnect Signed URL failed. Will try reconnecting with a new Axon session.');\n                this._config.resetSession();\n                this._reconnectAttempt = 0;\n            }\n            if (this._reconnectAttempt === 0) {\n                this.logWarn('WebSocket failed to connect cleanly. Will re-connect using an incremental backoff strategy.');\n                this._scheduleReconnectWithExponentialBackoff();\n            }\n            return;  // Returning early to avoid re-connecting client from being terminated.\n        }\n        if (this.isConnected()) {\n            if (event.code === AxonWebSocketStatusCodes.DISCONNECTED_SESSION_CLOSED) {\n                this._config.resetSession();\n                this.logDebug('Axon server permanently closed the current session.');\n            }\n            if (this.session.isEstablished()) {\n                this.logWarn('WebSocket closed unexpectedly. Will re-connect using an incremental backoff strategy.');\n                this._scheduleReconnectWithExponentialBackoff();\n                return;\n            }\n        }\n        this.terminate();\n    };\n\n    /**\n     * Handles WebSocket error event.\n     * @param event - WebSocket error event.\n     */\n    private _onWsError = (event: ErrorEvent) => {\n        if (this.state === AxonClientState.DISCONNECTING) {\n            // Consider WebSocket errors during the client's DISCONNECTING state as warnings.\n            this.logWarn(`Ignoring WebSocket error event while Axon Client is being disconnected (${event})`);\n        } else {\n            this.logError(`WebSocket error`, event);\n        }\n    };\n\n    /**\n     * Handles WebSocket message event.\n     * @param event - WebSocket message event.\n     */\n    private _onWsMessage = (event: MessageEvent) => {\n        if (typeof event.data === 'string') { // Handle text message.\n            this._handleTextMessage(event.data);\n        } else { // Handle binary message. Currently Unimplemented.\n            this.logError('Unsupported binary message received (Unimplemented).');\n        }\n    };\n\n    /**\n     * Cancels the heartbeat monitoring.\n     */\n    private _cancelHeartbeatMonitoring() {\n        if (this._heartbeatMonitorTimeout) {\n            clearTimeout(this._heartbeatMonitorTimeout);\n            this._heartbeatMonitorTimeout = undefined;\n        }\n    }\n\n    /**\n     * Restarts the heartbeat monitoring.\n    */\n    private _restartHeartbeatMonitoring() {\n        this._cancelHeartbeatMonitoring();\n        if (!this.isConnected() || !this.session.heartbeatIntervalInSec) { return; }\n        const timeoutMs = this.session.heartbeatIntervalInSec * SERVER_HEARTBEAT_MONITORING_INTERVAL_FACTOR;\n        this._heartbeatMonitorTimeout = setTimeout(() => {\n            if (this.isConnected()) {\n                this.logWarn('Missed heartbeat from Axon server! Client will reconnect using backoff strategy.');\n                this._scheduleReconnectWithExponentialBackoff();\n            }\n        }, timeoutMs);\n    }\n\n    /**\n     * Cancels the heartbeat message.\n     */\n    private _cancelHeartbeatMessage() {\n        if (this._heartbeatSenderTimeout) {\n            clearTimeout(this._heartbeatSenderTimeout);\n            this._heartbeatSenderTimeout = undefined;\n        }\n    }\n\n    /**\n     * Reschedules the heartbeat message.\n     */\n    private _rescheduleHeartbeatMessage() {\n        this._cancelHeartbeatMessage();\n        if (!this.isConnected() || !this.session.heartbeatIntervalInSec) { return; }\n        const timeoutMs = this.session.heartbeatIntervalInSec * CLIENT_HEARTBEAT_INTERVAL_FACTOR;\n        this._heartbeatSenderTimeout = setTimeout(() => {\n            if (this.isConnected()) { this.send(AXON_PROTOCOL_HEARTBEAT_MESSAGE); }\n        }, timeoutMs);\n    }\n\n    /**\n     * Handles WebSocket text message.\n     * @param data - data containing raw message to parse and handle by appropriate protocol handlers.\n     */\n    private _handleTextMessage(data: string) {\n        this._reconnectAttempt = 0;  // Assuming that client is properly connected; resetting the reconnect counter.\n        if (data === AXON_PROTOCOL_HEARTBEAT_MESSAGE) {\n            this._restartHeartbeatMonitoring();  // Restarting Axon Protocol heartbeat monitoring.\n            return;\n        }\n        this.logDebug(`Message of ${data.length} char(s) received.`);\n        try {\n            const frame: unknown = JSON.parse(data);\n            this._session.handleAxonFrame(frame);\n            if (!this._heartbeatSenderTimeout) { this._rescheduleHeartbeatMessage(); }  // Ensuring that the heartbeat is scheduled.\n            this._restartHeartbeatMonitoring();  // Any valid Axon Frame is also considered a heartbeat.\n        } catch (error) {\n            this.logDebug('Received WebSocket text message', data);\n            this.logError('Failed to handle WebSocket text message', error);\n        }\n    }\n\n    /**\n     * Transmits buffered messages over WebSocket.\n     */\n    private _transmit(): void {\n        if (!this._ws) { return; }\n        if (this._ws.readyState !== WebSocket.OPEN) { return; }\n        for (const item of this._txBuffer) {\n            this._ws.send(item);\n            if (item !== AXON_PROTOCOL_HEARTBEAT_MESSAGE) {\n                this.logDebug(`Message of ${item.length} byte(s) sent.`);\n            }\n        }\n        this._txBuffer = [];\n        this._rescheduleHeartbeatMessage();\n    }\n\n    /**\n     * Axon Config getter.\n     */\n    get config(): AxonClientConfig {\n        return this._config;\n    }\n\n    /**\n     * Axon Config getter.\n     */\n    get session(): AxonSession {\n        return this._session;\n    }\n\n    /**\n     * Returns whether the client is connected to the Axon service.\n     * @returns true if the client is connected, false otherwise.\n     */\n    isConnected(): boolean {\n        return this.state === AxonClientState.CONNECTED;\n    }\n\n    /**\n     * Connect to the Axon service and establish a session.\n     * @param timeoutMs Amount of time to wait before returning resolved promise.\n     * @returns promise, resolved to true upon successful authentication, client creation and connection, or false otherwise.\n     */\n    async connect(timeoutMs: number = WS_CONNECT_TIMEOUT_MS): Promise<boolean> {\n        if (this.state !== AxonClientState.RECONNECTING) { this._reconnectAttempt = 0; }\n        if (this.state !== AxonClientState.DISCONNECTED && this.state !== AxonClientState.RECONNECTING) {\n            this.logDebug(`Connection ignored; client not in DISCONNECTED or RECONNECTING state (current state: ${this.state}).`);\n            return false;\n        }\n        const currentConnectionCycle = ++this._connectionIteration;\n        this.transitionTo(AxonClientState.CONNECTING);\n        this.logDebug(`Connection initiated; authenticating client before opening WebSocket.`);\n        const isAuthenticated = await this._config.authenticate();\n\n        if (currentConnectionCycle !== this._connectionIteration) {\n            this.logDebug(`Connection aborted; client must have been simultaneously reconnected, disconnected or terminated.`);\n            return false;\n        }\n\n        if (!isAuthenticated) {\n            this.logError('Failed to authenticate against Axon service.');\n            return false;\n        }\n\n        this._wsIndex++;\n        this._ws = new WebSocket(this._config.signedUrl, AXON_PROTOCOL_VERSION);\n        this._ws.binaryType = 'arraybuffer';\n        this._ws.onerror = this._onWsError;\n        this._ws.onopen = this._onWsOpen;\n        this._ws.onclose = this._onWsClose;\n        this._ws.onmessage = this._onWsMessage;\n        this.logDebug('WebSocket initialized.');\n        return this._waitForConnection(timeoutMs);\n    }\n\n    /**\n     * Ensures that the Axon connection is active and the associated session is established.\n     * @param timeoutMs Amount of time to wait before returning resolved promise.\n     * @returns Promise resolving to true if the Axon connection was made, or false otherwise.\n     */\n    async ensureConnected(timeoutMs: number = WS_CONNECT_TIMEOUT_MS): Promise<boolean> {\n        if (this.state !== AxonClientState.DISCONNECTED) {\n            if (await this._waitForConnection(timeoutMs)) { return true; }\n        }\n        await this.reconnect();\n        return this.isConnected();\n    }\n\n    /**\n     * Waits for the WebSocket connection to be established.\n     * @param timeoutMs Amount of time to wait before returning resolved promise.\n     * @returns Promise resolving to true if the WebSocket connection was made, or false otherwise.\n     */\n    private async _waitForConnection(timeoutMs: number = WS_CONNECT_TIMEOUT_MS): Promise<boolean> {\n        if (this.isConnected()) { return true; }\n        this.logDebug('Waiting for WebSocket connection...');\n        const deadline = Date.now() + timeoutMs;\n        if (!this._ws) {\n            // Handling the corner case of being within the authentication phase of ongoing connect().\n            // Let's wait, within the allowed timeout, till the WebSocket is created.\n            await new Promise<void>(resolve => {\n                const interval = setInterval(() => {\n                    if (this._ws || Date.now() > deadline) {\n                        resolve();\n                        clearInterval(interval);\n                    }\n                }, 50);\n            });\n        }\n        const ws = this._ws;\n        if (!ws) { return false; }\n        if (ws.readyState === WebSocket.CONNECTING) {\n            await new Promise<void>(resolve => {\n                const timer = setTimeout(resolve, deadline - Date.now());\n                this.once('connected', () => {\n                    clearTimeout(timer);\n                    resolve();\n                });\n            });\n        }\n        if (this.isConnected()) {\n            this.logDebug('WebSocket connection established.');\n            return true;\n        } else {\n            this.logDebug('WebSocket connection failed.');\n            return false;\n        }\n    }\n\n    /**\n     * Deinitializes the WebSocket and disconnects the session.\n     * @param timeoutMs - Amount of time, in ms, to allow for WebSocket closing.\n     */\n    private async _deinitialize(timeoutMs: number) {\n        this._cancelHeartbeatMonitoring();\n        this._cancelHeartbeatMessage();\n        const deadline = Date.now() + timeoutMs;\n        const ws = this._ws;\n        if (ws) {\n            ws.onmessage = null;\n            ws.onopen = null;\n            ws.onclose = null;\n            if (ws.readyState === WebSocket.OPEN && this.session.isEstablished()) {\n                if (this.state === AxonClientState.RECONNECTING) {\n                    this.session.disconnect();\n                } else {\n                    this.session.close();\n                    // Wait for the Websocket to be closed upon session closure.\n                    await new Promise<void>(resolve => {\n                        const timer = setTimeout(resolve, deadline - Date.now());\n                        ws.addEventListener('close', () => {\n                            this.logDebug('WebSocket closed by server.');\n                            clearTimeout(timer);\n                            resolve();\n                        }, { once: true });\n                    });\n                }\n            }\n            if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {\n                const wsCloseCode = AxonWebSocketStatusCodes.DISCONNECTED_NORMAL;\n                ws.close(wsCloseCode);\n                this.logDebug(`WebSocket closing initiated with code ${wsCloseCode} and timeout of ${timeoutMs} ms.`);\n            }\n            if (ws.readyState === WebSocket.CLOSING) {\n                await new Promise<void>(resolve => {\n                    const timer = setTimeout(resolve, timeoutMs);\n                    ws.addEventListener('close', () => {\n                        this.logDebug('WebSocket closed by client.');\n                        clearTimeout(timer);\n                        resolve();\n                    }, { once: true });\n                });\n            }\n        }\n        this._ws = undefined;\n        this.logDebug('WebSocket deinitialized.');\n    }\n\n    /**\n     * Sends WebSocket message to the Axon Server.\n     * @param serializedFrameData - Serialized frame data to send.\n     * @param frameType - Type of the frame being sent.\n     */\n    send(serializedFrameData: string, frameType?: FrameType) {\n        if (frameType !== FrameType.Closesession) {\n            // Handling the message based on the current state of the client.\n            switch (this.state) {\n            case AxonClientState.CONNECTING:\n            case AxonClientState.RECONNECTING:\n                this._txBuffer.push(serializedFrameData);\n                break;\n            case AxonClientState.CONNECTED:\n                this._txBuffer.push(serializedFrameData);\n                this._transmit();\n                break;\n            case AxonClientState.DISCONNECTING:\n            case AxonClientState.DISCONNECTED:\n                break;\n            }\n        } else { // CloseSession frame is sent without buffering.\n            if (!this._ws) { return; }  // No WebSocket to send the message.\n            if (this._ws.readyState !== WebSocket.OPEN) { return; }  // WebSocket is not open.\n            this._ws.send(serializedFrameData);\n            this.logDebug(`Close Session frame of ${serializedFrameData.length} bytes sent.`);\n        }\n    }\n\n    /**\n     * Reconnect to Axon server unconditionally.\n     * @param timeoutMs Amount of time to wait before returning resolved promise.\n     */\n    async reconnect(timeoutMs: number = WS_CONNECT_TIMEOUT_MS) {\n        if (this.state === AxonClientState.RECONNECTING) {\n            this.logDebug(`reconnect() aborted; client is already in RECONNECTING state.`);\n            return;\n        }\n        this.session.expectReconnection();\n        ++this._connectionIteration;\n        if (this.state !== AxonClientState.DISCONNECTED) {\n            this.transitionTo(AxonClientState.RECONNECTING);\n            this.logInfo('WebSocket will reconnect now.');\n            await this._deinitialize(WS_TERMINATE_TIMEOUT_MS);\n        }\n        await this.connect(timeoutMs);\n    }\n\n    /**\n     * Clears the reconnect timer.\n     */\n    private _clearReconnectTimer() {\n        if (this._reconnectTimer) {\n            clearTimeout(this._reconnectTimer);\n            this._reconnectTimer = undefined;\n        }\n    }\n\n    /**\n     * Reconnect to Axon server using a backoff strategy.\n     */\n    private _scheduleReconnectWithExponentialBackoff() {\n        this._clearReconnectTimer();\n        if (++this._reconnectAttempt < WS_RECONNECT_WITH_BACKOFF_MAX_ATTEMPTS) {\n            const delay_ms = (this._reconnectAttempt < 5) ? (Math.pow(2, this._reconnectAttempt) * WS_RECONNECT_BACKOFF_INITIAL_DELAY_MS) : WS_RECONNECT_BACKOFF_MAX_DELAY_MS;\n            this._reconnectTimer = setTimeout(() => { this._scheduleReconnectWithExponentialBackoff(); }, delay_ms);\n            this.logInfo(`Reconnect attempt #${this._reconnectAttempt} starting now! The next attempt is scheduled in ${delay_ms}ms.`);\n        } else {\n            this.logInfo(`Reconnect attempt #${this._reconnectAttempt} starting now! This is the last attempt!`);\n        }\n        this.reconnect();\n    }\n\n    /**\n     * Forcibly drops the connection to the Axon server.\n     * Ordinarily, use {@link disconnect} instead; @see {@link disconnect} for details.\n     */\n    async terminate(timeoutMs: number = WS_TERMINATE_TIMEOUT_MS) {\n        if (this.state === AxonClientState.DISCONNECTED) {\n            this.logDebug(`terminate() aborted; client is already in DISCONNECTED state.`);\n            return;\n        }\n        this._clearReconnectTimer();\n        this._reconnectAttempt = 0;\n        ++this._connectionIteration;\n        if (this.state !== AxonClientState.DISCONNECTING) {\n            this.transitionTo(AxonClientState.DISCONNECTING);\n        }\n        this._txBuffer = [];\n        await this._deinitialize(timeoutMs);\n        if (this.state === AxonClientState.DISCONNECTING) {\n            this.transitionTo(AxonClientState.DISCONNECTED);\n        }\n    }\n\n    /**\n     * Gracefully disconnects from the Axon server. See {@link terminate} for details.\n     * @param timeoutMs Amount of time, in ms, to allow proper WebSocket closing.\n     */\n    async disconnect(timeoutMs: number = WS_DISCONNECT_TIMEOUT_MS): Promise<void> {\n        if (this.state === AxonClientState.DISCONNECTED) {\n            this.logDebug(`disconnect() aborted; client is already in DISCONNECTED state.`);\n            return;\n        }\n        this.session.expectDisconnection();\n        this._config.resetSession();\n        ++this._connectionIteration;\n        const deadline = Date.now() + timeoutMs;\n        const ws = this._ws;\n        this.logDebug(`disconnect() started with timeout of ${timeoutMs} ms.`);\n        this.transitionTo(AxonClientState.DISCONNECTING);\n        if (ws && ws.readyState === WebSocket.CONNECTING) {\n            // Wait for a connecting Websocket to be properly open before closing it.\n            await new Promise<void>(resolve => {\n                const timer = setTimeout(resolve, deadline - Date.now());\n                ws.addEventListener('open', () => {\n                    clearTimeout(timer);\n                    resolve();\n                }, { once: true });\n            });\n        }\n        await this.terminate(Math.max(0, deadline - Date.now()));\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { EventEmitter } from 'events';\nimport type { Loggable, Logger } from './Logging';\n\n/**\n * StateMachineEventEmitter class.\n * @remarks This class is a base class for state machines that emit events when transitioning between states.\n * @remarks The class extends the EventEmitter class.\n * @remarks The class provides logging functionality.\n * @remarks The class provides a transitionTo() method to transition between states.\n * @remarks The class provides logDebug(), logInfo(), logWarn(), and logError() methods to log messages.\n * @remarks The class provides a logSourceId hook to uniquely identify the instance of the logging source component.\n * @remarks StateType is the type of the state machine state. It must be an enum type with key names representing to the states.\n * @remarks The StateType must have value of string type equivalent to the key names of the enum.\n */\nexport abstract class StateMachineEventEmitter<StateType> extends EventEmitter implements Loggable {\n    private _state: StateType;\n    private readonly _logSourceName: string;\n    private readonly _logger: Logger;\n\n    /**\n     * Optional Hook returning an Id string by the logging component extending this class.\n     * See private member _logSourceString() for more details.\n     * @returns a printable string uniquely identifying instance of the logging source component.\n     */\n    logSourceId?: () => string = undefined;\n\n    /**\n     * Constructor for the StateMachineEventEmitter class.\n     * @param initalState - Initial state of the state machine.\n     * @param logger - Logger to use for logging.\n     * @param logSourceName - Name of the source of the logs.\n     * @remarks The logSourceName is used to identify the source of the logs. It prepends the logged messages.\n     * @remarks The logSourceId is an optional hook that can be set by the logging component extending this class.\n     * It is used to uniquely identify the instance of the logging source component.\n     */\n    constructor(initalState: StateType, logger: Logger, logSourceName: string = 'unknown') {\n        super();\n        this._state = initalState;\n        this._logger = logger;\n        this._logSourceName = logSourceName;\n        this.logDebug(`Created with an initial state ${this.state as string}.`);\n    }\n\n    private _sourceString(): string {\n        const logSourceId = this.logSourceId ? this.logSourceId() : '';\n        return this._logSourceName + (logSourceId ? `:${logSourceId}` : '(pending)');\n    }\n\n    /**\n     * Returns logger used by the state machine.\n     */\n    get logger(): Logger {\n        return this._logger;\n    }\n\n    /**\n     * Returns the current state of the state machine.\n     * @returns The current state of the state machine.\n     */\n    get state(): StateType {\n        return this._state;\n    }\n\n    /**\n     * Transitions the client to a new state.\n     * @param newState - New state to transition to.\n     */\n    transitionTo(newState: StateType) {\n        const eventName = newState as string;\n        this.logDebug(`State Transition: ${this.state} => ${newState}.`);\n        this._state = newState;\n        this.emit(eventName.toLowerCase());\n    }\n\n    /**\n     * Logs a debug message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logDebug(message: string, ...optionalParams: any[]) {\n        this._logger.logDebug(message, this._sourceString(), ...optionalParams);\n    }\n\n    /**\n     * Logs an info message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logInfo(message: string, ...optionalParams: any[]) {\n        this._logger.logInfo(message, this._sourceString(), ...optionalParams);\n    }\n\n    /**\n     * Logs a warning message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logWarn(message: string, ...optionalParams: any[]) {\n        this._logger.logWarn(message, this._sourceString(), ...optionalParams);\n    }\n\n    /**\n     * Logs an error message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     * @remarks If the first optional parameter is an Error object, the message will be appended with the error message.\n     */\n    logError(message: string, ...optionalParams: any[]) {\n        this._logger.logError(message, this._sourceString(), ...optionalParams);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport uuid from 'uuid';\nimport type { Frame, FrameType } from './AxonFrame.interface';\n\nexport class AxonUtils {\n    /**\n     * Creates a new Axon frame.\n     */\n    static CreateFrame(frameType: FrameType, frameId: string = uuid()): Frame {\n        return { frameType, frameId };\n    }\n\n}\n\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2025 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\nimport type { LocalAssetMetadata } from '../../assets/AdobeAsset';\nimport type AdobeAsset from '../../assets/AdobeAsset';\nimport type ISAMCorePrivate from '../ISAMCorePrivate';\nimport { OrderDirection, OrderField } from '../ItemSource';\nimport { getACPLModel, LIST_CHANGE_DELAY_MS } from './SAMCpp';\nimport type { RecentAdobeAssetConfig } from '../../assets/RecentAdobeAssetSource';\nimport type { IItemList } from '../ItemList';\nimport throttle from '../../utils/throttle';\nimport ACPLModelInterface from '../../interface/ACPLModelInterface';\n\ninterface ChangedAssetsEvent {\n    previews: AdobeAsset[];\n    properties: AdobeAsset[];\n    status: AdobeAsset[];\n}\n\nexport function acplAssetToLocalAsset(adobeAsset: AdobeAsset): LocalAssetMetadata {\n    return {\n        localID: adobeAsset.localID,\n        syncStatus: adobeAsset.syncStatus,\n        syncSuspensionReason: adobeAsset.syncSuspensionReason,\n        downloadStatus: adobeAsset.downloadStatus,\n        uploadStatus: adobeAsset.uploadStatus,\n        // In ACPL, the `repo:repositoryId` may be `~`, which represent the user's home repository;\n        // in this case, `repo:path` only contains a path relative to the home repository.\n        // SAM.js will internally convert that to a full repository path (see ACPLModelInterface).\n        'repo:repositoryId': adobeAsset.repositoryID,\n        'repo:path': adobeAsset.repoPath,\n        'repo:assetId': adobeAsset.cloudID,\n        'repo:size': adobeAsset.sizeInBytes,\n        'repo:name': adobeAsset.name,\n        'dc:format': adobeAsset.mediaType,\n        // Even though created and modified are not optional, they are not always present on ACPL assets.\n        'storage:deviceCreateDate': adobeAsset.created?.toISOString(),\n        'storage:deviceModifyDate': adobeAsset.modified?.toISOString(),\n        // TODO: In ACPL, etag and version are not yet exposed\n        // 'repo:etag': adobeAsset.etag,\n        // 'repo:version': adobeAsset.version,\n        'repo:createdBy': adobeAsset.createdBy,\n        'repo:modifiedBy': adobeAsset.modifiedBy,\n        // We no longer propagate `repo:state`. SAM.js will treat service responses as authoritative.\n    };\n}\n\n/**\n * A class that tracks the list of local assets, emitting \"localAssetChange\" events when that list changes.\n */\nclass LocalAssetUpdateTracker {\n    /** This is a SAM-C++ item list, not a SAM.js one. */\n    recentsList: IItemList<RecentAdobeAssetConfig>;\n\n    constructor(public applicationContext: any) {\n        this.recentsList = applicationContext.recentsSource.getList(OrderDirection.Descending, OrderField.Modified);\n\n        this.recentsList.on('refreshed', this.onListUpdated);\n        this.recentsList.on('movedAsset', this.onListUpdated);\n        this.recentsList.on('addedAsset', event => this.onAddedToRecents(event as unknown as AdobeAsset));\n        this.recentsList.on('removedAsset', event => this.onRemovedFromRecents(event as unknown as AdobeAsset));\n\n        applicationContext.on('changedAssets', this.onChangedAssets);\n        // Populate the initial list. (Usually this is empty; we monitor for subsequent changes.)\n        this.onListUpdated();\n    }\n\n    getLocalAssets() {\n        return this.recentsList.items.filter(item => item.localID).map(item => acplAssetToLocalAsset(item));\n    }\n\n    private isAssetInRecents(asset: AdobeAsset) {\n        return this.recentsList.items.some(item => asset.localID === item.localID || asset.cloudID === item.cloudID);\n    }\n\n    private emitLocalAssetChange(type: 'add' | 'delete' | 'update', localAsset: LocalAssetMetadata) {\n        getACPLModel()?.trigger('localAssetChange', JSON.stringify({\n            type,\n            localAsset\n        }));\n    }\n\n    onChangedAssets = ({ previews, properties, status }: ChangedAssetsEvent) => {\n        const changes = [ ...previews, ...properties, ...status ];\n        for (const asset of changes) {\n            if (this.isAssetInRecents(asset)) {\n                this.emitLocalAssetChange('update', acplAssetToLocalAsset(asset));\n            }\n        }\n        // Occasionally, ACPL emits changedAssets events with empty arrays, even when updates have occurred.\n        // To ensure these updates are still handled, invoke `onListChanged` when no changes are detected.\n        if (!changes.length) {\n            this.onListUpdated();\n        }\n    };\n\n    /** When an item is added to the recents list, notify clients immediately. */\n    onAddedToRecents = (asset: AdobeAsset) => {\n        this.emitLocalAssetChange(asset.cloudID ? 'update' : 'add', acplAssetToLocalAsset(asset));\n    };\n\n    /**\n     * When an asset is removed from the recents list, it is no longer considered part of the local list.\n     * This typically occurs when ACPL processes an ONS notification indicating the asset has been moved.\n     * To ensure the client stops treating it as local, we emit a final update clearing the localID,\n     * after which the asset will no longer be tracked unless it is re-added to the recents list.\n     */\n    onRemovedFromRecents = (asset: AdobeAsset) => {\n        this.emitLocalAssetChange('update', {\n            localID: '',\n            'repo:assetId': asset.cloudID,\n        });\n    };\n\n    onListUpdated = throttle(() => {\n        for (const item of this.recentsList.items) {\n            this.emitLocalAssetChange('update', acplAssetToLocalAsset(item));\n        }\n    }, LIST_CHANGE_DELAY_MS);\n}\n\nexport default async function patchACPLNext(_core: ISAMCorePrivate) {\n    const acplModel = getACPLModel();\n    if (!acplModel) {\n        return;\n    }\n\n    if (!acplModel.getLocalAssets) {\n        const initialLoadPromise = Promise.resolve().then(async () => {\n            const applicationContext = await acplModel.waitForApplicationContextReady();\n            return new LocalAssetUpdateTracker(applicationContext);\n        });\n\n        acplModel.getLocalAssets = async () => {\n            const tracker = await initialLoadPromise;\n            return tracker.getLocalAssets();\n        };\n    }\n\n    const acplModelInterface = new ACPLModelInterface(_core);\n    // We should always subscribe to localAssetChange: whether we polyfilled getLocalAssets ourselves\n    // or we're on a compatible host implementation, we need to keep the local asset list in sync.\n    acplModelInterface.subscribeToLocalAssetChanges();\n\n    if (!acplModel.downloadComposite) {\n        acplModel.downloadComposite = async (id: string) => {\n            const asset: AdobeAsset = await acplModel.applicationAssetContext.getAssetWithCloudID(id);\n            await asset.downloadComposite?.();\n        };\n    }\n\n    if (!acplModel.unpin) {\n        acplModel.unpin = async (id: string) => {\n            const asset: AdobeAsset = await acplModel.applicationAssetContext.getAssetWithCloudID(id);\n            await asset.unpin?.();\n        };\n    }\n\n    return acplModelInterface;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { memoize, synchronized } from './decorators';\nimport KeepAliveManager from './decorators/KeepAliveManager';\nimport type {\n    Configuration,\n    Hooks,\n    UpdatableConfiguration,\n    UpdatableKey } from './Environment';\nimport Environment, {\n    Env\n} from './Environment';\nimport type { CreateAtomFn } from './MobX';\nimport TypedEventEmitter from './TypedEventEmitter';\nimport packageJSON from '../../package.json';\nimport {\n    patchAdobeAsset,\n    patchAssetContext,\n    patchAssetList,\n    patchAssetSource,\n    patchSpaceJS\n} from './patches/SAMCpp';\n\n/**\n * Contexts\n */\nimport type AssetContext from '../assets/AssetContext';\nimport type AssetLinkManager from '../links/AssetLinkManager';\nimport type SpaceContext from '../workspaces/SpaceContext';\nimport type CollaborationContext from '../collaboration/CollaborationContext';\nimport type LibraryContext from '../libraries/LibraryContext';\nimport type FrameioContext from '../frameio/FrameioContext';\nimport type ProjectContext from '../projects/ProjectContext';\nimport type BoardContext from '../boards/BoardContext';\nimport type ClassroomContext from '../classrooms/ClassroomContext';\n\nimport type { ISAMCoreEvents, ISAMCorePrivate, ISAMCore } from '../indexPrivate';\nimport ItemPool from './ItemPool';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type Project from '../projects/Project';\n\nimport type Assignment from '../assignments/Assignment';\nimport type StudentAssignment from '../assignments/StudentAssignment';\nimport type StudentAssignmentFile from '../assignments/StudentAssignmentFile';\nimport type Library from '../libraries/Library';\nimport AdobeAssetFactory from '../assets/AdobeAssetFactory';\n\nimport type CustomModelContext from '../custom-models/CustomModelContext';\nimport type GenerationHistoryContext from '../generation-history/GenerationHistoryContext';\nimport type CustomModel from '../custom-models/CustomModel';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport { LogLevel as SyncServicesLogLevel } from '../sync-services/Logging';\nimport type { AxonClientAuthenticatedGet } from '../sync-services/AxonClientConfig';\nimport { AxonClientConfig } from '../sync-services/AxonClientConfig';\nimport { AxonClient } from '../sync-services/AxonClient';\nimport SAMError, { SAMErrorCode } from './SAMError';\nimport patchACPLNext from './patches/ACPLNext';\nimport type WorkfrontContext from '../workfront/WorkfrontContext';\nimport type GQLManager from '../graphql/GQLManager';\nimport type KnowledgeWorkspaceContext from '../knowledge-workspaces/KnowledgeWorkspaceContext';\nimport type AccessControlContext from '../access-control/AccessControlContext';\nimport type Board from '../boards/Board';\nimport type SharingContext from '../sharing/SharingContext';\n\n// If multiple versions of SAM.js are loaded in the same app, they will have different\n// contents in the closure of the module, so the Symbol used to store the global instances\n// of SAMCore must be a global Symbol.\nconst $SAM_INSTANCE_MAP = Symbol.for('com.adobe.ccac-sam-js.instances');\n\n// Matches ACPL log level enum\nexport enum LogLevel {\n    Off,\n    Err,\n    Warn,\n    Info,\n    Debug\n}\n\nexport type AssetPoolType = CustomModel | Assignment | StudentAssignment | StudentAssignmentFile | Project | Library | AdobeAsset | Board;\n\nexport default class SAMCore extends TypedEventEmitter<ISAMCoreEvents> implements ISAMCorePrivate {\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _environment: Environment;\n    private _AssetContext: AssetContext | undefined;\n    private _SpaceContext: SpaceContext | undefined;\n    private _CollaborationContext: CollaborationContext | undefined;\n    private _SharingContext: SharingContext | undefined;\n    private _ProjectContext: ProjectContext | undefined;\n    private _BoardContext: BoardContext | undefined;\n    private _ClassroomContext: ClassroomContext | undefined;\n    private _LibraryContext: LibraryContext | undefined;\n    private _CustomModelContext: CustomModelContext | undefined;\n    private _AxonClient: Promise<AxonClient> | undefined;\n    private _FrameioContext: FrameioContext | undefined;\n    private _GenerationHistoryContext: GenerationHistoryContext | undefined;\n    private _assetPool = new ItemPool<AssetPoolType>(this, 'project or adobeasset');\n    private _WorkfrontContext: WorkfrontContext | undefined;\n    private _KnowledgeWorkspaceContext: KnowledgeWorkspaceContext | undefined;\n    private _gqlManager?: GQLManager;\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _adobeAssetFactory: AdobeAssetFactory = new AdobeAssetFactory(this);\n\n    _fetchIndexState = {};\n\n    /**\n     * @package -- for use in SAM.js patches for SAM.cpp\n     */\n    _AssetContextJS?: AssetContext;\n\n    constructor(config: Configuration, hooks: Hooks = {}) {\n        super();\n        this._environment = new Environment(this, config, hooks);\n        if (config.CACHE_KEEP_ALIVE_TTL) {\n            KeepAliveManager.setTTL(config.CACHE_KEEP_ALIVE_TTL);\n        }\n    }\n\n    /**\n     * The primary ItemPool used by any context and item that extends AdobeAsset.\n     *\n     * @package - Used internally only.\n     */\n    _getAssetPool(): ItemPool<AssetPoolType> {\n        return this._assetPool;\n    }\n\n    /**\n     * @package -- Used for setting both the pure JS AssetContext,ts and the Native AssetContext\n     * provided from the bindings.\n     */\n    async _setAssetContextFromBindings(nativeAssetContext: AssetContext): Promise<void> {\n        if (this._AssetContext) {\n            // If multiple SAM.js instances invoke this, only the first gets to set it. This\n            // is likely a temporary condition while SAM.js clients converge on compatible versions.\n            console.error('[SAMCore] AssetContext already initialized');\n            return;\n        }\n\n        // Set the native context provided by the bindings.\n        this._AssetContext = nativeAssetContext;\n\n        // Set the pure JS Version of the context to be\n        // accessed during patches to provide pure js functionality that\n        // the native version doesn't provide.\n        const AssetContext = (await import('../assets/AssetContext')).default;\n\n        this._AssetContextJS = new AssetContext(this, this._assetPool);\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of AssetContext.\n     */\n    _getAssetContext(): AssetContext | undefined {\n        return this._AssetContext;\n    }\n\n    /**\n     * Returns an instance of AssetContext.\n     * @note this method can only be used when integrating with SAM.js sources\n     * and first calling initializeSharedAssetModel().\n     *\n     * @throws {SAMErrorCode.UNSUPPORTED} When initializeSharedAssetModel() has not been called first.\n     * @deprecated -  use getAssetContext()\n     */\n    get hostAssetContext(): AssetContext {\n        if (!this._AssetContext) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'samCore.hostAssetContext cannot be used without first calling initializeSharedAssetModel()'\n            );\n        }\n\n        return this._AssetContext;\n    }\n\n    /** @package -- only for use in SAM.js */\n    async _getGQLManager(): Promise<GQLManager> {\n        if (!this._gqlManager) {\n            const GQLManager = (await import('../graphql/GQLManager')).default;\n            this._gqlManager = new GQLManager(this);\n            await this._gqlManager.initialize();\n        }\n        return this._gqlManager;\n    }\n\n    /**\n     * Returns an instance of the AssetContext class which can be used\n     * to get the root folder and various sources for SWY or recent\n     * documents.\n     *\n     * @returns {AssetContext}\n     */\n    @synchronized\n    async getAssetContext(): Promise<AssetContext> {\n        if (this._AssetContext) {\n            return this._AssetContext;\n        }\n\n        const AssetContext = (await import('../assets/AssetContext')).default;\n        this._AssetContext = new AssetContext(this, this._assetPool);\n        await this._AssetContext._getONSContext();  // Ensure ONS Context is initialized.\n\n        // @TODO https://jira.corp.adobe.com/browse/SAM-3580\n        // Preload Collaboration Context since the ShareableItem.collaborators still requires some\n        // work to fully separate the lazily loading of CollaborationContext only when  collaborators\n        // and related features are required.\n        await this.getCollaborationContext();\n        return this._AssetContext;\n    }\n\n    /**\n     * @deprecated use AssetContext.assetLinkManager going forward.\n     *\n     */\n    @memoize\n    get assetLinkManager(): AssetLinkManager {\n        if (!this._AssetContext) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'samCore.assetLinkManager and samCore.assetContext cannot be used without first calling initializeSharedAssetModel()'\n            );\n        }\n\n        if (!this._AssetContext._getAssetLinkManager()) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'samCore.assetLinkManager cannot be used without first calling initializeSharedAssetModel()'\n            );\n        }\n\n        return this._AssetContext._getAssetLinkManager()!;\n    }\n\n    /**\n     * Returns an instance of SpaceContext.\n     * @note this method can only be used when integrating with SAM.js sources\n     * and first calling initializeSharedAssetModel().\n     *\n     * @throws {SAMErrorCode.UNSUPPORTED} When initializeSharedAssetModel() has not been called first.\n     * @deprecated -- will be removed on or after 2024-10-01\n     */\n    get spaceContext(): SpaceContext {\n        oneTimeWarning('SAMCore.spaceContext', 'spaceContext is deprecated and will be removed on or after 2024-10-01');\n        if (!this._SpaceContext) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'samCore.spaceContext cannot be used without first calling initializeSharedAssetModel()'\n            );\n        }\n\n        return this._SpaceContext;\n    }\n\n    /**\n     *\n     * @deprecated -- will be removed on or after 2024-10-01\n     */\n    @synchronized\n    async getSpaceContext(): Promise<SpaceContext> {\n        if (this._SpaceContext) {\n            return this._SpaceContext;\n        }\n\n        const SpaceContext = (await import('../workspaces/SpaceContext')).default;\n        this._SpaceContext = new SpaceContext(this);\n        return this._SpaceContext;\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of SpaceContext.\n     */\n    _getSpaceContext(): SpaceContext | undefined {\n        return this._SpaceContext;\n    }\n\n    /**\n     * Returns an instance of CollaborationContext.\n     * @note this method can only be used when integrating with SAM.js sources\n     * and first calling initializeSharedAssetModel().\n     *\n     * @throws {SAMErrorCode.UNSUPPORTED} When initializeSharedAssetModel() has not been called first.\n     *\n     * @deprecated - use getCollaborationContext()\n     */\n    @memoize\n    get collaborationContext(): CollaborationContext {\n        if (!this._CollaborationContext) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'samCore.collaborationContext cannot be used without first calling initializeSharedAssetModel()'\n            );\n        }\n        return this._CollaborationContext;\n    }\n\n    @synchronized\n    async getCollaborationContext(): Promise<CollaborationContext> {\n        if (this._CollaborationContext) {\n            return this._CollaborationContext;\n        }\n\n        const CollaborationContext = (await import('../collaboration/CollaborationContext')).default;\n        this._CollaborationContext = new CollaborationContext(this);\n        return this._CollaborationContext;\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of CollaborationContext.\n     */\n    _getCollaborationContext(): CollaborationContext | undefined {\n        return this._CollaborationContext;\n    }\n\n    /**\n     * Returns an instance of ProjectContext.\n     * @note this method can only be used when integrating with SAM.js sources\n     * and first calling initializeSharedAssetModel().\n     *\n     * @throws {SAMErrorCode.UNSUPPORTED} When initializeSharedAssetModel() has not been called first.\n     * @deprecated - use getProjectContext()\n     */\n    get projectContext(): ProjectContext {\n        if (!this._ProjectContext) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'samCore.projectContext cannot be used without first calling initializeSharedAssetModel()'\n            );\n        }\n        return this._ProjectContext;\n    }\n\n    async getProjectContext(): Promise<ProjectContext> {\n        if (this._ProjectContext) {\n            return this._ProjectContext;\n        }\n\n        const ProjectContext = (await import('../projects/ProjectContext')).default;\n        this._ProjectContext = new ProjectContext(this, this._assetPool);\n        return this._ProjectContext;\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of ProjectContext.\n     */\n    _getProjectContext(): ProjectContext | undefined {\n        return this._ProjectContext;\n    }\n\n    /**\n     * Provides all Classroom related functionality.\n     * @note this method can only be used when integrating with SAM.js sources\n     * and first calling initializeSharedAssetModel().\n     *\n     * @throws {SAMErrorCode.UNSUPPORTED} When initializeSharedAssetModel() has not been called first.\n     * @deprecated - Use getClassroomContext().\n     */\n    get classroomContext(): ClassroomContext {\n        if (!this._ClassroomContext) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'samCore.classroomContext cannot be used without first calling initializeSharedAssetModel()'\n            );\n        }\n\n        return this._ClassroomContext;\n    }\n\n    /**\n     * Get an instance of ClassroomContext\n     *\n     * Synchronize the context to avoid creating multiple instances of ClassroomContext\n     * when the context is accessed multiple times before the initial context is created.\n     */\n    @synchronized\n    async getClassroomContext(): Promise<ClassroomContext> {\n        if (this._ClassroomContext) {\n            return this._ClassroomContext;\n        }\n\n        const ClassroomContext = (await import('../classrooms/ClassroomContext')).default;\n        this._ClassroomContext = new ClassroomContext(this, this._assetPool);\n        return this._ClassroomContext;\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of ClassroomContext.\n     */\n    _getClassroomContext(): ClassroomContext | undefined {\n        return this._ClassroomContext;\n    }\n\n    /**\n     * Get an instance of BoardsContext\n     *\n     * Synchronize the context to avoid creating multiple instances of BoardContext\n     * when the context is accessed multiple times before the initial context is created.\n     *\n     * @experimental This API is in an experimental phase so expect that\n     * APIs will not be final and there will be breaking changes\n     * without bumping the major version until this comment is removed.\n     *\n     */\n    @synchronized\n    async getBoardContext(): Promise<BoardContext> {\n        if (this._BoardContext) {\n            return this._BoardContext;\n        }\n\n        const BoardContext = (await import('../boards/BoardContext')).default;\n        this._BoardContext = new BoardContext(this, this._assetPool);\n        return this._BoardContext;\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of BoardContext.\n     */\n    _getBoardContext(): BoardContext | undefined {\n        return this._BoardContext;\n    }\n\n    /**\n     * Provides Axon Client, representing an authenticated Axon Session over WebSocket protocol,\n     * which facilitates creation of Virtual Channels to Adobe Sync Servies such as ONS.\n     * This is a synchronous, promise-returning method, handling endpoint resolution,\n     * authentication, configuration and singleton initialization of the AxonClient object.\n     *\n     * @package -- for use in SAM.js only\n     */\n    _getAxonClient(): Promise<AxonClient> {\n        if (this._AxonClient) {  // Lazily initialized singleton instance.\n            return this._AxonClient;\n        }\n\n        // Authenticated fetch function supporting abort signal and setting noApiKeyHeader.\n        const authenticatedFetch: AxonClientAuthenticatedGet\n            = async (url: string) => this._environment.fetch(url, { noApiKeyHeader: true });\n\n        const axonConfig = new AxonClientConfig(\n            this._environment.endpoints.AXON_HOST,  // Axon endpoint.\n            authenticatedFetch,  // Must be of AxonClientAuthenticatedGet type.\n            this._environment.logSink,  // Logging sink implementing LogSink interface.\n        );\n\n        if (this._environment.getValue('ENVIRONMENT') === Env.Stage) {\n            // While on Stage, elevate the default log-level to DEBUG.\n            axonConfig.logger.logLevel = SyncServicesLogLevel.DEBUG;\n        }\n        const locale = this._environment.getValue('LOCALE');\n        if (locale) { axonConfig.locale = locale; }\n        this._AxonClient = Promise.resolve(new AxonClient(axonConfig));\n        return this._AxonClient;\n    }\n\n    /**\n     * Provides an instance of FrameioContext.\n     *\n     * @note this method can only be used when integrating with SAM.js sources\n     * and first calling initializeSharedAssetModel().\n     *\n     * @throws {SAMErrorCode.UNSUPPORTED} When initializeSharedAssetModel() has not been called first.\n     * @deprecated use getFrameioContext()\n     */\n    @memoize\n    get frameioContext(): FrameioContext {\n        if (!this._FrameioContext) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'samCore.frameioContext cannot be used without first calling initializeSharedAssetModel()'\n            );\n        }\n\n        return this._FrameioContext;\n    }\n\n    async getFrameioContext(): Promise<FrameioContext> {\n        if (this._FrameioContext) {\n            return this._FrameioContext;\n        }\n\n        const FrameioContext = (await import('../frameio/FrameioContext')).default;\n        this._FrameioContext = new FrameioContext(this);\n        return this._FrameioContext;\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of ProjectContext.\n     */\n    _getFrameioContext(): FrameioContext | undefined {\n        return this._FrameioContext;\n    }\n\n    async getLibraryContext(): Promise<LibraryContext> {\n        if (this._LibraryContext) {\n            return this._LibraryContext;\n        }\n\n        const LibraryContext = (await import('../libraries/LibraryContext')).default;\n        this._LibraryContext = new LibraryContext(this, this._assetPool);\n        return this._LibraryContext;\n    }\n\n    _getLibraryContext(): LibraryContext | undefined {\n        return this._LibraryContext;\n    }\n\n    async getCustomModelContext(): Promise<CustomModelContext> {\n        if (this._CustomModelContext) {\n            return this._CustomModelContext;\n        }\n\n        const CustomModelContext = (await import('../custom-models/CustomModelContext')).default;\n        this._CustomModelContext = new CustomModelContext(this, this._assetPool);\n        return this._CustomModelContext;\n    }\n\n    async getGenerationHistoryContext(): Promise<GenerationHistoryContext> {\n        if (this._GenerationHistoryContext) {\n            return this._GenerationHistoryContext;\n        }\n\n        const GenerationHistoryContext = (await import('../generation-history/GenerationHistoryContext')).default;\n        this._GenerationHistoryContext = new GenerationHistoryContext(this, this._assetPool);\n        return this._GenerationHistoryContext;\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of ProjectContext.\n     */\n    _getCustomModelContext(): CustomModelContext | undefined {\n        return this._CustomModelContext;\n    }\n\n    makeObservable(createAtom: CreateAtomFn): () => void {\n        return this._environment.mobx.register(createAtom);\n    }\n\n    /**\n     * @deprecated -- will be renamed for internal use on or after 2024-10-01\n     */\n    /**\n     * @package -- for use in SAM.js only\n     */\n    get environment(): Environment {\n        oneTimeWarning('SAMCore.environment', 'environment is deprecated and will be renamed for internal use on or after 2024-10-01');\n        return this._environment;\n    }\n\n    updateConfig(config: UpdatableConfiguration) {\n        const keys = Object.keys(config);\n        keys.forEach((key: string) => {\n            const updatableKey = key as UpdatableKey;\n            this._environment.setValue(updatableKey, config[updatableKey]);\n        });\n    }\n\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of WorkfrontContext.\n     */\n    _getWorkfrontContext(): WorkfrontContext | undefined {\n        return this._WorkfrontContext;\n    }\n\n    async getWorkfrontContext(): Promise<WorkfrontContext> {\n        if (this._WorkfrontContext) {\n            return this._WorkfrontContext;\n        }\n\n        const WorkfrontContext = (await import('../workfront/WorkfrontContext')).default;\n        this._WorkfrontContext = new WorkfrontContext(this);\n        return this._WorkfrontContext;\n    }\n\n    /**\n     * @package -- Used internally to synchronously get the loaded and cached instance\n     * of KnowledgeWorkspaceContext.\n     */\n    _getKnowledgeWorkspaceContext(): KnowledgeWorkspaceContext | undefined {\n        return this._KnowledgeWorkspaceContext;\n    }\n\n    async getKnowledgeWorkspaceContext(): Promise<KnowledgeWorkspaceContext> {\n        if (this._KnowledgeWorkspaceContext) {\n            return this._KnowledgeWorkspaceContext;\n        }\n\n        const KnowledgeWorkspaceContext = (await import('../knowledge-workspaces/KnowledgeWorkspaceContext')).default;\n        this._KnowledgeWorkspaceContext = new KnowledgeWorkspaceContext(this);\n        return this._KnowledgeWorkspaceContext;\n    }\n\n    /**\n     * Get the AccessControlContext for the Workfront context.\n     *\n     * @service For now only internal and aservice clients use cases are suppported.\n     * To share assets, use the CollaborationContext and ShareableItem.\n     *\n     * @returns The AccessControlContext for the Workfront context.\n     */\n    @memoize\n    async getAccessControlContext(): Promise<AccessControlContext> {\n        const AccessControlContext = (await import('../access-control/AccessControlContext')).default;\n        return new AccessControlContext(this);\n    }\n\n    async getSharingContext(): Promise<SharingContext> {\n        if (this._SharingContext) {\n            return this._SharingContext;\n        }\n\n        const SharingContext = (await import('../sharing/SharingContext')).default;\n        this._SharingContext = new SharingContext(this, this._assetPool);\n        return this._SharingContext;\n    }\n}\n\ntype SAMInstanceMap = { [s: string]: Promise<ISAMCore> };\n\ndeclare global {\n    interface Window {\n        [$SAM_INSTANCE_MAP]: SAMInstanceMap;\n    }\n}\n\nexport async function initializeSharedAssetModel(config: Configuration, hooks: Hooks = {}): Promise<ISAMCore> {\n    let samInstances: SAMInstanceMap = {};\n\n    // SAM.js supports running in a node.js _environment, so we can't assume that window is defined.\n    if (typeof window !== 'undefined') {\n        if (!window[$SAM_INSTANCE_MAP]) {\n            window[$SAM_INSTANCE_MAP] = samInstances;\n        } else {\n            samInstances = window[$SAM_INSTANCE_MAP];\n        }\n    }\n\n    // Check to see if any versions of SAM.js have already been loaded that are compatible with us (using semantic versioning, the\n    // major version must match, and the minor.patch version must be later than or equal to the one we need)\n    const version = (config._VERSION_OVERRIDE_FOR_TEST !== undefined && config._VERSION_OVERRIDE_FOR_TEST !== '')\n        ? config._VERSION_OVERRIDE_FOR_TEST\n        : packageJSON.version;\n    const [ major, minor, patch ] = version!.split('.').map(Number);\n    const loadedVersions = Object.keys(samInstances);\n    const compatibleLoadedVersion = loadedVersions.find(loadedVersion => {\n        if (loadedVersion === version) {\n            return true;\n        }\n        // If it's not an exact version match, we parse the versions and do a semantic version comparison - note that if\n        // the major version is 0, it's assumed that all changes are breaking.\n        const [ loadedMajor, loadedMinor, loadedPatch ] = loadedVersion.split('.').map(Number);\n        return major !== 0 && loadedMajor === major && (loadedMinor > minor || (loadedMinor === minor && loadedPatch >= patch));\n    });\n\n    // If there's a compatible version, use it!\n    if (compatibleLoadedVersion) {\n        return samInstances[compatibleLoadedVersion];\n    }\n\n    // If not, create a new version (warn if this means there will be multiple SAM.js versions)\n    if (loadedVersions.length > 0) {\n        console.warn(`An instance of SAM.js already exists, but is not compatible with the requested version: ${version}. `\n            + `Because of this, a new instance of SAM.js will be created. Loaded versions: ${loadedVersions.join(', ')}.`);\n    }\n\n    // Wait for host asset context, and patch SAM.cpp as needed\n    // Presence of global acplModel tells us SAM.cpp JS bindings are present\n    // @ts-expect-error\n    const acplModel: any = (typeof window !== 'undefined') && window.acplModel;\n    const enableACPLNextPolyfills = config.FEATURE_FLAGS?.['enable-acpl-next-polyfills'] ?? false;\n    const disableSamCppModels = config.FEATURE_FLAGS?.['disable-sam-cpp-models'] ?? false;\n\n    const isPatchableVersion = () => {\n        // SAM.cpp 2.0.0-main.1301 is the earliest release that supports patching prototypes.\n        const rootFolderProto = acplModel.applicationAssetContext?.rootFolder.constructor.prototype;\n        return Boolean(rootFolderProto) && Object.getOwnPropertyDescriptor(rootFolderProto, 'name')?.configurable === true;\n    };\n\n    /**\n     * Use before providing the core in order to\n     * import and set contexts for use with clients who\n     * are still integrating us by source.\n     *\n     * @param core {SAMCore}\n     */\n    const loadAndSetContexts = async (core: SAMCore) => {\n        const useLazyContext = core._environment.getValue('LAZY_CONTEXT');\n\n        if (enableACPLNextPolyfills) {\n            await patchACPLNext(core);\n        }\n\n        if (!core._getAssetContext()) {\n            await core.getAssetContext();\n        }\n\n        if (!useLazyContext) {\n            const loadedAssetContext = core._getAssetContext()!;\n            if (!loadedAssetContext._getAssetLinkManager()) {\n                await loadedAssetContext.getAssetLinkManager();\n            }\n\n            if (!core._getProjectContext()) {\n                await core.getProjectContext();\n            }\n\n            if (!core._getSpaceContext()) {\n                await core.getSpaceContext();\n            }\n\n            if (!core._getClassroomContext()) {\n                await core.getClassroomContext();\n            }\n\n            if (!core._getCollaborationContext()) {\n                await core.getCollaborationContext();\n            }\n\n            if (!core._getLibraryContext()) {\n                await core.getLibraryContext();\n            }\n\n            if (!core._getFrameioContext()) {\n                await core.getFrameioContext();\n            }\n\n            if (!core._getCustomModelContext()) {\n                await core.getCustomModelContext();\n            }\n\n            if (!core._getWorkfrontContext()) {\n                await core.getWorkfrontContext();\n            }\n        }\n    };\n\n    samInstances[version] = new Promise<ISAMCore>((resolve, reject) => {\n        if (acplModel && !config._DISABLE_SAM_CPP) {\n            // Either immediately resolve with existing applicationAssetContext, or wait for it\n            Promise.race([\n                acplModel.applicationAssetContext ?? acplModel.waitForApplicationContextReady()\n            ]).then(() => {\n                try {\n                    // If we can't (or shouldn't) patch this version of SAM.cpp, return a pure-JS implementation.\n                    if (disableSamCppModels || !isPatchableVersion()) {\n                        // This behavior is solidified by a test in SAMCore.spec.ts where \"it should only patch SAM.ccp if it\n                        // being patched\".\n                        const core = new SAMCore(config, hooks);\n                        loadAndSetContexts(core)\n                            .then(() => resolve(core));\n                        return;\n                    }\n                    const core = new SAMCore(config, hooks);\n                    // Patching should be done in this order, because the SAM.cpp prototypes aren't exposed in the global\n                    // namespace, or on global `acplModel`, so the only way to get prototypes is to find an instance of\n                    // the class and get a reference to `obj.constructor.prototype`. E.g., to patch AssetList, it needs\n                    // to get it from `acplModel.applicationAssetContext.rootFolder.children.getList()`, so\n                    // `AssetSource.getList()` cannot be patched yet.\n                    patchAdobeAsset(core);\n                    patchSpaceJS();\n                    patchAssetList(core);\n                    patchAssetSource(core);\n                    patchAssetContext(core);\n\n                    if (loadedVersions.length > 0) {\n                        console.error('[initializeSharedAssetModel] SAM.cpp can only be observable by one'\n                            + ' instance of SAMCore. Clients using SAM.js internal version ' + version + ' will not'\n                            + ' see Mobx observables working. Clients on a host app should align on the same SAM.js'\n                            + ' version before shipping to customers.');\n                    }\n\n                    // Provides the native context to SAM.js and creates a new\n                    // instance of the pure JS AssetContext to also be used in the bindings.\n                    core._setAssetContextFromBindings(acplModel.applicationAssetContext).then(() => {\n                        resolve(core);\n                    });\n                } catch (e) {\n                    console.error('[initializeSharedAssetModel] failed to patch SAM.cpp', e);\n                    reject(e);\n                }\n            });\n        } else {\n            // No SAM.cpp present, use pure SAM.js implementation\n            const samCore = new SAMCore(config, hooks);\n            loadAndSetContexts(samCore)\n                .then(() => resolve(samCore));\n        }\n    });\n\n    // Do not cache failed initialization attempts\n    try {\n        await samInstances[version];\n    } catch (e) {\n        delete samInstances[version];\n        throw e;\n    }\n    return samInstances[version];\n}\n\n/**\n * @deprecated Use {@link initializeSharedAssetModel} instead, will be removed on or after 2024-10-01.\n */\nexport function createSharedAssetModel(config: Configuration, hooks: Hooks = {}): ISAMCore {\n    oneTimeWarning('createSharedAssetModel',\n        'createSharedAssetModel is deprecated and will be removed on or after 2024-10-01. Use'\n        + ' initializeSharedAssetModel instead.');\n    return new SAMCore(config, hooks);\n}\n","/** Returns true if the object has a key. Can be used as a replacement to `Object.hasOwnProperty` and `Object.hasOwn`. */\nconst hasProperty = (obj: object, key: string): boolean => {\n    return Object.getOwnPropertyDescriptor(obj, key) !== undefined;\n};\n\nexport default hasProperty;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport InterfaceBase from './InterfaceBase';\nimport type {\n    ISearchQuery,\n    USSResponse\n} from './USSModel';\nimport {\n    USS_ARTIFACT_MEDIATYPE,\n    SearchProps\n} from './USSModel';\nimport packageJSON from '../../package.json';\nimport type Resource from '../assets/Resource';\n\nconst DefaultSearchQuery: ISearchQuery = {\n    scope: [ 'creative_cloud' ],\n    // Ensures assetIds in results are returned with the correct casing. E.g. \":US:\" instead of \":us:\"\n    asset_id_opacity: true\n};\n\nexport default class USSInterface extends InterfaceBase {\n\n    private _getEndpointHref(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.USS_HOST}${endpoint}`;\n    }\n\n    async getQueryResponse(searchQuery: ISearchQuery, resource?: Resource): Promise<USSResponse> {\n        searchQuery = { ...DefaultSearchQuery, ...searchQuery };\n        const endpointHref = this._getEndpointHref('/universal-search/v2/search');\n        const { PRODUCT_ID } = this._core._environment.getValue('HOST_PRODUCT_DATA');\n\n        const response = await this._doPost(\n            endpointHref,\n            {\n                'Content-Type': 'application/vnd.adobe.search-request+json',\n                'X-Product': PRODUCT_ID,\n                'X-Product-Location': `SAM.js/${packageJSON.version}`\n            },\n            JSON.stringify(searchQuery), [ 200 ], false, resource);\n\n        return response.json();\n    }\n\n    async searchSpace(\n        parentFolderId: string,\n        searchArtifacts: boolean,\n        embedPermissions: boolean,\n        options?: Partial<ISearchQuery>\n    ): Promise<USSResponse> {\n        const query: ISearchQuery = {\n            hints: [ { acp_platform_v2: true, creative_cloud_rendition_v2: true } ],\n            fetch_fields: { includes: [ 'app_metadata', 'collaboration_metadata' ] },\n            sort_orderby: options?.sort_orderby ?? 'modify_date',\n            sort_order: options?.sort_order ?? 'desc',\n            limit: options?.limit ?? 50,\n            start_index: options?.start_index ?? 0,\n            [SearchProps.TYPE]: options?.type || [],\n            container: { asset_id: [ parentFolderId ] },\n        };\n\n        if (!searchArtifacts) {\n            query.op_none_of = [\n                // exclude Artifacts\n                { op_field_exists: [ USS_ARTIFACT_MEDIATYPE ] },\n                // exclude hidden\n                { [SearchProps.VISIBILITY]: [ 'hiddenSelf', 'hiddenRecursive' ] }\n            ];\n        } else {\n            // Only include artifacts\n            query.op_field_exists = [ USS_ARTIFACT_MEDIATYPE ];\n        }\n        if (embedPermissions) {\n            query.fetch_fields!.includes.push('_embedded');\n        }\n\n        return this.getQueryResponse(query);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { SAMError, SAMErrorCode } from '../core/SAMError';\nimport InterfaceBase from './InterfaceBase';\nimport type {\n    IInvitationShareBatchResponse,\n    IInvitationShareResponse,\n    IInvitationShareRequest,\n    IInvitationSharePatchRequest,\n    IPendingInvitation,\n    IInvitationBulkPatchResponse,\n    IInvitationBulkPostResponse,\n    IAddCollaboratorResult,\n    IAccessRequestResult,\n    IBulkAccessRequestResponse,\n    IAccessRequestNotification,\n    IAccessRequestPermissions\n} from './InvitationModel';\n\nexport default class InvitationInterface extends InterfaceBase {\n\n    private _batchRequestLimit: number = 50;\n\n    get batchRequestLimit() {\n        return this._batchRequestLimit;\n    }\n\n    private _getUrl(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.INVITATIONS_HOST}${endpoint}`;\n    }\n\n    async getCollaborators(urn: string): Promise<IInvitationShareResponse> {\n        // This allows piggybacking on a single request, so that we can support loading both the collaborators\n        // and invitations at the same time, without making two separate requests (the data for both of these\n        // is in the same response).\n        return await this._getSharedResponse(this._getUrl(`/api/v4/share/${encodeURIComponent(urn)}?extraFeatures=direct_acl`));\n    }\n\n    async addCollaborators(urn: string, request: IInvitationShareRequest): Promise<IAddCollaboratorResult> {\n        const response = await this._doPost(\n            this._getUrl(`/api/v4/share/${encodeURIComponent(urn)}`),\n            {},\n            JSON.stringify(request),\n            [ 200 ]);\n\n        const result: IInvitationBulkPostResponse = await response.json();\n\n        const addResult: IAddCollaboratorResult = {\n            addedCollaborators: [],\n            failedCollaborators: []\n        };\n\n        for (const collaborator of result.collaborators) {\n            if (collaborator.statusCode === 201) {\n                addResult.addedCollaborators.push(collaborator.recipient);\n                continue;\n            }\n\n            let errorCode = SAMErrorCode.BAD_REQUEST;\n            switch (collaborator.statusCode) {\n            case 403:\n                errorCode = SAMErrorCode.ACCESS_DENIED;\n                break;\n            case 409:\n                errorCode = SAMErrorCode.CONFLICT;\n                break;\n            case 500:\n                errorCode = SAMErrorCode.INTERNAL_ERROR;\n                break;\n            }\n            addResult.failedCollaborators.push({\n                recipient: collaborator.recipient,\n                error: SAMError.create(errorCode, collaborator.statusText)\n            });\n        }\n\n        return addResult;\n    }\n\n    async modifyCollaborators(urn: string, request: IInvitationSharePatchRequest): Promise<IInvitationBulkPatchResponse> {\n        const response = await this._doPatch(\n            // As per the invitation service API spec, mode (optional) If not specified, the API makes the effective ACL match\n            // the specified role and permissions. If the value is \"direct_acl\", the API makes the direct ACL match the\n            // specified role and permissions. Sharesheet is using this mode and we are expected to use it as well.\n            this._getUrl(`/api/v4/share/${encodeURIComponent(urn)}?mode=direct_acl`),\n            {},\n            JSON.stringify(request),\n            [ 200 ]);\n        return await response.json();\n    }\n\n    async getCollaboratorListForUrns(urns: string[]): Promise<IInvitationShareBatchResponse> {\n        const request = {\n            'operation': 'bulkGetShares',\n            'parameters': {\n                urns,\n                'queryParams': {\n                    'extraFeatures': 'direct_acl,legacy_role'\n                }\n            }\n        };\n        const response =  await this._doPost(\n            this._getUrl(`/ops/v4/shares`),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(request),\n            [ 200 ]);\n\n        const result = await response.json();\n\n        // response is 200, but result is not in proper format\n        if (!result.result || !Array.isArray(result.result)) {\n            throw SAMError.create(SAMErrorCode.UNKNOWN, 'Failed to parse response for Invitation Service bulk API.');\n        }\n\n        return result;\n    }\n\n    async confirmAccess(urn: string): Promise<void> {\n        await this._doPost(\n            this._getUrl(`/api/v4/invitations/urn/${encodeURIComponent(urn)}`),\n            {},\n            undefined,\n            [ 200 ]);\n    }\n\n    // might be able to remove this after invitation service handles https://jira.corp.adobe.com/browse/CPX-7447\n    _shouldRetryMonitorResponse(asyncResponse: Response, body: string): boolean {\n        if (asyncResponse.status === 200) {\n            const responseBody = JSON.parse(body);\n            if (responseBody.jobStatus !== 'completed') {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    async declineAccess(urn: string): Promise<void> {\n        await this._doDelete(\n            this._getUrl(`/api/v4/invitations/urn/${encodeURIComponent(urn)}`),\n            {},\n            [ 200 ]);\n    }\n\n    async getPendingInvitations(): Promise<IPendingInvitation> {\n        const response = await this._doGet(\n            this._getUrl('/api/v4/invitations'),\n            { headers: { 'Content-Type': 'application/json' } }\n        );\n        return await response.json();\n    }\n\n    async createAccessRequest(\n        assetIds: string[],\n        notification: IAccessRequestNotification,\n        requestedPermissions?: IAccessRequestPermissions\n    ): Promise<IAccessRequestResult> {\n\n        const request = {\n            operation: 'bulkCreateAccessRequest',\n            parameters: {\n                urns: assetIds,\n                requestBody: {\n                    notification,\n                    ...(requestedPermissions ? { requestedPermissions } : {})\n                }\n            }\n        };\n\n        const response = await this._doPost(\n            this._getUrl('/ops/v4/shares'),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(request),\n            [ 200 ]\n        );\n\n        const result: IBulkAccessRequestResponse = await response.json();\n\n        const accessRequestResult: IAccessRequestResult = {\n            successfulRequests: [],\n            failedRequests: []\n        };\n\n        for (const item of result.result) {\n            if (item.statusCode === 201) {\n                accessRequestResult.successfulRequests.push(item.urn);\n                continue;\n            }\n\n            let errorCode = SAMErrorCode.BAD_REQUEST;\n            switch (item.statusCode) {\n            case 403:\n                errorCode = SAMErrorCode.ACCESS_DENIED;\n                break;\n            case 404:\n                errorCode = SAMErrorCode.NOT_FOUND;\n                break;\n            }\n            accessRequestResult.failedRequests.push({\n                assetId: item.urn,\n                error: SAMError.create(errorCode, item.response || 'Access request failed'),\n                response: item.response\n            });\n        }\n\n        return accessRequestResult;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport InterfaceBase from './InterfaceBase';\nimport {\n    cache,\n    key, synchronized,\n} from '../core/decorators';\nimport type {\n    HeaderMap } from './LinkUtils';\nimport {\n    getURLFromLinks,\n    RelType\n} from './LinkUtils';\nimport AssetInterface, { FOLDER_TYPE } from './AssetInterface';\nimport type ItemPool from '../core/ItemPool';\nimport type ItemBase from '../core/ItemBase';\nimport SAMError, {\n    ProblemType,\n    SAMErrorCode\n} from '../core/SAMError';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport type {\n    AssetLinks,\n    IBatchOperationResult,\n    ICopyOperation,\n    IFailedOperation,\n    IMoveOperation,\n    IOperationError,\n    IOperationQuery,\n    IOperationResult,\n    IOperationResults,\n    IOperationSingleError,\n    IRepositoryIndex,\n    ISAMOperationResult,\n    ISAMOperationResults,\n    RepositoryMetadata,\n    Owner, Assignee,\n    IWorkfrontRepositoryIndexResponse\n} from './RepositoryModel';\nimport type { IQuotaInfo } from '../assets/AssetContext';\nimport type Cache from '../core/Cache';\nimport { NotFound } from '../core/Cache';\nimport type { IRepositoriesDataResponse, MinimalAssetLinks } from './RepositoryModel';\nimport type Resource from '../assets/Resource';\nimport setURLSearchParams from '../utils/searchParams';\n\n// Maximum number of operations per batch request to avoid \"Invalid batch size\" errors\n// See: https://developers.corp.adobe.com/storage-api/docs/reference/operations-delete.md/\nconst MAX_BATCH_OPERATION_SIZE = 50;\n\nexport interface IQuotaServiceData {\n    'storage:bytesLimit': number;\n    'storage:bytesUsed': number;\n    'storage:limitType': 'soft' | 'hard';\n}\n\nconst MAX_INDEX_RETRIES = 5;\n\nexport default class RepositoryInterface extends InterfaceBase {\n    // Index document is a well-known endpoint, so does not need to come from discovery.\n    // https://developers.corp.adobe.com/index-repository-api/docs/index-document.md\n    public repositoryIndex = `https://${this._core._environment.endpoints.ACP_CS_HOST}/index`;\n    public repositoryNameIndex = `https://${this._core._environment.endpoints.ACP_CS_HOST}/repositories`;\n    public workfrontRepositoryIndex = `https://${this._core._environment.endpoints.ACP_CS_HOST}/index-workfront`;\n\n    protected _useHighPriorityRequestsIfEnabled = true;\n    private _cache: Cache = this._core._environment.cache;\n\n    private get _fetchIndexState() { return this._core._fetchIndexState; }\n    private set _fetchIndexState(state) { this._core._fetchIndexState = state; }\n\n    @cache\n    _getAndCacheDocument(@key href: string) {\n        return this._getAllPages(href);\n    }\n\n    private _getIndexHeaders() {\n        return {\n            // R-API returns an E-Tag which doesn't change when the content changes, causing the browser to\n            // use stale cached data. Using Cache-Control header to disable browser cache so this doesn't happen.\n            // [SAM-2952]\n            'Cache-Control': 'no-cache, no-store, max-age=0',\n            // SAMJS-467: calculating which regions the user has discoverable assets in is slow, but\n            // no clients require this behavior, so disable calculation for better performance.\n            'directive': 'index-skip-repo-regions'\n        };\n    }\n\n    public _getRepositoryHref(repositoryID: string): string {\n        return `https://${this._core._environment.endpoints.ACP_CS_HOST}/content/repo/${repositoryID}/repositoryResource`;\n    }\n\n    async getRootLink(relType: RelType, params: {[s: string]: string} = {}): Promise<string> {\n        // The only thing uses in SAM.js from the `/` resource is the `_links` metadata, which is identical to the\n        // `_links` in the `/index` resource, so use the `/index` resource for the root links\n        const rootDocument = await this.getIndex();\n        return getURLFromLinks(rootDocument._links, relType, params);\n    }\n\n    async getIndex(): Promise<IRepositoryIndex> {\n        const fetchIndexState = this._fetchIndexState;\n\n        // If something triggered clearing the cache, wait for it to finish\n        if (fetchIndexState.pendingCacheClear) {\n            await fetchIndexState.pendingCacheClear;\n        }\n        if (fetchIndexState.response && fetchIndexState.hasChildren) {\n            // Data is complete, so return it now\n            return fetchIndexState.response;\n        }\n\n        const existing = await this._cache.getItem(this.repositoryIndex);\n        if (existing !== NotFound) {\n            fetchIndexState.response = existing;\n            fetchIndexState.hasChildren = Boolean(fetchIndexState.response?.children?.length);\n        }\n\n        // Refresh index in background if it hasn't been refreshed successfully this session. This allows typical\n        // calls to return quickly from cache while still updating the cache regularly [SAM-3165].\n        if (!fetchIndexState.promise) {\n            fetchIndexState.promise = new Promise((resolve, reject) => {\n                this._getResponse<IRepositoryIndex>(\n                    this.repositoryIndex,\n                    {\n                        headers: this._getIndexHeaders(),\n                        // R-API might be temporarily returning 404 on the /index document for some users\n                        additionalRetryErrorCodes: [ 404 ],\n                    }\n                ).then(async indexJson => {\n                    // Only cache /index if it has children [SAM-2952]\n                    if (indexJson.children?.length) {\n                        await this._cache.setItem(this.repositoryIndex, indexJson);\n                        fetchIndexState.hasChildren = true;\n                    } else {\n                        // Allow getHomeDirectoryMetadata() to retry fetching /index if there were no children\n                        fetchIndexState.hasChildren = false;\n                        fetchIndexState.promise = undefined;\n                    }\n                    // Response can be used for _links even if there are no children\n                    fetchIndexState.response = indexJson;\n                    resolve(indexJson);\n                })\n                    .catch(reject);\n            });\n        }\n\n        // If the /index is not in cache, or missing data, wait for fetch, otherwise use the\n        // cache value while the index is refreshed in the background.\n        if (fetchIndexState.promise && (!fetchIndexState.response || !fetchIndexState.hasChildren)) {\n            try {\n                await fetchIndexState.promise;\n            } catch (e) {\n                // Do not cache bad response, but let the original error bubble up\n                fetchIndexState.promise = undefined;\n                throw e;\n            }\n        }\n\n        // The _links property of the response will still be usable even if children are not present.\n        return fetchIndexState.response!;\n    }\n\n    async getWorkfrontIndex(orgId: string): Promise<IWorkfrontRepositoryIndexResponse> {\n        const response = await this._getResponse<IWorkfrontRepositoryIndexResponse>(\n            this.workfrontRepositoryIndex,\n            {\n                headers: {\n                    ...this._getIndexHeaders(),\n                    'Org-Id': orgId\n                },\n                // R-API might be temporarily returning 404 on the /index document for some users\n                additionalRetryErrorCodes: [ 404 ]\n            }\n        );\n        return response;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _clearIndexCache(): void {\n        this._fetchIndexState.pendingCacheClear = new Promise(resolve => {\n            // Allow pending request to complete before clearing the cache so the final state is\n            // a clear cache.\n            Promise.resolve(this._fetchIndexState.promise)\n                .finally(() => {\n                    return this._cache.deleteItem(this.repositoryIndex);\n                })\n                .finally(() => {\n                    this._fetchIndexState = {};\n                    resolve();\n                });\n        });\n    }\n\n    @cache\n    private async _getAndCacheLinksFromHref(@key href: string): Promise<{ links: AssetLinks }> {\n        const response = await this._doGet(href);\n        // The etag header from Links API no longer represents the Asset or its repo metadata, so it\n        // isn't being stored in the SAM.js persistent cache.\n        const { _links } = await response.json();\n        return { links: _links };\n    }\n\n    getAssetResolveByIdHref(assetId: string): string {\n        // Links API is a \"well-known endpoint\" and so does not need to use discovery\n        // https://developers.corp.adobe.com/storage-api/docs/reference/links.md\n        const url = new URL(`https://${this._core._environment.endpoints.ACP_CS_HOST}/links`);\n        setURLSearchParams(url, { assetId });\n        return url.toString();\n    }\n\n    async getCloudQuotaUsedAndMax(): Promise<IQuotaInfo> {\n        const metadata = await this.getHomeDirectoryMetadata();\n        const url = getURLFromLinks(metadata._links, RelType.QUOTA);\n\n        const responseJson: IQuotaServiceData = await this._getResponse(url);\n        return { used: responseJson['storage:bytesUsed'], total: responseJson['storage:bytesLimit'] };\n    }\n\n    /**\n     * Takes an asset id and returns the links for the resource.\n     *\n     * @param id {string} assetId of the object\n     * @TODO_Deprecation to be removed after it is no longer used in SAMCpp.ts patchAdobeAsset\n     */\n    async resolveById(assetId: string): Promise<AssetInterface> {\n        const resolveHref = this.getAssetResolveByIdHref(assetId);\n        const { links } = await this._getAndCacheLinksFromHref(resolveHref);\n        return new AssetInterface(this, assetId, links, '');\n    }\n\n    async getRepoMetadataById(assetId: string, resource: Resource<RepositoryMetadata>, assetLinks?: MinimalAssetLinks): Promise<RepositoryMetadata> {\n        const resolveHref = assetLinks && assetLinks[RelType.REPO_METADATA]\n            // we have a client-provided link for repo:metadata, use that instead of a resolve call.\n            ? getURLFromLinks(assetLinks, RelType.REPO_METADATA)\n            // GET on the resolve link will return the repo metadata\n            : await this.getRootLink(RelType.RESOLVE_ID, { id: assetId });\n        await this._doGet(resolveHref, { resource });\n        return resource.data;\n    }\n\n    async getRepoMetadataByPath(repositoryId: string, path: string, resource: Resource<RepositoryMetadata>, assetLinks?: MinimalAssetLinks): Promise<RepositoryMetadata> {\n        const resolveHref = assetLinks && assetLinks[RelType.REPO_METADATA]\n            // we have a client-provided link for repo:metadata, use that instead of a resolve call.\n            ? getURLFromLinks(assetLinks, RelType.REPO_METADATA)\n            // GET on the resolve link will return the repo metadata\n            : await this.getRootLink(RelType.RESOLVE_PATH, { repositoryId, path, mode: 'id' });\n        await this._doGet(resolveHref, { resource });\n        return resource.data;\n    }\n\n    async getHomeDirectoryMetadata(): Promise<RepositoryMetadata> {\n        return await this._getHomeDirectoryMetadata(0);\n    }\n\n    private async _getHomeDirectoryMetadata(retryCount: number): Promise<RepositoryMetadata> {\n        // Fire off background refresh of index data\n        let index = await this.getIndex();\n\n        const featureFlags = this._core._environment.getValue('FEATURE_FLAGS');\n        if (featureFlags?.['enable-response-cache'] && retryCount === 0) {\n            // TODO: The behavior here is already the same effect (using a cached value first).\n            // We don't want to wait for the fetchIndexState.promise to resolve (for quick load),\n            // but we do want to properly handle all scenarios where that initial value might change.\n        } else {\n            // Wait for background refresh, which may or may not be the same as the cached value\n            index = await (this._fetchIndexState.promise ?? index);\n        }\n\n\n        // Likely cause: Enterprise user has not been granted quota by their administrator, but this error\n        // could change. Host apps should verify that the user has quota before trying to get their home\n        // directory info, and if they have none, show a message suggesting they contact their administrator.\n        if (!index.children.length) {\n            if (retryCount >= MAX_INDEX_RETRIES) {\n                throw SAMError.create(SAMErrorCode.INVALID_OPERATION, `Home repository not found after ${MAX_INDEX_RETRIES} retries`);\n            } else {\n                // NOTE: assumes that getIndex() does not cache if there are no children, so no need to clear cache here\n                this._core._environment.log(`/index has no children, ${MAX_INDEX_RETRIES - retryCount} retries left`);\n                await new Promise(resolve => setTimeout(resolve, this._getRetryErrorDelay(undefined, retryCount)));\n                return await this._getHomeDirectoryMetadata(retryCount + 1);\n            }\n        }\n        return index.children[0]._embedded[RelType.REPO_METADATA];\n    }\n\n    /**\n     * Run a cloud operation.\n     * https://git.corp.adobe.com/pages/caf/api-spec/schemas/repository/operation.html\n     *\n     * @param ops {IOperationQuery}\n     */\n    async runOperation(ops: IOperationQuery): Promise<ISAMOperationResults> {\n        const opHref = await this.getRootLink(RelType.OPS);\n\n        const headers: HeaderMap = {\n            'Content-type': 'application/vnd.adobe.asset-operation+json',\n            'Prefer': 'respond-async, wait=5',\n        };\n        const firstOp = Array.isArray(ops) ? ops[0] : ops;\n        // If the operation is copy and SAM is configured to copy all resources\n        // by default then we add the directive header in RAPI call as RAPI needs\n        // this header to copy secondary resources by default.\n        const copyResources = (firstOp as ICopyOperation)?.op === 'copy';\n        copyResources && (headers['directive'] = 'ops-2021');\n\n        // If the operation is move and the client has set the 'enable-x-bucket-move' feature flag to 'true',\n        // add the enable-x-bucket-move header to the request to ensure that cross bucket moves are enabled\n        // for the operation (SHARED-844). Cross-bucket moves will occur when the storage-assignee of the\n        // source and destination are different.\n        const moveResources = (firstOp as IMoveOperation)?.op === 'move';\n        const featureFlags = this._core._environment.getValue('FEATURE_FLAGS');\n        if (moveResources && featureFlags?.['enable-x-bucket-move']) {\n            headers['enable-x-bucket-move'] = 'true';\n        }\n\n        // If we send a single operation, then errors will fail the entire request.\n        // If we send multiple operations, we always get a 200 and then separate error\n        // codes inside the response. We want to normalize this behavior here, in order\n        // to make it easier to handle the response.\n        // Note that some errors are still going to return a proper array even\n        // for single items, so we need to be prepared for both types of replies.\n\n        // We are using 'any' below to disable the status code validation and allow\n        // this method to handle the error codes.\n        const response = await this._doPost(opHref, headers, JSON.stringify(ops), 'any');\n\n        let result: IOperationResults | IOperationError | undefined;\n        try {\n            result = await response.json();\n        } catch {\n            // Ignore the error here.\n        }\n\n        if (result && !Array.isArray(result) && response.status !== 200) {\n            // If this was a single operation request, then sometimes the service will fail the entire request\n            // instead of returning the array for the item. Try to normalize the reply to avoid bugs in the callers.\n            // https://jira.corp.adobe.com/browse/ACPCSS-3613\n            return [\n                {\n                    ...firstOp,\n                    error: SAMError.createWithRepositoryCode(\n                        // We cannot use the result.code as that uses non-standard HTTP error codes like 4041 instead of 404.\n                        response.status,\n                        (result as IOperationError).type ?? ProblemType.OPERATION_FAILED,\n                        (result as IOperationError).title ?? (result as IOperationSingleError).message ?? 'Operation failed'\n                    )\n                }\n            ];\n        }\n\n        // If we don't actually get a response or if we get an array,\n        // then we should expect to get a 200 response code.\n        this._checkResponseStatus(response, opHref, [ 200 ]);\n\n        if (!result) {\n            // We've got a 200 status, but there's no actual result or the JSON parsing failed.\n            throw SAMError.create(SAMErrorCode.UNKNOWN, 'Failed to parse response for repo bulk API.');\n        }\n\n        // Convert the result to ensure it is always an array.\n        // If we have a single item, we know it cannot be an error as that was handled above already.\n        const list = Array.isArray(result) ? result : [ result as IOperationResult ];\n\n        // Map errors to SAMErrors before returning.\n        return list.map((item): ISAMOperationResult => {\n            const { error } = item;\n            return {\n                ...item,\n                error: error ? SAMError.createWithRepositoryCode(error.status, error.type, error.title) : undefined\n            };\n        });\n    }\n\n    /**\n     * Utility function to chunk an array into smaller batches\n     * @param array The array to chunk\n     * @param chunkSize Maximum size of each chunk\n     * @returns Array of chunks\n     */\n    private _chunkArray<T>(array: T[], chunkSize: number): T[][] {\n        const chunks: T[][] = [];\n        for (let i = 0; i < array.length; i += chunkSize) {\n            chunks.push(array.slice(i, i + chunkSize));\n        }\n        return chunks;\n    }\n\n    /**\n     * Combine results from multiple batch operation results\n     * @param results Array of batch operation results to combine\n     * @returns Combined batch operation result\n     */\n    private _combineOperationResults<LocalType extends ItemBase>(results: IBatchOperationResult<LocalType>[]): IBatchOperationResult<LocalType> {\n        const combinedResult: IBatchOperationResult<LocalType> = {\n            failedResults: [],\n            newModels: []\n        };\n\n        for (const result of results) {\n            combinedResult.failedResults.push(...result.failedResults);\n            combinedResult.newModels.push(...result.newModels);\n        }\n\n        return combinedResult;\n    }\n\n    /**\n     * Runs the runOperation API for any specific context\n     * Initiate session of that context\n     * Check every model operation's result and update model meta data\n     * commit session\n     * returns ILocalOperationResult array collected over all results collectively\n     *\n     * @param ops Opeartions to run\n     * @param modelsById A map of model to it's id\n     * @param itemPool ItemPool of the specific context used to create session\n     * @param updateLocalModel for updating Model metaData\n     * @param errorHandlers If needed to validate or check any specific error code, and respond differently\n     */\n    async runOperationsForContext<LocalType extends ItemBase>(\n        ops: IOperationQuery,\n        modelsById: Map<string, LocalType>,\n        itemPool: ItemPool<LocalType>,\n        updateLocalModel: (session: IUpdateSession<LocalType>, model: LocalType, remoteItem?: RepositoryMetadata) => LocalType | undefined,\n        errorHandlers?: { match: (error: SAMError) => boolean, action: (model: LocalType, error: SAMError) => Promise<void | IFailedOperation<LocalType>> }[]\n    ): Promise<IBatchOperationResult<LocalType>> {\n        // Convert single operation to array for uniform processing\n        const operations = Array.isArray(ops) ? ops : [ ops ];\n\n        // Chunk operations and process in parallel (handles both small and large batches)\n        const chunks = this._chunkArray(operations, MAX_BATCH_OPERATION_SIZE);\n        const chunkPromises = chunks.map(chunk =>\n            this._runOperationsForContextBatch(chunk, modelsById, itemPool, updateLocalModel, errorHandlers)\n        );\n\n        // Wait for all chunks to complete\n        const chunkResults = await Promise.all(chunkPromises);\n\n        // Combine results from all chunks\n        return this._combineOperationResults(chunkResults);\n    }\n\n    /**\n     * Internal method to run operations for a single batch (within size limits)\n     * @param ops Operations to run (should be <= MAX_BATCH_OPERATION_SIZE)\n     * @param modelsById A map of model to it's id\n     * @param itemPool ItemPool of the specific context used to create session\n     * @param updateLocalModel for updating Model metaData\n     * @param errorHandlers If needed to validate or check any specific error code, and respond differently\n     * @returns Batch operation result\n     */\n    private async _runOperationsForContextBatch<LocalType extends ItemBase>(\n        ops: IOperationQuery,\n        modelsById: Map<string, LocalType>,\n        itemPool: ItemPool<LocalType>,\n        updateLocalModel: (session: IUpdateSession<LocalType>, model: LocalType, remoteItem?: RepositoryMetadata) => LocalType | undefined,\n        errorHandlers?: { match: (error: SAMError) => boolean, action: (model: LocalType, error: SAMError) => Promise<void | IFailedOperation<LocalType>> }[]\n    ): Promise<IBatchOperationResult<LocalType>> {\n        const result = await this.runOperation(ops);\n\n        const resultOps: IBatchOperationResult<LocalType> = { failedResults: [], newModels: [] };\n\n        const session = itemPool.createMutationSession();\n        const promises: Promise<void>[] = [];\n\n        for (const op of result) {\n            const currentModel = op.id && modelsById.get(op.id);\n            if (!currentModel) {\n                continue;\n            }\n\n            const { asset: updatedModelMetaData, error } = op;\n\n            if (error) {\n                if (errorHandlers) {\n                    const onError = (errorHandlers.find(errorHandler => errorHandler.match(error)))?.action;\n                    if (onError) {\n                        promises.push(onError(currentModel, error).then(failedOp => {\n                            if (failedOp) {\n                                resultOps.failedResults.push(failedOp);\n                            }\n                        }));\n                        continue;\n                    }\n                }\n\n                resultOps.failedResults.push({ model: currentModel, error });\n                continue;\n            }\n\n            try {\n                const newModel = updateLocalModel(session, currentModel, updatedModelMetaData);\n                if (newModel) {\n                    resultOps.newModels.push(newModel);\n                }\n            } catch (error: any) {\n                const samError = error as SAMError;\n                if (samError && samError.code === SAMErrorCode.UNKNOWN) {\n                    resultOps.failedResults.push({ model: currentModel, error: samError });\n                } else {\n                    throw error;\n                }\n            }\n        }\n\n        session.commit();\n\n        // Wait for any Promises from errorHandlers callback\n        await Promise.all(promises);\n\n        return resultOps;\n    }\n\n    /* Fetches data from the repositories endpoint.\n     * These are all the repositories that contain at least one discoverable asset for this user.\n     */\n    @synchronized\n    async getRepositoriesData(): Promise<IRepositoriesDataResponse> {\n        const fetchRepositories = () => this._getResponse(this.repositoryNameIndex);\n        const dayInMs = 24 * 60 * 60 * 1000; //30 day expiration on cache entry\n        return await this._cache.getItem(this.repositoryNameIndex, fetchRepositories, undefined, 30 * dayInMs);\n    }\n\n    async getRepositoryName(id: string): Promise<string | undefined> {\n        const response =  await this.getRepositoriesData();\n        if (!response) {\n            return undefined;\n        }\n\n        const children = response.children;\n        const data =  children.find(data => data._embedded[RelType.PRIMARY]['repo:repositoryId'] === id);\n        return data?._embedded[RelType.PRIMARY]['dc:title']?.['rdf:_1']?.['@value'];\n    }\n\n    async getStorageAssignee(id: string): Promise<Assignee | undefined> {\n        const response =  await this.getRepositoriesData();\n\n        const children = response.children;\n        const data =  children.find(data => data._embedded[RelType.PRIMARY]['repo:repositoryId'] === id);\n        if (data?._embedded[RelType.PRIMARY]['storage:assignee']) {\n            return data?._embedded[RelType.PRIMARY]['storage:assignee'];\n        } else {\n            return undefined;\n        }\n    }\n\n    /**\n     * Fetches and returns the owner details for a given list of repositoryIDs.\n     * @param targetRepoId Optional repository ID to ensure is included in the result. Will delete cache and retry fetching if not found in the initial response.\n     * @returns A map where each key is a repositoryID and the value is an Owner object.\n     */\n    async getRepoOwnerMap(targetRepoId?: string): Promise<Map<string, Owner>> {\n        let response = await this.getRepositoriesData();\n        let ownerMap = new Map(response.children.map(repoData => {\n            const primary = repoData._embedded[RelType.PRIMARY] || {};\n            return [ primary['repo:repositoryId'], primary['repo:owner'] ];\n        }));\n\n        // If a specific repository is missing, clear cache and try once more\n        if (targetRepoId && !ownerMap.has(targetRepoId)) {\n            await this._cache.deleteItem(this.repositoryNameIndex);\n            response = await this.getRepositoriesData();\n            ownerMap = new Map(response.children.map(repoData => {\n                const primary = repoData._embedded[RelType.PRIMARY] || {};\n                return [ primary['repo:repositoryId'], primary['repo:owner'] ];\n            }));\n        }\n\n        return ownerMap;\n    }\n\n    /* Call the Links API to get the asset links resulting in a service call instead of using local cache.\n     * This is intended as an eventual replacement for resolveById which uses the local cache.\n     * Fixes [SAM-3444]. NOTE: the /links API does not include the restore and discard links, but since\n     * SAM.js uses the /ops API for these operations, it shouldn't be needed. Meanwhile, SAM.js\n     * needs the download and block transfer links, which do not appear in the /:repometadata\n     * body (they're only in the header), but do appear in the /links body.\n     */\n    async getAssetLinks(assetId: string): Promise<AssetLinks> {\n        const resolveHref = this.getAssetResolveByIdHref(assetId);\n        const { _links } = await this._getResponse(resolveHref) as { _links: AssetLinks };\n        return _links;\n    }\n\n    @cache\n    async getRepositoryLinks(@key repositoryID: string): Promise<AssetLinks> {\n        const href = this._getRepositoryHref(repositoryID);\n        const { _links } = await this._getResponse(href) as { _links: AssetLinks };\n        return _links;\n    }\n\n    /**\n     * Creates a folder at the given path in the repository\n     *\n     * @param path The path to create the folder at.\n     * @param repositoryID The repository id to create the folder in.\n     * @param createIntermediates Whether to create intermediate folders if they don't exist.\n     * @param links The repository links to use for the request. Workfront repositories can only be fetched through /index-workfront and not\n     * from the /content/repo/:repositoryID endpoint.\n     * @returns The created folder's repository metadata.\n     */\n    async createFolderByPath(path: string, repositoryID: string, createIntermediates: boolean = true, links?: AssetLinks): Promise<RepositoryMetadata> {\n        const repositoryLinks = links ?? await this.getRepositoryLinks(repositoryID);\n        const createHref = getURLFromLinks(\n            repositoryLinks,\n            RelType.CREATE,\n            {\n                path,\n                intermediates: createIntermediates,\n                respondWith: RelType.REPO_METADATA\n            }\n        );\n\n        const response = await this._doPost(createHref, {\n            'Content-Type': FOLDER_TYPE\n        }, undefined, [ 200, 201 ]);\n        return response.json();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { default as ChangeEvent } from '../core/ChangeEvent';\nimport type { ONSResourceType } from './ONSResource';\n\nexport const ONS_FIRST_LONG_POLL_STARTED = 'firstLongPollStarted';\nexport const ONS_FIRST_LONG_POLL_COMPLETED = 'firstLongPollCompleted';\nexport const ONS_MONITORING_STATUS_CHANGED = 'onsMonitoringStatusChanged';\n/**\n * Status of the ONS Monitoring performed by the ONS Context.\n * @see ONSContext\n *\n */\nexport enum OnsMonitoringStatus {\n    Unknown,\n    Inactive,\n    Restarting,\n    Active,\n    Error\n}\n\n// Additional information that comes with an ONS event\nexport interface ONSChangedAssetInfo {\n    parentAssetId?: string;\n    plsAssetListId?: string;\n    changedLabels?: string[];\n    changedResources?: ONSResourceType[];\n    annotationIds?: string[];\n}\n\nexport class ONSAssetChangeEvent extends ChangeEvent {\n    constructor(\n        readonly changedAssets: Map<string, ONSChangedAssetInfo>\n    ) {\n        super();\n    }\n}\n\nexport class ONSFirstLongPollStartedEvent extends Event {\n    constructor(readonly cachedSubscriptionsUsed: boolean) {\n        super(ONS_FIRST_LONG_POLL_STARTED);\n    }\n}\n\nexport class ONSFirstLongPollCompletedEvent extends Event {\n    constructor(readonly expired: boolean) {\n        super(ONS_FIRST_LONG_POLL_COMPLETED);\n    }\n}\n\nexport class ONSMonitoringStatusChangedEvent extends Event {\n    constructor(readonly status: OnsMonitoringStatus) {\n        super(ONS_MONITORING_STATUS_CHANGED);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport {\n    FOLDER_ALTERNATE_TYPE,\n    FOLDER_TYPE\n} from './AssetInterface';\n\nexport function updateAssetTypeForUSS(type?: string[]) {\n    // directories in uss contain mime type 'application/x-sharedcloud-collection+json'\n    // adding it to the list if clients wants to search for directories\n    if (type?.find((item) => {return item === FOLDER_TYPE;})) {\n        type.push(FOLDER_ALTERNATE_TYPE);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport InterfaceBase from './InterfaceBase';\nimport type { ISearchQuery, ISearchSortOrderDirection, USSResponse } from './USSModel';\nimport { SearchProps } from './USSModel';\nimport type { ISBMAdobeAssetOrderBy } from './AssetModel';\nimport { updateAssetTypeForUSS } from './USSUtils';\n\ntype IPageOptions = {\n    limit: number;\n    start?: number;\n}\n\ninterface IListingOptions<IOrderField> extends IPageOptions {\n    orderDirection: IOrderDirection;\n    orderBy: IOrderField;\n}\n\nexport interface SBMAssetsListingOptions extends IListingOptions<ISBMAdobeAssetOrderBy> {\n    type?: string[]\n}\n\nconst DefaultSBMAssetsListingOptions: SBMAssetsListingOptions = {\n    orderDirection: 'descending',\n    orderBy: 'shared_date',\n    start: 0,\n    limit: 0\n};\n\nexport function getDirectionValue(userOptions: Partial<SBMAssetsListingOptions>): ISearchSortOrderDirection {\n    const directionFlag = userOptions.orderDirection === 'ascending' ? 'asc' : 'desc';\n    return directionFlag;\n}\n\nexport default class SBMInterface extends InterfaceBase {\n\n    async getSharedByMeAssets(parentId: string, options?: Partial<SBMAssetsListingOptions>): Promise<USSResponse> {\n        options = { ...DefaultSBMAssetsListingOptions, ...options };\n        updateAssetTypeForUSS(options.type);\n        const filters: ISearchQuery = {\n            hints: {\n                acp_platform_v2: true,\n            },\n            'fetch_fields': {\n                'includes': [\n                    'collab_metadata$$collaborators'\n                ]\n            },\n            'storage:assignee$$type': [ 'user' ],\n            op_none_of: [\n                {\n                    'app_metadata$$shell:visibility': 'hiddenSelf',\n                },\n            ],\n            parent_id: [ parentId ],\n            [SearchProps.TYPE]: options.type || [],\n            sort_orderby: options.orderBy,\n            sort_order: getDirectionValue(options),\n            limit: options.limit,\n            start_index: options.start\n        };\n\n        const response = await this._core.hostAssetContext._ussInterface.getQueryResponse(filters);\n        return response;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport InterfaceBase from './InterfaceBase';\nimport type { ISearchQuery, ISearchSortOrderDirection, USSResponse } from './USSModel';\nimport { SearchProps } from './USSModel';\nimport type { ISWYAdobeAssetOrderBy } from './AssetModel';\nimport { getUSSFetchFields } from './AssetModel';\nimport {\n    updateAssetTypeForUSS\n} from './USSUtils';\nimport { FOLDER_TYPE } from './AssetInterface';\nimport type Resource from '../assets/Resource';\nimport { excludeExpressArtifacts } from '../utils/excludeExpressArtifacts';\n\ntype IPageOptions = {\n    limit: number;\n    start?: number;\n}\n\ninterface IListingOptions<IOrderField> extends IPageOptions {\n    orderDirection: IOrderDirection;\n    orderBy: IOrderField;\n}\n\nexport interface SWYAssetsListingOptions extends IListingOptions<ISWYAdobeAssetOrderBy> {\n    mediaTypes?: string[],\n    excludeMediaTypes?: string[],\n    embedPermissions?: boolean,\n}\n\nconst DefaultSWYAssetsListingOptions: SWYAssetsListingOptions = {\n    orderDirection: 'descending',\n    orderBy: 'shared_date',\n    start: 0,\n    limit: 0,\n    mediaTypes: [],\n    excludeMediaTypes: [],\n};\n\nexport function getDirectionValue(userOptions: Partial<SWYAssetsListingOptions>): ISearchSortOrderDirection {\n    const directionFlag = userOptions.orderDirection === 'ascending' ? 'asc' : 'desc';\n    return directionFlag;\n}\n\nexport default class SWYInterface extends InterfaceBase {\n\n    async getSWYAssets(options?: Partial<SWYAssetsListingOptions>, resource?: Resource): Promise<USSResponse> {\n        options = { ...DefaultSWYAssetsListingOptions, ...options };\n        updateAssetTypeForUSS(options.mediaTypes);\n        options.excludeMediaTypes = [ ...new Set<string>(options.excludeMediaTypes!.concat(FOLDER_TYPE)) ];\n        updateAssetTypeForUSS(options.excludeMediaTypes);\n        const filters: ISearchQuery = {\n            shared_via_invite: true,\n            hints: {\n                acp_platform_v2: true,\n            },\n            fetch_fields: { includes: getUSSFetchFields() },\n            op_none_of: [\n                {\n                    op_field_exists: [\n                        'app_metadata$$cc:inheritable$$cc:team$$repo:assetId',\n                        // for excluding the older spaces and its children\n                        // We would want to show project children, but not projects themselves in swy\n                        'app_metadata$$cc:inherited$$cc:space$$repo:assetId',\n                        'app_metadata$$cc:inheritable$$cc:space$$repo:assetId'\n                    ],\n                },\n                {\n                    [SearchProps.VISIBILITY]: [ 'hiddenSelf', 'hiddenRecursive' ],\n                },\n                {\n                    [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: 'appdata',\n                },\n                {\n                    [SearchProps.TYPE]: options.excludeMediaTypes || [],\n                },\n                {\n                    [SearchProps.STORAGE_ASSIGNEE_ID]: this._core._environment.getValue('USER_ID'),\n                },\n                // SAMJS-773\n                ...excludeExpressArtifacts(),\n            ],\n            [SearchProps.TYPE]: options.mediaTypes || [],\n            sort_orderby: options.orderBy,\n            sort_order: getDirectionValue(options),\n            limit: options.limit,\n            start_index: options.start,\n        };\n\n        if (options.embedPermissions) {\n            filters.fetch_fields!.includes.push('_embedded');\n        }\n\n        const response = await this._core.hostAssetContext._ussInterface.getQueryResponse(filters, resource);\n        return response;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport InterfaceBase from './InterfaceBase';\nimport {\n    updateAssetTypeForUSS\n} from './USSUtils';\nimport type { UploadedFromType } from '../assets/USSAdobeAssetFilter';\nimport {\n    excludeExpressArtifacts,\n    type ISearchQueryEntryFilter,\n    type USSResponse,\n    USSv3FilterField,\n    USSv3Function,\n    USSv3OrderDir,\n    USSv3OrderField\n} from './USSv3Model';\n\nexport interface AssetsListingSearchOptions {\n    limit: number;\n    start?: number;\n    mediaTypes?: string[];\n    excludeMediaTypes?: string[];\n    query?: string;\n    deepSearch?: boolean;\n    assetId?: string;\n    embedPermissions?: boolean;\n    userId?: string;\n    uploadedFrom?: UploadedFromType;\n    orderBy: USSv3OrderField;\n    orderDirection: USSv3OrderDir;\n}\n\nconst DefaultAssetsListingSearchOptions: AssetsListingSearchOptions = {\n    orderDirection: USSv3OrderDir.Descending,\n    orderBy: USSv3OrderField.Modified,\n    start: 0,\n    limit: 0\n};\n\nexport default class AdobeAssetSearchInterface extends InterfaceBase {\n\n    async getFilteredAssets(options?: Partial<AssetsListingSearchOptions>): Promise<USSResponse> {\n        options = { ...DefaultAssetsListingSearchOptions, ...options };\n        updateAssetTypeForUSS(options.mediaTypes);\n        updateAssetTypeForUSS(options.excludeMediaTypes);\n        const filters: ISearchQueryEntryFilter[] = [\n            { [USSv3Function.NOT]: {\n                funcParams: {\n                    [USSv3FilterField.SHELL_VISIBILITY]: [ 'hiddenSelf', 'hiddenRecursive' ],\n                    // USS v3 new endpoint does not match on empty array\n                    ...(options.excludeMediaTypes?.length ? { [USSv3FilterField.MEDIA_TYPE]: options.excludeMediaTypes } : {}),\n                }\n            } }\n        ];\n\n        if (options.mediaTypes?.length) {\n            // USS v3 new endpoint does not match on empty array\n            filters.push({ [USSv3FilterField.MEDIA_TYPE]: options.mediaTypes });\n        }\n\n        if (options.deepSearch) {\n            filters.push({ [USSv3FilterField.REPO_ANCESTORS]: options.assetId });\n        } else {\n            filters.push({ [USSv3FilterField.PARENT_ID]: options.assetId });\n        }\n\n        const userId = options.userId;\n        const uploadedFrom = options.uploadedFrom;\n\n        if (userId) {\n            filters.push({ [USSv3FilterField.STORAGE_ASSIGNEE_ID]: userId });\n        }\n        if (uploadedFrom) {\n            filters.push({ [USSv3FilterField.CREATED_FROM_UPLOAD]: true });\n            if (uploadedFrom !== 'ALL') {\n                filters.push({ [USSv3FilterField.CREATED_BY_CLIENT_ID]: uploadedFrom });\n            }\n        }\n\n        // SAMJS-773\n        filters.push(excludeExpressArtifacts());\n\n        return await this._core.hostAssetContext.__ussInterfaceV3.getQueryResponse({\n            start: options.start!,\n            sorts: [ { sortOrderBy: options.orderBy!, sortOrder: options.orderDirection! } ],\n            limit: options.limit!,\n            ...(options.query ? { textQuery: options.query } : {}),\n            filters\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport InterfaceBase from './InterfaceBase';\nimport type { ISearchQuery, ISearchSortOrderDirection, USSResponse } from './USSModel';\nimport { SearchProps } from './USSModel';\nimport type { IUSSAdobeAssetOrderBy } from './AssetModel';\nimport { getUSSFetchFields } from './AssetModel';\nimport { updateAssetTypeForUSS } from './USSUtils';\n\n type IPageOptions = {\n     limit: number;\n     start?: number;\n }\n\ninterface IListingOptions<IOrderField> extends IPageOptions {\n    orderDirection: IOrderDirection;\n    orderBy: IOrderField;\n}\n\nexport interface AssetsListingGlobalSearchOptions extends IListingOptions<IUSSAdobeAssetOrderBy> {\n    mediaTypes?: string[];\n    query?: string;\n    excludeMediaTypes?: string[];\n    embedPermissions?: boolean;\n}\n\nconst DefaultAssetsListingGlobalSearchOptions: AssetsListingGlobalSearchOptions = {\n    orderDirection: 'descending',\n    orderBy: 'modify_date',\n    start: 0,\n    limit: 0\n};\n\nexport function getDirectionValue(userOptions: Partial<AssetsListingGlobalSearchOptions>): ISearchSortOrderDirection {\n    const directionFlag = userOptions.orderDirection === 'ascending' ? 'asc' : 'desc';\n    return directionFlag;\n}\n\nexport default class AdobeAssetGlobalSearchInterface extends InterfaceBase {\n    /**\n     * @TODO We should open this up to allow clients to configure the resctrictions\n     * on this query through a filter.\n     * https://jira.corp.adobe.com/browse/SAM-2542\n     */\n    async getFilteredAssets(options?: Partial<AssetsListingGlobalSearchOptions>): Promise<USSResponse> {\n        options = { ...DefaultAssetsListingGlobalSearchOptions, ...options };\n        updateAssetTypeForUSS(options.mediaTypes);\n        updateAssetTypeForUSS(options.excludeMediaTypes);\n        const filters: ISearchQuery = {\n            hints: {\n                acp_platform_v2: true,\n            },\n            fetch_fields: { includes: getUSSFetchFields() },\n            [SearchProps.STORAGE_ASSIGNEE_TYPE]: [ 'user' ],\n            op_none_of: [\n                {\n                    op_field_exists: [\n                        // for excluding the older spaces and its children\n                        // We would want to show project and its children in global search\n                        'app_metadata$$cc:inheritable$$cc:space$$repo:assetId',\n                        'app_metadata$$cc:inherited$$cc:space$$repo:assetId',\n                    ],\n                },\n                {\n                    [SearchProps.VISIBILITY]: [ 'hiddenSelf', 'hiddenRecursive' ],\n                },\n                {\n                    [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: 'appdata',\n                },\n                {\n                    [SearchProps.TYPE]: options.excludeMediaTypes || [],\n                },\n\n            ],\n            op_or: [\n                // TODO: Update _getItemData in AdobeAssetGlobalSearchLoader if we support Global\n                // search loader to show other items as well. For e.g. projects\n                {\n                    [SearchProps.STORAGE_ASSIGNEE_ID]: this._core._environment.getValue('USER_ID')\n                },\n                {\n                    [SearchProps.SHARED_VIA_INVITE]: true\n                }\n            ],\n            [SearchProps.TYPE]: options.mediaTypes || [],\n            sort_orderby: options.orderBy,\n            sort_order: getDirectionValue(options),\n            limit: options.limit,\n            start_index: options.start,\n            // Since this is a JSON payload in the request, the `query` param is safe from injection attacks\n            ...(options.query ? { q: options.query } : {})\n        };\n\n        if (options.embedPermissions) {\n            filters.fetch_fields!.includes.push('_embedded');\n        }\n\n        const response = await this._core.hostAssetContext._ussInterface.getQueryResponse(filters);\n        return response;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { UploadedFromType } from '../assets/USSAdobeAssetFilter';\nimport { getUSSFetchFields } from './AssetModel';\nimport InterfaceBase from './InterfaceBase';\nimport type { ISearchQuery, USSResponse, IOpOr } from './USSModel';\nimport { SearchProps, LastAccessedOrderField } from './USSModel';\nimport {\n    updateAssetTypeForUSS\n} from './USSUtils';\nimport { excludeExpressArtifacts } from '../utils/excludeExpressArtifacts';\n\ntype IPageOptions = {\n    limit: number;\n    start?: number;\n}\n\ninterface IListingOptions extends IPageOptions {}\n\nexport interface RecentAssetsListingOptions extends IListingOptions {\n    mediaTypes?: string[],\n    excludeMediaTypes?: string[],\n    embedPermissions?: boolean,\n    uploadedFrom?: UploadedFromType;\n    userId?: string;\n}\n\nconst DefaultRecentAssetsListingOptions: RecentAssetsListingOptions = {\n    start: 0,\n    limit: 0,\n    mediaTypes: [],\n    excludeMediaTypes: [],\n};\n\nexport default class RecentInterface extends InterfaceBase {\n\n    private _getCommonFilters(options?: Partial<RecentAssetsListingOptions>): ISearchQuery {\n        options = { ...DefaultRecentAssetsListingOptions, ...options };\n        const { uploadedFrom } = options ?? {};\n        updateAssetTypeForUSS(options.mediaTypes);\n        updateAssetTypeForUSS(options.excludeMediaTypes);\n        // Folders should never be included in Recents listing\n        options.excludeMediaTypes = Array.from(\n            new Set([ 'application/x-sharedcloud-collection+json', ...(options.excludeMediaTypes || []) ])\n        );\n        const filters: ISearchQuery = {\n            hints: {\n                acp_platform_v2: true,\n            },\n            fetch_fields: { includes: getUSSFetchFields() },\n            sort_order: 'desc',\n            limit: options.limit,\n            start_index: options.start,\n            [SearchProps.TYPE]: options.mediaTypes || [],\n            op_none_of: [\n                {\n                    [SearchProps.FIELD_EXISTS]: [\n                        // for excluding the older spaces and its children\n                        'app_metadata$$cc:inheritable$$cc:space$$repo:assetId',\n                        'app_metadata$$cc:inherited$$cc:space$$repo:assetId',\n                        // for excluding only the projects\n                        'app_metadata$$cc:inheritable$$cc:team$$repo:assetId',\n                    ],\n                },\n                {\n                    [SearchProps.VISIBILITY]: [ 'hiddenSelf', 'hiddenRecursive' ],\n                },\n                {\n                    [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: [ 'appdata' ],\n                },\n                {\n                    [SearchProps.TYPE]: options.excludeMediaTypes || [],\n                },\n                {\n                    // For excluding legacy artifacts.\n                    [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: 'pubs'\n                },\n                {\n                    // For excluding more modern artifacts.\n                    [SearchProps.OP_AND]: [\n                        {\n                            [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: 'cloud-content'\n                        },\n                        {\n                            [SearchProps.FIELD_EXISTS]: [ 'app_metadata$$review:sourceAsset$$dc:format' ]\n                        }\n                    ],\n                },\n                // SAMJS-773\n                ...excludeExpressArtifacts()\n            ],\n        };\n\n        if (options.embedPermissions) {\n            filters.fetch_fields!.includes.push('_embedded');\n        }\n\n        if (uploadedFrom) {\n            filters.op_and = [];\n            filters.op_and.push({\n                [SearchProps.CREATED_FROM_UPLOAD]: true\n            });\n        }\n\n        if (uploadedFrom && Array.isArray(uploadedFrom)) {\n            const length = filters.op_and!.push({\n                [SearchProps.OP_OR]: []\n            });\n            uploadedFrom.forEach((value: string) => {\n                const filter = filters.op_and![length - 1] as IOpOr;\n                filter[SearchProps.OP_OR].push(\n                    {\n                        [SearchProps.CREATED_BY_CLIENT_ID]: value\n                    }\n                );\n            });\n        }\n\n        if (uploadedFrom && !Array.isArray(uploadedFrom) && uploadedFrom !== 'ALL') {\n            filters.op_and!.push({\n                [SearchProps.CREATED_BY_CLIENT_ID]: uploadedFrom\n            });\n        }\n\n        return filters;\n    }\n\n    async getRecentAssets(options?: Partial<RecentAssetsListingOptions>): Promise<USSResponse> {\n        const filters = this._getCommonFilters(options);\n        const { userId } = options ?? {};\n        // should not give order given by client in this request\n        // because Recent assets mean descending direction of modified date\n        filters.sort_orderby = 'modify_date';\n        const storageAssigneeQuery = {\n            [SearchProps.STORAGE_ASSIGNEE_ID]: userId ?? this._core._environment.getValue('USER_ID')\n        };\n\n        // If the userId is present we want to add this to the and\n        // operation of the query.\n        if (userId) {\n            if (!filters.op_and) {\n                filters.op_and = [];\n            }\n            filters.op_and.push(storageAssigneeQuery);\n        } else {\n            // If the userId is present then we don't want to include the\n            // SHARED_VIA_INVITED as well since that will include results that are not\n            // equal to the userId provided.\n\n            if (!filters.op_or) {\n                filters.op_or = [];\n            }\n\n            filters.op_or.push(storageAssigneeQuery);\n            filters.op_or.push({\n                [SearchProps.SHARED_VIA_INVITE]: true\n            });\n        }\n\n        const response = await this._core.hostAssetContext._ussInterface.getQueryResponse(filters);\n        return response;\n    }\n\n    async getMRUAssets(options?: Partial<RecentAssetsListingOptions>): Promise<USSResponse> {\n        const filters = this._getCommonFilters(options);\n        filters.fetch_fields!.includes.push(LastAccessedOrderField);\n        const { userId } = options ?? {};\n\n        if (userId) {\n            if (!filters.op_and) {\n                filters.op_and = [];\n            }\n\n            filters.op_and.push({\n                [SearchProps.STORAGE_ASSIGNEE_ID]: userId\n            });\n        }\n\n        // should not give order given by client in this request\n        // because Recent assets mean descending direction of last accessed date\n        filters.sort_orderby = LastAccessedOrderField;\n        filters.op_field_exists = [ LastAccessedOrderField ];\n        const response = await this._core.hostAssetContext._ussInterface.getQueryResponse(filters);\n        return response;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport InterfaceBase from './InterfaceBase';\nimport type { IServiceLink } from './LinkUtils';\nimport { getURLFromLinks, RelType } from './LinkUtils';\nimport SAMError from '../core/SAMError';\n\ninterface IAssetTransferServiceLinks {\n    [RelType.ATS_MOVE]: IServiceLink\n}\n\ninterface IAssetTransferServiceIndexResponse {\n    _links: IAssetTransferServiceLinks\n}\n\ninterface IAssetTransferQuery {\n    source: { assetId: string, repositoryId: string},\n    target: { assetId: string, repositoryId: string}\n}\n\nexport default class AssetTransferInterface extends InterfaceBase {\n    async transfer(data: IAssetTransferQuery): Promise<string> {\n        const links = await this.discoverLinks();\n        const response = await this._doPost(\n            getURLFromLinks(links, RelType.ATS_MOVE),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(data), [ 200 ]);\n\n        // Asset Transfer Service will return a 200 response when a dependent service fails.\n        const json = await response.json();\n        if (json.status && json.status !== 200) {\n            throw SAMError.createWithResponse(response);\n        }\n\n        // Returns the transferred asset's Cloud ID.\n        return json.assetId;\n    }\n\n    async discoverLinks(): Promise<IAssetTransferServiceLinks> {\n        const response = await this._getResponse<IAssetTransferServiceIndexResponse>(this.getUrl('/'));\n        return response._links;\n    }\n\n    private getUrl(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.TRANSFER_SERVICE_HOST}${endpoint}`;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from './AdobeAsset';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { RecentAdobeAssetConfig } from './RecentAdobeAssetSource';\nimport type RecentAdobeAssetFilter from './RecentAdobeAssetFilter';\nimport type RecentInterface from '../interface/RecentInterface';\nimport type { IGetUSSResults, IUSSLoader } from './USSLoaderHelper';\nimport USSLoaderHelper from './USSLoaderHelper';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type AdobeAssetFilter from '../assets/AdobeAssetFilter';\nimport type { USSResponse } from '../interface/USSModel';\nimport type LibraryContext from '../libraries/LibraryContext';\nimport { USSAssetFilterName } from './USSAssetFilterName';\nimport type USSAdobeAssetFilter from './USSAdobeAssetFilter';\nimport type { RecentAssetsListingOptions } from '../interface/RecentInterface';\n\nexport default class RecentAdobeAssetLoader implements IUSSLoader<RecentAdobeAssetConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<RecentAdobeAssetConfig>;\n    /**\n      * @package -- only for use in SAM.js\n      */\n    _libraryContext?: LibraryContext;\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private _recentInterface: RecentInterface,\n        private _implicitFilter: RecentAdobeAssetFilter\n    ) {\n        this._ussLoaderHelper = new USSLoaderHelper(assetPool, _core, this);\n    }\n\n    supportsFilter(filter?: RecentAdobeAssetFilter | AdobeAssetFilter): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<RecentAdobeAssetConfig>): Promise<ILoadedPage<RecentAdobeAssetConfig>> {\n        if (!this._libraryContext) {\n            this._libraryContext = await this._core.getLibraryContext();\n        }\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- only for use by USSLoaderHelper\n     */\n    async _getUSSResults({\n        start,\n        loadOptions,\n        mediaTypes,\n        excludeMediaTypes,\n        filter\n    }: IGetUSSResults<RecentAdobeAssetConfig>): Promise<USSResponse> {\n        const options: Partial<RecentAssetsListingOptions> = {\n            start,\n            limit: loadOptions?.limit,\n            mediaTypes,\n            excludeMediaTypes,\n            embedPermissions: true\n        };\n        if (filter.name === USSAssetFilterName) {\n            const ussFilter = filter as USSAdobeAssetFilter;\n            options.userId = ussFilter.userId;\n            options.uploadedFrom = ussFilter.uploadedFrom;\n        }\n        return this._recentInterface.getRecentAssets(options);\n    }\n\n    /**\n     * @package -- only for use by USSLoaderHelper\n     */\n    _postProcessPage(\n        loaderOptions: IItemLoaderOptions<RecentAdobeAssetConfig>,\n        page: ILoadedPage<RecentAdobeAssetConfig>\n    ): void {\n        const { items } = page;\n\n        // update modification time of last asset on implicit filter (assets are already sorted by modification time),\n        // so that these items can be matched with this filter in ItemLoaderState before adding them in ItemLoaderState._pages\n        if (items.length) {\n            this._implicitFilter._lastModificationDate = items[items.length - 1].modified;\n        }\n    }\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\n\nexport default class RecentAdobeAssetFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _lastModificationDate: Date | undefined;\n    constructor() {\n        super({ _isSharedWithYou: true });\n    }\n\n    matches(item: AdobeAsset): boolean {\n        // We don't want folders to match the Recents filter\n        if (item.isFolder) {\n            return false;\n        }\n        if (this._lastModificationDate && item.modified < this._lastModificationDate) {\n            return false;\n        }\n        return super.matches(item);\n    }\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ItemBase from '../core/ItemBase';\nimport type SAMError from '../core/SAMError';\nimport { SAMErrorCode } from '../core/SAMError';\nimport type { IBatchOperationResult, IFailedOperation } from '../interface/RepositoryModel';\nimport type { AssetRenameMap, NameConflictMap } from './AssetUtils';\n\ninterface IConflictRetryOp<Source extends ItemBase, Destination extends ItemBase> {\n    (\n        assets: Source[],\n        destination: Destination,\n        assetRenameMap: AssetRenameMap<any>,\n        retryOnConflict: boolean,\n        conflictMap: NameConflictMap\n    ): Promise<IBatchOperationResult<Source>>\n}\n\n/**\n * Used by batch operations to retry failed ops and rename the conflicted assets\n * @param resultOps result for batch operation. Contains failed results and new models.\n * @param destination target asset location where the source assets are moved/copied\n * @param assetRenameMap allows renaming of assets in the batch operation\n * @param conflictMap saves the newName and count used for all files in batch\n * @param conflictRetryOp the original batch op method that is called after renaming conflicted assets\n * @returns the result for batch operation after retrying for failed assets.\n */\nexport async function retryFailedOpsDueToConflict<Source extends ItemBase, Destination extends ItemBase>(\n    resultOps: IBatchOperationResult<Source>,\n    destination: Destination,\n    assetRenameMap: AssetRenameMap<any>,\n    conflictMap: NameConflictMap,\n    conflictRetryOp: IConflictRetryOp<Source, Destination>\n): Promise<IBatchOperationResult<Source>> {\n    const failedAssetsDueToConflict: Source[] = [];\n    const otherFailedOps: IFailedOperation<Source>[] = [];\n\n    resultOps.failedResults.forEach((failedOp) => {\n        if ((failedOp.error as SAMError).code === SAMErrorCode.CONFLICT) {\n            failedAssetsDueToConflict.push(failedOp.model);\n        } else {\n            otherFailedOps.push(failedOp);\n        }\n    });\n\n    if (failedAssetsDueToConflict.length) {\n        for (const [ key, value ] of conflictMap) {\n            conflictMap.set(key, { newName: value.newName, countUsed: value.countUsed + 1 });\n        }\n        const newResultOps = await conflictRetryOp(failedAssetsDueToConflict, destination, assetRenameMap, true, conflictMap);\n        newResultOps.failedResults = [ ...newResultOps.failedResults, ...otherFailedOps ];\n        newResultOps.newModels = [ ...newResultOps.newModels, ...resultOps.newModels ];\n        return newResultOps;\n    }\n\n    return resultOps;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\n\nexport default class MRUAdobeAssetFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    constructor() {\n        super({ _isSharedWithYou: true });\n    }\n\n    matches(item: AdobeAsset): boolean {\n        // We don't want folders to match the Recents filter\n        if (item.isFolder) {\n            return false;\n        }\n\n        // do we need to allow certain items up to a threshold in the MRU list\n        // as we do in the recents list by keeping record of lastModified\n        if (item.lastAccessed === undefined) {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMEvent from '../core/SAMEvent';\nexport const LIBRARY_DATA_CHANGED = 'library_data_changed';\nexport default class LibraryDataChangedEvent extends SAMEvent {\n\n    constructor() {\n        super(LIBRARY_DATA_CHANGED);\n    }\n}\n\nexport const LibraryDataChangedEventInstance = new LibraryDataChangedEvent();\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\nimport SAMEvent from '../core/SAMEvent';\nexport const RESTRICT_EDIT_CHANGED = 'restrict_edit_changed';\nexport default class RestrictEditChangedEvent extends SAMEvent {\n\n    constructor() {\n        super(RESTRICT_EDIT_CHANGED);\n    }\n}\n\nexport const RestrictEditChangedEventInstance = new RestrictEditChangedEvent();\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type Library from '../libraries/Library';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport Resource from './Resource';\n\nexport default class RenditionTileResource extends Resource<Blob> {\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _parent: Library,\n        private _renditionUrl: string\n    ) {\n        super(_core, {\n            parseResponse: async (response: Response) => await response.blob(),\n            /**\n             * Revalidation is not needed because URL changes when tile rendition changes\n             */\n            skipRevalidation: () => true\n        });\n    }\n\n    get renditionUrl(): string {\n        return this._renditionUrl;\n    }\n\n    protected async _loadData() {\n        const libraryInterface = this._parent._getLibraryInterface();\n        return libraryInterface.getRenditionTileImage(this);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { RenditionStatus } from '../utils/RenditionFetcher';\nimport { RenditionFetcher, RenditionType } from '../utils/RenditionFetcher';\nimport type { LibraryRenditionData, DataRenditionMimeTypes, LibraryObjectRenditions } from '../interface/LibraryModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { observable } from '../core/decorators';\nimport TypedEventEmitter from '../core/TypedEventEmitter';\nimport type { ItemBaseEvents } from '../core/ItemBase';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport { RenditionTileBlobHelper } from '../utils/RenditionBlobHelper';\nimport RenditionTileResource from '../assets/RenditionTileResource';\n\nexport const IMG_TILE_SIZE = 200;\n\nexport class RenditionTile extends TypedEventEmitter<ItemBaseEvents> implements ISAMObject {\n    // 'href' rendition will be a BlobUrl for an image, a rendition of type\n    // DataRenditionMimeTypes is an  object (e.g. with color or gradient data).\n    type: 'href' | DataRenditionMimeTypes;\n    elementId: string;\n    elementType: string;\n    mimetype?: DataRenditionMimeTypes; // This data is only received for non-image renditions.\n    readonly _core: ISAMCorePrivate;\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _renditionFetcher?: RenditionFetcher;\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _renditionTileBlobHelper?: RenditionTileBlobHelper;\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _renditionData?: LibraryObjectRenditions;\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _renditionUrl?: string;\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _index: number = -1;\n\n    constructor(data: LibraryRenditionData, index: number, private _library: any) {\n        super();\n        this._core = this._library._core;\n        this.type = data.type as 'href' | DataRenditionMimeTypes;\n        this._index = index;\n        if (this.type === 'href') {\n            // Only image renditions have _renditionUrl.\n            this._renditionUrl = data.rendition as string;\n            // Only image renditions need a _renditionFetcher.\n            this._renditionTileBlobHelper = new RenditionTileBlobHelper();\n            this._renditionFetcher = new RenditionFetcher(\n                this._core,\n                [ IMG_TILE_SIZE ],\n                async () => {\n                    const resource = new RenditionTileResource(this._core,\n                        this._library,\n                        // @ts-expect-error -- Object is possibly 'undefined' even though\n                        // it is initialized in this block\n                        this._renditionUrl\n                    );\n                    // @ts-expect-error -- Object is possibly 'undefined' even though\n                    // it is initialized in this block\n                    return this._renditionTileBlobHelper.fetch(resource);\n                }\n            );\n\n            // Forward change events from the rendition fetcher\n            // to this class (to catch the event from the fetcher).\n            this._renditionFetcher.on('change', () => {\n                this.dispatch({ type: 'change' });\n            });\n        } else {\n            // Only non-image renditions have _renditionData and a mimetype.\n            this._renditionData = data.rendition as LibraryObjectRenditions;\n            this.mimetype = (data as { rendition_mimetype: DataRenditionMimeTypes }).rendition_mimetype;\n        }\n        this.elementId = data.elementId;\n        this.elementType = data.elementType;\n    }\n\n    /**\n     * Returns a blob url of an image based rendition. Returns an empty string while loading, and will\n     * notify observers when the image is done loading and the blobURL is ready.\n     * @example\n     * imageUrl only applies to image renditions.\n     * if (tile.type === 'href') return <img src={tile.imageUrl} />;\n     */\n    @observable\n    get imageUrl(): string {\n        if (this.type !== 'href') {\n            throw SAMError.create(SAMErrorCode.UNKNOWN, 'Cannot fetch rendition for non-image renditions');\n        }\n        return this._renditionFetcher!.getURL(IMG_TILE_SIZE, RenditionType.PNG, this._renditionUrl!);\n    }\n\n    /**\n     * Returns the rendition object for non-image based renditions (only applies to non-image renditions).\n     * @example\n     * if (tile.type !== 'href') return <div>{tile.data} </div>;\n     */\n    get data(): object {\n        if (this.type !== 'href') {\n            if (typeof this._renditionData === 'object') {\n                return this._renditionData;\n            }\n            console.warn('Rendition data is not an object, returning default value.');\n            return {};\n        } else {\n            throw SAMError.create(SAMErrorCode.UNKNOWN, 'Cannot get data for image renditions');\n        }\n    }\n\n    /**\n     * Returns one of the enumeration values of RenditionStatus.\n     *\n     * @returns {RenditionStatus}\n     */\n    @observable\n    get imageStatus(): RenditionStatus {\n        return this._renditionFetcher!.renditionURLStatus(IMG_TILE_SIZE, RenditionType.PNG, this._renditionUrl!);\n    }\n\n    /**\n     * For use internally to release renditions after\n     * the asset has been deleted permanently.\n     * @package\n     */\n    _releaseRenditions() {\n        if (this._renditionFetcher) {\n            this._renditionFetcher.release();\n        }\n    }\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type {\n    CreateTrainingSetOptions,\n    CustomModelCreateOptions,\n    CustomModelInfoMelville,\n    CustomModelUpdateInfoMelville,\n    CustomModelsResponseMelville,\n    MelvilleCustomModelListParameters,\n} from './CustomModelModel';\nimport InterfaceBase from './InterfaceBase';\nimport type { CreateLibraryOptions, MelvilleLink } from './LibraryModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type Library from '../libraries/Library';\nimport { moveUrlQueryParamsToHeaders } from './LibraryInterface';\nimport type { HeaderMap } from './LinkUtils';\nimport { fillURLTemplate } from './LinkUtils';\nimport type { ICustomModelListingOptions } from '../custom-models/CustomModelFilter';\n\nexport default class CustomModelInterface extends InterfaceBase {\n    private _getMelvilleUrl(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.MELVILLE_HOST}${endpoint}`;\n    }\n\n    async searchCustomModelsUsingPageLink(\n        body: ICustomModelListingOptions,\n        pageLink: MelvilleLink\n    ): Promise<CustomModelsResponseMelville> {\n\n        const [ url, headerParams ] = moveUrlQueryParamsToHeaders(pageLink.href);\n\n        const headers: HeaderMap = {\n            'Cache-Control': 'no-cache, no-store, max-age=0',\n            'Content-Type': 'application/json',\n            ...headerParams\n        };\n\n        const finalUrl = this._getMelvilleUrl(url);\n\n        const response = await this._doPost(\n            finalUrl,\n            headers,\n            JSON.stringify(body),\n            [ 200 ]\n        );\n\n        return await response.json();\n    }\n\n\n    async searchCustomModels(queryParams: MelvilleCustomModelListParameters, body: ICustomModelListingOptions): Promise<CustomModelsResponseMelville> {\n        if (queryParams?.limit && queryParams?.start === undefined) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, '[Melville] If limit is provided, start must also be provided.');\n        }\n        queryParams = sortParameters(queryParams);\n        const urlWithQueryParams = fillURLTemplate(\n            this._getMelvilleUrl('/api/v1/search/custom-models'),\n            queryParams\n        );\n        const [ url, headers ] = moveUrlQueryParamsToHeaders(urlWithQueryParams);\n        const defaultHeaders: HeaderMap = {\n            'Cache-Control': 'no-cache, no-store, max-age=0',\n            'Content-Type': 'application/json'\n        };\n        const finalHeaders = { ...defaultHeaders, ...headers };\n        const response = await this._doPost(\n            url,\n            finalHeaders,\n            JSON.stringify(body), [ 200 ]);\n        return await response.json();\n    }\n\n\n    /**\n   * Fetches the list of custom models based on the options provided\n   * @returns the list of custom models along with the page information and links to the next page\n   */\n    async getCustomModels(queryParams: MelvilleCustomModelListParameters): Promise<CustomModelsResponseMelville> {\n        if (queryParams?.limit && queryParams?.start === undefined) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, '[Melville] If limit is provided, start must also be provided.');\n        }\n        queryParams = sortParameters(queryParams);\n        const urlWithQueryParams = fillURLTemplate(\n            this._getMelvilleUrl('/api/v1/custom-models'),\n            queryParams\n        );\n        // Pass as many parameters as headers as we can, to avoid extra CORS preflight OPTIONS requests per url.\n        const [ url, headers ] = moveUrlQueryParamsToHeaders(urlWithQueryParams);\n        // Ensure browser doesn't automatically add If-None-Match, otherwise\n        // service may respond with cached data for a library\n        const defaultHeaders: HeaderMap = { ['Cache-Control']: 'no-cache, no-store, max-age=0' };\n        const finalHeaders = { ...defaultHeaders, ...headers };\n\n        return await this._getResponse(url, { headers: finalHeaders });\n    }\n\n    /**\n     * Fetches one custom model by ID\n     *\n     * @param customModelId ID of custom model to be fetched\n     * @returns the custom model\n     */\n    async getCustomModelById(customModelId: string): Promise<CustomModelInfoMelville> {\n        return await this._getResponse<CustomModelInfoMelville>(\n            this._getMelvilleUrl(`/api/v1/custom-models/${customModelId}`),\n            { headers: { 'Content-Type': 'application/json' } }\n        );\n    }\n\n    /**\n   * @package -- only for use in SAM.js\n   * Fetches the next page of custom models from Melville\n   * @returns a list of custom models along with page information and links to the next page\n   */\n    async getCustomModelsUsingPageLink(pageLink: MelvilleLink): Promise<CustomModelsResponseMelville> {\n        const [ url, headers ] = moveUrlQueryParamsToHeaders(this._getMelvilleUrl(pageLink.href));\n        return this._getResponse(url, { headers });\n    }\n\n    /**\n   * Create a training set to be used with a custom model. The training set is considered a child of the parent asset\n   * specified by the parentAssetId.\n   */\n    async createTrainingSet(options: CreateTrainingSetOptions): Promise<Library> {\n        // check for values under the deprecated firefly#ffmodel key\n        const cmeOptions = options['firefly#cme'] || options['firefly#ffmodel'];\n        if (!options.name) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Invalid argument: missing required name'\n            );\n        }\n\n        if (!options.projectId) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Invalid argument: missing required projectId. The parent must be a project'\n            );\n        }\n\n        if (!cmeOptions.schemaVersion) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid argument: missing required schemaVersion.');\n        }\n\n        if (!cmeOptions.trainingMode) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid argument: missing required trainingMode.');\n        }\n\n        const creationOptions: CreateLibraryOptions = {\n            name: options.name,\n            parent_assetId: options.projectId,\n            roles: [ {\n                type: 'cm_training_set'\n            } ],\n\n            'firefly#cme': {\n                ...cmeOptions,\n                // Melville is temporarily looking at version, but will soon switch to schemaVersion\n                version: cmeOptions.schemaVersion\n            }\n        };\n\n        const libraryContext = await this._core.getLibraryContext();\n        return libraryContext._createLibrary(creationOptions);\n    }\n\n    async getTrainingSetById(assetId: string): Promise<Library | undefined> {\n        const libraryContext = await this._core.getLibraryContext();\n        return libraryContext._getLibraryRemotely(assetId, { selectors: [ 'details' ] });\n    }\n\n    async createCustomModel(options: CustomModelCreateOptions): Promise<CustomModelInfoMelville> {\n        const endpoint: string = `/api/v1/custom-models`;\n\n        const response = await this._doPost(\n            this._getMelvilleUrl(endpoint),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(options),\n            [ 201 ]);\n\n        return response.json();\n    }\n\n    async updateCustomModel(assetId: string, options: CustomModelUpdateInfoMelville) {\n        const endpoint: string = `/api/v1/custom-models/${assetId}`;\n\n        await this._doPut(\n            this._getMelvilleUrl(endpoint),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(options),\n            [ 204, 201, 200 ]);\n    }\n\n    async deleteCustomModel(assetId: string): Promise<void> {\n        const endpoint: string = `/api/v1/custom-models/${assetId}`;\n\n        await this._doDelete(\n            this._getMelvilleUrl(endpoint),\n            { 'Content-Type': 'application/json' },\n            [ 204 ]);\n    }\n\n    async discardCustomModel(assetId: string): Promise<void> {\n        await this._doPost(\n            this._getMelvilleUrl(`/api/v1/custom-models/${assetId}/discard`),\n            { 'Content-Type': 'application/json' },\n            '',\n            [ 204 ]\n        );\n    }\n\n    async restoreCustomModel(assetId: string): Promise<void> {\n        await this._doPost(\n            this._getMelvilleUrl(`/api/v1/custom-models/${assetId}/restore`),\n            { 'Content-Type': 'application/json' },\n            '',\n            [ 204 ]\n        );\n    }\n\n    async publish(assetID: string): Promise<CustomModelInfoMelville> {\n        const endpoint: string = `/api/v1/custom-models/${assetID}/publish`;\n\n        const response = await this._doPost(\n            this._getMelvilleUrl(endpoint),\n            undefined,\n            undefined,\n            [ 200 ]);\n\n        return await response.json();\n    }\n\n    async unpublish(assetID: string): Promise<CustomModelInfoMelville> {\n        const endpoint: string = `/api/v1/custom-models/${assetID}/unpublish`;\n\n        const response = await this._doPost(\n            this._getMelvilleUrl(endpoint),\n            undefined,\n            undefined,\n            [ 200 ]);\n\n        return await response.json();\n    }\n}\n\n// Sort parameters so that the query string is stable, preventing unnecessary cache misses.\nexport const sortParameters = (parameters: MelvilleCustomModelListParameters): MelvilleCustomModelListParameters => {\n    return Object.fromEntries(\n        Object.entries(parameters)\n            .map(([ key, value ]) => {\n                if (Array.isArray(value)) {\n                    return [ key, value.sort() ];\n                }\n                return [ key, value ];\n            })\n            .sort()\n    );\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { AssetLinks } from '../interface/RepositoryModel';\nimport ItemUpdater from '../core/ItemUpdater';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { Permission } from '../interface/AssetModel';\nimport { NotFound } from '../core/PropertyUpdater';\nimport { parseEffectivePermissions } from '../interface/AssetModel';\nimport AdobeAsset from '../assets/AdobeAsset';\nimport type {\n    CustomModelAppMetadataPatch,\n    CustomModelInfoMelville,\n    CustomModelRestrictedMetadataKey,\n    CustomModelTrainingState,\n    CustomModelUpdateInfoMelville } from '../interface/CustomModelModel';\nimport {\n    CUSTOM_MODEL_RESTRICTED_METADATA_KEYS\n} from '../interface/CustomModelModel';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport { memoize, observable } from '../core/decorators';\nimport { isStrictEqual } from '../core/ObjectUtils';\nimport type Library from '../libraries/Library';\nimport CustomModelInterface from '../interface/CustomModelInterface';\nimport { THUMBNAIL_SIZE } from '../utils/RenditionFetcher';\n\n/**\n * Finds the last \".\" in a string and removes it and everything after.\n * Used to strip the file extension from repo:name on custom model.\n *\n * @example <caption>Trim \"My Model.ffmodel\"</caption>\n * trimRepoName(\"My Model.ffmodel\"); // returns \"My Model\"\n *\n * @param s {string} name to be stripped\n * @return {string} name stripped of its' extension\n */\nexport const trimRepoName = (s: string): string => {\n    const index = s.lastIndexOf('.');\n    return s.slice(0, index);\n};\n\nexport function isCustomModel(asset: AdobeAsset): asset is CustomModel {\n    return asset.isCustomModel;\n}\n\nfunction getCustomModelPermission(value: Partial<CustomModelInfoMelville>): Permission | typeof NotFound {\n    if (value.asset_acl !== undefined) {\n        return parseEffectivePermissions(value.asset_acl);\n    }\n    // If asset_acl is not present then return NotFound\n    return NotFound;\n}\n\nexport default class CustomModel extends AdobeAsset implements SAM.CustomModel {\n    public isCustomModel: boolean = true;\n\n    private _displayName: string = '';\n    private _conceptId: string = '';\n    private _trainingMode: string = '';\n    private _baseModelSuperclass: string | undefined;\n    private _deltaWeightsID: string | undefined;\n    private _contentType: string | undefined;\n    private _compression: string = '';\n    private _schemaVersion: string = '';\n\n    private _customModelInterface = new CustomModelInterface(this._core);\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        id: string,\n        metadata?: {\n            links?: AssetLinks;\n        }\n    ) {\n        super(_core, id, metadata);\n    }\n\n    @memoize\n    @observable\n    async trainingSet(): Promise<Library> {\n        const libraryContext = await this._core.getLibraryContext();\n        return await libraryContext.getLibraryByAssetId(this.trainingSetInfo.id);\n    }\n\n    /**\n     * Deletes a custom model by its ID.\n     * Will first check the local asset pool for the custom model to decide if we need to update the\n     * local asset pool.\n     */\n    async permanentlyDelete(): Promise<void> {\n        await this._customModelInterface.deleteCustomModel(this.id);\n\n        const assetPool = this._core.hostAssetContext._assetPool;\n        const session = assetPool.createUpdateSession<CustomModel>('Delete Custom Model');\n        session.queueDiscardedItem(this);\n        session.commit(); // fire notifications for tracked changes\n        // The session doesn't actually remove the item from the pool\n        assetPool.removeLocalItems([ this.id ]);\n    }\n\n    /**\n     * Discard the custom model through melville.\n     * This changes its repo:state to DISCARDED, but it can later be restored or permanently deleted.\n     */\n    async discard(): Promise<void> {\n        if (this.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Asset is already discarded');\n        }\n\n        await this._customModelInterface.discardCustomModel(this.id);\n\n        const customModelContext = await this._core.getCustomModelContext();\n        const session = customModelContext._assetPool.createUpdateSession<CustomModel>('discard custom model'); // tracks changes to the asset\n\n        // Update the local item with values from the remote item\n        const assetContext = await this._core.getAssetContext();\n        assetContext._adobeAssetUpdater.updateLocalItem(session, this, { 'repo:state': 'DISCARDED' });\n        session.commit(); // fire notifications for tracked changes\n    }\n\n    async restore(): Promise<void> {\n        if (!this.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Cannot restore an asset that is not discarded');\n        }\n\n        const assetContext = await this._core.getAssetContext();\n        await this._customModelInterface.restoreCustomModel(this.id);\n        const assetPool = this._core._getAssetPool();\n        const session = assetPool.createUpdateSession<CustomModel>('restore custom model');\n        assetContext._adobeAssetUpdater.updateLocalItem(session, this, { 'repo:state': 'ACTIVE' });\n        session.commit();\n    }\n\n    async publish(): Promise<void> {\n        if (this.publishedState === 'published') {\n            return;\n        }\n\n        const customModelData = await this._customModelInterface.publish(this.id);\n        const customModelContext = await this._core.getCustomModelContext();\n        const session = customModelContext._assetPool.createUpdateSession<CustomModel>();\n\n        customModelContext._customModelUpdaterMelville.updateRemoteItem(session, customModelData);\n        session.commit();\n\n        return;\n    }\n\n    async unpublish(): Promise<void> {\n        if (this.publishedState === 'unpublished') {\n            return;\n        }\n\n        const customModelData = await this._customModelInterface.unpublish(this.id);\n        const customModelContext = await this._core.getCustomModelContext();\n        const session = customModelContext._assetPool.createUpdateSession<CustomModel>();\n\n        customModelContext._customModelUpdaterMelville.updateRemoteItem(session, customModelData);\n        session.commit();\n\n        return;\n    }\n\n    @observable\n    get displayName() {\n        return this._displayName;\n    }\n\n    @observable\n    get inferenceReady() {\n        return this.appMetadata.data['cme:inferenceReady'];\n    }\n\n    @observable\n    get publishedState() {\n        return this.appMetadata.data['cme:publishedState'];\n    }\n\n    @observable\n    get category() {\n        return this.appMetadata.data['cme:category'];\n    }\n\n    get signature(): string | undefined {\n        return this.appMetadata.data['cme:signature'];\n    }\n\n    @observable\n    get baseModelName(): string | undefined {\n        return this.appMetadata.data['cme:baseModel']?.['name'];\n    }\n\n    @observable\n    get baseModelVersion(): string | undefined {\n        return this.appMetadata.data['cme:baseModel']?.['version'];\n    }\n\n    /**\n   * Information related to the status of the training process for the Custom Model.\n   */\n    @observable\n    get trainingInfo(): { trainingState: CustomModelTrainingState, progress: number, jobId: string, errorMessage: string | null, links: Record<string, any>, errorCode?: string } {\n        return {\n            trainingState: this.appMetadata.data['cme:training']['state'],\n            progress: this.appMetadata.data['cme:training']['progress'],\n            jobId: this.appMetadata.data['cme:training']['jobId'],\n            errorMessage: this.appMetadata.data['cme:training']['errorMessage'],\n            errorCode: this.appMetadata.data['cme:training']['errorCode'],\n            links: this.appMetadata.data['cme:training']['links']\n        };\n    }\n\n    /**\n   * The ID and Version of the Training Set this Custom Model was trained from.\n   */\n    @observable\n    get trainingSetInfo(): { id: string, version: string } {\n        return { id: this.appMetadata.data['cme:trainingSet']['repo:assetId'], version: this.appMetadata.data['cme:trainingSet']['repo:version'] };\n    }\n\n    @observable\n    get samplePrompt() {\n        return this.appMetadata.data['cme:samplePrompt'];\n    }\n\n    @observable\n    get renditionUrl(): string {\n        return super.getRenditionURL(THUMBNAIL_SIZE);\n    }\n\n    @observable\n    get conceptId() {\n        return this._conceptId;\n    }\n\n    @observable\n    get trainingMode() {\n        return this._trainingMode;\n    }\n\n    get baseModelSuperclass(): string | undefined {\n        return this._baseModelSuperclass;\n    }\n\n    @observable\n    get deltaWeightsID(): string | undefined {\n        return this._deltaWeightsID;\n    }\n\n    @observable\n    get contentType(): string | undefined {\n        return this._contentType;\n    }\n\n    @observable\n    get compression(): string {\n        return this._compression;\n    }\n\n    @observable\n    get schemaVersion(): string {\n        return this._schemaVersion;\n    }\n\n\n    /* This is a heuristic.  It does not definitively give information about who is or isn't a generator for this custom model\n     * However, given the default way we assign permissions, it's correct until we start adding new features to custom models\n     * So this is what we're using for the sake of performance until we come up with something better.\n     * Used in the dashboard source to determine which models we should show.\n     */\n    /** @package -- for use in SAM.js only */\n    get hasDefaultGeneratorPermissions(): boolean {\n        return this.hasPermission(Permission.Read)\n            && !this.hasPermission(Permission.Write)\n            && !this.hasPermission(Permission.WriteComment);\n    }\n\n    /**\n     * Updates the Custom Model with the provided options.\n     *\n     * @param options CustomModelUpdateInfoMelville\n     * @throws {SAMErrorCode.UNSUPPORTED}\n     * @returns Promise<void>\n     */\n    public async update(options: CustomModelUpdateInfoMelville) {\n        const unsupportedKeys = Object.keys(options)\n            .filter(key => CUSTOM_MODEL_RESTRICTED_METADATA_KEYS.includes(key as any));\n\n        if (unsupportedKeys.length) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                `Update keys are unsupported: [${unsupportedKeys}]. Use CustomModel.patchAppMetadata`\n            );\n        }\n\n        const context = await this._core.getCustomModelContext();\n        await context.updateCustomModel(this.id, options);\n    }\n\n    /**\n     * For exceptions that CustomModel.update doesn't cover,\n     * this method can be used to update the application metadata directly.\n     *\n     * @param patches CustomModelAppMetadataPatch[]\n     * @throws {SAMErrorCode.UNSUPPORTED}\n     * @returns Promise<void>\n     */\n    public patchAppMetadata(patches: CustomModelAppMetadataPatch[]): Promise<void> {\n        const unsupportedPatches = patches.map(patch => patch.path)\n            .filter((path) =>\n                !CUSTOM_MODEL_RESTRICTED_METADATA_KEYS.includes(path.substring(1) as CustomModelRestrictedMetadataKey)\n            );\n\n        if (unsupportedPatches.length) {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                `Patch paths are unsupported: [${unsupportedPatches}]. Use \"CustomModel.update\"`,\n            );\n        }\n\n        return super.patchAppMetadata(patches);\n    }\n}\n\nexport const CustomModelUpdaterMelville = new ItemUpdater<\nCustomModel,\nPartial<CustomModelInfoMelville>\n>({\n    localItemType: CustomModel,\n    remoteIdProperty: 'repo:assetId',\n    propertyUpdater: new PropertyUpdater({\n        '_appMetadata._data': {\n            name: 'application_metadata',\n            format: 'object_subset',\n            set: (parsedSource: any, dest: any) => {\n                const asset = dest as AdobeAsset;\n                asset.appMetadata._mergeData(parsedSource);\n            }\n        },\n        '_displayName': { name: 'repo:name', format: { parse: trimRepoName, isEqual: isStrictEqual } },\n        '_conceptId': { name: 'firefly#ffmodel', format: { parse: (ffmodel) => ffmodel.conceptId, isEqual: isStrictEqual } },\n        '_contentType': { name: 'firefly#ffmodel', format: { parse: (ffmodel) => ffmodel.contentType, isEqual: isStrictEqual } },\n        '_trainingMode': { name: 'firefly#ffmodel', format: { parse: (ffmodel) => ffmodel.trainingMode, isEqual: isStrictEqual } },\n        '_baseModelSuperclass': { name: 'firefly#ffmodel', format: { parse: (ffmodel) => ffmodel.baseModelSuperclass, isEqual: isStrictEqual } },\n        '_deltaWeightsID': { name: 'firefly#ffmodel', format: { parse: (ffmodel) => ffmodel.deltaWeightsID, isEqual: isStrictEqual } },\n        '_compression': { name: 'firefly#ffmodel', format: { parse: (ffmodel) => ffmodel.compression, isEqual: isStrictEqual } },\n        '_permissions': { get: getCustomModelPermission, format: 'number' },\n        '_schemaVersion': { name: 'firefly#ffmodel', format: { parse: (ffmodel) => ffmodel.schemaVersion, isEqual: isStrictEqual } },\n        __links: { name: '_links', format: 'object' },\n        _name: 'repo:name',\n        _path: 'repo:path',\n        _created: { name: 'repo:createDate', format: 'date_as_number' },\n        _modified: { name: 'repo:modifyDate', format: 'date_as_number' },\n        _createdBy: 'repo:createdBy',\n        _version: 'version',\n        _etag: 'repo:etag',\n        _storageRegion: 'storage:region',\n        _size: { name: 'repo:size', format: 'number' },\n    }),\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type CustomModel from './CustomModel';\nimport { isCustomModel } from './CustomModel';\nimport type {\n    IImplicitAdobeAssetFilterBaseOptions\n} from '../assets/ImplicitAdobeAssetFilterBase';\nimport ImplicitAdobeAssetFilterBase from '../assets/ImplicitAdobeAssetFilterBase';\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type AdobeAsset from '../assets/AdobeAsset';\n\nexport interface IImplicitCustomModelFilterOptions extends IImplicitAdobeAssetFilterBaseOptions {\n    trainingSetId?: string,\n    generatorOnly?: boolean\n}\n\nexport default class ImplicitCustomModelFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<CustomModel> {\n    private readonly _trainingSetId?: string;\n    private readonly _generatorOnly?: boolean;\n\n    constructor(options: Partial<IImplicitCustomModelFilterOptions> = {}) {\n        const { trainingSetId, generatorOnly, ...superOptions } = options;\n        super(superOptions);\n        this._trainingSetId = trainingSetId;\n        this._generatorOnly = generatorOnly;\n    }\n\n    matches(item: AdobeAsset) {\n        if (!isCustomModel(item)) {\n            return false;\n        }\n\n        if (this._trainingSetId && this._trainingSetId !== item.trainingSetInfo.id) {\n            return false;\n        }\n\n        if (this._generatorOnly && !item.hasDefaultGeneratorPermissions) {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ItemPool from '../core/ItemPool';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { AdobeAsset, Library } from 'src';\nimport type {\n    CustomModelConfig,\n} from './CustomModelSource';\nimport type {\n    IItemLoader,\n    ILoadedPage,\n} from '../core/ItemLoader';\nimport type CustomModel from '../custom-models/CustomModel';\nimport { CustomModelUpdaterMelville } from '../custom-models/CustomModel';\nimport type { CustomModelInfoMelville } from '../interface/CustomModelModel';\n\nexport default class TrainingSetCustomModelLoader\nimplements IItemLoader<CustomModelConfig> {\n    constructor(\n        private _assetPool: ItemPool<CustomModel | AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private _libraryId: string\n    ) {}\n\n    async loadPage() {\n        return await this._loadPage();\n    }\n\n    private async _loadPage(): Promise<ILoadedPage<CustomModelConfig>> {\n        // Fetch the training set library to make sure we have the latest list of custom models\n        // and update the asset pool\n        // Note: Libraries listings from Melville are considered \"USS\" sources (with the current exception of a public libraries-only listing),\n        // and may have stale data. Which is why we use `createLoaderUpdateSession`, not `createLoaderMutationSession`.\n        const libraryContext = await this._core.getLibraryContext();\n        const trainingSetLibraryData = await libraryContext._libraryInterface.getLibraryData(this._libraryId);\n        const latency = this._core._environment.getValue('USS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n        const session = this._assetPool.createLoaderUpdateSession<Library>(mostRecentValidMutation);\n        libraryContext._libraryUpdater.updateRemoteItem(session, trainingSetLibraryData);\n        session.commit();\n\n        // Double check that we are dealing with a training set library\n        // If so, update the asset pool with the custom models\n        let items: CustomModel[] = [];\n        if (trainingSetLibraryData.roles.some(role => role.type === 'cm_training_set')) {\n            const customModels = trainingSetLibraryData.custom_models;\n            if (!customModels) {\n                return { items, total: 0 };\n            }\n\n            const cmSession = this._assetPool.createLoaderUpdateSession<CustomModel>(mostRecentValidMutation);\n\n            items = CustomModelUpdaterMelville.updateRemoteItems(cmSession, customModels as CustomModelInfoMelville[]);\n\n            cmSession.commit();\n        }\n\n        return {\n            items,\n            total: items.length\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { SAM } from '@ccx-public/component-types';\n\nimport type { AssetLinks, RepositoryMetadata } from '../interface/RepositoryModel';\nimport LibraryInterface from '../interface/LibraryInterface';\nimport { RelType } from '../interface/LinkUtils';\nimport type {\n    BookmarkData,\n    LibraryData,\n    LibraryRenditionGridData,\n    LibraryRole,\n    Ownership,\n    LibraryRenditionData,\n    LibraryManifestId,\n    PublicLibraryId,\n    ParentAssetId,\n    ResourceRef,\n    LibraryReferencedByProject\n} from '../interface/LibraryModel';\nimport AdobeAsset, { StorageAssigneeFormat } from '../assets/AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { memoize, observable } from '../core/decorators';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type { IItemUpdaterOptions } from '../core/ItemUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { IPropertyTypeMap } from '../core/PropertyUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport { LIBRARY_DATA_CHANGED, LibraryDataChangedEventInstance } from './LibraryDataChangedEvent';\nimport { RESTRICT_EDIT_CHANGED, RestrictEditChangedEventInstance } from './RestrictEditChangedEvent';\nimport type { IPerUserMetadata } from '../interface/AssetModel';\nimport { Permission, PERMISSION_ALL } from '../interface/AssetModel';\nimport { parseEffectivePermissions } from '../interface/AssetModel';\nimport { lazyLoaded, LazyLoadManager, LoadStatus } from '../core/decorators/LazyLoadManager';\nimport { RenditionTile } from '../interface/RenditionTile';\nimport { NotFound } from '../core/PropertyUpdater';\nimport ItemSource from '../core/ItemSource';\nimport type ItemPool from '../core/ItemPool';\nimport type CustomModel from '../custom-models/CustomModel';\nimport type { CustomModelTrainingConfiguration } from '../interface/CustomModelModel';\nimport type { CustomModelConfig, CustomModelSource } from '../custom-models/CustomModelSource';\nimport ImplicitCustomModelFilter from '../custom-models/ImplicitCustomModelFilter';\nimport TrainingSetCustomModelLoader from '../custom-models/TrainingSetCustomModelLoader';\nimport { isDeepEqual } from '../core/ObjectUtils';\nimport {\n    getLibraryDirectCollaboratorCount, getLibraryIsPublicLink,\n    getLibraryIsShared,\n    getLibraryIsSharedWithYouAsset, getLibraryShareFlagsAreDirty\n} from './LibraryCollaborationUtils';\nimport type LibraryContents from '../library-contents/models/LibraryContents';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\n\nexport type LibraryDataLoadState = 'NOT_LOADED' | 'LOADING' | 'LOADED';\n\ninterface ILibraryDataLoadInfo {\n    state: LibraryDataLoadState;\n    promise?: Promise<void>; // A promise that completes when resolve is called, meant for waiting for libraries to load\n    resolve?: () => void; // Call to resolve promise\n}\n\nexport function isLibrary(asset: AdobeAsset): asset is Library {\n    return asset.isLibrary;\n}\nexport default class Library extends AdobeAsset implements SAM.Library {\n    public isLibrary: boolean = true;\n\n    private _libraryInterface = new LibraryInterface(this._core);\n    private _libraryRoles?: LibraryRole[];\n    private _orgID?: string;\n    private _ownership?: Ownership;\n    private _libraryDataLoadInfo: ILibraryDataLoadInfo = {\n        state: 'NOT_LOADED'\n    };\n    private _bookmark?: BookmarkData;\n    private _isEditingRestricted: boolean | undefined;\n    private _elementsCount?: number | undefined;\n    private _customModelInfo?: CustomModelTrainingConfiguration;\n    private _contents?: WeakRef<LibraryContents>;\n    private _displayName?: string;\n    private _documentType?: string;\n    private _legacyLibraryId?: LibraryManifestId | PublicLibraryId;\n    private _customThumbnail?: RenditionTile;\n\n\n    /**\n     * See Library.duplicate().\n     *\n     * _parentAssetId is used only as a fallback,\n     * when _ancestorIDs has not yet been set.\n     */\n    private _parentAssetId?: ParentAssetId;\n\n    /**\n     * A set of project IDs that this library is referenced by.\n     * This set is lazily updated as requests are made to Melville to fetch referenced libraries associated with a given project.\n     * See {@link Library.isReferencedByProject} for a way to check if this library is referenced by a project.\n     */\n    private _referencedByProjectIDs: Set<string> | undefined;\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _renditionGridTiles?: RenditionTile[];\n    /**\n     * @package -- for use in SAM.js only\n     */\n    _renditionGridRaw?: LibraryRenditionGridData;\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        id: string,\n        metadata?: {\n            links?: AssetLinks;\n        }\n    ) {\n        super(_core, id, metadata);\n        this._type = 'application/vnd.adobe.library+dcx';\n\n        // Overridden property.\n        // True to start with. If we have the metadata, we will update this.\n        this._needsRepoMetadata = true;\n\n        LazyLoadManager.manageLazyLoading(this, [ {\n            event: RestrictEditChangedEventInstance,\n            fetchData: this._refreshEditingRestricted\n        } ]);\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * Returns the LibraryInterface for the library.\n     */\n    _getLibraryInterface(): LibraryInterface {\n        return this._libraryInterface;\n    }\n\n    /**\n     * Returns the LibraryContents API for the library.\n     * LibraryContents controls and exposes the state of the library's contents, including elements and groups.\n     * The LibraryContents instance is stored using WeakRef to avoid leaking.\n     * Please note that the client is responsible for holding onto this reference if they do not want the contents to be garbage collected,\n     * and make sure to remove the reference when it is no longer needed, as we only keep the reference alive for the 10 minute default.\n     * @returns LibraryContents\n     */\n    @keepAlive\n    async getContents(): Promise<LibraryContents> {\n        if (!this._contents || !this._contents.deref()) { // deref() may return undefined if the object has been garbage collected\n            // Load and initialize CC Libraries API, if it isn't already\n            const libraryContext = await this._core.getLibraryContext();\n            const CCLibraries = await libraryContext._getLibrariesModule();\n            // Create a LibraryContents instance from the Library asset (this is\n            // a subset of the existing Library interface in the CC Libraries API)\n            this._contents = new WeakRef(CCLibraries.getLibraryContents(this));\n        }\n\n        return this._contents.deref() as LibraryContents; // typescript doesn't recognize we already did an undefined check, so we have to typecast\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * Use from inside library-contents code, where we know libraryContext and CCLibraries are already defined.\n     * Note: This returns a hard reference, not a weak reference.\n     */\n    @keepAlive\n    // TODO Later: Have a no-load version of this for use once load/change notifications set up.\n    _getContentsSync(): LibraryContents {\n        // Contents should already be defined if calling this from the CCLibraries Module, but just in case, we can get it synchronously here.\n        if (!this._contents || !this._contents.deref()) {\n            const libraryContext = this._core._getLibraryContext();\n            // Will throw error if CCLibraries is not defined, which is why this should only be accessed from inside /library-contents\n            const CCLibraries = libraryContext!._getLibrariesModule_NoLoad();\n            this._contents = new WeakRef(CCLibraries!.getLibraryContents(this));\n        }\n        return this._contents.deref() as LibraryContents;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    // Check if melville data is currently fully loaded\n    get _libraryLoaded(): boolean {\n        return this._libraryDataLoadInfo.state === 'LOADED';\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * Set a promise to resolve when libraries are loaded.  Returns a resolve function that needs to be called after\n     * the library is loaded, or undefined if something else is already calling for melville data.\n     */\n    _setLibraryLoadState(state: LibraryDataLoadState): void  {\n        const { state: priorState } = this._libraryDataLoadInfo;\n        if (state === priorState) { return; }\n\n        this._libraryDataLoadInfo.state = state;\n\n        if (state === 'LOADED') {\n            if (this._libraryDataLoadInfo.resolve) {\n                this._libraryDataLoadInfo.resolve();\n            }\n        } else if (state === 'LOADING') {\n            let resolve;\n            this._libraryDataLoadInfo.promise = new Promise(r => { resolve = r; });\n            this._libraryDataLoadInfo.resolve = resolve;\n        } else if (state === 'NOT_LOADED') {\n            // Transitioning to NOT_LOADED means the data still needs to be loaded. Notify listeners\n            // in order to trigger lazy-loading. Unblock anything waiting on the Promise.\n            // Use this also for when the data is stale and needs reloading.\n            if (this._libraryDataLoadInfo.resolve) {\n                this._libraryDataLoadInfo.resolve();\n            }\n            this.emit(LIBRARY_DATA_CHANGED);\n        }\n    }\n\n    /**\n     * Starts loading Melville data for a single Library, if it hasn't already been loaded, or waits\n     * for in-flight load to complete.\n     *\n     * @parameter canRetry {boolean} (optional) For cases in Library that need to ensure Library\n     *         data loads, but it may have failed from a listing, it can try one extra time.\n     *\n     * @package -- for use in SAM.js only\n     */\n    async _waitForLibraryLoad(canRetry: boolean = false): Promise<void> {\n        this._populateLibraryDataIfNotLoading();\n        await this._libraryDataLoadInfo.promise;\n        if (canRetry && !this._libraryLoaded) {\n            await this._waitForLibraryLoad(false);\n        }\n        return this._libraryDataLoadInfo.promise;\n    }\n\n    async _load({\n        repoMetadata,\n        appMetadata,\n        effectivePermission,\n        perUserMetadata,\n        requireLibraryDataFetch // e.g. newly created libraries need to load melville data to be filtered properly\n    }: {\n        repoMetadata?: RepositoryMetadata;\n        appMetadata?: any;\n        effectivePermission?: Permission;\n        perUserMetadata?: IPerUserMetadata;\n        requireLibraryDataFetch?: boolean;\n    } = {}): Promise<void> {\n        // When an ONS notification comes in, load the repoMetadata\n        await super._load({ repoMetadata, appMetadata, effectivePermission, perUserMetadata });\n\n        /* We need the melville reload to happen in all cases because the LibraryFilter won't match libraries without the melville data\n        * There's a pathological case where:\n        * - UI is currently showing libraries with a filter\n        * - A library is created externally\n        * - We receive a notification here to add the library\n        * - We add the library, but it has no melville data\n        * - The library doesn't pass the LibraryFilter without melville data\n        * - We don't show the library to the UI\n        * - The UI never requests any data that would trigger the lazy load, because it doesn't see the library\n        * - The library is never populated with melville data and therefore is never shown\n        */\n\n        this._setLibraryLoadState('NOT_LOADED');\n        if (requireLibraryDataFetch) {\n            this._populateLibraryDataIfNotLoading();\n            await this._waitForLibraryLoad();\n        }\n    }\n\n    @observable(LibraryDataChangedEventInstance)\n    get elementsCount(): number | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._elementsCount;\n    }\n\n    @observable(LibraryDataChangedEventInstance)\n    get displayName(): string | undefined {\n        this._populateLibraryDataIfNotLoading();\n        // Melville will always have the correct name, whereas the RAPI .name will not have the name for libraries in sync groups.\n        return this._displayName;\n    }\n\n    @observable(LibraryDataChangedEventInstance)\n    get documentType(): string | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._documentType;\n    }\n\n    /**\n     * OrgID the library belongs to\n     */\n    @observable(LibraryDataChangedEventInstance)\n    get orgID(): string | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._orgID;\n    }\n\n    /**\n     * AssetID of Published Brand Artifact, if it exists\n     */\n    @observable\n    get publishedTo(): string {\n        return this.appMetadata?.data?.['brand:publishedTo']?.['repo:assetId'];\n    }\n\n    /**\n     * AssetID of the Source Brand, if the current Brand is a Published Artifact\n     */\n    @observable\n    get publishedFrom(): string {\n        return this.appMetadata?.data?.['brand:publishedFrom']?.['repo:assetId'];\n    }\n\n    /**\n     * Last Published Version of the current Brand\n     */\n    @observable\n    get lastPublishedVersion(): string {\n        return this.appMetadata?.data?.['brand:lastPublishedVersion'];\n    }\n\n    /**\n     * AssetID of the extraction source pdfs\n     */\n    @observable\n    get extractedFrom(): string[] {\n        return this.appMetadata?.data?.['brand:extractedFrom']?.map((asset: ResourceRef) => asset['repo:assetId']);\n    }\n\n    @observable(LibraryDataChangedEventInstance)\n    get customThumbnail(): RenditionTile | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._customThumbnail;\n    }\n\n    /**\n     * Returns the Library's current roles.\n     *\n     */\n    @observable(LibraryDataChangedEventInstance)\n    public get roles(): LibraryRole[] | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._libraryRoles;\n    }\n\n    @observable(LibraryDataChangedEventInstance, '_customModelInfo')\n    get customModelInfo() {\n        this._populateLibraryDataIfNotLoading();\n        return this._customModelInfo;\n    }\n\n    /**\n     * Returns the Library's element renditions in a single array.\n     * The main tile is at index 0.\n     */\n    @observable(LibraryDataChangedEventInstance)\n    public get renditionGrid(): RenditionTile[] | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._renditionGridTiles;\n    }\n\n    /**\n     * Makes a service request to update the Library's metadata, then updates local Library model.\n     */\n    async setRoles(roles: LibraryRole[] | LibraryRole) {\n        const newRoles = { roles: Array.isArray(roles) ? roles : [ roles ] };\n        await this._libraryInterface.updateMetadata(this.id, newRoles);\n        this._setLibraryLoadState('NOT_LOADED');\n        await this._populateLibraryDataIfNotLoading();\n    }\n\n    /**\n     * Return whether the library is bookmarked (aka followed) by the user.\n     * Will return undefined if data has not been loaded yet.\n    */\n    // Blocked by CCXB-20127: Bookmark data may currently be out of date due to a caching issue in Melville.\n    // CCXC-20748: If we eventually support loading unbookmarked public libraries, bookmark data will already\n    // be present in the library data when unbookmarked. Thus, we will need to separately load the user's bookmarks to verify isBookmarked.\n    @observable(LibraryDataChangedEventInstance)\n    public get isBookmarked(): boolean | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._libraryLoaded ? !!this._bookmark : undefined;\n    }\n\n    @observable(LibraryDataChangedEventInstance)\n    // TODO: Not yet part of public interface, need to follow up to see if _isPublicLink can be set instead.\n    // Warning: `this.isPublicLink` (from USSMetadata) is false for public libraries.\n    get _isPublic(): boolean | undefined {\n        // Warning: `ownership` is 'public' for a public library in most melville responses,\n        // such as to the 'public' end points, or GET /libraries/<manifestId>.\n        // However, GET /libraries/<assetId> will return 'incoming' for a public library,\n        // and there's no way to tell it is public from the response\n        // -- even the `id` is no longer the public library id but a new id.\n        // But as long as we don't fetch public libraries that way, this definition is fine.\n        // Warning2: `isPublicLink` from USS loaders is false for public libraries.\n        return this._libraryLoaded ? this._ownership === 'public' : undefined;\n    } // We decided that ownership being incoming is the more important data case. And in that case, check isPublicLink to know if it's ALSO shared publicly.\n\n    @observable(LibraryDataChangedEventInstance)\n    get ownership(): Ownership | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._ownership;\n    }\n\n    /**\n     * @experimental API subject to move in the future\n     */\n    @memoize\n    async getCustomModels(): Promise<CustomModelSource> {\n        if (!this.roles?.filter(role => role.type === 'cm_training_set')) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Can only get custom models from training set libraries');\n        }\n        const assetPool = this._core._getAssetPool() as ItemPool<AdobeAsset | CustomModel>;\n\n        return new ItemSource<CustomModelConfig>(\n            assetPool as ItemPool<CustomModel>,\n            [\n                new TrainingSetCustomModelLoader(\n                    assetPool,\n                    this._core,\n                    this.id\n                )\n            ],\n            new ImplicitCustomModelFilter({ trainingSetId: this.id })\n        );\n    }\n\n    /**\n     * @deprecated -- will be removed on or after 2025-06-01 but not before durable links are available and used by all clients.\n     * And not before its use is removed from the CCLibraries module internally.\n     */\n    // This legacy id is usually the dcx manifest id, but on public libraries, it will be a unique type of public library id.\n    // With durable links enabled, this will be the manifest id even for public libraries.\n    @observable(LibraryDataChangedEventInstance)\n    public get libraryManifestId(): string | undefined {\n        this._populateLibraryDataIfNotLoading();\n        return this._legacyLibraryId;\n    }\n\n    // move calls moveLibrary without specifying restrictEdit, thus getting the default of \"team_view\"\n    async move(destFolder: AdobeAsset): Promise<void> {\n        return this.moveLibrary(destFolder);\n    }\n\n    /**\n     * Duplicate this Asset within the same folder.\n     *\n     * @param destName -- (not available on SAM.cpp) -- preferred name for the duplicate\n     */\n    async duplicate(destName?: string): Promise<this> {\n        /* AdobeAsset.duplicate() is uses this._ancestorIDs!.slice(-1)[0]\n         * to get the parent's asset id. _ancestorIDs is set with the\n         * USSMetadata { path: string[] } or the RepositoryMetadata\n         * { 'repo:ancestors': string[] }, and for other asset types\n         * it's always been assigned before duplicate() is called\n         * ( hence, _ancestorIDs! ).\n         *\n         * A Library updated with LibraryData sets _parentAssetId from\n         * { parent_assetId?: ParentAssetId }, but it doesn't touch\n         * _ancestorIDs.\n         *\n         * NOTE: setting _ancestorIDs = [ parent_assetId ] from LibraryData\n         * would be a mistake because existing code assumes a non-empty\n         * _ancestorIDs contains the entire path, not just the parent.\n         */\n\n        // prefer the original duplicate() if _ancestorIDs is non-empty\n        if (this.ancestorIDs && this.ancestorIDs.length > 0) {\n            return super.duplicate(destName);\n        }\n\n        // fallback on _parentAssetId if it's been set\n        if (this._parentAssetId) {\n            const assetContext = await this._core.getAssetContext();\n            const parentAsset = await assetContext.getAssetWithCloudID(this._parentAssetId);\n            return await this._copy(parentAsset, destName) as this;\n        }\n\n        return Promise.reject(SAMError.create(SAMErrorCode.BAD_REQUEST, 'Library.duplicate() requires at least one of { this.ancestorIDs, this._parentAssetId } to be defined.'));\n    }\n\n    /**\n     * Move a Library\n     * Reqired properties\n     * @param destFolder - The folder to move the library to\n     * Optional properties\n     * @param restrictEdit {boolean} (optional) If true, will tell Melville to move the library with TEAM_VIEW access.\n     *      If false, will tell Melville to move with TEAM_EDIT access. If undefined, it is up to Melville to decide.\n     */\n    async moveLibrary(destFolder: AdobeAsset, restrictEdit?: boolean): Promise<void> {\n        const libraryData = await this._libraryInterface.moveLibrary(this.cloudID, destFolder.cloudID, restrictEdit);\n        const assetContext = await this._core.getAssetContext();\n        const session = assetContext._assetPool.createUpdateSession<Library>('move library');\n        const libraryContext = await this._core.getLibraryContext();\n\n        if (libraryData.library_urn !== this.id) {\n            // Melville currently does a \"fake\" move using copy and delete.\n            // Melville team hopes to eventually turn this into a real move.\n            // For now we will just discard the old library and rely on ONS to create a new one in our pool.\n            session.queueDiscardedItem(this);\n        } else {\n            // If the cloudID didn't change, then it needs to be updated to reflect its new location\n            libraryContext._libraryUpdater.updateLocalItem(session, this, libraryData);\n            this._setLibraryLoadState('LOADED');\n        }\n        session.commit();\n    }\n\n    async rename(newName: string) {\n        await this._libraryInterface.updateMetadata(this.id, { name: newName });\n        this._setLibraryLoadState('NOT_LOADED');\n    }\n\n    /**\n     * Discard the library through melville, which also cleans up bookmarks.\n     * This changes its repo:state to DISCARDED, but it can later be restored or permanently deleted.\n     */\n    async discard(): Promise<void> {\n        if (this.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Asset is already discarded');\n        }\n\n        await this._libraryInterface.discardLibrary(this.cloudID);\n\n        const libraryContext = await this._core.getLibraryContext();\n        const session = libraryContext._assetPool.createUpdateSession<Library>('discard library'); // tracks changes to the asset\n\n        // Update the local item with values from the remote item\n        const assetContext = await this._core.getAssetContext();\n        assetContext._adobeAssetUpdater.updateLocalItem(session, this, { 'repo:state': 'DISCARDED' });\n        session.commit(); // fire notifications for tracked changes\n    }\n\n    async permanentlyDelete(): Promise<void> {\n        await this._libraryInterface.permanentlyDeleteLibrary(this.cloudID);\n        const libraryContext = await this._core.getLibraryContext();\n        const session = libraryContext._assetPool.createUpdateSession<Library>('permanently delete library'); // tracks changes to the asset\n        session.queueDiscardedItem(this);\n        session.commit(); // fire notifications for tracked changes\n    }\n\n    async restore(): Promise<void> {\n        if (!this.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Cannot restore an asset that is not discarded');\n        }\n\n        const assetContext = await this._core.getAssetContext();\n        await this._libraryInterface.restoreLibrary(this.cloudID);\n        const assetPool = this._core._getAssetPool();\n        const session = assetPool.createUpdateSession<Library>('restore library');\n        assetContext._adobeAssetUpdater.updateLocalItem(session, this, { 'repo:state': 'ACTIVE' });\n        session.commit();\n    }\n\n    /*\n     * Override AdobeAsset._copy() so that both AdobeAsset.copy() and AdobeAsset.duplicate()\n     * get handled by Melville. Melville handles rename on conflict.\n     */\n    protected async _copy(destFolder: AdobeAsset, destName?: string): Promise<Library> {\n        return this.copyLibrary(destFolder, destName);\n    }\n\n    /**\n     * Copy a Library\n     * Optional properties\n     * @param destFolder - If destFolder is undefined then the library will be copied in the User's personal library\n     *     folder\n     * @param destName - If destName is undefined then the current library name will be preserved\n     * @param restrictEdit (optional) If true, copies the library with TEAM_VIEW access. If false, copies the library\n     *      with TEAM_EDIT access. If undefined, Melville will determine the access.\n     * @returns - The new copied Library\n     */\n    async copyLibrary(destFolder?: AdobeAsset, destName?: string, restrictEdit?: boolean): Promise<Library> {\n        // When (!destName), we omit { name: destName } from the request body,\n        // and when { name:destName } has been omitted from the request body,\n        // Melville uses sourceComposite.getCompositeName() as the destination name.\n\n        // Melville will fix any name conflicts, unlike R-API\n        const libraryData = await this._libraryInterface.copyLibrary(this.cloudID, destName, destFolder?.cloudID, restrictEdit);\n        const assetPool = this._core._getAssetPool();\n        const session = assetPool.createUpdateSession<Library>('copy library');\n        const libraryContext = await this._core.getLibraryContext();\n        const library = libraryContext._libraryUpdater.updateRemoteItem(session, libraryData);\n        library._setLibraryLoadState('LOADED');\n        session.commit();\n\n        return library;\n    }\n\n    /**\n     * Makes a service request to bookmark the library, then updates local Library model.\n     * Applies to project (aka team) and shared private libraries. Public libraries not yet supported.\n     */\n    async bookmark(): Promise<void> {\n        await this._waitForLibraryLoad(true);\n        if (this.isBookmarked) { return; }\n\n        let bookmarkData: Partial<BookmarkData> = {};\n        if (this._isPublic) {\n            return Promise.reject('Bookmarking public libraries not implemented.');\n        } else {\n            bookmarkData = {\n                id: this._legacyLibraryId,\n                type: 'collab',\n                urn: this.cloudID\n            };\n        }\n\n        const { bookmarks } = await this._libraryInterface.bookmarkLibraries([ bookmarkData ]);\n        const bookmark = bookmarks.find(bookmark => bookmark.id === this._legacyLibraryId);\n        const libraryContext = await this._core.getLibraryContext();\n        const session = libraryContext._assetPool.createUpdateSession<Library>('bookmark library');\n        libraryContext._libraryUpdater.updateLocalItem(session, this,  { bookmark });\n        session.commit();\n    }\n\n    /**\n     * Makes a service request to remove a bookmark from the library, then updates local Library model.\n     */\n    async unbookmark(): Promise<void> {\n        await this._waitForLibraryLoad(true);\n\n        const bookmarkId = this._bookmark?.id;\n        if (!bookmarkId) { return; }\n\n        await this._libraryInterface.unbookmarkLibrary(bookmarkId); // 404 means it's already unbookmarked\n        const libraryContext = await this._core.getLibraryContext();\n        const session = libraryContext._assetPool.createUpdateSession<Library>('unbookmark library');\n        libraryContext._libraryUpdater.updateLocalItem(session, this,  { bookmark: undefined });\n        session.commit();\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    // calls out to melville to get the library data\n    async _populateLibraryDataIfNotLoading(): Promise<void> {\n        if (this._libraryDataLoadInfo.state === 'NOT_LOADED') {\n            this._setLibraryLoadState('LOADING');\n            const libraryContext = await this._core.getLibraryContext();\n            const libraryData = await this._libraryInterface.getLibraryData(this.id, { isDiscarded: this.isDiscarded });\n            const assetPool = this._core._getAssetPool();\n            const session = assetPool.createUpdateSession<Library>();\n            libraryContext._libraryUpdater.updateLocalItem(session, this, libraryData);\n            this._setLibraryLoadState('LOADED');\n            session.commit();\n        }\n    }\n\n    /**\n     * Returns `true` if the Library has inherited editing/sharing rights blocked, `false` if it is not. Direct\n     * collaborators and USM users are not affected.\n     *\n     * Lazy-loaded: the property will be `undefined` on initial access, and will contain the old value when it is being\n     * updated. Use Mobx to monitor for changes, or subscribe to 'restrict_edit_changed' event.\n     */\n    @lazyLoaded(RestrictEditChangedEventInstance, '_isEditingRestricted')\n    get isEditingRestricted(): boolean | undefined {\n        return this._isEditingRestricted;\n    }\n\n    get _isCCIProjectLibrary(): boolean {\n        return (this._ownership && this._ownership === 'team' && (this.storageAssignee.type === 'user') && this.repoPath?.startsWith('/projects/')) ?? false;\n    }\n\n    /**\n     * Sets or adds the ACL entries to block inherited editing/sharing rights to this Library. Clients MUST add the\n     * current user as a direct editor collaborator before calling or else no one can remove the restriction except\n     * admins.\n     *\n     * @param isRestricted {boolean} true to restrict inherited editing/sharing permissions, false to allow inherited\n     *      editing/sharing permissions.\n     * @param addCurrentUserAsEditor {boolean} When setting isRestricted to true, also adds the current user\n     *      to have direct edit/sharing permissions. This is so Share Sheet can detect if the user is already added\n     *      as an address book contact, in order to avoid duplicate ACEs for the same user.\n     */\n    async setEditingRestricted(restrictEdit: true, addCurrentUserAsEditor: boolean): Promise<void>;\n    // eslint-disable-next-line no-dupe-class-members\n    async setEditingRestricted(restrictEdit: false): Promise<void>;\n    // eslint-disable-next-line no-dupe-class-members\n    async setEditingRestricted(restrictEdit: boolean, addCurrentUserAsEditor?: boolean): Promise<void> {\n        await this._ensureLink(RelType.AC_POLICY);\n        const assetInterface = await this._getAssetInterface();\n        await assetInterface.setEditingInheritanceRestricted(restrictEdit, addCurrentUserAsEditor);\n        this._isEditingRestricted = restrictEdit;\n        LazyLoadManager.updatedExternally(this, RESTRICT_EDIT_CHANGED);\n    }\n\n    private async _refreshEditingRestricted(): Promise<void> {\n        await this._ensureLink(RelType.AC_POLICY);\n        const assetInterface = await this._getAssetInterface();\n        this._isEditingRestricted = await assetInterface.getEditingInheritanceRestricted();\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    async _reloadPermissions(): Promise<void> {\n        // When policy change is detected, mark restrictEdit data stale. Meanwhile, leave the last known state of\n        // _isEditingRestricted unchanged so it doesn't cause the UI to flash when the toggle is being changed.\n        LazyLoadManager.setLoadStatus(this, RESTRICT_EDIT_CHANGED, LoadStatus.NotLoaded);\n        return super._reloadPermissions();\n    }\n\n    /*  Internal data accessors are made public to prevent lazy loading, but are intended for use in SAM.js only. */\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    get _roles_NoLazyLoad(): LibraryRole[] | undefined {\n        return this._libraryRoles;\n    }\n\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    get _ownership_NoLazyLoad(): Ownership | undefined {\n        return this._ownership;\n    }\n\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    get _isBookmarked_NoLazyLoad(): boolean {\n        return !!this._bookmark;\n    }\n\n    /**\n     * @package -- for use in SAM.js\n     */\n    get _displayName_NoLazyLoad(): string | undefined {\n        return this._displayName;\n    }\n\n    /**\n     * @package -- for use in SAM.js\n     */\n    get _legacyLibraryId_NoLazyLoad(): LibraryManifestId | PublicLibraryId | undefined {\n        return this._legacyLibraryId;\n    }\n\n    /**\n     * Checks if this library is referenced by the project of the given projectId.\n     * @warning This method is not guaranteed to be up-to-date. It relies on library list data returned from Melville with project references included.\n     *\n     * @param projectId - The ID of the project to check.\n     * @returns undefined if reference data for this library has never been fetched, true if the library is referenced by the project, false otherwise.\n     * @see {@link Project.libraryReferencesSource} to fetch a list of libraries referenced by a project.\n     */\n    isReferencedByProject(projectId: string): boolean | undefined {\n        return this._referencedByProjectIDs?.has(projectId);\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * Used internally to update the _referencedByProjectIDs set.\n     * when isReference is true the projectId is added to the set, otherwise it is removed.\n     * @param projectId - The ID of the project to update.\n     * @param isReference - Whether the library is referenced by the project.\n     */\n    _updateReferencedByProjectIDs(projectId: string, isReference?: boolean) {\n        this._referencedByProjectIDs ??= new Set();\n        if (isReference) {\n            this._referencedByProjectIDs.add(projectId);\n        } else {\n            this._referencedByProjectIDs.delete(projectId);\n        }\n    }\n}\n\nfunction updateRenditionGrid(source: LibraryRenditionGridData, library: Library) {\n\n    // The rendition grid data from Melville is an object with a main tile and an array of tiles.\n    // The local representation of the rendition grid is an object with just one array of tiles, and we\n    // want the main tile from Melville to be the first tile in the local rendition grid tiles array.\n    // Melville currently limits the maximum number of tiles in the rendition grid to four tiles, although\n    // this implementation will support any number of tiles in a rendition grid should that change.\n    // The order of the tiles in the rendition grid is determined by Melville, so any tile reording as\n    // a result of an update will be handled here.\n\n    let destTiles = library._renditionGridTiles ??= [];\n\n    // Combine the main tile and the tiles array into one source array, ensuring that the main tile is first, and that\n    // no falsy tiles are included. The filter function is also used to narrow the tile type to LibraryRenditionData.\n    const sourceTiles: LibraryRenditionData[] = [ source.main, ...(source.tiles ?? []) ].filter((tile): tile is LibraryRenditionData => !!tile);\n\n    // Update existing tiles and create new tiles if they don't exist.\n    sourceTiles.forEach((sourceTile, index) => {\n        const destTile = destTiles.find(t => t.elementId === sourceTile.elementId);\n        if (destTile) {\n            destTile._index = index;\n            if (sourceTile.type === 'href') {\n                // Note: assumes `type` never changes.\n                destTile._renditionUrl = sourceTile.rendition;\n            } else {\n                destTile._renditionData = sourceTile.rendition;\n            }\n        } else {\n            destTiles.push(new RenditionTile(sourceTile, index, library));\n        }\n    });\n\n    // Remove all deleted tiles (note: `filter` creates a new array instance).\n    destTiles = destTiles.filter(destTile => {\n        if (sourceTiles.find(sourceTile => sourceTile.elementId === destTile.elementId)) {\n            return true;\n        }\n        destTile._releaseRenditions();\n        return false;\n    });\n\n    // Re-sort by index that was assigned from sourceTiles in case the order changed.\n    destTiles.sort((a, b) => a._index - b._index);\n    library._renditionGridTiles = destTiles;\n}\n\nfunction getLibraryPermission(value: Partial<LibraryData>): Permission | typeof NotFound {\n    if (value.asset_acl !== undefined) {\n        return parseEffectivePermissions(value.asset_acl);\n    }\n\n    // If asset_acl is not present then try to deduce permissions according to the ownership.\n    if (value.ownership === 'public') {\n        return (Permission.Read | Permission.Ack | Permission.ReadAppMetadata);\n    } else if (value.ownership === 'private') {\n        return PERMISSION_ALL;\n    }\n\n    // If asset_acl is not present and we tried assigning permissions based on ownership, but weren't successful,\n    // then do not change the current permissions.\n    return NotFound;\n}\n\n// These are properties specific to melville that are always safe to update as they will not overwrite RAPI data.\n// These properties should match LibrarySpecificData.\nconst safePropertyUpdaterTypes: IPropertyTypeMap = {\n    '_bookmark': { name: 'bookmark', format: 'object' },\n    '_libraryRoles': { name: 'roles', format: 'object',  isArray: true },\n    '_orgID': { name: 'org_id', format: 'string' },\n    '_ownership': 'ownership',\n    '_legacyLibraryId': 'id',\n    // \"version\" is soon to be deprecated in favor of schemaVersion, check for both and expose as schemaVersion\n    '_customModelInfo': { name: 'firefly#cme', format: { parse: ffmodel => {\n        const obj = { ...ffmodel, schemaVersion: (ffmodel.version ? ffmodel.version : ffmodel.schemaVersion) };\n        delete obj.version;\n        return obj;\n    }, isEqual: isDeepEqual } },\n    '_renditionGridRaw': {\n        name: 'rendition_grid',\n        format: 'object',\n        set: (parsedSource: LibraryRenditionGridData, dest: any) => {\n            const library = dest as Library;\n            updateRenditionGrid(parsedSource, library);\n            library._renditionGridRaw = parsedSource;\n        }\n    },\n    '_displayName': 'name', // May differ from AdobeAsset.name for libraries in sync groups\n    '_elementsCount': { name: 'elements_count', format: 'number' },\n    '_parentAssetId': { name: 'parent_assetId', format: 'string' },\n    '_documentType': { name: 'document_type', format: 'string' },\n    '_referencedByProject': { name: 'referenced_by_project', format: 'object',\n        set: (parsedSource: LibraryReferencedByProject, dest: any) => {\n            const library = dest as Library;\n            library._updateReferencedByProjectIDs(parsedSource.projectId, parsedSource.reference);\n        }\n    },\n    '_customThumbnail': { name: 'thumbnail', format: 'object', set: (parsedSource: LibraryRenditionData, dest: any) => {\n        dest._customThumbnail = new RenditionTile(parsedSource, -1, dest as Library);\n    } },\n};\n\n// These melville properties will overwrite RAPI data. This is not always safe to do.\n// Melville libraries listings coming from USS may have stale data, but when we fetch a specific library, the data will be up-to-date.\n// Know which melville call you are making (and what it is doing under the hood) to know if the data may be stale,\n// in which which case you should only pass LibrarySpecificData to the PropertyUpdater.\n// Note that safePropertyUpdaterTypes and rapiOverridesPropertyUpdaterTypes should be mutually exclusive.\nconst rapiOverridesPropertyUpdaterTypes: IPropertyTypeMap = {\n    '_etag': 'manifest_etag',\n    '_repositoryID': 'repo:repositoryId',\n    '_path': 'storage_path',\n    '_version': 'version',\n    '_created': { name: 'created_date', format: 'date_as_number' },\n    '_modified': { name: 'modified_date', format: 'date_as_number' },\n    '_discarded': { name: 'archived_date', format: 'date_as_number' },\n    '_createdBy': 'created_by',\n    '_modifiedBy': 'modified_by',\n    '_discardedBy': 'archived_by',\n    '_appMetadata._data': {\n        name: 'application_metadata',\n        // Use object_subset format to avoid unnecessary change events. E.g., if _appMetadata.data is\n        // `{ 'shell:visibility': 'hiddenSelf', foo: 32 }` and the listing contains\n        // `{ 'shell:visibility': 'hiddenSelf' }` then the _mergeData will cause no change, but using format\n        // 'object', isEqual() will see source and dest aren't equal and thus assume that a change did occur.\n        format: 'object_subset',\n        // Only update the appMetadata fields that are available from this data source\n        set: (parsedSource, dest) => {\n            const asset = dest as AdobeAsset;\n            asset.appMetadata._mergeData(parsedSource);\n        }\n    },\n    '_storageAssignee': { name: 'storage_assignee', format: StorageAssigneeFormat },\n    '_size': { name: 'storage_used', format: 'number' },\n    '_permissions': { get: getLibraryPermission, format: 'number' },\n\n    // The following block of properties are inherited from class ShareableItem.\n    // When a Melville request includes selector collaboration, then the LibraryData\n    // will include the optional member collaboration, and all of these will be set,\n    // which avoids ShareableItem lazy loading the same information from the Invitation\n    // Service. When collaboration is absent, none of them will be set by LibraryUpdater,\n    // so ShareableItem will lazy load them on demand.\n    '_isSharedWithYouAsset': { get: getLibraryIsSharedWithYouAsset, format: 'boolean' },\n    '_isShared': { get: getLibraryIsShared, format: 'boolean' },\n    '_directCollaboratorCount': { get: getLibraryDirectCollaboratorCount, format: 'number' },\n    '_isPublicLink': { get: getLibraryIsPublicLink, format: 'boolean' },\n    '_shareFlagsAreDirty': { get: getLibraryShareFlagsAreDirty, format: 'boolean' },\n\n    // TODO [SHARED-2169] Fill in other properties as needed, for example:\n    // '_storageRegion': { name: 'region', get: getUSSStorageRegion, format: 'string' }, // getUSSStorageRegion will uppercase 'va6c2' for consistency. are the rest of the values matching USS?\n    // '__links': { name: '_links', format: 'object' },\n};\nconst propertyUpdaterTypes: IPropertyTypeMap = { ...safePropertyUpdaterTypes, ...rapiOverridesPropertyUpdaterTypes };\n\nconst libraryItemUpdaterOptions: IItemUpdaterOptions<Library, Partial<LibraryData>> = {\n    localItemType: Library,\n    remoteIdProperty: 'library_urn',\n    // Any changes to these properties from the update will trigger watchers of LIBRARY_DATA_CHANGED.\n    // Other properties updated will trigger the  default 'change' event (which will affect observable Asset properties).\n    changeEventMap: new Map([\n        [ '_libraryRoles', LibraryDataChangedEventInstance ],\n        [ '_displayName', LibraryDataChangedEventInstance ],\n        [ '_legacyLibraryId', LibraryDataChangedEventInstance ],\n        [ '_bookmark', LibraryDataChangedEventInstance ],\n        [ '_ownership', LibraryDataChangedEventInstance ],\n        [ '_renditionGridRaw', LibraryDataChangedEventInstance ],\n        [ '_elementsCount', LibraryDataChangedEventInstance ],\n        [ '_documentType', LibraryDataChangedEventInstance ],\n    ]),\n    // Mapping LibraryData to Library\n    propertyUpdater: new PropertyUpdater(propertyUpdaterTypes)\n};\n\n// why is this uppercase by convention? They are instances and should be lowercase.\nexport const LibraryUpdater = new ItemUpdater<Library, Partial<LibraryData>>(libraryItemUpdaterOptions);\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { LibraryData } from '../interface/LibraryModel';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport { NotFound } from '../core/PropertyUpdater';\n\n/**\n * These utility functions are for the LibraryUpdater.\n *\n * class ShareableItem uses _shareFlagsAreDirty to decide when\n * to lazy load all of {  _isShared, _isSharedWithYouAsset,\n * _isPublicLink, _directCollaboratorCount } with a service\n * call to an Invitation Service endpoint.\n *\n * Melville uses the same endpoint to initialize its internal\n * data, and when a Melville request includes selector='collaboration',\n * the response will include collaboration data.\n *\n * Due to Melville re-arranging the data, a Melville Collaborator\n * is not the same data as an Invitation Service Collaborator,\n * so class Library cannot use the data to set ShareableItem._collaborationArray.\n *\n * But there is enough equivalent data for LibraryUpdater\n * to update all of the above properties and clear their dirty flag\n * when the optional collaboration data is present. When it's absent,\n * these getters return NotFound, so the ShareableItem properties\n * will be untouched by the update.\n */\nexport function getLibraryIsShared(value: Partial<LibraryData>): boolean | typeof NotFound {\n    if (value.collaboration) {\n        // CollaborationContext._handleBatchRequest() injects isDirect:true\n        // into Invitation Service Collaborator's being constructed for\n        // directCollaborators.\n\n        // DbLibraryCollaborationData.getFilteredCollaborators()\n        // ( in Melville source ) sets inheritanceType:'DIRECT' for the\n        // same condition.\n        //\n        // So the below handling of Melville Data is equivalent to\n        // ShareableItem._setCollaboratorData()'s handling of\n        // Invitation Service Data.\n\n        const collaborators = value.collaboration.collaborators;\n\n        return collaborators.some((collaborator) => {\n            return (collaborator.inheritanceType === 'DIRECT');\n        });\n    }\n\n    // When the response omits collaboration[], don't set ShareableItem properties\n    return NotFound;\n}\n\nexport function getLibraryIsSharedWithYouAsset(value: Partial<LibraryData>, dest: ISAMObject): boolean | typeof NotFound {\n    if (value.collaboration) {\n        // See above comment in getLibraryIsShared() to explain\n        // collaborator.inheritanceType.\n        //\n        // Collaborator.imsUserId return this.id for imsUser's,\n        // and this._additionalData?.linkedIdentity otherwise.\n        //\n        // DbLibraryCollaboratorData.getCollaborator() ( in Melville source )\n        // returns an imsUser's id, or additionalData.linkedIdentity\n        // for an Address Book Contact's.\n        //\n        // DbLibraryCollaborationData.getFilteredCollaborators() filters\n        // the list to only be imsUser's or Address Book Contact.\n        //\n        // So the below handling of Melville Data is equivalent to\n        // ShareableItem._setCollaboratorData()'s handling of\n        // Invitation Service Data.\n\n        const currentUser = dest._core._environment.getValue('USER_ID');\n        const collaborators = value.collaboration.collaborators;\n\n        return collaborators.some((collaborator) => {\n            return (collaborator.inheritanceType === 'DIRECT') && (collaborator.collaborator === currentUser);\n        });\n    }\n\n    // When the response omits collaboration[], don't set ShareableItem properties\n    return NotFound;\n}\n\n// If the library is shared with you, we still want to know if it's public.\nexport function getLibraryIsPublicLink(value: Partial<LibraryData>): boolean | typeof NotFound {\n    if (value.collaboration) {\n        // Melville's already determined if the library has a public link.\n\n        return !!value.collaboration.public;\n    }\n\n    // When the response omits collaboration[], don't set ShareableItem properties\n    return NotFound;\n}\n\nexport function getLibraryDirectCollaboratorCount(value: Partial<LibraryData>): number | typeof NotFound {\n    if (value.collaboration) {\n        // See above comment in getLibraryIsShared() to explain\n        // collaborator.inheritanceType, but this should be\n        // equivalent to ShareableItem._setCollaboratorData(),\n        // as we are counting the number of direct collaborators.\n\n        const collaborators = value.collaboration.collaborators;\n\n        return collaborators.filter((collaborator) => (collaborator.inheritanceType === 'DIRECT')).length;\n    }\n\n    // When the response omits collaboration[], don't set ShareableItem properties\n    return NotFound;\n}\n\nexport function getLibraryShareFlagsAreDirty(value: Partial<LibraryData>): boolean | typeof NotFound {\n    if (value.collaboration) {\n        // If we've updated the properties (with the above methods),\n        // then we need to clear the dirty flag as well.\n        return false;\n    }\n\n    // When the response omits collaboration[], don't set ShareableItem properties\n    return NotFound;\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport InterfaceBase from './InterfaceBase';\nimport type { ISearchQuery, ISearchSortOrderDirection, USSResponse } from './USSModel';\nimport { SearchProps } from './USSModel';\nimport type { IUSSAdobeAssetOrderBy } from './AssetModel';\nimport {\n    updateAssetTypeForUSS\n} from './USSUtils';\nimport { excludeExpressArtifacts } from '../utils/excludeExpressArtifacts';\n\ntype IPageOptions = {\n    limit: number;\n    start?: number;\n}\n\ninterface IListingOptions<IOrderField> extends IPageOptions {\n    orderDirection: IOrderDirection;\n    orderBy: IOrderField;\n}\n\nexport interface PublishedAssetsListingOptions extends IListingOptions<IUSSAdobeAssetOrderBy> {\n    mediaTypes?: string[],\n    excludeMediaTypes?: string[],\n}\n\nconst DefaultPublishedAssetsListingOptions: PublishedAssetsListingOptions = {\n    orderDirection: 'descending',\n    orderBy: 'modify_date',\n    start: 0,\n    limit: 0,\n    mediaTypes: [],\n    excludeMediaTypes: [],\n};\n\nexport function getDirectionValue(userOptions: Partial<PublishedAssetsListingOptions>): ISearchSortOrderDirection {\n    return userOptions.orderDirection === 'ascending' ? 'asc' : 'desc';\n}\n\nexport default class PublishedInterface extends InterfaceBase {\n\n    async getPublishedAssets(options?: Partial<PublishedAssetsListingOptions>): Promise<USSResponse> {\n        options = { ...DefaultPublishedAssetsListingOptions, ...options };\n        updateAssetTypeForUSS(options.mediaTypes);\n        updateAssetTypeForUSS(options.excludeMediaTypes);\n\n        const filters: ISearchQuery = {\n            sort_orderby: options.orderBy,\n            hints: {\n                acp_platform_v2: true,\n            },\n            fetch_fields: { includes: [ 'app_metadata' ] },\n            op_or: [\n                {\n                    [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: 'pubs'\n                },\n                {\n                    [SearchProps.OP_AND]: [\n                        {\n                            [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: 'cloud-content'\n                        },\n                        {\n                            [SearchProps.FIELD_EXISTS]: [ 'app_metadata$$review:sourceAsset$$dc:format' ]\n                        }\n                    ],\n                }\n            ],\n            op_none_of: [\n                {\n                    [SearchProps.TYPE]: options.excludeMediaTypes || [],\n                },\n                // SAMJS-773\n                ...excludeExpressArtifacts()\n            ],\n            [SearchProps.STORAGE_ASSIGNEE_ID]: this._core._environment.getValue('USER_ID'),\n            asset_id_opacity: true,\n            [SearchProps.TYPE]: options.mediaTypes || [],\n            sort_order: getDirectionValue(options),\n            limit: options.limit,\n            start_index: options.start,\n        };\n\n        return await this._core.hostAssetContext._ussInterface.getQueryResponse(filters);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IUSSAdobeAssetOrderBy } from '../interface/AssetModel';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type AdobeAsset from './AdobeAsset';\nimport { LastAccessedOrderField } from '../interface/USSModel';\nimport { USSv3OrderField } from '../interface/USSv3Model';\n\nexport type USSAdobeAssetOrderField =\n    | 'name'\n    | 'created'\n    | 'modified'\n    | 'lastAccessed';\n\nexport const OrderFieldToIUSSAdobeAssetOrderBy: { [key in USSAdobeAssetOrderField]: IUSSAdobeAssetOrderBy } = {\n    'name': 'asset_name',\n    'created': 'create_date',\n    'modified': 'modify_date',\n    'lastAccessed': LastAccessedOrderField\n};\n\nexport const OrderFieldToUSSv3OrderField: { [key in USSAdobeAssetOrderField]: USSv3OrderField } = {\n    'name': USSv3OrderField.Name,\n    'created': USSv3OrderField.Created,\n    'modified': USSv3OrderField.Modified,\n    // TODO: update with correct field once V3 supports it\n    'lastAccessed': USSv3OrderField.Modified\n};\n\nconst OrderFieldToComparator: IComparatorMap<AdobeAsset, USSAdobeAssetOrderField> = {\n    name(a: AdobeAsset, b: AdobeAsset): number {\n        return compareStrings(a.name, b.name);\n    },\n    created(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.created, b.created);\n    },\n    modified(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.modified, b.modified);\n    },\n    lastAccessed(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.lastAccessed, b.lastAccessed);\n    }\n};\n\nexport default class USSAdobeAssetOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new USSAdobeAssetOrder('descending', 'modified');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type PublishedInterface from '../interface/PublishedInterface';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { USSMetadata, USSResponse } from '../interface/USSModel';\nimport type { USSAdobeAssetUpdaterMetadata } from './AdobeAsset';\nimport type AdobeAsset from './AdobeAsset';\nimport type PublishedAdobeAssetFilter from './PublishedAdobeAssetFilter';\nimport type { PublishedAdobeAssetConfig } from './PublishedAdobeAssetSource';\nimport type { IUSSLoader, IGetUSSResults } from './USSLoaderHelper';\nimport USSLoaderHelper from './USSLoaderHelper';\nimport { OrderFieldToIUSSAdobeAssetOrderBy } from './USSAdobeAssetOrder';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type AdobeAssetFilter from '../assets/AdobeAssetFilter';\n\nexport default class PublishedAdobeAssetLoader implements IUSSLoader<PublishedAdobeAssetConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<PublishedAdobeAssetConfig>;\n\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        core: ISAMCorePrivate,\n        private _publishedInterface: PublishedInterface\n    ) {\n        this._ussLoaderHelper = new USSLoaderHelper(assetPool, core, this);\n    }\n\n    supportsFilter(filter?: PublishedAdobeAssetFilter | AdobeAssetFilter): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<PublishedAdobeAssetConfig>): Promise<ILoadedPage<PublishedAdobeAssetConfig>> {\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- only for use inside USSLoaderHelper\n     */\n    async _getUSSResults({\n        start,\n        loadOptions,\n        mediaTypes,\n        excludeMediaTypes,\n        order\n    }: IGetUSSResults<PublishedAdobeAssetConfig>): Promise<USSResponse> {\n        return this._publishedInterface.getPublishedAssets({\n            orderBy: OrderFieldToIUSSAdobeAssetOrderBy[order.field],\n            orderDirection: order.direction,\n            start,\n            limit: loadOptions?.limit,\n            mediaTypes,\n            excludeMediaTypes\n        });\n    }\n\n    /**\n     * @package -- only for use inside USSLoaderHelper\n     */\n    _getItemData(item: Partial<USSMetadata>): USSAdobeAssetUpdaterMetadata {\n        return {\n            ...item,\n            published: true\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\n\nexport default class PublishedAdobeAssetFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    constructor() {\n        super({ _isPublished: true });\n    }\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2023 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type AdobeAsset from './AdobeAsset';\nimport { Permission } from '../interface/AssetModel';\n\nexport default class DiscardedAdobeAssetFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    constructor() {\n        super({\n            _isDiscarded: true,\n            _isSharedWithYou: true\n        });\n    }\n\n    matches(item: AdobeAsset): boolean {\n\n        if (this.isSyncedAsset(item) || this.isMobileCreation(item)) {\n            return false;\n        }\n\n        // TODO: We should also handle this in the USS query when it's supported, but keep this check here for good measure.\n        // https://jira.corp.adobe.com/browse/SEARCH-41079\n        if (!item.hasPermission(Permission.Restore) && !item.hasPermission(Permission.Delete)) {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n\n    isSyncedAsset(item: AdobeAsset): boolean {\n        return item.repoPath.startsWith('/files/');\n    }\n\n    isMobileCreation(item: AdobeAsset): boolean {\n        return item.repoPath.startsWith('/assets/') && !item.repoPath.startsWith('/assets/adobe-libraries/');\n    }\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2023 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport InterfaceBase from './InterfaceBase';\nimport {\n    updateAssetTypeForUSS\n} from './USSUtils';\nimport type { ISearchQuery } from './USSModel';\nimport { OrderByToUSSOrderBy, SearchProps } from './USSModel';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport type { AdobeAssetOrderField } from '../assets/AdobeAssetOrder';\nimport type { IUSSFetchFieldType } from './AssetModel';\nimport { getUSSFetchFields } from './AssetModel';\nimport { RelType } from './LinkUtils';\nimport type Resource from '../assets/Resource';\nimport { excludeExpressArtifacts } from '../utils/excludeExpressArtifacts';\n\nexport interface DiscardedAssetsListingOptions {\n    limit?: number;\n    start?: number;\n    orderDirection?: IOrderDirection;\n    orderBy?: AdobeAssetOrderField;\n    mediaTypes?: string[];\n    excludeMediaTypes?: string[];\n}\n\nconst DEFAULT_OPTIONS: DiscardedAssetsListingOptions = {\n    limit: 50,\n    start: 0,\n    orderDirection: 'descending',\n    orderBy: 'modified',\n    mediaTypes: [],\n    excludeMediaTypes: []\n};\n\nexport const DISCARD_FETCH_FIELDS: IUSSFetchFieldType[] = [\n    'creative_cloud_colortheme',\n    'creative_cloud_gradient',\n    '_embedded'\n];\n\nexport const MOBILE_CREATIONS_MIMETYPES: string[] = [\n    'application/vnd.adobe.draw.project+dcx',\n    'application/vnd.adobe.sketch.project+dcx',\n    'application/vnd.adobe.photoshop-mix.composition+dcx',\n    'application/vnd.adobe.photoshop-fix.composition+dcx',\n    'application/vnd.adobe.line.sketchbook+dcx',\n    'application/vnd.adobe.layup.project+dcx',\n    'application/vnd.adobe.comp.project+dcx',\n    'application/vnd.adobe.clip.project+dcx',\n    'application/vnd.adobe.clsproject+dcx',\n    'image/vnd.adobe.cls+dcx'\n];\n\nexport default class DiscardedInterface extends InterfaceBase {\n\n    async getDiscardedAssets(options?: DiscardedAssetsListingOptions, resource?: Resource) {\n        options = { ...DEFAULT_OPTIONS, ...options };\n        updateAssetTypeForUSS(options.mediaTypes);\n        updateAssetTypeForUSS(options.excludeMediaTypes);\n\n        const sort_order = options.orderDirection === 'ascending' ? 'asc' : 'desc';\n        const sort_orderby = OrderByToUSSOrderBy[options.orderBy || 'modified'];\n        const userId = this._core._environment.getValue('USER_ID');\n\n        const filters: ISearchQuery = {\n            hints: { acp_platform_v2: true },\n            creative_cloud_archive: true,\n            creative_cloud_discarded_directly: true,\n            [SearchProps.TYPE]: options.mediaTypes || [],\n            fetch_fields: { includes: [\n                ...getUSSFetchFields(),\n                ...DISCARD_FETCH_FIELDS\n            ] },\n            // Asset must either be owned by the current user, or a Library (composite) that exists in /projects\n            // and the current user has write access to it.\n            op_or: [\n                { [SearchProps.STORAGE_ASSIGNEE_ID]: userId },\n                { op_and: [\n                    { [SearchProps.STORAGE_ASSIGNEE_TYPE]: 'org' },\n                    { [SearchProps.TYPE]: [ 'application/vnd.adobe.library+dcx' ] },\n                    {\n                        [SearchProps.REPO_ACL_MODIFIER]: 'grant',\n                        [SearchProps.REPO_ACL_PRIVILEGES]: [ 'write' ],\n                        [SearchProps.REPO_ACL_RELATIONS]: [ RelType.PRIMARY ]\n                    }\n                ] },\n                {\n                    // we just want the projects that are either owned by the current user\n                    // or are in shared-storage\n                    op_and: [\n                        { op_or: [\n                            { [SearchProps.STORAGE_ASSIGNEE_ID]: userId },\n                            { [SearchProps.STORAGE_ASSIGNEE_TYPE]: 'org' }\n                        ] },\n                        { op_field_exists: [\n                            'app_metadata$$cc:inheritable$$cc:team$$repo:assetId',\n                            'app_metadata$$cc:inherited$$cc:team$$repo:assetId',\n                        ] }\n                    ]\n                }\n            ],\n            op_none_of: [\n                { [SearchProps.TYPE]: options.excludeMediaTypes || [] },\n                { [SearchProps.VISIBILITY ]: [ 'hiddenSelf', 'hiddenRecursive' ] },\n                { [SearchProps.FIELD_EXISTS]: [ 'app_metadata$$review:sourceAsset$$dc:format' ] },\n                { [SearchProps.CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME]: [ 'archive', 'files' ] },\n                { [SearchProps.TYPE]: MOBILE_CREATIONS_MIMETYPES },\n                // SAMJS-773\n                ...excludeExpressArtifacts()\n            ],\n            sort_orderby,\n            sort_order,\n            limit: options.limit,\n            start_index: options.start\n        };\n\n        return this._core.hostAssetContext._ussInterface.getQueryResponse(filters, resource);\n    }\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2023 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type { IGetUSSResults, IUSSLoader } from './USSLoaderHelper';\nimport USSLoaderHelper from './USSLoaderHelper';\nimport type { DiscardedAdobeAssetConfig } from './DiscardedAdobeAssetSource';\nimport type { USSAdobeAssetUpdaterMetadata } from './AdobeAsset';\nimport type AdobeAsset from './AdobeAsset';\nimport type ItemPool from '../core/ItemPool';\nimport type { USSMetadata, USSResponse } from '../interface/USSModel';\nimport type { IItemLoaderOptions } from '../core/ItemLoader';\nimport type { ILoadedPage } from '../core/ItemLoader';\nimport type DiscardedInterface from '../interface/DiscardedInterface';\nimport { RelType } from '../interface/LinkUtils';\nimport type { AssetLinks } from '../interface/RepositoryModel';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type LibraryContext from '../libraries/LibraryContext';\nimport type Project from '../projects/Project';\nimport type { IUpdateSession } from '../core/UpdateSession';\nexport default class DiscardedAdobeAssetLoader implements IUSSLoader<DiscardedAdobeAssetConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<DiscardedAdobeAssetConfig>;\n    /**\n      * @package -- only for use in SAM.js\n      */\n    _libraryContext?: LibraryContext;\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private _discardedInterface: DiscardedInterface\n    ) {\n        this._ussLoaderHelper = new USSLoaderHelper<DiscardedAdobeAssetConfig>(assetPool, _core, this);\n    }\n\n    supportsFilter(filter?: DiscardedAdobeAssetConfig['filter']): boolean {\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<DiscardedAdobeAssetConfig>): Promise<ILoadedPage<DiscardedAdobeAssetConfig>> {\n        // Start prefetching data for the discarded source but don't block on it\n        // since this will be needed shortly for the discarded source and even if this finishes before\n        // the call to loadPage, the data will be available in the cache so the AdobeAssetFactory will get it from cache\n        // and set the restore permissions on the project. If this finishes after loadPage, this method will also look\n        // at the item pool for projects and set the restore permissions on each one found.\n        this._discardedSourcePrefetch();\n\n        if (!this._libraryContext) {\n            this._libraryContext = await this._core.getLibraryContext();\n        }\n\n        return await this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- for internal SAM.js use only\n     */\n    private async _discardedSourcePrefetch() {\n        const projectContext = await this._core.getProjectContext();\n\n        const assetContext = await this._core.getAssetContext();\n        const projectIndexPromise = projectContext._prefetchIndex();\n        const repositoriesPromise = assetContext._getListOfRepositoryIDs();\n\n        const results = await Promise.all([ projectIndexPromise, repositoriesPromise ]);\n\n        const canRestorePromises: Promise<boolean>[] = [];\n        const repositories = results[1];\n\n        repositories?.forEach(repository => canRestorePromises.push(projectContext._canRestoreProject(repository)));\n        await Promise.all(canRestorePromises);\n        const session = projectContext._assetPool.createUpdateSession();\n        projectContext._assetPool.forEach(item => {\n            if (item.isProject) {\n                const project = item as Project;\n                project._applyRestorePermission(session as IUpdateSession<Project>);\n            }\n        });\n        session.commit();\n    }\n\n    _getUSSResults({\n        start,\n        loadOptions,\n        mediaTypes,\n        excludeMediaTypes,\n        order,\n        resource\n    }: IGetUSSResults<DiscardedAdobeAssetConfig>): Promise<USSResponse> {\n        return this._discardedInterface.getDiscardedAssets({\n            start,\n            limit: loadOptions?.limit,\n            orderBy: order.field,\n            orderDirection: order.direction,\n            mediaTypes,\n            excludeMediaTypes\n        }, resource);\n    }\n\n    _getItemData(item: Partial<USSMetadata>): USSAdobeAssetUpdaterMetadata {\n        // TODO: come up with proposal for Melville to provide rendering service for non-image LEs\n        // Colors/gradients have RENDITION links that cause 404 error. Clear them out so that\n        // AdobeAsset does not try to fetch their renditions.\n\n        const LERenditionURL = item.creative_cloud_colortheme || item.creative_cloud_gradient\n            ? undefined\n            : item._links?.[RelType.RENDITION];\n\n        const isArchivedLibraryElement = item.asset_sub_type === 'element';\n        if (isArchivedLibraryElement) {\n            item._links = {\n                ...(item._links || {}),\n                [RelType.RENDITION]: LERenditionURL\n            } as AssetLinks;\n        }\n        return {\n            ...item,\n            isArchivedLibraryElement\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\n\n/**\n * @TODO We should open this up to allow clients to configure the restrictions\n * on this query through the filter options below.\n * https://jira.corp.adobe.com/browse/SAM-2542\n */\nexport interface IAdobeAssetGlobalSearchFilterOptions {\n    /**\n     * @package -- only for use by implicit filter\n     */\n    readonly _query: string;\n    readonly _matchingIDsFromSearch: Set<string>;\n    readonly _projectsOnly: boolean;\n}\n\nexport default class AdobeAssetGlobalSearchFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    _query: string = '';\n\n    /**\n     * @package -- only for use by AdobeAssetGlobalSearchFilter/Loader\n     */\n    _matchingIDsFromSearch: Set<string> | undefined;\n\n    /**\n     * @package only for use by AdobeAssetGlobalSearchFilter/Loader\n     */\n    _projectsOnly: boolean = false;\n\n    constructor(options?: Partial<IAdobeAssetGlobalSearchFilterOptions>) {\n        super({ _isSharedWithYou: true });\n        this._query = options?._query || '';\n        this._projectsOnly = options?._projectsOnly || false;\n    }\n    get query(): string {\n        return this._query;\n    }\n\n    get projectsOnly(): boolean {\n        return this._projectsOnly;\n    }\n\n    // The matching rules USS are deceptively complex, and could change over time. Attempting to\n    // replicate here could result in items being incorrectly filtered out or incorrectly included.\n    // Global search Lists should not try to share items from Lists with similar queries, other\n    // than treating the queries as case-insensitive.\n    matches(item: AdobeAsset): boolean {\n\n        // Check if the item's id is in the current filter's id list\n        if (this._matchingIDsFromSearch && !this._matchingIDsFromSearch.has(item.id)) {\n            return false;\n        }\n\n        // If the query exists but there's no id list, we probably haven't finished loading yet\n        if ((this._query) && !this._matchingIDsFromSearch) {\n            return false;\n        }\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2023 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport InterfaceBase from './InterfaceBase';\nimport {\n    FetchFields,\n    type ISearchQuery,\n    type ISearchQueryEntry,\n    type USSResponse,\n} from './USSv3Model';\n\nexport const DEFAULT_MAX_LIMIT = 50;\nexport const USS_CONTENT_TYPE = 'application/vnd.adobe.search-request+json';\nexport const DEFAULT_EXPERIENCE_ID = 'Default-Global-Search-Experience';\n\nexport default class USSv3Interface extends InterfaceBase {\n\n    readonly queryPath: string = '/uss/v3/query';\n\n    async getQueryResponse(queryEntry: ISearchQueryEntry): Promise<USSResponse> {\n        const url = `https://${this._core._environment.endpoints.USSv3_HOST}${this.queryPath}`;\n        const queryEntryWithDefaults: ISearchQueryEntry =  {\n            // USS only allows specific query ids to be passed, 'global-search-1' is the one USS team said SAM.js\n            // should use.\n            'id': 'global-search-1',\n            'scope': {\n                'entities': [ 'AcpAsset' ]\n            },\n            'fetchFields': [\n                FetchFields.SharedBy,\n                FetchFields.ShellVisibility,\n                // --- USS v3 includes these fields, and more, by default ---\n                // am.shell:lastActivity.date\n                // am.project:directoryType\n                // am.cc:inheritable:*\n                // am.cc:inherited:*\n                // am.assignment:*\n                // am.classroom:*\n                // am.hz:documentMetadata.*,\n                // --- end USS v3 default fields ---\n                FetchFields.ReviewSourceAssetType,\n                // --- Below are candidates for loadHints ---\n                FetchFields.ConvertedTo,\n                FetchFields.NonAutoMigratable,\n                FetchFields.CopiedLegacySparkId,\n                FetchFields.CreatedFromUpload\n            ],\n            ...queryEntry\n        };\n        const query: ISearchQuery = {\n            experienceId: DEFAULT_EXPERIENCE_ID,\n            queries: [ queryEntryWithDefaults ]\n        };\n        const response = await this._doPost(\n            url,\n            {\n                'content-type': USS_CONTENT_TYPE,\n            },\n            JSON.stringify(query),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2023 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type { IGetUSSResultsOpts, IUSSLoader } from './USSv3LoaderHelper';\nimport USSv3LoaderHelper from './USSv3LoaderHelper';\nimport type { AdobeAssetGlobalSearchConfig } from './AdobeAssetSource';\nimport type ItemPool from '../core/ItemPool';\nimport type AdobeAsset from './AdobeAsset';\nimport { DEFAULT_MAX_LIMIT } from '../interface/USSv3Interface';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type {\n    USSResponse,\n    USSv3InheritanceTypeField\n} from '../interface/USSv3Model';\nimport type AdobeAssetGlobalSearchFilter from './AdobeAssetGlobalSearchFilter';\nimport type GlobalSearchInterface from '../interface/GlobalSearchInterface';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type LibraryContext from '../libraries/LibraryContext';\nimport type USSAdobeAssetFilter from './USSAdobeAssetFilter';\n\nexport default class GlobalSearchLoader implements IUSSLoader<AdobeAssetGlobalSearchConfig> {\n    private _ussLoaderHelper: USSv3LoaderHelper<AdobeAssetGlobalSearchConfig>;\n    /**\n      * @package -- only for use in SAM.js\n      */\n    _libraryContext?: LibraryContext;\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private _globalSearchInterface: GlobalSearchInterface,\n        private _implicitFilter: AdobeAssetGlobalSearchFilter\n    ) {\n        this._ussLoaderHelper = new USSv3LoaderHelper<AdobeAssetGlobalSearchConfig>(assetPool, this._core, this);\n    }\n\n    supportsFilter(filter?: AdobeAssetGlobalSearchConfig['filter']): boolean {\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<AdobeAssetGlobalSearchConfig>): Promise<ILoadedPage<AdobeAssetGlobalSearchConfig>> {\n        if (!this._libraryContext) {\n            this._libraryContext = await this._core.getLibraryContext();\n        }\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    _getUSSResults({\n        start,\n        loadOptions,\n        order,\n        mediaTypes,\n        excludeMediaTypes,\n        filter\n    }: IGetUSSResultsOpts<AdobeAssetGlobalSearchConfig>): Promise<USSResponse> {\n        const { _query: query, projectsOnly } = this._implicitFilter;\n        const {\n            excludeInheritanceTypes,\n            assetTypes,\n            excludeAssetTypes,\n            assetSubTypes\n        } = filter as USSAdobeAssetFilter;\n\n        return this._globalSearchInterface.globalSearch({\n            start,\n            limit: loadOptions?.limit ?? DEFAULT_MAX_LIMIT,\n            query,\n            order,\n            mediaTypes,\n            excludeMediaTypes,\n            // Public interface doesn't enforce valid values for excludeInheritanceTypes. Using cast here\n            // to avoid breaking the public interface.\n            excludeInheritanceTypes: [ ...(excludeInheritanceTypes || []) ] as USSv3InheritanceTypeField[],\n            projectsOnly,\n            assetTypes: [ ...(assetTypes || []) ],\n            excludeAssetTypes: [ ...(excludeAssetTypes || []) ],\n            assetSubTypes: [ ...(assetSubTypes || []) ]\n        });\n    }\n\n    _postProcessPage(\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        { filter }: IItemLoaderOptions<AdobeAssetGlobalSearchConfig>,\n        { items }: ILoadedPage<AdobeAssetGlobalSearchConfig>\n    ): void {\n        this._implicitFilter._matchingIDsFromSearch = new Set([\n            // copy existing\n            ...(this._implicitFilter._matchingIDsFromSearch || []),\n            ...(items.map(item => item.id))\n        ]);\n    }\n}\n","/*************************************************************************\n *   ADOBE CONFIDENTIAL\n *\n *   Copyright 2023 Adobe\n *   All Rights Reserved.\n *\n *   NOTICE:  All information contained herein is, and remains\n *   the property of Adobe and its suppliers, if any. The intellectual\n *   and technical concepts contained herein are proprietary to Adobe\n *   and its suppliers and are protected by all applicable intellectual\n *   property laws, including trade secret and copyright laws.\n *   Dissemination of this information or reproduction of this material\n *   is strictly forbidden unless prior written permission is obtained\n *   from Adobe.\n **************************************************************************/\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport type { USSAdobeAssetOrderField } from '../assets/USSAdobeAssetOrder';\nimport { OrderFieldToUSSv3OrderField } from '../assets/USSAdobeAssetOrder';\nimport InterfaceBase from './InterfaceBase';\nimport {\n    excludeExpressArtifacts,\n    type ISearchQueryEntryFilter,\n    type USSResponse,\n    USSv3DirectoryType,\n    USSv3FilterField,\n    USSv3Function,\n    type USSv3InheritanceTypeField,\n    USSv3OrderDir\n} from './USSv3Model';\nimport type USSv3Interface from './USSv3Interface';\nimport { DEFAULT_MAX_LIMIT } from './USSv3Interface';\nimport type { ISAMCorePrivate } from '../indexPrivate';\n\nexport interface IGlobalSearchOpts {\n    query: string;\n    start: number;\n    limit: number;\n    order?: {\n        direction: IOrderDirection;\n        field: USSAdobeAssetOrderField;\n    },\n    mediaTypes?: string[];\n    excludeMediaTypes?: string[];\n    excludeInheritanceTypes?: USSv3InheritanceTypeField[];\n    projectsOnly?: boolean;\n    assetTypes?: string[];\n    excludeAssetTypes?: string[];\n    assetSubTypes?: string[];\n}\n\nexport default class GlobalSearchInterface extends InterfaceBase {\n\n    constructor(\n        _core: ISAMCorePrivate,\n        private _ussInterface: USSv3Interface\n    ) {\n        super(_core);\n    }\n\n    async globalSearch({\n        query,\n        start = 0,\n        limit = DEFAULT_MAX_LIMIT,\n        order,\n        mediaTypes,\n        excludeInheritanceTypes,\n        projectsOnly,\n        assetTypes,\n        excludeAssetTypes,\n        assetSubTypes\n    }: IGlobalSearchOpts): Promise<USSResponse> {\n        const { field = 'modified', direction = 'descending' } = order || {};\n\n        const filters: ISearchQueryEntryFilter[] = [];\n        if (projectsOnly) {\n            // As per the recent discussions this is how the project:directoryType is defined as of now\n            // The old spaces were identified with project:directoryType = project\n            // The old workspaces were identified with project:directoryType = team\n            // The new projects are now identified with project:directoryType = team\n            filters.push({ [USSv3FilterField.DIRECTORY_TYPE]: [ USSv3DirectoryType.PROJECT ] });\n        } else {\n            if (mediaTypes?.length) {\n                filters.push({\n                    [USSv3FilterField.MEDIA_TYPE]: mediaTypes,\n                });\n            }\n\n            if (excludeInheritanceTypes?.length) {\n                filters.push({\n                    [USSv3Function.MISSING]: {\n                        funcParams: { fields: excludeInheritanceTypes! }\n                    }\n                });\n            }\n            if (excludeAssetTypes?.length) {\n                filters.push({ [USSv3Function.NOT]: {\n                    funcParams: { [USSv3FilterField.ASSET_TYPE]: excludeAssetTypes }\n                } });\n            } else if (assetTypes?.length) {\n                filters.push({ [USSv3FilterField.ASSET_TYPE]: assetTypes });\n            }\n            if (assetSubTypes?.length) {\n                filters.push({ [USSv3FilterField.ASSET_SUB_TYPE]: assetSubTypes });\n            }\n\n            // SAMJS-773\n            filters.push(excludeExpressArtifacts());\n\n        }\n\n        return this._ussInterface.getQueryResponse({\n            start,\n            limit,\n            textQuery: query,\n            sorts: [ {\n                sortOrderBy: OrderFieldToUSSv3OrderField[field],\n                sortOrder: (direction === 'ascending' ? USSv3OrderDir.Ascending : USSv3OrderDir.Descending)\n            } ],\n            filters\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from './AdobeAsset';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { AdobeAssetGlobalSearchConfig } from './AdobeAssetSource';\nimport type AdobeAssetGlobalSearchFilter from './AdobeAssetGlobalSearchFilter';\nimport { OrderFieldToIUSSAdobeAssetOrderBy } from './USSAdobeAssetOrder';\nimport type AdobeAssetGlobalSearchInterface from '../interface/AdobeAssetGlobalSearchInterface';\nimport type { USSResponse } from '../interface/USSModel';\nimport type { IGetUSSResults, IUSSLoader } from './USSLoaderHelper';\nimport USSLoaderHelper from './USSLoaderHelper';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type AdobeAssetFilter from './AdobeAssetFilter';\nimport type LibraryContext from '../libraries/LibraryContext';\n\nexport default class AdobeAssetGlobalSearchLoader implements IUSSLoader<AdobeAssetGlobalSearchConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<AdobeAssetGlobalSearchConfig>;\n    _libraryContext?: LibraryContext;\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        private _implicitFilter: AdobeAssetGlobalSearchFilter,\n        private _core: ISAMCorePrivate,\n        private _adobeAssetGlobalSearchInterface: AdobeAssetGlobalSearchInterface\n    ) {\n        this._ussLoaderHelper = new USSLoaderHelper(assetPool, _core, this);\n    }\n\n    supportsFilter(filter?: AdobeAssetGlobalSearchFilter | AdobeAssetFilter): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<AdobeAssetGlobalSearchConfig>): Promise<ILoadedPage<AdobeAssetGlobalSearchConfig>> {\n        if (!this._libraryContext) {\n            this._libraryContext = await this._core.getLibraryContext();\n        }\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- only for use by USSLoaderHelper\n     */\n    _getUSSResults({\n        start,\n        loadOptions,\n        order,\n        mediaTypes,\n        excludeMediaTypes\n    }: IGetUSSResults<AdobeAssetGlobalSearchConfig>): Promise<USSResponse> {\n        const query = this._implicitFilter?._query;\n\n        return this._adobeAssetGlobalSearchInterface.getFilteredAssets({\n            orderBy: OrderFieldToIUSSAdobeAssetOrderBy[order.field],\n            orderDirection: order.direction,\n            start,\n            limit: loadOptions?.limit,\n            mediaTypes,\n            excludeMediaTypes,\n            query,\n            embedPermissions: true,\n        });\n    }\n\n    /**\n     * @package -- only for use by USSLoaderHelper\n     */\n    _postProcessPage(\n        loaderOptions: IItemLoaderOptions<AdobeAssetGlobalSearchConfig>,\n        page: ILoadedPage<AdobeAssetGlobalSearchConfig>\n    ): void {\n        const { items } = page;\n\n        this._implicitFilter!._matchingIDsFromSearch = new Set([\n            // copy existing, if needed\n            ...(this._implicitFilter!._matchingIDsFromSearch || []),\n            ...(items.map(item => item.id)) ]);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\n\nexport default class SWYAdobeAssetFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n\n    constructor() {\n        super({\n            _isSharedWithYou: true\n        });\n    }\n    matches(item: AdobeAsset): boolean {\n        if (!item._isSWYAsset_NoLazyLoad) {\n            return false;\n        }\n        if (item.isProject) {\n            return false;\n        }\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorSubCode, isSAMError } from '../core/SAMError';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport { cache, key, synchronized } from '../core/decorators';\nimport InterfaceBase from './InterfaceBase';\nimport type { IServiceLink } from './LinkUtils';\nimport { getURLFromLinks, JSON_MIME_TYPE, JSON_PATCH_MIME_TYPE, RelType, validateLinks } from './LinkUtils';\nimport type {\n    IProject,\n    IProjectsCreateData,\n    IProjectsEmbeddableResource,\n    IProjectsOrderBy,\n    IProjectsResponse,\n    IProjectsIndexLinks,\n    IProjectsIndexResponse,\n    IProjectLinks,\n    IProjectPatchData,\n    ProjectCapabilities,\n    IProjectsServiceErrorResponse,\n    IProjectView,\n    IRecentProjectsResponse,\n    ProjectDirectorySubtype,\n    IProjectCreateReferenceResponse\n} from './ProjectsModel';\nimport {\n    PROJECTS_INDEX_LINKS,\n    IProjectPatchKeys\n} from './ProjectsModel';\nimport { SAMErrorCode, ProblemType } from '../core/SAMError';\nimport type { IGradientsResponse } from './GradientModel';\nimport type jsonpatch from 'json-patch';\nimport type { IOrganizationsResponse } from './OrganizationsModel';\nimport Resource from '../assets/Resource';\n\n// Link for the projects service v3 API spec: https://developers.corp.adobe.com/ccteams/src/main/resources/static/openapi/v3/index.yaml\n\ntype IPageOptions = {\n    start: number;\n    limit: number;\n}\n\ninterface IListingOptions<IOrderField> extends IPageOptions {\n    orderDirection: IOrderDirection;\n    orderBy: IOrderField;\n}\n\nexport interface ProjectsListingOptions extends IListingOptions<IProjectsOrderBy> {\n    // Projects service allows certain properties to be embedded in the response as '_embedded' property in each child\n    embed?: IProjectsEmbeddableResource;\n\n    // filters out the projects based on the view. Gives all the results if not specified\n    view?: IProjectView;\n\n    // We need to provide support for repository ID based filtering\n    // This will be required by Admin console to narrow results to a specific organization\n    repositoryId?: string;\n\n    // String search term mostly used by AdminConsole.\n    nameContains?: string;\n\n    // Filters Projects by a comma-delimited list of repo:ownerIDs, which can be userIds or orgIds\n    ownerId?: string;\n\n    // Will fetch projects are discarded or not\n    isDiscarded?: boolean;\n\n    // Filters the listed values based on the sub type. Accepts multiple comma-separated values.\n    // For the first iteration, the two supported options are wfProject and ccProject, the others\n    // will be supported in the near future.\n    directorySubtypes?: ProjectDirectorySubtype[];\n}\n\nexport type RecentProjectsListingOptions = {\n    // we won't be using after as we always get the next page link from the response\n    after?: string;\n    first?: number;\n    embed?: IProjectsEmbeddableResource;\n}\nexport interface IContextAPIResponse {\n    'repo:assetId': string;\n}\n\nexport const DefaultEmbeddedResources: IProjectsEmbeddableResource = [\n    RelType.AC_EFFECTIVE,\n    RelType.APP_METADATA,\n    RelType.PROJECTS_CREATOR,\n    RelType.REPOSITORY\n];\n\nconst DefaultProjectsListingOptions: ProjectsListingOptions = {\n    orderDirection: 'ascending',\n    orderBy: 'repo:name',\n    start: 0,\n    limit: 0,\n    // we want to embed all the resources by default\n    embed: DefaultEmbeddedResources,\n\n    // The default use case is to show all active project projects.\n    isDiscarded: false\n};\n\nconst DefaultRecentProjectsListingOptions: RecentProjectsListingOptions = {\n    first: 10,\n    // we want to embed all the resources by default\n    embed: DefaultEmbeddedResources\n};\n\nfunction getDirectionValue<IOrderField>(userOptions: IListingOptions<IOrderField>) {\n    const directionFlag = userOptions.orderDirection === 'ascending' ? '+' : '-';\n    return directionFlag + userOptions.orderBy;\n}\n\nfunction createPageTemplate(options: IPageOptions) {\n    const templateValues: any = {};\n    if (options.start) {\n        templateValues.start = options.start;\n    }\n    if (options.limit) {\n        templateValues.limit = options.limit;\n    }\n    return templateValues;\n}\n\nexport function getProjectsListingPath(links: IProjectsIndexLinks, options?: Partial<ProjectsListingOptions>): string {\n    const userOptions: ProjectsListingOptions =  { ...DefaultProjectsListingOptions, ...options };\n    const templateValues: any = createPageTemplate(userOptions);\n    templateValues.orderBy = getDirectionValue(userOptions);\n    const { embed, view, repositoryId, ownerId, nameContains, isDiscarded, directorySubtypes } = userOptions;\n    if (embed?.length) {\n        templateValues.embed = embed.join(',');\n    }\n    if (view) {\n        templateValues.view = view;\n    }\n    if (repositoryId) {\n        templateValues.repositoryId = repositoryId;\n    }\n\n    // No default value for namContains so\n    // just pull the value from the filter.\n    if (nameContains) {\n        templateValues.nameContains = nameContains;\n    }\n\n    if (ownerId) {\n        templateValues.ownerId = ownerId;\n    }\n\n    if (isDiscarded) {\n        templateValues.state = 'discarded';\n    }\n\n    if (directorySubtypes) {\n        templateValues.directorySubtype = directorySubtypes.join(',');\n    }\n\n    return getURLFromLinks(links, RelType.PROJECTS_COLLECTION, templateValues);\n}\n\nfunction validateRequiredProjectLinks(links: any) {\n    return validateLinks(links, PROJECTS_INDEX_LINKS);\n}\n\n/**\n * Small utility function that returns an OpPatch operation\n * for gradients. Seperated to make it easier to share here and\n * in tests.\n *\n * @param path\n * @param gradientID\n * @returns\n */\nexport function getProjectGradientPatchOP(path: string, gradientID: string): jsonpatch.OpPatch {\n    return {\n        'op': 'replace',\n        path,\n        'value': gradientID\n    };\n}\n\nexport function getRecentProjectsListingURL(links: IProjectsIndexLinks, options?: Partial<RecentProjectsListingOptions>): string {\n    const userOptions =  { ...DefaultRecentProjectsListingOptions, ...options };\n    const templateValues: any = {};\n    if (userOptions.after) {\n        templateValues.after = userOptions.after;\n    }\n    if (userOptions.first) {\n        templateValues.first = userOptions.first;\n    }\n    if (userOptions.embed?.length) {\n        templateValues.embed = userOptions.embed.join(',');\n    }\n    return getURLFromLinks(links, RelType.PROJECTS_RECENT, templateValues);\n}\n\n// Exporting the path to make it easier to use in tests as well.\nexport const CSC_PROJECT_CREATE_ENDPOINT_PATH = '/api/v3/internal/csc-projects/:create';\n\nexport interface ICSCProjectCreateMetadata {\n    [RelType.APP_METADATA]?: Record<string, any>;\n    'repo:name': string;\n    'project:directorySubtype': string;\n    'repo:path'?: string;\n    'repo:assetId'?: string;\n}\n\nexport interface ICSCProjectBase {\n    projectDirectorySubType: ProjectDirectorySubtype;\n    name: string;\n    /**\n     * An object value with open-ended schema to support including additional properties to the application metadata of\n     * the Project. The purpose of this property is for Workfront to set some of their metadata on the\n     *  Project. Any property names that will conflict with Project app metadata will be overwritten.\n     */\n    appMetadata?:  Record<string, any>;\n}\n\ninterface ICSCProjectWithPath extends ICSCProjectBase {\n    /**\n     * The path of directories leading to the Project. This does not represent the entire path, but only the directories\n     * that should be created. This should include the Project name as the final segment of the path.\n     * If both this parameter and the repo:assetId are provided or the provided repo:path\n     * contains an existing Project, then an error will be returned.\n     */\n    path: string;\n    parentAssetId?: never;\n}\n\ninterface ICSCProjectWithParent extends ICSCProjectBase {\n    /**\n     * The asset ID of the Project that the new Project should be created within.\n     * The Project will be validated to ensure that it is of subType \"wfPortolio\" or \"wfProgram\".\n     * If this parameter is not provided, then the Project will be created starting from the top-level.\n     * If both this parameter and the \"repo:path\" are provided, then an error will be returned (see Response).\n     */\n    parentAssetId: string;\n    path?: never;\n}\n\ntype ICSCProjectCreate = ICSCProjectWithPath | ICSCProjectWithParent;\n\nexport default class ProjectsInterface extends InterfaceBase {\n\n    @cache(validateRequiredProjectLinks)\n    private async _discoverLinks(@key rootHref: string): Promise<IProjectsIndexLinks> {\n        const response: IProjectsIndexResponse = await this._getResponse(rootHref);\n        return response._links;\n    }\n\n    private _getEndpointHref(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.PROJECTS_HOST}${endpoint}`;\n    }\n\n    private _getCreateEndpointHref() {\n        // At the moment we don't need to worry about the region since\n        // the services will likely not be located in various regions at the moment\n        // so that optimizations is not necessary, it may change in the future if\n        // those reqs arise.\n\n        // This is also a well known URL\n        return this._getEndpointHref(CSC_PROJECT_CREATE_ENDPOINT_PATH);\n    }\n\n    /**\n     *\n     * @package Internal use only\n     */\n    async _discoverProjectLinks(): Promise<IProjectsIndexLinks> {\n        return this._discoverLinks(this._getEndpointHref(`/api/v3/index`));\n    }\n\n    /**\n     * Fetches the list of projects based on the options provided\n     * @param options : options to sort and filter the projects listing\n     * @returns the list of projects along with the page information and links to the next page\n     */\n    async getProjects(options: Partial<ProjectsListingOptions>, resource?: Resource<Response>): Promise<IProjectsResponse> {\n        const links = await this._discoverProjectLinks();\n        const url = getProjectsListingPath(links, options);\n        return await this._getResponse(url, { resource });\n    }\n\n    /**\n     * Fetches the list of recent projects based on the options provided\n     * @param options : options limit and pagination\n     * @returns the list of recent projects along with the page information\n     */\n    async getRecentProjects(options: Partial<RecentProjectsListingOptions>, resource?: Resource<Response>): Promise<IRecentProjectsResponse> {\n        const links = await this._discoverProjectLinks();\n        const url = getRecentProjectsListingURL(links, options);\n        return await this._getResponse(url, { resource });\n    }\n\n    private async _getProjectLink(\n        id: string,\n        embed: IProjectsEmbeddableResource = DefaultEmbeddedResources\n    ) {\n        const links = await this._discoverProjectLinks();\n        const url = getURLFromLinks(links, RelType.PROJECTS_PRIMARY, {\n            assetId: id,\n            ...(embed.length ? { embed: embed.join(',') } : undefined)\n        });\n        return url;\n    }\n    /**\n     *\n     * @param id Gets the project metadata for the given project id from the projects service\n     * @param embed the resources that are to be embedded in the response. By default all the resources are embedded\n     * @returns the project metadata for the given project id\n     */\n    async getProject(\n        id: string,\n        embed: IProjectsEmbeddableResource = DefaultEmbeddedResources\n    ): Promise<IProject> {\n        const url = await this._getProjectLink(id, embed);\n        return await this._getResponse(url);\n    }\n\n    async getProjectsWithLink(pageLink: IServiceLink): Promise<IProjectsResponse> {\n        return await this._getResponse(pageLink.href);\n    }\n\n    private async _getCreateLink(embed: IProjectsEmbeddableResource) {\n        const links = await this._discoverProjectLinks();\n        return getURLFromLinks(links, RelType.PROJECTS_CREATE, embed.length ? { embed: embed.join(',') } : undefined);\n    }\n\n    /**\n     * Creates a new project\n     * @param data needed to create a project like name and color\n     * @param embed the resources to be returned in the response of the newly created project. By default all the\n     *     resources are embedded\n     * @returns the newly created project\n     */\n    async createProject(data: IProjectsCreateData, embed: IProjectsEmbeddableResource = DefaultEmbeddedResources): Promise<IProject> {\n        const url = await this._getCreateLink(embed);\n\n        // 403 is included as a success code below so we can special case it after _doPost returns.\n        const response = await this._doPost(url, { 'Content-Type': JSON_MIME_TYPE }, JSON.stringify(data), [ 201, 403 ]);\n        let jsonResponse = {} as any;\n\n        // Use try/catch in case body is empty or not JSON. It's expected that success cases will always return\n        // JSON, but not sure about all error cases. Otherwise, it could throw an exception here and hide the\n        // service call that caused the problem.\n        try {\n            jsonResponse = await response.json();\n        } catch {\n            // Ignore the error here.\n        }\n\n        if (jsonResponse.status === 403) {\n            if (jsonResponse.type === ProblemType.CHILDREN_LIMIT_EXCEEDED) {\n                throw SAMError.create(\n                    SAMErrorCode.PROJECT_LIMIT_EXCEEDED,\n                    'Maximum number of Projects exceeded',\n                    { response, reqId: response.headers.get('x-request-id') || '' }\n                );\n            } else {\n                const error = SAMError.createWithResponse(response, response.url);\n                this._core._environment.error(`ProjectsInterface error ${error}`);\n                throw error;\n            }\n        }\n\n        return jsonResponse;\n    }\n\n    /**\n     * Creates a new CSC Project with the Projects Service\n     *\n     * The data interface is setup to only allow either a path or assetId\n     * supplying both may work but fail in the services since only one of\n     * these values are allowed.\n     *\n     */\n    async createCSCProject(data: ICSCProjectCreate, orgId: string, userId?: string): Promise<Partial<IProject>> {\n        const { path, parentAssetId, projectDirectorySubType, name, appMetadata } = data;\n        let projectCreateRepoData: ICSCProjectCreateMetadata = {\n            'project:directorySubtype': projectDirectorySubType.toString(),\n            'repo:name': name,\n            ...(appMetadata ? {\n                [RelType.APP_METADATA]: { ...appMetadata }\n            } : {})\n        };\n\n        const createLink = this._getCreateEndpointHref();\n\n        if (path) {\n            projectCreateRepoData = {\n                ...projectCreateRepoData,\n                'repo:path': path\n            };\n        } else {\n            projectCreateRepoData = {\n                ...projectCreateRepoData,\n                'repo:assetId': parentAssetId\n            };\n        }\n\n        // Currently there isn't a response from this API\n        // in the future there may be.\n        const response = await this._doPost(\n            createLink,\n            {\n                'Content-Type': JSON_MIME_TYPE,\n                'Org-Id': orgId,\n                ...(userId ? { 'User-Id': userId } : {})\n            },\n            JSON.stringify(projectCreateRepoData),\n            [ 201 ]\n        );\n\n        const responseJson = await response.json();\n\n        // Since there isn't a response from service, we need to return\n        // a partial metadata structure using the properties returned\n        // from the project service.\n        return responseJson;\n    }\n\n    /**\n     * Find the project that matches the given name, if available\n     * @param path relative path of the project, which is the project name\n     * @returns data associated with the project\n     */\n    async resolveProjectByName(path: string): Promise<IProject> {\n        const url = await this._getResolveByPathLink(path);\n        return this._getResponse(url);\n    }\n\n    /**\n     * Renames the project with the new name\n     * @param newName new name for the project\n     * @param links links associated with the project. We use the rename link to rename the project\n     */\n    async renameProject(newName: string, links: IProjectLinks): Promise<void> {\n        const href = getURLFromLinks(links, RelType.PROJECTS_RENAME);\n        await this._doPost(\n            href,\n            { 'Content-Type': JSON_MIME_TYPE },\n            JSON.stringify({ 'repo:name': newName }),\n            [ 204 ]);\n    }\n\n    private async _getResolveByPathLink(path: string, repositoryID?: string): Promise<string> {\n        const links = await this._discoverProjectLinks();\n        const url = getURLFromLinks(links, RelType.RESOLVE_PATH, {\n            path,\n            ...(repositoryID ? { repositoryId: repositoryID } : {})\n        });\n        return url;\n    }\n\n    /**\n     * Validate the project name either for creation or renaming a project.\n     * If the head call responds with 404, it means the project name is valid\n     * and no other project exists with the same name/path.\n     * 200 and 403 responses are considered name conflicts.\n     * Please refer https://wiki.corp.adobe.com/display/assetscollab/Proposal%3A+Project+API+V3+-+Resolve\n     * for more details.\n     * @param path The relative path or absolute path of a project. If the path is relative,\n     * project service prepends a prefix to form an absolute path\n     */\n    async validateProjectName(path: string, repositoryID?: string): Promise<void> {\n        const url = await this._getResolveByPathLink(path, repositoryID);\n        await this._doHead(url);\n    }\n\n    /**\n     * Discards a project.\n     */\n    async discardProject(id: string, links: IProjectLinks) {\n        if (!links?.[RelType.DISCARD]) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Discard link is missing for this project${id}`);\n        }\n\n        const href = getURLFromLinks(links, RelType.DISCARD);\n        await this._doPost(\n            href,\n            undefined,\n            undefined,\n            [ 204 ]\n        );\n    }\n\n    /**\n     * Restores a project.\n     */\n    async restoreProject(id: string, links: IProjectLinks) {\n        if (!links?.[RelType.RESTORE]) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Restore link is missing for this project${id}`);\n        }\n\n        const href = getURLFromLinks(links, RelType.RESTORE);\n        await this._doPost(\n            href,\n            undefined,\n            undefined,\n            [ 204 ]\n        );\n    }\n\n    _gradientResourcesByLanguage = new Map<string, Resource<IGradientsResponse>>();\n\n    /**\n     * Get a Resource representing the gradients available for a given language.\n     * By using separate resources for each language, we can more easily cache them,\n     * rather than one Resource that can vary by language.\n     */\n    getGradientsResource(language: string) {\n        let resource = this._gradientResourcesByLanguage.get(language);\n        if (!resource) {\n            let loadedOnceThisSession = false;\n            resource = new Resource<IGradientsResponse>(this._core, {\n                // Since gradients vary by language using the same URL,\n                // we need to include the language in the cache key.\n                getCacheKey: (method, href) => `${method}-${href}-${language}`,\n                skipRevalidation: () => loadedOnceThisSession,\n                onChange: async (_response, flags) => {\n                    if (!flags?.loading) {\n                        loadedOnceThisSession = true;\n                    }\n                },\n                loadData: async () => {\n                    const url = await this._getGradientsLink();\n                    await this._doGet(url, {\n                        headers: {\n                            'Content-Type': JSON_MIME_TYPE,\n                            'Accept-Language': language\n                        },\n                        resource\n                    });\n                },\n            });\n            this._gradientResourcesByLanguage.set(language, resource);\n        }\n        return resource;\n    }\n\n    private async _getGradientsLink() {\n        const links = await this._discoverProjectLinks();\n        const url = getURLFromLinks(\n            links,\n            RelType.PROJECTS_GRADIENTS_COLLECTION,\n        );\n        return url;\n    }\n\n    @synchronized\n    async getGradients(\n        languageCode: string\n    ): Promise<IGradientsResponse> {\n        const resource = this.getGradientsResource(languageCode);\n        return await resource.get({ });\n    }\n\n    async patchProject(links: IProjectLinks, data: IProjectPatchData) {\n        const jsonData: jsonpatch.OpPatch[] = [];\n\n        if (data.gradientID) {\n            jsonData.push(getProjectGradientPatchOP(IProjectPatchKeys.GRADIENT_ID, data.gradientID));\n        }\n\n        const url = getURLFromLinks(links, RelType.APP_METADATA);\n        await this._doPatch(url, { 'Content-Type': JSON_PATCH_MIME_TYPE, 'If-Match': '*' }, JSON.stringify(jsonData), [ 204 ]);\n    }\n\n    private async _getCapabilityLink(capability: ProjectCapabilities, repositoryID?: string) {\n        const links = await this._discoverProjectLinks();\n        return getURLFromLinks(links, RelType.PROJECTS_CAPABILITY, {\n            privilege: capability,\n            // @TODO We need change all instances of repositoryID to repositoryId\n            // in order to prevent some bugs in the future and keep the naming consistent.\n            ...(repositoryID ? { repositoryId: repositoryID } : {})\n        });\n    }\n\n    async getCapability(capability: ProjectCapabilities, repositoryID?: string) {\n        const url = await this._getCapabilityLink(capability, repositoryID);\n\n        try {\n            await this._doGet(url);\n        } catch (e) {\n            // If the error is not a SAMError then we can\n            // just throw it normally. We don't want to obfuscate a regular error\n            // that could occur just because it's not a SAMError.\n            if (!isSAMError(e)) {\n                throw e;\n            }\n\n            const samError = e as SAMError;\n            const errorResponse = samError._additionalInfo.response;\n\n            // If the response is not defined then let's just\n            // throw the error as well since it's not an error created by\n            // a response from a request in SAM.\n            if (!errorResponse) {\n                throw e;\n            }\n\n            const failedResponseCode = [ 404, 403 ];\n            if (!failedResponseCode.includes(errorResponse.status)) {\n                throw e;\n            }\n\n            const responseJson: IProjectsServiceErrorResponse = await errorResponse.json();\n            switch (responseJson.type) {\n            case ProblemType.ADMIN_ONLY:\n                throw SAMError.create(\n                    SAMErrorCode.ACCESS_DENIED,\n                    'Admin disabled creation of projects for user',\n                    undefined,\n                    SAMErrorSubCode.PROJECTS_ADMIN_ONLY\n                );\n            case ProblemType.NO_HOME_REPOSITORY:\n                throw SAMError.create(\n                    SAMErrorCode.NOT_FOUND,\n                    'No home repository for the user',\n                    undefined,\n                    SAMErrorSubCode.PROJECTS_NO_HOME_REPOSITORY\n                );\n            case ProblemType.INVALID_HOME_REPOSITORY:\n                throw SAMError.create(\n                    SAMErrorCode.NOT_FOUND,\n                    'Invalid home Repository for the user',\n                    undefined,\n                    SAMErrorSubCode.PROJECTS_INVALID_REPOSITORY\n                );\n            default:\n                throw e;\n            }\n        }\n    }\n\n    /**\n     * Creates a new library reference\n     * See https://git.corp.adobe.com/pages/stormcloud/ccteams/docs/reference/api/v3/#tag/relreferences for more details\n     * @param assetId the id of the asset to create a reference for\n     * @param links the links associated with the project, we use the create reference link\n     * @returns IProjectCreateReferenceResponse representing the newly created reference\n     */\n    async createLibraryReference(assetId: string, links: IProjectLinks): Promise<IProjectCreateReferenceResponse> {\n        const href = getURLFromLinks(links, RelType.PROJECTS_REFERENCE_CREATE);\n        const response = await this._doPost(href, { 'Content-Type': JSON_MIME_TYPE }, JSON.stringify({ 'project:referenceId': assetId }), [ 201 ]);\n        return response.json();\n    }\n\n    /**\n     *\n     * @package Internal use only\n     *\n     */\n    async _issueContextAPIRequest(assetId: string, repoId: string, href: string) {\n        const body = JSON.stringify({\n            'repo:assetId': assetId,\n            'repo:repositoryId': repoId\n        });\n        const response = await this._doPost(href, {\n            'Content-Type': 'application/json'\n        }, body, [ 200 ]);\n        return response.json();\n    }\n\n    private async _getOrganizationsCollectionLink() {\n        const links = await this._discoverProjectLinks();\n        return getURLFromLinks(links, RelType.ORGANIZATIONS_COLLECTION);\n    }\n\n    @synchronized\n    async getOrganizations(resource: Resource<IOrganizationsResponse>): Promise<void> {\n        const url = await this._getOrganizationsCollectionLink();\n        await this._doGet(url, { resource });\n    }\n\n    /**\n     * Move a CSC Project to a new location\n     *\n     * @note - The projects service currently doesn't return Project Metadata in the response\n     * but that should be fixed in the future.\n     *\n     * @param targetProjectId The ID of the project to move to\n     * @param links The links associated with the project, we use the move link to move the project\n     */\n    async moveCSCProject(targetProjectId: string, links: IProjectLinks): Promise<void> {\n        const url = await getURLFromLinks(links, RelType.PROJECTS_MOVE);\n        await this._doPost(url, {\n            'Content-Type': JSON_MIME_TYPE,\n        },\n        JSON.stringify({\n            target: {\n                'repo:assetId': targetProjectId\n            }\n        }), [ 204 ]\n        );\n    }\n\n    async deleteLibraryReference(assetId: string, links: IProjectLinks): Promise<void> {\n        const href = getURLFromLinks(links, RelType.PROJECTS_REFERENCE_PRIMARY, { referenceId: assetId });\n        await this._doDelete(href, { 'Content-Type': JSON_MIME_TYPE }, [ 204 ]);\n    }\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\nimport SAMEvent from '../core/SAMEvent';\nexport const ORGANIZATIONS_CHANGED = 'organizations_changed';\nexport default class OrganizationsChangedEvent extends SAMEvent {\n\n    constructor() {\n        super(ORGANIZATIONS_CHANGED);\n    }\n}\n\nexport const OrganizationsChangedEventInstance = new OrganizationsChangedEvent();\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { ISWYAdobeAssetOrderBy } from '../interface/AssetModel';\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type AdobeAsset from './AdobeAsset';\n\nexport type SWYAdobeAssetOrderField =\n     | 'name'\n     | 'created'\n     | 'modified'\n     | 'shared'\n\nexport const OrderFieldToISWYAdobeAssetOrderBy: { [key in SWYAdobeAssetOrderField]: ISWYAdobeAssetOrderBy } = {\n    'name': 'asset_name',\n    'created': 'create_date',\n    'modified': 'modify_date',\n    'shared': 'shared_date',\n};\n\nconst OrderFieldToComparator: IComparatorMap<AdobeAsset, SWYAdobeAssetOrderField> = {\n    name(a: AdobeAsset, b: AdobeAsset): number {\n        return compareStrings(a.name, b.name);\n    },\n    shared(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.shared, b.shared);\n    },\n    created(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.created, b.created);\n    },\n    modified(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.modified, b.modified);\n    }\n};\n\nexport default class SWYAdobeAssetOrder extends createItemOrderFactory(OrderFieldToComparator) implements SAM.SWYAdobeAssetOrder {\n    static default = new SWYAdobeAssetOrder('descending', 'shared');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport {\n    getMultiValueFilterRelation,\n    type IExplicitFilter,\n    type ItemFilterRelation\n} from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport { ModernSet } from '../utils/ModernSet';\nimport type {\n    AssetSubType,\n    AssetType\n} from '../interface/AssetModel';\n\nconst AdobeAssetFilterName = 'AdobeAssetFilter';\n\nexport interface IAdobeAssetFilterOptions {\n    readonly mediaTypes?: string[];\n    readonly excludeMediaTypes?: string[];\n    readonly assetTypes?: AssetType[];\n    readonly excludeAssetTypes?: AssetType[];\n    readonly assetSubTypes?: AssetSubType[];\n    /** @package -- for internal use only */\n    readonly _isDiscarded?: boolean;\n}\n\n/**\n * For ItemSources on AssetContext and AdobeAsset, the AdobeAssetFilter is the only one used by clients today.\n * Separately, we have the USSAdobeAssetFilter which is used by clients to filter USS assets,\n * and other external filters on other sources.\n * This filter can be used to filter AdobeAsset objects by mediaType and excludeMediaType.\n * If both mediaType and excludeMediaType are specified then only mediaType\n * will be considered for filtering. If neither mediaType nor excludeMediaType are specified then all mediaTypes\n * will be considered for filtering.\n */\n\nexport default class AdobeAssetFilter implements IExplicitFilter<AdobeAsset> {\n    private readonly _mediaTypes?: ModernSet<string> = undefined;\n    private readonly _excludeMediaTypes?: ModernSet<string> = undefined;\n    private readonly _assetTypes?: ModernSet<AssetType> = undefined;\n    private readonly _excludeAssetTypes?: ModernSet<AssetType> = undefined;\n    private readonly _assetSubTypes?: ModernSet<AssetSubType> = undefined;\n    private readonly _isDiscarded?: boolean = undefined;\n\n    constructor(options?: Partial<IAdobeAssetFilterOptions>) {\n        const makeSet = (a: string[] | undefined) => a?.length ? new ModernSet(a) : undefined;\n        this._mediaTypes = makeSet(options?.mediaTypes);\n        this._excludeMediaTypes = makeSet(options?.excludeMediaTypes);\n\n        if (this._mediaTypes?.size && this._excludeMediaTypes?.size) {\n            this._mediaTypes = new ModernSet([]);\n            console.warn('AdobeAssetFilter - cannot have both mediaTypes and excludeMediaTypes. Omitting mediaTypes.');\n        }\n\n        this._assetTypes = makeSet(options?.assetTypes) as ModernSet<AssetType> | undefined;\n        this._excludeAssetTypes = makeSet(options?.excludeAssetTypes) as ModernSet<AssetType> | undefined;\n        if (this._assetTypes?.size && this._excludeAssetTypes?.size) {\n            this._assetTypes = new ModernSet([]);\n            console.warn('AdobeAssetFilter - cannot have both assetTypes and excludeAssetTypes. Omitting assetTypes.');\n        }\n\n        this._assetSubTypes = makeSet(options?.assetSubTypes) as ModernSet<AssetSubType> | undefined;\n\n        this._isDiscarded = options?._isDiscarded;\n    }\n\n    get hash(): string {\n        const stringify = (s?: Set<string>) => s?.size ? [ ...s ].sort().join(',') : '';\n        let hash = 'mediatypes=' + stringify(this._mediaTypes);\n        hash += ':excludemediatypes=' + stringify(this._excludeMediaTypes);\n        hash += ':assetTypes=' + stringify(this._assetTypes);\n        hash += ':excludeAssetTypes=' + stringify(this._excludeAssetTypes);\n        hash += ':assetSubTypes=' + stringify(this._assetSubTypes);\n        hash += (this._isDiscarded !== undefined) ? ':isDiscarded=' + this._isDiscarded : '';\n        return hash;\n    }\n\n    get mediaTypes(): Set<string> | undefined {\n        return this._mediaTypes;\n    }\n\n    get excludeMediaTypes(): Set<string> | undefined {\n        return this._excludeMediaTypes;\n    }\n\n    get assetTypes(): Set<string> | undefined {\n        return this._assetTypes;\n    }\n\n    get excludeAssetTypes(): Set<string> | undefined {\n        return this._excludeAssetTypes;\n    }\n\n    get assetSubTypes(): Set<string> | undefined {\n        return this._assetSubTypes;\n    }\n\n    get name(): string {\n        return AdobeAssetFilterName;\n    }\n\n    matches(item: AdobeAsset): boolean {\n        return Boolean((!this._excludeMediaTypes?.size || !this._excludeMediaTypes.has(item.mediaType))\n            && (!this._mediaTypes?.size || this._mediaTypes.has(item.mediaType))\n            && (!this._assetTypes?.size || item.assetType && this._assetTypes.has(item.assetType))\n            // excludeAssetTypes should match assetType = undefined\n            && (!this._excludeAssetTypes?.size || !this._excludeAssetTypes.has(item.assetType!))\n            && (!this._assetSubTypes?.size || item.assetSubType && this._assetSubTypes.has(item.assetSubType))\n            && (this._isDiscarded === undefined || this._isDiscarded === item.isDiscarded)\n        );\n    }\n\n    getRelationToFilter(other: AdobeAssetFilter): ItemFilterRelation {\n        const relations: ItemFilterRelation[] = [\n            this.getMediaRelationToFilter(other),\n            this._getAssetTypeRelationToFilter(other),\n            getMultiValueFilterRelation(this._assetSubTypes, other.assetSubTypes),\n            this._getDiscardedTypeRelationToFilter(other)\n        ];\n\n        if (relations.includes('disjoint')) { return 'disjoint'; }\n        if (relations.includes('unknown')) { return 'unknown'; }\n\n        // Since the filters can't be 'disjoint', there must be some overlap, leaving only 'unknown' and 'subset' as a\n        // possibility. Then, since all 'unknown' cases have been eliminated, the only remaining possibility is\n        // 'subset'.\n        return 'subset';\n    }\n\n    // TODO: change to private _getMediaRelationToFilter after this method is removed from\n    // public API.\n    public getMediaRelationToFilter(other: AdobeAssetFilter): ItemFilterRelation {\n        return this._getExcludeIncludeFilterRelation(this._mediaTypes, this._excludeMediaTypes, other._mediaTypes, other._excludeMediaTypes);\n    }\n\n    private _getAssetTypeRelationToFilter(other: AdobeAssetFilter): ItemFilterRelation {\n        return this._getExcludeIncludeFilterRelation(this._assetTypes, this._excludeAssetTypes, other._assetTypes, other._excludeAssetTypes);\n    }\n\n    private _getExcludeIncludeFilterRelation<T>(\n        thisInclude?: ModernSet<T>,\n        thisExclude?: ModernSet<T>,\n        otherInclude?: ModernSet<T>,\n        otherExclude?: ModernSet<T>\n    ): ItemFilterRelation {\n        // Normalize undefined to empty ModernSet\n        thisInclude = new ModernSet(thisInclude);\n        thisExclude = new ModernSet(thisExclude);\n        otherInclude = new ModernSet(otherInclude);\n        otherExclude = new ModernSet(otherExclude);\n\n        // If both includes are non-empty, and they do not overlap, they are disjoint. Assume excludes are undefined,\n        // enforced in the constructor.\n        if (getMultiValueFilterRelation(thisInclude, otherInclude) === 'disjoint') { return 'disjoint'; }\n\n        // If `other` excludes all of `this`, there is no overlap. And vice versa.\n        if (otherExclude.size && thisInclude.size && otherExclude.isSupersetOf(thisInclude)\n            || thisExclude.size && otherInclude.size && thisExclude.isSupersetOf(otherInclude)\n        ) {\n            return 'disjoint';\n        }\n        // Note: it is impractical to compute the disjoint case between two \"exclude\" filters. To be disjoint,\n        // the union of both exclude filters must be a superset of all possible values (APV). For some properties, the\n        // APV may take gigabytes to represent.\n\n        // If `otherIncludes` only partially overlaps `thisIncludes`, then the relation is 'unknown'\n        if (!thisExclude.size && !otherExclude.size && getMultiValueFilterRelation(thisInclude, otherInclude) === 'unknown') {\n            return 'unknown';\n        }\n\n        // If 'other' excludes only some of `this`, `other` only partially overlaps `this`\n        if (!thisExclude.size && otherExclude.size && getMultiValueFilterRelation(thisInclude, otherExclude) === 'unknown') {\n            return 'unknown';\n        }\n        // if `other` includes more items than `this` excludes, then `other` only partially overlaps `this`\n        if (otherInclude.size && thisExclude.size && getMultiValueFilterRelation(thisExclude, otherInclude) === 'subset') {\n            return 'unknown';\n        }\n        // if `this` excludes none of the items `other` includes, then `other` only partially overlaps `this`\n        if (!otherExclude.size && thisExclude.size && getMultiValueFilterRelation(otherInclude, thisExclude) === 'disjoint') {\n            return 'unknown';\n        }\n        // if `other` excludes some, but `this` includes all, `other` is missing some\n        if (!thisExclude.size && !thisInclude.size && !otherInclude.size && otherExclude.size) { return 'unknown'; }\n\n        if (thisExclude.size && otherExclude.size) {\n            // If `other` is a proper subset of `this`, then `other` excludes fewer items than `this`, so it can provide\n            // all. E.g. `this` = ~{A, B} and `other` = ~{A} means `this` = {C...Z} and `other` = {B...Z}. If `other`\n            // excludes the same items as `this`, then they are identical. This condition is easier to eliminate than to\n            // find all the 'unknown' cases.\n            if (otherExclude.isSubsetOf(thisExclude)) { return 'subset'; }\n            // If `this` is not a subset of `other`, then it is either disjoint or intersects. If the two are disjoint,\n            // then each is missing something, but overlaps on everything else, so relation is 'unknown'. Otherwise, if\n            // there is partial overlap, but `other` is not a subset of `this`, then each is missing something, but\n            // overlaps on everything else, so relation is 'unknown'.\n            return 'unknown';\n        }\n\n        return 'subset';\n    }\n\n    private _getDiscardedTypeRelationToFilter(other: AdobeAssetFilter): ItemFilterRelation {\n        if (this._isDiscarded === other._isDiscarded || other._isDiscarded === undefined) {\n            return 'subset';\n        }\n\n        if (this._isDiscarded === undefined) {\n            return 'unknown';\n        }\n\n        // If one is discarded and the other is not, then they are disjoint.\n        return 'disjoint';\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError from '../core/SAMError';\nimport type { IAdobeAssetFilterOptions } from './AdobeAssetFilter';\nimport AdobeAssetFilter from './AdobeAssetFilter';\nimport { SAMErrorCode } from '../core/SAMError';\nimport type AdobeAsset from './AdobeAsset';\nimport {\n    getMultiValueFilterRelation,\n    type ItemFilterRelation\n} from '../core/ItemFilter';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport { USSAssetFilterName } from './USSAssetFilterName';\nimport { FetchFields } from '../interface/USSv3Model';\n/**\n * undefined = include files not uploaded by the user\n * string[] = include files uploaded by the user using these client ids\n * 'ALL' = include all files uploaded by the user under any client id\n */\nexport type UploadedFromType = 'ALL' | string[] | undefined;\n\nexport interface IUSSAdobeAssetFilter extends IAdobeAssetFilterOptions {\n    readonly uploadedFrom?: UploadedFromType;\n\n    /**\n     * Includes the provided value in the USS query\n     * to search for assets that match the storage:assignee.id value.\n     *\n     */\n    readonly userId?: string;\n    readonly excludeInheritanceTypes?: string[];\n}\n\n/**\n * A Filter that extends AdobeAssetFilter and provides some USS Specific\n * filter options that don't apply to RAPI directory listings.\n */\nexport default class USSAdobeAssetFilter extends AdobeAssetFilter {\n    private _uploadedFrom?: UploadedFromType;\n    private _userId: string | undefined;\n    private _excludeInheritanceTypes?: Set<string> = undefined;\n\n    constructor(options?: Partial<IUSSAdobeAssetFilter>) {\n        super(options);\n        const { uploadedFrom, userId, excludeInheritanceTypes } = options ?? {};\n\n        if (uploadedFrom !== undefined) {\n            if (!uploadedFrom.length) {\n                throw SAMError.create(SAMErrorCode.UNSUPPORTED, 'Empty uploadedFrom array is not currently supported.');\n            }\n            this._uploadedFrom = uploadedFrom;\n        }\n\n        if (userId) {\n            this._userId = userId;\n        }\n\n        if (excludeInheritanceTypes) {\n            this._excludeInheritanceTypes = new Set(excludeInheritanceTypes);\n        }\n    }\n\n    get name(): string {\n        return USSAssetFilterName;\n    }\n\n    get hash(): string {\n        let hash = `${super.hash}:${this._uploadedFrom}:${this._userId}`;\n        hash += ':excludeinheritancetypes=' + (this._excludeInheritanceTypes?.size ? `${[ ...this._excludeInheritanceTypes ].sort().join(',')}` : 'none');\n        return hash;\n    }\n\n    get uploadedFrom(): UploadedFromType {\n        return this._uploadedFrom;\n    }\n\n    /**\n     * Matches the provided userId to the value of storage:assignee.id in the service.\n     *\n     * @TODO_Deprecation [SAM-3813] will be removed in future releases in favor of using AdobeAsset.searchChildren searching\n     * for items in users /cloud-content.\n     *\n     * {@link AdobeAsset.searchChildren()}\n     */\n    get userId(): string | undefined {\n        return this._userId;\n    }\n\n    /**\n     * Excludes assets that are inherited or are inheritable of the types included. For example including\n     * \"am.cc:inherited.cc:studentAssignment.repo:assetId\" would exclude all assets that are within student\n     * assignment directories. Including \"am.cc:inheritable.cc:studentAssignment.repo:assetId\" would exclude\n     * all assets that ARE student assignment directories.\n     */\n    get excludeInheritanceTypes(): Set<string> | undefined {\n        return this._excludeInheritanceTypes;\n    }\n\n    matches(item: AdobeAsset): boolean {\n        // NOTE: storageAssignee is lazy-loaded from R-API data, but not USS. All USS loaders must use\n        //       LazyLoadManager to clear the dirty flag for storageAssignee.\n        if (this._userId && this._userId !== item.storageAssignee.id) {\n            return false;\n        }\n\n        /** Filter       Item         createdFromUpload    Return value\n         * -----------------------------------------------------------\n         * undefined    *            *                    super.matches()\n         * 'ALL'        'xyz'        true                 super.matches()\n         * ['xyz']      'xyz'        true                 super.matches()\n         * 'ALL'        *            false                false\n         * ['xyz']      undefined    *                    false\n         * ['xyz']      'pdq'        *                    false\n         * ['xyz']      *            false                false\n         *\n         * */\n\n        if (\n            Array.isArray(this._uploadedFrom)\n            && item.createdFromUpload\n            && !this._uploadedFrom.includes(item.createdByClientId ?? '')\n        ) {\n            return false;\n        }\n\n        if (\n            (this._uploadedFrom === 'ALL'\n            || Array.isArray(this._uploadedFrom))\n            && !item.createdFromUpload\n        ) {\n            return false;\n        }\n\n        if (this._excludeInheritanceTypes?.has(FetchFields.StudentAssignmentAssetId) && item.isChildOfStudentAssignment) {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n\n    getRelationToFilter(existingFilter: USSAdobeAssetFilter): ItemFilterRelation {\n        if (existingFilter.name !== USSAssetFilterName) {\n            // Currently we don't support switching between the AdobeAssetFilter and the\n            // USSAssetFilter.\n            // TODO [SAMJS-821]: cast AAF as USSAAF. If existingFilter is AAF, it works the same as USSAAF where\n            //    USSAAF-specific fields are undefined.\n            oneTimeWarning('USSAdobeAssetFilter', 'Cannot switch between an AdobeAssetFilter and a USSAdobeAssetFilter');\n            return 'disjoint';\n        }\n\n        // If they both have ID's and they both are not equal we can assume\n        // they are disjointed.\n        if (this._userId && existingFilter.userId && this._userId !== existingFilter.userId) {\n            return 'disjoint';\n        }\n\n        if (this._excludeInheritanceTypes && existingFilter._excludeInheritanceTypes) {\n            // Convert to a format that can be easily compared\n            const thisFilterExcludeInheritanceTypes = [ ...this._excludeInheritanceTypes ].sort();\n            const existingFilterExcludeInheritanceTypes = [ ...existingFilter._excludeInheritanceTypes ].sort();\n            // TODO [SAMJS-821]: this is comparing if the two arrays are the same *instance*, not the same *values*,\n            //      so will always be disjoint. Also, \"exclude\" relations are tricky. \"Exclude {A}\" entirely overlaps\n            //      \"exclude {A, B}\" but \"exclude {A, B}\" only partially overlaps \"exclude {A}\". See\n            //      AdobeAssetFilter.excludeMediaTypes for example on how to compare \"exclude\" filters.\n            if (thisFilterExcludeInheritanceTypes !== existingFilterExcludeInheritanceTypes) {\n                return 'disjoint';\n            }\n        }\n\n        // TODO [SAMJS-821] since there are additional 'disjoint' cases detected below, this can return 'unknown'\n        //    when the filters are actually 'disjoint'\n        if ((this.excludeInheritanceTypes && !existingFilter.excludeInheritanceTypes) || (!this.excludeInheritanceTypes && existingFilter.excludeInheritanceTypes)) {\n            return 'unknown';\n        }\n\n        // If both the new filter and the existing filter are arrays\n        // meaning they are requesting a specific applications client id\n        // and they are both different, this means the list is disjoint because\n        // if let's say the existing filter is app 'xyz' and the new one is 'zzz'\n        // they cannot share any items.\n        if (Array.isArray(this.uploadedFrom)\n            && Array.isArray(existingFilter.uploadedFrom)\n        ) {\n            const arrayRelationship = getMultiValueFilterRelation(this.uploadedFrom, existingFilter.uploadedFrom);\n            if (arrayRelationship === 'disjoint') {\n                return 'disjoint';\n            }\n            if (arrayRelationship === 'unknown') {\n                return 'unknown';\n            }\n        }\n\n        /**\n         * If the new filter has uploadedFrom undefined and the existing filter\n         * is defined that means we could possibly borrow some items from the new list.\n         */\n        if (!this.uploadedFrom && existingFilter.uploadedFrom) {\n            return 'unknown';\n        }\n\n        if (this.uploadedFrom === 'ALL' && Array.isArray(existingFilter.uploadedFrom)) {\n            return 'unknown';\n        }\n\n        if (!this.userId && existingFilter.userId) {\n            return 'unknown';\n        }\n\n        // Call into super to handle all AdobeAsset filter cases.\n        // TODO [SAMJS-821]: since the above will return 'unknown' before calling super, it will miss cases that are\n        //      disjoint in the super.\n        return super.getRelationToFilter(existingFilter);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { createItemOrderFactory } from '../core/ItemOrder';\nimport type Version from './AssetVersion';\nimport { compareValues } from '../core/ItemOrder';\n\n\nexport type AssetVersionField = 'created';\n\nconst OrderFieldToComparator: IComparatorMap<Version, AssetVersionField> = {\n    created(a: Version, b: Version): number {\n        return compareValues(a.created, b.created);\n    }\n};\n\nexport default class AssetVersionOrder extends createItemOrderFactory(OrderFieldToComparator) implements SAM.AssetVersionOrder {\n    static default = new AssetVersionOrder('descending', 'created');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { AssignmentAdobeAssetMetadata, ClassroomAssetsContext } from './AssignmentModel';\nimport type { IServiceLink, LinkRequirements } from './LinkUtils';\nimport { RelType } from './LinkUtils';\nimport type { AssetLinks, IAppMetadata, RepositoryMetadata } from './RepositoryModel';\nimport type { IRemoteStudentAssignmentFile } from './StudentAssignmentFileModel';\n\nexport type Assignee = {\n    displayName: string;\n    email: string;\n    id: string;\n}\n\nexport type IRemoteAssignee = {\n    displayName?: string;\n    email?: string;\n    id: string;\n}\n\nexport interface IStudentAssignmentsIndexResponse {\n    _links: IStudentAssignmentsIndexLinks\n}\n\nexport interface IStudentAssignmentsIndexLinks {\n    [RelType.STUDENT_ASSIGNMENTS_COLLECTION]: IServiceLink;\n    [RelType.STUDENT_ASSIGNMENTS_PRIMARY]: IServiceLink;\n}\n\nexport const STUDENT_ASSIGNMENTS_INDEX_LINKS: LinkRequirements = {\n    [RelType.STUDENT_ASSIGNMENTS_COLLECTION]: [ 'assignmentId', 'assignmentCode', 'includeStudentDocuments' ],\n    [RelType.STUDENT_ASSIGNMENTS_PRIMARY]: [ 'studentAssignmentId', 'includeStudentDocuments' ],\n};\n\nexport interface IStudentAssignmentsActions {\n    [RelType.ASSIGNMENTS_START]?: IServiceLink;\n    [RelType.ASSIGNMENTS_RETURN]?: IServiceLink;\n    [RelType.ASSIGNMENTS_SUBMIT]?: IServiceLink;\n}\n\nexport type StudentAssignmentLinks = AssetLinks & IStudentAssignmentsActions\n\nexport enum StudentAssignmentStatus {\n    NOT_STARTED = 'NOT_STARTED',\n    IN_PROGRESS = 'IN_PROGRESS',\n    RETURNED = 'RETURNED',\n    SUBMITTED = 'SUBMITTED',\n}\n\nexport const ALL_STATUSES = [ StudentAssignmentStatus.IN_PROGRESS, StudentAssignmentStatus.NOT_STARTED, StudentAssignmentStatus.RETURNED, StudentAssignmentStatus.SUBMITTED ];\n\nexport interface IRemoteStudentAssignmentAppMetadata extends Pick<IAppMetadata, 'cc:inherited'> {\n    /** ID of the student assignment. Not started student assignment will not have 'repo:assetId' */\n    'repo:assetId'?: string,\n    /** Owner of this assignment */\n    'assignment:assignee': Assignee;\n    /** The submitted work for the assignment */\n    'assignment:submission'?: AssignmentAdobeAssetMetadata;\n    /** Status */\n    'assignment:submissionStatus': StudentAssignmentStatus;\n    /** Date the assignment was submitted */\n    'assignment:submissionDate'?: string;\n}\n\nexport interface IRemoteStudentAssignment extends IRemoteStudentAssignmentAppMetadata, Pick<RepositoryMetadata, '_embedded'> {\n    /** Computed ID from id attribute of assignment:assignee */\n    computedAssigneeId?: string;\n    /** Student assignment links */\n    _links: StudentAssignmentLinks;\n    /** Student assignment files */\n    children: IRemoteStudentAssignmentFile[]\n    /** Classroom context data */\n    'classroom:context': ClassroomAssetsContext;\n}\n\nexport interface IStudentAssignmentReturnData {\n    /** The current set of student assignment links. */\n    links: StudentAssignmentLinks;\n    /** The student assignment ID that is being returned. */\n    studentAssignmentId: string;\n    /** The submission ID that is being returned for this assignment. */\n    submissionId: string;\n}\n\nexport interface IStudentAssignmentStartData {\n    /** The assignment ID that is being started. */\n    assignmentId: string;\n    /** The current set of student assignment links. */\n    links: StudentAssignmentLinks;\n}\n\nexport interface IStudentAssignmentSubmitClassroomContextData {\n    /** The assignment ID. This or studentAssignmentId is needed to submit an assignment. */\n    assignmentId?: string;\n    /** The current set of student assignment links. */\n    links: StudentAssignmentLinks;\n    /** The current status of the student assignment, when not provided the status is assumed to not be NOT_STARTED. */\n    status?: StudentAssignmentStatus;\n    /** The student assignment ID that is being submitted. This or assignmentId is needed to submit an assignment. */\n    studentAssignmentId?: string;\n    /** The submission ID that is being submitted for this assignment. */\n    submissionId: string;\n}\n\nexport interface IStudentAssignmentSubmitData {\n    /** The current set of student assignment links. */\n    links: StudentAssignmentLinks;\n    /** The student assignment ID that is being submitted. This or studentAssignmentId is needed to submit an assignment. */\n    studentAssignmentId: string;\n    /** The submission ID that is being submitted for this assignment. */\n    submissionId: string;\n}\n\nexport enum StudentAssignmentOwner {\n    Any = 'ANY',\n    Self = 'SELF'\n}\n\nexport interface StudentAssignmentOptionalParams {\n    /** The current user ID */\n    currentUserId?: string;\n    /** The student submission status */\n    status?: StudentAssignmentStatus[];\n    /** load student work files if true */\n    loadDocuments?: boolean;\n}\n\nexport interface StudentAssignmentCompleteParams extends StudentAssignmentOptionalParams {\n    /** The assignment code */\n    assignmentCode?: string;\n    /** The assignment ID */\n    assignmentId?: string;\n}\n\nexport interface IStudentAssignmentsPageSpec {\n    count: number;\n}\n\nexport interface IStudentAssignmentsLinks {\n    [RelType.STUDENT_ASSIGNMENTS_COLLECTION]: IServiceLink;\n}\n\nexport interface IStudentAssignmentResponse {\n    children: IRemoteStudentAssignment[];\n    _page: IStudentAssignmentsPageSpec;\n    _links: IStudentAssignmentsLinks;\n}\n\nexport type RequiredStudentAssignmentFilterOptions = (\n    {assignmentCode?: never; assignmentId: string;}\n    | { assignmentCode: string; assignmentId?: never}\n);\n\nexport interface GetStudentAssignmentOptions extends Pick<StudentAssignmentOptionalParams, 'loadDocuments'>{}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport InterfaceBase from './InterfaceBase';\nimport type { IRemoteStudentAssignment,  IStudentAssignmentReturnData, IStudentAssignmentStartData, IStudentAssignmentSubmitData, IStudentAssignmentResponse, StudentAssignmentCompleteParams, GetStudentAssignmentOptions, IStudentAssignmentsIndexLinks, IStudentAssignmentsIndexResponse, IStudentAssignmentsLinks } from './StudentAssignmentModel';\nimport { STUDENT_ASSIGNMENTS_INDEX_LINKS } from './StudentAssignmentModel';\nimport type { HeaderMap } from './LinkUtils';\nimport { RelType, getURLFromLinks, validateLinks } from './LinkUtils';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { cache, key } from '../core/decorators';\nimport { getSAMVersionRequestHeader } from '../utils/classroomUtils';\n\ninterface StudentAssignmentsListingBaseOptions {\n    includeStudentDocuments: boolean;\n}\n\ninterface StudentAssignmentListingIdentifier {\n    [identifier: string]: string;\n}\n\ntype StudentAssignmentsListingOptions = StudentAssignmentsListingBaseOptions | StudentAssignmentListingIdentifier;\n\nconst DefaultStudentAssignmentsListingOptions: StudentAssignmentsListingBaseOptions = {\n    includeStudentDocuments: false,\n};\n\nfunction validateRequiredStudentAssignmentLinks(links: any) {\n    return validateLinks(links, STUDENT_ASSIGNMENTS_INDEX_LINKS);\n}\n\nfunction getStudentAssignmentsListingPath(links: IStudentAssignmentsLinks, options: StudentAssignmentsListingOptions): string {\n    // Use defaults first and then overwrite any provided options.\n    const userOptions = { ...DefaultStudentAssignmentsListingOptions, ...options };\n\n    // Get appropriate link from collection and populate any templated options.\n    const url = new URL(getURLFromLinks(links, RelType.STUDENT_ASSIGNMENTS_COLLECTION, userOptions));\n\n    return url.toString();\n}\n\nconst headers = getSAMVersionRequestHeader();\n\nexport default class StudentAssignmentsInterface extends InterfaceBase {\n    @cache(validateRequiredStudentAssignmentLinks)\n    private async _discoverLinks(@key rootHref: string): Promise<IStudentAssignmentsIndexLinks> {\n        const response: IStudentAssignmentsIndexResponse = await this._getResponse(rootHref, { headers });\n        return response._links;\n    }\n\n    private _getEndpointHref(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.ASSIGNMENTS_HOST}${endpoint}`;\n    }\n\n    async discoverStudentAssignmentLinks(): Promise<IStudentAssignmentsIndexLinks> {\n        return this._discoverLinks(this._getEndpointHref('/api/v1/index'));\n    }\n\n    async getStudentAssignments(data: StudentAssignmentCompleteParams): Promise<IStudentAssignmentResponse> {\n        let identifier: StudentAssignmentListingIdentifier = {};\n        if (data.assignmentId) {\n            identifier = { assignmentId: data.assignmentId };\n        } else if (data.assignmentCode) {\n            identifier = { assignmentCode: data.assignmentCode };\n        } else {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Either assignmentCode or assignmentId must be provided');\n        }\n\n        const { loadDocuments = false, ...otherData } = data;\n        const dataForQuery = {  ...otherData };\n\n        // remove `undefined` and empty values from the data object\n        Object.keys(dataForQuery).forEach((key) => {\n            const value = dataForQuery[key as keyof Omit<StudentAssignmentCompleteParams, 'loadDocuments'>];\n            if (value === '' || value === undefined || Array.isArray(value) && value.length === 0) {\n                delete dataForQuery[key as keyof Omit<StudentAssignmentCompleteParams, 'loadDocuments'>];\n            }\n        });\n\n        // loadDocuments is deprecated on the Hume call; switch to includeStudentDocuments here.\n        const options = { ...identifier, ...dataForQuery, includeStudentDocuments: loadDocuments };\n\n        const links = await this.discoverStudentAssignmentLinks();\n        const url = getStudentAssignmentsListingPath(links, options);\n\n        const response: IStudentAssignmentResponse = await this._getResponse(url, { headers });\n\n        return response;\n    }\n\n    async getStudentAssignment(studentAssignmentId: string, options?: GetStudentAssignmentOptions, additionalHeaders?: HeaderMap): Promise<IRemoteStudentAssignment> {\n        const loadDocuments: boolean = options?.loadDocuments ?? false;\n\n        const preparedOptions: any = { studentAssignmentId, includeStudentDocuments: loadDocuments, ...options };\n\n        const links = await this.discoverStudentAssignmentLinks();\n        const url = getURLFromLinks(links, RelType.STUDENT_ASSIGNMENTS_PRIMARY, preparedOptions);\n\n        return this._getResponse(url, { headers: { ...headers, ...additionalHeaders } });\n    }\n\n    /**\n     * @description Calls the return API for a student assignment.\n     * @param data The information necessary for calling the return API.\n     * @returns A promise that the assignment has been returned.\n     */\n    async return(data: IStudentAssignmentReturnData): Promise<IRemoteStudentAssignment> {\n        const { links, studentAssignmentId, submissionId } = data;\n\n        const url = getURLFromLinks(links, RelType.ASSIGNMENTS_RETURN, { studentAssignmentId, submissionId });\n        const response = await this._doPost(url, headers, undefined, [ 200 ]);\n        return response.json();\n    }\n\n    /**\n     * @description Calls the start API for a student assignment.\n     * @param data The information necessary for calling the start API.\n     * @returns A promise that resolves to the interface for the remote student assignment.\n     */\n    async start(data: IStudentAssignmentStartData): Promise<IRemoteStudentAssignment> {\n        const { assignmentId, links } = data;\n\n        const url = getURLFromLinks(links, RelType.ASSIGNMENTS_START, { assignmentId });\n        const response = await this._doPost(url, headers, undefined, [ 200 ]);\n        return response.json();\n    }\n\n    /**\n     * @description Calls the submit API for a student assignment.\n     * @param data The information necessary for calling the submit API.\n     * @returns A promise that the assignment has been submitted.\n     */\n    async submit(data: IStudentAssignmentSubmitData): Promise<IRemoteStudentAssignment> {\n        const { links, studentAssignmentId, submissionId } = data;\n\n        const url = getURLFromLinks(links, RelType.ASSIGNMENTS_SUBMIT, { studentAssignmentId, submissionId });\n        const response = await this._doPost(url, headers, undefined, [ 200 ]);\n        return response.json();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n * Copyright 2021 Adobe Systems Incorporated\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type jsonpatch from 'json-patch';\n\nimport { default as SAMError, ProblemType, SAMErrorCode } from '../core/SAMError';\nimport { synchronized } from '../core/decorators';\nimport { isDeepEqual } from '../core/ObjectUtils';\nimport { SAMObjectEventEmitter } from '../core/SAMObjectEventEmitter';\nimport { default as ChangeEvent, CHANGE } from '../core/ChangeEvent';\nimport type { IEventMap } from '../core/ITypedEventEmitter';\nimport type { ONSAssetLabel, ONSObjectProperties, ONSResource, ONSResourceType } from './ONSResource';\nimport type { ONSChangedAssetInfo } from './ONSEvent';\nimport { ONSAssetChangeEvent } from './ONSEvent';\nimport { getRetryAfterHeader, JSON_PATCH_MIME_TYPE, RelType, getURLFromLinks } from '../interface/LinkUtils';\nimport type { ONSContext } from './ONSContext';\n\nconst ONS_SUBSCRIPTION_MIME_TYPE = 'application/vnd.adobecloud.subscription+json';\nconst ONS_SUBSCRIPTION_AUTH_HEADER = 'Authorization';\nconst MAX_RETRY_ATTEMPTS: number = 3;\nconst MIN_RETRY_INTERVAL_MS: number = 10; // 10 msec\n\nexport type ONSObjectMap = Map<string, ONSObjectProperties>;\n\nexport type SubscriptionConfig = {\n    maxSubscriptionPerLongPoll?: number,\n    maxAssetsPerRequest?: number,\n    onsAxonServiceName?: string,\n};\n\nexport enum SubscriptionMonitoringStatus {\n    Active,\n    Inactive,\n    Registering\n}\n\n/**\n * Properties used to configure each asset in the ONS subscription.\n *\n * directoryLevel\n *   self: Notified only when the directory asset itself changes.\n *   shallow: Notified when the directory asset or any of its immediate children change.\n *   deep: Notified when the directory asset or any of its children (recursively) change.\n * includeResources: Array of resources to monitor (if omitted, only repo metadata is monitored)\n */\n\n// Default properties for assets - includes annotation resources\nconst defaultAssetProperties: { includeResources: ONSResource[] } = {\n    includeResources: [\n        { reltype: 'api:annotation' },\n        { reltype: 'api:metadata/repository' },\n        { reltype: 'api:metadata/application' },\n        { reltype: 'api:ac/policy' }\n    ]\n};\n\nconst defaultPLSAssetListProperties: { includeLabels: ONSAssetLabel[] } = {\n    includeLabels: [ 'favorite', 'lastAccessDate' ]\n};\n\ntype ONSCreateRequestObject = { id: string } & ONSObjectProperties;\ntype ONSCreateRequestObjects = ONSCreateRequestObject[];\n\ntype ONSCreateRequestBody = {\n    id?: string,\n    objects: ONSCreateRequestObjects,\n    device: {\n        id: string\n    },\n    expiresAt: number\n}\n\nfunction createObjectsRequestBody(onsObjects: ONSObjectMap): ONSCreateRequestObjects {\n    const objects: ONSCreateRequestObjects = [];\n    onsObjects.forEach((properties, id) => {\n        if (properties.type === 'asset') {\n            objects.push({ id, ...defaultAssetProperties, ...properties });\n        } else if (properties.type === 'assetList') {\n            objects.push({ id, ...defaultPLSAssetListProperties, ...properties });\n        }\n    });\n\n    return objects;\n}\n\nexport class ONSSubscriptionChangeEvent extends ChangeEvent {\n    constructor(\n        readonly fromCache: boolean\n    ) {\n        super();\n    }\n}\n\nexport interface ONSSubscriptionEventMap extends IEventMap {\n    [CHANGE]: ONSSubscriptionChangeEvent;\n}\n\nexport interface ONSCachedSubscription {\n    id: string;\n    href: string;\n    onsObjects: { [id: string]: ONSObjectProperties };\n    expiresAt?: number;\n}\n\n/**\n* Interface to register ONS subscription and listen for change events.\n*/\nexport class ONSSubscription extends SAMObjectEventEmitter<ONSSubscriptionEventMap> {\n    private _lastError?: any;\n    private _retryTimeout?: ReturnType<typeof setTimeout>;\n    private _retryChangeLogTimeout?: ReturnType<typeof setTimeout>;\n    private _nextChangeLogLinks?: any;\n    private _pendingONSObjects: ONSObjectMap = new Map();\n    private _watchedONSObjects: ONSObjectMap = new Map();\n    private _initializedFromCache: boolean = false;\n    private _subscriptionId?: string;\n    private _subscriptionHref?: string;\n    private _expiresAt?: number;\n    private _continuationToken?: string;\n    private _monitoringStatus: SubscriptionMonitoringStatus = SubscriptionMonitoringStatus.Inactive;\n\n    // Default interval between retry attempts in seconds if no Retry-After header value is available.\n    static DEFAULT_RETRY_INTERVAL_SEC = 0;\n\n    constructor(\n        private _onsContext: ONSContext,\n        cachedSubscription?: ONSCachedSubscription\n    ) {\n        super(_onsContext._core);\n        if (cachedSubscription) {\n            const { id, href, onsObjects, expiresAt } = cachedSubscription;\n            this._subscriptionId = id;\n            this._subscriptionHref = href;\n            this._expiresAt = expiresAt;\n            this._watchedONSObjects = new Map(Object.entries(onsObjects || {}));\n\n            // We check if we are given watchedAssetId's and this will\n            // indicate that we are loading them from cache.\n            this._initializedFromCache = this._watchedONSObjects.size > 0;\n        }\n    }\n\n    get subscriptionId(): string | undefined {\n        return this._subscriptionId;\n    }\n    get subscriptionHref(): string | undefined {\n        return this._subscriptionHref;\n    }\n    get expiresAt(): number {\n        return this._expiresAt ?? 0;\n    }\n\n    get lastError(): any {\n        return this._lastError;\n    }\n\n    get watchedONSObjects(): ONSObjectMap {\n        return this._watchedONSObjects;\n    }\n\n    get continuationToken(): string | undefined {\n        return this._continuationToken;\n    }\n\n    set continuationToken(continuationToken: string | undefined) {\n        this._continuationToken = continuationToken;\n    }\n\n    get monitoringStatus(): SubscriptionMonitoringStatus {\n        return this._monitoringStatus;\n    }\n\n    set monitoringStatus(newStatus: SubscriptionMonitoringStatus) {\n        this._monitoringStatus = newStatus;\n    }\n\n    public abort(): boolean {\n        if (this._retryTimeout) {\n            clearTimeout(this._retryTimeout);\n            this._retryTimeout = undefined;\n            this.logInfo(`Subscription ${this.subscriptionId} retry got aborted`);\n            return true;\n        }\n        return false;\n    }\n\n    get pendingONSObjects(): ONSObjectMap { return this._pendingONSObjects; }\n\n    set pendingONSObjects(pendingONSObjects: ONSObjectMap) {\n        this._pendingONSObjects = new Map(pendingONSObjects);\n        this._update();\n    }\n\n    @synchronized\n    private async _update(tryAttempt: number = 0) {\n        // Abort any retry attempts as we might need to remove, add\n        // or update subscriptions which may cancel out previous\n        // requests.\n        this.abort();\n        const ONSObjects = this._pendingONSObjects;\n\n        //This makes a comparison of the \"new\" id's just added and the\n        //previous assets that were added (watchedAssets);\n\n        if (isDeepEqual(ONSObjects, this._watchedONSObjects)) {\n            if (this._lastError) {\n                // If we had an error creating or updating the subscription, but then we revert back to the\n                // previous state, we need to clear the error otherwise we'll be stuck with an error!\n                this._lastError = undefined;\n                // Emit a change event to tell ONSInterface that we can begin\n                // the longpoll request.\n                this.emit(CHANGE);\n            } else if (this._initializedFromCache) {\n                // If we initialized the subscription with information\n                // from the cache and the assets being added by the client\n                // are exactly the same, we still want to notify the ONSInterface\n                // that it can begin the longpoll request otherwise it wont.\n                this.emit(CHANGE, new ONSSubscriptionChangeEvent(true));\n            }\n            return;\n        }\n\n        this.logInfo(`Setting ${ONSObjects.size} object Id(s) for ${this.subscriptionId || '<pending subscription id>'}`);\n\n        try {\n            if (ONSObjects.size === 0) {\n                this.logInfo(`Deleting subscription ${this.subscriptionId} (requested objects no longer exist)`);\n                this.monitoringStatus = SubscriptionMonitoringStatus.Inactive;\n                await this._deleteSubscriptionFromServer();\n            } else if (this._subscriptionHref) {\n                this.logDebug(\n                    `Updating subscription ${this.subscriptionId} on the server with objects`,\n                    ONSObjects,\n                );\n                await this._updateSubscriptionOnServer(ONSObjects);\n            } else {\n                this.logDebug(\n                    `Creating new subscription with objects`,\n                    ONSObjects,\n                );\n                this.monitoringStatus = SubscriptionMonitoringStatus.Inactive;\n                await this._createSubscriptionOnServer(ONSObjects);\n            }\n            // Add the new ids to the \"old\" ids list so we can track changes later on when even newer ids are added to this subscription.\n            this._watchedONSObjects = ONSObjects;\n            this._lastError = undefined;\n            this.emit(CHANGE);\n        } catch (err) {\n            this.logError(`Error updating subscription ${this.subscriptionId}:`, err);\n            this._lastError = err;\n            this.emit(CHANGE);\n\n            // Schedule a retry for later if there's an error\n            if (tryAttempt < MAX_RETRY_ATTEMPTS) {\n                let retryAfter = (getRetryAfterHeader((err as any).response?.headers) || ONSSubscription.DEFAULT_RETRY_INTERVAL_SEC) * 1000;\n                retryAfter = Math.max(MIN_RETRY_INTERVAL_MS, retryAfter);\n                this._retryTimeout = setTimeout(() => {\n                    this._retryTimeout = undefined;\n                    this._update(tryAttempt + 1);\n                },\n                retryAfter);\n            }\n        }\n    }\n\n    private async _parseSubscriptionResponse(operation: string, getResponse: () => Promise<Response>) {\n        const response = await getResponse();\n\n        if (response.status < 200 || response.status >= 300) {\n            let errMsg = `operation ${operation} with http response.status: ${response.status}`;\n\n            if (response.status === 403) {\n                const jsonError = await response.json();\n                if (jsonError.type === ProblemType.SUBSCRIPTION_COUNT) {\n                    errMsg = `Maximum number of subscriptions per user per device exceeded (${jsonError.max})`;\n                }\n            }\n\n            this.logError(errMsg);\n            throw SAMError.createWithResponseAndDescription(response, errMsg);\n        }\n\n        const json = await response.json();\n\n        if (!json.id || !json._links || !json._links.self || !json._links.self.href) {\n            const errMsg = `No subscription ID or href was returned in subscribe response.`;\n            this.logError(errMsg);\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, errMsg, { response });\n        }\n\n        this._subscriptionId   = json.id;\n        this._subscriptionHref = json._links.self.href;\n\n        if (json.expiresAt) {\n            this._expiresAt = json.expiresAt;\n        }\n    }\n\n    private async _createRequestBody(onsObjects?: ONSObjectMap): Promise<string> {\n        const objects = createObjectsRequestBody(onsObjects ?? this.watchedONSObjects);\n        const deviceId = await this._core._environment.getDeviceId();\n        const requestBody: ONSCreateRequestBody = {\n            id: this.subscriptionId,\n            objects,\n            device: { id: deviceId },\n            expiresAt: Date.now() + this._core._environment.getValue('ONS_SUBSCRIPTION_TIME_TO_LIVE')\n        };\n        return JSON.stringify(requestBody);\n    }\n\n    private async _createSubscriptionOnServer(onsObjects: ONSObjectMap): Promise<void> {\n        const href = await this._onsContext.getLink(RelType.SUBSCRIPTION_CREATE);\n        const requestBody = await this._createRequestBody(onsObjects);\n        return this._parseSubscriptionResponse('create',\n            () => this._core._environment.fetch(href, {\n                method: 'POST',\n                body: requestBody,\n                authHeader: ONS_SUBSCRIPTION_AUTH_HEADER,\n                headers: {\n                    'Content-Type': ONS_SUBSCRIPTION_MIME_TYPE\n                }\n            }));\n    }\n\n    private async _updateSubscriptionOnServer(onsObjects: ONSObjectMap): Promise<void> {\n\n        const operations: jsonpatch.OpPatch[] = [];\n        onsObjects.forEach((properties: ONSObjectProperties, id: string) => {\n            if (!this._watchedONSObjects.has(id)) {\n                const defaultProps = properties.type === 'asset' ? defaultAssetProperties : defaultPLSAssetListProperties;\n                const item: jsonpatch.AddPatch = { 'op': 'add', 'path': '/objects/-', 'value': { id, ...defaultProps, ...properties } };\n                operations.push(item);\n            }\n        });\n        this._watchedONSObjects.forEach((properties: ONSObjectProperties, id: string) => {\n            if (!onsObjects.has(id)) {\n                const item: jsonpatch.RemovePatch = { 'op': 'remove', 'path': `/objects/id=${id}` };\n                operations.push(item);\n            }\n        });\n\n        const requestBody: string = JSON.stringify(operations);\n\n        try {\n            await this._parseSubscriptionResponse('update',\n                () => this._core._environment.fetch(this._subscriptionHref!, {\n                    method: 'PATCH',\n                    body: requestBody,\n                    authHeader: ONS_SUBSCRIPTION_AUTH_HEADER,\n                    headers: {\n                        'Content-Type': JSON_PATCH_MIME_TYPE\n                    }\n                }));\n            this.logDebug(`Updated subscription ${this._subscriptionId} on the server.`);\n        } catch (err) {\n            this.logError(`Error updating subscription ${this._subscriptionId} on the server:`, err);\n            // If we get a 404 updating a subscription, we should fall back to creating a new subscription instead\n            if ((err as SAMError).code === SAMErrorCode.NOT_FOUND) {\n                this.logWarn(`Subscription ${this._subscriptionId} no longer exists`);\n                this.logDebug(`Creating a new subscription for objects(s):`, onsObjects);\n                this.monitoringStatus = SubscriptionMonitoringStatus.Inactive;\n                this._subscriptionHref = undefined;\n                return this._createSubscriptionOnServer(onsObjects);\n            }\n            throw err;\n        }\n    }\n\n    private async _deleteSubscriptionFromServer(): Promise<void> {\n        this.logInfo(`Deleting subscription ${this._subscriptionId}`);\n\n        try {\n            // Note: There's no way to reach this point with _subscriptionHref undefined, so we assert that it's defined\n            await this._core._environment.fetch(this._subscriptionHref!, {\n                method: 'DELETE',\n                authHeader: ONS_SUBSCRIPTION_AUTH_HEADER\n            });\n        } catch (error) {\n            // We tried.\n            this.logError(`Unable to delete subscription: ${this._subscriptionHref}`, error);\n        }\n\n        // We clear the subscription even if we fail to delete it - ONS will auto-delete orphaned subscriptions after some time anyway,\n        // so we don't need to be aggressive about retrying\n        this._subscriptionId = undefined;\n        this._subscriptionHref = undefined;\n        this._expiresAt = undefined;\n        this.monitoringStatus = SubscriptionMonitoringStatus.Inactive;\n    }\n\n    async refreshSubscriptionExpiryDate(): Promise<void> {\n        this.logDebug(`Refreshing expiry date on subscription ${this.subscriptionId}`);\n        const requestBody = await this._createRequestBody();\n        return this._parseSubscriptionResponse(\n            'update',\n            () => this._core._environment.fetch(\n                this.subscriptionHref!,\n                {\n                    method: 'PUT',\n                    body: requestBody,\n                    authHeader: ONS_SUBSCRIPTION_AUTH_HEADER,\n                    headers: {\n                        'Content-Type': ONS_SUBSCRIPTION_MIME_TYPE\n                    }\n                }\n            )\n        )\n            .catch(() => {\n                // We tried to update the expiry date on the subscription and failed\n                // Lets try and update\n                return this._update();\n            });\n    }\n\n    private async _fetchChangeLogPage(changedAssets: Map<string, ONSChangedAssetInfo>): Promise<boolean> {\n        const options = { subscriptionId: this._subscriptionId! };\n\n        const href = this._nextChangeLogLinks\n            ? getURLFromLinks(this._nextChangeLogLinks, RelType.GENERIC_NEXT, options)\n            : await this._onsContext.getLink(RelType.ONS_CHANGELOG, options);\n\n        // Note: Unlike the other ONS calls, this uses the standard Authorization header (other ONS calls use X-User-Token)\n        // This is confusing and error-prone, so I'd like them to standardize on the Authorization header for all calls, but\n        // we have to live with this inconsistency for now.\n        // ONS introduced a new directive header, all clients are expected to pass ons-repometa to\n        // indicate they are ready to handle compact URI for repository metadata resource\n        const response = await this._core._environment.fetch(href, { headers: { 'directive': 'ons-repometa' } });\n\n        if (response.status !== 200) {\n            let errMsg = `Unexpected response fetching change log: ${response.status}`;\n            // In the case that it's 403 and the type is\n            // ONS_PROBLEM_LIMIT_CHANGELOGRETENTION this should mean that the\n            // the current Changelog Token is expired and the we should get\n            // a new \"next\" link.\n            if (response.status === 403) {\n                const parsedResponse = await response.json();\n                if (parsedResponse.type === ProblemType.LIMIT_CHANGELOGRETENTION) {\n                    errMsg = `Changelog retention period expired, discarding \"next\" link and fetching changelog again.`;\n                    // When we throw an error below, it will cause the caller\n                    // to retry this call and by setting _nextChangeLogLinks to undefined\n                    // it will then fetch a new \"next\" link above.\n                    this._nextChangeLogLinks = undefined;\n                }\n            }\n\n            this.logError(errMsg);\n            throw SAMError.createWithResponseAndDescription(response, errMsg);\n        }\n        const json = await response.json();\n\n        // From the response, determine which asset ids changed\n        const changedSubscriptions = json['ons:changedSubscriptions'] ?? [];\n        const changedSubscription = changedSubscriptions.find((subscriptionInfo: any) => subscriptionInfo['ons:subscriptionId'] === this._subscriptionId);\n        const changes = changedSubscription?.['ons:changes'] ?? [];\n        changes.forEach((assetInfo: any) => {\n            const assetId = assetInfo['repo:assetId'];\n            const onsResourceInfo = assetInfo['ons:resources'] ?? [];\n            const onsResourcesChanged: ONSResourceType[] = [ ...Object.keys(onsResourceInfo) as ONSResourceType[] ];\n            const parentAssetId = assetInfo['ons:subscribedDirectoryAssetId'];\n            const changedLabels = assetInfo['asset:labels'];\n            const annotationId: string | undefined = onsResourceInfo['api:annotation']?.['repo:resource']?.['annotation_id'];\n\n            if (assetId) {\n                // If the asset is already in changedAssets, merge the next changed resource so we\n                // don't lose any previous resources that were added here.\n                if (changedAssets.has(assetId)) {\n                    const existingAsset = changedAssets.get(assetId)!;\n                    existingAsset.changedResources = [ ...new Set([ ...existingAsset.changedResources!, ...onsResourcesChanged ]) ];\n\n                    if (annotationId) {\n                        existingAsset.annotationIds = [ ...new Set([ ...(existingAsset.annotationIds || []), ...[ annotationId ] ]) ];\n                    }\n                    changedAssets.set(assetId, existingAsset);\n                } else {\n                    changedAssets.set(assetId, {\n                        parentAssetId,\n                        changedLabels,\n                        changedResources: onsResourcesChanged,\n                        ...(annotationId && { annotationIds: [ annotationId ] })\n                    });\n                }\n            }\n        });\n\n        this._nextChangeLogLinks = json?._links;\n        return this._nextChangeLogLinks?.next?.nextPage;\n    }\n\n    /**\n     * Fetch the changed assets ids in the subscription, and emit a change event on the parent ONS Interface for any changed assets.\n     * The reason this API emits events rather than just returning the changed assets is so we can have robust retry logic - if it fails\n     * to fetch the change log it'll schedule a retry with an appropriate backoff, so it automatically recovers. The ONS Interface can\n     * simply call fetchAndNotifyChanges on a subscription that it knows has changes, and the subscription will take responsibility for\n     * eventually fetching and emitting notifications for these changes, even if it has to retry.\n     *\n     * This API is stateful, so if you call it when the subscription changed, it will emit a change event for those assets, but if you call it\n     * again (and there are no further changes), it will not emit an event.\n     */\n    @synchronized\n    async fetchAndNotifyChanges(attempt: number = 0): Promise<void> {\n        this.logInfo(`Fetching ChangeLog for subscription ${this._subscriptionId}...`);\n\n        // If we got another notification of a change, this causes us to retry immediately, and cancels any pending retry\n        if (this._retryChangeLogTimeout) {\n            clearTimeout(this._retryChangeLogTimeout);\n        }\n\n        const retry = (error: any) => {\n            const retryAfter = getRetryAfterHeader(error.response?.headers) * 1000;\n            const interval = Math.max(retryAfter, this._core._environment.getRetryInterval(attempt));\n\n            this.logInfo(`Retrying change log fetch in ${interval}ms`);\n            this._retryChangeLogTimeout = setTimeout(() => this.fetchAndNotifyChanges(attempt + 1), interval);\n        };\n\n        const changedAssets: Map<string, ONSChangedAssetInfo> = new Map();\n        try {\n            let hasMorePages = true;\n            while (hasMorePages) {\n                hasMorePages = await this._fetchChangeLogPage(changedAssets);\n            }\n        } catch (error) {\n            this.logError(`Error fetching change log`, error);\n            retry(error);\n        }\n\n        // Even if there's an error, we always notify of any changes we did manage to fetch - for example, if the\n        // first page succeeded, but the second page didn't, when we retry we'll retry from the second page.\n        if (changedAssets.size) {\n            this.logDebug(`Changed asset(s):`, changedAssets);\n            this._onsContext.emit(CHANGE, new ONSAssetChangeEvent(changedAssets));\n        }\n    }\n\n    // This is called to check whether the subscription still exists on the server.\n    // The ONS long poll will sometimes request the client to\n    // validate its subscriptions. If the subscription was deleted, it'll recreate it.\n    async validate() {\n        if (!this._subscriptionHref) {\n            // If we're requesting to watch at least one asset id, and don't have a subscription at all,\n            // something must have gone wrong creating it - we attempt to create again.\n            if (this._pendingONSObjects.size > 0) {\n                this.logWarn(`Objects exist for subscription but no _subscriptionHref was found, trying to _update() again...`);\n                return this._update();\n            }\n            this.logDebug(`Subscription has no assets and no _subscriptionHref set`);\n            return;\n        }\n\n        let checkResponse;\n        try {\n            // ONS spec says to GET (vs HEAD). Why?\n            checkResponse = await this._core._environment.fetch(this._subscriptionHref, {\n                authHeader: ONS_SUBSCRIPTION_AUTH_HEADER\n            });\n            this.logInfo(`Subscription ${this._subscriptionId} exists on the server`);\n        } catch (error) {\n            this.logError(`Error checking ${this._subscriptionId}, it does not exist on the server`, error);\n            return;\n        }\n\n        // If we can't find the subscription, we need to make a new one.\n        if (![ 200, 201, 204 ].includes(checkResponse.status)) {\n            this.logInfo(`ONS subscription has been invalidated. Creating new subscription...`);\n            this.monitoringStatus = SubscriptionMonitoringStatus.Inactive;\n            this._subscriptionHref = undefined;\n            this._subscriptionId = undefined;\n            this._watchedONSObjects = new Map();\n            return this._update();\n        }\n    }\n\n    /**\n     * Logs a debug message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logDebug(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logDebug(message, 'Subscription', ...optionalParams);\n    }\n\n    /**\n     * Logs an info message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logInfo(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logInfo(message, 'Subscription', ...optionalParams);\n    }\n\n    /**\n     * Logs a warning message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logWarn(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logWarn(message, 'Subscription', ...optionalParams);\n    }\n\n    /**\n     * Logs an error message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     * @remarks If the first optional parameter is an Error object, the message will be appended with the error message.\n     */\n    logError(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logError(message, 'Subscription', ...optionalParams);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n * Copyright 2020 Adobe Systems Incorporated\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n// TODO: Remove after all clients have upgraded to UXP 6.2\n// https://jira.corp.adobe.com/browse/UXP-19257\nimport 'abort-controller/polyfill';\n\nimport { getRetryAfterHeader, RelType } from '../interface/LinkUtils';\nimport { ONSFirstLongPollCompletedEvent, ONSFirstLongPollStartedEvent, ONSMonitoringStatusChangedEvent, ONS_FIRST_LONG_POLL_COMPLETED, ONS_FIRST_LONG_POLL_STARTED, ONS_MONITORING_STATUS_CHANGED, OnsMonitoringStatus } from './ONSEvent';\nimport type { ONSCachedSubscription, ONSSubscriptionChangeEvent } from './ONSSubscription';\nimport { ONSSubscription } from './ONSSubscription';\nimport { synchronized, memoize } from '../core/decorators';\nimport { SAMObjectEventEmitter } from '../core/SAMObjectEventEmitter';\nimport type { ONSContext } from './ONSContext';\nimport type { ONSWorkerEventMap, ONSWorkerInterface } from './ONSWorker.interface';\nimport type { default as Cache } from '../core/Cache';\nimport { NotFound } from '../core/Cache';\nimport type { ONSObjectProperties } from './ONSResource';\n\n// Set the x-poll-timeout request header value (in seconds) for ONS long poll requests\n// This controls the frequency of the ONS server long poll responses.\nconst ONS_POLLTIMEOUT_SECONDS = 160;\n\nexport const cacheKey = 'ONS_SUBSCRIPTIONS';\n\nconst ONS_LONG_POLL_AUTH_HEADER = 'X-User-Token';\n\ninterface OnsLongPollWorkerEventMap extends ONSWorkerEventMap {\n    [ONS_FIRST_LONG_POLL_STARTED]: ONSFirstLongPollStartedEvent;\n    [ONS_FIRST_LONG_POLL_COMPLETED]: ONSFirstLongPollCompletedEvent;\n}\n\n/**\n * Interface to register ONS subscription and listen for change events.\n * Design notes:\n * Polling will only happen when the following three conditions are ALL met:\n *  1. start() has been called (and stop() has not been called).\n *  2. watch() has been called with a non-empty set of asset ids.\n *  3. The document is visible (document.visibilityState === 'visible').\n */\nexport class ONSLongPollWorker extends SAMObjectEventEmitter<OnsLongPollWorkerEventMap> implements ONSWorkerInterface {\n    private _abortController?: AbortController;\n    private _pollURL?: string;\n    private _subscriptions: ONSSubscription[] = [];\n    private _maxAssetsPerSubscription: number = 5;\n    private _cachedSubscriptionsUsed: boolean = false;\n    private _cache: Cache;\n    private _ONSObjectIds: Set<string> = new Set();\n\n    constructor(\n        readonly _onsContext: ONSContext,\n    ) {\n        super(_onsContext._core);\n        this._cache = _onsContext._core._environment.cache;\n    }\n\n    get isActive() {\n        return Boolean(this._abortController);\n    }\n\n    get subscriptions(): ONSSubscription[] {\n        return this._subscriptions;\n    }\n\n    async ensureReady(): Promise<boolean> {\n        return true;\n    }\n\n    async deinitialize(): Promise<boolean> {\n        this.stop();\n        return true;\n    }\n\n    /**\n     * Start\n     */\n    async start(): Promise<void> {\n        if (this.isActive) {\n            this.logDebug(`ONS Long Poll worker is already started! Skipping this request!`);\n            return;\n        }\n        this.logInfo(`Starting ONS Long Poll Worker...`);\n        this._abortController = new AbortController();\n        this._poll();\n        this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Active));\n    }\n\n    /**\n     * Stop\n     */\n    stop() {\n        if (!this.isActive) {\n            this.logDebug(`ONS Long Poll worker is already stopped! Skipping this request!`);\n            return;\n        }\n\n        this.logInfo(`Stopping ONS Long Poll Worker...`);\n        this.subscriptions.forEach((sub: ONSSubscription) => sub.abort());\n        const abortController = this._abortController;\n        delete this._abortController;\n        this._abortController = undefined;\n        abortController?.abort();\n        this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Inactive));\n    }\n\n    @synchronized\n    private async _restartMonitoring() {\n        const activeSubscriptionIds: string[] = this._activeSubscriptionIds;\n\n        // we don't want to create a bogus long pollURL if\n        // there is no subscriptions...\n        const newPollURL = activeSubscriptionIds.length === 0 ? undefined : await this._onsContext.getLink(RelType.NOTIFICATIONS_LONGPOLL, {\n            includeJournal: 'false', subscriptionId: activeSubscriptionIds });\n\n        const isUrlChanged: boolean = this._pollURL !== newPollURL;\n        this._pollURL = newPollURL;\n        if (this.isActive && isUrlChanged) {\n            this.stop(); // Only stop if the URL has changed.\n            this.start(); // Ensure polling is started.\n        }\n    }\n\n    // This is used to notify the client that the initial long poll has been started along with the information\n    // whether cached subscriptions were used or not. It can be used by the clients to avoid any refresh of its cached\n    // data if cached subscriptions were used.\n    @memoize\n    private _notifyFirstLongPollStarted() {\n        this.emit(ONS_FIRST_LONG_POLL_STARTED, new ONSFirstLongPollStartedEvent(this._cachedSubscriptionsUsed));\n    }\n\n    // This is used to notify the client that the initial long poll has been completed along with the information\n    // whether they were expired or not. It can be used by the clients to avoid any refresh of its cached\n    // data if cached subscriptions were used.\n    @memoize\n    private _notifyFirstLongPollCompleted(expired: boolean) {\n        this.emit(ONS_FIRST_LONG_POLL_COMPLETED, new ONSFirstLongPollCompletedEvent(expired));\n    }\n\n    // ONS Subscriptions are more efficient if they are kept alive and updated so we check whether the subscription\n    // is within 10% of its TTL and refresh as necessary\n    private _validateAndUpdateSubscriptionExpiration() {\n        const now = Date.now();\n\n        // We calculate the remaining time to live being within a 10% zone of the current time based\n        // on environment set TTL with a minimum time remaining being 5 mins.\n        const ttl = Math.max(\n            this._core._environment.getValue('ONS_SUBSCRIPTION_TIME_TO_LIVE') * 0.1,\n            this._core._environment.getValue('ONS_SUBSCRIPTION_RENEW_TIME')\n        );\n        this.subscriptions\n            .filter(sub => sub.watchedONSObjects.size && (sub.expiresAt - now) < ttl)\n            .forEach(sub => sub.refreshSubscriptionExpiryDate());\n    }\n\n    private _truncateAssetIdsByMaxSizeIfNeeded(plsAssetListIds: Set<string>, assetIds: Set<string>): Set<string> {\n        const maxTotalAssets = this._maxAssetsPerSubscription * this._subscriptions.length;\n\n        // Combine all assets into one set\n        const combinedAssetIds = new Set<string>([ ...plsAssetListIds, ...assetIds ]);\n\n        // Prioritize PLS Asset Lists over individual assets during truncation\n        // since one list subscription can efficiently monitor changes for multiple assets within that list\n        if (combinedAssetIds.size > maxTotalAssets) {\n            this.logInfo(`Total number of assets (${combinedAssetIds.size}) exceeds the maximum allowed by ONS. Limiting to ${maxTotalAssets}`);\n            // TODO:\n            //this._analytics.reportError('ONSSubscriptionError', `Requested assets exceed number allowed. Count: ${allAssets.size}, Max: ${maxTotalAssets}`);\n            const truncatedArray = Array.from(combinedAssetIds).slice(0, maxTotalAssets);\n            return new Set<string>(truncatedArray);\n        }\n\n        return combinedAssetIds;\n    }\n\n    private async _getAndParseCachedSubscriptions(): Promise<ONSCachedSubscription[]> {\n        // @TODO SAM-2845 Prevent data from being retrieved from cache\n        // until it is enabled again in the future.\n        if (!this._onsContext.cacheEnabled) {return [];}\n\n        const existingCreatedSubscriptions = await this._cache.getItem(cacheKey);\n        if (existingCreatedSubscriptions !== NotFound) {\n            try {\n                return JSON.parse(existingCreatedSubscriptions).subscriptions;\n            } catch (e) {\n                this.logInfo('error parsing cached subscriptions');\n            }\n        }\n        return [];\n    }\n\n    private get _activeSubscriptionIds(): string[] {\n        return Array.from(this._subscriptions)\n            .filter(sub => sub.subscriptionId && sub.watchedONSObjects.size > 0) // Note: watchedONSObjects not assets\n            .map(sub => `${sub.subscriptionId}`)\n            .sort();\n    }\n\n    private _onSubscriptionChange = (event?: ONSSubscriptionChangeEvent) => {\n        // IF change are notified let's make sure to update the cache as well.\n        if (!event?.fromCache) {\n            this._cachedSubscriptionsUsed = false;\n        }\n        this._updateCachedSubscriptions();\n        this._restartMonitoring();\n    };\n\n    @synchronized\n    private async _updateCachedSubscriptions() {\n        // @TODO SAM-2845 where this is defined for more information.\n        // Prevent data from being written to cache\n        // until it is enabled again in the future.\n        if (!this._onsContext.cacheEnabled) { return; }\n\n        const newCachedSubscriptions: ONSCachedSubscription[] = [];\n        this._subscriptions.forEach((subscription) => {\n            const { subscriptionId, subscriptionHref, pendingONSObjects, expiresAt } = subscription;\n            // If the ONSSubscription doesn't have an ID or Href\n            // that means it wasn't created on the server and\n            // it doesn't have any information to cache.\n            if (!subscriptionId || !subscriptionHref) {\n                return;\n            }\n\n            const updatedCache: ONSCachedSubscription = {\n                id: subscriptionId,\n                href: subscriptionHref,\n                onsObjects: Object.fromEntries(pendingONSObjects),\n                expiresAt: expiresAt || Date.now() + this._core._environment.getValue('ONS_SUBSCRIPTION_TIME_TO_LIVE')\n            };\n\n            newCachedSubscriptions.push(updatedCache);\n        });\n\n        await this._cache.setItem(\n            cacheKey,\n            JSON.stringify({ subscriptions: newCachedSubscriptions }),\n\n            // This ensures that the cached subscription will expire the same time\n            // that the subscription expires on the server.\n            this._core._environment.getValue('ONS_SUBSCRIPTION_TIME_TO_LIVE')\n        );\n    }\n\n    private async _ensureSubscriptions() {\n        // This will create and store instances of ONSSubscription\n        // the number created will be the number of MAX_SUBSCRIPTIONS\n        // set by SAM.js or service (we don't actually create subscriptions\n        // on the server though, unless they have any assets to monitor)\n\n        const subscriptionConfig = await this._onsContext.getSubscriptionConfig();\n        const maxSubscriptions = subscriptionConfig.maxSubscriptionPerLongPoll || this._core._environment.getValue('ONS_DEFAULT_MAX_SUBSCRIPTIONS');\n        this._maxAssetsPerSubscription = subscriptionConfig.maxAssetsPerRequest || this._core._environment.getValue('ONS_DEFAULT_MAX_ASSETS_PER_SUBSCRIPTION');\n\n        if (maxSubscriptions > this._subscriptions.length) {\n            // Just because we are creating an ONSSubscription does not mean\n            // we are creating a subscription on the service. We actually\n            // create the max number of local ONSSubscription allowed by ONS but only\n            // create the subscription on the service if there are assets on that subscription.\n\n            const parsedCachedSubscriptions = await this._getAndParseCachedSubscriptions();\n            this._cachedSubscriptionsUsed = parsedCachedSubscriptions.length > 0;\n\n            // Add new subscriptions\n            for (let i = this._subscriptions.length; i < maxSubscriptions; ++i) {\n                // If we have a corresponding cached subscription\n                // pull the information from cache and construct\n                // the ONSSubscription with data from the cache.\n                // If the cached subscription information is out of date,\n                // it will be handled inside the ONSSubscription.\n                const sub = new ONSSubscription(\n                    this._onsContext,\n                    parsedCachedSubscriptions[i]\n                );\n\n                this._subscriptions.push(sub);\n                sub.on('change', this._onSubscriptionChange);\n            }\n        } else if (maxSubscriptions < this._subscriptions.length) {\n            // Remove subscriptions over the limit\n            for (let i = maxSubscriptions; i < this._subscriptions.length; ++i) {\n                const sub = this._subscriptions[i];\n                sub.pendingONSObjects = new Map();\n                sub.off('change', this._onSubscriptionChange);\n            }\n            this._subscriptions.length = maxSubscriptions; // Removes the overflow from the array\n        }\n    }\n\n    async watch(assetIdsToMonitor: Set<string>, plsAssetListIdsToMonitor: Set<string>) {\n        await this._ensureSubscriptions();\n        this._ONSObjectIds = this._truncateAssetIdsByMaxSizeIfNeeded(\n            plsAssetListIdsToMonitor,\n            assetIdsToMonitor\n        );\n\n        const getProps = (id: string): ONSObjectProperties => {\n            if (plsAssetListIdsToMonitor.has(id)) {\n                const props: ONSObjectProperties = {\n                    type: 'assetList',\n                    listLevel: 'shallow'\n                };\n                return props;\n            }\n            const asset = this._onsContext._core.hostAssetContext._assetPool.getLocalItemById(id);\n            const props: ONSObjectProperties = {\n                type: 'asset',\n                ...(asset?.isFolder ? { directoryLevel: 'shallow' } : {}),\n            };\n            return props;\n        };\n\n        // Map from subscription id to current assets being monitored,\n        // (in the form of a map from the asset id to its properties)\n        // minus ones we no longer need to monitor:\n        // Creates an array and each entry is a\n        // Map() that represents the assets in the subscription.\n\n        const existingObjectIds = new Set<string>();\n\n        const subscriptionToOnsObjects: Map<string, ONSObjectProperties>[] = this._subscriptions.map(\n            sub => {\n                const onsObjects = new Map<string, ONSObjectProperties>();\n                sub.pendingONSObjects.forEach((properties, id) => {\n                    if (this._ONSObjectIds.has(id) && existingObjectIds.add(id)) {\n                        onsObjects.set(id, getProps(id));\n                    }\n                });\n                return onsObjects;\n            }\n        );\n\n        // We assign the ons objects to subscriptions such that we fill up the first subscription first\n        // before creating new ones. Note that when this was first implemented in SAM.js, we\n        // would try to spread assets across as many subscriptions as possible, because ONS didn't\n        // tell us which asset in a subscription changed - but now that we have the changelog API,\n        // it's better to concentrate assets in as few subscriptions as possible.\n\n        let nextIndex = 0;\n        this._ONSObjectIds.forEach(id => {\n            if (existingObjectIds.has(id)) {return;}\n            // find a subscription with space\n            while (\n                subscriptionToOnsObjects[nextIndex].size >= this._maxAssetsPerSubscription\n            ) {\n                nextIndex++;\n            }\n\n            subscriptionToOnsObjects[nextIndex].set(id, getProps(id));\n        });\n\n        this._subscriptions.forEach((sub, index) => {\n            sub.pendingONSObjects = subscriptionToOnsObjects[index];\n\n            if (sub.pendingONSObjects.size > 0) {\n                this.logDebug(\n                    `Subscription #${index} (${sub.subscriptionId}) now has ${sub.pendingONSObjects.size} items.`\n                );\n            }\n        });\n    }\n\n    /**\n     * _poll sets up the longpoll request with retries if needed.\n     *\n     * @param attempt This tracks the number of attempts already made so we can back off in needed.\n     * @returns void;\n     */\n    private async _poll(attempt: number = 0) {\n        const retry = (error: any, interval: number = 0) => {\n            interval = Math.max(this._core._environment.getRetryInterval(attempt), interval);\n\n            const abortController = this._abortController;\n            if (!abortController) {\n                return;\n            }\n\n            this.logInfo(`Retrying long poll in ${interval}ms`);\n            const timeout = setTimeout(() => this._poll(attempt + 1), interval);\n            abortController.signal.addEventListener('abort', () => {\n                if (abortController !== this._abortController) {\n                    clearTimeout(timeout);\n                }\n            });\n        };\n\n        const abortController = this._abortController;\n        if (!abortController) {\n            this.logInfo(`No abort controller...`);\n            return;\n        }\n        try {\n            // this.pollURL can be undefined at start up when watch didn't have a time to build it yet,\n            // also if we deleted all subscriptions calling watch with empty set.\n            //\n            // _pollURL is set by calling watch() which calls _ensureSubscriptions() which then sets\n            // an event handler for a \"change\" event on each subscription created (ONSSubscription). The subscription\n            // will emit a \"change\" event for various cases but mainly for when assetIds are updated on\n            // the subscription. Once a change is emitted, the\n            // the assigned _onSubscriptionChangeFun() is called and then calls _onSubScriptionChange().\n            // then finally sets the URL. @TODO maybe we can streamline this process a bit more.\n            if (this._pollURL === undefined) {\n                this.logInfo(`Poll URL undefined...`);\n                // just returning here because when pollUrl get populated it will call _stop(), _start()\n                return;\n            }\n            // Go ahead and notify clients about first long poll.\n            this._notifyFirstLongPollStarted();\n\n            const href = this._pollURL as string;\n            // Give the service a 20s buffer to respond on their end before terminating on our end\n            const requestTimeoutMs = (ONS_POLLTIMEOUT_SECONDS + 20) * 1000;\n            const response = await this._core._environment.fetch(href, {\n                signal: abortController.signal,\n                authHeader: ONS_LONG_POLL_AUTH_HEADER,\n                headers: {\n                    'x-poll-timeout': `${ ONS_POLLTIMEOUT_SECONDS }`\n                },\n                requestTimeoutMs\n            });\n\n            if ([ 200, 201, 204 ].includes(response.status)) {\n                const json = await response.json();\n\n                this._notifyFirstLongPollCompleted(false);\n                this.logInfo(`Successful long poll for ${href}`);\n\n                // Sometimes (frequently) we get a 20x response, and nothing has changed.\n                if (json && json.subscriptions && json.subscriptions.length > 0) {\n                    this.logInfo(`Subscriptions changed: ${json.subscriptions.join(', ')}`);\n\n                    // Trigger the changed subscriptions to fetch changes via the changelog API:\n                    // Note that ONS does not yet support a single changelog for multiple subscriptions, so we have\n                    // to call the changelog separately for each subscription right now.\n                    json.subscriptions.forEach((id: string) => {\n                        const subscription = this.subscriptions.find(sub => sub.subscriptionId === id);\n                        subscription?.fetchAndNotifyChanges();\n                    });\n\n                    // After a successful long poll we should do a quick check on the expire times on the\n                    // active subscriptions.\n                    this._validateAndUpdateSubscriptionExpiration();\n\n                    // We don't really need this as part of the public API, but it makes the tests much easier,\n                    // so we can abort the polling.\n                    this.emit('notified');\n                }\n\n                // If ONS is worried that our subscription is invalid, verify it is still there. (ONS will do this\n                // every few hours no matter what.)\n                if (json && json.checkSubscriptions && json.checkSubscriptions.length > 0) {\n                    this.logInfo(`Checking subscriptions for subscriptions to check ${json.checkSubscriptions.length}`);\n                    json.checkSubscriptions.forEach((id: string) => {\n                        const subscription = this.subscriptions.find(sub => sub.subscriptionId === id);\n                        if (subscription) {\n                            subscription.validate();\n                        }\n                    });\n                }\n\n                this._pollURL = json && json._links && json._links.next && json._links.next.href;\n                this._poll();\n            } else if (response.status === 404) {\n                this._notifyFirstLongPollCompleted(true);\n                this.logInfo(`404 Response long poll for ${href}, subscription missing or expired`);\n                // If the response is a 404, we've somehow lost the subscriptions. Make a new one.\n                this.subscriptions.forEach((subscription: ONSSubscription) => {\n                    if (subscription.subscriptionId) {\n                        subscription.validate();\n                    }\n                });\n                // We need to retry here because if subscription will be validated on the server\n                // then 'change' event will not be emitted and we will stop polling here.\n                retry(undefined, this._core._environment.getValue('MAX_RETRY_INTERVAL'));\n            } else {\n                this.logInfo(`Unexpected response, trying again ${href}`);\n                // Otherwise, follow the retry logic defined by the ONS team.\n                retry(undefined, getRetryAfterHeader(response.headers) * 1000);\n            }\n        } catch (error) {\n            // If we aborted this request, we don't want to retry.\n            // But only if we aborted it locally. If it was aborted elsewhere, we want to retry.\n            // (AbortController is used for timeouts in Proxy#fetch)\n            if (abortController.signal.aborted && abortController !== this._abortController) {\n                this.emit('aborted');\n                this._notifyFirstLongPollCompleted(true);\n                return;\n            }\n            this.logInfo(`Error trying to create long poll request`);\n            retry(error);\n        }\n    }\n\n    /**\n     * Logs a debug message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logDebug(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logDebug(message, 'Long Poll', ...optionalParams);\n    }\n\n    /**\n     * Logs an info message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logInfo(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logInfo(message, 'Long Poll', ...optionalParams);\n    }\n\n    /**\n     * Logs a warning message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logWarn(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logWarn(message, 'Long Poll', ...optionalParams);\n    }\n\n    /**\n     * Logs an error message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     * @remarks If the first optional parameter is an Error object, the message will be appended with the error message.\n     */\n    logError(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logError(message, 'Long Poll', ...optionalParams);\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n * Copyright 2020 Adobe Systems Incorporated\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport uuid from 'uuid';\n\nimport type { ONSContext } from './ONSContext';\nimport type { ONSHeaderMap, ONSWorkerEventMap, ONSWorkerInterface } from './ONSWorker.interface';\nimport type { AxonVirtualConnection } from './AxonVirtualConnection';\nimport { synchronized } from '../core/decorators';\nimport { default as TypedEventEmitter } from '../core/TypedEventEmitter';\nimport type { ErrorMessage } from './AxonFrame.interface';\nimport type { default as ChangeEvent } from '../core/ChangeEvent';\nimport type { AxonClient } from './AxonClient';\nimport { ONSSubscription, SubscriptionMonitoringStatus } from './ONSSubscription';\nimport { ONS_MONITORING_STATUS_CHANGED, OnsMonitoringStatus, ONSMonitoringStatusChangedEvent } from './ONSEvent';\nimport type { ONSObjectProperties } from './ONSResource';\n\n\ninterface Subscription {\n    id: string;\n    continuationToken?: string;\n}\n\ninterface CheckSubscription {\n    id: string;\n}\n\ninterface Notification {\n    subscriptions?: Subscription[];\n    checkSubscriptions?: CheckSubscription[];\n}\n\ninterface RegistrationRequest {\n    subscriptions: Subscription[];\n}\n\ninterface Message {\n    operationName: string;\n    operationId: string;\n    body: Notification | RegistrationRequest;\n}\n\nexport class ONSAxonWorker extends TypedEventEmitter<ONSWorkerEventMap> implements ONSWorkerInterface {\n    private _axonVc: AxonVirtualConnection | undefined;\n    private _isActive: boolean = false;\n    private _subscriptions: ONSSubscription[] = [];\n    private _maxAssetsPerSubscription: number = 100;\n    private _ONSObjectIds: Set<string> = new Set();\n    private _registrationOperationIds: Set<string> = new Set();\n\n    constructor(\n        readonly _onsContext: ONSContext,\n    ) {\n        super();\n    }\n\n    get isActive(): boolean {\n        return this._isActive;\n    }\n\n    get subscriptions(): ONSSubscription[] {\n        return this._subscriptions;\n    }\n\n    /**\n     * Handles ONS Message event.\n     * @param event - Message.\n     */\n    private _onVcMessage = (message: Message) => {\n        switch (message.operationName) {\n        case 'notification':\n            this._handleNotification(message.body);\n            break;\n        case 'error':\n            if (this._registrationOperationIds.has(message.operationId)) {\n                this._registrationOperationIds.clear();\n                this.logError('ONS Error received for a registration operation. Will close the ONS Virtual Connection.', message);\n                this._closeAxonVc().then(() => {\n                    this._restartMonitoring();\n                });\n                return;\n            }\n            this.logError('Unknown ONS Error received.', message);\n            break;\n        default:\n            this.logWarn('Unknown Axon Message received', message);\n            break;\n        }\n    };\n\n    /**\n     * Handles ONS Error event.\n     * @param event - Message.\n     */\n    private _onVcError = (event: ErrorMessage) => {\n        this.logError('Axon Error received', event);\n    };\n\n    /**\n     * Handles Deleted VC event.\n     */\n    private _onVcDeleted = () => {\n        this.logInfo('Axon Virtual Connection has been deleted');\n        this.deinitialize();\n        this.ensureReady();  // Re-create the Virtual Connection.\n    };\n\n    private _onVcSessionStatusChanged = () => {\n        if (this._axonVc?.isActive()) {\n            this.logDebug('Virtual Connection status changed to Active. Restarting ONS Monitoring...');\n            this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Restarting));\n            this._restartMonitoring();\n        } else {\n            this.logDebug('Virtual Connection status changed to non-Active.');\n            this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Inactive));\n        }\n    };\n\n    private _handleNotification(notification: Notification) {\n        this.logDebug('Axon Notification received', notification);\n        notification.subscriptions?.forEach((sub: Subscription) => {\n            // Find subscription |sub| in the subscriptions array.\n            const subscription = this.subscriptions.find(s => s.subscriptionId === sub.id);\n            if (!subscription) {\n                this.logWarn(`Subscription ${sub.id} not found in the subscriptions array. Skipping notification handling.`);\n                return;\n            }\n\n            // Mark subscription as monitored.\n            subscription.monitoringStatus = SubscriptionMonitoringStatus.Active;\n\n            // Update subscription's continuation token.\n            subscription.continuationToken = sub.continuationToken;\n\n            // Trigger the changed subscription to fetch changes via the changelog API:\n            // Note that ONS does not yet support a single changelog for multiple subscriptions, so we have\n            // to call the changelog separately for each subscription right now.\n            subscription.fetchAndNotifyChanges();\n        });\n\n        // Quick check on the expire times on the active subscriptions.\n        this._validateAndUpdateSubscriptionExpiration();\n\n        // If ONS is worried that our subscription is invalid, verify it is still there. (ONS will do this\n        // every few hours no matter what.)\n        notification.checkSubscriptions?.forEach((checkSub: CheckSubscription) => {\n            const subscription = this.subscriptions.find(s => s.subscriptionId === checkSub.id);\n            if (subscription) {\n                subscription.validate();\n            }\n        });\n    }\n\n    private async _ensureAxonVc(): Promise<AxonVirtualConnection> {\n        const axonClient = await this._onsContext._core._getAxonClient();\n        if (!await axonClient.session.ensureEstablished()) {\n            throw new Error('Axon Session could not be established!');\n        }\n\n        if (this._axonVc && await this._axonVc.ensureActive()) {\n            return this._axonVc;\n        }\n\n        this.logDebug('ONS Virtual Connection is not active. Will create a new one...');\n        this._deactivate();\n\n        const onsSubscriptionConfig = await this._onsContext.getSubscriptionConfig();\n        if (!onsSubscriptionConfig?.onsAxonServiceName?.length) {\n            throw new Error('Failed to determine ONS Service Id');\n        }\n\n        const headers: ONSHeaderMap = {\n            'x-api-key': this._onsContext._core._environment.getValue('CLIENT_ID'),\n            'locale': axonClient.config.locale };\n        this._axonVc = await axonClient.session.createVc(onsSubscriptionConfig.onsAxonServiceName, headers);\n        this._axonVc.on('message', this._onVcMessage);\n        this._axonVc.on('error', this._onVcError);\n        this._axonVc.on('deleted', this._onVcDeleted);\n        this._axonVc.on('session_status_changed', this._onVcSessionStatusChanged);\n        return this._axonVc;\n    }\n\n    // ONS Subscriptions are more efficient if they are kept alive and updated so we check whether the subscription\n    // is within 10% of its TTL and refresh as necessary\n    private _validateAndUpdateSubscriptionExpiration() {\n        const now = Date.now();\n\n        // We calculate the remaining time to live being within a 10% zone of the current time based\n        // on environment set TTL with a minimum time remaining being 5 mins.\n        const ttl = Math.max(\n            this._onsContext._core._environment.getValue('ONS_SUBSCRIPTION_TIME_TO_LIVE') * 0.1,\n            this._onsContext._core._environment.getValue('ONS_SUBSCRIPTION_RENEW_TIME')\n        );\n        this.subscriptions\n            .filter(sub => sub.watchedONSObjects.size && (sub.expiresAt - now) < ttl)\n            .forEach(sub => sub.refreshSubscriptionExpiryDate());\n    }\n\n    private async _closeAxonVc() {\n        if (this._axonVc?.isActive()) {\n            const axonClient = await this._onsContext._core._getAxonClient();\n            if (await axonClient.session.ensureEstablished()) {\n                try {\n                    if (!await axonClient.session.deleteVc(this._axonVc)) {\n                        this.logWarn('Failed to delete ONS Virtual Connection');\n                    }\n                } catch (error) {\n                    this.logWarn('Failed to delete ONS Virtual Connection', error);\n                }\n            }\n        }\n        this._deactivate();\n    }\n\n    private _deactivate() {\n        this.subscriptions.forEach(sub => sub.monitoringStatus = SubscriptionMonitoringStatus.Inactive);\n        if (!this._axonVc) { return; }\n        this._axonVc.off('message', this._onVcMessage);\n        this._axonVc.off('error', this._onVcError);\n        this._axonVc.off('deleted', this._onVcDeleted);\n        this._axonVc = undefined;\n    }\n\n    /**\n     * Deinitializes the ONS Axon Worker and closes its underlying Virtual Connection to ONS.\n     * @returns A promise that resolves to true if the worker is deinitialized, false otherwise.\n     */\n    @synchronized\n    async deinitialize(): Promise<boolean> {\n        this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Inactive));\n        if (!this._axonVc) { return true; }  // VC is already deinitialized.\n        const vc = this._axonVc;\n        this._deactivate();\n        let axonClient: AxonClient;\n        if (!vc.isActive()) { return true; }  // VC is inactive.\n        try {\n            axonClient = await this._onsContext._core._getAxonClient();\n            if (!axonClient.isConnected()) {\n                return true;  // Axon Client is already disconnected.\n            }\n            if (!await axonClient.session.ensureEstablished()) {\n                throw new Error('Axon Session could not be established!');\n            }\n        } catch (error) {\n            this.logWarn('ONS Virtual Connection deletion skipped', error);\n            return true;\n        }\n        try {\n            return await axonClient.session.deleteVc(vc);\n        } catch (error) {\n            this.logError('Failed to delete ONS Virtual Connection', error);\n            return false;\n        }\n    }\n\n    /**\n     * Ensures that the ONS Virtual Connection is created and active.\n     * @returns A promise that resolves to true if the ONS Virtual Connection is ready, false otherwise.\n     */\n    @synchronized\n    async ensureReady(): Promise<boolean> {\n        try {\n            const vc = await this._ensureAxonVc();\n            if (!await vc.ensureActive()) {\n                this.logError('Failed to acquire an active ONS Virtual Connection!');\n                this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Error));\n                return false;\n            }\n            return true;\n        } catch (error) {\n            this.logError('Failed to get the ONS Virtual Connection', error);\n            this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Error));\n            return false;\n        }\n    }\n\n    @synchronized\n    async start(): Promise<void> {\n        if (this.isActive) {\n            this.logDebug('ONS Axon Worker is already active. Skipping this request!');\n            return;\n        }\n\n        this.logDebug('Starting ONS Axon Worker...');\n        this._isActive = true;\n        this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Active));\n\n        if (!await this.ensureReady()) {\n            this.logError(`Failed to acquire Axon virtual connection to the ONS! ONS Axon Worker will not be started.`);\n            return;\n        }\n\n        if (!await this._monitorActiveSubscriptions()) {\n            this.logError('Failed to start monitoring of active subscriptions!');\n        }\n    }\n\n    stop() {\n        if (!this.isActive) {\n            this.logDebug(`ONS Axon Worker is already stopped! Skipping this request!`);\n            return;\n        }\n        this.logDebug('Stopping ONS Axon Worker...');\n        this.subscriptions.forEach((sub: ONSSubscription) => sub.abort());\n        this._isActive = false;\n        this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(OnsMonitoringStatus.Inactive));\n    }\n\n    @synchronized\n    private async _restartMonitoring() {\n        if (!this.isActive) {\n            this.logDebug('ONS Axon Worker is not active. Skipping this request!');\n            return;\n        }\n        this.logDebug(`Restarting ONS Monitoring over Axon for active subscriptions: [${this._activeSubscriptions.map(sub => sub.subscriptionId).join(',')}].`);\n        this.stop();\n        await this.start();\n    }\n\n    private _onSubscriptionChange = (_event: ChangeEvent) => {\n        this.logDebug('Subscriptions changed!');\n        this._restartMonitoring();\n    };\n\n    private get _subscriptionsWithAssets(): ONSSubscription[] {\n        return Array.from(this._subscriptions)\n            .filter(sub => sub.pendingONSObjects.size > 0);\n    }\n\n    private get _activeSubscriptions(): ONSSubscription[] {\n        return this._subscriptionsWithAssets\n            .filter(sub => sub.subscriptionId && sub.subscriptionHref) // Note: watchedAssets not assets\n            .sort((a, b) => a.subscriptionId! <= b.subscriptionId! ? -1 : 1); // Sort by subscription ID.\n    }\n\n    private get _monitoredSubscriptions(): ONSSubscription[] {\n        return this._activeSubscriptions.filter(sub => sub.monitoringStatus === SubscriptionMonitoringStatus.Active);\n    }\n\n    @synchronized\n    private async _monitorActiveSubscriptions(): Promise<boolean> {\n        let subscriptionsToMonitor = this._activeSubscriptions.filter(sub => sub.monitoringStatus === SubscriptionMonitoringStatus.Inactive);\n        if (subscriptionsToMonitor.length === 0) {\n            this.logDebug(`No new subscriptions to register for monitoring. Currently monitoring: [${this._monitoredSubscriptions.map(sub => sub.subscriptionId).join(',')}].`);\n            return true;\n        }\n\n        if (!await this.ensureReady()) {\n            this.logError(`Failed to acquire Axon connection to ONS!`);\n            return false;\n        }\n\n        // Validate all subscriptions to be monitored.\n        for (const sub of subscriptionsToMonitor) {\n            await sub.validate();\n        }\n\n        // Only monitor subscriptions that have a subscriptionHref (presumed to be valid).\n        subscriptionsToMonitor = subscriptionsToMonitor.filter(sub => sub.subscriptionHref);\n\n        this.logDebug(`Registering monitoring for new active subscriptions: [${subscriptionsToMonitor.map(sub => sub.subscriptionId).join(',')}].`);\n        try {\n            const operationId = uuid();\n            this._registrationOperationIds.add(operationId);\n            const message: Message = {\n                'operationName': 'register',\n                operationId,\n                'body': this._createMonitoringRegistrationRequest(subscriptionsToMonitor),\n            };\n            this.logDebug(`Sending subscription monitoring request over Axon`, message);\n            this._axonVc!.sendMessage(JSON.stringify(message));\n            subscriptionsToMonitor.forEach(sub => sub.monitoringStatus = SubscriptionMonitoringStatus.Registering);\n            return true;\n        } catch (error) {\n            this.logError(`Failed to send subscription monitoring request over Axon`, error);\n            return false;\n        }\n    }\n\n    // Creates ONS Registration Request for the monitored subscriptions.\n    private _createMonitoringRegistrationRequest(subscriptions: ONSSubscription[]): RegistrationRequest {\n\n        const registerationRequest: RegistrationRequest = {\n            'subscriptions': []\n        };\n\n        for (const sub of subscriptions) {\n            if (!sub.subscriptionId) {\n                continue;\n            }\n            const item: Subscription = {\n                'id': sub.subscriptionId\n            };\n            if (sub.continuationToken) {\n                item.continuationToken = sub.continuationToken;\n            }\n            registerationRequest.subscriptions.push(item);\n        }\n\n        return registerationRequest;\n    }\n\n    private async _ensureSubscriptions() {\n        // This will create and store instances of ONSSubscription\n        // the number created will be the number of MAX_SUBSCRIPTIONS\n        // set by SAM.js or service (we don't actually create subscriptions\n        // on the server though, unless they have any assets to monitor)\n\n        const maxSubscriptions = this._onsContext._core._environment.getValue('ONS_DEFAULT_MAX_SUBSCRIPTIONS');\n        this._maxAssetsPerSubscription = this._onsContext._core._environment.getValue('ONS_DEFAULT_MAX_ASSETS_PER_SUBSCRIPTION');\n        if (maxSubscriptions > this._subscriptions.length) {\n            // Just because we are creating an ONSSubscription does not mean\n            // we are creating a subscription on the service. We actually\n            // create the max number of local ONSSubscription allowed by ONS but only\n            // create the subscription on the service if there are assets on that subscription.\n\n            // Add new subscriptions\n            for (let i = this._subscriptions.length; i < maxSubscriptions; ++i) {\n                // If we have a corresponding cached subscription\n                // pull the information from cache and construct\n                // the ONSSubscription with data from the cache.\n                // If the cached subscription information is out of date,\n                // it will be handled inside the ONSSubscription.\n                const sub = new ONSSubscription(this._onsContext);\n                this._subscriptions.push(sub);\n                sub.on('change', this._onSubscriptionChange);\n            }\n        } else if (maxSubscriptions < this._subscriptions.length) {\n            // Remove subscriptions over the limit\n            for (let i = maxSubscriptions; i < this._subscriptions.length; ++i) {\n                const sub = this._subscriptions[i];\n                sub.pendingONSObjects = new Map();\n                sub.off('change', this._onSubscriptionChange);\n            }\n            this._subscriptions.length = maxSubscriptions; // Removes the overflow from the array.\n        }\n    }\n\n    private _truncateAssetIdsByMaxSizeIfNeeded(plsAssetListIds: Set<string>, assetIds: Set<string>): Set<string> {\n        const maxTotalAssets = this._maxAssetsPerSubscription * this._subscriptions.length;\n\n        const combinedAssetIds = new Set<string>([ ...plsAssetListIds, ...assetIds ]);\n\n        // Prioritize PLS Asset Lists over individual assets during truncation\n        // since one list subscription can efficiently monitor changes for multiple assets within that list\n        if (combinedAssetIds.size > maxTotalAssets) {\n            this.logWarn(`Number of assets (${combinedAssetIds.size}) exceeds the maximum allowed by ONS. Limiting to ${maxTotalAssets}`);\n            // TODO:\n            //this._analytics.reportError('ONSSubscriptionError', `Requested assets exceed number allowed. Count: ${assetIds.length}, Max: ${maxTotalAssets}`);\n            const truncatedArray = Array.from(combinedAssetIds).slice(0, maxTotalAssets);\n            return new Set<string>(truncatedArray);\n        }\n\n        return combinedAssetIds;\n    }\n\n    async watch(assetIdsToMonitor: Set<string>, plsAssetListIdsToMonitor: Set<string>) {\n        await this._ensureSubscriptions();\n        this._ONSObjectIds = this._truncateAssetIdsByMaxSizeIfNeeded(\n            plsAssetListIdsToMonitor,\n            assetIdsToMonitor\n        );\n\n        const getProps = (id: string): ONSObjectProperties => {\n            if (plsAssetListIdsToMonitor.has(id)) {\n                const props: ONSObjectProperties = {\n                    type: 'assetList',\n                    listLevel: 'shallow'\n                };\n                return props;\n            }\n            const asset = this._onsContext._core.hostAssetContext._assetPool.getLocalItemById(id);\n            const props: ONSObjectProperties = {\n                type: 'asset',\n                ...(asset?.isFolder ? { directoryLevel: 'shallow' } : {}),\n            };\n            return props;\n        };\n\n\n        // Map from subscription id to current assets being monitored,\n        // (in the form of a map from the asset id to its properties)\n        // minus ones we no longer need to monitor:\n        // Creates an array and each entry is a\n        // Map() that represents the assets in the subscription.\n\n        const existingObjectIds = new Set<string>();\n\n        const subscriptionToOnsObjects: Map<string, ONSObjectProperties>[] = this._subscriptions.map(\n            sub => {\n                const onsObjects = new Map<string, ONSObjectProperties>();\n                sub.pendingONSObjects.forEach((properties, id) => {\n                    if (this._ONSObjectIds.has(id) && existingObjectIds.add(id)) {\n                        onsObjects.set(id, getProps(id));\n                    }\n                });\n                return onsObjects;\n            }\n        );\n        // We assign the ons objects to subscriptions such that we fill up the first subscription first\n        // before creating new ones. Note that when this was first implemented in SAM.js, we\n        // would try to spread assets across as many subscriptions as possible, because ONS didn't\n        // tell us which asset in a subscription changed - but now that we have the changelog API,\n        // it's better to concentrate assets in as few subscriptions as possible.\n\n        let nextIndex = 0;\n        this._ONSObjectIds.forEach(id => {\n            if (existingObjectIds.has(id)) {return;}\n\n            // find a subscription with space\n            while (\n                subscriptionToOnsObjects[nextIndex].size >= this._maxAssetsPerSubscription\n            ) {\n                nextIndex++;\n            }\n\n            subscriptionToOnsObjects[nextIndex].set(id, getProps(id));\n        });\n\n        this._subscriptions.forEach((sub, index) => {\n            sub.pendingONSObjects = subscriptionToOnsObjects[index];\n\n            if (sub.pendingONSObjects.size > 0) {\n                this.logDebug(\n                    `Subscription #${index} (${sub.subscriptionId}) now has ${sub.pendingONSObjects.size} items.`\n                );\n            }\n        });\n    }\n\n    /**\n     * Logs a debug message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logDebug(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logDebug(message, 'Axon', ...optionalParams);\n    }\n\n    /**\n     * Logs an info message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logInfo(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logInfo(message, 'Axon', ...optionalParams);\n    }\n\n    /**\n     * Logs a warning message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logWarn(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logWarn(message, 'Axon', ...optionalParams);\n    }\n\n    /**\n     * Logs an error message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     * @remarks If the first optional parameter is an Error object, the message will be appended with the error message.\n     */\n    logError(message: string, ...optionalParams: any[]) {\n        this._onsContext.logger.logError(message, 'Axon', ...optionalParams);\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { ONS_MONITORING_STATUS_CHANGED, OnsMonitoringStatus, ONSMonitoringStatusChangedEvent } from './ONSEvent';\nimport type { ONSFirstLongPollCompletedEvent, ONSFirstLongPollStartedEvent } from './ONSEvent';\nimport { ONS_FIRST_LONG_POLL_COMPLETED, ONS_FIRST_LONG_POLL_STARTED } from './ONSEvent';\nimport type { default as ISAMCorePrivate } from '../core/ISAMCorePrivate';\nimport { ONSLongPollWorker } from './ONSLongPollWorker';\nimport { CHANGE } from '../core/ChangeEvent';\nimport { getURLFromLinks, RelType } from '../interface/LinkUtils';\nimport { synchronized, cache, key } from '../core/decorators';\nimport type { ONSWorkerEventMap, ONSWorkerInterface } from './ONSWorker.interface';\nimport { ONS_AUTH_HEADER } from './ONSWorker.interface';\nimport { ONSAxonWorker } from './ONSAxonWorker';\nimport { SAMObjectEventEmitter } from '../core/SAMObjectEventEmitter';\nimport type { Loggable } from './Logging';\nimport { Logger } from './Logging';\nimport type { ONSSubscription, SubscriptionConfig } from './ONSSubscription';\nimport type { ONSObjectProperties } from './ONSResource';\nimport { Env } from '../core/Environment';\nimport { LogLevel as SyncServicesLogLevel } from './Logging';\nimport { SAMError, SAMErrorCode } from '../core/SAMError';\n\nconst REQUIRED_LINKS: RelType[] = [ RelType.SUBSCRIPTION_CREATE, RelType.ONS_CHANGELOG ];\nconst validateRootDocument = (json: any) => json._links && REQUIRED_LINKS.every(key => json._links[key]);\n\ninterface OnsContextEventMap extends ONSWorkerEventMap {\n    [ONS_FIRST_LONG_POLL_STARTED]: ONSFirstLongPollStartedEvent;\n    [ONS_FIRST_LONG_POLL_COMPLETED]: ONSFirstLongPollCompletedEvent;\n    [ONS_MONITORING_STATUS_CHANGED]: ONSMonitoringStatusChangedEvent;\n}\n\n/**\n * Provides SAM context for Object Notification System (ONS).\n */\nexport class ONSContext extends SAMObjectEventEmitter<OnsContextEventMap> implements Loggable {\n    private readonly _logger: Logger;\n    private _useAxon: boolean;\n    private _onsLongPollWorker: ONSWorkerInterface | undefined;\n    private _onsAxonWorker: ONSWorkerInterface | undefined;\n    private _isStarted = false;\n    private _stopTimeout?: ReturnType<typeof setTimeout>;\n    private _assetsIds: Set<string> = new Set();\n    private _plsAssetListIds: Set<string> = new Set();\n    private _onsMonitoringStatus: OnsMonitoringStatus = OnsMonitoringStatus.Unknown;\n\n    constructor(core: ISAMCorePrivate,\n        // @TODO SAM-2845 This may be enabled the same in the future but working\n        // with the SharedWorker. For now we want to return undefined.\n        private readonly _cacheEnabled: boolean = core._environment.getValue('ENABLE_ONS_CACHE')) {\n        super(core);\n        this._useAxon = core._environment.getValue('ONS_OVER_AXON');\n        this._logger = new Logger('ONS', core._environment.logSink);\n        if (this._core._environment.getValue('ENVIRONMENT') === Env.Stage) {\n            // While on Stage, elevate the default log-level to DEBUG.\n            this._logger.logLevel = SyncServicesLogLevel.DEBUG;\n        }\n        this.onsMonitoringStatus = OnsMonitoringStatus.Inactive;\n    }\n\n    // Sync ONS Monitoring Status with the ONS Worker.\n    private _onONSMonitoringStatusChanged = (event: ONSMonitoringStatusChangedEvent) => {\n        this.logDebug(`ONS Monitoring Status changed to '${OnsMonitoringStatus[event.status]}'.`);\n        this.onsMonitoringStatus = event.status;\n    };\n\n    /**\n     * Gets the current status of the ONS monitoring.\n     */\n    get onsMonitoringStatus(): OnsMonitoringStatus {\n        return this._onsMonitoringStatus;\n    }\n\n    /**\n     * Sets the current status of the ONS monitoring.\n     */\n    set onsMonitoringStatus(status: OnsMonitoringStatus) {\n        if (this.onsMonitoringStatus === status) {\n            return; // Ignore duplicate events.\n        }\n        this._onsMonitoringStatus = status;\n        this.emit(ONS_MONITORING_STATUS_CHANGED, new ONSMonitoringStatusChangedEvent(status));\n    }\n\n    /**\n     * Whether to use Axon as the transport mode for ONS.\n     */\n    get useAxon(): boolean {\n        return this._useAxon;\n    }\n\n    /**\n     * Enables or disables the use of Axon as the transport mode for ONS.\n     * @param newValue A boolean indicating whether to use Axon Virtual Connection. If false, Long Poll is used.\n     */\n    set useAxon(newValue: boolean) {\n        this.logInfo(`Setting ONS Context transport mode to ${newValue ? 'Axon' : 'Long Poll'}.`);\n        if (this._useAxon === newValue) { return; }\n        this._reinitialize(newValue);\n    }\n\n    /**\n     * Gets the logger.\n     */\n    get logger(): Logger {\n        return this._logger;\n    }\n\n    /**\n     * Whhether the cache is enabled.\n     */\n    get cacheEnabled(): boolean {\n        return this._cacheEnabled;\n    }\n\n    /**\n     * Whether the ONS Worker is active.\n     */\n    get isActive(): boolean {\n        if (this._useAxon && this._onsAxonWorker || !this._useAxon && this._onsLongPollWorker) {\n            return this.worker.isActive;\n        }\n        return false;\n    }\n\n    /**\n     * Whether the ONS Context is started.\n     */\n    get isStarted(): boolean {\n        return this._isStarted;\n    }\n\n    // TODO: [SHARED-4061] Improve readability of the following code. Note that worker should not be initialize\n    // only to check if it's active. This is a temporary solution until we have a better way to check if the worker is active.\n    get worker(): ONSWorkerInterface {\n        return this._useAxon ? this._getAxonWorker() : this._getLongPollWorker();\n    }\n\n    get watchedObjectIds(): Set<string> {\n        const objectIds: Set<string> = new Set();\n        this.worker.subscriptions.forEach((sub: ONSSubscription)  => {\n            sub.watchedONSObjects.forEach((properties: ONSObjectProperties, objectId: string) => objectIds.add(objectId));\n        });\n        return objectIds;\n    }\n\n    private get _document(): Document | undefined {\n        if (typeof window === 'object' && window !== null && window.document instanceof Document) {\n            return window.document;\n        }\n        return undefined;\n    }\n\n    private get _documentSupportsVisibility(): boolean {\n        const document = this._document;\n        if (!document) { return false; }\n        if (typeof document.addEventListener !== 'function' ||\n            typeof document.removeEventListener !== 'function') {\n            return false;\n        }\n        if (typeof document.visibilityState !== 'string') {\n            return false;\n        }\n        if (typeof document.onvisibilitychange !== 'object') {\n            return false;\n        }\n        return true;\n    }\n\n    private _getAxonWorker(): ONSWorkerInterface {\n        if (this._onsAxonWorker) {  // Ensure to maintain a singleton instance.\n            return this._onsAxonWorker;\n        }\n        this._onsAxonWorker = new ONSAxonWorker(this);\n        this.onsMonitoringStatus = OnsMonitoringStatus.Inactive;\n        this._onsAxonWorker.on(ONS_MONITORING_STATUS_CHANGED, this._onONSMonitoringStatusChanged);\n\n        return this._onsAxonWorker;\n    }\n\n    private _getLongPollWorker(): ONSWorkerInterface {\n        if (this._onsLongPollWorker) {  // Ensure to maintain a singleton instance.\n            return this._onsLongPollWorker;\n        }\n        this._onsLongPollWorker = new ONSLongPollWorker(this);\n        this.onsMonitoringStatus = OnsMonitoringStatus.Inactive;\n        this._onsLongPollWorker.on(ONS_MONITORING_STATUS_CHANGED, this._onONSMonitoringStatusChanged);\n        this._onsLongPollWorker.on(CHANGE, (event) => {\n            this.emit(CHANGE, event);\n        });\n        this._onsLongPollWorker.on(ONS_FIRST_LONG_POLL_STARTED, (event) => {\n            this.emit(ONS_FIRST_LONG_POLL_STARTED, event);\n        });\n        this._onsLongPollWorker.on(ONS_FIRST_LONG_POLL_COMPLETED, (event) => {\n            this.emit(ONS_FIRST_LONG_POLL_COMPLETED, event);\n        });\n        this._onsLongPollWorker.on('aborted', () => {\n            this.emit('aborted');\n        });\n        this._onsLongPollWorker.on('notified', () => {\n            this.emit('notified');\n        });\n        return this._onsLongPollWorker;\n    }\n\n    /**\n     * Cleanly (re)initializes the ONS Context for the selected transport mode (Axon vs Long Poll).\n     * @param useAxon A boolean indicating whether to use Axon Virtual Connection. If false, Long Poll is used.\n     */\n    private async _reinitialize(useAxon: boolean) {\n        const newModeName = useAxon ? 'Axon' : 'Long Poll';\n        this.logInfo(`Reinitializing ONS Context Process for transport mode: ${newModeName}...`);\n        const errorHandler = (error: unknown) => {\n            const errorMessage = `Error initializing ONS Context for transport mode: ${newModeName}`;\n            this.logError(errorMessage, error);\n        };\n        const wasStarted = this.isStarted;\n        await this._deinitialize()\n            .then((result) => {\n                if (!result) {\n                    throw new Error('Failed to deinitialize ONS Context');\n                } else {\n                    this.logInfo('ONS Context deinitialized.');\n                }\n            })\n            .catch(errorHandler);\n        this._useAxon = useAxon;\n        await this.watch(this._assetsIds, this._plsAssetListIds)\n            .then(() => {\n                this.logInfo('ONS Context reinitialized.');\n            }).catch(errorHandler);\n        if (wasStarted) { await this.start(); }\n    }\n\n    /**\n     * Ensures that the ONS Context is initialized and the underlying connection to ONS is active.\n     * @returns A promise that resolves to true if the ONS Context is initialized, false otherwise.\n     */\n    @synchronized\n    async ensureInitialized(): Promise<boolean> {\n        try {\n            return this.worker.ensureReady();\n        } catch (error) {\n            this.logError('Failed to initialize ONS Axon Worker', error);\n            return false;\n        }\n    }\n\n    /**\n     * Deinitializes the ONS Context and closes the underlying connection to ONS.\n     * @returns A promise that resolves to true if the ONS Context is deinitialized, false otherwise.\n     * @package -- only for use in SAM.js\n     */\n    @synchronized\n    async _deinitialize(): Promise<boolean> {\n        this.logInfo('Deinitializing ONS Context...');\n        if (this.isStarted) { this.stop(); }\n        const result = this.worker.deinitialize();\n        this.worker.off(ONS_MONITORING_STATUS_CHANGED, this._onONSMonitoringStatusChanged);\n        if (this._useAxon) {\n            this._onsAxonWorker = undefined;\n        } else {\n            this._onsLongPollWorker = undefined;\n        }\n        this.onsMonitoringStatus = OnsMonitoringStatus.Unknown;\n        return result;\n    }\n\n    private _onVisibilityChange = () => {\n        if (this._stopTimeout) {\n            clearTimeout(this._stopTimeout);\n            this._stopTimeout = undefined;\n        }\n        if (this._document?.visibilityState === 'visible') {\n            this.worker.start(); // Won't do anything if we didn't stop yet, since still active.\n        } else {\n            // we're de-bouncing to avoid repeatedly stopping/restarting if the user switches between Web browser tabs frequently.\n            this._stopTimeout = setTimeout(() => this.worker.stop(), this._core._environment.getValue('ONS_DOCUMENT_VISIBILITY_TIMEOUT')); // 10s\n        }\n    };\n\n    /**\n     * Activate ONS Context.\n     */\n    async start(): Promise<void> {\n        if (this._isStarted) {\n            this.logDebug('ONS Context is already active! Skipping activation call...');\n            return;\n        }\n        this.logInfo('Activating ONS Context...');\n        this._isStarted = true;\n        if (this._documentSupportsVisibility) {\n            this._document?.addEventListener('visibilitychange', this._onVisibilityChange);\n        }\n        if (!this._documentSupportsVisibility || this._document?.visibilityState === 'visible') {\n            return this.worker.start();\n        }\n    }\n\n    /**\n     * Deactivate ONS Context.\n     */\n    stop() {\n        if (!this._isStarted) {\n            this.logDebug('ONS Context is inactive! Skipping deactivation call...');\n            return;\n        }\n        this.logInfo('Deactivating ONS Context...');\n        this._isStarted = false;\n        if (this._documentSupportsVisibility) {\n            this._document?.removeEventListener('visibilitychange', this._onVisibilityChange);\n        }\n        if (this._stopTimeout) {\n            clearTimeout(this._stopTimeout);\n            this._stopTimeout = undefined;\n        }\n        this.worker.stop();\n    }\n\n    /**\n     * Watches an array of assetIds and PLSAssetListIds.\n     *\n     * @param {Array} assetIds\n     * @param {Array} plsAssetListIds\n     */\n    @synchronized\n    async watch(assetIds: Set<string>, plsAssetListIds: Set<string>) {\n        const assetIdsToMonitor = new Set<string>();\n        const plsAssetListIdsToMonitor = plsAssetListIds;\n        // Process asset IDs\n        assetIds.forEach(id => {\n            const asset = this._core.hostAssetContext._assetPool.getLocalItemById(id);\n            if (!asset || asset.isFolder) {\n                assetIdsToMonitor.add(id);\n                this.logDebug(`Will unconditionally monitor asset ${id} of type ${asset?.isFolder ? 'folder' : 'unknown'}.`);\n                return;\n            }\n\n            // If we're also monitoring the parent, we'll skip adding the asset to ONS subscription,\n            // since shallow directory monitoring of the parent covers all children.\n            const parentId = asset?.ancestorIDs?.at(-1);\n            if (!parentId) {\n                assetIdsToMonitor.add(id);\n                this.logDebug(`Will monitor asset ${id} because it has no parent.`);\n            } else if (!assetIds.has(parentId)) {\n                assetIdsToMonitor.add(id);\n                this.logDebug(`Will monitor asset ${id} because its parent is unknown.`);\n            } else {\n                this.logDebug(`Asset ${id} will be monitored via shallow monitoring of its parent ${parentId}`);\n            }\n        });\n\n        this._assetsIds = assetIdsToMonitor;\n        this.logDebug(`Watching ${this._assetsIds.size} asset(s):`, this._assetsIds);\n        if (await this.ensureInitialized()) {\n            return this.worker.watch(this._assetsIds, plsAssetListIdsToMonitor);\n        } else {\n            this.logError('Failed to watch assets due to ONS Context initialization error.');\n        }\n    }\n\n    @cache(validateRootDocument)\n    private async _getAndCacheDocument(@key href: string) {\n        const response = await this._core._environment.fetch(href, {\n            headers: {\n                Accept: 'application/vnd.syncservice.v2.hal+json'\n            },\n            authHeader: ONS_AUTH_HEADER\n        });\n\n        return response.json();\n    }\n\n    private async _getSyncServiceDiscovery() {\n        const discovery = await this._getAndCacheDocument(`https://${this._core._environment.endpoints.SYNC_SERVICE_HOST}/api/v1`);\n        if (!this.useAxon) {\n            // Ensure that the discovery comes with necessary Long Poll link.\n            if (!discovery?._links?.[RelType.NOTIFICATIONS_LONGPOLL]) {\n                throw SAMError.create(SAMErrorCode.UNKNOWN, 'Invalid Sync Service Discovery (Missing the required link for Long Poll).');\n            }\n        }\n        return discovery;\n    }\n\n    async getSubscriptionConfig(): Promise<SubscriptionConfig> {\n        try {\n            const rootDocument = await this._getSyncServiceDiscovery();\n            return rootDocument?.config?.subscriptions ?? {};\n        } catch (e) {\n            this.logInfo(`Error fetching ONS subscription config from the Sync Service Discovery: ${e}`);\n            return {};\n        }\n    }\n\n    async getLink(key: RelType, options: {[s: string]: string | string[]}  = {}) {\n        const rootDocument = await this._getSyncServiceDiscovery();\n        return getURLFromLinks(rootDocument._links, key, options);\n    }\n\n    /**\n     * Logs a debug message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logDebug(message: string, ...optionalParams: any[]) {\n        this._logger.logDebug(message, 'Context', ...optionalParams);\n    }\n\n    /**\n     * Logs an info message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logInfo(message: string, ...optionalParams: any[]) {\n        this._logger.logInfo(message, 'Context', ...optionalParams);\n    }\n\n    /**\n     * Logs a warning message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     */\n    logWarn(message: string, ...optionalParams: any[]) {\n        this._logger.logWarn(message, 'Context', ...optionalParams);\n    }\n\n    /**\n     * Logs an error message.\n     * @param message - Message to log.\n     * @param optionalParams - Optional objects to stringify and log after the message.\n     * @remarks If the first optional parameter is an Error object, the message will be appended with the error message.\n     */\n    logError(message: string, ...optionalParams: any[]) {\n        this._logger.logError(message, 'Context', ...optionalParams);\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n * Copyright 2020 Adobe Systems Incorporated\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { CHANGE } from '../core/ChangeEvent';\nimport type { default as TypedEventEmitter, IEventMap } from '../core/TypedEventEmitter';\nimport type { Loggable } from './Logging';\nimport type { ONS_MONITORING_STATUS_CHANGED, ONSAssetChangeEvent, ONSMonitoringStatusChangedEvent } from './ONSEvent';\nimport type { ONSSubscription } from './ONSSubscription';\n\nexport type ONSHeaderKeys = 'x-api-key' | 'locale';\nexport type ONSHeaderMap = { [key in ONSHeaderKeys]?: string };\n\nexport const ONS_AUTH_HEADER = 'X-User-Token';\n\nexport interface ONSWorkerEventMap extends IEventMap {\n    [CHANGE]: ONSAssetChangeEvent;\n    [ONS_MONITORING_STATUS_CHANGED]: ONSMonitoringStatusChangedEvent;\n}\n\nexport interface ONSWorkerInterface extends TypedEventEmitter<ONSWorkerEventMap>, Loggable {\n    get isActive(): boolean;\n    get subscriptions(): ONSSubscription[];\n    start(): Promise<void>;\n    stop(): void;\n    ensureReady(): Promise<boolean>;\n    deinitialize(): Promise<boolean>;\n    watch(assetIds: Set<string>, plsAssetListIds: Set<string>): Promise<void>;\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2025 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type AdobeAsset from './AdobeAsset';\n\nexport default class LocalAdobeAssetFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n\n    matches(item: AdobeAsset): boolean {\n        // Only show assets that are local (i.e. are available offline).\n        if (!item.isAvailableOffline) {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport ImplicitAdobeAssetFilterBase from './ImplicitAdobeAssetFilterBase';\n\nexport default class ImplicitFavoriteAdobeAssetFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<AdobeAsset> {\n    constructor() {\n        super({ _isSharedWithYou: true });\n    }\n\n    matches(item: AdobeAsset): boolean {\n        return item.isFavorite === true;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type {\n    IItemLoaderOptions,\n    IItemLoader,\n    ILoadedPage,\n    ILoadNextPage,\n} from '../core/ItemLoader';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type AdobeAsset from './AdobeAsset';\nimport { AdobeAssetUpdater } from './AdobeAsset';\nimport type AdobeAssetFilter from './AdobeAssetFilter';\nimport type { FavoriteAdobeAssetConfig } from './FavoriteAdobeAssetSource';\n\nexport default class FavoriteAdobeAssetLoader implements IItemLoader<FavoriteAdobeAssetConfig> {\n    private _assetListId: string | undefined;\n    constructor(private _core: ISAMCorePrivate) {}\n\n    async loadPage(options: IItemLoaderOptions<FavoriteAdobeAssetConfig>) {\n        return await this._loadPage(options);\n    }\n\n    get assetListId(): string | undefined {\n        return this._assetListId;\n    }\n\n    // fetch a page of assets from the service\n    // use the data to instantiate assets\n    // build next page link and recursively call _loadPage if necessary\n    // return ILoadedPage<FavoriteAdobeAssetConfig>\n    private async _loadPage(\n        options: IItemLoaderOptions<FavoriteAdobeAssetConfig>,\n        after?: string\n    ): Promise<ILoadedPage<FavoriteAdobeAssetConfig>> {\n        const gqlManager = await this._core._getGQLManager();\n        const { mediaTypes } = options.filter as AdobeAssetFilter;\n        const { field, direction } = options.order;\n\n        const { items: favorites, pageInfo, assetListId } = await gqlManager.getFavorites({\n            first: options.loadOptions?.limit || 50,\n            after,\n            filter: mediaTypes ? { dc_format: [ ...mediaTypes ].sort() } : undefined,\n            orderBy: {\n                field: field === 'name' ? 'NAME' : 'CREATE_DATE',\n                direction: direction === 'ascending' ? 'ASCENDING' : 'DESCENDING'\n            }\n        }, options.resource);\n        if (assetListId) {\n            this._assetListId = assetListId;\n        }\n\n        const latency = this._core._environment.getValue('GQL_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n        const session = this._core\n            ._getAssetPool()\n            .createLoaderUpdateSession<AdobeAsset>(mostRecentValidMutation);\n        const items = AdobeAssetUpdater.updateRemoteItems(\n            session,\n            favorites\n        );\n\n        session.commit();\n\n        let loadNextPage: ILoadNextPage<FavoriteAdobeAssetConfig> | undefined;\n        if (pageInfo.hasNextPage) {\n            loadNextPage = (options: IItemLoaderOptions<FavoriteAdobeAssetConfig>) =>\n                this._loadPage(options, pageInfo.endCursor!);\n        }\n\n        return {\n            items,\n            loadNextPage,\n            assetListId\n            // TODO: request total count come back as apart of AssetListConnection\n            // total: data.total\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { Asset, AssetListFilter } from './generated/types';\nimport type AdobeAssetFilter from '../assets/AdobeAssetFilter';\nimport type { AdobeAssetUpdaterMetadata } from '../assets/AdobeAsset';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type { PLSListResponse } from './models/PLSModels';\nimport { RelType } from '../interface/LinkUtils';\nimport type { IAppMetadata } from '../interface/RepositoryModel';\nimport type { IItemSourceConfig } from '../core/ItemList';\nimport type Resource from '../assets/Resource';\nimport { ManagedPromise } from '../utils/ManagedPromise';\n\nconst DEFAULT_PAGE_SIZE = 20;\n\nexport default abstract class PLSListLoader<TData, T extends IItemSourceConfig> implements IItemLoader<T> {\n    _assetListId?: string;\n    constructor(protected _core: ISAMCorePrivate) { }\n\n    async loadPage(options: IItemLoaderOptions<T>): Promise<ILoadedPage<T>> {\n        return await this._loadPage(options);\n    }\n\n    supportsFilter(): boolean {\n        return true;\n    }\n    /**\n    * Gets the assetListId associated with this loader, if available.\n    */\n    get assetListId(): string | undefined {\n        return this._assetListId;\n    }\n\n\n    private async _loadPage(\n        options: IItemLoaderOptions<T>,\n        after?: string\n    ): Promise<ILoadedPage<T>> {\n        const filter = this._getAssetListFilter(options);\n        const mostRecentValidMutation = Date.now() - this._core._environment.getValue('GQL_LIST_UPDATE_LATENCY');\n\n        // We must wait until we've added the list items to the ItemPool\n        // before we can update those items with _processIncrementalData,\n        // which assumes the items are in the pool.\n        const readyToProcessIncrementalData = new ManagedPromise<void>();\n\n        const { items: plsRemoteItems, pageInfo, assetListId } = await this._getPLSData({\n            first: options.loadOptions?.limit ?? DEFAULT_PAGE_SIZE,\n            after,\n            filter,\n            order: options.order,\n            resource: options.resource\n        }, async (incrementalData) => {\n            await readyToProcessIncrementalData.promise;\n            this._processIncrementalData(incrementalData);\n        });\n\n        if (assetListId) {\n            this._assetListId = assetListId;\n        }\n\n        const session = this._core\n            ._getAssetPool()\n            .createLoaderUpdateSession<AdobeAsset>(mostRecentValidMutation);\n        const updater = (await this._core.getAssetContext())._adobeAssetUpdater;\n        const items = updater.updateRemoteItems(session, this._extractRemoteItems(plsRemoteItems));\n\n        let loadNextPage: ILoadNextPage<T> | undefined;\n        if (pageInfo.hasNextPage) {\n            loadNextPage = (options: IItemLoaderOptions<T>) => this._loadPage(options, pageInfo.endCursor!);\n        }\n\n        session.commit();\n        readyToProcessIncrementalData.resolve();\n\n        return {\n            items,\n            loadNextPage,\n            mostRecentValidMutation,\n            assetListId: this._assetListId\n        };\n    }\n\n    private _getAssetListFilter(options: IItemLoaderOptions<T>): AssetListFilter {\n        const { mediaTypes, assetTypes, excludeAssetTypes, assetSubTypes } = options.filter as AdobeAssetFilter;\n\n        const filter: AssetListFilter = {};\n        if (mediaTypes?.size) {\n            filter.dc_format = [ ...mediaTypes ];\n        }\n\n        // NOTE: filter cannot have both assetTypes and excludeAssetTypes\n        if (excludeAssetTypes?.size) {\n            filter.assetType = { nin: [ ...excludeAssetTypes ] };\n        } else if (assetTypes?.size) {\n            filter.assetType = { in: [ ...assetTypes ] };\n        }\n        if (assetSubTypes?.size) {\n            filter.assetSubType = { in: [ ...assetSubTypes ] };\n        }\n\n        return filter;\n    }\n\n    abstract _getPLSData(\n        options: {\n            first: number;\n            after?: string;\n            filter: AssetListFilter;\n            order: T['order'],\n            resource?: Resource\n        },\n        processIncrementalData: (incrementalData: TData) => void\n    ): Promise<PLSListResponse>;\n\n\n    abstract getAssetNodesFromData(incrementalData: TData): Asset[];\n\n    private _processIncrementalData(incrementalData: TData): void {\n        const pool = this._core._getAssetPool();\n        const session = pool.createUpdateSession();\n        const updater = this._core._getAssetContext()!._adobeAssetUpdater;\n\n        const remoteItems: AdobeAssetUpdaterMetadata[] = this.getAssetNodesFromData(incrementalData)\n            .filter(item => {\n                return item.appMetadata?.valueOf && pool.getLocalItemById(item.repo_assetId) !== undefined;\n            })\n            .map(item => {\n                return {\n                    'repo:assetId': item.repo_assetId,\n                    _embedded: {\n                        [RelType.APP_METADATA]: item.appMetadata?.valueOf as IAppMetadata,\n                    }\n                };\n            });\n\n        updater.updateRemoteItems(\n            session,\n            remoteItems\n        );\n        session.commit();\n    }\n\n    protected _extractRemoteItems(plsRemoteItems: AdobeAssetUpdaterMetadata[]) {\n        return plsRemoteItems;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type {\n    Asset,\n    AssetListFilter,\n    SharedWithYouOrderByField,\n    SharedWithYouQuery,\n    SortOrder\n} from '../graphql/generated/types';\nimport type { SWYAdobeAssetOrderField } from './SWYAdobeAssetOrder';\nimport type { SWYAdobeAssetConfig } from './SWYAdobeAssetSource';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport type { PLSListResponse } from '../graphql/models/PLSModels';\nimport PLSListLoader from '../graphql/PLSListLoader';\nimport type { AdobeAssetUpdaterMetadata } from './AdobeAsset';\nimport type Resource from './Resource';\n\n\nexport const OrderFieldToSharedWithYouOrderBy: { [key in SWYAdobeAssetOrderField]: SharedWithYouOrderByField } = {\n    'name': 'NAME',\n    'created': 'DEVICE_CREATE_DATE',\n    'modified': 'DEVICE_MODIFY_DATE',\n    'shared': 'SHARE_DATE',\n};\n\nexport const OrderDirectionToSortOrder: { [key in IOrderDirection]: SortOrder } = {\n    'ascending': 'ASCENDING',\n    'descending': 'DESCENDING'\n};\n\nexport default class PLSSWYAdobeAssetLoader extends PLSListLoader<SharedWithYouQuery, SWYAdobeAssetConfig> {\n    async _getPLSData({\n        first,\n        after,\n        filter,\n        order,\n        resource,\n    }: {\n        first: number;\n        after?: string;\n        filter: AssetListFilter;\n        order: SWYAdobeAssetConfig['order'],\n        resource?: Resource\n    }, processIncrementalData: (incrementalData: SharedWithYouQuery) => void): Promise<PLSListResponse> {\n        const gqlManager = await this._core._getGQLManager();\n        return await gqlManager.getSharedWithYou({\n            first,\n            after,\n            filter,\n            orderBy: {\n                field: OrderFieldToSharedWithYouOrderBy[order.field],\n                direction: OrderDirectionToSortOrder[order.direction],\n            },\n        }, resource, processIncrementalData);\n    }\n\n    getAssetNodesFromData(incrementalData: SharedWithYouQuery): Asset[] {\n        return incrementalData.sharedWithYou.assetListConnection.edges.map(edge => {\n            // The generated types for for the query are slightly overspecified by codegen, so a cast is needed here\n            return edge.node as unknown as Asset;\n        });\n    }\n\n    protected _extractRemoteItems(plsRemoteItems: AdobeAssetUpdaterMetadata[]): AdobeAssetUpdaterMetadata[] {\n        return plsRemoteItems.filter(item => item['repo:assetClass'] !== 'directory');\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { MRUAdobeAssetConfig } from './MRUAdobeAssetSource';\nimport type { PLSListResponse } from '../graphql/models/PLSModels';\nimport type { Asset, AssetListFilter, PlsRecentsQuery } from '../graphql/generated/types';\nimport PLSListLoader from '../graphql/PLSListLoader';\nimport type Resource from './Resource';\n\nexport default class PLSRecentAdobeAssetLoader extends PLSListLoader<PlsRecentsQuery, MRUAdobeAssetConfig> {\n    async _getPLSData({ first, after, filter, resource }: {\n        first: number;\n        after?: string;\n        filter: AssetListFilter;\n        order: MRUAdobeAssetConfig['order'],\n        resource?: Resource\n    }, processIncrementalData: (incrementalData: PlsRecentsQuery) => void): Promise<PLSListResponse> {\n        const gqlManager = await this._core._getGQLManager();\n        return await gqlManager.recents({\n            first,\n            after,\n            filter,\n        }, resource, processIncrementalData);\n    }\n\n    getAssetNodesFromData(incrementalData: PlsRecentsQuery): Asset[] {\n        return incrementalData.recents.assetListConnection.edges.map(edge => {\n            // The generated types for for the query are slightly overspecified by codegen, so a cast is needed here\n            return edge.node as unknown as Asset;\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport type AdobeAsset from './AdobeAsset';\n\nexport enum IsSharedViewSelection { ALL, YOURS, SHARED_WITH_YOU/*, SHARED_VIA_PROJECT*/ }\n\n\nexport type IsSharedFilterOptions = {\n    isSharedWithYou?: boolean;\n    ownedBy?: string\n}\n\nexport default class IsSharedFilter implements IExplicitFilter<AdobeAsset> {\n    constructor(public options?: IsSharedFilterOptions) {}\n\n    get hash(): string {\n        return `isShared=${this.options?.isSharedWithYou ?? 'all'}:createdBy=${this.options?.ownedBy ?? 'any'}`;\n    }\n\n    getRelationToFilter(other: IsSharedFilter): ItemFilterRelation {\n        // we're filtering both this and other, but not the same filter\n        if ((this.options?.isSharedWithYou !== undefined) && (other.options?.isSharedWithYou !== undefined) && this.options.isSharedWithYou !== other.options.isSharedWithYou) {\n            return 'disjoint';\n        }\n\n        if (this.options?.ownedBy && other.options?.ownedBy && (this.options.ownedBy !== other.options.ownedBy)) {\n            return 'disjoint';\n        }\n\n        // we're filtering other, but not this, so we can partially seed from the other list but it won't have a full list\n        if ((this.options?.isSharedWithYou === undefined) && (other.options?.isSharedWithYou !== undefined)) {\n            return 'unknown';\n        }\n\n        if ((this.options?.ownedBy === undefined) && (other.options?.ownedBy !== undefined)) {\n            return 'unknown';\n        }\n\n        // either the other filter has a full list or the filters are the same\n        // either way, we can seed the new list completely from the other one\n        return 'subset';\n    }\n\n    matches(item: AdobeAsset): boolean {\n        if (this.options?.isSharedWithYou === undefined && this.options?.ownedBy === undefined) {\n            return true; // no specific view filter, match all\n        }\n\n        // _isSharedWithYouAsset undefined means not loaded yet\n        if (this.options?.isSharedWithYou && !item._isSWYAsset_NoLazyLoad) {\n            return false;\n        }\n\n        if ((this.options?.isSharedWithYou === false) && (item._isSWYAsset_NoLazyLoad !== false)) {\n            return false;\n        }\n\n        if (this.options?.ownedBy && (item._storageAssignee_NoLazyLoad?.id !== this.options.ownedBy)) {\n            return false;\n        }\n\n        return true;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport enum AvatarSizes {\n    Size50 = '50',\n    Size100 = '100',\n    Size115 = '115',\n    Size230 = '230',\n    Size138 = '138',\n    Size276 = '276'\n}\n\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport ItemBase from '../core/ItemBase';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { IAddressBookContact } from '../interface/AddressBookModel';\nimport { observable } from '../core/decorators';\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nclass AddressBookContact extends ItemBase {\n    private _countryCode: string = '';\n    private _displayName: string = '';\n    private _email: string = '';\n    private _firstName: string = '';\n    private _lastName: string = '';\n    private _addressBookIdent: string = '';\n    private _images: Record<string, string> = {};\n    private _linkPolicy?: IAddressBookContact['linkPolicy'];\n    private _linkedIdentity: string = '';\n    private _urn: string = '';\n    constructor(core: ISAMCorePrivate, id: string) {\n        super(core, id);\n    }\n\n    get ident(): string {\n        return this.id;\n    }\n\n    @observable\n    get countryCode(): string {\n        return this._countryCode;\n    }\n\n    @observable\n    get displayName(): string  {\n        return this._displayName;\n    }\n\n    @observable\n    get email(): string {\n        return this._email;\n    }\n\n    @observable\n    get firstName(): string {\n        return this._firstName;\n    }\n\n    @observable\n    get lastName(): string {\n        return this._lastName;\n    }\n\n    @observable\n    get addressBookIdent(): string {\n        return this._addressBookIdent;\n    }\n\n    @observable\n    get images(): Record<string, string> {\n        return this._images;\n    }\n\n    @observable\n    get linkPolicy(): IAddressBookContact['linkPolicy'] | undefined {\n        return this._linkPolicy;\n    }\n\n    @observable\n    get linkedIdentity(): string {\n        return this._linkedIdentity;\n    }\n\n    @observable\n    get urn(): string {\n        return this._urn;\n    }\n}\n\nexport const AddressBookContactUpdater = new ItemUpdater<AddressBookContact, IAddressBookContact>({\n    localItemType: AddressBookContact,\n    remoteIdProperty: 'ident',\n    propertyUpdater: new PropertyUpdater({\n        _countryCode: 'countryCode',\n        _displayName: 'displayName',\n        _email: 'email',\n        _firstName: 'firstName',\n        _addressBookIdent: 'addressBookIdent',\n        _images: { format: 'object', name: 'images' },\n        _lastName: 'lastName',\n        _linkPolicy: 'linkPolicy',\n        _linkedIdentity: 'linkedIdentity',\n        _urn: 'urn'\n    })\n});\n\nexport default AddressBookContact;\n\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type {\n    IItemLoader,\n    IItemLoaderOptions,\n    ILoadedPage\n} from '../core/ItemLoader';\nimport type { GroupMemberConfig } from './GroupMemberSource';\nimport type AddressBookContact from './AddressBookContact';\nimport type ItemPool from '../core/ItemPool';\nimport type AddressBookInterface from '../interface/AddressBookInterface';\nimport type ItemUpdater from '../core/ItemUpdater';\nimport type {\n    IAddressBookGroupMembersFlat,\n    IAddressBookContact\n} from '../interface/AddressBookModel';\n\nexport default class GroupMemberLoader implements IItemLoader<GroupMemberConfig> {\n\n    constructor(\n        private _addressBookUrl: string,\n        private _groupMemberPool: ItemPool<AddressBookContact>,\n        private _addressBookInterface: AddressBookInterface,\n        private _groupMemberUpdater: ItemUpdater<AddressBookContact, IAddressBookContact>,\n    ) {}\n\n    async loadPage(opts?: IItemLoaderOptions<GroupMemberConfig>, nextPageLink?: string): Promise<ILoadedPage<GroupMemberConfig>> {\n        const { limit = 100 } = opts?.loadOptions || { limit: 100 };\n        let result: IAddressBookGroupMembersFlat;\n\n        if (!nextPageLink) {\n            result = await this._addressBookInterface.getMembersFirstPage(this._addressBookUrl, limit);\n        } else {\n            result = await this._addressBookInterface.getMembersNextPage(nextPageLink);\n        }\n\n        const session = this._groupMemberPool.createLoaderMutationSession();\n        const items = this._groupMemberUpdater.updateRemoteItems(session, result._embedded.contacts);\n        session.commit();\n\n        const loadNextPage = result._links.next\n            ? () => this.loadPage(undefined, result._links.next.href)\n            : undefined;\n\n        return {\n            items,\n            loadNextPage,\n            total: result.total\n        };\n    }\n\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport InterfaceBase from './InterfaceBase';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type {\n    IAddressBookGroupMembersFlat,\n    IAddressBookList,\n    IAddressBookContact,\n    IResolveAddressBookGroupResponse\n} from './AddressBookModel';\n\nclass AddressBookInterface extends InterfaceBase {\n    constructor(\n        _core: ISAMCorePrivate\n    ) { super(_core); }\n\n    get endpoint() {\n        return `https://${this._core._environment.endpoints.ABS_HOST}`;\n    }\n\n    async getAddressBookURL(addressBookUrn: string): Promise<string> {\n        const result = await this._getResponse<IResolveAddressBookGroupResponse>(`${this.endpoint}/api/urns/resolve/${addressBookUrn}`);\n        return result.url;\n    }\n\n    async getMembersFirstPage(addressBookUrl: string, limit: number = 100): Promise<IAddressBookGroupMembersFlat> {\n        return this._getResponse(`${addressBookUrl}/members/flat?limit=${limit}`);\n    }\n\n    async getMembersNextPage(nextPageLink: string): Promise<IAddressBookGroupMembersFlat> {\n        return this._getResponse(nextPageLink);\n    }\n\n    async getAddressBooks(limit: number = 100): Promise<IAddressBookList> {\n        return this._getResponse<IAddressBookList>(`${this.endpoint}/api/address-books?limit=${limit}`);\n    }\n\n    async getContactInAddressBook(addressBookIdent: string, userId: string): Promise<IAddressBookContact> {\n        return this._getResponse<IAddressBookContact>(`${this.endpoint}/api/address-books/${addressBookIdent}/contacts?linkedIdentity=${userId}`);\n    }\n}\n\nexport default AddressBookInterface;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { SAM } from '@ccx-public/component-types';\nimport ItemBase from '../core/ItemBase';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type {\n    CollaboratorType,\n    ICollaboratorAdditionalData,\n    IComputedInvitationCollaborator,\n    InheritanceType,\n    Role\n} from '../interface/InvitationModel';\nimport {\n    memoize,\n    observable\n} from '../core/decorators';\nimport { SharedCollaboratorChangedEvent } from '../indexPrivate';\nimport { AvatarSizes } from './AvatarSizes';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport { AddressBookContactUpdater } from './AddressBookContact';\nimport type {\n    GroupMemberConfig,\n    GroupMemberSource\n} from './GroupMemberSource';\nimport GroupMemberLoader from './GroupMemberLoader';\nimport AddressBookInterface from '../interface/AddressBookInterface';\nimport ItemSource from '../core/ItemSource';\nimport SAMError from '../core/SAMError';\nimport { extractAddressBookIdent } from '../interface/AddressBookModel';\n\nexport type CollaboratorRole = Role;\nexport const CollaboratorRoles: CollaboratorRole[]  = [ 'owner', 'viewer', 'editor', 'none' ];\nconst ContributorRoles: CollaboratorRole[] = [ 'editor', 'owner' ];\n\nexport type { CollaboratorType } from '../interface/InvitationModel';\nconst CollaboratorTypes: CollaboratorType[] = [\n    'imsUser',\n    'addressBookGroup',\n    'addressBookContact',\n    'predefinedPrincipal',\n    'imsGroup',\n];\n\n// deep means that resource members have permission on the resource and all of its children.\n// deep_override is for admins and owners in user storage, meaning the same as deep but it cannot be denied.\n// If an admin is invited to collaborate, then they have both [deep_override, deep]\nexport type { InheritanceType } from '../interface/InvitationModel';\nexport const InheritanceTypes: InheritanceType[] = [ 'self', 'deep', 'deep_override' ];\n\n/**\n * A Collaborator represents the relationship between the user and the\n * asset. Users have other Profile information that is unique to the user.\n *\n * Eventually we will offer a Profile class with a Profile context that\n * offers information unrelated to an asset.\n */\nexport default class Collaborator extends ItemBase implements SAM.Collaborator {\n    private _role: CollaboratorRole = 'viewer';\n    private _type: CollaboratorType = 'imsUser';\n    private _inheritances?: InheritanceType[];\n    private _additionalData?: ICollaboratorAdditionalData;\n    private _isDirect: boolean = false;\n    private _assetID: string = '';\n    private _canDiscover: boolean = false;\n    private _canShare: boolean = false;\n    private _commentPermissions: string[] = [];\n\n    get assetId(): string {\n        return this._assetID;\n    }\n\n    /**\n     * Returns false if the Behance/PPS service\n     * was unable to return a profile for this collaborator.\n     * @deprecated -- clients should just check that profile info is not undefined (SAM-3420). Will be removed on or\n     *                after 2024-10-01\n     */\n    get hasProfile(): boolean | undefined {\n        oneTimeWarning('Collaborator.hasProfile', 'Collaborator.hasProfile is deprecated and will be'\n            + ' removed on or after 2024-10-01');\n        // This used to return the private property _hasProfile, but since _hasProfile was never\n        // set correctly, we're just returning undefined here to avoid confusion.\n        // This getter will eventually be removed by SAM-3420.\n        return undefined;\n    }\n\n    // `imsUser id` if invited via user email directly\n    // `addressBookContact id` (i.e urn.ab:contact:...) if members are invited via shareSheet's recommend dropdown\n    // `addressBookGroup id` (i.e urn:ab:group:...) if groups are invited via shareSheet's recommend dropdown\n    get collaboratorID(): string {\n        return this.id;\n    }\n\n    // Track the imsUser id\n    // - Same as 'id' for direct invited collaborators\n    // - Represents the collaborator actual ims id for addressBookContact, which is useful to check (compare ims id)\n    // for thing like if the logged in user is in the collaborator list ,...\n    // - undefined for 'addressBookGroup'\n    get imsUserId(): string | undefined {\n        const type = this._type;\n        if (type === 'imsUser') {\n            return this.id;\n        }\n\n        return this._additionalData?.linkedIdentity;\n    }\n\n    @observable(SharedCollaboratorChangedEvent)\n    // Collaborator email\n    get email(): string | undefined {\n        return this._additionalData?.email;\n    }\n\n    // Collaborator name for imsUser and addressBookContact\n    // Group name for addressBookGroup\n    @observable(SharedCollaboratorChangedEvent)\n    get name(): string | undefined {\n        const additionalData = this._additionalData;\n        return (additionalData?.displayName\n            ?? additionalData?.groupName\n            ?? additionalData?.organizationName);\n    }\n\n    get role(): CollaboratorRole {\n        return this._role;\n    }\n\n    get type(): CollaboratorType {\n        return this._type;\n    }\n\n    get commentPermissions(): string[] {\n        return this._commentPermissions;\n    }\n\n    get inheritances(): InheritanceType[] | undefined {\n        return this._inheritances;\n    }\n\n    get isDirect() {\n        return this._isDirect;\n    }\n\n    get hasContributorRole() {\n        return ContributorRoles.includes(this._role);\n    }\n\n    get hasName() {\n        return !!this.name;\n    }\n\n    get invited() {\n        return this._inheritances?.includes('deep');\n    }\n\n    get isAdmin() {\n        return this._inheritances?.includes('deep_override');\n    }\n\n    get canDiscover(): boolean {\n        return this._canDiscover;\n    }\n\n    get canShare(): boolean {\n        return this._canShare;\n    }\n\n    get additionalData(): ICollaboratorAdditionalData | undefined {\n        return this._additionalData;\n    }\n\n    /**\n     * Checks if this collaborator is the user that is currently logged in.\n     *\n     * **NOTE**: It is not safe to assume that Collaborator.id === currentUserId\n     *           will work. Always use Collaborator.isCurrentUser instead.\n     */\n    get isCurrentUser() {\n        return this._core._environment.getValue('USER_ID') === this.imsUserId;\n    }\n\n    /**\n     * Returns a standard size of 138x138\n     */\n    @observable(SharedCollaboratorChangedEvent)\n    get avatarURL(): string {\n        return this.getAvatarURL(AvatarSizes.Size138);\n    }\n\n    @observable(SharedCollaboratorChangedEvent)\n    getAvatarURL(size: AvatarSizes): string {\n        return this._additionalData?.images?.[size] ?? '';\n    }\n\n    @observable(SharedCollaboratorChangedEvent)\n    get addressBookGroupUrn(): string {\n        return this._additionalData?.groupUrn || '';\n    }\n\n    /**\n     * Lists AddressBookContacts for an AddressBook Group.\n     *\n     * @experimental -- given the way this feature was rushed in, and some gaps in knowledge\n     * about ABS and GenAI, this may not be the final API. Backward-compatibility will not\n     * be guaranteed.\n     *\n     * @returns {Promise<GroupMemberSource>}\n     */\n    @memoize\n    async getGroupMemberSource(): Promise<GroupMemberSource> {\n        if (this.type !== 'addressBookGroup') {\n            throw SAMError.create(SAM.SAMErrorCode.BAD_REQUEST,\n                'groupMemberSource only applies to addressBookGroup Collaborator');\n        }\n        if (!this.addressBookGroupUrn) {\n            throw SAMError.create(SAM.SAMErrorCode.BAD_REQUEST, 'addressBookGroupUrn is required');\n        }\n        const abs = new AddressBookInterface(this._core);\n        const url = await abs.getAddressBookURL(this.addressBookGroupUrn);\n        const addressBookIdent = extractAddressBookIdent(url);\n        const pool = this._core.collaborationContext._getAddressBookContactPool(addressBookIdent);\n\n        const loader = new GroupMemberLoader(\n            url,\n            pool,\n            abs,\n            AddressBookContactUpdater\n        );\n\n        return new ItemSource<GroupMemberConfig>(pool, [ loader ]);\n    }\n}\n\nexport const CollaboratorUpdater = new ItemUpdater<Collaborator, Partial<IComputedInvitationCollaborator>>({\n    localItemType: Collaborator,\n    remoteIdProperty: 'id',\n    changeEvent: SharedCollaboratorChangedEvent,\n    propertyUpdater: new PropertyUpdater({\n        '_type': { name: 'type', choices: CollaboratorTypes },\n        '_role': { name: 'role', choices: CollaboratorRoles },\n        '_inheritances': { name: 'inheritances', isArray: true, choices: InheritanceTypes },\n        '_additionalData': { name: 'additionalData', format: 'object' },\n        '_isDirect': { name: 'isDirect', format: 'boolean' },\n        '_avatarURLs': { name: 'avatarURLs', format: 'object' },\n        '_assetID': { name: 'assetID', format: 'string' },\n        '_canDiscover': { name: 'canDiscover', format: 'boolean' },\n        '_canShare': { name: 'canShare', format: 'boolean' },\n        '_commentPermissions': { name: 'commentPermissions', isArray: true },\n    })\n});\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\n// https://identity.corp.adobe.com/abs/docs/#_resolveurn\nexport interface IResolveAddressBookGroupResponse {\n    url: string;\n}\n\nexport interface IABSPageLinks {\n    next: { href: string };\n}\n\n// https://identity.corp.adobe.com/abs/docs/#_contactcoreresource\nexport interface IAddressBookContact {\n    /** unique identifier for this contact */\n    ident: string;\n    /** the unique identifier for the AddressBook this contact is a member of */\n    addressBookIdent: string;\n    countryCode?: string;\n    displayName?: string;\n    email?: string;\n    firstName?: string;\n    images?: Record<string, string>;\n    lastName?: string;\n    linkPolicy?: 'HARD_LINK' | 'NO_LINK' | 'SOFT_LINK';\n    linkedIdentity?: string;\n    urn?: string;\n}\n\n// https://identity.corp.adobe.com/abs/docs/#_listflatmembers\nexport interface IAddressBookGroupMembersFlat {\n    _embedded: {\n        contacts: IAddressBookContact[];\n    };\n    _links: IABSPageLinks;\n    total: number;\n}\n\nexport interface IAddressBook {\n    ident: string;\n    displayName: string;\n    ownerId: string;\n    _links: {\n        self: { href: string; }\n    };\n}\n\n// https://identity.corp.adobe.com/abs/docs/#_listaddressbooks\nexport interface IAddressBookList {\n    _embedded: {\n        addressBooks: IAddressBook[];\n    };\n    _links: IABSPageLinks;\n    total: number;\n}\n\nexport function extractAddressBookIdent(url: string): string {\n    return (new URL(url)).pathname.match(/^\\/api\\/address-books\\/[^/]+/)![1];\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type InvitationInterface from '../interface/InvitationInterface';\nimport type { IComputedInvitationCollaborator } from '../interface/InvitationModel';\nimport type Collaborator from './Collaborator';\nimport { CollaboratorUpdater } from './Collaborator';\nimport type { IItemLoader, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { CollaboratorConfig } from './CollaboratorSource';\n\nexport default class CollaboratorLoader implements IItemLoader<CollaboratorConfig> {\n\n    constructor(\n        private _collaboratorPool: ItemPool<Collaborator>,\n        private _invitationInterface: InvitationInterface,\n        private _urn: string) {\n    }\n\n    async loadPage(): Promise<ILoadedPage<CollaboratorConfig>> {\n        // FIXME: Implement latency tracker once we move more collaborator operations into SAM.JS.\n\n        // Note, this request is piggy-backed, so if we load both the collaborators and invited collaborators at the same\n        // time, it only results in one network call\n        const result = await this._invitationInterface.getCollaborators(this._urn);\n\n        // Update the collaborators\n        const collaboratorUpdateSession = this._collaboratorPool.createLoaderUpdateSession(Date.now());\n        const directSet = new Set(result.directCollaborators.map(({ id }) => id));\n        const collaboratorsWithComputedProps: IComputedInvitationCollaborator[] = result.collaborators.map(collaborator => {\n            const isDirect = directSet.has(collaborator.id);\n            const canDiscover = isDirect\n                ? result.directCollaborators.find(dc => dc.id === collaborator.id)?.canDiscover ?? false\n                : false;\n            return { ...collaborator, isDirect, canDiscover };\n        });\n        const collaborators = CollaboratorUpdater.updateRemoteItems(collaboratorUpdateSession, collaboratorsWithComputedProps);\n        collaboratorUpdateSession.commit();\n\n        return { items: collaborators };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemBase from '../core/ItemBase';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\n\nimport type { CollaboratorRole, InheritanceType } from './Collaborator';\nimport { CollaboratorRoles, InheritanceTypes } from './Collaborator';\nimport type { IInvitation } from '../interface/InvitationModel';\n\nexport default class InvitedCollaborator extends ItemBase {\n\n    private _email: string = '';\n    private _role: CollaboratorRole = 'viewer';\n    private _canComment: boolean = false;\n    private _canShare: boolean = false;\n    private _acceptanceRequired: boolean = false;\n    private _inheritance?: InheritanceType;\n    private _created: Date = new Date;\n\n    get invitationID(): string {\n        return this.id;\n    }\n\n    // Invited email\n    get email(): string {\n        return this._email;\n    }\n\n    get role(): CollaboratorRole {\n        return this._role;\n    }\n\n    get canComment(): boolean {\n        return this._canComment;\n    }\n\n    get canShare(): boolean {\n        return this._canShare;\n    }\n\n    get acceptanceRequired(): boolean {\n        return this._acceptanceRequired;\n    }\n\n    get inheritance(): InheritanceType | undefined {\n        return this._inheritance;\n    }\n\n    get created(): Date {\n        return this._created;\n    }\n}\n\nexport const InvitedCollaboratorUpdater = new ItemUpdater<InvitedCollaborator, Partial<IInvitation>>({\n    localItemType: InvitedCollaborator,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_email': 'email',\n        '_role': { name: 'role', choices: CollaboratorRoles },\n        '_canComment': { name: 'canComment', format: 'boolean' },\n        '_canShare': { name: 'canShare', format: 'boolean' },\n        '_acceptanceRequired': { name: 'acceptanceRequired', format: 'boolean' },\n        '_inheritance': { name: 'inheritance', choices: InheritanceTypes },\n        '_created': { name: 'created', format: 'date_as_number' }\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type InvitationInterface from '../interface/InvitationInterface';\nimport type InvitedCollaborator from './InvitedCollaborator';\nimport { InvitedCollaboratorUpdater } from './InvitedCollaborator';\nimport type { IItemLoader, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { InvitedCollaboratorConfig } from './InvitedCollaboratorSource';\n\nexport default class InvitedCollaboratorLoader implements IItemLoader<InvitedCollaboratorConfig> {\n\n    constructor(\n        private _invitedCollaboratorPool: ItemPool<InvitedCollaborator>,\n        private _invitationInterface: InvitationInterface,\n        private _urn: string) {\n    }\n\n    async loadPage(): Promise<ILoadedPage<InvitedCollaboratorConfig>> {\n        // FIXME: Implement latency tracker once we move more collaborator operations into SAM.JS.\n\n        // Note, this request is piggy-backed, so if we load both the collaborators and invited collaborators at the same\n        // time, it only results in one network call\n        const result = await this._invitationInterface.getCollaborators(this._urn);\n\n        // Update the pending invitations\n        const invitedCollaboratorUpdateSession = this._invitedCollaboratorPool.createLoaderUpdateSession(Date.now());\n        const invitedCollaborators = InvitedCollaboratorUpdater.updateRemoteItems(invitedCollaboratorUpdateSession, result.invitations);\n        invitedCollaboratorUpdateSession.commit();\n\n        return { items: invitedCollaborators };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemBase from '../core/ItemBase';\nimport type { PropertyFormatType } from '../core/PropertyUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { ISAMObject } from '../indexPrivate';\nimport ItemPool from '../core/ItemPool';\nimport { isDeepEqual } from '../core/ObjectUtils';\nimport SAMError from '../core/SAMError';\nimport type { IInvitationCollaborator, IInvitationShareBatchResponseItem, IInvitationShareResponse } from '../interface/InvitationModel';\nimport type Collaborator from './Collaborator';\nimport { CollaboratorUpdater } from './Collaborator';\n\nexport default class CollaboratorsByAssetID extends ItemBase {\n    private _collaborators: Collaborator[] = [];\n    private _error: SAMError | undefined = undefined;\n\n    /**\n     * Since collaborators are a model around the relationship of a\n     * particular user and an asset, it should always have an AssetID.\n     */\n    get getAssetID(): string {\n        return this.id;\n    }\n\n    get collaborators(): Collaborator[] {\n        return this._collaborators;\n    }\n\n    get error(): SAMError | undefined {\n        return this._error;\n    }\n}\n\nconst CollaboratorFormat: PropertyFormatType = {\n    parse: (value: Collaborator[]): Collaborator[] => {\n        return value;\n    },\n    isEqual: (a: Collaborator[], b: Collaborator[]): boolean => {\n        return isDeepEqual(a, b);\n    }\n};\n\nfunction getCollaborators(source: Partial<IInvitationShareBatchResponseItem>, dest: ISAMObject): Collaborator[] {\n    const collaboratorPool = new ItemPool<Collaborator>(dest._core, 'collaborator');\n    const session = collaboratorPool.createUpdateSession();\n    // failed to fetch collaborators for this asset\n    if (source.statusCode! !== 200) {\n        return [];\n    }\n    const response: IInvitationShareResponse = JSON.parse(source.response!);\n\n    // Add the assetID to the response from the URN provided by\n    // the service so Collaborators are tied to an asset.\n    const collaboratorsWithID = response.collaborators.map((collab: IInvitationCollaborator) => {\n        return { ...collab, assetID: source.urn };\n    });\n    const collaborators = CollaboratorUpdater.updateRemoteItems(session, collaboratorsWithID);\n    session.commit();\n    return collaborators;\n}\n\nconst ErrorFormat: PropertyFormatType = {\n    parse: (value: SAMError): SAMError => {\n        return value;\n    },\n    isEqual: (a: SAMError, b: SAMError): boolean => {\n        return isDeepEqual(a, b);\n    }\n};\n\nfunction getError(source: Partial<IInvitationShareBatchResponseItem>): SAMError | undefined {\n    if (source.statusCode! === 200) {\n        return undefined;\n    }\n    // this is how a sample response looks like (got it from the sam.js demo)\n    // response: '{\"statusCode\":404,\"error\":\"Not Found\"}'\n    const response = JSON.parse(source.response!);\n    return SAMError.createWithRepositoryCode(response.statusCode, '', response.error);\n}\n\nexport const CollaboratorsByAssetIDUpdater = new ItemUpdater<CollaboratorsByAssetID, Partial<IInvitationShareBatchResponseItem>>({\n    localItemType: CollaboratorsByAssetID,\n    remoteIdProperty: 'urn',\n    propertyUpdater: new PropertyUpdater({\n        '_collaborators': { get: getCollaborators, format: CollaboratorFormat },\n        '_error': { get: getError, format: ErrorFormat }\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type InvitationInterface from '../interface/InvitationInterface';\nimport type CollaboratorsByAssetID from './CollaboratorsByAssetID';\nimport { CollaboratorsByAssetIDUpdater } from './CollaboratorsByAssetID';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { CollaboratorsByAssetIDConfig } from './CollaboratorsByAssetIDSource';\n\nexport default class CollaboratorsByAssetIDLoader implements IItemLoader<CollaboratorsByAssetIDConfig> {\n\n    constructor(\n        private _collaboratorsByAssetIDPool: ItemPool<CollaboratorsByAssetID>,\n        private _invitationInterface: InvitationInterface,\n        private _assetIDs: string[]) {\n    }\n\n    async loadPage(options: IItemLoaderOptions<CollaboratorsByAssetIDConfig>): Promise<ILoadedPage<CollaboratorsByAssetIDConfig>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<CollaboratorsByAssetIDConfig>, start: number = 0): Promise<ILoadedPage<CollaboratorsByAssetIDConfig>> {\n        // max limit supported by invitation service batch api is 50, capping limit\n        const limit = Math.min(options.loadOptions?.limit ?? Infinity, this._invitationInterface.batchRequestLimit);\n\n        const slicedAssetIDs = this._assetIDs.slice(start, start + limit);\n\n        const batchInvitationResponse = await this._invitationInterface.getCollaboratorListForUrns(slicedAssetIDs);\n        const session = this._collaboratorsByAssetIDPool.createLoaderUpdateSession(Date.now());\n        const collaboratorByAssetIDs = CollaboratorsByAssetIDUpdater.updateRemoteItems(session, batchInvitationResponse.result);\n        session.commit();\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<CollaboratorsByAssetIDConfig> | undefined;\n        if (start + collaboratorByAssetIDs.length < this._assetIDs.length) {\n            loadNextPage = (options: IItemLoaderOptions<CollaboratorsByAssetIDConfig>) =>\n                this._loadPage(options, start + collaboratorByAssetIDs.length);\n        }\n\n        return { items: collaboratorByAssetIDs, loadNextPage };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport { ManagedPromise } from '../utils/ManagedPromise';\n\nclass BatchOperationQueue<T extends { id: string }> {\n    // Sets are guaranteed to be iterated in FIFO order\n    private _itemQueue: Set<T> = new Set();\n    private _itemPromises: Map<T, ManagedPromise<void>> = new Map();\n    private _inFlightBatches: Set<{ batch: Set<T>, promise: Promise<void> }> = new Set();\n    private _timer: any;\n\n    constructor(\n        private _batchProcessor: (items: Set<T>) => Promise<void>,\n        private _maxItemsPerBatch: number = 50,\n        private _delay: number = 50,\n        private _maxInFlightBatches: number = 3\n    ) {}\n\n    enqueue(item: T): Promise<void> {\n        // Already in progress\n        if (this.isInQueue(item) || this.isInFlight(item)) {\n            return this._itemPromises.get(item)!.promise;\n        }\n        this._itemQueue.add(item);\n        const managedPromise = new ManagedPromise<void>();\n        this._itemPromises.set(item, managedPromise);\n        if (!this._timer) {\n            this._timer = setTimeout(this._processQueue, this._delay);\n        }\n        // Don't wait to process the batch if a max-size batch request can be made\n        if (this._itemQueue.size >= this._maxItemsPerBatch) {\n            this._processQueue();\n        }\n        return managedPromise.promise;\n    }\n\n    dequeue(item: T): boolean {\n        const hasItem = this._itemQueue.has(item);\n        this._itemQueue.delete(item);\n        // Only resolve if still pending, otherwise it is too late to dequeue and must wait for the batch result\n        if (hasItem) {\n            this._itemPromises.get(item)!.resolve();\n            this._itemPromises.delete(item);\n        }\n        return hasItem;\n    }\n\n    /**\n     * Called by batchProcessor implementation if it needs to mark some items in the batch as successes, and some\n     * as failures. If it does neither, it will assume that resolving the batchProcessor means all succeeded, and\n     * rejecting the batchProcessor will mean all failed.\n     *\n     * @param item {T}\n     */\n    resolveItemPromise(item: T): void {\n        this._itemPromises.get(item)?.resolve();\n        this._itemPromises.delete(item);\n    }\n\n    rejectItemPromise(item: T): void {\n        this._itemPromises.get(item)?.reject();\n        this._itemPromises.delete(item);\n    }\n\n    get size(): number {\n        return this._itemQueue.size;\n    }\n\n    get inFlightCount(): number {\n        return this._inFlightBatches.size;\n    }\n\n    isInQueue(item: T): boolean {\n        return this._itemQueue.has(item);\n    }\n\n    isInFlight(item: T): boolean {\n        return !![ ... this._inFlightBatches ].find(inFlightBatch => inFlightBatch.batch.has(item));\n    }\n\n    /**\n     * Forces the queue to run all batches as fast as possible.\n     *\n     * @package -- for internal SAM.js use only\n     */\n    async _processNow(): Promise<void> {\n        if (!this._itemQueue.size && !this._inFlightBatches.size) {\n            // No work to do\n            return;\n        }\n        do {\n            this._processQueue();\n            try {\n                await Promise.race([ ...this._inFlightBatches ].map(batch => batch.promise));\n            } catch (e) {\n                // do nothing\n            }\n        } while (this._itemQueue.size);\n    }\n\n    private _processQueue = async () => {\n        clearTimeout(this._timer);\n        this._timer = undefined;\n\n        try {\n            if (this.inFlightCount >= this._maxInFlightBatches) {\n                await Promise.race([ ...this._inFlightBatches ].map(inFlightBatch => inFlightBatch.promise));\n            }\n        } catch (e) {\n            // Do nothing\n        }\n\n        while (this.inFlightCount <= this._maxInFlightBatches && this._itemQueue.size > 0) {\n            const batch: Set<T> = new Set();\n            while (this._itemQueue.size > 0 && batch.size < this._maxItemsPerBatch) {\n                const item = this._itemQueue.values().next().value;\n                this._itemQueue.delete(item);\n                batch.add(item);\n            }\n\n            // self-deleting batch Promise\n            const inFlightBatch = {\n                batch,\n                promise: this._batchProcessor(batch)\n                    .catch(() => { [ ...batch.values() ].forEach((item) => this.rejectItemPromise(item)); })\n                    .finally(() => {\n                        this._inFlightBatches.delete(inFlightBatch);\n                        [ ...batch.values() ].forEach(item => this.resolveItemPromise(item));\n                    })\n            };\n            this._inFlightBatches.add(inFlightBatch);\n        }\n\n        if (this._itemQueue.size > 0 && !this._timer) {\n            this._timer = setTimeout(this._processQueue, this._delay);\n        }\n    };\n}\n\nexport default BatchOperationQueue;\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport ItemBase from '../core/ItemBase';\nimport {\n    observable\n} from '../core/decorators';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { IAddressBook } from '../interface/AddressBookModel';\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport type AddressBookContact from './AddressBookContact';\n\n\nexport default class AddressBook extends ItemBase {\n    private _displayName: string = '';\n    private _ownerId: string = '';\n\n    constructor(_core: ISAMCorePrivate, id: string) {\n        super(_core, id);\n    }\n\n    @observable\n    get ident(): string {\n        return this.id;\n    }\n\n    @observable\n    get displayName(): string {\n        return this._displayName;\n    }\n\n    @observable\n    get ownerId(): string {\n        return this._ownerId;\n    }\n\n    async getContactInAddressBook(adobeId: string): Promise<AddressBookContact> {\n        return this._core.collaborationContext.getContactInAddressBook(this.ident, adobeId);\n    }\n}\n\nexport const AddressBookUpdater = new ItemUpdater<AddressBook, IAddressBook>({\n    localItemType: AddressBook,\n    remoteIdProperty: 'ident',\n    propertyUpdater: new PropertyUpdater({\n        _displayName: 'displayName',\n        _ownerId: 'ownerId'\n    })\n});\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type {\n    IItemLoader,\n    IItemLoaderOptions,\n    ILoadedPage\n} from '../core/ItemLoader';\nimport type { AddressBookConfig } from './AddressBookSource';\nimport type AddressBook from './AddressBook';\nimport type ItemPool from '../core/ItemPool';\nimport type AddressBookInterface from '../interface/AddressBookInterface';\nimport type {\n    IAddressBook,\n    IAddressBookList\n} from '../interface/AddressBookModel';\nimport type ItemUpdater from '../core/ItemUpdater';\n\nexport default class AddressBookLoader implements IItemLoader<AddressBookConfig> {\n\n    constructor(\n        private _addressBookPool: ItemPool<AddressBook>,\n        private _addressBookInterface: AddressBookInterface,\n        private _addressBookUpdater: ItemUpdater<AddressBook, IAddressBook>\n    ) {}\n\n    async loadPage(options?: IItemLoaderOptions<AddressBookConfig>): Promise<ILoadedPage<AddressBookConfig>> {\n        const { limit = 100 } = options?.loadOptions || { limit: 100 };\n        // Currently, pagination isn't supported because it is difficult to find a list of >1\n        // AddressBooks to validate the pagination works\n        const result: IAddressBookList = await this._addressBookInterface.getAddressBooks(limit);\n        const session = this._addressBookPool.createLoaderMutationSession();\n        const items = this._addressBookUpdater.updateRemoteItems(session, result._embedded.addressBooks);\n\n        return { items, total: result.total };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, createItemOrderFactory } from '../core/ItemOrder';\nimport type Collaborator from './Collaborator';\n\nexport type CollaboratorOrderField = 'name';\n\nconst OrderFieldToComparator: IComparatorMap<Collaborator, CollaboratorOrderField> = {\n    name(a: Collaborator, b: Collaborator): number {\n        return compareStrings(a.name ?? a.id, b.name ?? a.id);\n    }\n};\n\nexport default class CollaboratorOrder extends createItemOrderFactory(OrderFieldToComparator) implements SAM.CollaboratorOrder {\n    static default = new CollaboratorOrder('ascending', 'name');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, createItemOrderFactory } from '../core/ItemOrder';\nimport type InvitedCollaborator from './InvitedCollaborator';\n\nexport type InvitedCollaboratorOrderField = 'email';\n\nconst OrderFieldToComparator: IComparatorMap<InvitedCollaborator, InvitedCollaboratorOrderField> = {\n    email(a: InvitedCollaborator, b: InvitedCollaborator): number {\n        return compareStrings(a.email ?? a.id, b.email ?? a.id);\n    }\n};\n\nexport default class InvitedCollaboratorOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new InvitedCollaboratorOrder('ascending', 'email');\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type {\n    IComparatorMap\n} from '../core/ItemOrder';\nimport {\n    compareStrings,\n    createItemOrderFactory\n} from '../core/ItemOrder';\nimport type AddressBook from './AddressBook';\n\nexport type AddressBookOrderField = 'displayName';\n\nconst OrderFieldToComparator: IComparatorMap<AddressBook, AddressBookOrderField> = {\n    displayName(a: AddressBook, b: AddressBook): number {\n        return compareStrings(a.displayName, b.displayName);\n    }\n};\n\nexport default class AddressBookOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new AddressBookOrder('ascending', 'displayName');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemPool from '../core/ItemPool';\nimport ItemSource from '../core/ItemSource';\nimport type {\n    ISAMCorePrivate,\n    ISAMObject } from '../indexPrivate';\nimport {\n    SharedCollaboratorChangedEvent,\n} from '../indexPrivate';\nimport InvitationInterface from '../interface/InvitationInterface';\nimport Collaborator, { CollaboratorUpdater } from './Collaborator';\nimport type InvitedCollaborator from './InvitedCollaborator';\nimport CollaboratorLoader from './CollaboratorLoader';\nimport InvitedCollaboratorLoader from './InvitedCollaboratorLoader';\nimport type { CollaboratorConfig, CollaboratorSource } from './CollaboratorSource';\nimport CollaboratorsByAssetIDLoader from './CollaboratorsByAssetIDLoader';\nimport type { InvitedCollaboratorConfig, InvitedCollaboratorSource } from './InvitedCollaboratorSource';\nimport type CollaboratorsByAssetID from './CollaboratorsByAssetID';\nimport type { CollaboratorsByAssetIDConfig, CollaboratorsByAssetIDSource } from './CollaboratorsByAssetIDSource';\nimport EverythingFilter from '../core/EverythingFilter';\nimport BatchOperationQueue from '../core/BatchOperationQueue';\nimport type ShareableItem from './ShareableItem';\nimport type {\n    IInvitationShareBatchResponseItem,\n    IInvitationShareResponse,\n    IInvitationShareBatchResponse,\n    IInvitationShareRequest,\n    IInvitationRecipient,\n    IPendingInvitation,\n    IInvitationConfiguration,\n    IInvitationNotification,\n    IInvitationCaptcha,\n    IComputedInvitationCollaborator,\n    IInvitationPatch,\n    IInvitationSharePatchRequest,\n    IAddCollaboratorResult,\n    IAccessRequestNotification,\n    IAccessRequestPermissions,\n    IAccessRequestResult\n} from '../interface/InvitationModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport { LazyLoadManager } from '../core/decorators/LazyLoadManager';\nimport AddressBookInterface from '../interface/AddressBookInterface';\nimport { memoize } from '../core/decorators';\nimport type AddressBook from './AddressBook';\nimport { AddressBookUpdater } from './AddressBook';\nimport type { AddressBookSource } from './AddressBookSource';\nimport AddressBookLoader from './AddressBookLoader';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport type AddressBookContact from './AddressBookContact';\nimport { AddressBookContactUpdater } from './AddressBookContact';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport {\n    default as CollaboratorOrder,\n    type CollaboratorOrderField\n} from './CollaboratorOrder';\nimport {\n    default as InvitedCollaboratorOrder,\n    type InvitedCollaboratorOrderField\n} from './InvitedCollaboratorOrder';\nimport type { AddressBookOrderField } from './AddressBookOrder';\nimport AddressBookOrder from './AddressBookOrder';\n\nexport interface ICollaboratorSources {\n    collaboratorPool: ItemPool<Collaborator>,\n    collaboratorSource: ItemSource<CollaboratorConfig>,\n    invitedCollaboratorPool: ItemPool<InvitedCollaborator>,\n    invitedCollaboratorSource: ItemSource<InvitedCollaboratorConfig>\n}\n\nexport type AssetToCollaborator = {\n    id: string;\n    collaborator: Collaborator;\n}\n\n\nexport default class CollaborationContext implements ISAMObject {\n\n    private _collaboratorSourceMap = new Map<string, ICollaboratorSources>();\n    private _invitationInterface = new InvitationInterface(this._core);\n    private _collaboratorsByAssetIDPool = new ItemPool<CollaboratorsByAssetID>(this._core, 'collaboratorsByAssetID');\n    private _accessConfirmedIDs = new Set<string>();\n    private _addressBookPool = new ItemPool<AddressBook>(this._core, 'addressBook');\n    // Note: presuming that AddressBookContact is unique to an AddressBook\n    private _addressBookContactPoolMap = new Map<string, ItemPool<AddressBookContact>>();\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _collaboratorRequestQueue: BatchOperationQueue<ShareableItem>;\n\n    constructor(readonly _core: ISAMCorePrivate) {\n        this._collaboratorRequestQueue = new BatchOperationQueue<ShareableItem>(this._handleBatchRequest);\n    }\n\n    private _handleBatchRequest = async (items: Set<ShareableItem>): Promise<void> => {\n        const assetMap = new Map([ ...items ].map(item => [ item.id, item ]));\n        const batchInvitationResponse: IInvitationShareBatchResponse = await this._invitationInterface.getCollaboratorListForUrns([ ...assetMap.keys() ]);\n        const results: IInvitationShareBatchResponseItem[] = batchInvitationResponse.result;\n        results.forEach((result: IInvitationShareBatchResponseItem) => {\n            const assetId = result.urn;\n            const asset = assetMap.get(assetId);\n            if (!asset) {\n                return;\n            }\n            if (result.statusCode !== 200) {\n                // Reject the item promise so that the item can be fetched again later.\n                this._collaboratorRequestQueue.rejectItemPromise(asset);\n                return;\n            }\n\n            const sources = this._getCollaboratorSources(assetId);\n            const invitationResponse: IInvitationShareResponse = JSON.parse(result.response);\n\n            // Add the assetId and isDirect to the returned data.\n            const collaboratorsWithAssetIds: IComputedInvitationCollaborator[] = invitationResponse.collaborators.map(\n                (collaboratorData) => {\n                    const isDirectCollaborator = invitationResponse.directCollaborators.find((c) => c.id === collaboratorData.id);\n                    return {\n                        ...collaboratorData,\n                        assetID: assetId,\n                        isDirect: !!isDirectCollaborator\n                    };\n                }\n            );\n\n            const collaboratorUpdateSession = sources.collaboratorPool.createUpdateSession();\n            const collaborators = CollaboratorUpdater.updateRemoteItems(collaboratorUpdateSession, collaboratorsWithAssetIds);\n            collaboratorUpdateSession.commit();\n\n            asset._setCollaboratorData(collaborators);\n        });\n    };\n\n    /**\n     * For use-cases where we want to immediately fetch collaborators but using the batch system\n     * instead of the collaborator listing.\n     */\n    private async _getCollaboratorsNow(asset: ShareableItem): Promise<void> {\n        await this._collaboratorRequestQueue.enqueue(asset);\n        await this._collaboratorRequestQueue._processNow();\n        if (LazyLoadManager.hasManager(asset, SharedCollaboratorChangedEvent)) {\n            LazyLoadManager.updatedExternally(asset, SharedCollaboratorChangedEvent);\n        } else {\n            // SAM.cpp doesn't have LazyLoadManager\n            asset.dispatch(SharedCollaboratorChangedEvent);\n        }\n    }\n\n    /**\n     * get a list of Collaborators\n     * @param assetsIDs list of assetIDs (including from Teams and Spaces, not just AdobeAssets)\n     */\n    /**\n     * @deprecated -- will be removed on or after 2024-10-01\n     *  Use {@link ShareableItem.collaboratorArray} instead.\n     */\n    getCollaboratorsForAssets(assetsIDs: string[]): CollaboratorsByAssetIDSource {\n        oneTimeWarning('getCollaboratorsForAssets',\n            'This method is deprecated and will be removed. Use ShareableItem.collaboratorArray instead.');\n        const loader = new CollaboratorsByAssetIDLoader(this._collaboratorsByAssetIDPool, this._invitationInterface, assetsIDs);\n        const source = new ItemSource<CollaboratorsByAssetIDConfig>(this._collaboratorsByAssetIDPool, [ loader ], new EverythingFilter());\n        return source;\n    }\n\n    /**\n     * Get's all the ItemSources for Collaborators and InvitedCollaborators.\n     * @note ItemPools for collaborators can't be shared between assets because they may have different roles per asset.\n     * @note This no longer stores and returns WeakRefs due to how we have to update the collaborators, it causes\n     * the refs to be reclaimed before we are able to update the collaborators with new information and causes\n     * new item pools to be created everytime.\n     * @package used internally only\n     */\n    _getCollaboratorSources(assetID: string): ICollaboratorSources {\n        const sources = this._collaboratorSourceMap.get(assetID);\n        if (sources) {\n            return sources;\n        }\n\n        // We cannot share the pools for Collaborator/InvitedCollaborator objects between\n        // assets as they might have different roles for the same IDs.\n        const collaboratorPool = new ItemPool<Collaborator>(this._core, 'collaborator');\n        const collaboratorLoader = new CollaboratorLoader(collaboratorPool, this._invitationInterface, assetID);\n        const collaboratorSource = new ItemSource<CollaboratorConfig>(collaboratorPool, [ collaboratorLoader ], new EverythingFilter());\n\n        const invitedCollaboratorPool = new ItemPool<InvitedCollaborator>(this._core, 'invitedCollaborator');\n        const invitedCollaboratorLoader = new InvitedCollaboratorLoader(invitedCollaboratorPool, this._invitationInterface, assetID);\n        const invitedCollaboratorSource = new ItemSource<InvitedCollaboratorConfig>(invitedCollaboratorPool, [ invitedCollaboratorLoader ], new EverythingFilter());\n\n        const collaboratorSources = { collaboratorPool, collaboratorSource, invitedCollaboratorPool, invitedCollaboratorSource };\n        this._collaboratorSourceMap.set(assetID, collaboratorSources);\n        return collaboratorSources;\n    }\n\n    /**\n     * @deprecated -- will be removed on or after 2024-10-01\n     *    Use {@link ShareableItem.collaboratorArray} instead\n     */\n    getCollaborators(assetID: string): CollaboratorSource {\n        oneTimeWarning('CollaborationContext.getCollaborators',\n            'This method is deprecated and will be removed. Use ShareableItem.collaboratorArray instead.');\n        return this._getCollaboratorSources(assetID).collaboratorSource;\n    }\n\n    /**\n     * @deprecated -- will be renamed for internal use on or after 2024-10-01.\n     *   Use {@link ShareableItem.removeCollaborator} instead\n     */\n    async removeCollaborator(assetID: string, collaborator: Collaborator): Promise<void> {\n        oneTimeWarning('CollaborationContext.removeCollaborator',\n            'This method is deprecated and will be removed on or after 2024-10-01. Use ShareableItem.removeCollaborator instead.');\n        return this._removeCollaborator(assetID, collaborator);\n    }\n\n    /**\n     * Removes the provided Collaborator and updates the ItemPools.\n     *\n     * This eventually performs a PATCH request to the invitations service and removes the provided invited\n     * collaborator.\n     *\n     * @package -- for use in SAM.js only\n     *\n     * @throws If the request is not successful, an error is thrown.\n     *\n     * @param assetID\n     * @param collaborator {Collaborator}\n     */\n    async _removeCollaborator(assetID: string, collaborator: Collaborator): Promise<void> {\n        const response = await this._invitationInterface.modifyCollaborators(\n            assetID,\n            {\n                collaborators: [ { id: collaborator.id, action: 'remove' } ]\n            }\n        );\n\n        const collaboratorResponse = response.collaborators?.find((c) => c.id === collaborator.id);\n        if (!collaboratorResponse) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Collaborator patch request unsuccessful');\n        }\n\n        if (collaboratorResponse.statusCode !== 200) {\n            throw SAMError.createWithRepositoryCode(\n                collaboratorResponse.statusCode,\n                collaboratorResponse.errorSubcode ?? '',\n                collaboratorResponse.statusText\n            );\n        }\n\n        const { collaboratorPool } = this._getCollaboratorSources(assetID);\n        const updateSession = collaboratorPool.createUpdateSession();\n        updateSession.queueDiscardedItem(collaborator);\n\n        // If the current user is being removed from the collaboration list, remove the asset from accessConfirmedIDs\n        // in case the user is re-invited to the asset and needs to confirm access again.\n        if (collaborator.isCurrentUser) {\n            this._accessConfirmedIDs.delete(assetID);\n        }\n        updateSession.commit();\n    }\n\n    /**\n     * Removes the provided InvitedCollaborator and updates the ItemPools.\n     *\n     * This eventually performs a PATCH request to the invitations service and removes the provided invited\n     * collaborator.\n     *\n     * @throws If the request is not successful, an error is thrown.\n     *\n     * @param assetID\n     * @param invitedCollaborator {InvitedCollaborator}\n     */\n    /**\n     * @deprecated -- will be removed on or after 2025-01-01.\n     */\n    async removeInvitedCollaborator(assetID: string, invitedCollaborator: InvitedCollaborator): Promise<void> {\n        oneTimeWarning('CollaborationContext.removeInvitedCollaborator',\n            'This method is deprecated and will be removed on or after 2025-01-01.');\n        const response = await this._invitationInterface.modifyCollaborators(\n            assetID,\n            {\n                invitations: [ { id: invitedCollaborator.id, action: 'remove' } ]\n            }\n        );\n\n        const collaboratorResponse = response.invitations?.find((c) => c.id === invitedCollaborator.id);\n        if (!collaboratorResponse) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'InvitedCollaborator patch request unsuccessful');\n        }\n\n        if (collaboratorResponse.statusCode !== 200) {\n            throw SAMError.createWithRepositoryCode(\n                collaboratorResponse.statusCode,\n                collaboratorResponse.errorSubcode ?? '',\n                collaboratorResponse.statusText\n            );\n        }\n\n        const { invitedCollaboratorPool } = this._getCollaboratorSources(assetID);\n        const updateSession = invitedCollaboratorPool.createUpdateSession();\n        updateSession.queueDiscardedItem(invitedCollaborator);\n        updateSession.commit();\n    }\n\n    /**\n     * @deprecated -- will be removed on or after 2025-01-01.\n     *    It may be possible to use {@link ShareableItem.collaboratorArray}. If this does not work, contact the\n     *    SAM.js team before removal.\n     */\n    getInvitedCollaborators(assetID: string): InvitedCollaboratorSource {\n        oneTimeWarning('CollaborationContext.getInvitedCollaborators',\n            'This method is deprecated and will be removed on or after 2025-01-01. Use'\n            + ' ShareableItem.collaboratorArray instead.');\n        return this._getCollaboratorSources(assetID).invitedCollaboratorSource;\n    }\n\n    /**\n     * Used by ShareableItem and SAMCpp.ts patches\n     *\n     * @package -- only for use inside SAM.js\n     */\n    async _removeCurrentUserFromCollaborationList(asset: ShareableItem): Promise<void> {\n        // If collaborator array isn't loaded or needs refresh, load it immediately\n        if (!asset._isCollaboratorDataLoaded) {\n            await this._getCollaboratorsNow(asset);\n        }\n        const collaborator = asset.collaboratorArray.find(c => c.isCurrentUser);\n        if (!collaborator) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Current user is not a collaborator on ${asset.id}`);\n        }\n        await this._removeCollaborator(asset.id, collaborator);\n        // _removeCollaborator() will remove the Collaborator from the pools, but it also needs to be removed from the\n        // collaboratorArray, and the collaboration flags need to be re-calculated, and collaboration event listeners\n        // notified.\n        if (asset.collaboratorArray.includes(collaborator)) {\n            const updatedCollaborators = asset.collaboratorArray.filter(c => c !== collaborator);\n            asset._setCollaboratorData(updatedCollaborators);\n            if (LazyLoadManager.hasManager(asset, SharedCollaboratorChangedEvent)) {\n                LazyLoadManager.updatedExternally(asset, SharedCollaboratorChangedEvent);\n            } else {\n                // SAM.cpp doesn't have LazyLoadManager\n                asset.dispatch(SharedCollaboratorChangedEvent);\n            }\n        }\n    }\n\n    /**\n     * @deprecated -- do not use, it does not work for users who were invited via an address book contact,\n     * and may break for all use cases in the future. Instead, use\n     * {@link ShareableItem.removeCurrentUserFromCollaborationList}. Will be removed on or after 2024-10-01.\n     *\n     *  https://jira.corp.adobe.com/browse/SAM-3564\n     */\n    removeCurrentUserFromCollaborationList(assetID: string): Promise<void> {\n        oneTimeWarning('removeCurrentUserFromCollaborationList/getCollaborator',\n            'This method does not work correctly and will be removed. Use'\n            + ' ShareableItem.removeCurrentUserFromCollaboratorList() insstead.');\n        const collaborator = this.getCollaborator(assetID);\n        return this._removeCollaborator(assetID, collaborator);\n    }\n\n    /**\n     * @deprecated -- Do not use, it does not work unless collaborator data is already loaded, and the Collaborator\n     * representing the current user was NOT invited via an address book contact. The Collaborator it returns in most\n     * cases will have invalid data in it. Will be removed on or after 2024-10-01.\n     *\n     * https://jira.corp.adobe.com/browse/SAM-3564\n     */\n    getCollaborator(assetID: string): Collaborator {\n        oneTimeWarning('removeCurrentUserFromCollaborationList/getCollaborator',\n            'This method does not work correctly and will be removed. Use'\n            + ' ShareableItem.collaboratorsArray.find(c => c.isCurrentUser()) instead.');\n\n        const userID = this._core._environment.getValue('USER_ID');\n        const collaborator: Collaborator = this._getCollaboratorSources(assetID).collaboratorPool.getLocalItemById(userID) ?? new Collaborator(this._core, userID);\n        return collaborator;\n    }\n\n    /**\n     *\n     * @package Used internally.\n     *\n     * @param assetID\n     * @param collaborators List of collaborators to add\n     * @param configuration Configuration for the invitation, for example useMounts and acceptanceRequired.\n     * @param notification Notification for the invitation, @note undefined will not send any notifications.\n     * @param captcha Captcha for the invitation.\n     * @param inviterLabel Inviter label for the invitation.\n     */\n    async _addCollaborators(\n        assetID: string,\n        collaborators: IInvitationRecipient[],\n        configuration?: IInvitationConfiguration,\n        /**\n         * Leaving this undefined will not send any notifications.\n         */\n        notification?: IInvitationNotification,\n        captcha?: IInvitationCaptcha,\n        /**\n         * Required for service principal token requests.\n         */\n        inviterLabel?: string\n    ): Promise<IAddCollaboratorResult> {\n        const request: IInvitationShareRequest = {\n            recipients: collaborators,\n            // Notification parameter requires a value.\n            ...(\n                !notification\n                    ? {\n                        notification: {\n                            ans: {}\n                        }\n                    }\n                    : { notification }\n            ),\n            ...(configuration ? { configuration } : {}),\n            ...(captcha ? { captcha } : {}),\n            ...(inviterLabel ? { inviterLabel } : {})\n        };\n        return await this._invitationInterface.addCollaborators(assetID, request);\n    }\n\n    /**\n     * @package -- Used internally.\n     *\n     * @param assetID Resources URN or AssetID of the resource to modify collaborators for.\n     * @param collaborators List of collaborators to add.\n     * @param configuration Configuration for the invitation, for example useMounts and acceptanceRequired.\n     * @param notification Notification for the invitation, @note undefined will not send any notifications.\n     */\n    public async _modifyCollaborators(\n        assetID: string,\n        collaborators: IInvitationPatch[],\n        configuration?: IInvitationConfiguration,\n        notification?: IInvitationNotification\n    ) {\n        const request: IInvitationSharePatchRequest = {\n            collaborators,\n            ...(configuration ? { configuration } : {}),\n            ...(notification ? { notification } : {})\n        };\n        return this._invitationInterface.modifyCollaborators(assetID, request);\n    }\n\n    getPendingInvitations(): Promise<IPendingInvitation> {\n        return this._invitationInterface.getPendingInvitations();\n    }\n\n    /**\n     * A method that confirms access for a resource or asset and keeps\n     * track of that confirmation for this session to prevent\n     * more than one call being made per session per asset.\n     *\n     * Confirming access is not about permissions per se, it's more\n     * about accepting the invitation to a resource that requires acceptance.\n     *\n     * It also handles email/account ambiguity so let's say an email\n     * has more than one adobe account associated with it, calling\n     * confirm access will also resolve this issue at that time.\n     *\n     * @note This is really just a temporary measure until\n     * the Invitations Service can provide a more efficient way\n     * of checking multiple assets at a time to see if they\n     * have already confirmed access for the current user token.\n     *\n     *\n     * @param assetId Resource URN\n     * @returns void\n     */\n    async confirmAccess(assetId: string) {\n        // Skip confirm access call if we have already confirmed access, or if the user is using a guest access token.\n        if (this._accessConfirmedIDs.has(assetId) || this._core._environment.getValue('SESSION_TYPE') === 'guest') {\n            return;\n        }\n\n        await this._invitationInterface.confirmAccess(assetId);\n        this._accessConfirmedIDs.add(assetId);\n    }\n\n    /**\n     * Returns a list of AddressBooks for the current user.\n     *\n     * @experimental -- given the way this feature was rushed in, and some gaps in knowledge\n     * about ABS and GenAI, this may not be the final API. Backward-compatibility will not\n     * be guaranteed.\n     *\n     * @returns {AddressBookSource}\n     */\n    @memoize\n    get addressBookSource(): AddressBookSource {\n        const loader = new AddressBookLoader(this._addressBookPool, new AddressBookInterface(this._core), AddressBookUpdater);\n        return new ItemSource(this._addressBookPool, [ loader ]);\n    }\n\n    /**\n     * @experimental\n     */\n    getAddressBookOrder(direction: IOrderDirection = 'ascending', field: AddressBookOrderField = 'displayName'): AddressBookOrder {\n        return new AddressBookOrder(direction, field);\n    }\n\n    /** @package -- for use in SAM.js only */\n    _getAddressBookContactPool(addressBookIdent: string): ItemPool<AddressBookContact> {\n        let pool = this._addressBookContactPoolMap.get(addressBookIdent);\n        if (!pool) {\n            pool = new ItemPool<AddressBookContact>(this._core, 'addressBookContact');\n            this._addressBookContactPoolMap.set(addressBookIdent, pool);\n        }\n        return pool;\n    }\n\n    /**\n     * For a specified AddressBook, look up the Contact for a specified userId\n     *\n     * @experimental -- given the way this feature was rushed in, and some gaps in knowledge\n     * about ABS and GenAI, this may not be the final API. Backward-compatibility will not\n     * be guaranteed.\n     *\n     * @param {string} addressBookIdent\n     * @param {string} userId\n     * @returns {Promise<AddressBookContact>}\n     */\n    @keepAlive\n    async getContactInAddressBook(addressBookIdent: string, userId: string): Promise<AddressBookContact> {\n        const pool = this._getAddressBookContactPool(addressBookIdent);\n        let contact = pool.getLocalItemById(userId);\n        if (contact) {\n            return contact;\n        }\n        const abs = new AddressBookInterface(this._core);\n        const result = await abs.getContactInAddressBook(addressBookIdent, userId);\n        const session = pool.createMutationSession();\n        contact = AddressBookContactUpdater.updateRemoteItem(session, result);\n        session.commit();\n        return contact;\n    }\n\n    /**\n     * @experimental\n     */\n    getCollaboratorOrder(direction: IOrderDirection = 'ascending', field: CollaboratorOrderField = 'name'): CollaboratorOrder {\n        return new CollaboratorOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getInvitedCollaboratorOrder(direction: IOrderDirection = 'ascending', field: InvitedCollaboratorOrderField = 'email'): InvitedCollaboratorOrder {\n        return new InvitedCollaboratorOrder(direction, field);\n    }\n\n    /**\n     * @package -- Currently only used by Project.requestAccessToLibraryReferences\n     *\n     * Request access to one or more assets.\n     *\n     * @param assetIds - Array of resource URNs or asset IDs to request access to\n     * @param notification - Notification configuration for the access request\n     * @param requestedPermissions - Optional requested permissions. By default, the user will be added as a viewer.\n     * @returns Promise that resolves with results indicating success/failure for each asset\n     *\n     * @throws {SAMError} If the request itself fails (network issues, etc.), but not for individual asset failures\n     */\n    async _requestAccess(\n        assetIds: string[],\n        notification: IAccessRequestNotification,\n        requestedPermissions?: IAccessRequestPermissions\n    ): Promise<IAccessRequestResult> {\n\n        return await this._invitationInterface.createAccessRequest(assetIds, notification, requestedPermissions);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from './AdobeAsset';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { IGetUSSResults, IUSSLoader } from './USSLoaderHelper';\nimport USSLoaderHelper from './USSLoaderHelper';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { USSResponse } from '../interface/USSModel';\nimport type { FFBoardsAdobeAssetConfig } from '../assets/FFBoardsSource';\nimport type FFBoardsInterface from '../interface/FFBoardsInterface';\nimport type { FFBoardsAssetsListingOptions } from '../interface/FFBoardsInterface';\nimport { DEFAULT_MAX_LIMIT } from '../interface/USSv3Interface';\nimport { getMediaTypesFromFilters, getVariableFromObj } from '@sam-js-src/utils/loaderUtils';\n\nexport default class FFBoardsLoader implements IUSSLoader<FFBoardsAdobeAssetConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<FFBoardsAdobeAssetConfig>;\n    /**\n     * @package -- only for use in SAM.js\n     */\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        _core: ISAMCorePrivate,\n        private _ffBoardsInterface: FFBoardsInterface\n    ) {\n        this._ussLoaderHelper = new USSLoaderHelper<FFBoardsAdobeAssetConfig>(assetPool, _core, this);\n    }\n\n    async loadPage(options: IItemLoaderOptions<FFBoardsAdobeAssetConfig>): Promise<ILoadedPage<FFBoardsAdobeAssetConfig>> {\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    private _getListingOptionsFromFilters(implicitFilter: FFBoardsAdobeAssetConfig['implicitFilter'], filter: FFBoardsAdobeAssetConfig['filter']) {\n        const opts = getVariableFromObj('options', filter);\n\n        return {\n            isSharedWithYou: getVariableFromObj('isSharedWithYou', opts),\n            ownedBy: getVariableFromObj('ownedBy', opts),\n            mediaTypes: getMediaTypesFromFilters(implicitFilter, filter)\n        };\n    }\n\n    /**\n     * @package -- only for use by USSLoaderHelper\n     */\n    async _getUSSResults({\n        start,\n        loadOptions,\n        order,\n        implicitFilter,\n        filter\n    }: IGetUSSResults<FFBoardsAdobeAssetConfig>): Promise<USSResponse> {\n        const options: FFBoardsAssetsListingOptions = {\n            start,\n            limit: loadOptions?.limit || DEFAULT_MAX_LIMIT,\n            orderDirection: order.direction,\n            orderBy: order.field,\n            ...this._getListingOptionsFromFilters(implicitFilter, filter)\n        };\n        return this._ffBoardsInterface.getAssets(options);\n    }\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { getUSSFetchFields } from './AssetModel';\nimport InterfaceBase from './InterfaceBase';\nimport type { ISearchQuery, USSResponse } from './USSModel';\nimport { OrderByToUSSOrderBy, SearchProps } from './USSModel';\nimport {\n    updateAssetTypeForUSS\n} from './USSUtils';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport type { USSAdobeAssetOrderField } from '../assets/USSAdobeAssetOrder';\n\ninterface IListingOptions {\n    limit: number;\n    start: number;\n    orderDirection: IOrderDirection;\n    orderBy: USSAdobeAssetOrderField;\n}\n\n\nexport interface FFBoardsAssetsListingOptions extends IListingOptions {\n    mediaTypes?: string[],\n    isSharedWithYou?: boolean,\n    ownedBy?: string\n}\n\nconst DEFAULT_MAX_LIMIT = 50;\n\nconst DefaultListingOptions: IListingOptions = {\n    start: 0,\n    limit: DEFAULT_MAX_LIMIT,\n    orderDirection: 'descending',\n    orderBy: 'modified'\n};\n\nexport default class FFBoardsInterface extends InterfaceBase {\n    private _getCommonFilters(options?: Partial<IListingOptions>): ISearchQuery {\n        const listingOptions: IListingOptions = { ...DefaultListingOptions, ...options };\n\n        return {\n            hints: {\n                acp_platform_v2: true,\n            },\n            fetch_fields: { includes: [ ...getUSSFetchFields(), '_embedded' ] }, //include effective permissions\n            limit: listingOptions.limit,\n            start_index: listingOptions.start,\n            op_none_of: [\n                {\n                    [SearchProps.VISIBILITY]: [ 'hiddenSelf', 'hiddenRecursive' ],\n                }\n            ],\n            sort_orderby: OrderByToUSSOrderBy[listingOptions.orderBy],\n            sort_order: listingOptions.orderDirection === 'ascending' ? 'asc' : 'desc'\n        };\n    }\n\n    async getAssets(options: FFBoardsAssetsListingOptions): Promise<USSResponse> {\n        const { ownedBy, isSharedWithYou, mediaTypes, ...listingOptions } = options;\n        const filters = this._getCommonFilters(listingOptions);\n\n        if (ownedBy) {\n            filters[SearchProps.STORAGE_ASSIGNEE_ID] = ownedBy;\n        }\n\n        if (isSharedWithYou !== undefined) {\n            filters[SearchProps.SHARED_VIA_INVITE] = isSharedWithYou;\n        }\n\n        if (mediaTypes && mediaTypes.length > 0) {\n            updateAssetTypeForUSS(mediaTypes);\n            filters[SearchProps.TYPE] = mediaTypes;\n        }\n\n        return this._core.hostAssetContext._ussInterface.getQueryResponse(filters);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset/*, { USSAdobeAssetUpdaterMetadata }*/  from './AdobeAsset';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { SWYAdobeAssetConfig } from './SWYAdobeAssetSource';\nimport type SWYAdobeAssetFilter from './SWYAdobeAssetFilter';\nimport { OrderFieldToISWYAdobeAssetOrderBy } from './SWYAdobeAssetOrder';\nimport type SWYInterface from '../interface/SWYInterface';\nimport type { USSResponse } from '../interface/USSModel';\nimport type { IGetUSSResults, IUSSLoader } from './USSLoaderHelper';\nimport USSLoaderHelper from './USSLoaderHelper';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type AdobeAssetFilter from '../assets/AdobeAssetFilter';\nimport type LibraryContext from '../libraries/LibraryContext';\n\nexport default class SWYAdobeAssetLoader implements IUSSLoader<SWYAdobeAssetConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<SWYAdobeAssetConfig>;\n    /**\n      * @package -- only for use in SAM.js\n      */\n    _libraryContext?: LibraryContext;\n\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private _swyInterface: SWYInterface,\n    ) {\n        this._ussLoaderHelper = new USSLoaderHelper(assetPool, _core, this);\n    }\n\n    supportsFilter(filter?: SWYAdobeAssetFilter | AdobeAssetFilter): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<SWYAdobeAssetConfig>): Promise<ILoadedPage<SWYAdobeAssetConfig>> {\n        if (!this._libraryContext) {\n            this._libraryContext = await this._core.getLibraryContext();\n        }\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- for use by USSLoaderHelper\n     */\n    async _getUSSResults({\n        start,\n        loadOptions,\n        mediaTypes,\n        excludeMediaTypes,\n        order,\n        resource\n    }: IGetUSSResults<SWYAdobeAssetConfig>): Promise<USSResponse> {\n        return this._swyInterface.getSWYAssets({\n            orderBy: OrderFieldToISWYAdobeAssetOrderBy[order.field],\n            orderDirection: order.direction,\n            start,\n            limit: loadOptions?.limit,\n            mediaTypes,\n            excludeMediaTypes,\n            embedPermissions: true\n        }, resource);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from './AdobeAsset';\nimport type { IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { MRUAdobeAssetConfig } from './MRUAdobeAssetSource';\nimport type MRUAdobeAssetFilter from './MRUAdobeAssetFilter';\nimport type RecentInterface from '../interface/RecentInterface';\nimport type { USSResponse } from '../interface/USSModel';\nimport type { IGetUSSResults, IUSSLoader } from './USSLoaderHelper';\nimport USSLoaderHelper from './USSLoaderHelper';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type AdobeAssetFilter from '../assets/AdobeAssetFilter';\nimport type USSAdobeAssetFilter from './USSAdobeAssetFilter';\n\nexport default class MRUAdobeAssetLoader implements IUSSLoader<MRUAdobeAssetConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<MRUAdobeAssetConfig>;\n\n    constructor(\n        assetPool: ItemPool<AdobeAsset>,\n        _core: ISAMCorePrivate,\n        private _recentInterface: RecentInterface\n    ) {\n        this._ussLoaderHelper = new USSLoaderHelper(assetPool, _core, this);\n    }\n\n    supportsFilter(filter?: MRUAdobeAssetFilter | AdobeAssetFilter | USSAdobeAssetFilter): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<MRUAdobeAssetConfig>): Promise<ILoadedPage<MRUAdobeAssetConfig>> {\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- only for use by USSLoaderHelper\n     */\n    async _getUSSResults({\n        start,\n        loadOptions,\n        mediaTypes,\n        excludeMediaTypes\n    }: IGetUSSResults<MRUAdobeAssetConfig>): Promise<USSResponse> {\n        return this._recentInterface.getMRUAssets({\n            start,\n            limit: loadOptions?.limit,\n            mediaTypes,\n            excludeMediaTypes,\n            embedPermissions: true\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport path from 'path-browserify';\nimport type { SAM } from '@ccx-public/component-types';\nimport { key, synchronized } from '../core/decorators';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { COLLABORATOR_CHANGED } from '../indexPrivate';\nimport type ItemPool from '../core/ItemPool';\nimport type { ItemsChangedEvent } from '../core/ItemPool';\nimport { ITEMS_CHANGED } from '../core/ItemPool';\nimport USSInterface from '../interface/USSInterface';\nimport InvitationInterface from '../interface/InvitationInterface';\nimport RepositoryInterface from '../interface/RepositoryInterface';\nimport type { ONSAssetChangeEvent, ONSChangedAssetInfo } from '../sync-services/ONSEvent';\nimport {\n    ONS_FIRST_LONG_POLL_COMPLETED,\n    ONS_FIRST_LONG_POLL_STARTED,\n    ONS_MONITORING_STATUS_CHANGED,\n    ONSFirstLongPollCompletedEvent,\n    ONSFirstLongPollStartedEvent,\n    OnsMonitoringStatus,\n    ONSMonitoringStatusChangedEvent\n} from '../sync-services/ONSEvent';\nimport type {\n    AssetLinks,\n    Assignee,\n    IAppMetadata,\n    IAssetRefRepoAssetId,\n    IBatchOperationResult,\n    IDeleteOperation,\n    IMoveOperation,\n    IOperationQuery,\n    IRepository,\n    MoveCapability,\n    RepositoryMetadata\n} from '../interface/RepositoryModel';\nimport { CannotMoveReason, MoveWarning } from '../interface/RepositoryModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type { ItemId } from '../core/ItemBase';\nimport ItemBase from '../core/ItemBase';\nimport { SAMObjectEventEmitter } from '../core/SAMObjectEventEmitter';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport type { SWYAdobeAssetConfig, SWYAdobeAssetSource } from './SWYAdobeAssetSource';\nimport SBMInterface from '../interface/SBMInterface';\nimport SWYInterface from '../interface/SWYInterface';\nimport AdobeAssetSearchInterface from '../interface/AdobeAssetSearchInterface';\nimport type { RecentAdobeAssetConfig, RecentAdobeAssetSource } from './RecentAdobeAssetSource';\nimport type { AdobeAssetGlobalSearchSource } from './AdobeAssetSource';\nimport AdobeAssetGlobalSearchInterface from '../interface/AdobeAssetGlobalSearchInterface';\nimport RecentInterface from '../interface/RecentInterface';\nimport type AdobeAsset from './AdobeAsset';\nimport { AdobeAssetUpdater, USSAdobeAssetUpdater } from './AdobeAsset';\nimport type { AssetRenameMap, NameConflictMap } from './AssetUtils';\nimport { batchFormatFileName, getBatchRenamedAssetName, isTopLevelFolder, updateCachedDescendents } from './AssetUtils';\nimport AssetTransferInterface from '../interface/AssetTransferInterface';\nimport type { IReviewServiceAssetIdentifer } from '../interface/AssetReviewServiceInterface';\nimport AssetReviewServiceInterface, { mapAssetsToAssetIndentifier } from '../interface/AssetReviewServiceInterface';\nimport Space from '../workspaces/Space';\nimport ItemSource from '../core/ItemSource';\nimport RecentAdobeAssetLoader from './RecentAdobeAssetLoader';\nimport memoize from '../core/decorators/memoize';\nimport RecentAdobeAssetFilter from './RecentAdobeAssetFilter';\nimport { retryFailedOpsDueToConflict } from './ConflictRetryHelper';\nimport type { AssetLoadHints, IPerUserMetadata, IXDCEDocument } from '../interface/AssetModel';\nimport { CLOUD_CONTENT_ROOT_FOLDER, Permission } from '../interface/AssetModel';\nimport type { IItemSourceConfig } from '../core/ItemList';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport type { IEventMap } from '../core/TypedEventEmitter';\nimport type { MRUAdobeAssetConfig, MRUAdobeAssetSource } from './MRUAdobeAssetSource';\nimport MRUAdobeAssetFilter from './MRUAdobeAssetFilter';\nimport type Library from '../libraries/Library';\nimport { isLibrary } from '../libraries/Library';\nimport LibraryInterface from '../interface/LibraryInterface';\nimport PublishedInterface from '../interface/PublishedInterface';\nimport type { PublishedAdobeAssetSource } from './PublishedAdobeAssetSource';\nimport PublishedAdobeAssetLoader from './PublishedAdobeAssetLoader';\nimport PublishedAdobeAssetFilter from './PublishedAdobeAssetFilter';\nimport type { DiscardedAdobeAssetSource } from './DiscardedAdobeAssetSource';\nimport DiscardedAdobeAssetFilter from './DiscardedAdobeAssetFilter';\nimport DiscardedInterface from '../interface/DiscardedInterface';\nimport DiscardedAdobeAssetLoader from './DiscardedAdobeAssetLoader';\nimport AdobeAssetGlobalSearchFilter from './AdobeAssetGlobalSearchFilter';\nimport { RelType } from '../interface/LinkUtils';\nimport USSv3Interface from '../interface/USSv3Interface';\nimport GlobalSearchLoader from './GlobalSearchLoader';\nimport GlobalSearchInterface from '../interface/GlobalSearchInterface';\nimport AdobeAssetGlobalSearchLoader from './AdobeAssetGlobalSearchLoader';\nimport SWYAdobeAssetFilter from './SWYAdobeAssetFilter';\nimport AssetInterface from '../interface/AssetInterface';\nimport type Project from '../projects/Project';\nimport type ChangeEvent from '../core/ChangeEvent';\nimport { CHANGE } from '../core/ChangeEvent';\nimport ProjectsInterface from '../interface/ProjectsInterface';\nimport {\n    appMetadataIsProject,\n    metadataIsStudentAssignment,\n    repoMetadataIsGenerationHistoryAsset\n} from './AdobeAssetFactory';\nimport type { IProject } from '../interface/ProjectsModel';\nimport WeakRef from '../core/WeakRef';\nimport CommentsResource from '../comments/CommentsResource';\nimport { lazyLoaded, LazyLoadManager } from '../core/decorators/LazyLoadManager';\nimport type { IOrganizationsResponse, Organization } from '../interface/OrganizationsModel';\nimport { OrganizationsChangedEventInstance } from '../projects/OrganizationsChangedEvent';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport { default as SWYAdobeAssetOrder, type SWYAdobeAssetOrderField } from './SWYAdobeAssetOrder';\nimport { type AdobeAssetOrderField, default as AdobeAssetOrder } from './AdobeAssetOrder';\nimport { default as USSAdobeAssetOrder, type USSAdobeAssetOrderField } from './USSAdobeAssetOrder';\nimport { default as AdobeAssetFilter, type IAdobeAssetFilterOptions } from './AdobeAssetFilter';\nimport { default as USSAdobeAssetFilter, type IUSSAdobeAssetFilter } from './USSAdobeAssetFilter';\nimport { default as AssetVersionFilter, type IAssetVersionFilterOptions } from './AssetVersionFilter';\nimport { default as AssetVersionOrder } from './AssetVersionOrder';\nimport StudentAssignmentsInterface from '../interface/StudentAssignmentsInterface';\nimport type { IRemoteStudentAssignment } from '../interface/StudentAssignmentModel';\nimport type StudentAssignment from '../assignments/StudentAssignment';\nimport Resource from './Resource';\nimport RepoMetadataResource from './RepoMetadataResource';\nimport AppMetadataResource from './AppMetadataResource';\nimport EffectivePermissionsResource from './EffectivePermissionsResource';\nimport { RequestHeaders } from '../utils/classroomUtils';\nimport { STORAGE_ASSIGNEE_CHANGED } from './AssetEvents';\nimport type AssetLinkManager from '../links/AssetLinkManager';\nimport { NetworkStatus } from './NetworkStatus';\nimport { ONSContext } from '../sync-services/ONSContext';\nimport type { ConfigurationPayload } from '../core/Environment';\nimport { Env } from '../core/Environment';\nimport type { ConfigChangeEvent } from '../core/SAMCoreEvents';\nimport { CONFIG_CHANGE } from '../core/SAMCoreEvents';\nimport { FolderContentChangedEvent } from '../core/FolderContentChangedEvent';\nimport LocalAssetLoader from './LocalAssetLoader';\nimport LocalAdobeAssetFilter from './LocalAdobeAssetFilter';\nimport type { LocalAdobeAssetConfig, LocalAdobeAssetSource } from './LocalAdobeAssetSource';\nimport type { FavoriteAdobeAssetConfig, FavoriteAdobeAssetSource } from './FavoriteAdobeAssetSource';\nimport ImplicitFavoriteAdobeAssetFilter from './ImplicitFavoriteAdobeAssetFilter';\nimport FavoriteAdobeAssetLoader from './FavoriteAdobeAssetLoader';\nimport PerUserMetadataResource from './PerUserMetadataResource';\nimport type { GenerationHistoryAssetData } from '../interface/GenerationHistoryAssetModel';\nimport type { GenerationHistoryContext, GenericAssetList } from '../index';\nimport ACPLModelInterface from '../interface/ACPLModelInterface';\nimport PLSSWYAdobeAssetLoader from './PLSSWYAdobeAssetLoader';\nimport PLSRecentAdobeAssetLoader from './PLSRecentAdobeAssetLoader';\nimport IsSharedFilter, { IsSharedViewSelection } from './IsSharedFilter';\n\n// AssetContext has an implicit dependency on CollaborationContext.\n// This import is used to ensure the CollaborationContext and AssetContext are bundled together.\n// @TODO: https://jira.corp.adobe.com/browse/SAM-3580\nimport '../collaboration/CollaborationContext';\nimport type { FFBoardsAdobeAssetConfig, FFBoardsAdobeAssetSource } from './FFBoardsSource';\nimport FFBoardsLoader from './FFBoardsLoader';\nimport FFBoardsInterface from '../interface/FFBoardsInterface';\nimport SWYAdobeAssetLoader from './SWYAdobeAssetLoader';\nimport MRUAdobeAssetLoader from './MRUAdobeAssetLoader';\n\nexport type IBatchOperationAssetResult = IBatchOperationResult<AdobeAsset>;\n\n// Must be kept in sync with CloudSyncStatus in CCAssetContext.h\nexport enum CloudSyncStatus {\n    Initializing,\n    Offline,\n    NotStarted,\n    Disabled,\n    Synchronized,\n    InProgress,\n    ErrorQuotaExceeded,\n    ErrorSyncDown,\n    ErrorOther\n}\n\nexport interface IQuotaInfo {\n    readonly used: number;\n    readonly total: number;\n}\n\nexport interface IAssetContextEvents extends IEventMap {\n    [CHANGE]: ChangeEvent;\n    [ONS_MONITORING_STATUS_CHANGED]: ONSMonitoringStatusChangedEvent;\n    [ONS_FIRST_LONG_POLL_STARTED]: ONSFirstLongPollStartedEvent;\n    [ONS_FIRST_LONG_POLL_COMPLETED]: ONSFirstLongPollCompletedEvent;\n}\n\nexport default class AssetContext extends SAMObjectEventEmitter<IAssetContextEvents> implements SAM.AssetContext {\n    private _rootFolder?: AdobeAsset;\n    private _homeFolder?: AdobeAsset;\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _rapi: RepositoryInterface = new RepositoryInterface(this._core);\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _invitationInterface: InvitationInterface = new InvitationInterface(this._core);\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _ussInterface: USSInterface = new USSInterface(this._core);\n    private _SBMInterface = new SBMInterface(this._core);\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _swyInterface = new SWYInterface(this._core);\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _recentInterface = new RecentInterface(this._core);\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _adobeAssetSearchInterface = new AdobeAssetSearchInterface(this._core);\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _adobeAssetGlobalSearchInterface = new AdobeAssetGlobalSearchInterface(this._core);\n    private _assetTransferService: AssetTransferInterface = new AssetTransferInterface(this._core);\n    private _assetReviewServiceInterface: AssetReviewServiceInterface = new AssetReviewServiceInterface(this._core);\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _publishedInterface: PublishedInterface = new PublishedInterface(this._core);\n    private readonly _discardedInterface: DiscardedInterface = new DiscardedInterface(this._core);\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly __ussInterfaceV3: USSv3Interface = new USSv3Interface(this._core);\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    readonly _globalSearchInterfaceV3: GlobalSearchInterface = new GlobalSearchInterface(this._core, this.__ussInterfaceV3);\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    readonly _libraryInterface: LibraryInterface = new LibraryInterface(this._core);\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    readonly _acplModelInterface: ACPLModelInterface = new ACPLModelInterface(this._core);\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    readonly _ffBoardsInterface = new FFBoardsInterface(this._core);\n\n    private _commentsById = new Map<string, WeakRef<CommentsResource>>();\n\n    private _organizations: Organization[] | undefined;\n    private _defaultOrganizationId: string | undefined;\n    private _AssetLinkManager: AssetLinkManager | undefined;\n    private _OnsContext: ONSContext | undefined;\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        /**\n         * @package -- only for use in SAM.js\n         */\n        readonly _assetPool: ItemPool<AdobeAsset>\n    ) {\n        super(_core);\n\n        // We want to know all the asset ids that we care about, so we can register for change\n        // notifications with ONS. This consists of all loaded assets in the asset pool.\n        this._assetPool.on(ITEMS_CHANGED, this._onAssetsChanged);\n\n        LazyLoadManager.manageLazyLoading(this, [ {\n            event: OrganizationsChangedEventInstance,\n            fetchData: this._fetchOrganizations,\n            // [SHARED-3811] there's no reason to allow cancelling lazy-loading of orgs\n            prefetchTimeout: 0\n        } ]);\n\n        // Handle dynamic configuration change.\n        this._core.on(CONFIG_CHANGE, (event: ConfigChangeEvent, sender: ISAMCorePrivate, payload: ConfigurationPayload) => {\n            switch (payload.configurationKeyName) {\n            case 'ONS_OVER_AXON':\n                if (this._core._environment.getValue('ENVIRONMENT') === Env.Stage) {\n                    if (this.onsContext) { this.onsContext.useAxon = this._core._environment.getValue('ONS_OVER_AXON'); }\n                } else {\n                    console.warn('Runtime config update for ONS_OVER_AXON is only supported in the Stage environment.');\n                }\n                break;\n            default:\n                break;\n            }\n        });\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     * Updaters shouldn't be accessed directly.\n     */\n    readonly _adobeAssetUpdater = AdobeAssetUpdater;\n\n    /** @package -- for use in SAM.js only */\n    @synchronized\n    async _getONSContext(): Promise<ONSContext> {\n        if (this._OnsContext) { return this._OnsContext; }\n        this._OnsContext = new ONSContext(this._core);\n\n        // Dispatch the initial ONS monitoring status.\n        this.dispatch(new ONSMonitoringStatusChangedEvent(this._OnsContext.onsMonitoringStatus));\n\n        // Attach the ONS asset change event listener.\n        this._OnsContext.on(CHANGE, this._onOnsAssetChangeEvent);\n\n        // Long Poll related events.\n        this._OnsContext.on(ONS_FIRST_LONG_POLL_STARTED, event => {\n            this.dispatch(new ONSFirstLongPollStartedEvent(event.cachedSubscriptionsUsed));\n        });\n        this._OnsContext.on(ONS_FIRST_LONG_POLL_COMPLETED, event => {\n            this.dispatch(new ONSFirstLongPollCompletedEvent(event.expired));\n        });\n\n        // ONS monitoring status changed event.\n        this._OnsContext.on(ONS_MONITORING_STATUS_CHANGED, event => {\n            this.dispatch(new ONSMonitoringStatusChangedEvent(event.status));\n        });\n\n        return this._OnsContext;\n    }\n\n    /**\n     * Gets the current status of the ONS monitoring.\n     */\n    get onsMonitoringStatus(): OnsMonitoringStatus {\n        return this._OnsContext?.onsMonitoringStatus ?? OnsMonitoringStatus.Unknown;\n    }\n\n    /**\n     * Gets OnsContext.\n     * @package -- for use in SAM.js only\n     */\n    get onsContext(): ONSContext | undefined {\n        return this._OnsContext;\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    readonly _ussAdobeAssetUpdater = USSAdobeAssetUpdater;\n\n    /**\n     * @package -- for use in SAM.js only\n     * @deprecated -- will be removed on or after 2024-10-01.\n     */\n    get repoInterface(): RepositoryInterface {\n        oneTimeWarning('AssetContext.repoInterface', 'AssetContext.repoInterface is deprecated and will be removed'\n            + ' on or after 2024-10-01. It is for internal SAM.js use only.');\n        return this._rapi;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * @deprecated -- will be removed on or after 2024-10-01.\n     */\n    get ussInterface(): USSInterface {\n        oneTimeWarning('AssetContext.ussInterface', 'AssetContext.ussInterface is deprecated and will be removed'\n            + ' on or after 2024-10-01. It is for internal SAM.js use only.');\n        return this._ussInterface;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * @deprecated -- will be removed on or after 2024-10-01.\n     */\n    get ussInterfaceV3(): USSv3Interface {\n        oneTimeWarning('AssetContext.ussInterfaceV3', 'AssetContext.ussInterfaceV3 is deprecated and will be removed'\n            + ' on or after 2024-10-01. It is for internal SAM.js use only.');\n        return this.__ussInterfaceV3;\n    }\n\n    /**\n     * @deprecated -- will be removed on or after 2024-10-01 with no replacement.\n     */\n    get sbmInterface(): SBMInterface {\n        oneTimeWarning('AssetContext.sbmInterface', 'AssetContext.sbmInterface is deprecated and will be removed'\n            + ' on or after 2024-10-01.');\n        return this._SBMInterface;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * @deprecated -- will be removed on or after 2024-10-01.\n     */\n    get swyInterface(): SWYInterface {\n        oneTimeWarning('AssetContext.swyInterface', 'AssetContext.swyInterface is deprecated and will be removed'\n            + ' on or after 2024-10-01. It is for internal SAM.js use only.');\n        return this._swyInterface;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * @deprecated -- will be removed on or after 2024-10-01.\n     */\n    get recentInterface(): RecentInterface {\n        oneTimeWarning('AssetContext.recentInterface', 'AssetContext.recentInterface is deprecated and will be removed'\n            + ' on or after 2024-10-01. It is for internal SAM.js use only.');\n        return this._recentInterface;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * @deprecated -- will be removed on or after 2024-10-01.\n     */\n    get invitationInterface(): InvitationInterface {\n        oneTimeWarning('AssetContext.invitationInterface', 'AssetContext.invitationInterface is deprecated and will be removed'\n            + ' on or after 2024-10-01. It is for internal SAM.js use only.');\n        return this._invitationInterface;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * @deprecated -- will be removed on or after 2024-10-01.\n     */\n    get publishedInterface(): PublishedInterface {\n        oneTimeWarning('AssetContext.publishedInterface', 'AssetContext.publishedInterface is deprecated and will be removed'\n            + ' on or after 2024-10-01. It is for internal SAM.js use only.');\n        return this._publishedInterface;\n    }\n\n    /**\n     * @package -- for internal use only\n     * @deprecated -- will be removed on or after 2024-10-01.\n     */\n    get assetPool(): ItemPool<AdobeAsset> {\n        oneTimeWarning('AsseContext._assetPool', 'AssetContext._assetPool is deprecated and will be removed on or after'\n            + ' 2024-10-01. ItemPools are for internal SAM.js use only.');\n        return this._assetPool;\n    }\n\n    // Once the performance is better when compared to the USS,\n    // we will default to PLSSWYAdobeAssetLoader\n    @memoize\n    get sharedSource(): SWYAdobeAssetSource {\n        const implicitFilter = new SWYAdobeAssetFilter();\n        const localAssetsLoader = new LocalAssetLoader<SWYAdobeAssetConfig>(this._assetPool, this._core);\n        const featureFlags = this._core._environment.getValue('FEATURE_FLAGS');\n        const usePLSSharedWithYou = featureFlags?.['use-pls-swy'] ?? false;\n        const swyloader = usePLSSharedWithYou\n            ? new PLSSWYAdobeAssetLoader(this._core)\n            : new SWYAdobeAssetLoader(this._assetPool, this._core, this._swyInterface);\n        return new ItemSource<SWYAdobeAssetConfig>(this._assetPool, [ swyloader, localAssetsLoader ], implicitFilter);\n    }\n\n    @memoize\n    get recentAssetsSource(): RecentAdobeAssetSource {\n        const implicitFilter = new RecentAdobeAssetFilter();\n        const recentAssetsLoader = new RecentAdobeAssetLoader(this._assetPool, this._core, this._recentInterface, implicitFilter);\n        const localAssetsLoader = new LocalAssetLoader<RecentAdobeAssetConfig>(this._assetPool, this._core);\n        implicitFilter._lastModificationDate = new Date(9999, 0, 1);\n        return new ItemSource<RecentAdobeAssetConfig>(this._assetPool, [ recentAssetsLoader, localAssetsLoader ], implicitFilter);\n    }\n\n    @memoize\n    get favoriteAssetsSource(): FavoriteAdobeAssetSource {\n        return new ItemSource<FavoriteAdobeAssetConfig>(\n            this._assetPool,\n            [ new FavoriteAdobeAssetLoader(this._core) ],\n            new ImplicitFavoriteAdobeAssetFilter()\n        );\n    }\n\n    // Once the performance is better when compared to the USS,\n    // we will default to PLSRecentAdobeAssetLoader\n    @memoize\n    get MRUAssetsSource(): MRUAdobeAssetSource {\n        const implicitFilter = new MRUAdobeAssetFilter();\n        const localAssetsLoader = new LocalAssetLoader<MRUAdobeAssetConfig>(this._assetPool, this._core);\n        const featureFlags = this._core._environment.getValue('FEATURE_FLAGS');\n        const usePLSRecents = featureFlags?.['use-pls-recents'] ?? false;\n        const MRUAssetsLoader = usePLSRecents\n            ? new PLSRecentAdobeAssetLoader(this._core)\n            : new MRUAdobeAssetLoader(this._assetPool, this._core, this._recentInterface);\n        return new ItemSource<MRUAdobeAssetConfig>(\n            this._assetPool,\n            [ MRUAssetsLoader, localAssetsLoader ],\n            implicitFilter);\n    }\n\n    @memoize\n    get publishedSource(): PublishedAdobeAssetSource | undefined {\n        const implicitFilter = new PublishedAdobeAssetFilter();\n        const publishedLoader = new PublishedAdobeAssetLoader(this._assetPool, this._core, this._publishedInterface);\n        return new ItemSource(this._assetPool, [ publishedLoader ], implicitFilter);\n    }\n\n    @memoize\n    get discardedSource(): DiscardedAdobeAssetSource {\n        const implicitFilter = new DiscardedAdobeAssetFilter();\n        const loader = new DiscardedAdobeAssetLoader(this._assetPool, this._core, this._discardedInterface);\n        return new ItemSource(this._assetPool, [ loader ], implicitFilter);\n    }\n\n    /**\n     * A source that only contains local assets.\n     */\n    @memoize\n    get localRecentsSource(): LocalAdobeAssetSource | undefined {\n        if (this._acplModelInterface.supportsLocalAssets) {\n            const localAssetLoader = new LocalAssetLoader<LocalAdobeAssetConfig>(this._assetPool, this._core);\n            const implicitFilter = new LocalAdobeAssetFilter();\n            return new ItemSource(this._assetPool, [ localAssetLoader ], implicitFilter);\n        } else {\n            return undefined;\n        }\n    }\n\n    /**\n     * Provides an instance of AssetLinkManager.\n     */\n    @synchronized\n    async getAssetLinkManager(): Promise<AssetLinkManager> {\n        if (this._AssetLinkManager) {\n            return this._AssetLinkManager;\n        }\n\n        const AssetLinkManager = (await import('../links/AssetLinkManager')).default;\n        this._AssetLinkManager = new AssetLinkManager(this);\n        return this._AssetLinkManager;\n    }\n\n    /**\n     * @package - used internally to get the cached instance of\n     * AssetLinkManager.\n     */\n    _getAssetLinkManager(): AssetLinkManager | undefined {\n        return this._AssetLinkManager;\n    }\n\n    getGlobalSearchAssetsSource(query: string): AdobeAssetGlobalSearchSource {\n        const implicitFilter = new AdobeAssetGlobalSearchFilter({\n            _query: query,\n            _matchingIDsFromSearch: new Set<string>()\n        });\n        const globalSearchLoader = new AdobeAssetGlobalSearchLoader(\n            this._assetPool,\n            implicitFilter,\n            this._core,\n            this._adobeAssetGlobalSearchInterface\n        );\n        return new ItemSource(this._assetPool, [ globalSearchLoader ], implicitFilter);\n    }\n\n    /**\n     * Experimental -- this is for early integration by Project X and will be removed\n     * in the future.  When the real API is ready, this method will be marked deprecated\n     * at that time.\n     */\n    getGlobalSearchAssetsSourceV3(query: string): AdobeAssetGlobalSearchSource {\n        const implicitFilter = new AdobeAssetGlobalSearchFilter({\n            _query: query,\n            _matchingIDsFromSearch: new Set<string>()\n        });\n        const globalSearchLoader = new GlobalSearchLoader(\n            this._assetPool,\n            this._core,\n            this._globalSearchInterfaceV3,\n            implicitFilter\n        );\n        return new ItemSource(this._assetPool, [ globalSearchLoader ], implicitFilter);\n    }\n\n    @memoize\n    get ffBoardsSource(): FFBoardsAdobeAssetSource {\n        const ffBoardsMediaType = 'application/vnd.adobe.hz.aura+dcx';\n        const implicitFilter = new AdobeAssetFilter({ mediaTypes: [ ffBoardsMediaType ], _isDiscarded: false });\n        const ffBoardsLoader = new FFBoardsLoader(this._assetPool, this._core, this._ffBoardsInterface);\n        return new ItemSource<FFBoardsAdobeAssetConfig>(this._assetPool, [ ffBoardsLoader ], implicitFilter);\n    }\n\n    /**\n     * Clients should use isOnline() to determine online/offline status so that SAM is responsible for encapsulating\n     * which values of NetworkStatus mean \"online\" vs \"offline\".\n     */\n    get isOnline(): boolean {\n        oneTimeWarning('AssetContext.isOnline', 'AssetContext.isOnline() is not fully implemented for web');\n        return this.networkStatus !== NetworkStatus.Offline;\n    }\n\n    /**\n     * Use for fine-grain network status (WAN vs Cellular). For offline/online, use isOnline() above.\n     */\n    get networkStatus(): NetworkStatus {\n        oneTimeWarning('AssetContext.networkStatus', 'AssetContext.networkStatus is not fully implemented for web');\n        return NetworkStatus.OnlineUnknown;\n    }\n\n    /**\n     * Gets an Asset from cache, or loads it from the cloud. If ONS is disabled, it will also refresh\n     * cached Assets as well.\n     *\n     * Uses @synchronized to ensure only one request for a particular Asset can be serviced at a time,\n     * which prevents race conditions due to multiple load requests for the same Asset stepping on\n     * one another.\n     *\n     * @param assetId {string}\n     * @param resolveMetadata {RepositoryMetadata} -- For getAssetWith* calls that have already resolved the\n     *        Asset repo metadata to get the assetId, so additional resolve requests are unnecessary.\n     * @returns Promise<AdobeAsset>\n     * @private\n     */\n    @synchronized\n    private async _getAssetById(@key assetId: string, repoMetadataResource?: RepoMetadataResource, forONSNotification?: boolean): Promise<AdobeAsset> {\n        const asset = this._assetPool.getLocalItemById(assetId) ?? await this._acplModelInterface.getLocalAsset(assetId);\n        if (asset) {\n            // Force refresh if ONS is disabled, because the data may be stale\n            const forceRefresh = this._core._environment.getValue('DISABLE_ONS') || asset.needsRepoMetadata;\n            if (forceRefresh) {\n                // If the reload fails, we still return the asset but schedule a retry - that's equivalent to using the\n                // cached data for the asset (e.g. if go offline), and having the asset update later.\n                // @TODO Another potential optimisation here is to not load the project metadata again if we come to this\n                // code path because the project lacks repo metadata and ONS is enabled.\n                await asset._loadWithRetry();\n            } else if (!asset._linksCameFromResolveAPI) {\n                // No resolve metadata was passed in, or the links metadata came from listings,\n                // which might be stale (esp. from USS). Assume that the metadata is likely up-to-date,\n                // but refresh in the background in case it isn't.\n                this._rapi.getAssetLinks(assetId).then((links) => {\n                    const session = this._assetPool.createUpdateSession();\n                    this._adobeAssetUpdater.updateLocalItem(session, asset!, {\n                        _links: links\n                    });\n                    asset!._linksCameFromResolveAPI = true;\n                    session.commit();\n                });\n            }\n            return asset;\n        }\n\n        const appMetadataResource = new AppMetadataResource(this._core);\n        const effectivePermissionsResource = new EffectivePermissionsResource(this._core);\n        const perUserMetadataResource = new PerUserMetadataResource(this._core);\n\n        let appMetadata: IAppMetadata = {};\n        let repoMetadata: RepositoryMetadata;\n        let assetPerUserMetadata: IPerUserMetadata | undefined;\n        const useGraphQL = this._core._environment.getValue('FEATURE_FLAGS')?.['use-graphql'];\n\n        if (!useGraphQL) {\n            if (!repoMetadataResource) {\n                repoMetadataResource = new RepoMetadataResource(this._core);\n                await this._rapi.getRepoMetadataById(assetId, repoMetadataResource);\n            }\n            repoMetadata = repoMetadataResource.data;\n            const assetInterface = new AssetInterface(this._rapi, assetId, repoMetadata._links, repoMetadata['repo:etag']);\n            await assetInterface.getEffectivePermissions(effectivePermissionsResource);\n\n            if ((effectivePermissionsResource.data & Permission.ReadAppMetadata) === Permission.ReadAppMetadata) {\n                await assetInterface.getAppMetadata(appMetadataResource);\n                appMetadata = appMetadataResource.data;\n            }\n        } else {\n            const gqlManager = await this._core._getGQLManager();\n            if (!repoMetadataResource) {\n                repoMetadataResource = new RepoMetadataResource(this._core);\n            }\n\n            await gqlManager.getAssetResourcesById(assetId, {\n                repoMetadataResource,\n                appMetadataResource,\n                effectivePermissionsResource,\n                perUserMetadataResource\n            });\n            repoMetadata = repoMetadataResource.data;\n            assetPerUserMetadata = perUserMetadataResource.data;\n            appMetadata = appMetadataResource.data;\n        }\n\n        const permission = effectivePermissionsResource.data;\n\n        const projectInterface = new ProjectsInterface(this._core);\n        const studentAssignmentInterface = new StudentAssignmentsInterface(this._core);\n\n        // Check if this is a Project and populate some params for assetFromRepoMetadata.\n        let projectMetadata: IProject | undefined;\n        let studentAssignmentMetadata: Partial<IRemoteStudentAssignment> = {} as Partial<IRemoteStudentAssignment>;\n        const isProject = appMetadataIsProject(appMetadata);\n        const isStudentAssignment = metadataIsStudentAssignment({ appMetadata, repoMetadata });\n        if (isProject) {\n            projectMetadata = await projectInterface.getProject(repoMetadata['repo:assetId']!);\n        } else if (isStudentAssignment) {\n            const remoteStudentAssignment = await studentAssignmentInterface.getStudentAssignment(assetId, undefined, { [RequestHeaders.PREFER_RAPI]: 'true' });\n            studentAssignmentMetadata = this.repoToStudentAssignmentData(repoMetadata, { ...appMetadata, ...remoteStudentAssignment });\n        }\n\n        const computedRepositoryMetadata = {\n            ...repoMetadataResource?.data,\n            _embedded: {\n                [RelType.APP_METADATA]: appMetadata\n            }\n        } as RepositoryMetadata;\n\n        const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ computedRepositoryMetadata ]);\n        // Check if this is a Generation History Asset and populate generationModelDisplayName\n        let generationHistoryContext: GenerationHistoryContext | undefined;\n        const isGenerationHistoryAsset = repoMetadataIsGenerationHistoryAsset(repoMetadata);\n        let generationHistoryMetadata: Partial<GenerationHistoryAssetData> = {};\n        if (isGenerationHistoryAsset) {\n            generationHistoryContext = await this._core.getGenerationHistoryContext();\n            generationHistoryMetadata = (await generationHistoryContext._generationHistoryInterface.getGenerationHistoryAssetById(assetId));\n        }\n\n        const session = this._assetPool.createMutationSession();\n        const newAsset = this._core._adobeAssetFactory.assetFromRepoMetadata({\n            session,\n            repoMetadata,\n            updaters,\n            permissions: permission,\n            appMetadata,\n            projectMetadata,\n            studentAssignmentMetadata: isStudentAssignment ? studentAssignmentMetadata : undefined,\n            perUserMetadata: assetPerUserMetadata,\n            generationHistoryMetadata: isGenerationHistoryAsset ? generationHistoryMetadata : undefined\n        });\n\n        // Mark storage:assignee as loaded, if it is set from repo:metadata\n        if (repoMetadata && repoMetadata['storage:assignee'] && newAsset._storageAssignee_NoLazyLoad.id === repoMetadata['storage:assignee'].id) {\n            LazyLoadManager.updatedByItemUpdater(newAsset, STORAGE_ASSIGNEE_CHANGED);\n        }\n\n        session.commit();\n        if (forONSNotification && newAsset.isLibrary) {\n            // SHARED-3623 - when we create a library in response to ONS,\n            // LibraryFilter.matches() requires it to be in the 'LOADED' state\n            // if we want lists from the librarySource to update.\n            await (newAsset as Library)._waitForLibraryLoad();\n        }\n\n        newAsset._setResources({\n            repoMetadataResource,\n            appMetadataResource,\n            effectivePermissionsResource,\n            perUserMetadataResource\n        });\n\n        if (isProject) {\n            await (newAsset as Project)._load({\n                repoMetadata,\n                appMetadata,\n                effectivePermission: permission,\n                projectMetadata,\n                perUserMetadata: assetPerUserMetadata\n            });\n        } else if (isStudentAssignment) {\n            await (newAsset as StudentAssignment)._load({\n                repoMetadata: studentAssignmentMetadata as RepositoryMetadata,\n                appMetadata,\n                effectivePermission: permission,\n                perUserMetadata: assetPerUserMetadata,\n                // we don't need to fetch the student assignment metadata again\n                doFetchStudentAssignmentMetadata: false\n            });\n        } else if (isLibrary(newAsset)) {\n            await newAsset._load({\n                repoMetadata,\n                appMetadata,\n                effectivePermission: permission,\n                perUserMetadata: assetPerUserMetadata,\n                requireLibraryDataFetch: forONSNotification\n            });\n        } else {\n            await newAsset._load({\n                repoMetadata,\n                appMetadata,\n                effectivePermission: permission,\n                perUserMetadata: assetPerUserMetadata\n            });\n        }\n\n        newAsset!._linksCameFromResolveAPI = true;\n        return newAsset;\n    }\n\n    /**\n     * Returns the \"/\" folder for USM users and the \"/users/<user-id>\" folder for ESM user. For access to the\n     * \"/cloud-content\" folder for the current user, use `getRootFolder()`\n     */\n    @keepAlive\n    @synchronized\n    async getHomeFolder(): Promise<AdobeAsset> {\n        if (!this._homeFolder) {\n            const homeDirectoryMetadata = await this._rapi.getHomeDirectoryMetadata();\n            const session = this._assetPool.createMutationSession();\n            this._setHomeFolder(this._adobeAssetUpdater.updateRemoteItem(session, homeDirectoryMetadata));\n            session.commit();\n        }\n        return this._homeFolder!;\n    }\n\n    private _setHomeFolder(homeFolder: AdobeAsset): void {\n        this._homeFolder = homeFolder;\n        this._homeFolder.on(CHANGE, this._onHomeFolderChange);\n    }\n\n    private _onHomeFolderChange = (): void => {\n        // Clear cached /index so it gets refreshed on next request\n        this._rapi._clearIndexCache();\n    };\n\n    /**\n     * Gets the current user's `/cloud-content` folder. If the folder does not exist, it will be\n     * created.\n     * @param @experimental loadHints - hints for loading the root folder\n     */\n    @keepAlive\n    @synchronized\n    async getRootFolder(loadHints?: AssetLoadHints): Promise<AdobeAsset> {\n        if (!this._rootFolder) {\n            const useGraphQL = this._core._environment.getValue('FEATURE_FLAGS')?.['use-graphql'];\n            if (useGraphQL) {\n                const listingHints = loadHints?.listingHints?.map((hint) => ({\n                    ...hint,\n                    effectivePermissions: false,\n                }));\n                const internalLoadHints: AssetLoadHints = {\n                    ...loadHints,\n                    listingHints,\n                    appMetadata: false,\n                    effectivePermissions: false,\n                    perUserMetadata: false\n                };\n                const gqlManager = await this._core._getGQLManager();\n                // if home folder is cached, use it to get the root folder\n                if (this._homeFolder) {\n                    const assetPath = path.join(this._homeFolder.repoPath, CLOUD_CONTENT_ROOT_FOLDER);\n                    this._rootFolder = (await gqlManager.getAssetByPath(assetPath, this._homeFolder.repositoryID, internalLoadHints)).asset!;\n                } else {\n                    // if home folder is not cached, get both the root folder and the home folder\n                    const result = await gqlManager.getAssetByPath(CLOUD_CONTENT_ROOT_FOLDER, undefined, internalLoadHints);\n                    this._rootFolder = result.asset!;\n                    this._setHomeFolder(result.homeFolder!);\n                }\n            } else {\n                this._rootFolder = await this._getAssetWithRepoPathImpl(CLOUD_CONTENT_ROOT_FOLDER);\n            }\n        }\n        return this._rootFolder;\n    }\n\n    async getUserRepoID(): Promise<string> {\n        return this.getHomeFolder().then((asset) => asset.repositoryID);\n    }\n\n    @keepAlive\n    async getAssetWithCloudID(assetId: string, confirmAccess: boolean = false): Promise<AdobeAsset> {\n        if (confirmAccess) {\n            const collaborationContext = await this._core.getCollaborationContext();\n            await collaborationContext.confirmAccess(assetId);\n        }\n        return this._getAssetById(assetId);\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    async _getAssetRepoDataWithCloudID(assetId: string): Promise<RepoMetadataResource> {\n        const repoMetadataResource = new RepoMetadataResource(this._core);\n        await this._rapi.getRepoMetadataById(assetId, repoMetadataResource);\n        return repoMetadataResource;\n    }\n\n    /**\n     * Resolves the Asset at the given assetPath. If repositoryId is not passed, it will look up the repositoryId\n     * for the current user, and assume that the path is relative to the user's home directory (`/` for USM users,\n     * `/users/<userId>` for ESM users). If the repositoryId is passed, then the path is assumed to be absolute.\n     *\n     * @example <caption>Assuming 'xyz' is the current userId and 'abc' is the repositoryId</caption>\n     *    getAssetWithRepoPath('/cloud-content');                  // returns /users/xyz/cloud-content\n     *    getAssetWithRepoPath('/users/xyz/cloud-content', 'abc'); // \"\n     *    getAssetWithRepoPath('/users/xyz/cloud-content');        // NOT_FOUND error\n     *\n     * @param assetPath {string}\n     * @param repositoryId {string} (optional)\n     * @return AdobeAsset\n     */\n    @keepAlive\n    @synchronized\n    async getAssetWithRepoPath(assetPath: string, repositoryId?: string): Promise<AdobeAsset> {\n        // cache and use the cloud-content folder\n        if (assetPath === CLOUD_CONTENT_ROOT_FOLDER) {\n            return this.getRootFolder();\n        }\n        return this._getAssetWithRepoPathImpl(assetPath, repositoryId);\n    }\n\n    /**\n     * A small abstraction to get the repository metadata and resources for a given asset path and repository ID.\n     * @package -- only for use in SAM.js\n     *\n     * @param assetPath The path to get the repository metadata for.\n     * @param repositoryId The repository ID to get the repository metadata for.\n     * @returns The repository metadata for the given asset path and repository ID.\n     */\n    public async _getRepoDataByPath(assetPath: string, repositoryId: string): Promise<RepoMetadataResource> {\n        const repoMetadataResource = new RepoMetadataResource(this._core);\n        const data = await this._rapi.getRepoMetadataByPath(\n            repositoryId!,\n            assetPath,\n            repoMetadataResource\n        );\n        repoMetadataResource._setData(data);\n        return repoMetadataResource;\n    }\n\n    /**\n     * Gets a top-level folder asset by its path and repository ID.\n     * This is a lightweight method optimized for top-level folders that avoids the overhead\n     * of _getAssetById by directly creating the asset from repository metadata.\n     *\n     * @private\n     * @param assetPath - The path of the top-level folder\n     * @param repositoryId - The repository ID containing the folder\n     * @returns Promise resolving to the AdobeAsset for the top-level folder\n     * @throws {SAMError} If the asset ID is missing from metadata\n     */\n    private async _getTopLevelFolder(assetPath: string, repositoryId: string): Promise<AdobeAsset> {\n        const repoMetadataResource = await this._getRepoDataByPath(assetPath, repositoryId);\n        const assetId = repoMetadataResource.data['repo:assetId'];\n\n        if (!assetId) {\n            throw SAMError.create(SAMErrorCode.NOT_FOUND, `Top-level folder not found at path: ${assetPath}`);\n        }\n\n        const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ repoMetadataResource.data ]);\n\n        return this._assetPool.getLocalItemById(assetId) ?? (() => {\n            const session = this._assetPool.createMutationSession();\n            const newAsset = this._core._adobeAssetFactory.assetFromRepoMetadata({ session, repoMetadata: repoMetadataResource.data, updaters });\n            session.commit();\n            return newAsset;\n        })();\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    @synchronized\n    private async _getAssetWithRepoPathImpl(assetPath: string, repositoryId?: string): Promise<AdobeAsset> {\n        if (!repositoryId) {\n            // Since clients typically start by resolving a folder by path, also get the `/` folder so that it is\n            // monitored for ONS changes.\n            const homeFolder = await this.getHomeFolder();\n            repositoryId = homeFolder.repositoryID;\n            const userContentRootFolder = homeFolder.repoPath;\n            assetPath = path.join(userContentRootFolder, assetPath);\n        }\n        try {\n            let asset: AdobeAsset | undefined = undefined;\n\n            // If the asset is a top-level folder call _getTopLevelFolder which just creates it with repository metadata\n            if (isTopLevelFolder(assetPath)) {\n                asset = await this._getTopLevelFolder(assetPath, repositoryId);\n                return asset;\n            }\n            const repoMetadataResource = await this._getRepoDataByPath(assetPath, repositoryId);\n            const data = repoMetadataResource.data;\n            asset = await this._getAssetById(data['repo:assetId'], repoMetadataResource);\n            asset._setResources({ repoMetadataResource });\n            return asset;\n        } catch (e) {\n            const topLevelFolders = [ 'cloud-content', 'temp' ];\n            for (const topLevelFolder of topLevelFolders) {\n                const topLevelPath = `/${topLevelFolder}`;\n                const appearsOnlyOnce = assetPath.indexOf(topLevelPath) === assetPath.lastIndexOf(topLevelPath);\n                if ((e as SAMError).code === SAMErrorCode.NOT_FOUND && appearsOnlyOnce && assetPath.endsWith(topLevelPath)) {\n                    const homeFolder = await this.getHomeFolder();\n                    // return the promise to create the folder\n                    return homeFolder.createFolder(topLevelFolder);\n                }\n            }\n            throw e;\n        }\n    }\n\n    // including confirmAccess to match Seal bindings.\n    @keepAlive\n    async getAssetWithAssetRefString(assetRefStr: string, confirmAccess = false): Promise<AdobeAsset> {\n        type AssetRefKeys = 'cloud_id' | 'local_id' | 'path' | 'repository_id';\n        let parsedAssetRef: Partial<{ [key in AssetRefKeys]: string }>;\n\n        try {\n            parsedAssetRef = JSON.parse(assetRefStr);\n        } catch (error: any) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Incorrectly formatted AssetRefString', { underlyingError: error });\n        }\n\n        if (parsedAssetRef.cloud_id) {\n            return this.getAssetWithCloudID(parsedAssetRef.cloud_id, confirmAccess);\n        } else if (parsedAssetRef.path) {\n            return this.getAssetWithRepoPath(parsedAssetRef.path, parsedAssetRef.repository_id);\n        } else {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid AssetRefString');\n        }\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _createAssetFromMetadata(assetMetaData: RepositoryMetadata): AdobeAsset {\n        const session = this._assetPool.createUpdateSession();\n        const localItem = this._adobeAssetUpdater.updateRemoteItem(session, assetMetaData);\n        session.commit();\n\n        return localItem;\n    }\n\n    async _repositoryNameFromID(id: string): Promise<string | undefined> {\n        return await this._rapi.getRepositoryName(id);\n    }\n\n\n    /** @package -- only for use in SAM.js */\n    async _getStorageAssigneeFromID(id: string): Promise<Assignee | undefined> {\n        return await this._rapi.getStorageAssignee(id);\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    async _getListOfRepositoryIDs(): Promise<string[] | undefined> {\n        const response = await this._rapi.getRepositoriesData();\n        if (!response) {\n            return undefined;\n        }\n\n        const children = response.children;\n        return children.map(repositoryInfo => repositoryInfo._embedded[RelType.PRIMARY]['repo:repositoryId']);\n    }\n\n    /**\n     * XD layers their own artifact publishing system on top of CCAC Projects, backed by their own service. Clients like\n     * CDO and Projects UI need to call this API in order to get metadata for rendering these special Artifacts.\n     * @param assetId\n     */\n    async getXDCEData(assetId: string): Promise<IXDCEDocument> {\n        return this._core._environment.fetch(`https://${this._core._environment.endpoints.XDCE_HOST}/v2/document/${assetId}`)\n            .then(response => response.json());\n    }\n\n    private removeAssetsFromAssetsPool(assetIds: string[]): void {\n        this._assetPool.removeLocalItems(assetIds);\n    }\n\n    async permanentlyDeleteAssets(assets: AdobeAsset[]): Promise<IBatchOperationAssetResult> {\n        let assetResults: IBatchOperationAssetResult;\n\n        // If client wll try to resolve permanently deleted assets, SAM should not return the cached assets\n        // from asset pool. Hence removing permanently deleted assets from asset pool.\n        const onItemsChanged = (event: ItemsChangedEvent<AdobeAsset>) => {\n            // Remove only successfully permanently deleted items from asset pool.\n            if (event.discardedItems) {\n                const permanentDeletedAssetsIds: ItemId[] = event.discardedItems.filter(value => assets.includes(value)).map(item => item.id);\n                if (permanentDeletedAssetsIds.length) {\n                    this.removeAssetsFromAssetsPool(permanentDeletedAssetsIds);\n                }\n            }\n        };\n\n        // ITEMS_CHANGED event is triggered from item pool for all update/mutate sessions.\n        // This event will be triggered by other sessions (sessions other than the session\n        // created by this permanent delete operation) also. But in onItemsChanged we will\n        // remove assets which were added in this session.\n        this._assetPool.on(ITEMS_CHANGED, onItemsChanged);\n\n        try {\n            await ItemBase.runExclusiveTask('delete', assets, async () => {\n                const assetsById = new Map<string, AdobeAsset>();\n\n                const ops = assets.map((asset) => {\n                    assetsById.set(asset.id, asset);\n\n                    const deleteOp: IDeleteOperation = {\n                        op: 'delete',\n                        id: asset.id,\n                        target: {\n                            'repo:assetId': asset.id,\n                        }\n                    };\n\n                    // repository id is optional field in target here\n                    // because target is specified by assetId\n                    if (asset.repositoryID) {\n                        const target = deleteOp.target as IAssetRefRepoAssetId;\n                        target['repo:repositoryId'] = asset.repositoryID;\n                    }\n\n                    deleteOp.recursive = asset.isFolder;\n                    return deleteOp;\n                });\n\n                assetResults = await this._runOperations(ops,\n                    assetsById,\n                    (session: IUpdateSession<AdobeAsset>, asset: AdobeAsset) => {\n                        // Since we know the asset has been permanently deleted\n                        // we should clear any renditions on it to prevent memory leaks.\n                        asset._releaseRenditions();\n\n                        // If the Asset was removed from the pool while the operation was underway (such as by ONS-\n                        // triggered refresh), do not try to update it again, as it will get re-added to the pool.\n                        if (!this._assetPool.getLocalItemById(asset.id)) {\n                            return undefined;\n                        }\n\n                        // We update the effectivePermission here first to notify on \"change\" subscribers\n                        // of AdobeAsset (such as AssetLink) that may need to know this assets permission is set to None before\n                        // it gets discarded.\n                        this._adobeAssetUpdater.updateLocalItem(session, asset, { effectivePermission: Permission.None });\n                        session.queueDiscardedItem(asset);\n                        return undefined;\n                    });\n\n            });\n        } finally {\n            this._assetPool.off(ITEMS_CHANGED, onItemsChanged);\n        }\n\n        return assetResults!;\n    }\n\n    // [SAM-2245][SAM-2244][SAM-2242] TS interface for SAM.cpp-only features. After SAM-1586, the public TypeScript API\n    // will be defined in a separate file, and these definitions should be removed.\n    syncingSource?: ItemSource<IItemSourceConfig<AdobeAsset, any>>;\n    cloudSyncStatus?: CloudSyncStatus;\n\n    getAssetWithLocalID?(id: string): Promise<AdobeAsset>;\n\n    async getCloudQuotaUsedAndMax(): Promise<IQuotaInfo> {\n        return this._rapi.getCloudQuotaUsedAndMax();\n    }\n\n    // Note: Other props/methods in JS bindings that are only used in the SAM.cpp demo app have been removed.\n    //       E.g. release(), appDidEnterBackground(), etc.\n    // end [SAM-2245][SAM-2244][SAM-2242]\n\n    public async transfer(source: AdobeAsset, target: AdobeAsset | Space): Promise<string> {\n        let targetId: string;\n        if (target instanceof Space) {\n            const workingFiles = await target.getChild('working_files');\n            if (!workingFiles) {\n                throw SAMError.create(SAMErrorCode.NOT_FOUND, 'unable to find working_files for provided space');\n            }\n            targetId = workingFiles.id;\n        } else {\n            targetId = target.cloudID;\n        }\n\n        const payload = {\n            source: { assetId: source.cloudID, repositoryId: source.repositoryID },\n            target: { assetId: targetId, repositoryId: target.repositoryID }\n        };\n\n        const response = await this._assetTransferService.transfer(payload);\n\n        const updater = this._assetPool.createUpdateSession();\n        updater.queueDiscardedItem(source);\n        updater.commit();\n\n        return response;\n    }\n\n    /**\n     * Internal helper method for moving assets (batch).\n     * @param assets assets to be moved (in the same repository)\n     * @param destFolder destination folder where assets are intended to be moved\n     * @param assetRenameMap allows renaming of assets in the batch operation\n     * @param retryOnConflict whether to retry the move op for failed assets in case of conflict\n     * @param assetConflictMap map to save the newName and count used for all assets in batch\n     * @returns the result for batch operation after retrying for failed assets if asked.\n     */\n    private async _moveAssets(\n        assets: AdobeAsset[],\n        destFolder: AdobeAsset,\n        assetRenameMap: AssetRenameMap<AdobeAsset> = new Map(),\n        retryOnConflict: boolean = true,\n        assetConflictMap?: NameConflictMap\n    ): Promise<IBatchOperationAssetResult> {\n        let resultOps: IBatchOperationAssetResult = { failedResults: [], newModels: [] };\n\n        await ItemBase.runExclusiveTask('move', assets, async () => {\n            // In case of Asset created from USS response, repo id is not present\n            // Jira on USS https://jira.corp.adobe.com/browse/SRCH-1989\n            if (!destFolder.repositoryID) {\n                await destFolder._load();\n            }\n            if (assetConflictMap === undefined) {\n                assetConflictMap = new Map() as NameConflictMap;\n            }\n            const assetsById = new Map<string, AdobeAsset>();\n            const ops = assets.map((asset) => {\n                assetsById.set(asset.id, asset);\n                let newPath = `${destFolder.repoPath}/${getBatchRenamedAssetName(asset, assetRenameMap)}`;\n                newPath = batchFormatFileName(this._core, asset.id, newPath, false, assetConflictMap!);\n\n                const op: IMoveOperation = {\n                    op: 'move',\n                    id: asset.id,\n                    source: {\n                        'repo:assetId': asset.id\n                    },\n                    target: {\n                        'repo:path': newPath,\n                        'repo:repositoryId': destFolder.repositoryID\n                    }\n                };\n\n                if (asset.repositoryID) {\n                    const source = op.source as IAssetRefRepoAssetId;\n                    source['repo:repositoryId'] = asset.repositoryID;\n                }\n\n                return op;\n            });\n\n            const updater = (session: IUpdateSession<AdobeAsset>, asset: AdobeAsset, remoteItem?: RepositoryMetadata): AdobeAsset => {\n\n                // trigger re-fetch repository name if the dest folder is in a different repository\n                if (asset.repositoryID !== destFolder.repositoryID) {\n                    asset._clearRepositoryName();\n                }\n\n                if (asset.isFolder) {\n                    updateCachedDescendents({\n                        assetPool: this._assetPool,\n                        asset,\n                        session,\n                        operation: { type: 'rename', newPath: remoteItem!['repo:path'] },\n                        assetContext: this\n                    });\n                }\n\n                this._adobeAssetUpdater.updateLocalItem(session, asset, remoteItem!);\n                return asset;\n            };\n\n            resultOps = await this._runOperations(ops, assetsById, updater);\n        });\n\n        if (retryOnConflict) {\n            return await retryFailedOpsDueToConflict(resultOps, destFolder, assetRenameMap, assetConflictMap!, this._moveAssets.bind(this));\n        }\n        return resultOps;\n    }\n\n    /**\n     * Public method to move assets to a folder\n     * @param assets assets to be moved\n     * @param destFolder destination folder where spaces are intended to be moved\n     * @param assetRenameMap allows renaming of assets in the batch operation\n     * @returns the result for batch operation after retrying for failed assets.\n     */\n    async moveAssets(assets: AdobeAsset[], destFolder: AdobeAsset, assetRenameMap: AssetRenameMap<AdobeAsset> = new Map()): Promise<IBatchOperationAssetResult> {\n        return this._moveAssets(assets, destFolder, assetRenameMap);\n    }\n\n    /**\n     * Public method to check move assets capabilities to a target folder\n     * @param assets List of assets to be moved\n     * @param targetFolder destination folder where spaces are intended to be moved\n     * @returns the move capability results for the assets to be moved.\n     */\n    public async getMoveCapability(\n        assets: AdobeAsset[],\n        targetFolder: AdobeAsset\n    ): Promise<MoveCapability> {\n\n        if (!targetFolder.isFolder) {\n            return { canMove: false, reason: CannotMoveReason.NotAFolder };\n        }\n\n        if (!targetFolder.hasPermission(Permission.Write)) {\n            return { canMove: false, reason: CannotMoveReason.PermissionDeniedDestination };\n        }\n\n        if (assets.some(asset => !asset.hasPermission(Permission.Move))) {\n            return { canMove: false, reason: CannotMoveReason.PermissionDeniedSource };\n        }\n\n        // Ensure that storage assignee is loaded, as we need it for the following checks.\n        await Promise.all([ ...assets, targetFolder ].map(asset => LazyLoadManager.fetchIfNeeded(asset, STORAGE_ASSIGNEE_CHANGED)));\n\n        // If they're the same assignee, they're in the same bucket, so no warning checks are needed.\n        if (assets.every(asset => asset.storageAssignee.id === targetFolder.storageAssignee.id)) {\n            return { canMove: true, warning: MoveWarning.None, warnings: [] };\n        }\n\n        const assetRepoOwnerById = await this._rapi.getRepoOwnerMap(targetFolder.repositoryID);\n        const targetRepoOwner = assetRepoOwnerById.get(targetFolder.repositoryID);\n        if (targetRepoOwner === undefined) {\n            throw SAMError.create(SAMErrorCode.NOT_FOUND, 'target\\'s repo owner detail is not available');\n        }\n\n        // SHARED-3744 : We expect (asset._repositoryID !== '') because\n        // AdobeAsset's are always constructed with 'repo:repositoryId'.\n        //\n        // But subclasses of AdobeAsset, such as Library, can be\n        // constructed data that omits 'repo:repositoryId', in which case\n        //  (asset._needsRepoMetadata === true) && (asset._repositoryID === '')\n        //\n        // Let's try to recover from this by updating _repositoryID's\n        // before proceeding.\n        //\n        // NOTE: If your code triggers this oneTimeWarning(), consider\n        // getting your service to include 'repo:repositoryId' in responses,\n        // so this doesn't happen. You can also make sure assets have\n        // been load()-ed, for instance, with getAssetWithCloudID(),\n        // before calling getMoveCapability().\n\n        for (const asset of assets) {\n            if (asset.repositoryID === '') {\n                oneTimeWarning('AssetContext.getMoveCapability',\n                    'getMoveCapability() requires asset._repositoryID to be set.'\n                );\n                await asset._loadRepoMetadata();\n            }\n        }\n\n        if (!this._core._environment.getValue('FEATURE_FLAGS')?.['enable-x-bucket-move']) {\n            return { canMove: false, reason: CannotMoveReason.CrossBucketMoveDisabled };\n        }\n\n        const warnings: MoveWarning[] = [];\n\n        if (assets.some(asset => {\n            const sourceOwner = assetRepoOwnerById.get(asset.repositoryID);\n            // Allow moves between repositories if both owners are users (CCI to CCI move) and the feature flag is enabled\n            if (this._core._environment.getValue('FEATURE_FLAGS')?.['move-capabilities']?.['enable-CCI-CCI-move']\n                && sourceOwner?.type === 'user' && targetRepoOwner!.type === 'user'\n            ) {\n                warnings.push(MoveWarning.OwnerChange);\n                return false; // Don't block the move\n            }\n            // Otherwise block if owners are different\n            return sourceOwner?.id !== targetRepoOwner!.id;\n        })) {\n            return { canMove: false, reason: CannotMoveReason.DifferentOwner };\n        }\n\n\n        // Cross-bucket moves (i.e., different assignee, same owner) can cause data loss if a collaborator is editing. To optimize\n        // checking for the possibility of editors, we can assume Projects & their children have editors. Folders might have shared items,\n        // but it are too expensive to exhaustively check, so assume they could have shared items. If isShared flag is already\n        // populated, we will assume it probably has an editor without loading Collaborators.\n        let maybeHasEditors = assets.some(asset => (\n            asset.isFolder\n            || asset.isProject\n            || asset.isChildOfProject\n            || asset._isShared_NoLazyLoad\n        ));\n\n        if (maybeHasEditors) {\n            warnings.push(MoveWarning.CollaboratorMaybeEditing);\n            return { canMove: true, warning: MoveWarning.CollaboratorMaybeEditing, warnings };\n        }\n\n        // If the _isShared_NoLazyLoad flag is not populated, we have to fetch the Collaborator data to\n        // see if we need to warn about editors. Since we're fetching the Collaborators anyway, might as\n        // well check explicitly if there are direct editors, rather than assuming they exist.\n        let needsProcessing = false;\n        assets.forEach(asset => {\n            if (!asset._isCollaboratorDataLoaded && asset.isShared === undefined) {\n                LazyLoadManager.fetchIfNeeded(asset, COLLABORATOR_CHANGED);\n                needsProcessing = true;\n            }\n        });\n        if (needsProcessing) {\n            const collaborationContext = await this._core.getCollaborationContext();\n            await collaborationContext._collaboratorRequestQueue._processNow();\n            maybeHasEditors = assets.some(asset => asset.isShared\n                && asset.collaboratorArray.some(collab => collab.isDirect && collab.role === 'editor'));\n            if (maybeHasEditors) {\n                warnings.push(MoveWarning.CollaboratorMaybeEditing);\n                return { canMove: true, warning: MoveWarning.CollaboratorMaybeEditing, warnings };\n            }\n        }\n\n        // When there are multiple warnings, prefer CollaboratorMaybeEditing as the singular warning if present, for\n        // backward compatibility. Otherwise, use the first warning.\n        const warning = warnings.find(w => w === MoveWarning.CollaboratorMaybeEditing)\n            || warnings[0]\n            || MoveWarning.None;\n        return { canMove: true, warning, warnings };\n    }\n\n    /**\n     * Checks an array of the provided AdobeAssets have an outputs directory and returns true\n     * if any of the assets have an output folder. This will also update each\n     * AdobeAsset.hasArtifacts property to true if the asset does have it.\n     *\n     * Currently the UI is not expected\n     * to show which folders have artificats individually but rather if any of the selected\n     * assets contain artifacts.\n     *\n     * Usage of this API requires the user to have at least READ\n     * permissions on the source document.\n     *\n     * @note This method is inteded to be a stop gap solution until simulated sub assets\n     * are shipped. See https://wiki.corp.adobe.com/x/h8JNp\n     *\n     * @param assets {AdobeAsset}\n     */\n    async assetsHaveArtifacts(assets: AdobeAsset[]): Promise<boolean> {\n        const assetIndentifiers: IReviewServiceAssetIdentifer[] = mapAssetsToAssetIndentifier(assets);\n        const results = await this._assetReviewServiceInterface.hasOutputs(assetIndentifiers);\n        if (results.length === 0) {\n            return false;\n        }\n\n        const session = this._assetPool.createUpdateSession();\n        this._adobeAssetUpdater.updateRemoteItems(\n            session,\n            results.map(result => {\n                return { 'repo:assetId': result['repo:assetId'], 'hasArtifacts': true };\n            })\n        );\n        session.commit();\n        return true;\n    }\n\n    /**\n     * The asset to delete the output folders for. Currently the\n     * API only supports one asset at a time.\n     *\n     * @param asset Single asset to delete.\n     * @package Only to be used within SAM.js\n     */\n    async _deleteAssetOutputsFolder(asset: AdobeAsset) {\n        return this._assetReviewServiceInterface.discardOutputsForAsset(asset.id);\n    }\n\n    /**\n     * @package -- Internal helper method for copying assets (batch).\n     *\n     * @param assets assets to be copied (in the same repository)\n     * @param destFolder destination folder where assets are intended to be copied\n     * @param assetRenameMap allows renaming of assets in the batch operation\n     * @param retryOnConflict whether to retry the copy op for failed assets in case of conflict\n     * @param assetConflictMap map to save the newName and count used for all assets in batch\n     * @returns the result for batch operation after retrying for failed assets if asked.\n     */\n    private async _copyAssets(\n        assets: AdobeAsset[],\n        destFolder: AdobeAsset,\n        assetRenameMap: AssetRenameMap<AdobeAsset> = new Map(),\n        retryOnConflict: boolean = true,\n        assetConflictMap?: NameConflictMap\n    ): Promise<IBatchOperationAssetResult> {\n        let resultOps: IBatchOperationAssetResult = { failedResults: [], newModels: [] };\n        await ItemBase.runExclusiveTask('copy', assets, async () => {\n            // In case of Asset created from USS response, repo id is not present\n            // Jira on USS https://jira.corp.adobe.com/browse/SRCH-1989\n            if (!destFolder.repositoryID) {\n                await destFolder._load();\n            }\n            if (assetConflictMap === undefined) {\n                assetConflictMap = new Map() as NameConflictMap;\n            }\n            const assetsById = new Map<string, AdobeAsset>();\n            const ops = assets.map((asset) => {\n                assetsById.set(asset.id, asset);\n\n                let newPath = `${destFolder.repoPath}/${getBatchRenamedAssetName(asset, assetRenameMap)}`;\n                const sameFolder = destFolder.repoPath === asset.repoPath.substring(0, asset.repoPath.lastIndexOf('/'));\n                newPath = batchFormatFileName(this._core, asset.id, newPath, sameFolder, assetConflictMap!);\n\n                return asset._getCopyOp(destFolder.repositoryID, newPath);\n            });\n\n            resultOps = await this._runOperations(\n                ops,\n                assetsById,\n                (session: IUpdateSession<AdobeAsset>, asset: AdobeAsset, remoteItem?: RepositoryMetadata) => {\n                    if (!remoteItem) {\n                        throw SAMError.create(SAMErrorCode.UNKNOWN, 'Missing metadata from asset bulk operation.');\n                    }\n                    return this._adobeAssetUpdater.updateRemoteItem(session, remoteItem);\n                }\n            );\n        });\n\n        if (retryOnConflict) {\n            return await retryFailedOpsDueToConflict(resultOps, destFolder, assetRenameMap, assetConflictMap!, this._copyAssets.bind(this));\n        }\n\n        return resultOps;\n    }\n\n    /**\n     * Public method to copy assets to a folder\n     * @param assets assets to be copied\n     * @param destFolder destination folder where spaces are intended to be copied\n     * @param assetRenameMap allows renaming of assets in the batch operation\n     * @returns the result for batch operation after retrying for failed assets.\n     */\n    async copyAssets(assets: AdobeAsset[], destFolder: AdobeAsset, assetRenameMap: AssetRenameMap<AdobeAsset> = new Map()): Promise<IBatchOperationAssetResult> {\n        return await this._copyAssets(assets, destFolder, assetRenameMap);\n    }\n\n    async duplicateAssets(assets: AdobeAsset[]): Promise<IBatchOperationAssetResult> {\n        const parentRepoPath = assets[0].repoPath.substring(0, assets[0].repoPath.lastIndexOf('/'));\n        const parentAsset = await this.getAssetWithRepoPath(parentRepoPath, assets[0].repositoryID);\n        return await this._copyAssets(assets, parentAsset);\n    }\n\n    /**\n     * Creates a folder at the given path in the provided repository.\n     *\n     * @service This API is intended as a \"lower level\" API in a service context to\n     * prevent pre-loading unnessecary data for the caller once the folder is created.\n     *\n     * Use AdobeAsset.createFolder() to create a folder and get a full AdobeAsset object for the created folder.\n     *\n     * @param path The path to create the folder at.\n     * @param repository The repository data to use to create the folder.\n     * @param createIntermediates Whether to create intermediate folders if they don't exist.\n     * @returns The created folder's repository metadata.\n     */\n    async createFolderByPath(path: string, repository: IRepository, createIntermediates: boolean = true): Promise<AdobeAsset> {\n        const newFolderMetadata = await this._rapi.createFolderByPath(path, repository.id, createIntermediates, repository.links);\n        const session = this._assetPool.createUpdateSession();\n        const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ newFolderMetadata ]);\n        const newFolder = this._core._adobeAssetFactory.assetFromRepoMetadata({ session, repoMetadata: newFolderMetadata, updaters });\n        session.commit();\n        return newFolder;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    async _runOperations(\n        ops: IOperationQuery,\n        assetsById: Map<string, AdobeAsset>,\n        assetUpdater?: (\n            session: IUpdateSession<AdobeAsset>,\n            asset: AdobeAsset,\n            remoteItem?: RepositoryMetadata\n        ) => AdobeAsset | undefined\n    ): Promise<IBatchOperationAssetResult> {\n        return await this._rapi.runOperationsForContext<AdobeAsset>(\n            ops,\n            assetsById,\n            this._assetPool,\n            assetUpdater ? assetUpdater : (session: IUpdateSession<AdobeAsset>, asset: AdobeAsset, updatedAssetMetaData?: RepositoryMetadata) => {\n                if (!updatedAssetMetaData) {\n                    throw SAMError.create(SAMErrorCode.UNKNOWN, 'Missing metadata from asset bulk operation.');\n                }\n                this._adobeAssetUpdater.updateLocalItem(session, asset, updatedAssetMetaData);\n                return undefined;\n            },\n            [\n                {\n                    // If remote asset found to be SAMErrorCode.ACCESS_DENIED or SAMErrorCode.NOT_FOUND\n                    // that means we need to update local asset to get it in sync with remote\n                    match: (error: SAMError) => error.code === SAMErrorCode.ACCESS_DENIED || error.code === SAMErrorCode.NOT_FOUND,\n                    action: async (asset: AdobeAsset, error: SAMError) => {\n                        await asset._load();\n                        return { model: asset, error };\n                    }\n                }\n            ]\n        );\n    }\n\n    // Called when we get a notification from ONS - we reload any assets when we find out they changed\n    private _onOnsAssetChangeEvent = (event: ONSAssetChangeEvent) => {\n        // Track parent folders with changes for notification dispatch\n        const changedFolders: Set<AdobeAsset> = new Set();\n        // Update any assets in the pool\n        event.changedAssets.forEach((assetInfo: ONSChangedAssetInfo, assetID: string) => {\n\n            // Route annotation notifications to corresponding CommentsResource.\n            // Use the assetID instead of the asset, as it's possible to have the\n            // comments without the asset, such as\n            //      const comments = await assetContext.getCommentsResource(assetId);\n\n            if (assetInfo.changedResources?.includes('api:annotation')) {\n                const commentsResource = this._commentsById.get(assetID)?.deref();\n\n                if (commentsResource) {\n                    commentsResource._onONSNotification(assetInfo);\n                }\n            }\n\n            const asset = this._assetPool.getLocalItemById(assetID);\n            if (asset) {\n                asset.handleOnsChangedResources(assetInfo.changedResources);\n            }\n\n            if (assetInfo.parentAssetId && this._assetPool.getLocalItemById(assetInfo.parentAssetId)) {\n                // Check for items that were added remotely to a folder that we're monitoring (e.g. move, restore, discard,\\\n                // and copy can cause an item to appear in a folder that is being monitored). This will cause any list of children\n                // for the folder to be updated when a new asset is added to it.\n                //\n                // Note that we ONLY do this if the parent asset is loaded - in the case where we're monitoring asset ids\n                // directly via the link list, as the CC Library process does, no AdobeAssets are loaded (SAM is only used\n                // to get the notifications). So if we always loaded the asset here it would introduce unnecessary network\n                // calls. In the folder listing case, we always have the parent asset loaded, so this is safe.\n                const parentAsset = this._assetPool.getLocalItemById(assetInfo.parentAssetId);\n\n                // We do not want to load children automatically from a parent that has been loaded as a minimal asset\n                // via the KnowledgeWorkspaceContext, as Acrobat manages its own listings.\n                const kwContext = this._core._getKnowledgeWorkspaceContext();\n                const isMinimalAsset = kwContext && kwContext._isMinimalAsset(parentAsset!);\n\n                if (!asset && parentAsset!._canLoadNewChildrenFromONSNotification && !isMinimalAsset) {\n                    this._getAssetById(assetID, undefined, true).catch(error => {\n                        if (error.code === SAMErrorCode.NOT_FOUND) {\n                            // During a permanent delete, we remove the asset from the pool and unsubscribe from ONS However, there is a race condition where the ONS notification for the removed asset arrived, before our unsubscribe call is processed.\n                            this._core._environment.log(`_onOnsChangeAssetEvent asset ${assetID} not found, likely deleted or unshared.`);\n                        } else {\n                            throw error;\n                        }\n                    });\n                }\n\n                // Add parent folder to set of folders with changed child assets\n                changedFolders.add(parentAsset!);\n            }\n        });\n\n        // Dispatch events for folders with changed child assets.\n        changedFolders.forEach((folder: AdobeAsset) => {\n            folder.dispatch(new FolderContentChangedEvent());\n        });\n\n        // If AssetLinkManager hasn't been used, we don't need to\n        // look through each list.\n        const changedIDs = new Set(event.changedAssets.keys());\n        const alm = this._getAssetLinkManager();\n        if (alm) {\n            // Also refresh any links that changed\n            alm.lists.forEach(list => list._refreshLinksForChangedAssets(changedIDs));\n        }\n    };\n\n    /**\n     * Event handler for the ItemPool's ITEMS_CHANGED event\n     *\n     *  @package -- only for use in SAM.js\n     */\n    _onAssetsChanged = (e: ItemsChangedEvent<AdobeAsset>) => {\n        // ItemsChangedEvent should ignore assets queued for removal from the pool\n        const excludeAssetIDs = e?.discardedItems?.map(asset => asset.id);\n        this._updateONSSubscriptions(excludeAssetIDs);\n    };\n\n    /**\n     * Collects assetListIds from PLSListLoader instances in the various sources.\n     * @private\n     */\n    private _collectPLSAssetListIds(): Set<string> {\n        const assetListIds = new Set(\n            [\n                ...this.sharedSource._loaders,\n                ...this.MRUAssetsSource._loaders,\n                ...this.favoriteAssetsSource._loaders\n            ]\n                .map(loader => 'assetListId' in loader && loader.assetListId)\n                .filter((assetListId): assetListId is string => !!assetListId)\n        );\n\n        return assetListIds;\n    }\n\n    /**\n     * Called whenever any new assets are added to the asset pool, or when links / link\n     * lists are modified. When this happens, we gather the set of all assets we need to\n     *  monitor and trigger watching this with ONS.\n     *\n     *  @package -- only for use in SAM.js\n     */\n    _updateONSSubscriptions(excludeAssetIDs?: string[]) {\n        // Compute the set of asset ids to watch - start with an empty set.\n        const assetIDs: Set<string> = new Set();\n\n        // If we have some assets requested via the KnowledgeWorkspaceContext, those assets\n        // may be part of a Curated Collection, and we do not want to monitor those assets\n        // via ONS. If the KnowledgeWorkspaceContext instance is cached, then a client has\n        // requested an instance of it, and we should check whether each asset is part of\n        // a Curated Collection before we begin monitoring via ONS.\n        const kwContext = this._core._getKnowledgeWorkspaceContext();\n\n        // We want to monitor most assets in the asset pool (so they get updated when they change)\n        // unless they are a special case like the /temp folder or knowledge workspaces\n        this._assetPool.forEach((asset: AdobeAsset) => {\n            // Skip monitoring the /temp folder\n            if (asset.repoPath === '/temp') {\n                return;\n            }\n\n            // Skip all assets in Curated Collections or files in Knowledge Workspaces.\n            // Acrobat manages its own asset updates for those assets by monitoring folder content\n            // changed events instead of asset events.\n            // Also skip assets that are not actual assets yet either because they are still offline or in their initial alternate state (e.g., NOT_STARTED StudentAssignment assets)\n            if (!(kwContext?._isCuratedCollectionAsset(asset) || (asset.isFile && kwContext?._isMinimalAsset(asset))) && !asset.isVirtual) {\n                assetIDs.add(asset.id);\n            }\n        });\n\n        // Ignore Assets queued for removal from the pool, if this is an ItemsChangedEvent\n        excludeAssetIDs?.forEach((assetId: string) => assetIDs.delete(assetId));\n\n        // If a local instance of AssetLinkManager doesn't exist, that means we don't\n        // need to iterate through the links since a client has yet to use this feature.\n        const alm = this._getAssetLinkManager();\n        if (alm) {\n            // And also any assets referenced by links (since the link might be broken and we want\n            // to re-resolve when the asset comes in)\n            alm.lists.forEach(list => list.monitoredAssetIDs.forEach(id => assetIDs.add(id)));\n        }\n\n        // It's possible to have comments without the asset, such as\n        //      const comments = await assetContext.getCommentsResource(assetId);\n        // vs   const comments = await asset.getCommentsResource();\n        //\n        // So also add assetID's from any comments\n        this._commentsById.forEach((commentsRef, key) => {\n            const comments = commentsRef.deref();\n            if (comments) {\n                assetIDs.add(comments._assetId);\n            } else {\n                this._commentsById.delete(key); // get rid of stale references\n            }\n        });\n        // Add assetListIds from PLS lists\n        // QN: Can this lists be collected from\n        const plsAssetListIds = this._collectPLSAssetListIds();\n\n\n        // Update the list of assetIds that ONS is watching - note that this only modifies the\n        // subscription if the list of assets changes, so calling ONS with the same assetIds won't\n        // cause any new API calls.\n        const onsContext = this.onsContext;\n        if (onsContext) {\n            if (assetIDs.size > 0 && !this._core._environment.getValue('DISABLE_ONS')) {\n                onsContext.watch(assetIDs, plsAssetListIds);\n                onsContext.start();\n            } else {\n                onsContext.stop();\n            }\n        }\n    }\n\n    /**\n     * We are keeping the following library element methods here to support SAM.cpp and will\n     * move them to LibraryContext after we get better support for library elements.\n     */\n    async restoreLibraryElement(elementId: string) {\n        await this._libraryInterface.restoreLibraryElement(elementId);\n    }\n\n    async permanentlyDeleteLibraryElement(elementId: string) {\n        await this._libraryInterface.permanentlyDeleteLibraryElement(elementId);\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * @deprecated -- will be removed on or after after 2024-10-01\n     */\n    getAssetInterface(repoMetadata: RepositoryMetadata): AssetInterface {\n        oneTimeWarning('AdobeAsset.getAssetInterface', 'AdobeAsset.getAssetInterface is deprecated and will be removed on or after 2024-10-01.');\n        return new AssetInterface(this._rapi, repoMetadata['repo:assetId'], repoMetadata._links, repoMetadata['repo:etag']);\n    }\n\n    /**\n     * Asynchronous method that returns the CommentsResource associated with the asset identified by assetId.\n     *\n     * Clients with an AdobeAsset instance should use AdobeAsset.getCommentsResource(),\n     * but when the Commenting UI has ( SESSION_TYPE === 'logged-out' ),\n     * it isn't possible to construct an AdobeAsset, so they will call this method directly.\n     *\n     * CommentsResource's are asset specific, and they are cached in a Map of WeakRef's,\n     * so client code should ensure there is a pinning reference if they want the context\n     * to be preserved.\n     *\n     * @param assetId {string}\n     * @returns {Promise<CommentContent>}\n     * @see {@link AdobeAsset.getCommentsResource}\n     */\n    async getCommentsResource(assetId: string): Promise<CommentsResource> {\n        let comments = this._commentsById.get(assetId)?.deref();\n\n        if (!comments) {\n            comments = new CommentsResource(this._core, assetId);\n            this._commentsById.set(assetId, new WeakRef(comments));\n\n            this._updateONSSubscriptions(); // make sure we've subscribed to assetId\n        }\n        return comments!;\n    }\n\n    /**\n     * Returns a Promise that resolves when a List is loaded.\n     */\n    async waitForListLoad(list: GenericAssetList): Promise<void> {\n        const { waitForListLoad } = await import('../utils/waitForListLoad');\n        return waitForListLoad(list);\n    }\n\n    _organizationsResource = new Resource<IOrganizationsResponse>(this._core, {\n        onChange: async (organizationsResponse) => {\n            this._defaultOrganizationId = organizationsResponse?.default;\n            this._organizations = organizationsResponse?.children.map(org => ({\n                id: org['organization:id'],\n                name: org['organization:name'] || ''\n            }));\n        }\n    });\n    /*\n     * @package -- only for use in SAM.js\n     * fetches the organizations for the user.\n     */\n    async _fetchOrganizations(): Promise<void> {\n        const projectInterface = new ProjectsInterface(this._core);\n        await projectInterface.getOrganizations(this._organizationsResource);\n    }\n\n    /**\n     * Lazy-loads the list of Organizations for the current user. Use {@link AssetContext.defaultOrganizationId} to\n     * determine which is the home org. The name of the home org is what should be displayed in the UI for the \"Yours\"\n     * view for ESM users.\n     * @returns {Organization[] | undefined}\n     */\n    @lazyLoaded(OrganizationsChangedEventInstance, '_organizations')\n    get organizations(): Organization[] | undefined {\n        return this._organizations;\n    }\n\n    /**\n     * Lazy-loads the \"home organization\" of the current user. See {@link AssetContext.organizations}\n     * @returns {string | undefined}\n     */\n    @lazyLoaded(OrganizationsChangedEventInstance, '_defaultOrganizationId')\n    get defaultOrganizationId(): string | undefined {\n        return this._defaultOrganizationId;\n    }\n\n    /**\n     * @experimental\n     */\n    getAdobeAssetOrder(direction: IOrderDirection = 'descending', field: AdobeAssetOrderField = 'modified'): AdobeAssetOrder {\n        return new AdobeAssetOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getSWYAdobeAssetOrder(direction: IOrderDirection = 'descending', field: SWYAdobeAssetOrderField = 'shared'): SWYAdobeAssetOrder {\n        return new SWYAdobeAssetOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getUSSAdobeAssetOrder(direction: IOrderDirection = 'descending', field: USSAdobeAssetOrderField = 'modified'): USSAdobeAssetOrder {\n        return new USSAdobeAssetOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getAssetVersionOrder(direction: IOrderDirection = 'descending', field: 'created' = 'created'): AssetVersionOrder {\n        return new AssetVersionOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getAdobeAssetFilter(options?: Partial<IAdobeAssetFilterOptions>): AdobeAssetFilter {\n        return new AdobeAssetFilter(options);\n    }\n\n    /**\n     * @experimental\n     */\n    async getSWYAdobeAssetFilter(): Promise<SWYAdobeAssetFilter> {\n        // Filter not lazily loaded async as the sync `sharedSource` accessor requires it.\n        return new SWYAdobeAssetFilter();\n    }\n\n    /**\n     * @experimental\n     */\n    getUSSAdobeAssetFilter(options?: Partial<IUSSAdobeAssetFilter>): USSAdobeAssetFilter {\n        return new USSAdobeAssetFilter(options);\n    }\n\n    /**\n     * @experimental\n     */\n    getRecentAdobeAssetFilter(): RecentAdobeAssetFilter {\n        return new RecentAdobeAssetFilter();\n    }\n\n    /**\n     * @experimental\n     */\n    getAssetVersionFilter(options?: IAssetVersionFilterOptions): AssetVersionFilter {\n        return new AssetVersionFilter(options);\n    }\n\n    /**\n     * @experimental\n     */\n    getIsSharedFilter(view: IsSharedViewSelection = IsSharedViewSelection.ALL): IsSharedFilter {\n        switch (view) {\n        case IsSharedViewSelection.ALL:\n            return new IsSharedFilter();\n        case IsSharedViewSelection.SHARED_WITH_YOU:\n            return new IsSharedFilter({ isSharedWithYou: true });\n        case IsSharedViewSelection.YOURS:\n            return new IsSharedFilter({ ownedBy: this._core._environment.getUserId() });\n        // case IsSharedViewSelection.SHARED_VIA_PROJECT:\n        default:\n            throw SAMError.create(SAMErrorCode.UNKNOWN, `Unsupported view selection: ${view}`);\n        }\n    }\n\n    repoToStudentAssignmentData(item: Partial<RepositoryMetadata>, additionalMetadata: IAppMetadata & Partial<IRemoteStudentAssignment>): Partial<IRemoteStudentAssignment> {\n        const { _links: _linksFromAdditionalMetadata, ...restAdditionalMetadata } = additionalMetadata;\n        const { _links: _linksFromItem, ...restItem } = item;\n        return {\n            ...restItem,\n            ...restAdditionalMetadata,\n            _links: { ..._linksFromItem as AssetLinks, ..._linksFromAdditionalMetadata },\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { CustomModelInfoMelville } from './CustomModelModel';\nimport type { CustomModelTrainingConfiguration } from './CustomModelModel';\nimport type { Assignee, IAppMetadata, IEffectivePermissions } from './RepositoryModel';\n// `_fc` is short for \"from cache\". It signals whether or not the object is fetched from the Melville cache (true) or from the data source (false)\nexport type LibraryRenditionGridData = {\n    main?: LibraryRenditionData;\n    tiles?: LibraryRenditionData[];\n    _fc?: boolean;\n};\n/**\n * DataRenditionMimeTypes is a union of the different possible non-image Library renditions.\n * The following are their respective schemas:\n * https://git.corp.adobe.com/caf/xcm/blob/main/schemas/cc/library/data/color/color.schema.json\n * https://git.corp.adobe.com/caf/xcm/blob/main/schemas/cc/library/data/color-theme/color-theme.schema.json\n * https://git.corp.adobe.com/caf/xcm/blob/main/schemas/cc/library/data/gradient/gradient.schema.json\n * https://git.corp.adobe.com/caf/xcm/blob/main/schemas/cc/library/data/noise-gradient/noise-gradient.schema.json\n*/\nexport type DataRenditionMimeTypes =\n    | 'application/vnd.adobe.color+json'\n    | 'application/vnd.adobe.colortheme+json'\n    | 'application/vnd.adobe.gradient+json'\n    | 'application/vnd.adobe.gradient.noise+json';\n\n/**\n * DataRenditionElementTypes is a union of the different possible non-image Library elements.\n * The following are their respective schemas:\n * https://git.corp.adobe.com/caf/xcm/tree/main/schemas/cc/library/element/color\n * https://git.corp.adobe.com/caf/xcm/tree/main/schemas/cc/library/element/color-theme\n * https://git.corp.adobe.com/caf/xcm/tree/main/schemas/cc/library/element/gradient\n*/\n\nexport type DataElementTypes =\n    | 'application/vnd.adobe.element.color+dcx'\n    | 'application/vnd.adobe.element.colortheme+dcx'\n    | 'application/vnd.adobe.element.gradient+dcx'\n\nexport type LibraryRenditionData = {\n    // Shared property\n    elementId: string;\n} & ({\n    // Only applies to type = 'href'\n    type: 'href';\n    rendition: string;\n    templatedLink?: string;\n    elementType: 'application/vnd.adobe.element.image+dcx';\n} | {\n    // Applies to all other types\n    type: DataElementTypes;\n    rendition: LibraryObjectRenditions;\n    rendition_mimetype: DataRenditionMimeTypes;\n    elementType: DataElementTypes;\n});\n\ntype SwatchValue = {\n    r: number;\n    g: number;\n    b: number;\n};\n\ntype BaseSwatch = {\n    mode: string;\n    alpha: number;\n    value: SwatchValue;\n};\n\ntype ElementColorSwatchRendition = {\n    swatches: (BaseSwatch & { library_rel: string; type: string })[][];\n};\n\ntype ElementColorPaletteRendition = {\n    swatches: BaseSwatch[][];\n};\n\nexport type LibraryObjectRenditions = ElementColorSwatchRendition | ElementColorPaletteRendition;\n\n/**\n * This field reflects legacy behavior from USS, so try to use storage:assignee, path, etc. if it is more applicable.\n * A few things to note:\n * 'private' is a library owned by the user and stored in the user's storage\n * 'incoming' is a bookmarked library in user or org storage, that is not owned by the session user and the user does not have read access to the directory\n * 'team' is a project library in either ESM or USM. Could by owned by session user, or not. Could be bookmarked, or not. (e.g. can be returned by the 'owner=incoming' or 'owner=other' filter.)\n * 'public' is any library owned by someone else that was shared publicly by link, and which the session user is following.\n * The rest, I am unsure if they are really returned. https://jira.corp.adobe.com/browse/CCXB-21079\n */\n// https://git.corp.adobe.com/Stormcloud/melville/blob/integration/com.adobe.melville.core/src/main/java/com/adobe/melville/derivables/ownership/OwnershipDeriverImpl.java\n// https://git.corp.adobe.com/Stormcloud/melville/blob/integration/com.adobe.melville.core/src/main/java/com/adobe/melville/dto/library/LibraryOwnershipScope.java#L45\nexport type Ownership = 'private' | 'public' | 'incoming' | 'outgoing' | 'team' | 'discovery' | 'other';\n\nexport type MelvilleCollaboration = {\n    rootURN: string;\n    ownerId: string;\n    state: string;\n    // role: 'owner' | 'viewer' | 'editor'; // ported from CCLibs Collaboration. Need to check if this is valid. [SHARED-4445]\n    collaborators: MelvilleCollaborator[];\n    invitations: MelvilleInvitation[];\n    public: boolean;\n    hasAdmin: boolean;\n    _fc: boolean;\n};\n\n/**\n * SAM.js already defines class Collaborator to encapsulate a collaborator\n * returned by the Invitation Service, hence, MelvilleCollaborator.\n *\n * NOTE: Melville obtains the same collaborator data, but they process\n * it into a DbLibraryCollaboratorData before generating a\n * MelvilleCollaborator, omitting some of the original information,\n * so Collaborator and MelvilleCOllaborator are not interchangeable.\n *\n * You can find the response schema's on Melville's Swagger:\n * https://git.corp.adobe.com/pages/Stormcloud/apidocs/?urls.primaryName=melville#/Libraries/getLibrary\n */\nexport type MelvilleCollaborator = {\n    email: string;\n    displayName: string;\n    collaborator: string;\n    role: string;\n    canComment: boolean;\n    canShare: boolean;\n    inheritanceType: 'DIRECT' | 'INHERITED';\n    _fc?: boolean;\n};\n\ntype MelvilleInvitation = {\n    id: string;\n    recipientEmail: string;\n    senderName: string;\n    created: string;\n    role: string;\n    canComment: boolean;\n    canShare: boolean;\n};\n\nexport type LibraryRole = {\n    type: 'brand' | 'cm_training_set' | string;\n    usage?: string;\n    priority?: string;\n};\n\n\nexport type BookmarkData = {\n    id: LibraryManifestId | PublicLinkId,\n    type?: string,\n    url?: string, // public links cdn url for public libraries\n    urn?: string, // in collab bookmarks, will be added to the public bookmarks.\n    role?: string,\n    can_share?: boolean,\n    can_comment?: boolean,\n    created?: number,\n    _fc?: boolean\n};\n\nexport type BookmarksResponse = {\n    bookmarks: BookmarkData[],\n    _fc?: boolean\n};\n\nexport type GroupData = {\n    id?: string;\n    name: string;\n    classifier?: string;\n    order: string;\n    created_date?: number;\n    modified_date?: number;\n    parent_id?: string;\n    // In the schema, but not yet supported by melville:\n    localized_names?: { [s: string]: string };\n    sourceRef?: string; // Only present in published libraries.\n};\n\n// This is not part of Melville's response, but is added internally by SAM.js\n// Melville only supplies a boolean `reference` property when a library is returned from a listing requested with the reference parameter for a specific project.\n// This property is used to update the Library instance with the project ID that it is referenced by.\n// see ProjectLibraryListLoader._decorateLibraryDataWithReferencedByProject for more details.\nexport type LibraryReferencedByProject = {\n    projectId: string;\n    reference?: boolean;\n}\n\nexport type LibraryAssetId = string; // the urn used as the global asset identifier. This will be the id we use moving forwards.\n// Legacy IDs:\nexport type LibraryManifestId = string; // the id of the dcx manifest, previously used as the library id (except on public libraries)\nexport type PublicLibraryId = string; // A special id for public libraries that looks like '1UIWQK2SZ5GWPJPLJMNVJS154OMEFF'\nexport type PublicLinkId = string; // Currently for public libraries, the link is its own entity with its own permissions and id. Has the same format as a manifest id.\n\ntype LibraryRemoteIdProperty = {\n    library_urn: LibraryAssetId; // Equivalent to the asset id or cloudID. Required in the updater to identify or create the item in the pool.\n};\n\n// This data is always safe to pass to LibraryUpdater, as it will not overwrite RAPI data.\n// These properties should be updated in Library > safePropertyUpdaterTypes.\nexport type LibrarySpecificData = LibraryRemoteIdProperty & {\n    id: LibraryManifestId | PublicLibraryId;\n    bookmark?: BookmarkData;\n    name: string; // Gets saved to _displayName instead of _name so it does not overwrite RAPI data.\n    ownership: Ownership;\n    roles: LibraryRole[];\n    'firefly#cme'?: CustomModelTrainingConfiguration;\n    rendition_grid: LibraryRenditionGridData;\n    thumbnail?: LibraryRenditionData; // This is the thumbnail\n    referenced_by_project?: LibraryReferencedByProject;\n}\n\nexport type UpdateLibraryMetadataPayload = {\n    name: string;\n    roles: LibraryRole[];\n    'firefly#cme'?: Partial<CustomModelTrainingConfiguration>;\n    // id is intentionally commented out as we don't currently want to expose the ability to change the Library ID\n    // id: string;\n}\n\nexport type ParentAssetId = string;\n\n// This captures the library level metadata in a Library response. The elements properties aren't returned here, as they are fetched separately by library.\nexport type LibraryData = LibrarySpecificData & {\n    custom_models?: CustomModelInfoMelville[];\n    toolkit_id?: string;\n    storage_used?: number;\n    document_id?: string;\n    document_type?: string; // xd document type\n    creator?: string;\n    org_id?: string; // Equivalent to `storage_assignee?.type === 'org' && storage_assignee.id`. Only present on project libraries in ESM. EDIT: This will support the id of personal projects moving fowards as well.\n    workspace_name?: string;\n    workspace_urn?: ParentAssetId; // legacy property kept for backwards compatibility. Use the newer parent_assetId.\n    application_metadata?: IAppMetadata; // seems to be returned on USM or ESM project libraries, regardless of the list selector\n    created_date: number;\n    modified_date: number;\n    'repo:repositoryId': string;\n    version: string;\n    region?: string;\n    storage_path?: string;\n    elements_count: number;\n    removed_elements_count: number;\n    document_elements_count?: number;\n    rendition_grid?: LibraryRenditionGridData;\n    thumbnail?: LibraryRenditionData;\n    collaboration?: MelvilleCollaboration;\n    asset_acl: IEffectivePermissions;\n    // Source: https://git.corp.adobe.com/Stormcloud/melville/blob/integration/com.adobe.melville.core/src/main/java/com/adobe/melville/db/dto/library/DbLibraryDetail.java\n    details?: {\n        manifest_id: LibraryManifestId; // Only place to find the manifest id on public libraries, but it is not used for anything.\n        num_elements?: number;\n        num_documentation_elements?: number;\n        num_archived_elements?: number;\n        types?: string[];\n        element_type_counts?: { [key: string]: number };\n        etag?: string;\n        state?: string;\n        manifest_format_version?: string;\n        description?: string;\n        'firefly#cme'?: CustomModelTrainingConfiguration;\n        'brand#copyGuideLines'?: any;\n    };\n    groups?: GroupData[];\n    _links: MelvilleLinks;\n    searchable?: boolean;\n    raw_name?: string;\n    renditionGridMissing?: boolean;\n    assetSubType?: string;\n    _fc?: boolean;\n    manifest_etag?: string; // This might not be present on older libraries\n    is_searchable?: boolean;\n    parent_assetId?: ParentAssetId; // any parent urn, whether project, sync group, or other folder. This should be mapped to the Asset's _ancestorIDs, but at the moment there is no client need to expose this.\n    archived_date?: number;\n    archived_by?: string;\n    storage_assignee?: Assignee; // will not be present on public libraries\n    created_by?: string;\n    modified_by?: string;\n    reference?: boolean; // whether the library is referenced by a project\n};\n\nexport type MelvilleLink = {\n    href: string;\n    rel: string;\n    templated?: boolean;\n    type?: string; // did not see this returned in reality\n}\n\nexport type MelvilleLinks = {\n    [key: string]: MelvilleLink;\n}\n\nexport type LibraryListLinks = MelvilleLinks & {\n    page: MelvilleLink;\n    next: MelvilleLink;\n};\n\nexport type LibrariesResponse = {\n    total_count: number;\n    libraries: LibraryData[];\n    _page: {\n        orderBy: string,\n        start: string,\n        next: string,\n        count: 0,\n        type: string,\n        property: string\n    };\n    _links: LibraryListLinks;\n    inaccessibleReferences?: string[];\n}\n\nexport type AccessOption = 'team_edit' | 'team_view' | 'invite_only';\n\nexport type CopyLibraryRequest = {\n    source: string;\n    name?: string;\n    access?: AccessOption;\n    parent_assetId?: string;\n}\n\nexport type Guideline = {\n    text: string;\n}\n\nexport type ResourceDesignator = {\n    reltype: string;\n    revision: string;\n    component_id: string;\n}\n\nexport type BrandCopyGuidelines = {\n    toneOfVoice: Guideline[];\n    coreValues: Guideline[];\n    uniqueAttributes: Guideline[];\n    frequentKeywords: Guideline[];\n    guidelines: Guideline[];\n    restrictions: Guideline[];\n    additionalGuidelines: Guideline[];\n};\n\n\nexport type CreateLibraryOptions = {\n    syncCreate?: boolean; // If true, the library will be created with invocation_mode=sync. Otherwise, it will be created with invocation_mode=async\n    name: string;\n    parent_assetId?: string;\n    roles?: LibraryRole[];\n    source?: string;\n    self?: string;\n    access?: AccessOption;\n    repository?: string;\n    'firefly#ffmodel'?: {\n        schemaVersion: string;\n        [key: string]: any;\n    };\n    // the field below is accepted for now with plans to move to `firefly#ffmodel`\n    'firefly#cme'?: {\n        version: string;\n        [key: string]: any;\n    };\n    'brand#copyGuideLines'?: {\n        brandCopyGuidelines: BrandCopyGuidelines\n    },\n    'library#description'?: {\n        [key: string]: any;\n    },\n    includeResources?: ResourceDesignator[];\n};\n\nexport type CreatePersonalLibraryData = Pick<CreateLibraryOptions, 'name' | 'roles'>;\nexport type CreateProjectLibraryData = Pick<CreateLibraryOptions, 'name' | 'roles'> & { restrictEdit?: boolean };\n\nexport type MoveLibraryRequest = {\n    self: string;\n    parent_assetId: string;\n    'repo:manifestPatch': { op: 'replace', path: '/id', value: string }[];\n    access?: AccessOption;\n}\n\nexport enum LibraryOrderBy {\n    MODIFIED_DATE = 'modified_date',\n    CREATED_DATE = 'created_date',\n    NAME = 'name' // actually displayName\n}\n\n/**\n * Enum for library owner filter\n * (If you update this list, also update LibraryFilter.matches/getRelationToFilter.)\n * @enum {string}\n */\nexport enum LibraryOwnerFilter {\n    /**\n     * Personal libraries created in User Storage that are specifically stored inside the sync group: `/assets/adobe-libraries`\n     * Excludes CCI Project Libraries.\n     */\n    Personal = 'private',\n    /**\n     * Bookmarked public libraries.\n     * Currently will be ignored if combined with other ownership types.\n     */\n    Public = 'public',\n    /**\n     * Bookmarked incoming libraries. This includes:\n     * - Libraries shared directly with the user that the user has accepted the invite to\n     * - CCI Project Libraries which live in User Storage (`/users/{userId}` in ESM, `/` in USM and for unified users)\n     * - Project Libraries the user has followed (After SMU, these will all live in `/projects/{projectName}`)\n     */\n    Incoming = 'incoming',\n    /**\n     * Everything the user has acccess to that is not in User Storage, except public libraries.\n     * Includes: Project libraries, Incoming libraries (except CCI Project Libraries since they are in User Storage)\n     * Excludes: Public libraries, CCI Project Libraries, Private Libraries\n     */\n    Discovery = 'discovery',\n    /**\n     * A subset of 'discovery' that excludes already bookmarked libraries.\n     */\n    // Other = 'other',\n    /**\n     * All of the above except public libraries currently (until supported by USS).\n     * If combined with other owner types, the others will be ignored.\n     */\n    All = 'all'\n}\n\nexport enum LibraryProjectFilterEnum {\n    /**\n     * Include all project libraries.\n     */\n    All = 'all',\n    /**\n     * Do not include any project libraries.\n     */\n    None = 'none',\n    /**\n     * Include project libraries that the user is NOT a member of.\n     */\n    // Other = 'other'\n}\n/**\n * Project filter supports a project id or any value in the LibraryProjectFilterEnum\n */\nexport type LibraryProjectFilter = LibraryProjectFilterEnum | ProjectAssetId;\n\n/**\n * @experimental API May change.\n *\n * Enum for library reference filter\n * This filter must be used in conjunction with a projectID via the LibraryProjectFilter.\n * @enum {string}\n */\nexport enum LibraryReferenceFilter {\n    /**\n     * Return all libraries beneath the project or referenced by the project\n     */\n    All = 'all',\n    /**\n     * Include only libraries referenced by the project\n     */\n    Only = 'only',\n}\n\nexport enum LibraryRolesFilter {\n    /**\n     * Include libraries that have no roles\n     */\n    None = 'none',\n    /**\n     * Include libraries that have at least one role where role.type === 'brand'\n     */\n    Brand = 'brand',\n    /**\n     * Include training set libraries. Currently the default, as it is the only option.\n     */\n    TrainingSet = 'cm_training_set'\n}\n\n/**\n * This enum is used for filtering the library list view for brands specifically based on it's publishing related app metadata.\n * This filter is only usable if the brand role is true.\n *\n * There are three types of brands that exist in the data:\n * 1. Published brands -- These are the brands that have brand:publishedFrom in their app metadata.\n * Nobody is able to update these brands directly, they can only be updated by publishing changes from their draft brand counterpart (which is what brand:publishedFrom points to).\n *\n * 2. Draft brands with a published counterpart -- These are the brands that have brand:publishedTo in their app metadata.\n * These brands do NOT show up in the list of brands, but still can be accessed when a user goes to edit a published brand.\n * This is so we can maintain a \"Draft\" state for a published brand so brand creators can make revisions without updating the published copy that is currently in use.\n *\n * 3. Draft brands that are unpublished -- These are brands that are not part of a published brand in any way, and thus have neither brand:publishedFrom nor brand:publishedTo.\n * These brands are editable, and do show up in the brands listing view.\n */\nexport enum BrandPublishMetadataFilter {\n    /**\n     * Includes: Published brands\n     *\n     * Excludes: Unpublished draft brands, Draft brands with a published counterpart\n     */\n    PublishedBrands = 'publishedBrands',\n    /**\n     * Includes: Published brands, Unpublished draft brands\n     *\n     * Excludes: Draft brands with a published counterpart\n     */\n    AllBrands = 'allBrands',\n    /**\n     * Includes: Unpublished draft brands, Draft brands with a published counterpart\n     *\n     * Excludes: Published brands\n     */\n    AllEditableBrands = 'allEditableBrands'\n}\n\ntype CommaDelimitedString = string;\n/**\n * Selectors determine what data is returned in the libraries response. You may combine multiple in a comma delimited list.\n * default: only base data for a library (You do not need to specify this to get default data from the other selectors.)\n * rendition_grid: adds `rendition_grid` and `renditionGridMissing` to default data\n * collaboration: adds `collaboration` to default data\n * groups: adds `groups` to default data\n * details: adds `details` to the default data\n * app_metadata: <needs to be tested. `application_metadata` appears on team libraries without using this.>\n */\nexport type LibrarySelectors = 'default' | 'details' | 'collaboration' | 'groups' | 'rendition_grid' | 'app_metadata' | CommaDelimitedString;\nexport type OwnerParameters = LibraryOwnerFilter | CommaDelimitedString;\ntype ProjectAssetId = string; // urn of the project\ntype TeamParameters = LibraryProjectFilter;\ntype ReferenceParameters = LibraryReferenceFilter;\ntype LibraryCapabilities = 'write' | CommaDelimitedString;\nexport type RolesParameters = LibraryRolesFilter | CommaDelimitedString;\ntype ItemFilterParameters = BrandPublishMetadataFilter;\ntype ToolkitId = string;\ntype ToolkitParameter = 'all' | 'none' | ToolkitId | CommaDelimitedString;\ntype OrderBy = LibraryOrderBy.NAME | LibraryOrderBy.MODIFIED_DATE | LibraryOrderBy.CREATED_DATE | '-name' | '-created_date' | '-modified_date' | CommaDelimitedString; // Default: modified_date. Sorting is not available for public libraries.\n/**\n * Query parameters from the GET /libraries endpoint via Melville's API\n * @see https://git.corp.adobe.com/pages/Stormcloud/apidocs/?urls.primaryName=melville#/Libraries/getLibraries\n*/\nexport type LibraryListParameters = {\n    owner?: OwnerParameters;\n    team?: TeamParameters;\n    roles?: RolesParameters;\n    itemFilter?: ItemFilterParameters;\n    toolkit?: ToolkitParameter;\n    selector?: LibrarySelectors;\n    capabilities?: LibraryCapabilities;\n    workspace?: string;\n    start?: number; // paging not available for public libraries. Default if undefined: 0. Required if there is a limit.\n    limit?: number; // paging not available for public libraries. Default if undefined: 50. Limits greated than 50 will be capped at 50.\n    orderBy?: OrderBy;\n    references?: ReferenceParameters;\n};\n\n\n/**\n * Query parameters from the GET /libraries/search endpoint via Melville's API\n * @see https://git.corp.adobe.com/pages/Stormcloud/apidocs/?urls.primaryName=melville#/Libraries/search\n*/\nexport type SearchLibraryRequest = {\n    query_string: string;\n    asset_type?: string[];\n    selector?: LibrarySelectors;\n    start?: string;\n    limit?: string;\n}\n\nexport type ResourceRef = {\n    'repo:assetId'?: string;\n    'repo:version'?: string;\n}\n\nexport interface IBrandsAssetAppMetadata {\n    'brand:publishedFrom'?: ResourceRef;\n    'brand:publishedTo'?: ResourceRef;\n    'brand:lastPublishedVersion'?: string;\n    'brand:extractedFrom'?: ResourceRef[];\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { LibraryOrderBy } from '../interface/LibraryModel';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\n\nimport type Library from './Library';\n\nexport type LibraryOrderField =\n    | 'name'\n    | 'created'\n    | 'modified';\n\nexport const OrderFieldToLibraryOrderBy: { [key in LibraryOrderField]: LibraryOrderBy} = {\n    'name': LibraryOrderBy.NAME,\n    'created': LibraryOrderBy.CREATED_DATE,\n    'modified': LibraryOrderBy.MODIFIED_DATE\n};\n\n// Appropriate comparator is used in order.sortItems when copying or updating ItemLists,\n// which occurs when a page is loaded and the ItemLoaderState changes.\nconst OrderFieldToComparator: IComparatorMap<Library, LibraryOrderField> = {\n    name(a: Library, b: Library): number {\n        // LibraryOrder is only used on lists from LibrarySource, where LibraryData from melville should already be loaded.\n        // (But just in case, this falls back to repoMetadata name, though this wouldn't work properly for libraries in sync groups.)\n        return compareStrings(a.displayName || a.name, b.displayName || b.name);\n    },\n\n    created(a: Library, b: Library): number {\n        return compareValues(a.created, b.created);\n    },\n\n    modified(a: Library, b: Library): number {\n        return compareValues(a.modified, b.modified);\n    }\n};\n\nexport default class LibraryOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new LibraryOrder('descending', 'modified');\n}\n","import type { ItemFilterRelation } from '../core/ItemFilter';\nimport type {\n    LibraryProjectFilter } from '../interface/LibraryModel';\nimport {\n    LibraryOwnerFilter,\n    LibraryProjectFilterEnum,\n    LibraryRolesFilter,\n    BrandPublishMetadataFilter,\n    LibraryReferenceFilter\n} from '../interface/LibraryModel';\nimport type Library from './Library';\nimport { ModernSet } from '../utils/ModernSet';\n\n// Helper methods for IItemFilter.matches() when the filter uses LibraryFilterOptions.\n\nexport function itemMatchesOwnerFilter(item: Library, owner: Set<LibraryOwnerFilter>) {\n    if (item._ownership_NoLazyLoad === undefined) {\n        return false;\n    }\n\n    return owner.has(item._ownership_NoLazyLoad as LibraryOwnerFilter)\n        // Public libraries are not returned by the 'all' owner filter\n        || (owner.has(LibraryOwnerFilter.All) && !item._isPublicLink_NoLazyLoad)\n        // 'ownership' field can be 'incoming' or 'team' for followed project libraries. We are trying to move away from relying on this field,\n        // so this just checks for a collab bookmark.\n        || (owner.has(LibraryOwnerFilter.Incoming) && !item._isPublicLink_NoLazyLoad && item._isBookmarked_NoLazyLoad)\n        // Discovery includes everything the user has access to that is NOT in User Storage except public libraries.\n        // * Includes: Incoming libraries, Project libraries (except CCI Project Libraries since they are in User Storage)\n        // * Excludes: Public libraries, CCI Project Libraries, Private Libraries\n        || (owner.has(LibraryOwnerFilter.Discovery) && (item._ownership_NoLazyLoad !== 'private') && !item._isPublicLink_NoLazyLoad && !item._isCCIProjectLibrary);\n}\n\nexport function itemMatchesRolesFilter(item: Library, roles: Set<LibraryRolesFilter>) {\n    if (item._roles_NoLazyLoad === undefined) {\n        return false;\n    }\n\n    return roles.has(LibraryRolesFilter.None) && (!item._roles_NoLazyLoad || item._roles_NoLazyLoad.length === 0)\n        // one of the roles filters matches one of the roles on the library\n        || item._roles_NoLazyLoad?.some(role => roles.has(role.type as LibraryRolesFilter));\n}\n\nexport function itemMatchesProjectFilter(item: Library, project: LibraryProjectFilter, reference?: LibraryReferenceFilter) {\n    return (project === LibraryProjectFilterEnum.All && item.isChildOfProject)\n        || (project === 'none' && !item.isChildOfProject)\n        || (project === 'other' && item.isChildOfProject && !item._isBookmarked_NoLazyLoad)\n        || (reference === LibraryReferenceFilter.Only && item.isReferencedByProject(project))\n        || (reference === LibraryReferenceFilter.All && item.isReferencedByProject(project))\n        || (project === item.parentProjectID && reference !== LibraryReferenceFilter.Only);\n}\n\nexport function itemMatchesPublishMetadataFilter(item: Library, publishMetadata: BrandPublishMetadataFilter) {\n    return (publishMetadata === BrandPublishMetadataFilter.AllBrands && !item.publishedTo)\n        || (publishMetadata === BrandPublishMetadataFilter.PublishedBrands && item.publishedFrom)\n        || (publishMetadata === BrandPublishMetadataFilter.AllEditableBrands && !item.publishedFrom);\n}\n\n// Helper methods for IItemFilter.getRelationToFilter() when the filter uses LibraryFilterOptions.\n\nexport function checkOwnerRelation(newOwnerSet: Set<LibraryOwnerFilter> = new Set([ LibraryOwnerFilter.All ]), existingOwnerSet: Set<LibraryOwnerFilter> = new Set([ LibraryOwnerFilter.All ])): ItemFilterRelation {\n    const intersection = ModernSet.prototype.intersection.call(newOwnerSet, existingOwnerSet);\n    const subset = intersection.size === newOwnerSet.size;\n    if (subset) { return 'subset';} // all new values are in existing values\n\n    const difference = ModernSet.prototype.symmetricDifference.call(newOwnerSet, existingOwnerSet);\n\n    //Public libraries don't overlap with anything, including 'all'\n    if (difference.has(LibraryOwnerFilter.Public)) {\n        return 'disjoint';\n    }\n\n    // all other combinations are subsets of 'all'\n    if (existingOwnerSet.has(LibraryOwnerFilter.All)) {\n        return 'subset';\n    }\n\n    // newOwnerSet is a superset of existing owner set, because all includes all libraries\n    if (newOwnerSet.has(LibraryOwnerFilter.All)) {\n        return 'unknown';\n    }\n\n    if (difference.has(LibraryOwnerFilter.Discovery) && difference.has(LibraryOwnerFilter.Incoming)) {\n        // If one filter is 'incoming', it may partially overlap with a 'discovery' filter,\n        // regardless of what other filters are present, or which is pre-existing.\n        if (newOwnerSet.has(LibraryOwnerFilter.Discovery) && existingOwnerSet.has(LibraryOwnerFilter.Incoming)\n                || existingOwnerSet.has(LibraryOwnerFilter.Discovery) && newOwnerSet.has(LibraryOwnerFilter.Incoming)) {\n            return 'unknown';\n        }\n    }\n\n    if (intersection.size > 0) { return 'unknown'; } // some overlap\n    return 'disjoint'; // no overlap since intersection.size === 0\n}\n\nexport function checkRolesRelation(newRolesSet?: Set<LibraryRolesFilter>, existingRolesSet?: Set<LibraryRolesFilter>): ItemFilterRelation {\n    if (newRolesSet && existingRolesSet) {\n        return checkSetOverlap(newRolesSet, existingRolesSet);\n    }\n    if (newRolesSet || existingRolesSet) {\n        return 'unknown';\n    }\n    // if both are undefined, we don't need to check roles. 'undefined' is equivalent to 'all roles'\n    return 'subset';\n}\n\nexport function checkProjectRelation(newProjectFilter?: LibraryProjectFilter, existingProjectFilter?: LibraryProjectFilter): ItemFilterRelation {\n    if (newProjectFilter) {\n        const checkIfIsProjId = (projectFilter: string): boolean => {\n            // Assume that any projectFilter that is not one of the enum values is a project id\n            return !Object.values(LibraryProjectFilterEnum).includes(projectFilter as LibraryProjectFilterEnum);\n        };\n        const subset = !existingProjectFilter // if existing project filter is undefined, that means it includes libraries that may or may not be in a project\n            || newProjectFilter === existingProjectFilter\n            || (checkIfIsProjId(newProjectFilter) && existingProjectFilter === LibraryProjectFilterEnum.All); // if project filter is 'all', that means the library must be in a project\n        return subset ? 'subset' : 'disjoint';\n    }\n    if (!newProjectFilter && existingProjectFilter) {\n        return 'unknown';\n    }\n    return 'subset';\n}\n\nexport function checkPublishMetadataRelation(newPublishMetadataFilter?: BrandPublishMetadataFilter, existingPublishMetadataFilter?: BrandPublishMetadataFilter): ItemFilterRelation {\n    // If there was no filter before or the filter has not changed, we can assume that the new filter is a subset of the existing filter\n    if (!existingPublishMetadataFilter || newPublishMetadataFilter === existingPublishMetadataFilter) {\n        return 'subset';\n    }\n\n    // If the new filter is for published brands and the existing filter is for all editable brands, they are inverse of each other and there is no overlap\n    if (newPublishMetadataFilter === BrandPublishMetadataFilter.PublishedBrands && existingPublishMetadataFilter === BrandPublishMetadataFilter.AllEditableBrands) {\n        return 'disjoint';\n    }\n\n    // The inverse is also true -- if the new filter is for all editable brands and the existing filter is for published brands, they are inverse of each other and there is no overlap\n    if (newPublishMetadataFilter === BrandPublishMetadataFilter.AllEditableBrands && existingPublishMetadataFilter === BrandPublishMetadataFilter.PublishedBrands) {\n        return 'disjoint';\n    }\n\n    // The \"All brands\" publish metadata filter will always include all published brands as well\n    if (existingPublishMetadataFilter === BrandPublishMetadataFilter.AllBrands && newPublishMetadataFilter === BrandPublishMetadataFilter.PublishedBrands) {\n        return 'subset';\n    }\n\n    return 'unknown';\n}\n\n/**\n  * Checks the relation between the new reference filter and the existing reference filter.\n  * @param newReference - The new reference filter\n  * @param existingReference - The existing reference filter\n  * @returns The relation between the new reference filter and the existing reference filter\n  */\nexport function checkReferenceRelation(newReference?: LibraryReferenceFilter, existingReference?: LibraryReferenceFilter): ItemFilterRelation {\n\n    // If the reference filter is the same, it's a subset\n    if (newReference === existingReference) {\n        return 'subset';\n    }\n\n    // All covers both Only and undefined\n    if (existingReference === LibraryReferenceFilter.All) {\n        return 'subset';\n    }\n\n    // If the new reference is All then the existing reference must not be All (because we made it here after the prior equality check)\n    // the list can be partially built with the existing reference, so it's unknown\n    if (newReference === LibraryReferenceFilter.All) {\n        return 'unknown';\n    }\n\n    // new reference is undefined and existing reference is Only\n    // new reference is Only and existing reference is undefined\n    return 'disjoint';\n}\n\nfunction checkSetOverlap(newValuesSet: Set<string>, existingValuesSet: Set<string>): ItemFilterRelation {\n    const intersection = ModernSet.prototype.intersection.call(newValuesSet, existingValuesSet);\n    const subset = intersection.size === newValuesSet.size;\n\n    if (subset) { return 'subset';} // all new values are in existing values\n    if (intersection.size > 0) { return 'unknown'; } // some overlap\n    return 'disjoint'; // no overlap since intersection.size === 0\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport type { default as Library } from './Library';\nimport type { LibraryProjectFilter, LibraryReferenceFilter } from '../interface/LibraryModel';\nimport { LibraryOwnerFilter, LibraryRolesFilter, BrandPublishMetadataFilter } from '../interface/LibraryModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { checkOwnerRelation, checkProjectRelation, checkRolesRelation, checkPublishMetadataRelation, itemMatchesOwnerFilter, itemMatchesProjectFilter, itemMatchesRolesFilter, itemMatchesPublishMetadataFilter, checkReferenceRelation } from './LibraryFilterUtils';\n\n/**\n * Filter options for libraries.\n */\nexport interface LibraryFilterOptions {\n    owner?: LibraryOwnerFilter[];\n    roles?: LibraryRolesFilter[];\n    project?: LibraryProjectFilter;\n    /**\n     * NOTE: This maps to Melville's \"itemFilter\" parameter, but that name is very confusing to use when there's an existing \"ItemFilter\" class and type.\n     * Therefore, we're naming this \"publishMetadata\" to be more clear.\n     */\n    publishMetadata?: BrandPublishMetadataFilter;\n    reference?: LibraryReferenceFilter;\n}\n/**\n * Internal filter that is for defining the ItemSource(s).\n * It contains both the parameters sent in the server request, and the filters used on the returned item data.\n * e.g. The LibrarySource should return libraries that are private, incoming, etc.\n */\nexport default class LibraryFilter implements IExplicitFilter<Library> {\n    _hash: string | undefined;\n    _owner: Set<LibraryOwnerFilter> | undefined;\n    _roles: Set<LibraryRolesFilter> | undefined;\n    _project: LibraryProjectFilter | undefined;\n    _publishMetadata: BrandPublishMetadataFilter | undefined;\n    _reference: LibraryReferenceFilter | undefined;\n    /* Static filters that represent typical filters used in the UI. */\n\n    // Contains all of the user's libraries, including private, followed project libraries, and libraries the user has accepted an invite to.\n    // In the future, this will also include followed public libraries. (USS does not currently support adding public to the query.)\n    static AllLibraries = new LibraryFilter({\n        // we don't use LibraryOwnerFilter.All query param because it includes unfollowed business storage libraries\n        owner: [ LibraryOwnerFilter.Incoming, LibraryOwnerFilter.Personal ]\n    });\n\n    /**\n     * This filter is used to fetch the brands of a brands consumer, who can only see published brands (but not edit them).\n     */\n    static CollaboratorBrands = new LibraryFilter({\n        owner: [ LibraryOwnerFilter.All ],\n        roles: [ LibraryRolesFilter.Brand ],\n        publishMetadata: BrandPublishMetadataFilter.PublishedBrands\n    });\n\n    /**\n     * This filter is used to fetch the brands of a brands editor, who can edit all brands in the given brands project.\n     * This filter should return all published brands in the project, along with any draft brands that are not published.\n     *\n     * _NOTE: This does NOT include the draft brands that have a published counterpart, since those should not be listed in their main view._\n     * @param brandsProjectId The project ID for the brands project.\n     */\n    static EditorBrands(brandsProjectId: string): LibraryFilter {\n        return new LibraryFilter({\n            owner: [ LibraryOwnerFilter.All ],\n            roles: [ LibraryRolesFilter.Brand ],\n            publishMetadata: BrandPublishMetadataFilter.AllBrands,\n            project: brandsProjectId\n        });\n    }\n\n    static DEFAULT = LibraryFilter.AllLibraries;\n\n    constructor(readonly filterOptions: LibraryFilterOptions = {}) {\n        this._project = filterOptions.project;\n        if (filterOptions.roles && filterOptions.roles.length > 0) {\n            this._roles = new Set([ ...(filterOptions.roles) ]);\n        }\n        if (filterOptions.reference) {\n            this._reference = filterOptions.reference;\n            if (filterOptions.owner) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The reference filter cannot be used with the owner filter.');\n            }\n            if (!this._project) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The reference filter must be used with the project filter.');\n            }\n        } else {\n            this._owner = filterOptions.owner ? new Set([ ...filterOptions.owner ]) : LibraryFilter.DEFAULT._owner;\n            if (this._owner && this._owner.size > 1) {\n                if (this._owner.has(LibraryOwnerFilter.Public)) {\n                    // This is the case temporarily until melville supports public libraries in the same query.\n                    throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Public libraries cannot be combined with other ownership types.');\n                }\n                if (this._owner.has(LibraryOwnerFilter.Discovery) && this._owner.has(LibraryOwnerFilter.Incoming)) {\n                    throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Discovery and Incoming are redundant, as Incoming is a subset of Discovery.');\n                }\n            }\n        }\n        if (filterOptions.publishMetadata) {\n            if (!this._roles || !this._roles.has(LibraryRolesFilter.Brand)) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The publish metadata filter can only be used with the brands role.');\n            }\n            this._publishMetadata = filterOptions.publishMetadata;\n        }\n    }\n\n    // Used in ItemSource._getListHash to identify the list.\n    get hash(): string {\n        if (!this._hash) {\n            this._hash = [\n                this._owner ? `owner=${[ ...this._owner ].sort().join(',')}` : undefined,\n                this._roles ? `roles=${[ ...this._roles ].sort().join(',')}` : undefined,\n                this._project ? `project=${this._project}` : undefined,\n                this._publishMetadata ? `publishMetadata=${this._publishMetadata}` : undefined,\n                this._reference ? `reference=${this._reference}` : undefined\n            ].filter(x => x).join(':');\n        }\n        return this._hash;\n    }\n\n    /**\n     * Checks if an item matches the filter. (May be used by ItemList and ItemLoaderState, and is called when asset change notifications\n     * come in to check if the asset is still eligible to be on a particular list.)\n     */\n    matches(item: Library): boolean {\n        // If a library has not loaded melville data, it is not considered a match.\n        // We also make sure not to trigger lazy loading on an unloaded library, as that should only be triggered by the client.\n        // If the data has been loaded once, we want the library to pass here (unless we get data that says it no longer passes) because\n        //   we don't want it to disappear from listings after it's already been shown to the user\n        if (!item.isLibrary) {\n            return false;\n        }\n        if (this._owner && !itemMatchesOwnerFilter(item, this._owner)) {\n            return false;\n        }\n        if (this._project && !itemMatchesProjectFilter(item, this._project, this._reference)) {\n            return false;\n        }\n        if (this._roles && !itemMatchesRolesFilter(item, this._roles)) {\n            return false;\n        }\n        if (this._publishMetadata && !itemMatchesPublishMetadataFilter(item, this._publishMetadata)) {\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * This method determines the commonality between the already present filter (existing)\n     * and the new filter to be applied (this). The point of this is to\n     * see if the new filter (this) can build some, all, or none of it's items\n     * from (existing) filter.\n     *\n     * Subset: Means that ALL items for this filter can be built from existing\n     * Disjoint: No items for this filter can be built from existing.\n     * Unknown: Some items for this filter can be built from existing.\n     *\n     * @note we should always determine disjoint cases first before other cases.\n     * @note this = NEW FILTER, existing = EXISTING FILTER\n     *\n     * @param existing The existing filter that we are getting the relation to.\n     * @returns { ItemFilterRelation }\n     */\n    getRelationToFilter(existing: LibraryFilter): ItemFilterRelation {\n        const relations = [\n            // owner filter always exists\n            checkOwnerRelation(this._owner, existing._owner),\n            checkRolesRelation(this._roles, existing._roles),\n            checkProjectRelation(this._project, existing._project),\n            checkPublishMetadataRelation(this._publishMetadata, existing._publishMetadata),\n            checkReferenceRelation(this._reference, existing._reference)\n        ];\n\n        if (relations.includes('disjoint')) {\n            return 'disjoint';\n        }\n        if (relations.includes('unknown')) {\n            return 'unknown';\n        }\n\n        // only remaining possibility is 'subset'\n        return 'subset';\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { compareStrings, compareValues, createItemOrderFactory } from '../../core/ItemOrder';\nimport type { IComparatorMap } from '../../core/ItemOrder';\n\nimport type Element from '../../library-contents/models/Element';\n\nexport enum ElementOrderBy {\n    MODIFY_DATE = 'modifyDate',\n    CREATE_DATE = 'createDate',\n    NAME = 'name'\n}\n\nexport type ElementOrderField =\n    | 'name'\n    // | 'created'\n    | 'modified';\n\nconst OrderFieldToComparator: IComparatorMap<Element, ElementOrderField> = {\n    name(a: Element, b: Element): number {\n        return compareStrings(a.name, b.name);\n    },\n    //\n    // created(a: Element, b: Element): number {\n    //     return compareValues(a.created, b.created);\n    // },\n\n    modified(a: Element, b: Element): number {\n        return compareValues(a.modified, b.modified);\n    }\n};\n\nexport default class ElementOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new ElementOrder('descending', 'modified');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ClassroomMemberRole } from './ClassroomMemberModel';\nimport type { RequiredStudentAssignmentFilterOptions } from './StudentAssignmentModel';\nimport type { CreateBoardOptions } from './BoardModel';\n\nexport interface IEntityRef {\n    authSrc: string;\n    ident: string;\n}\nexport interface IUserProfile {\n    email: string;\n    firstName: string;\n    lastName: string;\n    userId: string;\n}\n\nexport enum LearningManagementSystems {\n    GC = 'GC', // GC is Google Classroom\n}\n\nexport enum LearningManagementSystemRoles {\n    STUDENT = 'STUDENT',\n    TEACHER = 'TEACHER',\n}\n\nexport enum RosterImportState {\n    BLOCKED = 'BLOCKED',\n    INVITED = 'INVITED',\n    JOINED = 'JOINED',\n    NOT_ENROLLED = 'NOT_ENROLLED',\n    REMOVED = 'REMOVED',\n}\n\nexport enum ImportSourceType {\n    CLEVER = 'clever',\n    CLASS_LINK = 'classlink',\n}\n\nexport enum ClassroomStatus {\n    ACTIVE = 'ACTIVE',\n    ARCHIVED = 'ARCHIVED',\n}\n\nexport enum ClassroomType {\n    /** Allowed classrooms for Top Down organization users */\n    TRUE = 'TRUE',\n    /** Allowed classrooms for Bottom up organization users */\n    RESTRICTED = 'RESTRICTED',\n    /** Allowed classrooms for users on their personal account */\n    UNRESTRICTED = 'UNRESTRICTED',\n    /** Not allowed classrooms */\n    NONE = 'NONE',\n}\n\nexport interface IRemoteImportSource {\n    /** The ImportSource's ID of the classroom */\n    source?: ImportSourceType;\n    /** The type of import source, e.g., 'clever', 'classlink' */\n    sourceId?: string;\n    /** The date when the classroom was last synced with the import source */\n    lastUpdatedAt?: string;\n}\n\nexport interface IImportSource {\n    /**\n     * The ImportSource's ID of the classroom\n     * Maps to the remote importedFrom.sourceId\n     * */\n    id?: string;\n    /**\n     * The type of import source, e.g., 'clever', 'classlink'\n     * Maps to the remote importedFrom.source\n     * */\n    type?: ImportSourceType;\n    /**\n     * The date when the classroom was last synced with the import source\n     * Maps to the remote importedFrom.lastUpdatedAt\n     * */\n    synced?: Date;\n}\n\nexport interface IRosterEntry {\n    adobeId: string;\n    courseId: string;\n    emailID: string;\n    firstName: string;\n    lastName: string;\n    lmsRole: LearningManagementSystemRoles;\n    rosterImportState: RosterImportState[];\n    sourceLms: LearningManagementSystems;\n    userId: string;\n}\n\nexport enum SubjectTypes {\n    noSubject = '',\n    allsubjects = 'allsubjects',\n    careersTechnicalEducation = 'careersTechnicalEducation',\n    computerScience = 'computerScience',\n    english = 'english',\n    math = 'math',\n    otherLanguages = 'otherLanguages',\n    others = 'others',\n    science = 'science',\n    socialStudies = 'socialStudies',\n    visualPerformingArts = 'visualPerformingArts',\n}\n\nexport interface IClassroomCreateData {\n    // Can be undefined if the classroom is being created from a virtual class\n    name?: string;\n    // Defined if the classroom is being created from a virtual class\n    id?: string;\n    subject?: SubjectTypes;\n    grades?: string[];\n    period?: string;\n    // Defined if the classroom is created or updated with co-teachers\n    teachers?: string[];\n}\n\nexport interface IClassroomUpdateData extends Partial<IClassroomCreateData> {}\n\nexport enum ClassroomRole {\n    STUDENT = 'STUDENT',\n    TEACHER = 'TEACHER',\n}\n\nexport interface IRemoteClassroom {\n    /**\n     * The asset ID of the classroom.\n     */\n    assetId: string;\n    /**\n     * The class code for the classroom.  Used for generating invite links and LMS integration.\n     * @example '3R9RPQ'\n     */\n    classCode: string;\n    /**\n     * The unique id that represents the classroom.\n     * @example 'EFBF1A3F6567A3180A494138@AdobeOrg'\n     */\n    classId: string;\n    /**\n     * The name of the classroom.\n     */\n    className: string;\n    /**\n     * Username for the account that created this classroom.\n     */\n    createdBy: string;\n    /**\n     * The unix time the classroom was created. Note that it is in seconds and not milliseconds.\n     */\n    createdOn: number;\n    entityRef: IEntityRef;\n    /**\n     * Indicates if the classroom has been deleted.\n     */\n    deleted: boolean;\n    /**\n     * The list of grades associated with the classroom.\n     * @example [ 'K', '1' ]\n     */\n    grades: string[];\n    importedFrom?: IRemoteImportSource;\n    /**\n     * Contains the role of the member fetching the classroom.\n     */\n    memberRole: ClassroomMemberRole;\n    /**\n     * The period of the classroom.\n     * @example '1'\n     */\n    period: string;\n    /** True if the classroom is a virtual classroom */\n    isVirtual?: boolean;\n    /**\n     * The class status\n     * @example 'ACTIVE'\n     */\n    status: ClassroomStatus;\n    /**\n     * The class subject.\n     * @example 'math'\n     */\n    subject: SubjectTypes;\n    /**\n     * The class type\n     * @example 'UNRESTRICTED'\n     */\n    type: ClassroomType;\n    /**\n     * For SAM.js internal use only\n     * Due to the classroom ID changing when the classroom is migrated\n     * from a virtual to a real class, clients will NOT have access to\n     * the new instance of the classroom through their existing reference\n     * to the original virtual instance of the class.\n     *\n     * To support classroom workflow reattempts directly following the migration\n     * of the virtual class when the client is still referencing the class\n     * ID when it was virtual, the virtual instance of the class ID will persist\n     * on this session's migrated instance of the class.\n     */\n    virtualId?: string;\n}\n\nexport interface IRemoteBlockOrRemoveResponse {\n    apiSuccessResponse: BlockApiSuccessResponses;\n    httpStatus: string;\n}\n\nexport interface IRemoteMembership {\n    role: ClassroomMemberRole;\n    status: MembershipStatus;\n}\n\nexport enum BlockApiSuccessResponses {\n    REMOVE_STUDENT_SUCCESS = 'REMOVE_STUDENT_SUCCESS',\n    BLOCK_STUDENT_SUCCESS = 'BLOCK_STUDENT_SUCCESS',\n    UNBLOCK_STUDENT_SUCCESS = 'UNBLOCK_STUDENT_SUCCESS',\n    DELETE_DOMAIN_MAPPING_ACCEPTED = 'DELETE_DOMAIN_MAPPING_ACCEPTED',\n}\n\nexport enum MembershipStatus {\n    OWNER = 'OWNER',\n    ACTIVE = 'ACTIVE',\n    INACTIVE = 'INACTIVE',\n    INVITED = 'INVITED',\n    IN_REVIEW = 'IN_REVIEW',\n    DECLINED = 'DECLINED',\n    NOT_A_MEMBER = 'NOT_A_MEMBER',\n}\n\nexport enum CoTeacherEligibilityStatus {\n    ALLOWED = 'ALLOWED',\n    NOT_ALLOWED = 'NOT_ALLOWED'\n}\n\nexport enum CoTeacherIneligibilityReason {\n    ACCOUNT_NOT_FOUND = 'ACCOUNT_NOT_FOUND',\n    STUDENT_IN_CLASSROOM = 'STUDENT_IN_CLASSROOM',\n    TEACHER_IN_CLASSROOM = 'TEACHER_IN_CLASSROOM'\n}\n\nexport interface ICoTeacherEligibilityEntry {\n    email?: string;\n    userId?: string;\n    status: CoTeacherEligibilityStatus;\n    reason?: CoTeacherIneligibilityReason;\n}\n\nexport interface ICheckCoTeacherEligibilityOptions {\n    emails: string[];\n    classroomId?: string;\n}\n\nexport type GetClassroomBoardsOptions = (\n    {classroomCode?: never; classroomId: string;}\n    | { classroomCode: string; classroomId?: never}\n);\n\nexport type ValidateClassroomBoardNameForCreateOptions = Partial<GetClassroomBoardsOptions> & {\n    /** The name of the classroom board to validate */\n    name: string;\n}\n\nexport type ValidateClassroomBoardNameForUpdateOptions = GetClassroomBoardsOptions & {\n    /** The ID of the classroom board */\n    boardId: string;\n    /** The name of the classroom board to validate */\n    name: string;\n}\n\nexport type GetAssignmentBoardsOptions = RequiredStudentAssignmentFilterOptions;\n\nexport type CreateClassroomBoardOptions = Pick<CreateBoardOptions, 'name' | 'description' | 'posts'> & GetClassroomBoardsOptions\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport interface IClassroomMember {\n    classroomId: string;\n    computedKey: string;\n    userId: string;\n    firstName: string;\n    lastName: string;\n    email: string;\n    displayName: string;\n    role: ClassroomMemberRole;\n    membershipStatus: ClassroomMemberStatus;\n    inviteSource: ClassroomMemberInviteSource;\n}\n\nexport interface IRemoteClassroomMembers {\n    members: IClassroomMember[];\n    classroomId: string;\n}\n\nexport enum ClassroomMemberRole {\n    STUDENT = 'student',\n    TEACHER = 'teacher',\n    NONE = 'none',\n}\n\nexport enum ClassroomMemberStatus {\n    ACTIVE = 'ACTIVE',\n    DECLINED = 'DECLINED',\n    INACTIVE = 'INACTIVE',\n    INVITED = 'INVITED',\n    IN_REVIEW = 'IN_REVIEW',\n    NOT_A_MEMBER = 'NOT_A_MEMBER',\n    OWNER = 'OWNER',\n}\n\nexport enum ClassroomMemberInviteSource {\n    CLASSLINK = 'CLASSLINK',\n    CLEVER = 'CLEVER',\n    EMAIL = 'EMAIL',\n    GOOGLE_CLASSROOM = 'GOOGLE_CLASSROOM',\n    NONE = 'NONE',\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type Classroom from './Classroom';\n\nexport type ClassroomOrderField =\n    | 'name'\n    | 'created';\n\nconst OrderFieldToComparator: IComparatorMap<Classroom, ClassroomOrderField> = {\n    name(a: Classroom, b: Classroom): number {\n        return compareStrings(a.name, b.name);\n    },\n    created(a: Classroom, b: Classroom): number {\n        let value;\n        if (!a.created && !b.created) {\n            value  = 0;\n        } else if (!a.created) {\n            value = 1; // Undefined date should be sorted last in ascending order\n        } else if (!b.created) {\n            value = -1;\n        } else {\n            value = compareValues(a.created.getTime(), b.created.getTime());\n        }\n        if (value === 0) {\n            // Within the same created, sort by name\n            return compareStrings(a.name, b.name);\n        }\n        return value;\n    },\n};\n\nexport default class ClassroomOrder extends createItemOrderFactory(OrderFieldToComparator) implements SAM.ClassroomOrder {\n    static default = new ClassroomOrder('ascending', 'name');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IClassroomMember } from '../interface/ClassroomMemberModel';\nimport { ClassroomMemberRole } from '../interface/ClassroomMemberModel';\nimport { observable } from '../core/decorators';\nimport ItemBase from '../core/ItemBase';\nimport { ClassroomMemberStatus } from '../interface/ClassroomMemberModel';\nimport { ClassroomMemberInviteSource } from '../interface/ClassroomMemberModel';\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nexport default class ClassroomMember extends ItemBase {\n    private _classroomId: string = '';\n    private _displayName: string = '';\n    private _email: string = '';\n    private _firstName: string = '';\n    private _inviteSource: ClassroomMemberInviteSource = ClassroomMemberInviteSource.NONE;\n    private _lastName: string = '';\n    private _membershipStatus: ClassroomMemberStatus = ClassroomMemberStatus.NOT_A_MEMBER;\n    private _role: ClassroomMemberRole = ClassroomMemberRole.NONE;\n    private _userId: string = '';\n\n    @observable\n    get classroomId(): string {\n        return this._classroomId;\n    }\n\n    @observable\n    get displayName(): string {\n        return this._displayName;\n    }\n\n    @observable\n    get email(): string {\n        return this._email;\n    }\n\n    @observable\n    get firstName(): string {\n        return this._firstName;\n    }\n\n    @observable\n    get inviteSource(): ClassroomMemberInviteSource {\n        return this._inviteSource;\n    }\n\n    @observable\n    get lastName(): string {\n        return this._lastName;\n    }\n\n    @observable\n    get membershipStatus(): ClassroomMemberStatus {\n        return this._membershipStatus;\n    }\n\n    @observable\n    get role(): ClassroomMemberRole {\n        return this._role;\n    }\n\n    @observable\n    get userId(): string {\n        return this._userId;\n    }\n}\n\nexport const ClassroomMemberUpdater = new ItemUpdater<ClassroomMember, Partial<IClassroomMember>>({\n    localItemType: ClassroomMember,\n    // Note that ID of classroomMember is computed, and in the format of `{classroomId}-{role}`\n    remoteIdProperty: 'computedKey',\n    propertyUpdater: new PropertyUpdater({\n        _classroomId: { name: 'classroomId', format: 'string' },\n        _displayName: { name: 'displayName', format: 'string' },\n        _email: { name: 'email', format: 'string' },\n        _firstName: { name: 'firstName', format: 'string' },\n        _inviteSource: { name: 'inviteSource', format: 'string', choices: Object.values(ClassroomMemberInviteSource) },\n        _lastName: { name: 'lastName', format: 'string' },\n        _membershipStatus: { name: 'membershipStatus', format: 'string', choices: Object.values(ClassroomMemberStatus) },\n        _role: { name: 'role', format: 'string', choices: Object.values(ClassroomMemberRole) },\n        _userId: { name: 'userId', format: 'string' },\n    }),\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, createItemOrderFactory } from '../core/ItemOrder';\nimport type ClassroomMember from './ClassroomMember';\n\nexport type ClassroomMemberOrderField =\n    | 'name';\n\nconst OrderFieldToComparator: IComparatorMap<ClassroomMember, ClassroomMemberOrderField> = {\n    name(a: ClassroomMember, b: ClassroomMember): number {\n        return compareStrings(a.displayName, b.displayName);\n    },\n};\n\nexport default class ClassroomMemberOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new ClassroomMemberOrder('ascending', 'name');\n}\n","import type ClassroomMember from '../classroom-member/ClassroomMember';\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport { ClassroomMemberRole } from '../interface/ClassroomMemberModel';\n\nexport interface IClassroomMemberFilterOptions {\n    classroomId: string;\n    role: ClassroomMemberRole;\n}\n\n/**\n * A filter for classroom members\n *\n * Example usage, to get just a list of students back:\n *\n * classroom.members.getList(ClassroomMemberOrder.default, new ClassroomMemberFilter({ classroomId: classroom.id, role: 'student' }), { refreshTimeout: -1 });\n */\nexport default class ClassroomMemberFilter implements IExplicitFilter<ClassroomMember> {\n    public classroomId: string;\n    public role: ClassroomMemberRole;\n\n    constructor(options: Partial<IClassroomMemberFilterOptions>) {\n        this.classroomId = options.classroomId || '';\n        this.role = options.role || ClassroomMemberRole.NONE;\n    }\n\n    matches(item: ClassroomMember): boolean {\n        // Can return immediately if the classroomId doesn't match\n        if (this.classroomId !== item.classroomId) {\n            return false;\n        }\n\n        // If we have a role, we're only loading students OR teachers\n        if (this.role && this.role !== ClassroomMemberRole.NONE) {\n            return item.role === this.role;\n        }\n\n        // If we don't have a role, we're loading all members, so check against either student or teacher\n        return item.role === ClassroomMemberRole.STUDENT || item.role === ClassroomMemberRole.TEACHER;\n    }\n\n    /**\n     * This method determines the commonality between the already present filter (other)\n     * and the new filter to be applied (this). The point of this is to\n     * see if the new filter (this) can build some, all, or none of it's items\n     * from (other) filter.\n     *\n     * Subset: Means that ALL items for this filter can be built from other\n     * Disjoint: No items for this filter can be built from other.\n     * Unknown: Some items for this filter can be built from other.\n     *\n     * @note we should always determine disjoint cases first before other cases.\n     * @note this = NEW FILTER, other = EXISTING FILTER\n     *\n     * @param other The existing filter that we are getting the relation to.\n     * @returns { ItemFilterRelation }\n     */\n    getRelationToFilter(other: ClassroomMemberFilter): ItemFilterRelation {\n        // Consider disjoint cases before all others\n        // If classroomId is different, relation is disjoint\n        if (other.classroomId !== this.classroomId) {\n            return 'disjoint';\n        }\n\n        // If role is different, and neither is NONE, relation is disjoint\n        if (this.role !== other.role && this.role !== ClassroomMemberRole.NONE && other.role !== ClassroomMemberRole.NONE) {\n            return 'disjoint';\n        }\n\n        // If role and classroomId are the same, relation is subset\n        if (this.role === other.role) {\n            return 'subset';\n        }\n\n        // If other role is NONE, it means the filter we're checking against has loaded all members, so we can be sure that it's a subset as either teacher or student is contained in the other filter.\n        if (other.role === ClassroomMemberRole.NONE) {\n            return 'subset';\n        }\n\n        return 'unknown';\n    }\n\n    get hash(): string {\n        return `id=${this.classroomId}-${this.role}`;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { AssetLinks, RepositoryMetadata } from './RepositoryModel';\nimport type { IServiceLink, LinkRequirements } from './LinkUtils';\nimport { RelType } from './LinkUtils';\nimport type { IRemoteStudentAssignment } from './StudentAssignmentModel';\nimport type { Tutorial } from './TutorialModel';\n\nexport interface IAssignmentsIndexResponse {\n    _links: IAssignmentsIndexLinks\n}\n\nexport interface IAssignmentsIndexLinks {\n    [RelType.ASSIGNMENTS_COLLECTION]: IServiceLink,\n    [RelType.ASSIGNMENTS_CREATE]: IServiceLink,\n    [RelType.ASSIGNMENTS_PRIMARY]: IServiceLink,\n}\n\nexport const ASSIGNMENTS_INDEX_LINKS: LinkRequirements = {\n    [RelType.ASSIGNMENTS_COLLECTION]: [ 'classroomId' ],\n    [RelType.ASSIGNMENTS_CREATE]: [ 'classroomId' ],\n    [RelType.ASSIGNMENTS_PRIMARY]: [ 'assignmentId' ]\n};\n\nexport interface IAssignmentActions {\n    [RelType.ASSIGNMENTS_PRIMARY]: IServiceLink;\n    [RelType.ASSIGNMENTS_CODE]: IServiceLink,\n    [RelType.ASSIGNMENTS_ASSIGN]: IServiceLink;\n    [RelType.DISCARD]: IServiceLink;\n    [RelType.RESTORE]: IServiceLink;\n}\n\nexport type AssignmentLinks = AssetLinks & IAssignmentActions;\n\nexport enum AssignmentStatus {\n    DRAFT = 'DRAFT',\n    ASSIGNED = 'ASSIGNED',\n}\n\nexport interface AssignmentAdobeAssetMetadata {\n    'repo:assetId': string;\n}\n\n/** Model representing an assignment from the service */\nexport interface IRemoteAssignment extends IRemoteAssignmentAppMetadata, Pick<RepositoryMetadata,\n    'repo:assetId' | 'repo:createDate' | 'repo:state' | 'repo:name' | 'repo:path' | 'repo:createdBy' | 'repo:modifiedBy' | 'repo:repositoryId'\n> {\n    /** Student assignments */\n    'children': IRemoteStudentAssignment[];\n    /** Assignment links */\n    _links?: AssignmentLinks;\n    /** Classroom context */\n    'classroom:context': AssignmentAssetsContext;\n}\n\n/** Model representing an assignment info stored as appMetadata */\nexport interface IRemoteAssignmentAppMetadata {\n    /** Whether student can read each other's submission */\n    'assignment:canClassroomReadSubmissions': boolean;\n    /** Associated campaign ID */\n    'assignment:campaignId'?: string;\n    /** Associated classroom ID */\n    'assignment:classroomId': string;\n    /** Assignment creator */\n    'assignment:createdBy': string;\n    /** Instructions */\n    'assignment:instructions': string;\n    /** Due date */\n    'assignment:dueDate'?: string;\n    /** Status */\n    'assignment:status': string;\n    /** acceptable types of assignment task document: https://git.corp.adobe.com/Horizon/hz/blob/main/features/tasks/src/typings/TaskIDEnums.ts#L26 */\n    'assignment:tasks'?: string[];\n    /** Asset IDs of template files that students can use to start their assignment */\n    'assignment:templateIds'?: string[];\n    /** Asset ID of a guided activity as a starting point for the student's assignment */\n    'assignment:externalTemplateIds'?: string[];\n    /** A stringified list of @see {Tutorial} objects */\n    'assignment:externalTutorials'?: string;\n    /** Assignment code used for URLs/share with students */\n    'assignment:code': string;\n    /** Additional reference assets used to create the assignment */\n    'assignment:referenceIds'?: string[];\n}\n\nexport interface ExternalAsset {\n    content: Blob | string;\n    name: string;\n    mediaType?: string;\n}\n\nexport interface IAssignmentCreateData {\n    canClassroomReadSubmissions?: boolean;\n    campaignId?: string;\n    classroomId: string;\n    createdBy?: string;\n    dueDate?: Date;\n    externalTemplateIds?: string[],\n    instructions?: string;\n    name: string;\n    status?: AssignmentStatus;\n    tasks?: string[];\n    templateIds?: string[];\n    references?: (string | ExternalAsset)[];\n    externalTutorials?: Tutorial[];\n}\n\nexport interface IAssignmentUpdateData extends IAssignmentCreateData {}\n\nexport interface IAssignmentPatchData extends Partial<Pick<IAssignmentUpdateData,\n    | 'canClassroomReadSubmissions'\n    | 'instructions'\n    | 'dueDate'\n    | 'externalTemplateIds'\n    | 'externalTutorials'\n    | 'name'\n    | 'tasks'\n    | 'templateIds'\n    | 'status'>> {\n    referenceIds?: string[]\n}\n\nexport interface IAssignmentRemotePatchData extends Partial<Pick<IRemoteAssignment,\n    | 'assignment:canClassroomReadSubmissions'\n    | 'assignment:instructions'\n    | 'assignment:dueDate'\n    | 'assignment:externalTemplateIds'\n    | 'assignment:externalTutorials'\n    | 'assignment:templateIds'\n    | 'repo:name'\n    | 'assignment:tasks'\n    | 'assignment:status'\n    | 'assignment:referenceIds'>> {}\n\n/**\n * A mapping of fields from the local assignment model to the remote assignment model\n * This is the inverse of AssignmentUpdater.\n */\nexport const assignmentRemoteFieldMapping: Record<keyof IAssignmentPatchData, keyof IAssignmentRemotePatchData> = {\n    canClassroomReadSubmissions: 'assignment:canClassroomReadSubmissions',\n    instructions: 'assignment:instructions',\n    dueDate: 'assignment:dueDate',\n    externalTemplateIds: 'assignment:externalTemplateIds',\n    templateIds: 'assignment:templateIds',\n    name: 'repo:name',\n    tasks: 'assignment:tasks',\n    status: 'assignment:status',\n    referenceIds: 'assignment:referenceIds',\n    externalTutorials: 'assignment:externalTemplateIds'\n};\n\nexport interface IAssignmentsAppMetadata {\n    // not sure what would be the required/optional app metadata here, will update this later when we learn more\n    'assignment:rendition': Partial<IRemoteAssignment>;\n}\n\nexport type IAssignmentsOrderBy =\n  | 'repo:name'\n  | 'assignment:status'\n  | 'assignment:dueDate';\n\nexport interface IAssignmentsPageSpec {\n    start: number;\n    limit: number;\n    orderBy: string;\n    count: number;\n    total: number;\n}\n\nexport interface IAssignmentsLinks {\n    [RelType.ASSIGNMENTS_CREATE]: IServiceLink;\n    [RelType.ASSIGNMENTS_COLLECTION]: IServiceLink;\n}\n\nexport interface IAssignmentsResponse {\n    children: IRemoteAssignment[];\n    _page: IAssignmentsPageSpec;\n    _links: IAssignmentsLinks;\n}\n\nexport enum AssignmentSubmissionOwnershipEnums {\n    ANY = 'ANY',\n    NONE = 'NONE',\n    SELF = 'SELF'\n}\n\nexport type ClassroomAssetsContext = {\n    'classroom:classroomContext': {\n        'classroom:classroomAssetId': string;\n    },\n    // AssetId of a specific assignment folder (ie /content/assets/classrooms/{classOrgId}/assignments/{assignmentName})\n    'classroom:assignmentContext': {\n        'classroom:assignmentAssetId': string;\n    },\n    // AssetId of the top level assignments folder (ie /content/assets/classrooms/{classOrgId}/assignments)\n    // There is one situation where we don't have this field -- when we're getting a student assignment that has status NOT_STARTED. Can rely on it in all other cases.\n    'classroom:assignmentsContext'?: {\n        'classroom:assignmentsAssetId'?: string;\n    },\n    'assignment:materialsContext': {\n        'assignment:materialsAssetId': string;\n    },\n    'assignment:studentsContext': {\n        'assignment:studentsAssetId': string;\n    }\n}\n\nexport type AssignmentAssetsContext = Required<ClassroomAssetsContext>\n","import type { SAM } from '@ccx-public/component-types';\nimport { AssignmentStatus } from '../interface/AssignmentModel';\nimport type {\n    IComparatorMap } from '../core/ItemOrder';\nimport {\n    compareStrings,\n    compareValues,\n    createItemOrderFactory\n} from '../core/ItemOrder';\nimport type Assignment from './Assignment';\n\nexport type AssignmentOrderField = 'name' | 'dueDate' | 'status';\n\nconst StatusOrderValues = {\n    [AssignmentStatus.DRAFT]: 0,\n    [AssignmentStatus.ASSIGNED]: 1,\n};\n\nconst compareAssignmentNames =  (a: Assignment, b: Assignment) => {\n    return compareStrings(a.name || '', b.name || '');\n};\n\nconst OrderFieldToComparator: IComparatorMap<Assignment, AssignmentOrderField>\n  = {\n      name(a: Assignment, b: Assignment): number {\n          return compareAssignmentNames(a, b);\n      },\n      dueDate(a: Assignment, b: Assignment): number {\n          let value;\n          if (!a.dueDate && !b.dueDate) {\n              value  = 0;\n          } else if (!a.dueDate) {\n              value = 1; // Undefined date should be sorted last in ascending order\n          } else if (!b.dueDate) {\n              value = -1;\n          } else {\n              value = compareValues(a.dueDate.getTime(), b.dueDate.getTime());\n          }\n          if (value === 0) {\n              // Within the same dueDate, sort by name\n              return compareAssignmentNames(a, b);\n          }\n          return value;\n      },\n      status(a: Assignment, b: Assignment): number {\n          const value = compareValues(StatusOrderValues[a.status as AssignmentStatus], StatusOrderValues[b.status as AssignmentStatus]);\n          if (value === 0) {\n              // Within the same status, sort by name\n              return compareAssignmentNames(a, b);\n          }\n          return value;\n      }\n  };\n\nexport default class AssignmentOrder extends createItemOrderFactory(OrderFieldToComparator) implements SAM.AssignmentOrder {\n    static default = new AssignmentOrder('ascending', 'name');\n}\n","import type { AssignmentSubmissionOwnershipEnums } from '../interface/AssignmentModel';\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport type Assignment from './Assignment';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\n\nexport interface IAssignmentFilterOptions {\n    classroomId?: string;\n    campaignId?: string;\n    submissions?: AssignmentSubmissionOwnershipEnums;\n}\n\nexport default class AssignmentFilter implements IExplicitFilter<Assignment> {\n    public classroomId?: string;\n    public campaignId?: string;\n    public submissions?: AssignmentSubmissionOwnershipEnums | undefined;\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    public _monitoredFolder?: AdobeAsset;\n\n    /**\n     * @throws {SAMError} if both classroomId and campaignId are provided or neither are provided\n     * @package -- only for use in SAM.js\n     */\n    constructor(options: Partial<IAssignmentFilterOptions> = {}) {\n        this.classroomId = options.classroomId || '';\n        this.campaignId = options.campaignId || '';\n        // We don't have any use cases where we would filter by both classroomId and campaignId or neither\n        // so we throw an error if both are provided or neither are provided\n        if (this.campaignId && this.classroomId) {\n            throw SAMError.create(SAMErrorCode.UNSUPPORTED, 'Cannot filter by both campaignId and classroomId');\n        } else if (!this.campaignId && !this.classroomId) {\n            throw SAMError.create(SAMErrorCode.UNSUPPORTED, 'Must filter by either campaignId or classroomId');\n        }\n        this.submissions = options.submissions;\n    }\n\n    matches(item: Assignment): boolean {\n        if (!item.isAssignment) {\n            return false;\n        }\n        if (this.classroomId && item.classroomId !== this.classroomId) {\n            return false;\n        }\n        if (this.campaignId && item.campaignId !== this.campaignId) {\n            return false;\n        }\n        if (item.isDiscarded) {\n            return false;\n        }\n        return true;\n    }\n\n    getRelationToFilter(other: AssignmentFilter): ItemFilterRelation {\n        // Consider all subset cases first\n        if (this.classroomId && this.classroomId === other.classroomId) {\n            return 'subset';\n        } else if (this.campaignId && this.campaignId === other.campaignId) {\n            return 'subset';\n        } else {\n            return 'disjoint';\n        }\n    }\n\n    get hash(): string {\n        return `classroomId=${this.classroomId}&campaignId=${this.campaignId}`;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport {\n    getMultiValueFilterRelation,\n    type IExplicitFilter,\n    type ItemFilterRelation\n} from '../core/ItemFilter';\nimport type StudentAssignment from './StudentAssignment';\nimport type { StudentAssignmentStatus, StudentAssignmentOptionalParams } from '../interface/StudentAssignmentModel';\nimport { ALL_STATUSES } from '../interface/StudentAssignmentModel';\n\nexport default class StudentAssignmentFilter implements IExplicitFilter<StudentAssignment> {\n    public loadDocuments: boolean;\n    public status: StudentAssignmentStatus[];\n    private currentUserId?: string;\n\n    constructor(options: StudentAssignmentOptionalParams = {}) {\n        const { currentUserId, loadDocuments, status } = options;\n        this.loadDocuments = loadDocuments === undefined ? true : loadDocuments;\n        this.status = status && status.length > 0 ? status : ALL_STATUSES;\n        this.currentUserId = currentUserId;\n    }\n\n    matches(item: StudentAssignment): boolean {\n        // If we have items in the pool that extends beyond Self, then we filter to get only the assignments that currently logged in user submitted.\n        // NOT_STARTED assignments would not attach a student so it would not be the users assignment.\n        if (this.currentUserId && item.student.id !== this.currentUserId) {\n            return false;\n        }\n\n        if (!this.status.includes(item.status)) {\n            return false;\n        }\n\n        return true;\n    }\n\n    getRelationToFilter(other: StudentAssignmentFilter): ItemFilterRelation {\n        const statusRelation = getMultiValueFilterRelation(this.status, other.status);\n        // --- Handle all the 'disjoint' cases first ---\n\n        if (statusRelation === 'disjoint') {\n            return 'disjoint';\n        }\n        // NOTE: There are no disjoint cases for loadDocuments yet.\n\n        // --- Handle all 'unknown' cases next ---\n        // This has some statuses that are not included with other, but we've ruled out disjoint, so there\n        // could be more matches on the server\n        if (statusRelation === 'unknown') {\n            return 'unknown';\n        }\n        // If this wants documents and other does not, then the other might have assignments, but it'll\n        // still need to fetch documents.\n        if (this.loadDocuments && !other.loadDocuments) {\n            return 'unknown';\n        }\n        // This wants all owners, other only has current user\n        if (!this.currentUserId && other.currentUserId) {\n            return 'unknown';\n        }\n\n        // --- All 'disjoint' and 'unknown' cases are handled above, so it can only be 'subset'  ---\n        return 'subset';\n    }\n\n    get hash(): string {\n        return `status=${this.status.join()}&loadDocuments=${this.loadDocuments}${this.currentUserId ? `&currentUserId=${this.currentUserId}` : ''}`;\n    }\n}\n\n","import type { SAM } from '@ccx-public/component-types';\nimport type {\n    IComparatorMap } from '../core/ItemOrder';\nimport {\n    compareValues,\n    createItemOrderFactory\n} from '../core/ItemOrder';\nimport { StudentAssignmentStatus } from '../interface/StudentAssignmentModel';\nimport type StudentAssignment from './StudentAssignment';\n\nexport type StudentAssignmentOrderField = 'studentDisplayName' | 'submissionDate' | 'status';\n\n// Prioritize assignments that require teacher attention: SUBMITTED, IN_PROGRESS, RETURNED, NOT_STARTED\nconst StatusOrderValues = {\n    [StudentAssignmentStatus.SUBMITTED]: 0,\n    [StudentAssignmentStatus.IN_PROGRESS]: 1,\n    [StudentAssignmentStatus.RETURNED]: 2,\n    [StudentAssignmentStatus.NOT_STARTED]: 3,\n};\n\nconst compareStudentDisplayName =  (a: StudentAssignment, b: StudentAssignment) => {\n    return compareValues(a.student.displayName || '', b.student.displayName || '');\n};\n\nconst OrderFieldToComparator: IComparatorMap<StudentAssignment, StudentAssignmentOrderField>\n  = {\n      studentDisplayName(a: StudentAssignment, b: StudentAssignment): number {\n          return compareStudentDisplayName(a, b);\n      },\n      submissionDate(a: StudentAssignment, b: StudentAssignment): number {\n          let value;\n          if (!a.submissionDate && !b.submissionDate) {\n              value  = 0;\n          } else if (!a.submissionDate) {\n              value = 1; // Undefined date should be sorted last in ascending order\n          } else if (!b.submissionDate) {\n              value = -1;\n          } else {\n              value = compareValues(a.submissionDate.getTime(), b.submissionDate.getTime());\n          }\n          if (value === 0) {\n              // If equal submission date (probably both are undefined), sort by student display name\n              return compareStudentDisplayName(a, b);\n          }\n          return value;\n      },\n      status(a: StudentAssignment, b: StudentAssignment): number {\n          const value = compareValues(StatusOrderValues[a.status], StatusOrderValues[b.status]);\n          if (value === 0) {\n              // Within the same status, sort by student display name\n              return compareStudentDisplayName(a, b);\n          }\n          return value;\n      }\n  };\n\nexport default class StudentAssignmentOrder extends createItemOrderFactory(\n    OrderFieldToComparator\n) implements SAM.StudentAssignmentOrder {\n    static default = new StudentAssignmentOrder('ascending', 'studentDisplayName');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport AppMetadataResource from '../assets/AppMetadataResource';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type StudentAssignmentFile from './StudentAssignmentFile';\nimport { StudentAssignmentFileUpdater } from './StudentAssignmentFile';\n\nexport default class StudentAssignmentFileAppMetadataResource extends AppMetadataResource {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _parent: StudentAssignmentFile,\n    ) {\n        super(_core, _parent);\n    }\n\n    protected async _loadData() {\n        // Directly fetches app metadata from R-API since there is a chance app metadata\n        // has been fetched external to Hume, such as the case the StudentAssignmentFile was fetched\n        // with AssetContext.getAssetWithCloudID.\n        await super._loadData();\n        // Updates the StudentAssignmentFile to include the latest app metadata\n        const session = this._core._getAssetPool().createMutationSession<StudentAssignmentFile>();\n        StudentAssignmentFileUpdater.updateLocalItem(session, this._parent, this.data);\n        session.commit();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport { observable } from '../core/decorators';\nimport type { AdobeAssetUpdaterMetadata } from '../assets/AdobeAsset';\nimport AdobeAsset from '../assets/AdobeAsset';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { IPatchStudentAssignmentFileData, IRemoteStudentAssignmentFileMetadataWithComputedValues } from '../interface/StudentAssignmentFileModel';\nimport type { Tutorial } from '../interface/TutorialModel';\nimport type { IItemSourceConfig } from '../core/ItemList';\nimport StudentAssignmentFileAppMetadataResource from './StudentAssignmentFileAppMetadataResource';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { AssetLinks } from '../interface/RepositoryModel';\nimport { AssetClassChoices } from '../interface/RepositoryModel';\nimport type { LinkReference } from '../links/AssetLink';\n\nexport type StudentAssignmentFileConfig = IItemSourceConfig<StudentAssignmentFile>;\n\n/**\n * Represents a file that is part of a student assignment.\n */\nexport default class StudentAssignmentFile extends AdobeAsset implements SAM.StudentAssignmentFile {\n    private _studentAssignmentId: string = '';\n    private _parentAssignmentId: string = '';\n    private _parentClassroomId: string = '';\n    /**\n     * @TODO_Deprecation will be marked as deprecated once all SAM clients\n     * have migrated over to linking using sourceAsset.\n     */\n    private _sourceAssets: string[] = [];\n    private _sourceAsset?: LinkReference;\n    private _sourceTasks: string[] = [];\n    private _sourceTutorials: Partial<Tutorial>[] = [];\n    private _studentAssignmentFileAppMetadata: StudentAssignmentFileAppMetadataResource;\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        id: string,\n        metadata?: {\n            links?: AssetLinks;\n        }\n    ) {\n        super(_core, id, metadata);\n        this._studentAssignmentFileAppMetadata = new StudentAssignmentFileAppMetadataResource(_core, this);\n        this._needsRepoMetadata = true;\n    }\n\n    @observable\n    get isChildOfStudentAssignment(): boolean {\n        return true;\n    }\n\n    @observable\n    get studentAssignmentId(): string {\n        return this._studentAssignmentId;\n    }\n\n    /**\n     * Overrides AdobeAsset instance of parentStudentAssignmentId.\n     * Equivalent to studentAssignmentId.\n     * */\n    @observable\n    get parentStudentAssignmentId(): string {\n        return this._studentAssignmentId || super.parentStudentAssignmentId || '';\n    }\n\n    /**\n     * Overrides AdobeAsset instance of parentAssignmentID.\n     * */\n    @observable\n    get parentAssignmentID(): string {\n        return this._parentAssignmentId || super.parentAssignmentID || '';\n    }\n\n    /**\n     * Overrides AdobeAsset instance of isChildOfAssignment.\n     * */\n    @observable\n    get isChildOfAssignment(): boolean {\n        return true;\n    }\n\n    /**\n     * Overrides AdobeAsset instance of isChildOfClassroom.\n     * */\n    @observable\n    get isChildOfClassroom(): boolean {\n        return true;\n    }\n\n    /**\n     * Overrides AdobeAsset instance of parentClassroomId.\n     * */\n    @observable\n    get parentClassroomId(): string | undefined {\n        return this._parentClassroomId  || super.parentClassroomId;\n    }\n\n    /**\n     * Overrides AdobeAsset instance of isChildOfAssignmentMaterials.\n     * */\n    @observable\n    get isChildOfAssignmentMaterials(): boolean {\n        return false;\n    }\n\n    /**\n     * A link to the asset that this file was copied from.\n     * Undefined if sourceAssets is set instead OR if this file\n     * was NOT copied from an asset\n     */\n    @observable\n    get sourceAsset(): LinkReference | undefined {\n        return this._sourceAsset;\n    }\n\n    /**\n     * Use sourceAsset over sourceAssets if sourceAsset is defined\n     * to access the link to the file's source asset.\n     *\n     * @TODO_Deprecation will be marked as deprecated once all SAM clients\n     * have migrated over to linking using sourceAsset.\n     */\n    @observable\n    get sourceAssets(): string[] | undefined {\n        return this._sourceAssets;\n    }\n\n    @observable\n    get sourceTasks(): string[] | undefined {\n        return this._sourceTasks;\n    }\n\n    @observable\n    get sourceTutorials(): Partial<Tutorial>[] | undefined {\n        return this._sourceTutorials;\n    }\n\n    @observable\n    get appMetadata(): StudentAssignmentFileAppMetadataResource {\n        return this._studentAssignmentFileAppMetadata;\n    }\n\n    /**\n     * Updates a StudentAssignmentFile with new metadata.\n     *\n     * @throws {Error} Incorrect parameters: sourceAsset, sourceTasks, or sourceTutorials parameter required\n     *\n     * @example <caption>Update a StudentAssignmentFile's sourceAsset</caption>\n     * await studentAssignmentFile.update({ sourceAsset: {'repo:assetId': 'urn:mock-id'} });\n     */\n    async update({ sourceAsset, sourceAssets, sourceTasks, sourceTutorials }: IPatchStudentAssignmentFileData): Promise<StudentAssignmentFile> {\n        if (!sourceAsset && !sourceAssets && !sourceTasks && !sourceTutorials) {\n            throw Error('Incorrect parameters: sourceAsset, sourceTasks, or sourceTutorials parameter required');\n        }\n\n        await this._core.classroomContext.updateStudentAssignmentFile(\n            this,\n            {\n                sourceAsset,\n                sourceAssets,\n                sourceTasks,\n                sourceTutorials\n            },\n        );\n\n        return this;\n    }\n}\n\nexport const StudentAssignmentFileUpdater = new ItemUpdater<StudentAssignmentFile, Partial<IRemoteStudentAssignmentFileMetadataWithComputedValues | AdobeAssetUpdaterMetadata>>({\n    localItemType: StudentAssignmentFile,\n    remoteIdProperty: 'repo:assetId',\n    propertyUpdater: new PropertyUpdater({\n        _repositoryID: 'repo:repositoryId',\n        _name: 'repo:name',\n        _path: 'repo:path',\n        _type: 'dc:format',\n        _assetClass: { name: 'repo:assetClass', choices: AssetClassChoices },\n        _created: { name: 'repo:createDate', format: 'date' },\n        _modified: { name: 'repo:modifyDate', format: 'date' },\n        _createdBy: 'repo:createdBy',\n        _modifiedBy: 'repo:modifiedBy',\n        __links: { name: '_links', format: 'object' },\n        _parentAssignmentId: { name: 'computedAssignmentId', format: 'string' },\n        _parentClassroomId: { name: 'computedClassroomAssetId', format: 'string' },\n        _studentAssignmentId: { name: 'computedStudentAssignmentId', format: 'string' },\n        _sourceAsset: { name: 'assignment:sourceAsset', format: 'object' },\n        /**\n         * @TODO_Deprecation will be marked as deprecated once all SAM clients\n         * have migrated over to linking using sourceAsset.\n         */\n        _sourceAssets: { isArray: true, name: 'assignment:sourceAssets', format: 'string' },\n        _sourceTasks: { isArray: true, name: 'assignment:sourceTasks', format: 'string' },\n        _sourceTutorials: { isArray: true, name: 'assignment:sourceTutorials', format: 'object' },\n    })\n});\n","import type AdobeAsset from '../assets/AdobeAsset';\nimport { createItemOrderFactory } from '../core/ItemOrder';\nimport { compareValues } from '../core/ItemOrder';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport type StudentAssignmentFile from './StudentAssignmentFile';\n\nexport type StudentAssignmentFileOrderField = 'modified' | 'name' | 'created';\n\nconst OrderFieldToComparator: IComparatorMap<StudentAssignmentFile, StudentAssignmentFileOrderField> = {\n    modified(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.modified, b.modified);\n    },\n    name(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.name, b.name);\n    },\n    created(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.created, b.created);\n    },\n};\n\nexport default class StudentAssignmentFileOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new StudentAssignmentFileOrder('descending', 'modified');\n}\n","import type AdobeAsset from '../assets/AdobeAsset';\nimport AdobeAssetFilter from '../assets/AdobeAssetFilter';\n\n/**\n * This file and filter may not be needed in the future.\n * @deprecated This can be removed with ClassroomContext.getStudentAssignmentFiles(). Will be removed in ACPCEDU-3305.\n */\n// NOTE: This is used as an implicit filter in StudentAssignment.files, and internally as an explicit filter in\n// ClassroomContext.getStudentAssignmentFiles(). In the latter case, it is used to filter AdobeAsset.children()\n// so it must extend AdobeAssetFilter for type-checking purposes, even though none of the features of\n// AdobeAssetFilter are used. This is preferable to allowing AdobeAsset.children take StudentAssignmentFilesListFilter\n// as an explicit filter, as it shouldn't be part of the public interface.\nexport default class StudentAssignmentFilesListFilter extends AdobeAssetFilter {\n    matches(item: AdobeAsset): boolean {\n        // Note: not calling super here, because this is only needed for the internal case\n        // of using StudentAssignmentFilesListFilter as the explicit filter in\n        // ClassroomContext.getStudentAssignmentFiles()\n        return item.isChildOfStudentAssignment;\n    }\n}\n","import { isAssetAWebsiteTemplate } from '../utils/classroomUtils';\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport { FOLDER_TYPE } from '../interface/AssetInterface';\nimport type StudentAssignmentFile from './StudentAssignmentFile';\n\n/**\n * @deprecated further filtering of files is not supported at this time\n */\nexport interface StudentAssignmentFileFilterOptions {\n    /**\n     * @deprecated This should only be used when filtering StudentAssignments, not StudentAssignmentFiles.\n     * Regardless of whether this is true or false, files will be fetched for given StudentAssignment\n     * This property will be removed on or after 2025-7-1 in ACPCEDU-3393\n     */\n    loadDocuments?: boolean;\n}\n\nexport default class StudentAssignmentFileFilter implements IExplicitFilter<StudentAssignmentFile> {\n    /**\n     * @deprecated loadDocuments is not applicable at the StudentAssignmentFile-level. It only applies to StudentAssignments.\n     * This property will be removed on or after 2025-7-1 in ACPCEDU-3393\n     */\n    public loadDocuments: boolean;\n\n    /**\n     *\n     * @param studentAssignmentId The ID of the StudentAssignment that the files returned are associated with\n     * @param options Deprecated, further filtering of files is not supported at this time. This argument will be removed on or after 2025-7-1 in ACPCEDU-3393\n     */\n    constructor(\n        public studentAssignmentId: string,\n        options?: StudentAssignmentFileFilterOptions\n    ) {\n        this.loadDocuments = options?.loadDocuments ?? true;\n    }\n\n    matches(item: StudentAssignmentFile): boolean {\n        /**\n         * Assets that are StudentAssignmentFiles may start out cached\n         * as an AdobeAsset when the asset initially exists outside EDU assets.\n         * Therefore this checks for SAFs using attributes that are also available through\n         * the AdobeAsset interface.\n         *\n         * [ACPCEDU-3290] will introduce a longer-term approach for handling this behavior\n         * to support other/future cases where the asset type changes over time\n         * */\n\n        return item.isChildOfStudentAssignment === true\n            && item.studentAssignmentId === this.studentAssignmentId\n            && !item.isFolder\n            && item.mediaType !== FOLDER_TYPE // [ACPCEDU-3156]: Can be removed once hume is returning repo:assetClass\n            && !isAssetAWebsiteTemplate(item);\n    }\n\n    getRelationToFilter(other: StudentAssignmentFileFilter): ItemFilterRelation {\n        if (this.loadDocuments !== other.loadDocuments) {\n            return 'disjoint';\n        }\n\n        return this.studentAssignmentId === other.studentAssignmentId\n            ? 'subset' : 'disjoint';\n    }\n\n    get hash(): string {\n        return `studentAssignmentId=${this.studentAssignmentId}&loadDocuments=${this.loadDocuments}`;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../../src/core/SAMError';\n\n/**\n * Returns the keys of an enum that are not numbers.\n *\n * @param e - The enum to get the keys of.\n * @returns The keys of the enum that are not numbers.\n */\nfunction enumKeys<E extends object>(e: E): (keyof E)[] {\n    return Object\n        .keys(e)\n        .filter(k => isNaN(Number(k))) as (keyof E)[];\n}\n\n/**\n * Creates a bi-directional map between two enums.\n *\n * @typeParam A - The \"local\" enum.\n * @typeParam B - The \"remote\" enum.\n * @typeParam TPair - The type of the array of pairs of values from the two enums.\n *\n * @param pairs - An array of pairs of values from the two enums.\n * @returns An object with methods to convert between the two enums.\n */\nexport function enumMap<\n    TEnumA extends Record<string, unknown>,\n    TEnumB extends Record<string, unknown>,\n    TValueA extends TEnumA[keyof TEnumA],\n    TValueB extends TEnumB[keyof TEnumB]\n>(\n    enumA: TEnumA,\n    enumB: TEnumB,\n    entries: ReadonlyArray<[TValueA, TValueB]>\n): {\n        toB(value: TValueA): TValueB;\n        toA(value: TValueB): TValueA;\n    } {\n    // Gather the enum keys as the values to work with from the two enums.\n    const valuesA = enumKeys(enumA).map(k => enumA[k]);\n    const valuesB = enumKeys(enumB).map(k => enumB[k]);\n\n    // The mapping must cover every value exactly once or there is likely a mismatch.\n    if (entries.length !== valuesA.length || entries.length !== valuesB.length) {\n        throw SAMError.create(SAMErrorCode.INTERNAL_ERROR,\n            `Enum-to-enum map must have exactly ${valuesA.length} entries, got ${entries.length}`\n        );\n    }\n\n    const aToB = new Map<TValueA, TValueB>();\n    const bToA = new Map<TValueB, TValueA>();\n\n    // Create the forward and reverse mappings, keeping track of which values have been seen to\n    // catch duplicates.\n    for (const [ valueA, valueB ] of entries) {\n        if (!valuesA.includes(valueA)) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR,\n                `Value ${valueA} not in enum A`\n            );\n        }\n        if (!valuesB.includes(valueB)) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR,\n                `Value ${valueB} not in enum B`\n            );\n        }\n        if (aToB.has(valueA)) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR,\n                `Duplicate mapping for A value ${valueA}`\n            );\n        }\n        if (bToA.has(valueB)) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR,\n                `Duplicate mapping for B value ${valueB}`\n            );\n        }\n\n        aToB.set(valueA, valueB);  // Map A to B.\n        bToA.set(valueB, valueA);  // Map B to A.\n    }\n\n    return {\n        toB(value: TValueA): TValueB {\n            const valueB = aToB.get(value);\n            if (valueB === undefined) {\n                throw SAMError.create(SAMErrorCode.INTERNAL_ERROR,\n                    `No B-value mapped for A value ${value}`\n                );\n            }\n            return valueB;\n        },\n        toA(value: TValueB): TValueA {\n            const valueA = bToA.get(value);\n            if (valueA === undefined) {\n                throw SAMError.create(SAMErrorCode.INTERNAL_ERROR,\n                    `No A-value mapped for B value ${value}`\n                );\n            }\n            return valueA;\n        }\n    };\n}\n","/*************************************************************************\n   *\n   * ADOBE CONFIDENTIAL\n   * ___________________\n   *\n   *  Copyright 2025 Adobe Systems Incorporated\n   *  All Rights Reserved.\n   *\n   * NOTICE:  All information contained herein is, and remains\n   * the property of Adobe Systems Incorporated and its suppliers,\n   * if any.  The intellectual and technical concepts contained\n   * herein are proprietary to Adobe Systems Incorporated and its\n   * suppliers and are protected by trade secret or copyright law.\n   * Dissemination of this information or reproduction of this material\n   * is strictly forbidden unless prior written permission is obtained\n   * from Adobe Systems Incorporated.\n   **************************************************************************/\n\nimport type RequiredProps from '../utils/RequiredProps';\nimport type { AssetLinks, RepositoryMetadata } from './RepositoryModel';\nimport type { LinkRequirements, IServiceLink } from './LinkUtils';\nimport { RelType } from './LinkUtils';\nimport type { LinkReference } from '../links/AssetLink';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport type { BoardOrderField } from '../boards/BoardOrder';\nimport { enumMap } from '@sam-js-src/utils/enumMap';\nimport type { PostOrderField } from '@sam-js-src/boards/PostOrder';\n\nexport type BoardLinks = AssetLinks & IBoardActions;\n\nexport interface BoardContext {\n    baseAssetId: string;\n    boardsAssetId: string;\n}\n\nexport enum BoardMemberRole {\n    OWNER = 'OWNER',\n    POSTER = 'POSTER',\n    VIEWER = 'VIEWER',\n    UNKNOWN = 'UNKNOWN',\n}\n\n/** Model representing an assignment from the service */\nexport interface RemoteBoard extends Pick<RepositoryMetadata,\n    'repo:assetId' | 'repo:createDate' | 'repo:state' | 'repo:name' | 'repo:createdBy' | 'repo:modifiedBy' | 'repo:modifyDate' | 'dc:format'\n> {\n    'memberRole': BoardMemberRole;\n    /** Board context */\n    'board:context': BoardContext;\n    /** Board description */\n    'dc:description': string;\n    /** Remote post data in the board */\n    posts?: (RemoteTextPost | RemoteAssetLinkPost)[];\n    /** Board links */\n    _links?: BoardLinks;\n    /** The schema version of the board */\n    'board#version': string;\n    /** The source board */\n    'board:sourceBoard'?: RemoteSourceBoardInfo;\n    /** The published board */\n    'board:publishedBoard'?: RemotePublishedBoardInfo;\n}\n\ninterface PostData {\n    /* Post name */\n    name?: string;\n    /* Post description */\n    description?: string;\n    /* Post type */\n    type: PostType;\n    userId?: string;\n}\n\nexport enum PostType {\n    Text = 'text',\n    AssetLink = 'assetLink'\n}\n\nexport interface AddTextPostOptions extends PostData {\n    /* Text content */\n    text: string;\n    type: PostType.Text;\n}\n\nexport type UploadFileOptions = {\n    /** The blob to upload */\n    blob: Blob;\n    /** The name of the file */\n    fileName: string;\n    /** The parent asset ID of the file */\n    parentAssetId?: string;\n    /** The media type of the file */\n    mediaType?: string;\n}\n\nexport interface AddAssetLinkPostOptions extends PostData, Partial<UploadFileOptions> {\n    /* Asset ID of the underlying asset */\n    assetId?: string;\n    type: PostType.AssetLink;\n}\n\nexport type AddBoardPostOptions = AddTextPostOptions | AddAssetLinkPostOptions;\n\n/** This is meant for BoardContext.addPost() */\nexport type AddPostOptions = AddBoardPostOptions & {\n    /* Board ID where post is added */\n    boardId: string;\n}\n\nexport type RemovePostOptions = {\n    boardId: string;\n    postId: string;\n}\n\nexport type UpdateBoardNameOptions = {\n    name: string;\n}\n\nexport interface RemotePost {\n    id: string;\n    type: PostRemoteType;\n    name: string;\n    created?: string;\n    modified?: string;\n    'board#postDescription'?: string;\n    postedBy?: RemotePostOwner;\n}\n\nexport interface AddPostValuePayload extends Omit<RemotePost, 'id' | 'postedBy' | 'name'> {\n    name?: string; // Name is not required by the API on Post creation\n    userId?: string; // userId is only required when creating a Board with posts, but not when updating an existing Board with a new post\n}\n\nexport interface RemoteAssetLinkPost extends RemotePost {\n    link: ResourceReference;\n}\n\nexport interface RemoteTextPost extends RemotePost {\n    'board#postText': string;\n}\n\nexport enum BoardType {\n    CLASSROOM = 'classroom',\n}\n\nexport interface CreateBoardOptions {\n    /** The name of the board */\n    name: string;\n    /** The parent asset ID of the board */\n    baseAssetId: string;\n    /** The description of the board */\n    description?: string;\n    /** The type of the board */\n    type: BoardType;\n    /** Additional data for the board */\n    additionalData?: Record<string, string | number>;\n    /** Posts to add to the board */\n    posts?: AddBoardPostOptions[];\n    /**\n     * If true the board asset will be created in the base asset's directory. If false then a \"boards\" directory\n     * will be created in the base asset's directory if it does not exist, and the new board asset will be placed\n     * in that directory. Defaults to false.\n     */\n    shouldCreateDirectlyInBaseAsset?: boolean;\n    /**\n     * If true the board name will be checked for duplicates. If false then the board name will not be checked for duplicates.\n     * Defaults to true.\n     */\n    shouldCheckForDuplicateName?: boolean;\n}\n\nexport type UpdatePostOptions = Pick<PostData, 'description'> & {\n    /** The ID of the post to update */\n    id: string;\n};\n\nexport type UpdateBoardPostOptions = UpdatePostOptions & {\n    /** The ID of the board that the post belongs to */\n    boardId: string;\n}\n\nexport interface UpdateBoardOptions extends Pick<CreateBoardOptions, 'description'> {\n    /** The ID of the board to update */\n    boardId: string;\n    /** The display name to update on the board */\n    displayName?: string;\n    /** The posts to add to the board */\n    postsToAdd?: AddBoardPostOptions[];\n    /** The posts to remove from the board */\n    postsToRemove?: string[];\n    /** The posts to update */\n    postsToUpdate?: UpdatePostOptions[];\n}\n\nexport interface PostRemoteDataWithComputedValues {\n    computedBoardId: string;\n}\n\nexport interface AssetLinkPostRemoteData extends RemoteAssetLinkPost, PostRemoteDataWithComputedValues {}\n\nexport interface TextPostRemoteData extends RemoteTextPost, PostRemoteDataWithComputedValues {}\n\nexport interface ChangeContext {\n    userId: string;\n    deviceId: string;\n    device: string;\n    app: string;\n    time?: number;\n}\n\nexport type ResourceReference = RequiredProps<LinkReference, 'repo:assetId' | 'dc:format'> & {\n    /** The public URL of the linked asset. Only available if it's an asset link post of a public board. */\n    'board#postPublicUrl'?: string;\n};\n\nexport const BOARDS_REQUIRED_INDEX_LINKS: LinkRequirements = {\n    [RelType.BOARDS_PRIMARY]: [ 'boardId' ]\n};\n\nexport interface BoardsIndexLinks {\n    [RelType.BOARDS_COLLECTION]: IServiceLink,\n    [RelType.BOARDS_CREATE]: IServiceLink,\n    [RelType.BOARDS_PRIMARY]: IServiceLink,\n}\n\nexport interface IBoardActions {\n    [RelType.BOARDS_PRIMARY]: IServiceLink;\n    [RelType.BOARDS_DISCARD]: IServiceLink;\n    [RelType.BOARDS_PUBLISH]: IServiceLink;\n    [RelType.BOARDS_UNPUBLISH]: IServiceLink;\n}\n\nexport interface BoardsIndexResponse {\n    _links: BoardsIndexLinks\n}\n\nexport enum PostRemoteType {\n    TEXT = 'application/vnd.adobe.post.text+dcx',\n    ASSET_LINK = 'application/vnd.adobe.post.assetlink+dcx',\n}\n\n// Source of truth for the mapping between PostType and PostRemoteType.\nexport const PostTypeMap = enumMap(\n    PostType,\n    PostRemoteType,\n    [\n        [ PostType.Text, PostRemoteType.TEXT ],\n        [ PostType.AssetLink, PostRemoteType.ASSET_LINK ],\n    ]\n);\n\nexport interface RemotePostOwner {\n    userId?: string;\n    displayName?: string;\n    email?: string;\n    firstName?: string;\n    lastName?: string;\n    images?: Record<string, string>;\n}\n\nexport type BoardUpdateOptions = Omit<UpdateBoardOptions, 'boardId'>;\n\nexport interface BoardOrderOptions {\n    direction: IOrderDirection;\n    field: BoardOrderField;\n}\n\nexport interface CreateBoardPayload {\n    'repo:name': string;\n    'dc:description'?: string;\n    'board#type': string;\n    additionalMetadata?: Record<string, string | number>;\n    posts?: AddPostValuePayload[];\n}\n\nexport interface GetBoardsResponse {\n    children: RemoteBoard[];\n    _page: {\n        count: number;\n    };\n}\n\nexport type GetBoardsOptions = {\n    /** The base asset ID to fetch the boards from */\n    baseAssetId: string;\n    /**\n     * If true the boards will be fetched in the base asset's directory. If false then it will fetch boards from the \"boards\" directory\n     * in the base asset's directory. Defaults to false.\n     */\n    shouldGetDirectlyInBaseAsset?: boolean;\n}\nexport type ValidateBoardNameOptions = {\n    /** The name to validate */\n    name: string;\n    /** The base asset ID of the board */\n    baseAssetId?: string;\n    /** The board ID of the board to update */\n    boardId?: string;\n    /**\n     * If true the board assets will be fetched in the base asset's directory to check against. If false then it will fetch boards from the \"boards\" directory\n     * in the base asset's directory. Defaults to false.\n     */\n    shouldValidateDirectlyInBaseAsset?: boolean;\n}\n\nexport type ValidateBoardNameForCreateOptions = Pick<ValidateBoardNameOptions, 'name' | 'baseAssetId' | 'shouldValidateDirectlyInBaseAsset'>;\n\nexport type ValidateBoardNameForUpdateOptions = Pick<ValidateBoardNameOptions, 'name' | 'shouldValidateDirectlyInBaseAsset'> & {\n    /** The base asset ID of the board */\n    baseAssetId: string;\n    /** The board ID of the board to update */\n    boardId: string;\n}\n\nexport type AssetLinkPostDetails = {\n    /** The media type of the linked asset */\n    mediaType: string;\n    /** The ID of the linked asset */\n    assetId: string;\n    /** The public URL of the linked asset. Only available if it's an asset link post of a public board. */\n    publicUrl?: string;\n}\n\nexport interface GetPostByBoardAndPostIdOptions {\n    /** The ID of the board to get the post from */\n    boardId: string;\n    /** The ID of the post to get */\n    postId: string;\n}\n\nexport const MAX_POST_FILE_NAME_LENGTH = 240;\n\nexport interface PublishedBoardInfo {\n    /** The asset ID of the published board */\n    boardId: string;\n    /** Whether to show user names. Defaults to false. */\n    showPosterName: boolean;\n}\n\nexport interface SourceBoardInfo {\n    /** The asset ID of the source board */\n    boardId: string;\n    /** The published version number */\n    publishedVersion: number;\n}\n\nexport interface RemotePublishedBoardInfo {\n    /** The asset ID of the published board */\n    'repo:assetId': string;\n    /** Whether to show user names */\n    'board:showPosterName'?: boolean;\n}\n\nexport interface RemoteSourceBoardInfo {\n    /** The asset ID of the source board */\n    'repo:assetId': string;\n    /** The published version number */\n    'repo:version': number;\n}\n\nexport interface PublishOptions {\n    /** The name of the published board. Asset name limit is 1-255 characters (inclusive) */\n    boardTitle?: string;\n    /** The subtitle of the published board */\n    boardSubTitle?: string;\n    /** Whether to show user names. If not provided, the service will default to false. */\n    showPosterName?: boolean;\n}\n\nexport interface PublishBoardOptions extends PublishOptions {\n    /** The ID of the board to publish */\n    boardId: string;\n}\n\nexport interface PublishBoardInterfaceOptions extends PublishBoardOptions {\n    /** The links of the board */\n    links: BoardLinks;\n}\n\nexport interface PostOrderOptions {\n    direction: IOrderDirection;\n    field: PostOrderField;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type { PostConfig } from './PostSource';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type Board from './Board';\n\n\nexport default class PostListLoader implements IItemLoader<PostConfig> {\n    constructor(private _core: ISAMCorePrivate, private _board: Board) {}\n\n    async loadPage(options: IItemLoaderOptions<PostConfig>): Promise<ILoadedPage<PostConfig>> {\n        return await this._loadPage(options);\n    }\n\n    /** @note api does not support pagination */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    private async _loadPage(options: IItemLoaderOptions<PostConfig>): Promise<ILoadedPage<PostConfig>> {\n\n        const boardContext = await this._core.getBoardContext();\n        const board = await boardContext.getBoardById(this._board.id);\n        const posts = board._postPool.toArray();\n\n        return {\n            items: posts,\n            total: posts.length,\n            loadNextPage: undefined,\n        };\n    }\n}\n","import { AvatarSizes } from '../collaboration/AvatarSizes';\nimport { type RemotePostOwner } from '../interface/BoardModel';\n\nclass PostOwner {\n    private _userId: string | undefined = undefined;\n    private _displayName: string | undefined = undefined;\n    private _email: string | undefined = undefined;\n    private _firstName: string | undefined = undefined;\n    private _lastName: string | undefined = undefined;\n    private _images: Record<string, string> | undefined = undefined;\n\n    constructor(readonly data: RemotePostOwner) {\n        this._userId = data.userId;\n        this._displayName = data.displayName;\n        this._email = data.email;\n        this._firstName = data.firstName;\n        this._lastName = data.lastName;\n        this._images = data.images;\n    }\n\n    get userId(): string | undefined { return this._userId; }\n    get displayName(): string | undefined { return this._displayName; }\n    get email(): string | undefined { return this._email; }\n    get firstName(): string | undefined { return this._firstName; }\n    get lastName(): string | undefined { return this._lastName; }\n    get avatarImageURLs(): Record<string, string> | undefined { return this._images; }\n    get avatarUrl(): string | undefined {\n        return this.avatarImageURLs?.[AvatarSizes.Size138];\n    }\n}\n\nexport { PostOwner };\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IPropertyTypeMap } from '../core/PropertyUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemBase from '../core/ItemBase';\nimport { observable } from '../core/decorators';\nimport type { PostType } from '../interface/BoardModel';\nimport { BoardMemberRole, PostRemoteType, type RemotePostOwner, PostTypeMap } from '../interface/BoardModel';\nimport type Board from './Board';\nimport type { ISAMObject } from '../indexPrivate';\nimport { PostOwner } from './PostOwner';\n\n/** Represents a post for a Board */\nclass Post extends ItemBase {\n    private _type!: PostRemoteType;\n    private _name!: string;\n    private _created!: Date;\n    private _modified!: Date;\n    private _description: string | undefined = undefined;\n    private _boardId: string = '';\n    private _owner: PostOwner | undefined = undefined;\n\n    /** The ID of the board that the post belongs to */\n    @observable\n    get boardId(): string { return this._boardId; }\n\n    /** The type of the post */\n    @observable\n    get type(): PostType {\n        return PostTypeMap.toA(this._type);\n    }\n\n    /** The name of the post */\n    @observable\n    get name(): string { return this._name; }\n\n    /** The date the post was created */\n    @observable\n    get created(): Date { return this._created; }\n\n    /** The date the post was modified */\n    @observable\n    get modified(): Date { return this._modified; }\n\n    /** The description of the post */\n    @observable\n    get description(): string | undefined { return this._description; }\n\n    /** The owner of the post */\n    @observable\n    get owner(): PostOwner | undefined { return this._owner; }\n\n    /** Returns whether the current post can be deleted */\n    @observable\n    get isDeletable(): boolean {\n        // if the board is a published board (published from another board), then the post cannot be deleted\n        if (this._isBoardReadOnly()) {\n            return false;\n        }\n        // only board owner or the post owner can delete the post\n        return this._isOwner() || this._isBoardOwner();\n    }\n\n    /** Returns whether the current post can be edited */\n    @observable\n    get isEditable(): boolean {\n        // the post is editable only if the current user is the owner of the post or the board\n        // if the board is a published board (published from another board), then the post cannot be edited\n        // this logic is the same as isDeletable\n        return this.isDeletable;\n    }\n\n    /** Returns whether the current user is the owner of the post */\n    private _isOwner(): boolean | undefined {\n        if (this._owner) {\n            return this._owner.userId === this._core._environment.getUserId();\n        }\n    }\n\n    /** Returns the board that the post belongs to */\n    private _getBoard(): Board | undefined {\n        return this._core._getAssetPool().getLocalItemById<Board>(this._boardId);\n    }\n\n    /** Returns whether the current user is the owner of the board */\n    private _isBoardOwner(): boolean {\n        return this._getBoard()?.role === BoardMemberRole.OWNER;\n    }\n\n    /**\n     * Returns whether the board is published from another board.\n     * Default to true if the board is not found in unlikely scenario, so post cannot be modified by default\n     */\n    private _isBoardReadOnly(): boolean {\n        return this._getBoard()?.isReadOnly() ?? true;\n    }\n}\n\nconst getChildPostUpdater = (map: IPropertyTypeMap) =>  new PropertyUpdater({\n    _boardId: { name: 'computedBoardId', format: 'string' },\n    _name: { name: 'name', format: 'string' },\n    _type: { name: 'type', format: 'string', choices: Object.values(PostRemoteType) },\n    _description: { name: 'board#postDescription', format: 'string' },\n    _modified: { name: 'modified', format: 'date' },\n    _created: { name: 'created', format: 'date' },\n    _owner: {\n        name: 'postedBy',\n        format: 'object',\n        set: (parsedSource: RemotePostOwner, dest: ISAMObject) => {\n            const post = dest as Post;\n            const postOwner = new PostOwner(parsedSource);\n            post['_owner'] = postOwner;\n        }\n    },\n    ...map,\n});\n\nexport default Post;\nexport { getChildPostUpdater };\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport Post, { getChildPostUpdater } from './Post';\nimport type { AssetLinkPostDetails, RemoteAssetLinkPost, ResourceReference } from '../interface/BoardModel';\nimport { observable } from '../core/decorators';\n\n/** Represents a post for a Board which links to an Asset */\nclass AssetLinkPost extends Post {\n    private _remoteLink!: ResourceReference;\n\n    @observable\n    get link(): AssetLinkPostDetails {\n        return {\n            mediaType: this._remoteLink['dc:format'],\n            assetId: this._remoteLink['repo:assetId'],\n            publicUrl: this._remoteLink['board#postPublicUrl']\n        };\n    }\n}\n\nconst AssetLinkPostUpdater = new ItemUpdater<AssetLinkPost, Partial<RemoteAssetLinkPost>>({\n    localItemType: AssetLinkPost,\n    remoteIdProperty: 'id',\n    propertyUpdater: getChildPostUpdater({\n        _remoteLink: { name: 'link', format: 'object' },\n    }),\n});\n\nexport default AssetLinkPost;\nexport { AssetLinkPostUpdater };\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport Post, { getChildPostUpdater } from './Post';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { RemoteTextPost } from '../interface/BoardModel';\n\n/** Represents a post for a Board which just contains text */\nclass TextPost extends Post {\n    private _text!: string;\n\n    /** The text content of the post */\n    get text(): string {\n        return this._text;\n    }\n}\n\nconst TextPostUpdater = new ItemUpdater<TextPost, Partial<RemoteTextPost>>({\n    localItemType: TextPost,\n    remoteIdProperty: 'id',\n    propertyUpdater: getChildPostUpdater({\n        _text: { name: 'board#postText', format: 'string' },\n    })\n});\n\nexport default TextPost;\nexport { TextPostUpdater };\n","/*************************************************************************\n   *\n   * ADOBE CONFIDENTIAL\n   * ___________________\n   *\n   *  Copyright 2025 Adobe Systems Incorporated\n   *  All Rights Reserved.\n   *\n   * NOTICE:  All information contained herein is, and remains\n   * the property of Adobe Systems Incorporated and its suppliers,\n   * if any.  The intellectual and technical concepts contained\n   * herein are proprietary to Adobe Systems Incorporated and its\n   * suppliers and are protected by trade secret or copyright law.\n   * Dissemination of this information or reproduction of this material\n   * is strictly forbidden unless prior written permission is obtained\n   * from Adobe Systems Incorporated.\n   **************************************************************************/\n\nimport type { AdobeAssetUpdaterMetadata } from '../assets/AdobeAsset';\nimport type { AssetLinks, RepositoryMetadata } from '../interface/RepositoryModel';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type BoardContext from './BoardContext';\nimport type { PostSource } from './PostSource';\nimport type { AddBoardPostOptions, BoardLinks, BoardUpdateOptions, PublishedBoardInfo, PublishOptions, RemoteAssetLinkPost, RemoteBoard, RemotePublishedBoardInfo, RemoteSourceBoardInfo, RemoteTextPost, SourceBoardInfo, UpdatePostOptions } from '../interface/BoardModel';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport type Post from './Post';\nimport type AssetLinkPost from './AssetLinkPost';\nimport type TextPost from './TextPost';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport type { ONSChangedAssetInfo } from '../sync-services/ONSEvent';\n\nimport AdobeAsset from '../assets/AdobeAsset';\nimport { AssetClassChoices, AssetStateChoices } from '../interface/RepositoryModel';\nimport ItemUpdater from '../core/ItemUpdater';\nimport { BoardMemberRole, PostRemoteType } from '../interface/BoardModel';\nimport PropertyUpdater, { NotFound } from '../core/PropertyUpdater';\nimport ItemSource from '../core/ItemSource';\nimport { memoize, observable, retry } from '../core/decorators';\nimport PostListLoader from './PostListLoader';\nimport { parseEffectivePermissions } from '../interface/AssetModel';\nimport type { Permission } from '../interface/AssetModel';\nimport { SAM } from '@ccx-public/component-types';\nimport { RelType } from '../interface/LinkUtils';\nimport { AssetLinkPostUpdater } from './AssetLinkPost';\nimport { TextPostUpdater } from './TextPost';\nimport ItemPool from '../core/ItemPool';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\n\n\nexport default class Board extends AdobeAsset {\n    private _description: string | undefined;\n    private _baseAssetId: string | undefined;\n    private _boardContext!: BoardContext;\n    private _memberRole: BoardMemberRole = BoardMemberRole.UNKNOWN;\n    private _publishedBoardInfo: PublishedBoardInfo | undefined;\n    private _sourceBoardInfo: SourceBoardInfo | undefined;\n    // Have the associated Posts been loaded into the pool?\n    // Note: the odd \"...Prop\" naming is to avoid a conflict with the getter/setter\n    private _hasLoadedPostsProp: boolean = false;\n\n    /** @package -- for SAM.js internal use only */\n    public _postPool = new ItemPool<Post>(this._core, 'post');\n\n    /**\n     * This field is intended to preserve the references to posts provided by the remote item so that\n     * they do not get garbage collected before {@link posts}.getList is called.\n     * @package -- for SAM.js internal use only\n     */\n    public _posts: Post[] = [];\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        id: string,\n        metadata?: {\n            links?: AssetLinks;\n        }\n    ) {\n        super(_core, id, metadata);\n\n        this._core.getBoardContext().then((boardContext) => {\n            this._boardContext = boardContext;\n        });\n\n        // Overridden property.\n        // True to start with. If we have the metadata, we will update this.\n        // Keep in mind that the board service does not include all Adobe\n        // Asset metadata in its responses, hence why this is needed.\n        this._needsRepoMetadata = true;\n    }\n\n    /**\n     * Ensures that the board context has been fetched before using it\n     * @throws {SAMError} if the board context is not initialized\n     * @package -- for SAM.js internal use only\n     */\n    private _ensureBoardContext(): BoardContext {\n        if (!this._boardContext) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Board context not initialized');\n        }\n        return this._boardContext;\n    }\n\n    /**\n     * Were posts fetched in parallel to this Board.  This differentiates\n     * when posts were NOT fetched vs posts were fetched but the posts are not yet associated\n     * with the Board (i.e. the posts are not present in this._postPool)\n     * @package Only for use in SAM.js.\n     */\n    get _hasLoadedPosts(): boolean {\n        return this._hasLoadedPostsProp;\n    }\n\n    /**\n     * @package Only for use in SAM.js.\n     */\n    set _hasLoadedPosts(value: boolean) {\n        this._hasLoadedPostsProp = value;\n    }\n\n    /**\n     * Fetches the list of Posts for this Board\n     *\n     * @example <caption>Get all posts for this board</caption>\n     * const posts = board.posts.getList(PostOrder.default);\n     */\n    @memoize\n    get posts(): PostSource {\n        // board.id is not passed into the filter because the PostListLoader already has a reference to the board from the constructor\n        // The PostListLoader will access the board's _postPool which only contains posts for this board\n        const loader = new PostListLoader(this._core, this);\n        return new ItemSource(this._postPool, [ loader ]);\n    }\n\n    @observable\n    get description(): string | undefined {\n        return this._description;\n    }\n\n    static boardNameSuffix = '.ccboard';\n\n    /** The board name contains '.ccboard' suffix, so we need to remove it for display */\n    @observable\n    get displayName(): string {\n        return this._name.replace(Board.boardNameSuffix, '');\n    }\n\n    /**\n     * The ID of the asset containing the 'boards' directory that contains the board.\n     * In other words, the ID of the asset that is 2 levels up from the board.\n     *\n     * @package -- for SAM.js internal use only\n     */\n    @observable\n    get _idOfBaseAsset(): string | undefined {\n        return this._baseAssetId;\n    }\n\n    /**\n     * The role of the current user in the board.\n     *\n     * @example <caption>Get the role of the current user in the board</caption>\n     * const role = board.role;\n     */\n    @observable\n    get role(): BoardMemberRole {\n        return this._memberRole;\n    }\n\n    /**\n     * The information about the published board. Only available if the board is a source board.\n     *\n     * @example <caption>Get the published board info</caption>\n     * const publishedBoardInfo = board.publishedBoardInfo;\n     */\n    @observable\n    get publishedBoardInfo(): PublishedBoardInfo | undefined {\n        return this._publishedBoardInfo;\n    }\n\n    /**\n     * Whether the board is published to another board.\n     *\n     * @example <caption>Check if the board has been published</caption>\n     * const isPublishedToAnotherBoard = board.isPublishedToAnotherBoard;\n     */\n    @observable\n    get isPublishedToAnotherBoard(): boolean {\n        return !!this._publishedBoardInfo;\n    }\n\n    /**\n     * The information about the source board. Only available if the board is a published board.\n     *\n     * @example <caption>Get the source board info</caption>\n     * const sourceBoardInfo = board.sourceBoardInfo;\n     */\n    @observable\n    get sourceBoardInfo(): SourceBoardInfo | undefined {\n        return this._sourceBoardInfo;\n    }\n\n    /**\n     * Whether the board is published from another board.\n     *\n     * @example <caption>Check if the board is a published board</caption>\n     * const isPublishedFromAnotherBoard = board.isPublishedFromAnotherBoard;\n     */\n    @observable\n    get isPublishedFromAnotherBoard(): boolean {\n        return !!this._sourceBoardInfo;\n    }\n\n    /**\n     * Adds a new post to a board.\n     * - If the type is AssetLink:\n     *   - If assetId is provided then the board will create a reference to that asset. The blob is ignored in this case\n     *   - If a blob is provided then the file will be uploaded and a new asset will be created from it which the board will reference\n     * - If the type is Text then the board will create a new text post with the provided text\n     * @throws {SAMError} for AssetLink posts:\n     *   - If the blob is provided without fileName\n     *   - If the blob's filename is invalid\n     *   - If the blob is provided and the parent folder cannot be found or created\n     *   - If neither an assetId nor a blob is provided\n     * @throws {SAMError} for Text posts:\n     *   - If the text is not provided\n     * @example <caption>Add a post to the board</caption>\n     * await board.addPost({ type: 'text', text: 'Hello, world!' });\n     * await board.addPost({ type: 'assetLink', assetId: 'asset-id' });\n     * await board.addPost({ type: 'assetLink', blob: new Blob([ 'Hello, world!' ]), fileName: 'hello.txt' });\n     */\n    async addPost(options: AddBoardPostOptions): Promise<void> {\n        return this._ensureBoardContext().addPost({ boardId: this.id, ...options });\n    }\n\n    /**\n     * Removes a post from a board\n     * @example <caption>Remove a post from the board</caption>\n     * await board.removePost('post-id');\n     */\n    async removePost(postId: string): Promise<void> {\n        await this._ensureBoardContext().removePost({ boardId: this.id, postId });\n    }\n\n    /**\n     * Updates a post on the given board\n     * @example <caption>Update a post on the board</caption>\n     * await board.updatePost({ postId: 'post-id', text: 'Hello, world!' });\n     */\n    async updatePost(options: UpdatePostOptions): Promise<void> {\n        await this._ensureBoardContext().updatePost({ boardId: this.id, ...options });\n    }\n\n    /**\n     * Update the board. Use {@link addPost}, {@link updatePost}, and {@link removePost} to manage posts.\n     *\n     * @example <caption>Update the board </caption>\n     * await board.update({ displayName: 'Updated name', description: 'Updated description' });\n     */\n    async update(options: BoardUpdateOptions): Promise<void> {\n        return this._ensureBoardContext().updateBoard({ boardId: this.id, ...options });\n    }\n\n    /**\n     * Discard this board\n     * @example <caption>Discard the board</caption>\n     * await board.discard();\n     */\n    async discard(): Promise<void> {\n        return this._ensureBoardContext().discardBoard(this.id);\n    }\n\n    /**\n     * @experimental\n     */\n    async restore(): Promise<void> {\n        // TODO [ACPCEDU-3754]: implement this function\n        return;\n    }\n\n    @observable\n    get links(): BoardLinks {\n        // Make a copy to avoid the client accidentally manipulating the links\n        return Object.assign({}, this.__links as BoardLinks);\n    }\n\n    /**\n     * Publishes the current board. This returns a new board object that is public.\n     * @returns the public/published board\n     * @experimental Boards functionality is still in progress, this method is subject to change ACPCEDU-3888\n     * @example <caption>Publish the board with a custom title and subtitle</caption>\n     * const publishedBoard = await board.publish({ boardTitle: 'Published Biology Board', boardSubTitle: 'By Biology - Period 2', showPosterName: true });\n     */\n    async publish(options: PublishOptions = {}): Promise<Board> {\n        return this._ensureBoardContext().publishBoard({ boardId: this.id, ...options });\n    }\n\n    /**\n     * Unpublishes the current board. This removes the published board from the board service.\n     * @experimental Boards functionality is still in progress, this method is subject to change ACPCEDU-3888\n     * @example <caption>Unpublish the board</caption>\n     * await board.unpublish();\n     */\n    async unpublish(): Promise<void> {\n        return this._ensureBoardContext().unpublishBoard(this.id);\n    }\n\n    /**\n     * Whether the board is read only. This means the board name and description cannot be edited.\n     * This is overriding AdobeAsset.isReadOnly function.\n     *\n     * @example <caption>Check if the board is read only</caption>\n     * const isReadOnly = board.isReadOnly;\n     */\n    @observable\n    isReadOnly(): boolean {\n        // the board is read only if the board is published from another board or the user does not have permission to write to it\n        return this.isPublishedFromAnotherBoard || !this.hasPermission(SAM.Permission.Write);\n    }\n\n    /**\n     * Whether the current user can add a post to the board.\n     *\n     * @example <caption>Check if the current user can add a post to the board</caption>\n     * const canAddPost = board.canAddPost;\n     */\n    @observable\n    get canAddPost(): boolean {\n        // user (regardless of role) cannot add post to a board that is published from another board\n        if (this.isPublishedFromAnotherBoard) {\n            return false;\n        }\n\n        return this._memberRole === BoardMemberRole.OWNER || this._memberRole === BoardMemberRole.POSTER;\n    }\n\n    /**\n     * Whether the current user can unpublish the board.\n     *\n     * @example <caption>Check if the current user can unpublish the board</caption>\n     * const canUnpublish = board.canUnpublish;\n     */\n    @observable\n    get canUnpublish(): boolean {\n        return this._memberRole === BoardMemberRole.OWNER && this.isPublishedToAnotherBoard;\n    }\n\n    /**\n     * Whether the current user can publish the board.\n     *\n     * @example <caption>Check if the current user can publish the board</caption>\n     * const canPublish = board.canPublish;\n     */\n    @observable\n    get canPublish(): boolean {\n        // if the board is read only / published from another board, then the user cannot publish it\n        if (this.isPublishedFromAnotherBoard) {\n            return false;\n        }\n\n        return this._memberRole === BoardMemberRole.OWNER;\n    }\n\n    /**\n     * Get a post by its ID in this board\n     * @throws {SAMError} if the post is not found in this board\n     * @example <caption>Get a post by its ID</caption>\n     * const post = await board.getPostById('post-id');\n     */\n    async getPostById(id: string): Promise<Post> {\n        return this._ensureBoardContext().getPostByBoardAndPostId({ boardId: this.id, postId: id });\n    }\n\n    /**\n     * Overwrites AdobeAsset instance of handleOnsChangedResources.\n     *\n     * The board service is the source of truth for Board-specific\n     * repo metadata, app metadata, and permissions/links. Meaning\n     * metadata that is not required for board actions is fetched\n     * with R-API. There is a chance the cached board contains a\n     * combination of board metadata and core asset metadata\n     * therefore metadata is fetched from both the board service and R-API\n     *\n     * @package -- for SAM.js internal use only\n     */\n    handleOnsChangedResources(changedResources: ONSChangedAssetInfo['changedResources']) {\n        // Refetch any potential non-board metadata using the AdobeAsset's handleOnsChangedResources\n        super.handleOnsChangedResources(changedResources);\n        // If changedResources includes repoMetadata changes then Board._load will be\n        // called by the line above which calls the same line as below. This check\n        // minimizes unnecessary calls to the board service\n        if (!changedResources?.includes('api:metadata/repository')) {\n            // Then fetch board-specific metadata from the board service\n            this._boardContext._fetchBoardById(this.id);\n        }\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * Will override any cached board with the latest data from the board service and R-API\n     */\n    @retry\n    _loadWithRetry(): Promise<void> {\n        return this._load();\n    }\n\n    /**\n     * @param repoMetadata {RepositoryMetadata} If passed in, it will be used instead of loading from the service\n     * @param appMetadata {any} If passed in, it will be used instead of loading from the service\n     * @param effectivePermission {Permission} If passed in, it will be used instead of loading from the service\n     *\n     * @package -- only for use in SAM.js\n     */\n    async _load({\n        repoMetadata,\n        appMetadata,\n        effectivePermission,\n    }: {\n        repoMetadata?: RepositoryMetadata;\n        appMetadata?: any;\n        effectivePermission?: Permission;\n    } = {}): Promise<void> {\n        // Ensure board context is initialized\n        if (!this._boardContext) {\n            this._boardContext = await this._core.getBoardContext();\n        }\n\n        const promise = super._load({ repoMetadata, appMetadata, effectivePermission });\n        // Run both loading operations in parallel\n        await Promise.allSettled([\n            promise,\n            // since we don't want the RAPI call to override the result from this._boardContext._fetchBoardById, we pass in the promise from super._load\n            // This way, this._boardContext._fetchBoardById will wait for the super._load to complete before making changes to the internal state of the board\n            this._boardContext._fetchBoardById(this.id, promise)\n        ]);\n    }\n}\n\nfunction getBoardPermission(source: Partial<AdobeAssetUpdaterMetadata> & Pick<RemoteBoard, 'memberRole'>): SAM.Permission | typeof NotFound {\n    // From R-API directory listing or USS listings\n    if (source._embedded?.[RelType.AC_EFFECTIVE]) {\n        return parseEffectivePermissions(source._embedded[RelType.AC_EFFECTIVE]!);\n    }\n\n    // TODO [ACPCEDU-3995]: remove the following switch block when \"_embedded\" is available\n    switch (source.memberRole) {\n    case BoardMemberRole.OWNER:\n        return SAM.Permission.Write | SAM.Permission.Read | SAM.Permission.Delete;\n    case BoardMemberRole.POSTER:\n    case BoardMemberRole.VIEWER:\n        return SAM.Permission.Read;\n    case BoardMemberRole.UNKNOWN:\n        return SAM.Permission.None;\n    default:\n        return NotFound;\n    }\n}\n\nexport const BoardUpdater = new ItemUpdater<Board, Partial<RemoteBoard | AdobeAssetUpdaterMetadata>>({\n    localItemType: Board,\n    remoteIdProperty: 'repo:assetId',\n    propertyUpdater: new PropertyUpdater({\n        _id: { name: 'repo:assetId', format: 'string' },\n        _assetClass: { name: 'repo:assetClass', choices: AssetClassChoices },\n        _description: { name: 'dc:description', format: 'string' },\n        _name: { name: 'repo:name', format: 'string' },\n        _created: { name: 'repo:createDate', format: 'date' },\n        _repositoryID: { name: 'repo:repositoryId', format: 'string' },\n        __links: { name: '_links', format: 'object' },\n        _createdBy: { name: 'repo:createdBy', format: 'string' },\n        _modifiedBy: { name: 'repo:modifiedBy', format: 'string' },\n        _modified: { name: 'repo:modifyDate', format: 'date' },\n        _assetState: { name: 'repo:state', choices: AssetStateChoices },\n        _type: { name: 'dc:format', format: 'string' },\n        _path: { name: 'repo:path', format: 'string' },\n        _remotePosts: {\n            isArray: true,\n            name: 'posts',\n            format: 'object',\n            set: async (remotePosts: (RemoteTextPost | RemoteAssetLinkPost)[], dest: ISAMObject) => {\n                const board = dest as Board;\n                board._posts.length = 0;\n                const session = board._postPool.createMutationSession<Post>();\n\n                // When a post is deleted it will not be in the remotePosts array, but it will still exist in the pool\n                // Here we will remove the posts from the pool that are not in the new remotePosts array\n                const itemsToRemoveFromPool = board._postPool.toArray().filter((post) => !remotePosts.some((remotePost) => remotePost.id === post.id));\n                itemsToRemoveFromPool.forEach((post) => session.queueDiscardedItem(post));\n                board._postPool.removeLocalItems(itemsToRemoveFromPool.map((post) => post.id));\n\n                // Add new posts to the pool, or update remaining posts\n                const posts: Post[] = [];\n                remotePosts.forEach((remotePost) => {\n                    const remotePostWithComputedValues = { ...remotePost, computedBoardId: board.id };\n                    if (remotePost.type === PostRemoteType.TEXT) {\n                        posts.push(TextPostUpdater.updateRemoteItem(session as IUpdateSession<TextPost>, remotePostWithComputedValues));\n                    } else if (remotePost.type === PostRemoteType.ASSET_LINK) {\n                        posts.push(AssetLinkPostUpdater.updateRemoteItem(session as IUpdateSession<AssetLinkPost>, remotePostWithComputedValues));\n                    }\n                });\n                session.commit();\n                board._posts.push(...posts);\n            }\n        },\n        _baseAssetId: { name: 'board:context[baseAssetId]', format: 'string' },\n        _memberRole: { name: 'memberRole', choices: Object.values(BoardMemberRole) },\n        _permissions: { get: getBoardPermission, format: 'number' },\n        _publishedBoardInfo: {\n            name: 'board:publishedBoard',\n            format: 'object',\n            set: (publishedBoardInfo: RemotePublishedBoardInfo | undefined, dest: ISAMObject) => {\n                const board = dest as Board;\n                if (!publishedBoardInfo) {\n                    board['_publishedBoardInfo'] = undefined;\n                    return;\n                }\n                board['_publishedBoardInfo'] = {\n                    boardId: publishedBoardInfo['repo:assetId'],\n                    showPosterName: publishedBoardInfo['board:showPosterName'] || false,\n                };\n            }\n        },\n        _sourceBoardInfo: {\n            name: 'board:sourceBoard',\n            format: 'object',\n            set: (sourceBoardInfo: RemoteSourceBoardInfo, dest: ISAMObject) => {\n                const board = dest as Board;\n                board['_sourceBoardInfo'] = {\n                    boardId: sourceBoardInfo['repo:assetId'],\n                    publishedVersion: sourceBoardInfo['repo:version'],\n                };\n            }\n        },\n    }),\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type {\n    IComparatorMap } from '../core/ItemOrder';\nimport {\n    createItemOrderFactory\n} from '../core/ItemOrder';\nimport type Post from './Post';\n\nexport type PostOrderField = 'noop';\n\n\nconst OrderFieldToComparator: IComparatorMap<Post, PostOrderField> = {\n    // Preserve original order\n    noop(): number {\n        return 0;\n    },\n};\n\nexport default class PostOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    /**\n     * Default ordering - original order from the server (no sorting)\n     */\n    static default = new PostOrder('ascending', 'noop');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type Board from './Board';\nimport type { IComparatorMap } from '../core/ItemOrder';\n\nexport type BoardOrderField = 'name' | 'created' | 'modified';\n\nconst compareBoardNames = (a: Board, b: Board) => compareStrings(a.displayName || '', b.displayName || '');\n\nconst compareBoardTimes = (a: Board, b: Board, field: 'created' | 'modified') => {\n    let value: number;\n    if (!a[field] && !b[field]) {\n        value = 0;\n    } else if (!a[field]) {\n        value = 1;\n    } else if (!b[field]) {\n        value = -1;\n    } else {\n        value = compareValues(a[field].getTime(), b[field].getTime());\n    }\n    return value === 0 ? compareBoardNames(a, b) : value;\n};\n\nconst OrderFieldToComparator: IComparatorMap<Board, BoardOrderField> = {\n    name(a: Board, b: Board): number {\n        return compareBoardNames(a, b);\n    },\n    created(a: Board, b: Board): number {\n        return compareBoardTimes(a, b, 'created');\n    },\n    modified(a: Board, b: Board): number {\n        return compareBoardTimes(a, b, 'modified');\n    }\n};\n\nexport default class BoardOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new BoardOrder('ascending', 'name');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type Board from './Board';\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport type AdobeAsset from '../assets/AdobeAsset';\n\nexport interface BoardFilterOptions {\n    baseAssetId: string;\n    shouldGetDirectlyInBaseAsset?: boolean;\n}\n\nexport default class BoardFilter implements IExplicitFilter<Board> {\n    public baseAssetId: string;\n    public shouldGetDirectlyInBaseAsset?: boolean;\n    /**\n     * @package only for use in SAM.js\n     */\n    public _monitoredFolder?: AdobeAsset;\n\n    constructor(options: Partial<BoardFilterOptions> = {}) {\n        this.baseAssetId = options.baseAssetId || '';\n        this.shouldGetDirectlyInBaseAsset = options.shouldGetDirectlyInBaseAsset || false;\n    }\n\n    matches(item: Board): boolean {\n        if (!item.isBoard) {\n            return false;\n        }\n        // Filter by baseAssetId and discard discarded boards\n        if (item._idOfBaseAsset !== this.baseAssetId) {\n            return false;\n        }\n        if (item.isDiscarded) {\n            return false;\n        }\n        return true;\n    }\n\n    getRelationToFilter(other: BoardFilter): ItemFilterRelation {\n        if (this.baseAssetId !== other.baseAssetId) {\n            return 'disjoint';\n        } else {\n            return 'subset';\n        }\n    }\n\n    get hash(): string {\n        return `baseAssetId=${this.baseAssetId}&shouldGetDirectlyInBaseAsset=${this.shouldGetDirectlyInBaseAsset}`;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { observable } from '../core/decorators';\nimport ItemBase from '../core/ItemBase';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { IProjectsOrgRepository, IProjectsTeamCreateData } from '../interface/WorkspacesModel';\nimport type Team from './Team';\n\nexport default class OrgRepository extends ItemBase {\n\n    private _repositoryID: string = '';\n\n    @observable\n    get repositoryID(): string {\n        return this._repositoryID;\n    }\n\n    /**\n     * Create a team under /content/assets folder.\n     */\n    async createTeam(data: IProjectsTeamCreateData): Promise<Team> {\n        return await this._core.spaceContext.createTeam(this, data);\n    }\n}\n\nexport const OrgRepositoryUpdater = new ItemUpdater<OrgRepository, Partial<IProjectsOrgRepository>>({\n    localItemType: OrgRepository,\n    remoteIdProperty: 'repositoryId',\n    propertyUpdater: new PropertyUpdater({\n        '_repositoryID': 'repositoryId'\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareValues, createItemOrderFactory } from '../core/ItemOrder';\n\nexport type FavoriteAdobeAssetOrderField = 'created' | 'name';\n\nconst OrderFieldToComparator: IComparatorMap<AdobeAsset, FavoriteAdobeAssetOrderField> = {\n    created(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.created, b.created);\n    },\n    name(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.name, b.name);\n    }\n};\n\n// This sort order will eventually be moved to a generic sort order for all GraphQL sort options.\n/**\n * @experimental\n */\nexport default class FavoriteAdobeAssetOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new FavoriteAdobeAssetOrder('descending', 'created');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport USSAdobeAssetOrder from './USSAdobeAssetOrder';\n\nexport default class MRUAdobeAssetOrder extends USSAdobeAssetOrder {\n    static default = new MRUAdobeAssetOrder('descending', 'lastAccessed');\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n\nimport USSAdobeAssetOrder from './USSAdobeAssetOrder';\n\nexport default class PublishedAdobeAssetOrder extends USSAdobeAssetOrder {\n    static default = new PublishedAdobeAssetOrder('descending', 'modified');\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { IProjectsOrderBy } from '../interface/ProjectsModel';\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type Project from './Project';\nimport { LastAccessedOrderField } from '../interface/USSModel';\n\nexport type ProjectOrderField =\n    | 'name'\n    | 'created'\n    | 'lastAccessed';\n\nexport const OrderFieldToIProjectsOrderBy: { [key in ProjectOrderField]: IProjectsOrderBy } = {\n    'name': 'repo:name',\n    'created': 'repo:createDate',\n    'lastAccessed': LastAccessedOrderField\n};\n\nconst OrderFieldToComparator: IComparatorMap<Project, ProjectOrderField> = {\n    name(a: Project, b: Project): number {\n        return compareStrings(a.name, b.name);\n    },\n    created(a: Project, b: Project): number {\n        return compareValues(a.created, b.created);\n    },\n    lastAccessed(a: Project, b: Project): number {\n        return compareValues(a.lastAccessed, b.lastAccessed);\n    }\n};\n\nexport default class ProjectOrder extends createItemOrderFactory(OrderFieldToComparator) implements SAM.ProjectOrder {\n    static default = new ProjectOrder('ascending', 'name');\n    static createdDesc = new ProjectOrder('descending', 'created');\n    static lastAccessed = new ProjectOrder('descending', 'lastAccessed');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { CustomModelOrderBy } from '../interface/CustomModelModel';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\n\nimport type CustomModel from './CustomModel';\nimport type { ISearchSortOrderBy, ISearchQuery } from '../interface/USSModel';\n\nexport type CustomModelOrderField =\n    | 'name'\n    | 'created'\n    | 'modified';\n\nexport const OrderFieldToCustomModelOrderBy: { [key in CustomModelOrderField]: CustomModelOrderBy} = {\n    'name': CustomModelOrderBy.NAME,\n    'created': CustomModelOrderBy.CREATE_DATE,\n    'modified': CustomModelOrderBy.MODIFY_DATE\n};\n\nconst OrderFieldToComparator: IComparatorMap<CustomModel, CustomModelOrderField> = {\n    name(a: CustomModel, b: CustomModel): number {\n        return compareStrings(a.name, b.name);\n    },\n\n    created(a: CustomModel, b: CustomModel): number {\n        return compareValues(a.created, b.created);\n    },\n\n    modified(a: CustomModel, b: CustomModel): number {\n        return compareValues(a.modified, b.modified);\n    }\n};\n\nexport default class CustomModelOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new CustomModelOrder('descending', 'modified');\n}\n\n\nexport const customModelOrderToUSSOrder = (itemOrder: CustomModelOrder): Required<Pick<ISearchQuery, 'sort_order' | 'sort_orderby'>> => {\n    const orderMap: { [key in CustomModelOrderField]: ISearchSortOrderBy } = {\n        'name': 'asset_name',\n        'created': 'create_date',\n        'modified': 'modify_date'\n    };\n\n    return {\n        sort_order: itemOrder.direction === 'ascending' ? 'asc' : 'desc',\n        sort_orderby: orderMap[itemOrder.field]\n    };\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareValues, createItemOrderFactory } from '../core/ItemOrder';\n\nexport type GenerationHistoryAssetOrderField = 'created';\n\nconst OrderFieldToComparator: IComparatorMap<AdobeAsset, GenerationHistoryAssetOrderField> = {\n    created(a: AdobeAsset, b: AdobeAsset): number {\n        return compareValues(a.created, b.created);\n    },\n};\n\nexport default class GenerationHistoryAssetOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new GenerationHistoryAssetOrder('descending', 'created');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { CustomModelOrderBy } from './LegacyCustomModelModel';\nimport type { IComparatorMap } from '../../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../../core/ItemOrder';\n\nimport type LegacyCustomModel from './LegacyCustomModel';\n\nexport type CustomModelOrderField =\n    | 'name'\n    | 'created'\n    | 'modified';\n\nexport const LegacyOrderFieldToCustomModelOrderBy: { [key in CustomModelOrderField]: CustomModelOrderBy} = {\n    'name': CustomModelOrderBy.NAME,\n    'created': CustomModelOrderBy.CREATE_DATE,\n    'modified': CustomModelOrderBy.MODIFY_DATE\n};\n\nconst OrderFieldToComparator: IComparatorMap<LegacyCustomModel, CustomModelOrderField> = {\n    name(a: LegacyCustomModel, b: LegacyCustomModel): number {\n        return compareStrings(a.name, b.name);\n    },\n\n    created(a: LegacyCustomModel, b: LegacyCustomModel): number {\n        return compareValues(a.created, b.created);\n    },\n\n    modified(a: LegacyCustomModel, b: LegacyCustomModel): number {\n        return compareValues(a.modified, b.modified);\n    }\n};\n\nexport default class LegacyCustomModelOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new LegacyCustomModelOrder('descending', 'modified');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, createItemOrderFactory } from '../core/ItemOrder';\nimport type OrgRepository from './OrgRepository';\n\nexport type OrgRepositoryOrderField = 'id';\n\nconst OrderFieldToComparator: IComparatorMap<OrgRepository, OrgRepositoryOrderField> = {\n    id(a: OrgRepository, b: OrgRepository): number {\n        return compareStrings(a.id, b.id);\n    }\n};\n\nexport default class OrgRepositoryOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new OrgRepositoryOrder('ascending', 'id');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IProjectsTeamsOrderBy } from '../interface/WorkspacesModel';\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type Team from './Team';\n\nexport type TeamOrderField =\n    | 'name'\n    | 'created';\n\nexport const OrderFieldToIProjectsTeamsOrderBy: { [key in TeamOrderField]: IProjectsTeamsOrderBy } = {\n    'name': 'name',\n    'created': 'createDate',\n};\n\nconst OrderFieldToComparator: IComparatorMap<Team, TeamOrderField> = {\n    name(a: Team, b: Team): number {\n        return compareStrings(a.name, b.name);\n    },\n    created(a: Team, b: Team): number {\n        return compareValues(a.created, b.created);\n    }\n};\n\nexport default class TeamOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new TeamOrder('ascending', 'name');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IProjectsSpaceOrderBy } from '../interface/WorkspacesModel';\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { compareStrings, compareValues, createItemOrderFactory } from '../core/ItemOrder';\nimport type Space from './Space';\n\nexport type SpaceOrderField =\n    | 'name'\n    | 'created';\n\nexport const OrderFieldToIProjectsSpaceOrderBy: { [key in SpaceOrderField]: IProjectsSpaceOrderBy } = {\n    'name': 'name',\n    'created': 'createdDate',\n};\n\nconst OrderFieldToComparator: IComparatorMap<Space, SpaceOrderField> = {\n    name(a: Space, b: Space): number {\n        return compareStrings(a.name, b.name);\n    },\n    created(a: Space, b: Space): number {\n        return compareValues(a.created, b.created);\n    }\n};\n\nexport default class SpaceOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new SpaceOrder('ascending', 'name');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IComparatorMap } from '../core/ItemOrder';\nimport { createItemOrderFactory } from '../core/ItemOrder';\nimport type CollaboratorsByAssetID from './CollaboratorsByAssetID';\n\nexport type CollaboratorsByAssetIDOrderField = 'noop';\n\nconst OrderFieldToComparator: IComparatorMap<CollaboratorsByAssetID, CollaboratorsByAssetIDOrderField> = {\n    // there is nothing in collaboratorListByUrn to order, this will keep order same\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    noop(a: CollaboratorsByAssetID, b: CollaboratorsByAssetID): number {\n        return 0;\n    }\n};\n\nexport default class CollaboratorsByAssetIDOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new CollaboratorsByAssetIDOrder('ascending', 'noop');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nconst whitespaceFilter = (w: string) => /\\S/.test(w);\n\nexport default whitespaceFilter;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { SAM } from '@ccx-public/component-types';\nimport {\n    getMultiValueFilterRelation,\n    type IExplicitFilter,\n    type ItemFilterRelation\n} from '../core/ItemFilter';\nimport type { default as Project } from './Project';\nimport whitespaceFilter from '../utils/whitespaceFilter';\nimport { ProjectDirectorySubtype } from '../interface/ProjectsModel';\n\nenum ProjectStringRelationResult {\n    DISJOINTED,\n    SUPERSET,\n    SUBSET,\n    UNKNOWN,\n    IDENTICAL\n}\n\ntype PrivateProjectFilterOptions = {\n    /**\n     * Use isDiscarded going forward.\n     * @deprecated;\n     */\n    _isDiscarded?: boolean;\n    view?: SAM.ProjectViews;\n    repositoryID?: string;\n    organizationID?: string;\n    nameContains?: string;\n    /**\n     * Public facing filter for fetching and filtering\n     * discarded projects from the projects service.\n     */\n    isDiscarded?: boolean;\n    directorySubtypes?: ProjectDirectorySubtype[];\n}\n\nconst DIRECT_COMPARE_VIEWS = [ SAM.ProjectViews.Yours, SAM.ProjectViews.SWY ];\n\nexport default class ProjectFilter implements IExplicitFilter<Project> {\n    private _isDiscarded: boolean;\n    private _view: SAM.ProjectViews = SAM.ProjectViews.All;\n    private _repositoryID?: string;\n    private _nameContains?: string;\n    private _organizationID?: string;\n    private _directorySubtypes?: ProjectDirectorySubtype[] = [\n        // Default to CC_PROJECTS because the service just defaults to\n        // returning CC_PROJECTS if no directorySubtypes are provided.\n        ProjectDirectorySubtype.CC_PROJECTS\n    ];\n\n    static YourProjects = new ProjectFilter({\n        view: SAM.ProjectViews.Yours\n    });\n\n    static AllProjects = new ProjectFilter({\n        view: SAM.ProjectViews.All\n    });\n\n    static SWYProjects = new ProjectFilter({\n        view: SAM.ProjectViews.SWY\n    });\n\n    static AdminProjects = new ProjectFilter({\n        view: SAM.ProjectViews.Admin\n    });\n\n    constructor(\n        options: PrivateProjectFilterOptions = {\n            view: SAM.ProjectViews.All\n        }\n    ) {\n        const { _isDiscarded, view, repositoryID, organizationID, nameContains, isDiscarded, directorySubtypes } = options;\n        this._isDiscarded = !!(_isDiscarded || isDiscarded);\n        if (view !== undefined) {\n            this._view = view;\n        }\n        this._repositoryID = repositoryID;\n        this._organizationID = organizationID;\n        // @TODO Eventually just store the sorted name with no whitespace in the array\n        // so we don't have to do it in multiple places.\n        this._nameContains = nameContains;\n        this._directorySubtypes = directorySubtypes ?? this._directorySubtypes;\n    }\n\n    get hash(): string {\n        return `discarded=${this._isDiscarded}view=${this._view}repositoryId=${this._repositoryID}`\n       + `orgID=${this._organizationID || ''}nameContains=${this._nameContains}directorySubtype=${this._directorySubtypes?.sort().join('')}`;\n    }\n\n    get view(): SAM.ProjectViews {\n        return this._view;\n    }\n\n    /**\n     * @TODO_Deprecation will be marked as deprecated on or after 2025-01-01 and removed on or after 2025-03-01\n     *    Use ownerIDs instead.\n     */\n    get repositoryID(): string | undefined {\n        return this._repositoryID;\n    }\n\n    get nameContains(): string | undefined {\n        return this._nameContains;\n    }\n\n    get isDiscarded(): boolean {\n        return this._isDiscarded;\n    }\n\n    /**\n     *\n     * @NOTE this code is to be analyzed at a future date, we may want to remove this logic\n     * or improve it so it can become a fast client side optimization for\n     * all USS based lists. Will likely require some syncing with what the services provide.\n     * @TODO https://jira.corp.adobe.com/browse/SHARED-3489\n     *\n     */\n    private _getRelationToNameContains(name: string = '', otherName: string = ''): ProjectStringRelationResult {\n        if (name === otherName) {\n            return ProjectStringRelationResult.IDENTICAL;\n        }\n        if (!name && otherName) {\n            // `otherName` matches some names, while `name` matches all\n            return ProjectStringRelationResult.UNKNOWN;\n        }\n        const nameTerms = name.toLowerCase()\n            .split(' ').filter(whitespaceFilter).sort();\n        const otherNameTerms = otherName.toLowerCase()\n            .split(' ').filter(whitespaceFilter).sort();\n\n        if (nameTerms.length === 0 && otherNameTerms.length === 0) {\n            return ProjectStringRelationResult.IDENTICAL;\n        }\n\n        if (nameTerms.length === otherNameTerms.length\n            && nameTerms.every(\n                (n, i) => n === otherNameTerms[i]\n            )) {\n            return ProjectStringRelationResult.IDENTICAL;\n        }\n\n        let subsetMatches = 0;\n        let supersetMatches = 0;\n\n        nameTerms.forEach((nameTerm) => {\n            const findMatch = otherNameTerms.find((otherTerm) => {\n                const superSet = otherTerm.startsWith(nameTerm);\n                const subSet = nameTerm.startsWith(otherTerm);\n                return superSet || subSet;\n            });\n\n            if (findMatch) {\n                if (nameTerm.length <= findMatch.length) {\n                    supersetMatches++;\n                }\n\n                if (nameTerm.length > findMatch.length) {\n                    subsetMatches++;\n                }\n            }\n        });\n\n        if (nameTerms.length === subsetMatches) {\n            return ProjectStringRelationResult.SUBSET;\n        }\n\n        if (nameTerms.length === supersetMatches) {\n            return ProjectStringRelationResult.SUPERSET;\n        }\n\n        if (subsetMatches === 0 && supersetMatches === 0) {\n            return ProjectStringRelationResult.DISJOINTED;\n        }\n\n        return ProjectStringRelationResult.UNKNOWN;\n    }\n\n    /**\n     *\n     * @TODO https://jira.corp.adobe.com/browse/SHARED-3489\n     */\n    private _searchTarget(searchString: string, targetString: string): boolean {\n        const searchTerms = searchString.toLowerCase().split(/\\s+/);\n        const targetTerms = targetString.toLowerCase().split(/\\s+/);\n\n        // Empty word or search term\n        if (searchTerms.length === 0 || targetTerms.length === 0) {\n            return false;\n        }\n\n        return searchTerms.every((searchTerm) => {\n            return targetTerms.find((targetTerm) => {\n                return targetTerm.startsWith(searchTerm);\n            });\n        });\n    }\n\n    get organizationID(): string | undefined {\n        return this._organizationID;\n    }\n\n    get directorySubtypes(): ProjectDirectorySubtype[] | undefined {\n        return this._directorySubtypes;\n    }\n\n    matches(item: Project): boolean {\n        // Note: ImplicitProjectFilter requires Project to be either _isRecent or _allowInLists\n\n        // We don't want to allow any matching for the Recent project listing\n        // TODO: once we have support for lastAccessDate from projects service, we should use that instead.\n        if (this._view === SAM.ProjectViews.Recent && !item._isRecent) {\n            return false;\n        }\n\n        // For views other than Recent, only allow _isRecent Project if it was also seen in some other listing from the\n        // service (All, Yours, etc)\n        if (this.view !== SAM.ProjectViews.Recent && item._isRecent && !item._allowInLists) {\n            return false;\n        }\n\n        if (!item.isProject) {\n            return false;\n        }\n\n        if (item.isDiscarded !== this._isDiscarded) {\n            return false;\n        }\n\n        // For Admin view: If specified, match on repositoryID\n        if (this._repositoryID && this._repositoryID !== item.repositoryID) {\n            return false;\n        }\n\n        // For view = Organization or Admin, filter by organizationID\n        if (this._organizationID && this._organizationID !== item.repositoryOwner.id) {\n            return false;\n        }\n\n        if (this._directorySubtypes?.length && !this._directorySubtypes.includes(item.directorySubtype)) {\n            return false;\n        }\n\n\n        const nameContains = this._nameContains;\n        if (nameContains\n            && !this._searchTarget(nameContains, item.name)\n        ) {\n            return false;\n        }\n\n        // Project.view computes Yours and SWY\n        if (DIRECT_COMPARE_VIEWS.includes(this._view) && this._view !== item.view) {\n            return false;\n        }\n\n        // this.view is undefined, All, or Admin\n        return true;\n    }\n\n    /**\n     * This method determines the commonality between the already present filter (other)\n     * and the new filter to be applied (this). The point of this is to\n     * see if the new filter (this) can build some, all, or none of it's items\n     * from (other) filter.\n     *\n     * Subset: Means that ALL items for this filter can be built from other\n     * Disjoint: No items for this filter can be built from other.\n     * Unknown: Some items for this filter can be built from other.\n     *\n     * @note we should always determine disjoint cases first before other cases.\n     * @note this = NEW FILTER, other = EXISTING FILTER\n     *\n     * @param other The existing filter that we are getting the relation to.\n     * @returns { ItemFilterRelation }\n     */\n    getRelationToFilter(other: ProjectFilter): ItemFilterRelation {\n        if (this._repositoryID && other.repositoryID && this._repositoryID !== other.repositoryID) {\n            return 'disjoint';\n        }\n\n        if (this._isDiscarded !== other._isDiscarded) {\n            return 'disjoint';\n        }\n\n        // SWY and Yours are disjoint to each other.\n        if (this._view !== other.view\n            && DIRECT_COMPARE_VIEWS.includes(this._view)\n            && DIRECT_COMPARE_VIEWS.includes(other.view)) {\n            return 'disjoint';\n        }\n\n        let searchMatch;\n        if (this.nameContains || other.nameContains) {\n            searchMatch = this._getRelationToNameContains(this.nameContains, other.nameContains);\n            if (searchMatch === ProjectStringRelationResult.DISJOINTED) {\n                return 'disjoint';\n            }\n        }\n\n        if (this._organizationID && other.organizationID && this._organizationID !== other.organizationID) {\n            return 'disjoint';\n        }\n\n        const subTypeArrayComparison = getMultiValueFilterRelation<string>(this._directorySubtypes, other._directorySubtypes);\n        if (subTypeArrayComparison === 'disjoint') {\n            return 'disjoint';\n        }\n\n        // ------ All disjoint cases should be handled above this line ------\n        if (searchMatch && searchMatch === ProjectStringRelationResult.SUPERSET\n            || searchMatch === ProjectStringRelationResult.UNKNOWN\n        ) {\n            return 'unknown';\n        }\n\n        // Other view contains one organization, but there could be more\n        if (!this._organizationID && other.organizationID) {\n            return 'unknown';\n        }\n\n        if ([ SAM.ProjectViews.All, SAM.ProjectViews.Admin, undefined ].includes(this._view)\n            && DIRECT_COMPARE_VIEWS.includes(other.view)) {\n            return 'unknown';\n        }\n\n        // SAMJS-795 Switching from All to Yours/SWY requires fetching the orgs to do server-side and\n        // client-side filtering properly. To ensure the orgs are fetched, always treat All -> Yours/SWY\n        // as 'unknown'. The expectation is that clients typically filter by All and users rarely switch\n        // to Yours/SWY, so it's better to optimize fetching All from an empty cache than it is to optimize\n        // for switching from All to Yours/SWY.\n        if (DIRECT_COMPARE_VIEWS.includes(this.view) && other.view === SAM.ProjectViews.All) {\n            return 'unknown';\n        }\n\n        // Admin can contain projects that are excluded from All\n        if (this.view === SAM.ProjectViews.Admin && other.view === SAM.ProjectViews.All) {\n            return 'unknown';\n        }\n\n        if (this._view === SAM.ProjectViews.Recent) {\n            switch (other.view) {\n            // Recent view is a subset of All and Admin. For now we are setting the relation to be unknown.\n            // TODO: once we have support for lastAccessDate from projects service, we can set the relation to be subset.\n            case SAM.ProjectViews.Recent:\n            case SAM.ProjectViews.All:\n            case SAM.ProjectViews.Admin:\n                return 'unknown';\n            // Recent view has an unknown relation with Yours, SWY, and Organization\n            case SAM.ProjectViews.Yours:\n            case SAM.ProjectViews.SWY:\n            case SAM.ProjectViews.Organization:\n            default:\n                return 'unknown';\n            }\n        }\n\n        // If the other view is Recent, then this view has an unknown relation to it apart from Recent itself\n        // which is handled above.\n        if (other.view === SAM.ProjectViews.Recent) {\n            return 'unknown';\n        }\n\n        if (subTypeArrayComparison === 'unknown') {\n            return 'unknown';\n        }\n\n        // ------ All unknown cases should be handled above this line ------\n\n        // If not disjoint or unknown, then it's a subset.\n        return 'subset';\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { CustomModelPublishedState, CustomModelTrainingState } from '../interface/CustomModelModel';\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport { getDateRangeRelation } from '../core/ItemFilter';\nimport type CustomModel from './CustomModel';\nexport interface ICustomModelListingOptions {\n    publishedState?: CustomModelPublishedState;\n    createDateMin?: Date;\n    createDateMax?: Date;\n    modifyDateMin?: Date;\n    modifyDateMax?: Date;\n    createdBy?: string;\n    trainingSetId?: string;\n    baseModelName?: string;\n    baseModelVersion?: string;\n    category?: string;\n    inferenceReady?: boolean;\n    trainingJobId?: string;\n    trainingState?: CustomModelTrainingState;\n    trainingSetVersion?: string;\n}\n\nexport default class CustomModelFilter implements IExplicitFilter<CustomModel> {\n    private _listingOptions: Partial<ICustomModelListingOptions> = {};\n\n    constructor(listingOptions?: Partial<ICustomModelListingOptions>) {\n        if (listingOptions) {\n            this._listingOptions = listingOptions;\n        }\n    }\n\n    get listingOptions() {\n        return this._listingOptions;\n    }\n\n    get hash(): string {\n        const o = this._listingOptions;\n        return [\n            o.publishedState !== undefined ? `publishedState:${o.publishedState}` : undefined,\n            o.createDateMin ? `createDateMin:${o.createDateMin.getTime()}` : undefined,\n            o.createDateMax ? `createDateMax:${o.createDateMax.getTime()}` : undefined,\n            o.modifyDateMin ? `modifyDateMin:${o.modifyDateMin.getTime()}` : undefined,\n            o.modifyDateMax ? `modifyDateMax:${o.modifyDateMax.getTime()}` : undefined,\n            o.createdBy ? `createdBy:${o.createdBy}` : undefined,\n            o.trainingSetId ? `trainingSetId:${o.trainingSetId}` : undefined,\n            o.baseModelName ? `baseModelName:${o.baseModelName}` : undefined,\n            o.baseModelVersion ? `baseModelVersion:${o.baseModelVersion}` : undefined,\n            o.category ? `category:${o.category}` : undefined,\n            o.inferenceReady !== undefined ? `inferenceReady:${o.inferenceReady}` : undefined,\n            o.trainingJobId ? `trainingJobId:${o.trainingJobId}` : undefined,\n            o.trainingState ? `trainingState:${o.trainingState}` : undefined,\n            o.trainingSetVersion ? `trainingSetVersion:${o.trainingSetVersion}` : undefined,\n        ].filter(x => x !== undefined).join(':');\n    }\n\n    matches(item: CustomModel) {\n        if (this._listingOptions.publishedState !== undefined && item.publishedState !== this._listingOptions.publishedState) {\n            return false;\n        }\n        if (this._listingOptions.createdBy !== undefined && item.createdBy !== this._listingOptions.createdBy) {\n            return false;\n        }\n        if (this._listingOptions.createDateMin !== undefined && item.created < this._listingOptions.createDateMin) {\n            return false;\n        }\n        if (this._listingOptions.createDateMax !== undefined && item.created > this._listingOptions.createDateMax) {\n            return false;\n        }\n        if (this._listingOptions.modifyDateMin !== undefined && item.modified < this._listingOptions.modifyDateMin) {\n            return false;\n        }\n        if (this._listingOptions.modifyDateMax !== undefined && item.modified > this._listingOptions.modifyDateMax) {\n            return false;\n        }\n        if (this._listingOptions.trainingSetId !== undefined && item.trainingSetInfo.id !== this._listingOptions.trainingSetId) {\n            return false;\n        }\n        if (this._listingOptions.baseModelName !== undefined && item.baseModelName !== this._listingOptions.baseModelName) {\n            return false;\n        }\n        if (this._listingOptions.baseModelVersion !== undefined && item.baseModelVersion !== this._listingOptions.baseModelVersion) {\n            return false;\n        }\n        if (this._listingOptions.category !== undefined && item.category !== this._listingOptions.category) {\n            return false;\n        }\n        if (this._listingOptions.inferenceReady !== undefined && item.inferenceReady !== this._listingOptions.inferenceReady) {\n            return false;\n        }\n        if (this._listingOptions.trainingJobId !== undefined && item.trainingInfo.jobId !== this._listingOptions.trainingJobId) {\n            return false;\n        }\n        if (this._listingOptions.trainingState !== undefined && item.trainingInfo.trainingState !== this._listingOptions.trainingState) {\n            return false;\n        }\n        if (this._listingOptions.trainingSetVersion !== undefined && item.trainingSetInfo.version !== this._listingOptions.trainingSetVersion) {\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * This method determines the commonality between the already present filter (other)\n     * and the new filter to be applied (this). The point of this is to\n     * see if the new filter (this) can build some, all, or none of it's items\n     * from (other) filter.\n     *\n     * Subset: Means that ALL items for this filter can be built from other\n     * Disjoint: No items for this filter can be built from other.\n     * Unknown: Some items for this filter can be built from other.\n     *\n     * @note we should always determine disjoint cases first before other cases.\n     * @note this = NEW FILTER, other = EXISTING FILTER\n     *\n     * @param other The existing filter that we are getting the relation to.\n     * @returns { ItemFilterRelation }\n     */\n    getRelationToFilter(other: CustomModelFilter): ItemFilterRelation {\n        // Simple parameters that can use the generic relation function\n        const simpleParams: (keyof ICustomModelListingOptions)[] = [\n            'publishedState',\n            'createdBy',\n            'trainingSetId',\n            'baseModelName',\n            'baseModelVersion',\n            'category',\n            'inferenceReady',\n            'trainingJobId',\n            'trainingState',\n            'trainingSetVersion'\n        ];\n\n        const relationWrtCreatedAt: ItemFilterRelation = getDateRangeRelation(\n            this._listingOptions.createDateMin,\n            this._listingOptions.createDateMax,\n            other._listingOptions.createDateMin,\n            other._listingOptions.createDateMax);\n\n        const relationWrtModifiedAt: ItemFilterRelation = getDateRangeRelation(\n            this._listingOptions.modifyDateMin,\n            this._listingOptions.modifyDateMax,\n            other._listingOptions.modifyDateMin,\n            other._listingOptions.modifyDateMax);\n\n        const allRelations: ItemFilterRelation[] = [\n            // Simple parameters using generic function\n            ...simpleParams.map(param => this.getRelationForParam(other, param)),\n            // Date range relations\n            relationWrtCreatedAt,\n            relationWrtModifiedAt\n        ];\n\n        //Check for any disjoint cases first\n        if (allRelations.some(x => x === 'disjoint')) {\n            return 'disjoint';\n        }\n\n        //Then check for any unknown cases\n        if (allRelations.some(x => x === 'unknown')) {\n            return 'unknown';\n        }\n\n        //All cases are subset\n        return 'subset';\n    }\n\n    private getRelationForParam(\n        other: CustomModelFilter,\n        paramName: keyof ICustomModelListingOptions\n    ): ItemFilterRelation {\n        if (this._listingOptions[paramName] === other._listingOptions[paramName]) {\n            return 'subset';\n        }\n\n        if (!other._listingOptions[paramName]) {\n            return 'subset';\n        }\n\n        if (!this._listingOptions[paramName]) {\n            return 'unknown';\n        }\n\n        return 'disjoint';\n    }\n\n    getRelationPublishedState(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'publishedState');\n    }\n\n    getRelationCreatedBy(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'createdBy');\n    }\n\n    getRelationTrainingSetId(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'trainingSetId');\n    }\n\n    getRelationBaseModelName(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'baseModelName');\n    }\n\n    getRelationBaseModelVersion(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'baseModelVersion');\n    }\n\n    getRelationCategory(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'category');\n    }\n\n    getRelationInferenceReady(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'inferenceReady');\n    }\n\n    getRelationTrainingJobId(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'trainingJobId');\n    }\n\n    getRelationTrainingState(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'trainingState');\n    }\n\n    getRelationTrainingSetVersion(other: CustomModelFilter): ItemFilterRelation {\n        return this.getRelationForParam(other, 'trainingSetVersion');\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport { SAM } from '@ccx-public/component-types';\nimport type AdobeAsset from '../../src/assets/AdobeAsset';\nimport {\n    GENERATION_HISTORY_VIDEO_MEDIA_TYPE, MEDIA_TO_HISTORY_ASSET_TYPE\n} from '../../src/interface/GenerationHistoryAssetModel';\nimport { ModernSet } from '../../src/utils/ModernSet';\nimport type {\n    IItemFilter,\n    ItemFilterRelation\n} from '../../src/core/ItemFilter';\nimport {\n    getMultiValueFilterRelation,\n    getSingleValueFilterRelation\n} from '../../src/core/ItemFilter';\nimport { SAMError, SAMErrorCode } from '../../src/core/SAMError';\n\n\nexport interface IGenerationHistoryAssetListingOptions {\n    generationGroupId?: string,\n    historyAssetTypes?: SAM.GenerationHistoryAssetType[]\n\n    /**\n    * @deprecated Use historyAssetTypes\n    */\n    historyAssetType?: SAM.GenerationHistoryAssetType,\n}\n\nexport interface GenerationHistoryFeatureFlags {\n    featureFlags?: {\n        generationHistoryVectors?: boolean;\n        generationHistoryAudio?: boolean;\n    }\n}\n\nexport type IGenerationHistoryFilterParams = IGenerationHistoryAssetListingOptions & GenerationHistoryFeatureFlags;\n\nexport default class GenerationHistoryAssetFilter implements IItemFilter<AdobeAsset> {\n    private _generationGroupId?: string;\n    private _historyAssetTypes: SAM.GenerationHistoryAssetType[];\n    private _featureFlags?: { generationHistoryVectors?: boolean, generationHistoryAudio?: boolean };\n\n    constructor(listingOptions?: Partial<IGenerationHistoryFilterParams>) {\n        this._generationGroupId = listingOptions?.generationGroupId;\n        this._featureFlags = listingOptions?.featureFlags;\n\n        let allowedMediaTypes = new ModernSet([\n            SAM.GenerationHistoryAssetType.IMAGE,\n            SAM.GenerationHistoryAssetType.VIDEO,\n            ...(listingOptions?.featureFlags?.generationHistoryVectors ? [ SAM.GenerationHistoryAssetType.VECTOR ] : []),\n            ...(listingOptions?.featureFlags?.generationHistoryAudio ? [ SAM.GenerationHistoryAssetType.AUDIO ] : [])\n        ]);\n\n        if (listingOptions?.historyAssetTypes) {\n            allowedMediaTypes = allowedMediaTypes.intersection(new ModernSet(listingOptions.historyAssetTypes));\n        }\n\n        if (listingOptions?.historyAssetType) {\n            allowedMediaTypes = allowedMediaTypes.intersection(new ModernSet([ listingOptions.historyAssetType ]));\n        }\n\n        this._historyAssetTypes = Array.from(allowedMediaTypes);\n\n        if (this._historyAssetTypes.length === 0) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'GenerationHistoryAssetFilter: No valid history asset types provided.');\n        }\n    }\n\n    get generationGroupId() {\n        return this._generationGroupId;\n    }\n\n    get historyAssetTypes() {\n        return this._historyAssetTypes;\n    }\n\n    get hash(): string {\n        return [\n            this._generationGroupId ? `generationGroupId:${this._generationGroupId}` : undefined,\n            this._historyAssetTypes ? `historyAssetType:${this._historyAssetTypes}` : undefined,\n        ].filter(x => x).join(':');\n    }\n\n    matches(item: AdobeAsset) {\n        if (!this._featureFlags?.generationHistoryAudio) {\n            if (item.mediaType === GENERATION_HISTORY_VIDEO_MEDIA_TYPE && item.appMetadata.data?.firefly?.module === 'SoundFXGeneration') {\n                return false;\n            }\n        }\n\n        if (this._generationGroupId) {\n            return item.appMetadata.data?.firefly?.generationGroupId === this._generationGroupId;\n        }\n\n        return !!this._historyAssetTypes.find(requestedFilterType => {\n            return requestedFilterType === MEDIA_TO_HISTORY_ASSET_TYPE[item.mediaType];\n        });\n    }\n\n    _getGenerationGroupIdRelation(previousGenerationGroupId?: string, newGenerationGroupId?: string): ItemFilterRelation {\n        if (previousGenerationGroupId && newGenerationGroupId && previousGenerationGroupId !== newGenerationGroupId) {\n            return 'disjoint';\n        }\n\n        if (!newGenerationGroupId && previousGenerationGroupId) {\n            return 'unknown';\n        }\n\n        return 'subset';\n    }\n\n    /**\n     * This method determines the commonality between the already present filter (previous)\n     * and the new filter to be applied (this). The point of this is to\n     * see if the new filter (this) can build some, all, or none of it's items\n     * from (previous) filter.\n     *\n     * Subset: Means that ALL items for this filter can be built from previous\n     * Disjoint: No items for this filter can be built from previous.\n     * Unknown: Some items for this filter can be built from previous.\n     *\n     * @note we should always determine disjoint cases first before other cases.\n     * @note this = NEW FILTER, previous = EXISTING FILTER\n     *\n     * @param previousFilter The existing filter that we are getting the relation to.\n     * @returns { ItemFilterRelation }\n     */\n    getRelationToFilter(previousFilter: GenerationHistoryAssetFilter): ItemFilterRelation {\n        // We don't need to test for the feature flags here because the behavior is incorporated into the historyAssetTypes\n        const { _generationGroupId: previousGenerationGroupId,\n            _historyAssetTypes: previousHistoryAssetTypes } = previousFilter;\n        const { _generationGroupId: newGenerationGroupId,\n            _historyAssetTypes: newHistoryAssetTypes } = this;\n\n        const relations: ItemFilterRelation[] = [\n            getSingleValueFilterRelation(newGenerationGroupId, previousGenerationGroupId),\n            getMultiValueFilterRelation(newHistoryAssetTypes, previousHistoryAssetTypes),\n        ];\n\n        if (relations.includes('disjoint')) { return 'disjoint'; }\n        if (relations.includes('unknown')) { return 'unknown'; }\n\n        return 'subset';\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { CustomModelPublishedState } from './LegacyCustomModelModel';\nimport type { IExplicitFilter, ItemFilterRelation } from '../../core/ItemFilter';\nimport { getDateRangeRelation } from '../../core/ItemFilter';\nimport type LegacyCustomModel from './LegacyCustomModel';\n\nexport interface ICustomModelListingOptions {\n    publishedState?: CustomModelPublishedState;\n    createDateMin?: Date;\n    createDateMax?: Date;\n    modifyDateMin?: Date;\n    modifyDateMax?: Date;\n    createdBy?: string;\n}\n\nexport default class CustomModelFilter implements IExplicitFilter<LegacyCustomModel> {\n    private _listingOptions: Partial<ICustomModelListingOptions> = {};\n\n    constructor(listingOptions?: Partial<ICustomModelListingOptions>) {\n        if (listingOptions) {\n            this._listingOptions = listingOptions;\n        }\n    }\n\n    get listingOptions() {\n        return this._listingOptions;\n    }\n\n    get hash(): string {\n        return [\n            this._listingOptions.publishedState ? `publishedState:${this._listingOptions.publishedState}` : undefined,\n            this._listingOptions.createDateMin ? `createDateMin:${this._listingOptions.createDateMin.getTime()}` : undefined,\n            this._listingOptions.createDateMax ? `createDateMax:${this._listingOptions.createDateMax.getTime()}` : undefined,\n            this._listingOptions.modifyDateMin ? `modifyDateMin:${this._listingOptions.modifyDateMin.getTime()}` : undefined,\n            this._listingOptions.modifyDateMax ? `modifyDateMax:${this._listingOptions.modifyDateMax.getTime()}` : undefined,\n            this._listingOptions.createdBy ? `createdBy:${this._listingOptions.createdBy}` : undefined,\n        ].filter(x => x).join(':');\n    }\n\n    matches(item: LegacyCustomModel) {\n        if (this._listingOptions.publishedState\n            && (item.publishedState !== this._listingOptions.publishedState)\n            && this._listingOptions.publishedState !== CustomModelPublishedState.ALL) {\n            return false;\n        }\n\n        if (this._listingOptions.createdBy && (item.createdBy !== this._listingOptions.createdBy)) {\n            return false;\n        }\n\n        if (this._listingOptions.createDateMin && (item.created < this._listingOptions.createDateMin)) {\n            return false;\n        }\n\n        if (this._listingOptions.createDateMax && (item.created > this._listingOptions.createDateMax)) {\n            return false;\n        }\n\n        if (this._listingOptions.modifyDateMin && (item.modified < this._listingOptions.modifyDateMin)) {\n            return false;\n        }\n\n        if (this._listingOptions.modifyDateMax && (item.modified > this._listingOptions.modifyDateMax)) {\n            return false;\n        }\n\n        return true;\n    }\n\n    /**\n     * This method determines the commonality between the already present filter (other)\n     * and the new filter to be applied (this). The point of this is to\n     * see if the new filter (this) can build some, all, or none of it's items\n     * from (other) filter.\n     *\n     * Subset: Means that ALL items for this filter can be built from other\n     * Disjoint: No items for this filter can be built from other.\n     * Unknown: Some items for this filter can be built from other.\n     *\n     * @note we should always determine disjoint cases first before other cases.\n     * @note this = NEW FILTER, other = EXISTING FILTER\n     *\n     * @param other The existing filter that we are getting the relation to.\n     * @returns { ItemFilterRelation }\n     */\n    getRelationToFilter(other: CustomModelFilter): ItemFilterRelation {\n        const relationWrtPublishedState: ItemFilterRelation = this.getRelationPublishedState(other);\n        const relationWrtCreatedBy: ItemFilterRelation = this.getRelationCreatedBy(other);\n\n        const relationWrtCreatedAt: ItemFilterRelation = getDateRangeRelation(\n            this._listingOptions.createDateMin,\n            this._listingOptions.createDateMax,\n            other._listingOptions.createDateMin,\n            other._listingOptions.createDateMax);\n\n        const relationWrtModifiedAt: ItemFilterRelation = getDateRangeRelation(\n            this._listingOptions.modifyDateMin,\n            this._listingOptions.modifyDateMax,\n            other._listingOptions.modifyDateMin,\n            other._listingOptions.modifyDateMax);\n\n        //Check for any disjoint cases first\n        if ([ relationWrtPublishedState, relationWrtCreatedBy, relationWrtCreatedAt, relationWrtModifiedAt ].some(x => x === 'disjoint')) {\n            return 'disjoint';\n        }\n\n        //Then check for any unknown cases\n        if ([ relationWrtPublishedState, relationWrtCreatedBy, relationWrtCreatedAt, relationWrtModifiedAt ].some(x => x === 'unknown')) {\n            return 'unknown';\n        }\n\n        //All cases are subset\n        return 'subset';\n    }\n\n    getRelationPublishedState(other: CustomModelFilter): ItemFilterRelation {\n        if (this._listingOptions.publishedState === other._listingOptions.publishedState) {\n            return 'subset';\n        }\n\n        if (other._listingOptions.publishedState === CustomModelPublishedState.ALL || other._listingOptions.publishedState === undefined) {\n            return 'subset';\n        }\n\n        if (this._listingOptions.publishedState === CustomModelPublishedState.ALL || this._listingOptions.publishedState === undefined) {\n            return 'unknown';\n        }\n\n        return 'disjoint';\n    }\n\n    getRelationCreatedBy(other: CustomModelFilter): ItemFilterRelation {\n        if (this._listingOptions.createdBy === other._listingOptions.createdBy) {\n            return 'subset';\n        }\n\n        if (!other._listingOptions.createdBy) {\n            return 'subset';\n        }\n\n        if (!this._listingOptions.createdBy) {\n            return 'unknown';\n        }\n\n        return 'disjoint';\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport type { default as Space, SpaceState, TeamRole } from './Space';\n\nexport interface ISpaceFilterOptions {\n    readonly bookmarked?: boolean;\n    readonly teamID?: string;\n    readonly state?: SpaceState;\n\n    /**\n     * Undefined -> returns all spaces, regardless of the role on the parent team.\n     * 'NONE' -> Returns only the spaces from teams the user IS NOT part of\n     * (ie. the role of the user on those team is none).\n     *\n     * In the future we may add a value of 'MEMBER' to return only the spaces from teams the\n     * user IS part of. However, that feature is not supported by the server at the moment,\n     * so we are not exposing that value yet.\n     */\n    readonly teamRole?: TeamRole;\n}\n\nexport default class SpaceFilter implements IExplicitFilter<Space> {\n\n    private _bookmarked: boolean = false;\n    private _teamID?: string;\n    private _state?: SpaceState;\n    private _teamRole?: TeamRole;\n\n    constructor(options?: Partial<ISpaceFilterOptions>) {\n        this._bookmarked = Boolean(options?.bookmarked);\n        this._teamID = options?.teamID;\n        this._teamRole = options?.teamRole;\n        this._state = options?.state;\n        this._teamRole = options?.teamRole;\n    }\n\n    static ActiveSpaces = new SpaceFilter({\n        state: 'active'\n    });\n\n    static ArchivedSpaces = new SpaceFilter({\n        state: 'archived'\n    });\n\n    static ActiveBookmarkedSpaces = new SpaceFilter({\n        state: 'active',\n        bookmarked: true\n    });\n\n    static ActiveSpacesFromOtherTeams = new SpaceFilter({\n        state: 'active',\n        teamRole: 'NONE'\n    });\n\n    static ActiveSpacesFromTeam(teamID: string) {\n        return new SpaceFilter({\n            state: 'active',\n            teamID\n        });\n    }\n\n    get bookmarked(): boolean {\n        return this._bookmarked;\n    }\n\n    get teamID(): string | undefined {\n        return this._teamID;\n    }\n\n    get teamRole(): TeamRole | undefined {\n        return this._teamRole;\n    }\n\n    get state(): SpaceState | undefined {\n        return this._state;\n    }\n\n    get hash(): string {\n        return String(this.bookmarked) + ':'\n            + (this.teamID || 'all-teams') + ':'\n            + (this._teamRole ?? 'all-roles') + ':'\n            + (this._state ?? 'any-state');\n    }\n\n    matches(item: Space): boolean {\n        if (this._bookmarked && !item.isBookmarked) {\n            return false;\n        }\n        const teamID = this._teamID;\n        if (teamID && item.teamID !== teamID) {\n            return false;\n        }\n\n        const teamRole = this._teamRole;\n        if (teamRole && item.teamRole !== teamRole) {\n            return false;\n        }\n\n        const state = this._state;\n        if (state && state !== item.state) {\n            return false;\n        }\n\n        return true;\n    }\n\n    getRelationToFilter(other: SpaceFilter): ItemFilterRelation {\n        const otherSpaceFilter = other as SpaceFilter;\n\n        if (this._teamRole !== otherSpaceFilter._teamRole) {\n            if (this._teamRole && otherSpaceFilter._teamRole) {\n                // If both filters specify a completely different teamRole then the\n                // lists are entirely disjoint.\n                return 'disjoint';\n            }\n            // If only one filter specifically looks for the team role, then the other might be\n            // able to borrow some items from it.\n            return 'unknown';\n        }\n\n        if (this.teamID && otherSpaceFilter.teamID && this.teamID !== otherSpaceFilter.teamID) {\n            // Teams are entirely different, no shared elements are expected.\n            return 'disjoint';\n        }\n\n        if (!this.teamID && otherSpaceFilter.teamID) {\n            // If the other list has a teamID and this filter doesn't then\n            // this is list is going to have an unknown final state.\n            return 'unknown';\n        }\n\n        // If the other list filtered for only bookmarked items and this doesn't,\n        // then this is list is going to have an unknown final state.\n        if (!this.bookmarked && other.bookmarked) {\n            return 'unknown';\n        }\n\n        if (this._state !== other._state) {\n            // If both filters expect a state and the states do not match, then\n            // the lists are not going to have any items in common.\n            if (this._state && other._state) {\n                return 'disjoint';\n            }\n            // If only one list expects a specific state and the other can take any state,\n            // then we could possible share some items.\n            return 'unknown';\n        }\n\n        return 'subset';\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n\nimport type { IExplicitFilter, ItemFilterRelation } from '../core/ItemFilter';\nimport type { default as Team, TeamState } from './Team';\nimport whitespaceFilter from '../utils/whitespaceFilter';\n\nexport interface ITeamFilterOptions {\n    readonly nameContains?: string;\n    readonly state?: TeamState;\n}\n\nenum StringRelationResult {\n    DISJOINTED,\n    SUPERSET,\n    SUBSET,\n    UNKNOWN,\n    IDENTICAL\n}\n\n/**\n * Available when M2 is released, M1 currently\n * does not support this filter.\n * @experimental\n */\nexport default class TeamFilter implements IExplicitFilter<Team> {\n    private _nameContains?: string;\n    private _state?: TeamState;\n\n    constructor(options?: Partial<ITeamFilterOptions>) {\n        this._nameContains = options?.nameContains;\n        this._state = options?.state;\n    }\n\n    static TeamsContainingName(name: string) {\n        return new TeamFilter({\n            nameContains: name\n        });\n    }\n\n    static ActiveTeams = new TeamFilter({\n        state: 'active'\n    });\n\n    static DiscardedTeams = new TeamFilter({\n        state: 'discarded'\n    });\n\n    get nameContains(): string | undefined {\n        return this._nameContains;\n    }\n\n    get state(): TeamState | undefined {\n        return this._state;\n    }\n\n    get hash(): string {\n        return (this._nameContains ?? 'any-name') + ':'\n            + (this._state ?? 'any-state');\n    }\n\n    private _getRelationToNameContains(name: string, otherName: string): StringRelationResult {\n        if (name === otherName) {\n            return StringRelationResult.IDENTICAL;\n        }\n        const nameTerms = name.toLowerCase()\n            .split(' ').filter(whitespaceFilter).sort();\n        const otherNameTerms = otherName.toLowerCase()\n            .split(' ').filter(whitespaceFilter).sort();\n\n        if (nameTerms.length === 0 && otherNameTerms.length === 0) {\n            return StringRelationResult.IDENTICAL;\n        }\n\n        if (nameTerms.length === 0 || otherNameTerms.length === 0) {\n            return StringRelationResult.DISJOINTED;\n        }\n\n        if (nameTerms.length === otherNameTerms.length\n            && nameTerms.every(\n                (n, i) => n === otherNameTerms[i]\n            )) {\n            return StringRelationResult.IDENTICAL;\n        }\n\n        let subsetMatches = 0;\n        let supersetMatches = 0;\n\n        nameTerms.forEach((nameTerm) => {\n            const findMatch = otherNameTerms.find((otherTerm) => {\n                const superSet = otherTerm.startsWith(nameTerm);\n                const subSet = nameTerm.startsWith(otherTerm);\n                return superSet || subSet;\n            });\n\n            if (findMatch) {\n                if (nameTerm.length <= findMatch.length) {\n                    supersetMatches++;\n                }\n\n                if (nameTerm.length > findMatch.length) {\n                    subsetMatches++;\n                }\n            }\n        });\n\n        if (nameTerms.length === subsetMatches) {\n            return StringRelationResult.SUBSET;\n        }\n\n        if (nameTerms.length === supersetMatches) {\n            return StringRelationResult.SUPERSET;\n        }\n\n        if (subsetMatches === 0 && supersetMatches === 0) {\n            return StringRelationResult.DISJOINTED;\n        }\n\n        return StringRelationResult.UNKNOWN;\n    }\n\n    private _searchTarget(searchString: string, targetString: string): boolean {\n        const searchTerms = searchString.toLowerCase()\n            .split(' ').filter(whitespaceFilter);\n        const targetTerms = targetString.toLowerCase()\n            .split(' ').filter(whitespaceFilter);\n\n        // Empty word or search term\n        if (searchTerms.length === 0 || targetTerms.length === 0) {\n            return false;\n        }\n\n        return searchTerms.every((searchTerm) => {\n            return targetTerms.find((targetTerm) => {\n                return targetTerm.startsWith(searchTerm);\n            });\n        });\n    }\n\n    matches(item: Team): boolean {\n        const state = this._state;\n        if (state && state !== item.state) {\n            return false;\n        }\n\n        const nameContains = this._nameContains;\n        if (nameContains\n            && !this._searchTarget(nameContains, item.name)\n        ) {\n            return false;\n        }\n\n        return true;\n    }\n\n    getRelationToFilter(other: TeamFilter): ItemFilterRelation {\n        let searchMatch;\n        if (this.nameContains && other.nameContains) {\n            searchMatch = this._getRelationToNameContains(this.nameContains, other.nameContains);\n            if (searchMatch === StringRelationResult.DISJOINTED) {\n                return 'disjoint';\n            }\n        }\n\n        if (this.state && other.state && this.state !== other.state) {\n            return 'disjoint';\n        }\n\n        if (!this.state && other.state) {\n            return 'unknown';\n        }\n\n        if (!this.nameContains && other.nameContains) {\n            return 'unknown';\n        }\n\n        if (searchMatch && searchMatch === StringRelationResult.SUPERSET\n            || searchMatch === StringRelationResult.UNKNOWN\n        ) {\n            return 'unknown';\n        }\n\n        //------ All 'unknown' cases must be handled above this line\n        return 'subset';\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { observable } from '../core/decorators';\nimport ShareableItem from '../collaboration/ShareableItem';\nimport type { IProjectsCreateData, IProjectsTeam, IProjectsTeamLinks, IProjectsTeamState } from '../interface/WorkspacesModel';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { CollaboratorRole } from '../collaboration/Collaborator';\nimport { CollaboratorRoles } from '../collaboration/Collaborator';\nimport type Space from './Space';\nimport type { ITeamUpdate } from './SpaceContext';\nimport oneTimeWarning from '../utils/oneTimeWarning';\n\nexport type RepositoryOwnerType =\n    | 'org'\n    | 'user';\n\nconst RepositoryOwnerTypes: RepositoryOwnerType[]  = [ 'org', 'user' ];\n\nexport type TeamState = IProjectsTeamState;\nconst TeamStates: TeamState[] = [ 'active', 'discarded' ];\n\n/**\n * Represents the notion of a \"team\" of Adobe account\n * holders that collaborate on projects.\n *\n * @example\n * // Instatiate list and load contents\n * const teamsList = core.spaceContext.getTeams().getList(...options);\n * await waitForListLoad(teamsList);\n *\n * // Get the first team in the list as an example.\n * const team = teamsList.items[0];\n *\n * // Perform some actions on a team.\n * await team.rename('newName');\n * await team.archive();\n * await team.restore();\n *\n * // log the teamID\n * console.log(team.teamID)\n *\n */\nexport default class Team extends ShareableItem {\n\n    private _created: Date = new Date();\n    private _createdBy: string = '';\n    private _description?: string;\n    private _name: string = '';\n    private _repositoryID: string = '';\n    private _repositoryName: string = '';\n    private _repositoryOwnerID: string | undefined;\n    private _repositoryOwnerEmail: string | undefined;\n    private _repositoryOwnerType: RepositoryOwnerType | undefined;\n    private _state: TeamState = 'active';\n    private _role: CollaboratorRole = 'none';\n    private __links: IProjectsTeamLinks | undefined;\n\n    /**\n     * The unique id that represents the team.\n     */\n    get teamID(): string {\n        return this.id;\n    }\n\n    @observable\n    get created(): Date {\n        return this._created;\n    }\n\n    @observable\n    get createdBy(): string {\n        return this._createdBy;\n    }\n\n    /**\n     * The user-visible name assigned to the team\n     */\n    @observable\n    get name(): string {\n        return this._name;\n    }\n\n    /**\n     * The description property of this team.\n     *\n     * @note Only available after a call to ensureDescription()\n     */\n    @observable\n    get description(): string | undefined {\n        return this._description;\n    }\n\n    /**\n     * The unique id of the repository that owns this team\n     */\n    @observable\n    get repositoryID(): string {\n        return this._repositoryID;\n    }\n\n    /**\n     * The user-visible name of the repository (i.e. the organization name)\n     * that owns this team\n     */\n    @observable\n    get repositoryName(): string {\n        return this._repositoryName;\n    }\n\n    @observable\n    get repositoryOwnerID(): string | undefined {\n        return this._repositoryOwnerID;\n    }\n\n    @observable\n    get repositoryOwnerEmail(): string | undefined {\n        return this._repositoryOwnerEmail;\n    }\n\n    @observable\n    get repositoryOwnerType(): RepositoryOwnerType | undefined {\n        return this._repositoryOwnerType;\n    }\n\n    /**\n     * The role or permissions of the user for this team.\n     * 'editor' and 'owner' are combined for backward\n     * compatibility.\n     * @deprecated Use 'role' instead.\n     */\n    @observable\n    get collaboratorRole(): CollaboratorRole {\n        oneTimeWarning(\n            'collaboratorRoleDeprecated',\n            'The property collaboratorRole has been depecrated in favor of role.'\n        );\n        return this._role === 'owner'\n            ? 'editor' : this._role;\n    }\n\n    /**\n     * The role or permissions of the user for this team.\n     * can be any of the following values: 'editor', 'viewer'\n     * 'owner'.\n     *\n     * @note The 'viewer' role is not set in any workflow currently.\n     */\n    @observable\n    get role(): CollaboratorRole {\n        return this._role;\n    }\n\n    @observable\n    get state(): TeamState {\n        return this._state;\n    }\n\n    /**\n     * The links provided by the service for this team.\n     *\n     * @private\n     */\n    @observable\n    get _links(): IProjectsTeamLinks | undefined {\n        return this.__links;\n    }\n\n    /**\n     * Archive/Discard team\n     *\n     * @NOTE Currently there are some inconsistencies in how the API's are\n     * named within Projects\n     * Team API uses “discarded”, Project API uses “archived”\n     */\n    async archive(): Promise<void> {\n        await this._core.spaceContext.archiveTeam(this);\n    }\n\n    /**\n     * Create a space for this team.\n     *\n     * @param data {IProjectsCreateData}\n     */\n    async createSpace(data: IProjectsCreateData): Promise<Space> {\n        return await this._core.spaceContext.createSpace(this, data);\n    }\n\n    /**\n     * Permanently Delete a Team that has already been discarded.\n     *\n     */\n    async permanentlyDelete(): Promise<void> {\n        await this._core.spaceContext.permanentlyDeleteTeam(this);\n    }\n\n    /**\n     * Rename this Team.\n     *\n     * @param newName\n     */\n    async rename(newName: string): Promise<void> {\n        await this._core.spaceContext.renameTeam(this, newName);\n    }\n\n    /**\n     * Restore this Team\n     */\n    async restore(): Promise<void> {\n        await this._core.spaceContext.restoreTeam(this);\n    }\n\n    /**\n     * Update properties on this team\n     */\n    async update(data: ITeamUpdate): Promise<void> {\n        await this._core.spaceContext.updateTeam(this, data);\n    }\n\n    /**\n     * Ensures the description is loaded and available\n     * on a team.\n     */\n    async ensureDescription(): Promise<void> {\n        await this._core.spaceContext.loadTeamProperties(this);\n    }\n}\n\nexport const TeamUpdater = new ItemUpdater<Team, Partial<IProjectsTeam>>({\n    localItemType: Team,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_created': { name: 'createDate', format: 'date' },\n        '_createdBy': 'createdBy',\n        '_description': 'description',\n        '_name': 'name',\n        '_repositoryID': 'repositoryId',\n        '_repositoryName': 'repositoryName',\n        '_repositoryOwnerID': 'repositoryOwner.id',\n        '_repositoryOwnerEmail': 'repositoryOwner.email',\n        '_repositoryOwnerType': { name: 'repositoryOwner.type', choices: RepositoryOwnerTypes },\n        '_role': { name: 'role', choices: CollaboratorRoles },\n        '_state': { name: 'state', choices: TeamStates },\n        '__links': { name: '_links', format: 'object' }\n    })\n});\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\n\nimport type {\n    IComparatorMap\n} from '../core/ItemOrder';\nimport {\n    compareStrings,\n    createItemOrderFactory\n} from '../core/ItemOrder';\nimport type AddressBookContact from './AddressBookContact';\n\nconst OrderFieldToComparator: IComparatorMap<AddressBookContact, 'displayName'> = {\n    displayName(a: AddressBookContact, b: AddressBookContact): number {\n        // List is sorted in order returned by service\n        return compareStrings(a.displayName, b.displayName);\n    }\n};\n\nexport default class AddressBookContactOrder extends createItemOrderFactory(OrderFieldToComparator) {\n    static default = new AddressBookContactOrder('ascending', 'displayName');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport ItemUpdater from '../core/ItemUpdater';\nimport ItemBase from '../core/ItemBase';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport type { IGradientColorRGB, IGradientColorStop, IGradientComputedItemResponse } from '../interface/GradientModel';\n\nexport class Gradient extends ItemBase implements SAM.Gradient {\n    private _isDefault: boolean = false;\n    private _type: string = '';\n    private _angle: number = 0;\n    private _stops: IGradientColorStop[] = [];\n    private _name: string = '';\n    private _languageCode: string = '';\n    private _gradientID: string = '';\n    private _textAlpha: number = 1;\n    private _textMode: string = 'RGB';\n    private _textColorValue: IGradientColorRGB = { r: 0, g: 0, b: 0 };\n    private _textType: string | 'process' = 'process';\n\n    get isDefault() {\n        return this._isDefault;\n    }\n\n    get type(): string {\n        return this._type;\n    }\n\n    get angle(): number {\n        return this._angle;\n    }\n\n    get stops(): IGradientColorStop[] {\n        return this._stops;\n    }\n\n    get name(): string {\n        return this._name;\n    }\n\n    get languageCode(): string {\n        return this._languageCode;\n    }\n\n    /**\n     * The original non-computed gradient ID to be used when\n     * assigning a gradient to a Project.\n     */\n    get gradientID(): string {\n        return this._gradientID;\n    }\n\n    get textAlpha(): number {\n        return this._textAlpha;\n    }\n\n    get textMode(): string {\n        return this._textMode;\n    }\n\n    get textColorValue(): IGradientColorRGB {\n        return this._textColorValue;\n    }\n\n    get textType(): 'process' | string {\n        return this._textType;\n    }\n}\n\nexport const GradientUpdater = new ItemUpdater<Gradient, Partial<IGradientComputedItemResponse>>({\n    localItemType: Gradient,\n    /**\n     * The computedID is property that is computed based on the\n     * gradientId from the service, and the language code from the service.\n     * It typically looks something like. 'FUSCHIA-en-US'. This helps\n     * us store and retrieve the gradients by not just id but also language to\n     * make it more performant if the user switches languages during runtime.\n     * IGradientComputedItemResponse extends IGradientItemResponse to include\n     * the computedID property.\n     */\n    remoteIdProperty: 'computedID',\n    propertyUpdater: new PropertyUpdater({\n        '_isDefault': { name: 'project:gradientData.isDefault', format: 'boolean' },\n        '_type': { name: 'project:gradientData.type', format: 'string' },\n        '_angle': { name: 'project:gradientData.angle', format: 'string' },\n        '_name': { name: 'project:gradientName', format: 'string' },\n        '_stops': { name: 'project:gradientData.stops', format: 'object' },\n        '_languageCode': { name: 'project:gradientData.languageCode', format: 'string' },\n        '_gradientID': 'project:gradientId',\n        '_textAlpha': { name: 'project:gradientTextColor.alpha', format: 'number' },\n        '_textMode': { name: 'project:gradientTextColor.mode', format: 'string' },\n        '_textColorValue': { name: 'project:gradientTextColor.value', format: 'object' },\n        '_textType': { name: 'project:gradientTextColor.type', format: 'string' }\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMEvent from '../core/SAMEvent';\n\nexport const FRAMEIO_AUTHORIZATION_CHANGE = 'frameioAuthorizationChange';\n\nexport default class FrameioAuthorizationChangeEvent extends SAMEvent {\n    constructor() {\n        super(FRAMEIO_AUTHORIZATION_CHANGE);\n    }\n}\n\nexport const SharedFrameioAuthorizationChangeEvent = new FrameioAuthorizationChangeEvent();\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMEvent from '../core/SAMEvent';\n\nexport const FRAMEIO_REVIEW_LINKS_CHANGE = 'frameioReviewLinksChange';\n\nexport default class FrameioReviewLinksChangeEvent extends SAMEvent {\n    constructor() {\n        super(FRAMEIO_REVIEW_LINKS_CHANGE);\n    }\n}\n\nexport const SharedFrameioReviewLinksChangeEvent = new FrameioReviewLinksChangeEvent();\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport InterfaceBase from '../interface/InterfaceBase';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport UriTemplate from 'uri-templates';\nimport LinkHeader from 'http-link-header';\nimport type { IFetchOptions } from '../core/Environment';\nimport { NotFound } from '../core/Cache';\nimport { millisecondsPerHour, secondsPerHour } from '../core/ObjectUtils';\nimport type { FrameioSourceDocument } from './FrameioContext';\nimport type FrameioContext from './FrameioContext';\nimport { FRAMEIO_AUTHORIZATION_CHANGE, SharedFrameioAuthorizationChangeEvent } from './FrameioAuthorizationChangeEvent';\nimport { FRAMEIO_REVIEW_LINKS_CHANGE } from './FrameioReviewLinksChangeEvent';\n\n// Consolidate Frame.io links used by FrameioInterface into\n// templated urls\nconst FRAMEIO_API_BASE = 'https://api.frame.io';\nconst FRAMEIO_LINKS = {\n    ME: `${FRAMEIO_API_BASE}/v2/me`,\n    ACCOUNT: `${FRAMEIO_API_BASE}/v2/accounts/{accountId}`,\n    ACCOUNTS: `${FRAMEIO_API_BASE}/v2/accounts?join=collaborator`,\n    TEAMS: `${FRAMEIO_API_BASE}/v2/accounts/{accountId}/teams?include=user_role&role=member`,\n    TEAM: `${FRAMEIO_API_BASE}/v2/teams/{teamId}?include=account`,\n    PROJECT: `${FRAMEIO_API_BASE}/v2/projects/{projectId}?include=string`,\n    PROJECTS: `${FRAMEIO_API_BASE}/v2/teams/{teamId}/projects?filter[archived]`,\n    SHAREDPROJECTS: `${FRAMEIO_API_BASE}/v2/projects/shared?filter[account_id]={accountId}`,\n    REVIEWS: `${FRAMEIO_API_BASE}/v2/projects/{projectId}/review_links`,\n    REVIEW: `${FRAMEIO_API_BASE}/v2/review_links/{reviewLinkId}`,\n    ITEMCREATE: `${FRAMEIO_API_BASE}/v2/review_links/{reviewLinkId}/assets`,\n    ASSETS: `${FRAMEIO_API_BASE}/v2/assets/{assetId}/children?include=cover_asset`,\n    ASSET: `${FRAMEIO_API_BASE}/v2/assets/{assetId}?type=folder&include=cover_asset`,\n    CREATEASSET: `${FRAMEIO_API_BASE}/v2/assets/{parentId}/children`,\n    VERSION: `${FRAMEIO_API_BASE}/v2/assets/{assetId}/version`,\n    CREATECOMMENT: `${FRAMEIO_API_BASE}/v2/assets/{assetId}/comments`,\n    GETCOMMENT: `${FRAMEIO_API_BASE}/v2/comments/{commentId}?include=string`,\n    GETCOMMENTS: `${FRAMEIO_API_BASE}/v2/assets/{assetId}/comments?include=string`,\n    IMPRESSIONS: `${FRAMEIO_API_BASE}/v2/comments/{commentId}/impressions?include=string`,\n    COMMENT: `${FRAMEIO_API_BASE}/v2/comments/{commentId}`,\n    REPLY: `${FRAMEIO_API_BASE}/v2/comments/{commentId}/replies`,\n    GETREPLIES: `${FRAMEIO_API_BASE}/v2/comments/{commentId}/replies?include=replies`,\n    LIKE: `${FRAMEIO_API_BASE}/v2/comments/{commentId}/like`,\n    COMPLETE: `${FRAMEIO_API_BASE}/v2/comments/{commentId}/complete`,\n    FOLDERTREE: `${FRAMEIO_API_BASE}/v2/projects/{projectId}/folder_tree`,\n    ANCESTORS: `${FRAMEIO_API_BASE}/v2/assets/{assetId}/ancestors`,\n    ADOBE_SUSI_USER: `${FRAMEIO_API_BASE}/v2/auth/adobe/method`,\n    ADOBE_SUSI: `${FRAMEIO_API_BASE}/v2/auth/adobe/callback`\n};\n\nfunction fillURLTemplate(url: string, params: any) {\n    // such as fillURLTemplate('v2/accounts/{accountId}', { \"accountId\": \"id-for-account\"})\n    const template = UriTemplate(url);\n    return template.fill(params);\n}\n\nexport interface FrameioNativeAuthenticationInfo {\n    adobeId: string;\n    ccUserId: string;\n    productKey: string;\n    xFrameioClient: string;\n\n    // The native code ignores the remaining properties when (!frameioToken),\n    // and it requires them all when (frameioToken)\n    // !!@ Consider grouping them in an interface, so this all or nothing\n    // aspect could be captured by the API.\n    frameioToken?: string;\n    frameioRefreshToken?: string;\n    frameioTokenExpires?: string;\n    frameioUserId?: string;\n    frameioLastRefresh?: string;\n}\n\nexport enum IFrameioAuthenticationStatus {\n    authLoggedOut,\n    authLoggedIn,\n    authExpired\n}\n\nexport interface IFrameioFileHandle {\n    close(): Promise<void>;\n    size(): number;\n    read(srcOffset?: number, destBuffer?: ArrayBuffer): Promise<ArrayBuffer>;\n}\n\n// Some Frame.io methods are implemented with native code\nexport interface IFrameioNativeContext {\n    authenticateUser(info: FrameioNativeAuthenticationInfo): Promise<string>;\n    deauthenticateUser(userid: string): Promise<void>;\n    isUserAuthenticated(userid: string): boolean;\n    authenticationStatus(userid: string): IFrameioAuthenticationStatus;\n    authenticationInfo(): FrameioNativeAuthenticationInfo;\n    getToken(forceRefresh?: boolean): Promise<string>;\n    openFile(filename: string): IFrameioFileHandle;\n    addEventListener(name: string, listener: any): void;\n    removeEventListener(name: string, listener: any): void;\n    dispatchReviewLinksChangeEvent(json: string): void;\n}\n\n// See https://developer.frame.io/api/reference/operation/getMe/\n//  for schema of a user\nexport interface IFrameioUserResponse {\n    _type: string;\n    account_id: string;\n    bio: any;\n    context: any;\n    deleted_at: any; // ISO Date\n    digest_frequency: string;\n    email: string;\n    email_confirm_by: any;\n    email_preferences: any;\n    features_seen: any;\n    first_login_at: string;\n    from_google: boolean;\n    id: string;\n    image_128: string;\n    image_256: string;\n    image_32: string;\n    image_64: string;\n    inserted_at: string;\n    joined_via: string;\n    last_seen: string;\n    location: any;\n    mfa_enforced_at: string;\n    name: string;\n    next_digest_date: string;\n    phone: any;\n    profile_image: string;\n    profile_image_original: any;\n    roles: any;\n    timezone_value: string;\n    updated_at: string;\n    upload_url: string;\n    user_default_color: string;\n    user_hash: string;\n}\n\n// See https://developer.frame.io/api/reference/operation/getAccount/\n//  for schema of an account\nexport interface IFrameioAccountResponse {\n    _type: string;\n    account_default_color: string;\n    account_settings: any;\n    account_members: IFrameioAccountMemberResponse[];\n    archived_storage: number;\n    available_features: any;\n    billing_emails: string;\n    city: string;\n    collaborator_count: number;\n    collaborator_role_count: number;\n    company_address: string;\n    company_name: string;\n    country: string;\n    deleted_at: string;\n    delinquent_at: string;\n    display_name: string;\n    drm_configuration_id: string;\n    duration: number;\n    file_count: number;\n    folder_count: number;\n    frames: number;\n    id: string;\n    image: string;\n    image_128: string;\n    image_256: string;\n    image_32: string;\n    image_64: string;\n    inserted_at: string;\n    invoice_emails: string[];\n    lifetime_file_count: number;\n    line1: string;\n    line2: string;\n    locked_at: string;\n    member_count: number;\n    mfa_enforced_at: string;\n    owner: IFrameioUserResponse\n    owner_id: string;\n    plan: IFrameioPlanResponse;\n    postal_code: string;\n    project_count: number;\n    state: string;\n    storage: number;\n    subscription: IFrameioSubscriptionResponse;\n    team_count: number;\n    teams: IFrameioTeamResponse[];\n    unpaid_at: string;\n    updated_at: string;\n    upload_url: string;\n    user_count: number;\n    vat: string;\n    version: number;\n    watermark: IFrameioWatermarkResponse;\n}\n\n// See https://developer.frame.io/api/reference/operation/getTeam/\n//  for schema of a team\nexport interface IFrameioTeamResponse {\n    account_id: string,\n    disable_sbwm_internally: boolean,\n    creator_id: string,\n    storage: number,\n    default_font_color: string,\n    access: FrameioTeamAccess,\n    font_color: string,\n    // @TODO replace any\n    user_role: any,\n    file_count: number,\n    // @TODO replace any\n    default_session_watermark_template: any;\n    link: string;\n    asset_lifecycle_policy: number;\n    upload_url: string;\n    // @TODO replace any\n    admin_only_actions: any;\n    deleted_at: string,\n    default_background_color: string,\n    storage_limit: number,\n    location: string,\n    name: string,\n    default_color: string,\n    // @TODO replace any\n    slack_webhook: any,\n    image_64: string,\n    archived_storage: number,\n    image_128: string,\n    solo: false,\n    // @TODO replace any\n    account: any,\n    image_32: string,\n    inserted_at: string,\n    updated_at: string,\n    project_count: number,\n    duration: number,\n    team_image: string,\n    collaborator_count: number,\n    bio: string,\n    // @TODO replace any\n    watermark: any;\n    color: string;\n    // @TODO replace any\n    email_branding: any;\n    folder_count: number;\n    dark_theme: boolean;\n    id: string;\n    member_limit: number;\n    frames: number;\n    member_count: number;\n    image_256: string;\n    background_color: string;\n    _type: string;\n}\n\n// See https://developer.frame.io/api/reference/operation/getProject/\n//  for schema of a project\nexport interface IFrameioProjectResponse {\n    _type: string;\n    archive_status: string;\n    archived_at: string;\n    archived_file_count: number;\n    archived_storage: number;\n    collaborator_count: number;\n    deleted_at: string;\n    description: string;\n    file_count: number;\n    folder_count: number;\n    id: string;\n    ignore_archive: boolean;\n    inserted_at: string;\n    invite_url: string;\n    name: string;\n    owner_id: string;\n    private: boolean;\n    project_preferences: any;\n    read_only: boolean;\n    root_asset: any; /* IFrameioAssetResponse */ /* folder */\n    root_asset_id: string;\n    shared: boolean;\n    storage: number;\n    team: IFrameioTeamResponse;\n    team_id: string;\n    updated_at: string;\n    user_permissions: any;\n    user_preferences: any;\n    watermark: any;\n}\n\n// See https://developer.frame.io/api/reference/operation/reviewLinkGet/\n//  for schema of a review\nexport interface IFrameioReviewLinkResponse {\n    access_control: Partial<IFrameioAccessControlResponse>;\n    allow_approvals: boolean;\n    available_features: any;\n    bundle_count: number;\n    current_version_only: boolean;\n    deleted_at: string;\n    enable_comments: boolean;\n    enable_downloading: boolean;\n    expires_at: string;\n    folder_item_count: number;\n    has_password: boolean;\n    id: string;\n    inserted_at: string;\n    is_active: boolean;\n    is_autoplay: boolean;\n    item_count: number;\n    items: any; /* Array<ReviewLinkItem> */\n    name: string;\n    notify_on_view: boolean;\n    owner: any; /* IFrameioUserResponse */\n    owner_id: string;\n    password: string;\n    project: any /* IFrameioProjectResponse */\n    project_id: string;\n    reviewer_count: number;\n    short_url: string;\n    team: any /* IFrameioTeamResponse */\n    updated_at: string;\n    view_count: number;\n    _type: string;\n\n    // these come from the Review Service, and not Frame.io\n    'frameio:artifactId': string;\n    'repo:etag': string;\n}\n\n\n// See https://developer.frame.io/api/reference/operation/getAsset/\n//  for schema of an asset - type is one of { file, folder, version_stack, bundle }\nexport interface IFrameioAssetResponse {\n    _type: string;\n    account_id: string;\n    allow_original_playback: boolean;\n    archive_from: string;\n    asset_type: string;\n    cover_asset: any;\n    comment_count: number;\n    cover_asset_id: string;\n    creator: IFrameioUserResponse;\n    creator_id: string;\n    deleted_at: string;\n    filesize: number;\n    filetype: string;\n    frames: number;\n    hard_deleted_at: string;\n    id: string;\n    index: number;\n    inserted_at: string;\n    is_hls_required: boolean;\n    is_session_watermarked: boolean;\n    item_count: number;\n    label: string;\n    metadata: any;\n    metadata_flags: any;\n    name: string;\n    original: string;\n    parent_id: string | null;\n    project_id: string;\n    properties: any; /* accepts arbitrary key/value pairs ... can we use this ? */\n    required_transcodes: any;\n    team_id: string;\n    type: string;\n    updated_at: string;\n    uploaded_at: string;\n    upload_urls: string[];\n    user_permissions: any;\n    versions: number;\n    view_count: number;\n}\n\nexport interface IFrameioCommentResponse {\n    _type: string;\n    annotation: string;\n    anonymous_user_id: string;\n    aspect_ratio: number;\n    asset_id: string;\n    comment_entities: any; // [] ??\n    completed: boolean;\n    completed_at: string;\n    completer_id: string;\n    deleted_at: string;\n    device_channel_input_id: string;\n    duration: string;\n    fov: number;\n    frame: string;\n    has_replies: boolean;\n    id: string;\n    inserted_at: string;\n    like_count: number;\n    owner: IFrameioUserResponse;\n    owner_id: string;\n    page: string;\n    parent_id: string;\n    pitch: number;\n    private: boolean;\n    read_count: number;\n    review_link_id: string;\n    target_asset_id: string;\n    text: string;\n    text_edited_at: string;\n    thumb: any;\n    timestamp: number;\n    timestamp_microseconds: number;\n    updated_at: string;\n    yaw: any;\n}\n\nexport interface IFrameioLikeResponse {\n    _type: string;\n    anonymous_user_id: string;\n    comment: IFrameioCommentResponse;\n    comment_id: string;\n    deleted_at: string;\n    id: string;\n    inserted_at: string;\n    type: string;\n    updated_at: string;\n    user_id: string;\n}\n\n\nexport interface IFrameioImpressionResponse {\n    assetId: string;\n    count: number;\n    deleted_at: string;\n    id: string;\n    inserted_at: string;\n    review_link_id: string;\n    type: string;\n    updated_at: string;\n    user: IFrameioUserResponse;\n    user_id: string;\n}\n\nexport interface IFrameioFolderTreeFolderResponse {\n    id: string;\n    name: string;\n    parent_id: string | null;\n}\n\nexport interface IFrameioOwnerResponse {\n    email: string;\n}\n\n// Response format from Frame.io's SUSI(Single User Sign In) availability.\nexport interface IFrameioAdobeSusiUserResponse {\n    _type: string;\n    exists: boolean;\n    id: string | null;\n    method: string;\n    restriction: string | null;\n}\n\n// Response format from Frame.io's SUSI(Single User Sign In) account information\n// and authentication. If the user's IMS token does not already have an existing\n// Frame.io account, it will create it at the same time. The auth info will be\n// in the response headers rather than in the body.\nexport interface IFrameioAdobeSusiResponse {\n    updated_at: Date | null,\n    joined_via: string,\n    inserted_at: Date | null,\n    profile_image_original: string | null,\n    id: string,\n    location: string,\n    image_128: string | null,\n    name: string | null,\n    last_seen: Date | null,\n    email_confirm_by: any | null,\n    phone: string | null,\n    user_hash: string,\n    email: string,\n    roles: string | null,\n    features_seen: string | null,\n    account_id: string,\n    timezone_value: string,\n    _type: string,\n    deleted_at: Date | null,\n    image_32: string | null,\n    bio: string | null,\n    image_64: string | null,\n    user_default_color: string,\n    profile_image: string | null,\n    from_google: boolean,\n    digest_frequency: string,\n    first_login_at: Date | null,\n    email_preferences: string | null,\n    image_256: string | null,\n    mfa_enforced_at: Date | null,\n    from_adobe: boolean,\n    next_digest_date: Date | null,\n    context: any | null,\n    upload_url: string | null,\n    highest_account_role: string | null\n}\n\nexport type FrameioTeamAccess = 'private' | 'public' | 'restricted';\n\n/**\n * Optional parameter to FrameioInterface.authenticate.\n *\n * When using a Frame.io developer token,\n * set frameioToken with the developer token,\n * and leave the rest undefined.\n *\n * When using your own authentication,\n * all values are expected.\n *\n * When relying on the native authentication\n * provided by SAM, omit the optional parameter\n * to authenticate().\n */\nexport interface FrameioAuthenticationInfo {\n    frameioToken: string;\n    frameioRefreshToken?: string;\n    frameioTokenExpires?: string;\n    frameioUserId?: string;\n    frameioLastRefresh?: string;\n    useAdobeSusi?: boolean;\n}\n\n// Info from Frame.io relating to the Adobe SUSI (Single User Sign In) user.\nexport interface FrameioAdobeSusiInfo {\n    userExists: boolean;\n    susiAvailable: boolean;\n    // Frame.io provides the restriction string values as \"admin-block\",\n    // \"region-block\" (+ code: <code>), or \"unspecified\"\n    restriction?: string;\n}\n\ninterface IFrameioAccessControlResponse {\n    id: string;\n    invite_only: boolean;\n}\n\ninterface IFrameioPlanResponse {\n}\n\ninterface IFrameioWatermarkResponse {\n}\n\ninterface IFrameioSubscriptionResponse {\n}\n\ninterface IFrameioAccountMemberResponse {\n}\n\nexport interface FrameioReviewLinksChangeEventParam {\n    source: FrameioSourceDocument;\n    reviewLink: Partial<IFrameioReviewLinkResponse>;\n}\n\n// Values for credential caching.\nconst frameioCredentialsCacheKey = 'FRAMEIO_CREDENTIALS_';\n// Local cache expires in 14 days (in ms)\nconst frameioCredentialsTTL = millisecondsPerHour * (24 * 14);\n// Refresh token expiration (in second)\nconst frameioRefreshTokenDuration = secondsPerHour * (24 * 15);\n\n// An Interface, in this context, is the RESTful interface implemented\n// by a service, so most methods of FrameioInterface wrap an HTTP\n// Request to Frame.io, and all requests we make to Frame.io should\n// go through some method of FrameioInterface.\n\nexport default class FrameioInterface extends InterfaceBase {\n    private _frameioContext: FrameioContext;\n    private _frameioClientId: string;\n    private _nativeContext: IFrameioNativeContext | undefined;\n    private _authenticationInfo: FrameioAuthenticationInfo | undefined;\n\n    constructor(ctx: FrameioContext) {\n        super(ctx._core);\n        this._frameioContext = ctx;\n\n        // Set the Frame.io client ID used in request analytics.\n        const { PRODUCT_ID } = this._core._environment.getValue('HOST_PRODUCT_DATA');\n        const frameioClient = 'adobe+' + PRODUCT_ID;\n        this._frameioClientId = frameioClient.toLowerCase();\n    }\n\n    /**\n     * We use native code to login to Frame.io,\n     * and authentication is specific to their service,\n     * so we'll only access nativeContext methods\n     * from FrameioInterface.\n     */\n\n    //----------------------------------------------------------------\n    // Limit FrameioInterface to be the only client of IFrameioNativeContext,\n    // the interface implementing the native support for frame.io.\n    private get nativeContext(): IFrameioNativeContext {\n        // @ts-expect-error\n        const acplModel: any = (typeof window !== 'undefined') && window.acplModel;\n\n        if (!this._nativeContext && acplModel) {\n            const workflows = acplModel.Workflows;\n\n            if (workflows.createShareForReviewWorkflow) {\n                const shareForReviewWorkflow = workflows.createShareForReviewWorkflow(acplModel.applicationAssetContext);\n                this._nativeContext = shareForReviewWorkflow.getFrameioAssetContext();\n\n                if (this._nativeContext) {\n                    const self = this;\n\n                    this._nativeContext.addEventListener(FRAMEIO_REVIEW_LINKS_CHANGE,  (json: string) => {\n                        self._frameioContext._handleReviewLinksChangeEvent(json);\n                    });\n\n                    this._nativeContext.addEventListener(FRAMEIO_AUTHORIZATION_CHANGE, async () => {\n                        const nativeAuthInfo = self.nativeContext.authenticationInfo();\n\n                        if (nativeAuthInfo.frameioToken) {\n                            // logged in, or refreshed\n                            await self._cacheCredentials(JSON.stringify(nativeAuthInfo));\n\n                            // when the id changes, the context will clear user data\n                            self._frameioContext._updateCurrentUserId(nativeAuthInfo.frameioUserId);\n                        } else {\n                            // logged out\n                            await self._core._environment.cache.deleteItem(self._cachedCredentialsId());\n\n                            // clear user specific information.\n                            self._frameioContext._updateCurrentUserId(undefined);\n                        }\n\n                        self._frameioContext.dispatch(SharedFrameioAuthorizationChangeEvent);\n                    });\n                }\n\n            } else {\n                oneTimeWarning('FrameioInterface.nativeContext',\n                    'Share for Review workflows are not enabled for this application');\n            }\n        }\n\n        if (!this._nativeContext) {\n            oneTimeWarning('FrameioInterface.nativeContext',\n                'native Frameio context does not exist, web/browser mode is utilized for testing only');\n        }\n        return this._nativeContext!;\n    }\n\n    // ID value to use as a key for authentication credentials.\n    private get _authenticationId(): string {\n        return this.adobeId;\n    }\n\n    private _cachedCredentialsId(): string {\n        return frameioCredentialsCacheKey + this._authenticationId;\n    }\n\n    private _getRefreshTokenExpiration(lastRefresh: any): number {\n        const lastRefreshVal = parseInt(lastRefresh);\n\n        if (lastRefreshVal) {\n            return lastRefreshVal + frameioRefreshTokenDuration;\n        }\n        return 0;\n    }\n\n    // Retrieve the cached string.\n    private async _getCachedCredentials(): Promise<string> {\n        const credentialsId = this._cachedCredentialsId();\n        const existingCredentials = await this._core._environment.cache.getItem(credentialsId);\n        if (existingCredentials !== NotFound) {\n            return existingCredentials;\n        }\n        return '';\n    }\n\n    // Persist the credenital string in the browser cache. Eventually this\n    // may be transfered to the native side and persisted in the device keychain.\n    private async _cacheCredentials(credentials: string): Promise<void> {\n        return this._core._environment.cache.setItem(\n            this._cachedCredentialsId(),\n            credentials,\n            frameioCredentialsTTL\n        );\n    }\n\n    public get adobeId(): string {\n        // This is expected to return the Adobe user GUID.\n        return this._core._environment.getValue('USER_ID');\n    }\n\n    public get ccUserId(): string {\n        // This is expected to return the Adobe CC ID (email address use to login)\n        return this._core._environment.getValue('USER_EMAIL') || '';\n    }\n\n    public get imsToken(): string {\n        return this._core._environment.getValue('ACCESS_TOKEN');\n    }\n\n    public get xFrameioClient(): string {\n        return this._frameioClientId;\n    }\n\n    public get productKey(): string {\n        const { PRODUCT_ID } = this._core._environment.getValue('HOST_PRODUCT_DATA');\n\n        // The Frame.io native module expect the product code to be the 4CC\n        // client product identifier.  However, SAM.js seems to use the whole\n        // product name, so we need to do a conversion here.\n        // Currently only Photoshop(PHXS), Illustrator(ILST), InDesign(IDSN) and\n        // the `dev` key are supported.\n        if (PRODUCT_ID.includes('Photoshop')) {\n            return 'PHXS';\n        } else if (PRODUCT_ID.includes('Illustrator')) {\n            return 'ILST';\n        } else if (PRODUCT_ID.includes('InDesign')) {\n            return 'IDSN';\n        } else if (PRODUCT_ID.includes('SAMJSDemoApp')) {\n            return 'dev';\n        } else if (PRODUCT_ID.includes('/')) {\n            // According to the SAM.js comments, this should be passed in as\n            // client name/version - but we only need the client name, so drop\n            // the rest. This handles the case where the client may pass in the\n            // 4CC code with the version (i.e. 'PHXS/25.0') instead of the full\n            // name handled above.\n            return PRODUCT_ID.slice(0, PRODUCT_ID.indexOf('/'));\n        }\n        // If its an unsupported or demo application, then default to dev key.\n        return 'dev';\n    }\n\n    public async checkForCachedCredentials(): Promise<IFrameioAuthenticationStatus> {\n        // Quick check if we have already set credentials at least once\n        // that have not expired.\n        const cachedCredentials = await this._getCachedCredentials();\n\n        if (cachedCredentials !== '') {\n            const nativeContext: IFrameioNativeContext = this.nativeContext;\n            const parsedCredentials = JSON.parse(cachedCredentials);\n            const refreshExpiration = this._getRefreshTokenExpiration(parsedCredentials.frameioLastRefresh);\n\n            if (refreshExpiration) {\n                const nowSec = Math.floor(Date.now() / 1000); // ms -> s\n                const expired = refreshExpiration - nowSec;\n\n                if (expired <= 0) {\n                    return IFrameioAuthenticationStatus.authExpired;\n                }\n            }\n            // Always use the current app version no matter what version was cached.\n            parsedCredentials.xFrameioClient = this.xFrameioClient;\n            if (nativeContext) {\n                // Not expired refresh so auto login.\n                const token = await nativeContext.authenticateUser(parsedCredentials);\n\n                // Check to see if there was a refresh on the token, and refresh\n                // the cached credentials if there was.\n                if (token !== parsedCredentials.token) {\n                    const nativeAuthInfo = nativeContext.authenticationInfo();\n                    await this._cacheCredentials(JSON.stringify(nativeAuthInfo));\n                    return IFrameioAuthenticationStatus.authLoggedIn;\n                }\n            }\n            // else not supported for web so issue logout.\n        }\n        return IFrameioAuthenticationStatus.authLoggedOut;\n    }\n\n    public async isAuthenticated(): Promise<boolean> {\n        const authStatus = await this.authenticationStatus();\n        return (authStatus === IFrameioAuthenticationStatus.authLoggedIn);\n    }\n\n    public async authenticationStatus(): Promise<IFrameioAuthenticationStatus> {\n        const nativeContext: IFrameioNativeContext = this.nativeContext;\n\n        if (nativeContext) {\n            let nativeAuthStatus =  nativeContext.authenticationStatus(this._authenticationId);\n\n\n            if (nativeAuthStatus === IFrameioAuthenticationStatus.authLoggedOut) {\n                // If the state is logged out - check for previous cached info.\n                nativeAuthStatus = await this.checkForCachedCredentials();\n            }\n            return nativeAuthStatus;\n        }\n        if (this._authenticationInfo?.frameioLastRefresh) {\n            // Check for the last refresh expiration.  Frame.io refresh tokens\n            // expire in 15 day, so set refresh an hour before.\n            const kExpiresHours = (15 * 24) - 1;\n            const now = new Date();\n            const lastRefresh = new Date(0);\n            lastRefresh.setUTCSeconds(parseInt(this._authenticationInfo?.frameioLastRefresh));\n            // The `valueOf` looks weird here but it is needed to avoid the Typescript\n            // error of: \"The left-hand side of an arithmetic operation must be of type\n            //   'any', 'number', 'bigint' or an enum type.\"\n            const deltaT = Math.abs(now.valueOf() - lastRefresh.valueOf()) / 36e5;\n\n            if (deltaT >= kExpiresHours) {\n                return IFrameioAuthenticationStatus.authExpired;\n            }\n            return (this._authenticationInfo?.frameioToken ? IFrameioAuthenticationStatus.authLoggedIn : IFrameioAuthenticationStatus.authLoggedOut);\n        }\n        // If auth refresh is not set - assume logged out.\n        return IFrameioAuthenticationStatus.authLoggedOut;\n    }\n\n    public async getToken(): Promise<string> {\n        const nativeContext: IFrameioNativeContext = this.nativeContext;\n\n        if (nativeContext) {\n            // The native code caches the token and refreshes it\n            // when it's stale, so don't persistently store the\n            // token in javascript as it will break the refresh.\n            return await nativeContext.getToken();\n        }\n        return this._authenticationInfo?.frameioToken || '';\n    }\n\n    // Execute a force refresh of the authentication token.\n    public async refreshToken(): Promise<string> {\n        const nativeContext: IFrameioNativeContext = this.nativeContext;\n\n        if (nativeContext) {\n            // The native code caches the token and refreshes it\n            // when it's stale, so don't persistently store the\n            // token in javascript as it will break the refresh.\n            const token = await nativeContext.getToken(true);\n            // After refreshing to token, the save the new info to the store.\n            const nativeAuthInfo = nativeContext.authenticationInfo();\n            if (token === nativeAuthInfo.frameioToken) {\n                await this._cacheCredentials(JSON.stringify(nativeAuthInfo));\n            }\n            return token;\n        }\n        // not supported for web based, so only return what we currently have.\n        return this._authenticationInfo?.frameioToken || '';\n    }\n\n    public async authenticate(info?: FrameioAuthenticationInfo): Promise<string> {\n        const nativeContext: IFrameioNativeContext = this.nativeContext;\n\n        if (nativeContext) {\n            const adobeId = this.adobeId;\n            const ccUserId = this.ccUserId;\n            const productKey = this.productKey;\n            const xFrameioClient = this.xFrameioClient;\n\n            if (!nativeContext.isUserAuthenticated(this._authenticationId)) {\n                const nativeInfo: FrameioNativeAuthenticationInfo = {\n                    adobeId,\n                    ccUserId,\n                    productKey,\n                    xFrameioClient,\n                };\n\n                if (info !== undefined) {\n                    nativeInfo.frameioToken = info.frameioToken;\n                    // non-required parameters\n                    nativeInfo.frameioRefreshToken = info?.frameioRefreshToken || undefined;\n                    nativeInfo.frameioTokenExpires = info?.frameioTokenExpires || undefined;\n                    nativeInfo.frameioUserId = info?.frameioUserId || undefined;\n                    nativeInfo.frameioLastRefresh = info?.frameioLastRefresh || undefined;\n                }\n                // Removing the following block for now as PM has decided they dont want to have\n                // single sign on for the moment as to allow the user to select login account rather\n                // than limiting it to the Adobe associated account.  This is subject to change and\n                // so its better to leave the SUSI block here for the time being.\n                // } else {\n                //     // check for SUSI availability.\n                //     const susiInfo = await this.getAdobeSusiInfo();\n\n                //     if (susiInfo.susiAvailable) {\n                //         const susiAuthInfo = await this.authenticateAdobeSusi();\n\n                //         nativeInfo.frameioToken = susiAuthInfo.frameioToken;\n                //         // non-required parameters\n                //         nativeInfo.frameioRefreshToken = susiAuthInfo?.frameioRefreshToken || undefined;\n                //         nativeInfo.frameioTokenExpires = susiAuthInfo?.frameioTokenExpires || undefined;\n                //         nativeInfo.frameioUserId = susiAuthInfo?.frameioUserId || undefined;\n                //         nativeInfo.frameioLastRefresh = susiAuthInfo?.frameioLastRefresh || undefined;\n                //     }\n                // }\n                const token = await nativeContext.authenticateUser(nativeInfo);\n\n                if (token !== '') {\n                    const nativeAuthInfo = nativeContext.authenticationInfo();\n                    await this._cacheCredentials(JSON.stringify(nativeAuthInfo));\n                }\n                return token;\n            }\n        } else {\n            this._authenticationInfo = info || undefined;\n        }\n        return await this.getToken();\n    }\n\n    public async deauthenticate(): Promise<void> {\n        this._authenticationInfo = undefined;\n        await this._core._environment.cache.deleteItem(this._cachedCredentialsId());\n        const nativeContext: IFrameioNativeContext = this.nativeContext;\n\n        if (nativeContext) {\n            await nativeContext.deauthenticateUser(this._authenticationId);\n        }\n        return;\n    }\n\n    public async openFile(filename: string) {\n        const nativeContext: IFrameioNativeContext = this.nativeContext;\n\n        if (nativeContext) {\n            return await nativeContext.openFile(filename);\n        }\n        throw SAMError.create(SAMErrorCode.UNSUPPORTED,\n            'Method is not supported in browser _environment.');\n    }\n\n    // end of IFrameioNativeContext\n    //----------------------------------------------------------------\n\n    public dispatchReviewLinksChangeEvent(json: string) {\n        const nativeContext: IFrameioNativeContext = this.nativeContext;\n\n        if (!nativeContext) {\n            throw SAMError.create(SAMErrorCode.UNSUPPORTED,\n                'Method is not supported in browser _environment.');\n        }\n\n        nativeContext.dispatchReviewLinksChangeEvent(json);\n    }\n\n    // Methods related to using Adobe Single User Sign In (SUSI)\n    public async getAdobeSusiInfo(): Promise<FrameioAdobeSusiInfo> {\n        const respJson = await this._adobeSusiUserRequest();\n        const susiInfo: FrameioAdobeSusiInfo = {\n            userExists: respJson.exists,\n            susiAvailable: (respJson.method === 'adobe'),\n            restriction: respJson.restriction || undefined\n        };\n        return susiInfo;\n    }\n\n    public async authenticateAdobeSusi(): Promise<FrameioAuthenticationInfo> {\n        const authInfo = await this._adobeSusiRequest();\n        return authInfo;\n    }\n\n    private async _adobeSusiUserRequest(): Promise<IFrameioAdobeSusiUserResponse> {\n        const response = await this._doPost(\n            FRAMEIO_LINKS.ADOBE_SUSI_USER,\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ access_token: this.imsToken }),\n            [ 200 ]\n        );\n        return response.json();\n    }\n\n    private async _adobeSusiRequest(): Promise<FrameioAuthenticationInfo> {\n        const response = await this._doPost(\n            FRAMEIO_LINKS.ADOBE_SUSI,\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ access_token: this.imsToken }),\n            [ 200 ]\n        );\n        const respHeaders = response.headers;\n        const respBody = await response.json();\n        const token = respHeaders.get('authorization');\n        const refreshToken = respHeaders.get('x-refresh-token');\n        const tokenExpires = respHeaders.get('x-expires');\n        const authInfo: FrameioAuthenticationInfo = {\n            frameioToken: token ? token.replace('Bearer ', '') : '',\n            frameioRefreshToken: refreshToken || undefined,\n            frameioTokenExpires: tokenExpires || undefined,\n            frameioUserId: respBody.id || undefined,\n            frameioLastRefresh: Date.now().toString(),\n            useAdobeSusi: true\n        };\n        return authInfo;\n    }\n\n    //----------------------------------------------------------------\n    // InterfaceBase._fetch() lets subclasses adjust the fetch options\n    // by calling _getFetchOptionOverrides().\n    //\n    // FrameioInterface specifies noOtherHeaders=true to block ACP\n    // specific headers, such as _fetch() injecting it's own\n    // ACP specific authorization token. Instead, we specify\n    // the Frameio authorization token\n    protected  async _getFetchOptionOverrides(\n        href: string,\n        fetchOptions: IFetchOptions\n    ): Promise<{ href: string, options: IFetchOptions}> {\n        const token = await this.getToken();\n        return {\n            href,\n            options: {\n                ...fetchOptions,\n                headers: {\n                    ...fetchOptions.headers,\n                    // Override Environment.fetch default auth header\n                    'authorization': `Bearer ${token}`,\n                    'x-frameio-client': this.xFrameioClient\n                },\n                // Do not allow Environment.fetch to supply its default headers\n                noOtherHeaders: true\n            }\n        };\n    }\n\n    // Frameio endpoints that return Array<>'s can be paginated:\n    //   https://developer.frame.io/docs/getting-started/key-concepts#h2-section-pagination\n    //   NOTE: The default page size is 50.\n    //\n    // _getMultiPageResponse() will read each page in the response,\n    // and return the result of combining them into one large array.\n    private async _getMultiPageResponse(href: string) {\n        let result: any[] = [];\n\n        const nextPageUri = (response: any) => {\n            const linkHeader = response && response.headers && response.headers.get('Link');\n            const link = linkHeader && LinkHeader.parse(linkHeader);\n            const ref = link && link.has('rel', 'next') && link.get('rel', 'next');\n            const uri = ref && ref[0] && ref[0].uri;\n\n            // For some reason, the link headers are specifying http,\n            // but our requests fail with 403 unless we use https.\n            return uri && uri.replace('http:', 'https:');\n        };\n\n        const readPage = async (url: string): Promise<any> => {\n            const response = await this._doGet(url);\n            const json = await response.json();\n\n            const next = nextPageUri(response);\n\n            // Accumulate the pages in result\n            result = result.concat(json);\n\n            // Use tail recursion to read the next page, or return\n            // the final result if there are no more pages.\n            return next ? readPage(next) : result;\n        };\n\n        return readPage(href);\n    }\n    //\n    //----------------------------------------------------------------\n\n    // See https://developer.frame.io/api/reference/operation/getMe/\n    public async getCurrentUser(): Promise<IFrameioUserResponse> {\n        return this._getResponse(\n            FRAMEIO_LINKS.ME\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getAccount/\n    public async getAccount(accountId: string): Promise<IFrameioAccountResponse> {\n        return this._getResponse(\n            fillURLTemplate(FRAMEIO_LINKS.ACCOUNT, { accountId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getAccounts/\n    public async getAccounts(): Promise<Array<IFrameioAccountResponse>> {\n        return this._getMultiPageResponse(\n            FRAMEIO_LINKS.ACCOUNTS\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getTeamsByAccount/\n    public async getTeams(accountId: string): Promise<Array<IFrameioTeamResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.TEAMS, { accountId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getTeam/\n    public async getTeam(teamId: string): Promise<IFrameioTeamResponse> {\n        return this._getResponse(\n            fillURLTemplate(FRAMEIO_LINKS.TEAM, { teamId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getProject/\n    public async getProject(projectId: string): Promise<IFrameioProjectResponse> {\n        return this._getResponse(\n            fillURLTemplate(FRAMEIO_LINKS.PROJECT, { projectId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getProjectsByTeam/\n    public async getProjects(teamId: string): Promise<Array<IFrameioProjectResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.PROJECTS, { teamId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getSharedProjects/\n    // NOTE: Using filter[account_id]={accountId} to restrict results to a specific account\n    public async getSharedProjects(accountId: string): Promise<Array<IFrameioProjectResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.SHAREDPROJECTS, { accountId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/reviewLinksList/\n    public async getReviewLinks(projectId: string): Promise<Array<IFrameioReviewLinkResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.REVIEWS, { projectId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/reviewLinkGet/\n    public async getReviewLink(reviewLinkId: string): Promise<IFrameioReviewLinkResponse> {\n        return this._getResponse(\n            fillURLTemplate(FRAMEIO_LINKS.REVIEW, { reviewLinkId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/reviewLinkCreate/\n    public async createReviewLink(projectId: string, displayName: string): Promise<IFrameioReviewLinkResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.REVIEWS, { projectId }),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ name: displayName }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/createAsset/\n    public async createFolder(parentId: string, displayName: string): Promise<IFrameioAssetResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.CREATEASSET, { parentId }),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ name: displayName, type: 'folder' }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/createAsset/\n    // See also https://developer.frame.io/docs/workflows-assets/uploading-assets\n    public async createFile(parentId: string, displayName: string, fileSize: number, mimeType: string = 'application/pdf'): Promise<IFrameioAssetResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.CREATEASSET, { parentId }),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({\n                name: displayName,\n                type: 'file',\n                filetype: mimeType,\n                filesize: fileSize\n            }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/createAsset/\n    // See also https://developer.frame.io/docs/workflows-assets/uploading-assets\n    public async uploadFile(url: string, bytes: ArrayBuffer, mimeType: string = 'application/pdf'): Promise<void> {\n        // !!@ The upload urls are to AWS, so I'm just using a raw fetch for now...\n        const init = {\n            method: 'PUT',\n            headers: {\n                'Content-Type': mimeType,\n                'x-amz-acl': 'private'\n            },\n            body: bytes\n        };\n\n        await fetch(url, init);\n    }\n\n    // See https://developer.frame.io/api/reference/operation/reviewLinkItemCreate/\n    public async reviewLinkAddAsset(reviewLinkId: string, assetId: string): Promise<IFrameioReviewLinkResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.ITEMCREATE, { reviewLinkId }),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ asset_ids: [ assetId ] }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n\n    // See https://developer.frame.io/api/reference/operation/getAssets/\n    public async getChildren(assetId: string): Promise<Array<IFrameioAssetResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.ASSETS, { assetId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getAsset/\n    public async getAsset(assetId: string): Promise<IFrameioAssetResponse> {\n        return this._getResponse(\n            fillURLTemplate(FRAMEIO_LINKS.ASSET, { assetId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/addVersionToAsset/\n    public async addVersionToAsset(assetId: string, nextAssetId: string): Promise<IFrameioAssetResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.VERSION, { assetId }),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ next_asset_id: nextAssetId }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/createComment/\n    public async createComment(assetId: string, text: string): Promise<IFrameioCommentResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.CREATECOMMENT, { assetId }),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ text }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getComment/\n    public async getComment(commentId: string): Promise<IFrameioCommentResponse> {\n        return this._getResponse(\n            fillURLTemplate(FRAMEIO_LINKS.GETCOMMENT, { commentId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getComments/\n    public async getComments(assetId: string): Promise<Array<IFrameioCommentResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.GETCOMMENTS, { assetId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getCommentImpressions/\n    public async getImpressions(commentId: string): Promise<Array<IFrameioImpressionResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.IMPRESSIONS, { commentId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/updateComment/\n    public async updateComment(commentId: string, text: string): Promise<IFrameioCommentResponse> {\n        const response = await this._doPut(\n            fillURLTemplate(FRAMEIO_LINKS.COMMENT, { commentId }),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ text }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/deleteComment/\n    public async deleteComment(commentId: string): Promise<IFrameioCommentResponse> {\n        const response = await this._doDelete(\n            fillURLTemplate(FRAMEIO_LINKS.COMMENT, { commentId })\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/createReply/\n    public async createReply(commentId: string, text: string): Promise<IFrameioCommentResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.REPLY, { commentId }),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify({ text }),\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/getComments/\n    public async getReplies(commentId: string): Promise<Array<IFrameioCommentResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.GETREPLIES, { commentId })\n        );\n    }\n\n    // See https://developer.frame.io/api/reference/operation/createCommentImpressionLike/\n    public async createLike(commentId: string): Promise<IFrameioLikeResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.LIKE, { commentId }),\n            { },\n            undefined,\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n\n    // See https://developer.frame.io/api/reference/operation/deleteCommentImpressionLike/\n    public async deleteLike(commentId: string): Promise<IFrameioLikeResponse> {\n        const response = await this._doDelete(\n            fillURLTemplate(FRAMEIO_LINKS.LIKE, { commentId })\n        );\n\n        return response.json();\n    }\n\n    // See https://developer.frame.io/api/reference/operation/completeComment/\n    public async completeComment(commentId: string): Promise<IFrameioCommentResponse> {\n        const response = await this._doPost(\n            fillURLTemplate(FRAMEIO_LINKS.COMPLETE, { commentId }),\n            { },\n            undefined,\n            [ 200 ]\n        );\n\n        return response.json();\n    }\n\n\n    // See https://developer.frame.io/api/reference/operation/uncompleteComment/\n    public async uncompleteComment(commentId: string): Promise<IFrameioCommentResponse> {\n        const response = await this._doDelete(\n            fillURLTemplate(FRAMEIO_LINKS.COMPLETE, { commentId })\n        );\n\n        return response.json();\n    }\n\n    // This is an undocumented interface. It will not work with developer tokens\n\n    // Loosely speaking, a tree of assets gets stringify()'ed as a dictionary.\n    //\n    // Each folder in the tree is added to the dictionary using the folder id\n    // as a key, and an array of objects describing the folder's immediate children\n    // as the value. The description of a child includes { id, parent_id, name },\n    // but is not a full asset description ( IFrameioAssetResponse ).\n    //\n    // As the root folder has no parent to describe it, the value of data[\"root\"]\n    // is an array containing the root folder's description.\n    public async getFolderTree(projectId: string): Promise<any> {\n        return this._getResponse(\n            fillURLTemplate(FRAMEIO_LINKS.FOLDERTREE, { projectId })\n        );\n    }\n\n    // This is an undocumented interface. It will not work with developer tokens.\n    //\n    // The response is an array of assets.\n    //\n    // If the asset's path relative to it's project is ./folder/asset,\n    // then the array would be:\n    //\n    // array[0] = root_asset\n    // array[1] = folder\n    // array[2] = asset\n    public async getAncestors(assetId: string): Promise<Array<IFrameioAssetResponse>> {\n        return this._getMultiPageResponse(\n            fillURLTemplate(FRAMEIO_LINKS.ANCESTORS, { assetId })\n        );\n    }\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemBase from '../core/ItemBase';\nimport type FrameioContext from './FrameioContext';\n\nexport default class FrameioBase extends ItemBase {\n    // ItemBase implements this.id for us\n\n    /**\n     * @package - not yet decided if context is internal use only.\n     *  In the meantime, I'm decorating them to discourage it's use.\n     */\n    get context(): FrameioContext {\n        return this._core.frameioContext;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nimport type { IFrameioUserResponse } from './FrameioInterface';\nimport type FrameioAccount from './FrameioAccount';\nimport FrameioBase from './FrameioBase';\n\n// See https://developer.frame.io/api/reference/operation/getAccount/\n//  for schema of the data FrameioAccount encapsulates.\nexport default class FrameioUser extends FrameioBase {\n    private _accountId: string = '';\n    private _email: string = '';\n    private _name: string = '';\n    private _profileImage: string = '';\n    private _userDefaultColor: string = '';\n\n    private _account: FrameioAccount | undefined;\n\n    get accountId(): string {\n        return this._accountId;\n    }\n\n    get email(): string {\n        return this._email;\n    }\n\n    get name(): string {\n        return this._name;\n    }\n\n    get profileImage(): string {\n        return this._profileImage;\n    }\n\n    get userDefaultColor(): string {\n        return this._userDefaultColor;\n    }\n\n    async getAccount(): Promise<FrameioAccount> {\n        if (!this._account) {\n            this._account = await this.context.getAccount(this.accountId);\n        }\n\n        return this._account;\n    }\n}\n\nexport const FrameioUserUpdater = new ItemUpdater<FrameioUser, Partial<IFrameioUserResponse>>({\n    localItemType: FrameioUser,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_accountId': 'account_id',\n        '_email': 'email',\n        '_name': 'name',\n        '_profileImage': 'profile_image',\n        '_userDefaultColor': 'user_default_color'\n    })\n});\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport FrameioBase from './FrameioBase';\n\n// See https://developer.frame.io/api/reference/operation/getAsset/\n//  for schema of IFrameioAssetResponse. FrameioFolder\n//  encapsulates the data for assets of type=\"folder\".\n//\n// See FrameioFile, FrameioVersionStack for other asset types.\nexport default class FrameioAsset extends FrameioBase {\n    // ItemBase implements this.id for us\n    private _insertedAt?: Date;\n    private _name: string = '';\n    private _parentId: string | undefined;\n    private _projectId: string = '';\n    private _teamId: string = '';\n    private _updatedAt?: Date;\n\n    /* All of a FrameioAsset's id's should be valid id's.\n     *\n     * But Frame.io indicates a root_asset folder with\n     * (parent_id == null), as a root doesn't have a parent.\n     *\n     * SAM.js isn't a fan of the null's, so it's using\n     * undefined for the same thing.\n     */\n    get insertedAt(): Date | undefined {\n        return this._insertedAt;\n    }\n\n    get name(): string {\n        return this._name;\n    }\n\n    get parentId(): string | undefined {\n        return this._parentId;\n    }\n\n    async getParent(): Promise<FrameioAsset | undefined> {\n        const ctx = this.context;\n        const parentId = this.parentId;\n\n        if (parentId) {\n            return ctx.getAsset(parentId);\n        }\n        return undefined;\n    }\n\n    get projectId(): string {\n        return this._projectId;\n    }\n\n    get teamId(): string {\n        return this._teamId;\n    }\n\n    get updatedAt(): Date | undefined {\n        return this._updatedAt;\n    }\n\n    /*\n     * If the path to an asset relative to it's project is\n     *      ./folder/subfolder/asset\n     *\n     * Then\n     *      ancestors[0] = folder : FrameioFolder\n     *      ancestors[1] = subfolder : FrameioFolder\n     *      ancestors[2] = asset : FrameioAsset\n     */\n    async getAncestors(): Promise<Array<FrameioAsset>> {\n        return this.context.getAncestors(this.id);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport FrameioBase from './FrameioBase';\nimport type { IFrameioCommentResponse, IFrameioLikeResponse } from './FrameioInterface';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport type FrameioComment from './FrameioComment';\nimport { FrameioCommentUpdater } from './FrameioComment';\n\n// See https://developer.frame.io/api/reference/operation/createCommentImpressionLike/\n//  for schema of IFrameioLikeResponse, aka response.type=\"like\".\n\nexport default class FrameioLike extends FrameioBase {\n    // Frame.io uses { myString : null } for unspecified\n    // values, which causes our updater to set the string\n    // property to undefined, but our getters substitute\n    // '' for undefined, so our clients aren't exposed to this.\n    private _anonymousUserId?: string;\n    private _comment?: FrameioComment;\n    private _commentId?: string;\n    private _deletedAt?: Date;\n    private _insertedAt?: Date;\n    private _updatedAt?: Date;\n    private _userId?: string;\n\n    get anonymousUserId(): string {\n        return this._anonymousUserId || '';\n    }\n\n    get comment(): FrameioComment | undefined {\n        return this._comment;\n    }\n\n    get commentId(): string {\n        return this._commentId || '';\n    }\n\n    get deletedAt(): Date | undefined {\n        return this._deletedAt;\n    }\n\n    get insertedAt(): Date | undefined {\n        return this._insertedAt;\n    }\n\n    get updatedAt(): Date | undefined {\n        return this._updatedAt;\n    }\n\n    get userId(): string {\n        return this._userId || '';\n    }\n}\n\nexport const FrameioLikeUpdater = new ItemUpdater<FrameioLike, Partial<IFrameioLikeResponse>>({\n    localItemType: FrameioLike,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_anonymousUserId': 'anonymous_user_id',\n        '_comment': {\n            // The comment property of an IFrameioLikeResponse is a nested\n            // object of type IFrameioCommentResponse, so let's update it!\n            set: (comment: IFrameioCommentResponse, dest: ISAMObject) => {\n                const like = dest as FrameioLike;\n                const context = like.context;\n                const pool = context._objectPool;\n\n                const session = pool.createUpdateSession<FrameioComment>();\n                like['_comment'] = FrameioCommentUpdater.updateRemoteItem(session, comment);\n                session.commit();\n            },\n            name: 'comment',\n            format: 'object'\n        },\n        '_commentId': 'comment_id',\n        '_deletedAt': { name: 'deleted_at', format: 'date' },\n        '_insertedAt': { name: 'inserted_at', format: 'date' },\n        '_updatedAt': { name: 'updated_at', format: 'date' },\n        '_userId': 'user_id'\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport FrameioBase from './FrameioBase';\nimport type { IFrameioCommentResponse, IFrameioUserResponse } from './FrameioInterface';\nimport type FrameioLike from './FrameioLike';\nimport { FrameioLikeUpdater } from './FrameioLike';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport type FrameioUser from './FrameioUser';\nimport { FrameioUserUpdater } from './FrameioUser';\n\nexport type FrameioCommentParam = {\n    text: string;\n    mentions?: any; /* unimplemented, currently ignored */\n    annotationData?: any; /* unimplemented, currently ignored */\n};\n\n// See https://developer.frame.io/api/reference/operation/getAsset/\n//  for schema of IFrameioAssetResponse. FrameioFile\n//  encapsulates the data for assets of type=\"file\".\n//\n// See FrameioFolder, FrameioVersionStack for other asset types.\nexport default class FrameioComment extends FrameioBase {\n    // Frame.io uses { myString : null } for unspecified\n    // values, which causes our updater to set the string\n    // property to undefined, but our getters substitute\n    // '' for undefined, so our clients aren't exposed to this.\n\n    private _assetId?: string;\n    private _completed: boolean = false;\n    private _completedAt?: Date;\n    private _completerId?: string;\n    private _deletedAt?: Date;\n    private _hasReplies: boolean = false;\n    private _insertedAt?: Date;\n    private _likeCount: number = 0;\n    private _owner?: FrameioUser;\n    private _ownerId?: string;\n    private _page?: string;\n    private _parentId?: string;\n    private _private: boolean = false;\n    private _readCount: number = 0;\n    private _reviewLinkId?: string;\n    private _targetAssetId?: string;\n    private _text?: string;\n    private _textEditedAt?: Date;\n    private _timestamp: number = 0;\n    private _timestampMicroseconds: number = 0;\n    private _updatedAt?: Date;\n\n    get assetId(): string {\n        return this._assetId || '';\n    }\n\n    get completed(): boolean {\n        return this._completed;\n    }\n\n    get completedAt(): Date | undefined {\n        return this._completedAt;\n    }\n    get completerId(): string {\n        return this._completerId || '';\n    }\n\n    get deletedAt(): Date | undefined {\n        return this._deletedAt;\n    }\n\n    get hasReplies(): boolean {\n        return this._hasReplies;\n    }\n\n    get insertedAt(): Date | undefined {\n        return this._insertedAt;\n    }\n\n    get likeCount(): number {\n        return this._likeCount;\n    }\n\n    get owner(): FrameioUser | undefined {\n        return this._owner;\n    }\n\n    get ownerId(): string {\n        return this._ownerId || '';\n    }\n\n    get page(): string {\n        return this._page || '';\n    }\n\n    get parentId(): string {\n        return this._parentId || '';\n    }\n\n    get private(): boolean {\n        return this._private;\n    }\n\n    get readCount(): number {\n        return this._readCount;\n    }\n\n    get reviewLinkId(): string {\n        return this._reviewLinkId || '';\n    }\n\n    get targetAssetId(): string {\n        return this._targetAssetId || '';\n    }\n\n    get text(): string {\n        return this._text || '';\n    }\n\n    get textEditedAt(): Date | undefined {\n        return this._textEditedAt;\n    }\n\n    get timestamp(): number {\n        return this._timestamp;\n    }\n\n    get timestampMicroseconds(): number {\n        return this._timestampMicroseconds;\n    }\n\n    get updatedAt(): Date | undefined {\n        return this._updatedAt;\n    }\n\n    async updateComment(param: FrameioCommentParam): Promise<FrameioComment> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.updateComment(this.id, param.text);\n        const session = ctx._objectPool.createUpdateSession<FrameioComment>();\n        const comment = FrameioCommentUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        return comment;\n    }\n\n    async deleteComment(): Promise<FrameioComment> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.deleteComment(this.id);\n        const session = ctx._objectPool.createUpdateSession<FrameioComment>();\n        const comment = FrameioCommentUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        return comment;\n    }\n\n    async createLike(): Promise<FrameioLike> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.createLike(this.id);\n        const session = ctx._objectPool.createUpdateSession<FrameioLike>();\n        const like = FrameioLikeUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        return like;\n    }\n\n    async deleteLike(): Promise<FrameioLike> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.deleteLike(this.id);\n        const session = ctx._objectPool.createUpdateSession<FrameioLike>();\n        const like = FrameioLikeUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        return like;\n    }\n\n    async createReply(param: FrameioCommentParam): Promise<FrameioComment> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.createReply(this.id, param.text);\n        const session = ctx._objectPool.createUpdateSession<FrameioComment>();\n        const reply = FrameioCommentUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        return reply;\n    }\n\n    async getReplies(): Promise<Array<FrameioComment>> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.getReplies(this.id);\n        const session = ctx._objectPool.createUpdateSession<FrameioComment>();\n        const replies = FrameioCommentUpdater.updateRemoteItems(session, response);\n        session.commit();\n\n        return replies;\n    }\n\n    async completeComment(): Promise<FrameioComment> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.completeComment(this.id);\n        const session = ctx._objectPool.createUpdateSession<FrameioComment>();\n        const comment = FrameioCommentUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        return comment;\n    }\n\n    async uncompleteComment(): Promise<FrameioComment> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.uncompleteComment(this.id);\n        const session = ctx._objectPool.createUpdateSession<FrameioComment>();\n        const comment = FrameioCommentUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        return comment;\n    }\n\n\n}\n\nexport const FrameioCommentUpdater = new ItemUpdater<FrameioComment, Partial<IFrameioCommentResponse>>({\n    localItemType: FrameioComment,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n\n\n        '_assetId': 'asset_id',\n        '_completed': { name: 'completed', format: 'boolean' },\n        '_completedAt': { name: 'completed_at', format: 'date' },\n        '_completerId': 'completer_id',\n        '_deletedAt': { name: 'deleted_at', format: 'date' },\n        '_hasReplies': { name: 'has_replies', format: 'boolean' },\n        '_insertedAt': { name: 'inserted_at', format: 'date' },\n        '_likeCount': { name: 'like_count', format: 'number' },\n        '_owner': {\n            // The owner property of an IFrameioComment is a nested\n            // IFrameioUserResponse, so let's update it!\n            set: (owner: IFrameioUserResponse, dest: ISAMObject) => {\n                const comment = dest as FrameioComment;\n                const context = comment.context;\n                const pool = context._objectPool;\n\n                const session = pool.createUpdateSession<FrameioUser>();\n                comment['_owner'] = FrameioUserUpdater.updateRemoteItem(session, owner);\n                session.commit();\n            },\n            name: 'owner',\n            format: 'object'\n        },\n        '_ownerId': 'owner_id',\n        '_page': 'page',\n        '_parentId': 'parent_id',\n        '_private': { name: 'private', format: 'boolean' },\n        '_readCount': { name: 'read_count', format: 'number' },\n        '_reviewLinkId': 'review_link_id',\n        '_targetAssetId': 'target_asset_id',\n        '_text': 'text',\n        '_textEditedAt': { name: 'text_edited_at', format: 'date' },\n        '_timestamp': { name: 'timestamp', format: 'number' },\n        '_timestampMicroseconds': { name: 'timestamp_microseconds', format: 'number' },\n        '_updatedAt': { name: 'updated_at', format: 'date' }\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nimport type { IFrameioAssetResponse } from './FrameioInterface';\nimport FrameioAsset from './FrameioAsset';\nimport type { FrameioCommentParam } from './FrameioComment';\nimport type FrameioComment from './FrameioComment';\nimport { FrameioCommentUpdater } from './FrameioComment';\n\n// See https://developer.frame.io/api/reference/operation/getAsset/\n//  for schema of IFrameioAssetResponse. FrameioFile\n//  encapsulates the data for assets of type=\"file\".\n//\n// See FrameioFolder, FrameioVersionStack for other asset types.\nexport default class FrameioFile extends FrameioAsset {\n    private _comments: Array<FrameioComment> | undefined;\n\n    async createComment(param: FrameioCommentParam): Promise<FrameioComment> {\n        const ctx = this.context;\n\n        const response = await ctx._frameioInterface.createComment(this.id, param.text);\n        const session = ctx._objectPool.createUpdateSession<FrameioComment>();\n        const comment = FrameioCommentUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        this._comments = undefined; // force it to refresh the next time it's called.\n\n        return comment;\n    }\n\n    // https://developer.frame.io/docs/workflows-projects/gather-all-comments-from-a-project\n    //  implies that only a file can have comments, folders and version stacks should\n    //  enumerate their children for files with comments\n    async getComments(): Promise<Array<FrameioComment>> {\n        let comments = this._comments;\n        if (!comments) {\n            const ctx = this.context;\n\n            const response = await ctx._frameioInterface.getComments(this.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioComment>();\n            comments = FrameioCommentUpdater.updateRemoteItems(session, response);\n            session.commit();\n\n            this._comments = comments;\n        }\n\n        return comments;\n    }\n}\n\nexport const FrameioFileUpdater = new ItemUpdater<FrameioFile, Partial<IFrameioAssetResponse>>({\n    localItemType: FrameioFile,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_commentCount': 'comment_count',\n        '_insertedAt': { name: 'inserted_at', format: 'date' },\n        '_name': 'name',\n        '_parentId': 'parent_id',\n        '_projectId': 'project_id',\n        '_teamId': 'team_id',\n        '_updatedAt': { name: 'updated_at', format: 'date' }\n    })\n});\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nimport type { IFrameioAssetResponse, IFrameioFileHandle } from './FrameioInterface';\nimport FrameioAsset from './FrameioAsset';\nimport type FrameioFile from './FrameioFile';\nimport { FrameioFileUpdater } from './FrameioFile';\nimport type FrameioContext from './FrameioContext';\nimport { frameioAssetUpdater } from './FrameioContext';\n\n// See https://developer.frame.io/api/reference/operation/getAsset/\n//  for schema of IFrameioAssetResponse. FrameioFolder\n//  encapsulates the data for assets of type=\"folder\".\n//\n// See FrameioFile, FrameioVersionStack for other asset types.\nexport default class FrameioFolder extends FrameioAsset {\n    private _children: Array<FrameioAsset> | undefined;\n\n    // clients shouldn't need to deal with id's\n\n    async getChildren(): Promise<Array<FrameioAsset>> {\n        if (!this._children) {\n            const ctx = this.context;\n            const response = await ctx._frameioInterface.getChildren(this.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioAsset>();\n\n            // IFrameioAssetResponse is a special case, as it corresponds to multiple classes\n            // inheriting from FrameioAsset ( FrameioFile, FrameioFolder, FrameioVersionStack ),\n            // so use a utility function to select the correct updater for the type.\n            //\n            // See also FrameioContext.getAncestors()\n            this._children = response.map((asset: IFrameioAssetResponse) => frameioAssetUpdater(session, asset));\n            session.commit();\n        }\n\n        return this._children;\n    }\n\n    private async _uploadFile(urls: Array<string>, fp: IFrameioFileHandle): Promise<void> {\n        // Frame.io splits uploads into ~20MB chunks, whereas our expected\n        // artifact size is ~5MB, so the most common case will be (numChunks == 1).\n\n        const ctx: FrameioContext = this.context;\n\n        // limit the number of concurrent streams\n        const maxStreams = 8;\n\n        const fileSize = fp.size();\n        const numChunks = urls.length;\n        const chunkSize = Math.ceil(fileSize / numChunks); // round-down might lead to omitted bytes.\n\n        let iChunk = 0;\n\n        const nextChunk = async (bytes: ArrayBuffer): Promise<void> => {\n            const i = iChunk++;\n            bytes = await fp.read((i) * chunkSize, bytes);\n\n            return ctx._frameioInterface.uploadFile(urls[i], bytes).then(() => {\n                return  (iChunk < numChunks) ? nextChunk(bytes) : Promise.resolve();\n            });\n        };\n\n        const limit = Math.min(numChunks, maxStreams);\n        const promises = [];\n\n        for (let i = 0; i < limit; i++) {\n            promises.push(nextChunk(new ArrayBuffer(chunkSize)));\n        }\n\n        await Promise.all(promises);\n    }\n\n    async createFile(display_name: string, path: string): Promise<FrameioFile> {\n        const ctx: FrameioContext = this.context;\n\n        const fp = await ctx._frameioInterface.openFile(path);\n        const fileSize = fp.size();\n\n        // create the empty asset\n        const response = await ctx._frameioInterface.createFile(this.id, display_name, fileSize);\n        const session = ctx._objectPool.createUpdateSession<FrameioFile>();\n        const file = FrameioFileUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        await this._uploadFile(response['upload_urls'], fp);\n        fp.close();\n\n        return file;\n    }\n\n    async createFolder(display_name: string): Promise<FrameioFolder> {\n        const ctx: FrameioContext = this.context;\n\n        const response = await ctx._frameioInterface.createFolder(this.id, display_name);\n        const session = ctx._objectPool.createUpdateSession<FrameioFolder>();\n        const folder = FrameioFolderUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        return folder;\n    }\n\n}\n\nexport const FrameioFolderUpdater = new ItemUpdater<FrameioFolder, Partial<IFrameioAssetResponse>>({\n    localItemType: FrameioFolder,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_insertedAt': { name: 'inserted_at', format: 'date' },\n        '_name': 'name',\n        '_parentId': 'parent_id',\n        '_projectId': 'project_id',\n        '_teamId': 'team_id',\n        '_updatedAt': { name: 'updated_at', format: 'date' }\n    })\n});\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nimport type { IFrameioTeamResponse } from './FrameioInterface';\nimport FrameioBase from './FrameioBase';\nimport type FrameioProject from './FrameioProject';\nimport { FrameioProjectUpdater } from './FrameioProject';\n\n// See https://developer.frame.io/api/reference/operation/getTeamsByAccount/\n//  for schema of the data FrameioTeam encapsulates.\nexport default class FrameioTeam extends FrameioBase {\n    private _projects: Array<FrameioProject> | undefined;\n    private _email: string = '';\n    private _name: string = '';\n\n    get email(): string {\n        return this._email;\n    }\n\n    get name(): string {\n        return this._name;\n    }\n\n    async getProjects(): Promise<Array<FrameioProject>> {\n        let projects = this._projects;\n        if (!projects) {\n            const ctx = this.context;\n\n            const projectsResponse = await this._core.frameioContext._frameioInterface.getProjects(this.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioProject>();\n            projects = FrameioProjectUpdater.updateRemoteItems(session, projectsResponse);\n            session.commit();\n\n            this._projects = projects;\n        }\n\n        return projects;\n    }\n}\n\nexport const FrameioTeamUpdater = new ItemUpdater<FrameioTeam, Partial<IFrameioTeamResponse>>({\n    localItemType: FrameioTeam,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_email': 'owner.email',\n        '_name': 'name'\n    })\n});\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nimport type { IFrameioAssetResponse } from './FrameioInterface';\nimport FrameioAsset from './FrameioAsset';\nimport { frameioAssetUpdater } from './FrameioContext';\nimport type { ISAMObject } from '../core/ISAMObject';\n\n// See https://developer.frame.io/api/reference/operation/getAsset/\n//  for schema of IFrameioAssetResponse. FrameioVersionStack\n//  encapsulates the data for assets of type=\"version_stack\".\n//\n// See FrameioFile, FrameioFolder for other asset types.\nexport default class FrameioVersionStack extends FrameioAsset {\n    private _children?: Array<FrameioAsset>;\n    private _coverAsset?: FrameioAsset;\n    private _coverAssetId: string = '';\n    private _versions: number = 0;\n\n    get coverAssetId(): string {\n        return this._coverAssetId;\n    }\n\n    async getCoverAsset(): Promise<FrameioAsset> {\n        if (!this._coverAsset) {\n            this._coverAsset = await this.context.getAsset(this.coverAssetId);\n        }\n\n        return this._coverAsset!;\n    }\n\n    get versions(): number {\n        return this._versions;\n    }\n\n    set coverAsset(asset: FrameioAsset) {\n        this._coverAsset = asset;\n    }\n\n    async getChildren(): Promise<Array<FrameioAsset>> {\n        if (!this._children) {\n            const ctx = this.context;\n            const response = await ctx._frameioInterface.getChildren(this.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioAsset>();\n\n            // IFrameioAssetResponse is a special case, as it corresponds to multiple classes\n            // inheriting from FrameioAsset ( FrameioFile, FrameioFolder, FrameioVersionStack ),\n            // so use a utility function to select the correct updater for the type.\n            //\n            // See also FrameioContext.getAncestors()\n            this._children = response.map((asset: IFrameioAssetResponse) => frameioAssetUpdater(session, asset));\n            session.commit();\n        }\n\n        return this._children;\n    }\n}\n\nexport const FrameioVersionStackUpdater = new ItemUpdater<FrameioVersionStack, Partial<IFrameioAssetResponse>>({\n    localItemType: FrameioVersionStack,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_coverAsset': {\n            // when the update reads response.root_asset\n            // ( which matches name: 'root_asset' ),\n            // it will invoke set: with the child object\n            //\n            name: 'cover_asset',\n            format: 'object',\n            set: (response: IFrameioAssetResponse, dest: ISAMObject): void => {\n                const stack = dest as FrameioVersionStack;\n                const pool = stack.context._objectPool;\n                const session = pool.createUpdateSession<FrameioAsset>();\n                const asset = frameioAssetUpdater(session, response);\n                session.commit();\n\n                stack.coverAsset = asset;\n            },\n\n        },\n        '_coverAssetId': 'cover_asset_id',\n        '_insertedAt': { name: 'inserted_at', format: 'date' },\n        '_name': 'name',\n        '_parentId': 'parent_id',\n        '_projectId': 'project_id',\n        '_teamId': 'team_id',\n        '_updatedAt': { name: 'updated_at', format: 'date' },\n        '_versions': { name: 'versions', format: 'number' }\n    })\n});\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nimport type { FrameioReviewLinksChangeEventParam, IFrameioReviewLinkResponse } from './FrameioInterface';\nimport type { FrameioSourceDocument } from './FrameioContext';\nimport type FrameioContext from './FrameioContext';\nimport FrameioBase from './FrameioBase';\nimport type FrameioAsset  from './FrameioAsset';\nimport type FrameioFile  from './FrameioFile';\nimport type FrameioFolder  from './FrameioFolder';\nimport FrameioVersionStack, { FrameioVersionStackUpdater } from './FrameioVersionStack';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\n\n// See https://developer.frame.io/api/reference/operation/getTeamsByAccount/\n//  for schema of the data FrameioTeam encapsulates.\nexport default class FrameioReviewLink extends FrameioBase {\n    private _name: string = '';\n    private _shortUrl: string = '';\n    private _ownerId: string = '';\n    private _projectId: string = '';\n    private _active: boolean = false;\n    private _inviteOnly: boolean = false;\n    private _etag?: string;\n\n    private _itemId?: string;\n    private _item?: FrameioAsset;\n\n    get name(): string {\n        return this._name;\n    }\n\n    get shortUrl(): string {\n        return this._shortUrl;\n    }\n\n    get ownerId(): string {\n        return this._ownerId;\n    }\n\n    get projectId(): string {\n        return this._projectId;\n    }\n\n    get active(): boolean {\n        return this._active;\n    }\n\n    get inviteOnly(): boolean {\n        return this._inviteOnly;\n    }\n\n    get itemId(): string | undefined {\n        return this._itemId;\n    }\n\n    /*\n     * Returns the number of artifacts currently in the review.\n     */\n    async getArtifactCount(): Promise<number> {\n        const item = await this.getItem();\n\n        if (item instanceof FrameioVersionStack) {\n            return item.versions;\n        }\n\n        return 1;\n    }\n\n    /*\n    * Recents the most recently published artifact,\n    * a FrameioFile containing a PDF.\n    */\n    async getArtifact(): Promise<FrameioFile> {\n        const item = await this.getItem();\n\n        if (item instanceof FrameioVersionStack) {\n            return (await item.getCoverAsset()) as FrameioFile;\n        }\n\n        return item as FrameioFile;\n    }\n\n    async getItem(): Promise<FrameioAsset> {\n        if (!this._item) {\n            if (!this._itemId) {\n                return Promise.reject(SAMError.create(SAMErrorCode.BAD_REQUEST, `FrameioReviewLink.getItem() could not find item ${this._itemId}`));\n            }\n\n            this._item = await this.context.getAsset(this._itemId);\n        }\n\n        return this._item!;\n    }\n\n    private _dispatchReviewLinksChangeEvent(source: FrameioSourceDocument) {\n        const ctx: FrameioContext = this.context;\n\n        // After a successful updateReviewLink(),\n        // we use SAM.cpp to dispatch an event to all DOM's,\n        // so they can each update FrameioContext._reviewLinksForDocument\n        //\n        // For example, when ShareSheet creates a new review link,\n        // ShareSheet and Commenting want to update their cache.\n        //\n        // See also FrameioContext._handleReviewLinksChangeEvent()\n\n        const param: FrameioReviewLinksChangeEventParam = {\n            source,\n            reviewLink: {\n                id: this.id,\n                name: this._name,\n                short_url: this._shortUrl,\n                owner_id: this._ownerId,\n                project_id: this._projectId,\n                is_active: (this._active) ? true : false,\n                access_control: {\n                    invite_only: (this._inviteOnly) ? true : false\n                },\n                'frameio:artifactId': this._itemId,\n                'repo:etag': this._etag\n            }\n        };\n\n        ctx._frameioInterface.dispatchReviewLinksChangeEvent(JSON.stringify(param));\n    }\n    async updateReviewLink(source: FrameioSourceDocument, parent: FrameioFolder, artifactPath: string) {\n        const file = await parent.createFile(this.name, artifactPath);\n\n        if (!this._itemId) {\n            // (_itemId === undefined) means this review has never been updated,\n            // so the file asset should be added as an item to the review and remembered.\n            const ctx: FrameioContext = this.context;\n\n            const response = await ctx._frameioInterface.reviewLinkAddAsset(this.id, file.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioReviewLink>();\n            FrameioReviewLinkUpdater.updateRemoteItem(session, response); // updates this\n            session.commit();\n\n            // Notify the Review Service of the newly created review.\n            const result = await ctx._reviewServiceInterface.createReviewLink({\n                ...source,\n                projectId: this.projectId,\n                reviewLinkId: this.id,\n                artifactId: file.id\n            });\n            this._etag = result['repo:etag'];\n\n            this._item = file;\n            this._itemId = file.id;\n        } else {\n            // (_itemId !== undefined) means this isn't the first update.\n            //\n            // For the second update, we'll version the original file\n            // (this._itemId) with the new file to create a stack.\n            // We'll overwrite this._itemId with the stack's id and notify\n            // the Review Service.\n            //\n            // For any remaining calls, this._itemId is already a stack,\n            // and versioning a stack with a new file just adds the file\n            // to the stack. As the stack doesn't change, there's no\n            // further need to update the Review Service.\n\n            const ctx: FrameioContext = this.context;\n            const response = await ctx._frameioInterface.addVersionToAsset(this._itemId, file.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioVersionStack>();\n            const item = FrameioVersionStackUpdater.updateRemoteItem(session, response);\n            session.commit();\n\n            if (this._itemId !== item.id) {\n                // Notify the Review Service that the file\n                // has been replaced with a version stack.\n                const result = await ctx._reviewServiceInterface.updateReviewLink({\n                    ...source,\n                    projectId: this.projectId,\n                    reviewLinkId: this.id,\n                    artifactId: item.id,\n                    etag: this._etag\n                });\n                this._etag = result['repo:etag'];\n\n                this._item = item;\n                this._itemId = item.id;\n            }\n        }\n        this._dispatchReviewLinksChangeEvent(source);\n    }\n}\n\nexport const FrameioReviewLinkUpdater = new ItemUpdater<FrameioReviewLink, Partial<IFrameioReviewLinkResponse>>({\n    localItemType: FrameioReviewLink,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_name': 'name',\n        '_shortUrl': 'short_url',\n        '_ownerId': 'owner_id',\n        '_projectId': 'project_id',\n        '_active': { name: 'is_active', format: 'boolean' },\n        '_inviteOnly': { name: 'access_control.invite_only', format: 'boolean' },\n        '_itemId': 'frameio:artifactId',\n        '_etag': 'repo:etag'\n    })\n});\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport type { ISAMObject } from '../indexPrivate';\n\nimport type {\n    IFrameioAssetResponse,\n    IFrameioProjectResponse,\n    IFrameioTeamResponse,\n    IFrameioFolderTreeFolderResponse\n} from './FrameioInterface';\nimport type FrameioContext from './FrameioContext';\nimport type FrameioFolder from './FrameioFolder';\nimport { FrameioFolderUpdater } from './FrameioFolder';\nimport type FrameioTeam from './FrameioTeam';\nimport { FrameioTeamUpdater } from './FrameioTeam';\nimport type FrameioReviewLink from './FrameioReviewLink';\nimport { FrameioReviewLinkUpdater } from './FrameioReviewLink';\nimport FrameioBase from './FrameioBase';\n\n// See https://developer.frame.io/api/reference/operation/getProjectsByTeam/\n//  for schema of the data FrameioProject encapsulates.\nexport default class FrameioProject extends FrameioBase {\n    private _reviews: Array<FrameioReviewLink> | undefined;\n    private _rootAssetId: string = '';\n    private _rootFolder: FrameioFolder | undefined;\n    private _name: string = '';\n    private _ownerId: string = '';\n    private _teamId: string = '';\n    private _team: FrameioTeam | undefined;\n\n\n    get name(): string {\n        return this._name;\n    }\n\n    get ownerId(): string {\n        return this._ownerId;\n    }\n\n    get rootAssetId(): string {\n        return this._rootAssetId;\n    }\n\n    get teamId(): string {\n        return this._teamId;\n    }\n\n    async getTeam(): Promise<FrameioTeam> {\n        if (!this._team) {\n            this._team = await this.context.getTeam(this.rootAssetId);\n        }\n\n        return this._team!;\n    }\n\n    async getRootFolder(): Promise<FrameioFolder> {\n        if (!this._rootFolder) {\n            this._rootFolder = await this.context.getAsset(this.rootAssetId) as FrameioFolder;\n        }\n\n        return this._rootFolder!;\n    }\n\n    async getReviewLinks(): Promise<FrameioReviewLink[]> {\n        let reviews = this._reviews;\n        if (!reviews) {\n            const ctx = this.context;\n\n            const response = await ctx._frameioInterface.getReviewLinks(this.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioReviewLink>();\n            reviews = FrameioReviewLinkUpdater.updateRemoteItems(session, response);\n            session.commit();\n\n            this._reviews = reviews;\n        }\n\n        return reviews;\n    }\n\n    private createFolder(data: any, folder: IFrameioFolderTreeFolderResponse): FrameioFolder {\n        const ctx = this.context;\n\n        // IFrameioFolderTreeFolderResponse only contains\n        //      { id, name, parent_id }\n        //\n        // but FrameioFolderUpdater expects to read\n        //      { id, name, parent_id, project_id, team_id }\n        //\n        // from a IFrameioAssetResponse, so copy { project_id, team_id }\n        // from this project into the response so we can use the\n        // updater.\n\n        const response = folder as IFrameioAssetResponse;\n        response['project_id'] = this.id;\n        response['team_id'] = this.teamId;\n\n        const session = ctx._objectPool.createUpdateSession<FrameioFolder>();\n        const that = FrameioFolderUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        that['_children'] = data[response.id].map((folder: IFrameioFolderTreeFolderResponse) => this.createFolder(data, folder));\n\n        return that;\n    }\n    async getFolderTree(): Promise<FrameioFolder> {\n        // returns the rootFolder, but only after constructing FrameioFolder's for all of the\n        // folders in project using an undocumented API.\n\n        const response =  await this._core.frameioContext._frameioInterface.getFolderTree(this.id);\n\n        this._rootFolder = this.createFolder(response.data, response.data['root'][0]);\n\n        return this._rootFolder;\n    }\n\n    async createReviewLink(display_name: string): Promise<FrameioReviewLink> {\n        const ctx: FrameioContext = this.context;\n        const response = await ctx._frameioInterface.createReviewLink(this.id, display_name);\n\n\n        const session = ctx._objectPool.createUpdateSession<FrameioReviewLink>();\n        const review = FrameioReviewLinkUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        if (this._reviews) {\n            // update the cache of reviews owned by this project\n            // by adding the newly created review.\n            this._reviews.push(review);\n        }\n\n        return review;\n    }\n}\n\nexport const FrameioProjectUpdater = new ItemUpdater<FrameioProject, Partial<IFrameioProjectResponse>>({\n    localItemType: FrameioProject,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_name': 'name',\n        '_ownerId': 'owner_id',\n        '_rootAssetId': 'root_asset_id',\n        '_rootFolder': {\n            // when the update reads response.root_asset\n            // ( which matches name: 'root_asset' ),\n            // it will invoke set: with the child object\n            //\n            name: 'root_asset',\n            format: 'object',\n            set: (rootFolder: IFrameioAssetResponse, dest: ISAMObject): void => {\n                const project = dest as FrameioProject;\n                const pool = project.context._objectPool;\n                const session = pool.createUpdateSession<FrameioFolder>();\n                const folder = FrameioFolderUpdater.updateRemoteItem(session, rootFolder);\n                session.commit();\n\n                // @ts-expect-error\n                project._rootFolder = folder;\n            },\n\n        },\n        '_team': {\n            // The owner property of an IFrameioAccountResponse is a nested\n            // object of type IFrameioUserResponse, so let's construct that\n            // while we are here.\n            set: (team: IFrameioTeamResponse, dest: ISAMObject) => {\n                const project = dest as FrameioProject;\n                const context = project.context;\n                const pool = context._objectPool;\n\n                const session = pool.createUpdateSession<FrameioTeam>();\n                project['_team'] = FrameioTeamUpdater.updateRemoteItem(session, team);\n                session.commit();\n            },\n            name: 'team',\n            format: 'object'\n        },\n\n        '_teamId': 'team_id'\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ISAMObject } from '../indexPrivate';\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\nimport type { IFrameioAccountResponse, IFrameioUserResponse } from './FrameioInterface';\nimport FrameioBase from './FrameioBase';\nimport type FrameioProject from './FrameioProject';\nimport { FrameioProjectUpdater } from './FrameioProject';\nimport type FrameioTeam from './FrameioTeam';\nimport { FrameioTeamUpdater } from './FrameioTeam';\nimport type FrameioUser from './FrameioUser';\nimport { FrameioUserUpdater } from './FrameioUser';\n\n// See https://developer.frame.io/api/reference/operation/getAccount/\n//  for schema of the data FrameioAccount encapsulates.\nexport default class FrameioAccount extends FrameioBase {\n    private _teams: Array<FrameioTeam> | undefined;\n    private _sharedProjects: Array<FrameioProject> | undefined;\n    private _displayName: string = '';\n    private _owner: FrameioUser | undefined;\n    private _ownerId: string = '';\n    private _version: number = 0;\n\n    /**\n     * @package - not yet decided if id's are internal use only.\n     *  In the meantime, I'm decorating them to discourage their use.\n     */\n    get ownerId(): string {\n        return this._ownerId;\n    }\n\n    get owner(): FrameioUser | undefined {\n        return this._owner;\n    }\n\n    get displayName(): string {\n        return this._displayName!;\n    }\n\n    get version(): number {\n        return this._version;\n    }\n\n    // getTeams() should really be a getter for property teams,\n    // but then we'd need an async getter, and I'm not sure\n    // of the convention for that.\n    // https://medium.com/trabe/async-getters-and-setters-is-it-possible-c18759b6f7e4\n\n    // see getProjectTree() below\n    async getTeams(): Promise<Array<FrameioTeam>> {\n        let teams = this._teams;\n        if (!teams) {\n            const ctx = this.context;\n\n            const teamsResponse = await ctx._frameioInterface.getTeams(this.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioTeam>();\n            teams = FrameioTeamUpdater.updateRemoteItems(session, teamsResponse);\n            session.commit();\n\n            this._teams = teams;\n        }\n\n        return teams;\n    }\n\n    async getSharedProjects(): Promise<Array<FrameioProject>> {\n        let shared = this._sharedProjects;\n        if (!shared) {\n            const ctx = this.context;\n\n            const projectsResponse = await ctx._frameioInterface.getSharedProjects(this.id);\n            const session = ctx._objectPool.createUpdateSession<FrameioProject>();\n            shared = FrameioProjectUpdater.updateRemoteItems(session, projectsResponse);\n            session.commit();\n\n            this._sharedProjects = shared;\n        }\n\n        return shared;\n    }\n\n    async getSharedTeams(): Promise<Array<FrameioTeam>> {\n        const projects = await this.getSharedProjects();\n        const set = new Set<string>();\n        const teams: Array<FrameioTeam> = [];\n\n        // The array we return should not contain duplicates,\n        // but a team could have more than one shared projects,\n        // so use a set to unique the teams we add to the array.\n\n        for (const project of projects) {\n            const id = project.teamId;\n\n            if (!set.has(id)) {\n                const team = await project.getTeam();\n\n                set.add(id);\n                teams.push(team);\n            }\n        }\n\n        return teams;\n    }\n\n    // same return as getTeams(), but we pre-load the projects of each team\n    // before resolving the promise.\n    async getProjectTree(): Promise<Array<FrameioTeam>> {\n        const teams = await this.getTeams();\n        const promises: Array<any> = [];\n\n        teams.forEach((team: any) => {\n            promises.push(team.getProjects());\n        });\n\n        await Promise.all(promises);\n        return teams;\n    }\n}\n\nexport const FrameioAccountUpdater = new ItemUpdater<FrameioAccount, Partial<IFrameioAccountResponse>>({\n    localItemType: FrameioAccount,\n    remoteIdProperty: 'id',\n    propertyUpdater: new PropertyUpdater({\n        '_displayName': 'display_name',\n        '_owner': {\n            // The owner property of an IFrameioAccountResponse is a nested\n            // object of type IFrameioUserResponse, so let's construct that\n            // while we are here.\n            set: (owner: IFrameioUserResponse, dest: ISAMObject) => {\n                const account = dest as FrameioAccount;\n                const context = account.context;\n                const pool = context._objectPool;\n\n                const session = pool.createUpdateSession<FrameioUser>();\n                account['_owner'] = FrameioUserUpdater.updateRemoteItem(session, owner);\n                session.commit();\n            },\n            name: 'owner',\n            format: 'object'\n        },\n        '_ownerId': 'owner_id',\n        '_version': { name: 'version', format: 'number' }\n    })\n});\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport ItemPool from '../core/ItemPool';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\n\nimport type {\n    IFrameioAssetResponse,\n    IFrameioAuthenticationStatus,\n    FrameioAuthenticationInfo,\n    FrameioAdobeSusiInfo, IFrameioReviewLinkResponse, FrameioReviewLinksChangeEventParam\n} from './FrameioInterface';\nimport FrameioInterface from './FrameioInterface';\nimport type {\n    IReviewServiceFrameLinkResponse\n} from '../interface/AssetReviewServiceInterface';\nimport AssetReviewServiceInterface from '../interface/AssetReviewServiceInterface';\nimport type FrameioBase from './FrameioBase';\nimport type FrameioUser from './FrameioUser';\nimport { FrameioUserUpdater } from './FrameioUser';\nimport type FrameioAccount from './FrameioAccount';\nimport { FrameioAccountUpdater } from './FrameioAccount';\nimport type FrameioAsset from './FrameioAsset';\nimport type FrameioFile from './FrameioFile';\nimport { FrameioFileUpdater } from './FrameioFile';\nimport type FrameioFolder from './FrameioFolder';\nimport { FrameioFolderUpdater } from './FrameioFolder';\nimport type FrameioProject from './FrameioProject';\nimport { FrameioProjectUpdater } from './FrameioProject';\nimport type FrameioTeam from './FrameioTeam';\nimport { FrameioTeamUpdater } from './FrameioTeam';\nimport type FrameioVersionStack from './FrameioVersionStack';\nimport { FrameioVersionStackUpdater } from './FrameioVersionStack';\nimport type FrameioReviewLink from './FrameioReviewLink';\nimport { FrameioReviewLinkUpdater } from './FrameioReviewLink';\nimport type FrameioComment from './FrameioComment';\nimport { FrameioCommentUpdater } from './FrameioComment';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type { IEventMap } from '../core/ITypedEventEmitter';\nimport type FrameioAuthorizationChangeEvent from './FrameioAuthorizationChangeEvent';\nimport TypedEventEmitter from '../core/TypedEventEmitter';\nimport type FrameioReviewLinksChangeEvent from './FrameioReviewLinksChangeEvent';\nimport { SharedFrameioReviewLinksChangeEvent } from './FrameioReviewLinksChangeEvent';\n\n//----------------------------------------------------------------\n\ntype FrameioCloudSourceDocument = {\n    assetId: string;\n    assetRegion?: string;\n    repositoryId?: string;\n    documentId?: never;\n}\n\ntype FrameioLocalSourceDocument = {\n    documentId: string;\n    assetId?: never;\n    assetRegion?: never;\n    repositoryId?: never;\n}\n\n// When the source is a local-only document, you must provide only the documentId.\n//\n// When the source is a creative cloud document, you must provide an assetId,\n// you cannot provide a documentId, and you can optionally provide the assetRegion\n// and repositoryId for potential performance gains.\nexport type FrameioSourceDocument =  (FrameioCloudSourceDocument | FrameioLocalSourceDocument);\n\n//----------------------------------------------------------------\n\ntype FrameioReviewLinkForDocumentError = {\n    error: SAMError;\n    reviewLink?: never;\n}\n\ntype FrameioReviewLinkForDocumentReviewLink = {\n    error?: never;\n    reviewLink: FrameioReviewLink;\n}\n\n// getReviewLinksForDocument() returns a Promise<Array<FrameioReviewLinkForDocumentItem>>\nexport type FrameioReviewLinkForDocumentItem =  (FrameioReviewLinkForDocumentError | FrameioReviewLinkForDocumentReviewLink);\n\n//----------------------------------------------------------------\n\nexport interface FrameioContextEvents extends IEventMap {\n    frameioAuthorizationChange: FrameioAuthorizationChangeEvent;\n    frameioReviewLinksChange: FrameioReviewLinksChangeEvent;\n}\n\n//----------------------------------------------------------------\n\nexport default class FrameioContext extends TypedEventEmitter<FrameioContextEvents> implements ISAMObject, SAM.FrameioContext {\n    /**\n     * @package - internal use only\n     */\n    _objectPool: ItemPool<FrameioBase> = new ItemPool(this._core, 'frameio');\n\n    /**\n     * @package - internal use only\n     */\n    _frameioInterface: FrameioInterface = new FrameioInterface(this);\n\n    /**\n     * @package - internal use only\n     */\n    _reviewServiceInterface: AssetReviewServiceInterface = new AssetReviewServiceInterface(this._core);\n\n    private _currentUserId: string | undefined;\n    private _currentUser: FrameioUser | undefined;\n    private _accounts: Array<FrameioAccount> | undefined;\n    private _reviewLinksForDocument: Map<string, WeakRef<Array<FrameioReviewLinkForDocumentItem>>> = new Map();\n\n    constructor(readonly _core: ISAMCorePrivate) {\n        super();\n    }\n    /**\n     * @package\n     *\n     * We _updateUserId() whenever the native FrameioAssetContext::authInfo_\n     * changes, to allow us to reset any user specific data when the user id\n     * changes.\n     */\n    _updateCurrentUserId(id: string | undefined) {\n        if (!id || (this._currentUserId !== id)) {\n            this._currentUserId = id;\n            this._currentUser = undefined;\n            this._accounts = undefined;\n            this._reviewLinksForDocument.clear();\n        }\n    }\n\n    private _mapKeyForSourceDocument(source: FrameioSourceDocument): string {\n        // We need a hash key for a Map<>,\n        // so use the assetId of cloud documents,\n        // and the documentId of local documents.\n        if (source.documentId) {\n            return source.documentId;\n        }\n\n        // ignore the optional assetRegion and repositoryId\n        return source.assetId!;\n    }\n\n    private _retainUntilTimeout(weak: WeakRef<Array<FrameioReviewLinkForDocumentItem>>, milliseconds = 2 * 60 * 1000) {\n        const obj = weak.deref();\n\n        // obj will be retained until the timeout fires\n        // because it's referenced in the handler.\n        setTimeout(function (): any { return obj; }, milliseconds);\n    }\n\n    _handleReviewLinksChangeEvent(json: string): void {\n        // after a successful FrameioReviewLink.updateReviewLink(),\n        // we use SAM.cpp to dispatch an event to all DOM's,\n        // so they can each update FrameioContext._reviewLinksForDocument\n        //\n        // For example, when ShareSheet creates a new review link,\n        // ShareSheet and Commenting want to update their cache.\n        //\n        // See also FrameioReviewLink._dispatchReviewLinksChangeEvent()\n\n        const param: FrameioReviewLinksChangeEventParam = JSON.parse(json);\n        const response: Partial<IFrameioReviewLinkResponse> = param.reviewLink;\n        const key: string = this._mapKeyForSourceDocument(param.source);\n\n        const session = this._objectPool.createUpdateSession<FrameioReviewLink>();\n        const reviewLink = FrameioReviewLinkUpdater.updateRemoteItem(session, response);\n        session.commit();\n\n        const weak = new WeakRef([ { reviewLink } ]);\n\n        this._reviewLinksForDocument.set(key, weak);\n        this._retainUntilTimeout(weak);\n\n        // let client know the reviewLinksForDocument has changed.\n        this.dispatch(SharedFrameioReviewLinksChangeEvent);\n    }\n\n    async isAuthenticated(): Promise<boolean> {\n        return await this._frameioInterface.isAuthenticated();\n    }\n\n    async authenticationStatus(): Promise<IFrameioAuthenticationStatus> {\n        return await this._frameioInterface.authenticationStatus();\n    }\n\n    // !!@ Consider making this package scoped\n    async getToken(): Promise<string> {\n        return this._frameioInterface.getToken();\n    }\n\n    async refreshToken(): Promise<string> {\n        return this._frameioInterface.refreshToken();\n    }\n\n    /* Call with void parameters to rely on native authentication.\n     * The return is a token.\n     */\n    async authenticate(info?: FrameioAuthenticationInfo): Promise<string> {\n        return await this._frameioInterface.authenticate(info);\n    }\n\n    async deauthenticate(): Promise<void> {\n        return await this._frameioInterface.deauthenticate();\n    }\n\n    async getCurrentUser(): Promise<FrameioUser> {\n        let user = this._currentUser;\n        if (!user) {\n            const response = await this._frameioInterface.getCurrentUser();\n            const session = this._objectPool.createUpdateSession<FrameioUser>();\n            user = FrameioUserUpdater.updateRemoteItem(session, response);\n            session.commit();\n\n            this._currentUser = user;\n        }\n        return user;\n    }\n\n\n    async getAccounts(): Promise<Array<FrameioAccount>> {\n        let accounts = this._accounts;\n        if (!accounts) {\n            const response = await this._frameioInterface.getAccounts();\n            const session = this._objectPool.createUpdateSession<FrameioAccount>();\n            accounts = FrameioAccountUpdater.updateRemoteItems(session, response);\n            session.commit();\n            this._accounts = accounts;\n        }\n\n        return accounts;\n    }\n\n    private _getLocalAncestors(id: string): Array<FrameioAsset> | undefined {\n        // Based on prior usage of the package, it's possible\n        // we can build ancestors from already local objects\n        // in the _objectPool. If so, return the completed\n        // array so getAncestors() can avoid the server call.\n        //\n        // However, if not all of the ancestors are locally available,\n        // make the server call to get the entire array.\n        const ancestors = new Array<FrameioAsset>();\n\n        for (;;) {\n            const asset = this._objectPool.getLocalItemById(id) as FrameioAsset;\n\n            if (asset === undefined) {\n                // At least one item isn't local,\n                // so we'll need to GET the ancestors from the server.\n                return undefined;\n            }\n\n            // add latest ancestor to front of array\n            ancestors.unshift(asset);\n\n            // walk up one link of the ancestor chain\n            if (asset.parentId) {\n                id = asset.parentId;\n                continue;\n            }\n\n            // we've reached the root asset of the project\n            break;\n        }\n        return ancestors;\n    }\n\n    async getAncestors(id: string): Promise<Array<FrameioAsset>> {\n        // ideally, the whole ancestor chain is already local,\n        // and we can fulfill this promise without a server call.\n        let ancestors = this._getLocalAncestors(id);\n\n        if (!ancestors) {\n            const response = await this._frameioInterface.getAncestors(id);\n            const session = this._objectPool.createUpdateSession<FrameioAsset>();\n\n            // IFrameioAssetResponse is a special case, as it corresponds to multiple classes\n            // inheriting from FrameioAsset ( FrameioFile, FrameioFolder, FrameioVersionStack ),\n            // so use a utility function to select the correct updater for the type.\n            //\n            // See also FrameioFolder.getChildren()\n            ancestors = response.map((asset: IFrameioAssetResponse) => frameioAssetUpdater(session, asset));\n\n            session.commit();\n        }\n\n        return ancestors;\n    }\n\n    async getReviewLinksForDocument(source: FrameioSourceDocument, refresh: boolean = true): Promise<Array<FrameioReviewLinkForDocumentItem>> {\n        const key: string = this._mapKeyForSourceDocument(source);\n        const weak = this._reviewLinksForDocument.get(key);\n        let result: Array<FrameioReviewLinkForDocumentItem> | undefined = weak ? weak.deref() : undefined;\n\n        if (!refresh && result) {\n            this._retainUntilTimeout(weak!); // non-null result means weak is also non-null\n            return result; // return cached result\n        }\n\n        // compute result from scratch\n        result = [];\n\n        // The Review Service maintains a database of FrameioReview links we've\n        // created maintained by our calls to ReviewServiceInterface.createReviewLinks()\n        // and ReviewServiceInterface.updateReviewLinks().\n\n        // Get the list of review links\n        const reviews: Array<IReviewServiceFrameLinkResponse> = await this._reviewServiceInterface.getReviewLinks(source);\n\n        // I'm uncertain of the list ordering, so sort it by date.\n        reviews.sort((a, b) => (b['repo:createdDate'] - a['repo:createdDate']));\n\n        // The id's associated with a review link may no longer be valid\n        // ( i.e. the link has been deleted ) or not currently valid\n        // ( i.e. we've logged into the wrong account ), so we need\n        // to filter the list to only containing currently valid\n        // review links.\n        //\n        // NOTE: As we cannot distinquish between no longer valid and\n        // not currently valid, it's not safe to\n        // ReviewServiceInterface.deleteReviewLinks() to clean up the\n        // list.\n\n        for (let i = 0; i < reviews.length; i++) {\n            const review = reviews[i];\n            const projectId = review['frameio:projectId'];\n            const reviewLinkId = review['frameio:reviewLinkId'];\n            const itemId = review['frameio:artifactId'];\n            const etag = review['repo:etag'];\n\n            // review is valid if we can obtain a reviewLink using reviewLinkId,\n            // and we can obtain an item using itemId.\n            //\n            // ShareSheet potentially shows toast when the most recent reviewLinks\n            // are invalid, so we push FrameioReviewLinkForDocumentError into\n            // result when there's an error validating review.\n            //\n            // Because validation is expensive, and because reviews[] grows\n            // unbounded, and because ShareSheet only cares whether there is\n            // 0 or 1 valid reviews, we stop after adding a valid reviewLink\n            // to result.\n\n            let reviewLink: FrameioReviewLink | undefined = undefined;\n\n            // obtain the reviewLink directly from Frame.io\n            try {\n                const response = await this._frameioInterface.getReviewLink(reviewLinkId);\n                const session = this._objectPool.createUpdateSession<FrameioReviewLink>();\n                reviewLink = FrameioReviewLinkUpdater.updateRemoteItem(session, response);\n                session.commit();\n            } catch (e) {\n                // we expect it to throw when a review has been disabled.\n            }\n\n            try {\n                if (!reviewLink) {\n                    // disabled reviewLink's are known to throw 403 errors,\n                    // so as a fallback, try to get the project, the project's\n                    // list of reviewLinks, and find reviewLinkId in the list\n                    // (disabled reviewLink's are known to be reachable this way)\n\n                    // project is cached in the object pool,\n                    // and project._reviewLinks is memoized,\n                    // so although we are in a loop,\n                    // each method should never hit the network more than once.\n                    const project = await this.getProject(projectId);\n                    const reviewLinks = await project.getReviewLinks();\n\n                    reviewLink = reviewLinks.find(({ id }) => (id === reviewLinkId));\n                }\n\n                if (reviewLink) {\n                    // Copy data that's on the Review Service and not Frame.io\n                    // into the reviewLink.\n                    reviewLink['_itemId'] = itemId;\n                    reviewLink['_etag'] = etag;\n\n                    // getItem() rejects when itemId isn't valid.\n                    await reviewLink.getItem();\n\n                    result.push({ reviewLink });\n                    break;\n                } else {\n                    const error = SAMError.create(SAMErrorCode.NOT_FOUND, `frameio:reviewLinkId = ${reviewLinkId} not found in projectId = ${projectId}`);\n                    result.push({  error });\n                }\n            } catch (e) {\n                const error = e as SAMError;\n                result.push({ error });\n            }\n        }\n\n        const ref = new WeakRef(result);\n\n        // cache the newly computed result\n        this._reviewLinksForDocument.set(key, ref);\n        this._retainUntilTimeout(ref);\n\n        return result;\n    }\n\n\n    async getAccount(id: string): Promise<FrameioAccount> {\n        const accounts = await this.getAccounts();\n        let account = accounts.find(element => (element.id === id));\n\n        if (!account) {\n            const response = await this._frameioInterface.getAccount(id);\n            const session = this._objectPool.createUpdateSession<FrameioAccount>();\n            account = FrameioAccountUpdater.updateRemoteItem(session, response);\n            session.commit();\n        }\n\n        return account;\n    }\n\n    @keepAlive\n    async getAsset(id: string): Promise<FrameioAsset> {\n        // avoid server call for local asset\n        let asset = this._objectPool.getLocalItemById(id) as FrameioAsset;\n\n        if (!asset) {\n            // fetch remote asset with a server call\n            const response = await this._frameioInterface.getAsset(id);\n            const session = this._objectPool.createUpdateSession<FrameioAsset>();\n            asset = frameioAssetUpdater(session, response);\n            session.commit();\n        }\n        return asset;\n    }\n\n    async getTeam(id: string): Promise<FrameioTeam> {\n        // avoid server call for local asset\n        let team = this._objectPool.getLocalItemById(id) as FrameioTeam;\n\n        if (!team) {\n            // fetch remote asset with a server call\n            const response = await this._frameioInterface.getTeam(id);\n            const session = this._objectPool.createUpdateSession<FrameioTeam>();\n            team = FrameioTeamUpdater.updateRemoteItem(session, response);\n            session.commit();\n        }\n        return team;\n    }\n\n    async getProject(id: string): Promise<FrameioProject> {\n        // avoid server call for local asset\n        let project = this._objectPool.getLocalItemById(id) as FrameioProject;\n\n        if (!project) {\n            // fetch remote asset with a server call\n            const response = await this._frameioInterface.getProject(id);\n            const session = this._objectPool.createUpdateSession<FrameioProject>();\n            project = FrameioProjectUpdater.updateRemoteItem(session, response);\n            session.commit();\n        }\n        return project;\n    }\n\n    async getComment(id: string): Promise<FrameioComment> {\n        // avoid server call for local asset\n        let comment = this._objectPool.getLocalItemById(id) as FrameioComment;\n\n        if (!comment) {\n            // fetch remote asset with a server call\n            const response = await this._frameioInterface.getComment(id);\n            const session = this._objectPool.createUpdateSession<FrameioComment>();\n            comment = FrameioCommentUpdater.updateRemoteItem(session, response);\n            session.commit();\n        }\n        return comment;\n    }\n\n    async getAdobeSusiInfo(): Promise<FrameioAdobeSusiInfo> {\n        return await this._frameioInterface.getAdobeSusiInfo();\n    }\n}\n\nexport function frameioAssetUpdater(session: IUpdateSession<FrameioBase>, asset: IFrameioAssetResponse): FrameioAsset {\n    // frame.io multiplexes asset.type's 'file', 'folder', 'version_stack' and 'bundle' into IFrameioAssetResponse,\n    // but we have separate FrameioFile, FrameioFolder, FrameioVersionStack classes that inherit from FrameioAsset.\n\n    if (asset.type === 'file') {\n        const fileSession = session as IUpdateSession<FrameioFile>;\n        return FrameioFileUpdater.updateRemoteItem(fileSession, asset);\n    } else if (asset.type === 'folder') {\n        const folderSession = session as IUpdateSession<FrameioFolder>;\n        return FrameioFolderUpdater.updateRemoteItem(folderSession, asset);\n    } else if (asset.type === 'version_stack') {\n        const versionStackSession = session as IUpdateSession<FrameioVersionStack>;\n        return FrameioVersionStackUpdater.updateRemoteItem(versionStackSession, asset);\n    }\n    throw SAMError.create(SAMErrorCode.UNSUPPORTED, `Invalid Frameio asset type ${asset.type}`);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { RelType } from '../interface/LinkUtils';\n\nexport enum AccessControlPrincipalType {\n    USER =  'https://ns.adobe.com/adobeaemcloud/aem/user',\n    GROUP = 'https://ns.adobe.com/adobeaemcloud/aem/group'\n}\n\nexport interface IAccessControlListResponse {\n    'repo:acl': IAccessControlEntryResponse[];\n}\n\nexport enum AccessControlPrivileges {\n    /**\n     * The existence of a resource can be checked.\n     */\n    ACK = 'ack',\n    /**\n     * The resource can be retrieved via a GET request.\n     */\n    READ = 'read',\n    /**\n     * The resource can be updated via a PUT request; and PATCH request where applicable.\n     */\n    WRITE = 'write',\n    /**\n     * The resource can be deleted via a DELETE request.\n     */\n    DELETE = 'delete'\n\n    /**\n     * @note\n     * COMPATIBILITY NOTE: FULL and MODIFY are deprecated aliases to combinations of privileges.\n     * New clients SHOULD NOT use these. They MAY continue to be used by existing clients to update policies,\n     * but will always be expanded to the individual non-aliased privileges when the policy is returned to clients.\n     * MODIFY privilege is translated to READ and WRITE.\n     * FULL privilege is translated to ACK, READ, WRITE, DELETE.\n     */\n}\n\nexport enum AccessControlModifier {\n    GRANT = 'grant',\n    DENY = 'deny'\n}\n\nexport enum AccessControlInheritance {\n    SELF = 'self',\n    DEEP = 'deep',\n    DEEP_OVERRIDE = 'deep_override'\n}\n\nexport interface IAccessControlResponse {\n    'etag': string;\n    'repo:acl': IAccessControlEntryResponse[];\n}\n\nexport interface IAccessControlEntryResponse {\n    'repo:principal': IAccessControlPrincipal | string;\n    'repo:privileges': AccessControlPrivileges[];\n    'repo:modifier': AccessControlModifier;\n    'repo:inheritance': AccessControlInheritance;\n    'repo:relations': RelType[];\n}\n\nexport enum RelTypePlatform {\n    PRINCIPAL_TYPE_IMS_USER = 'https://ns.adobe.com/adobecloudplatform/ims/user',\n    PRINCIPAL_TYPE_IMS_GROUP = 'https://ns.adobe.com/adobecloudplatform/ims/group'\n}\n\nexport interface IAccessControlPrincipal {\n    '@id': string;\n    '@type': RelTypePlatform;\n    'xdm:provider': IAccessControlProvider;\n}\n\nexport interface IAccessControlProvider {\n    '@id': 'https://ims-na1.adobelogin.com/' | string;\n}\n\nexport const AccessControlProvider = {\n    '@id': 'https://ims-na1.adobelogin.com/'\n};\n\nexport interface AdobeACEMetadata {\n    principal: IAccessControlPrincipal | string;\n    privileges: AccessControlPrivileges[];\n    modifier: AccessControlModifier;\n    inheritance: AccessControlInheritance;\n    relations?: RelType[];\n}\n\nexport type Principal = IAccessControlPrincipal;\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n    extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n    return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n    if (typeof b !== \"function\" && b !== null)\r\n        throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n    extendStatics(d, b);\r\n    function __() { this.constructor = d; }\r\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n    __assign = Object.assign || function __assign(t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    }\r\n    return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        t[p] = s[p];\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                t[p[i]] = s[p[i]];\r\n        }\r\n    return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n    return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n    if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n    return new (P || (P = Promise))(function (resolve, reject) {\r\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n    });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n    function verb(n) { return function (v) { return step([n, v]); }; }\r\n    function step(op) {\r\n        if (f) throw new TypeError(\"Generator is already executing.\");\r\n        while (_) try {\r\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n            if (y = 0, t) op = [op[0] & 2, t.value];\r\n            switch (op[0]) {\r\n                case 0: case 1: t = op; break;\r\n                case 4: _.label++; return { value: op[1], done: false };\r\n                case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                default:\r\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                    if (t[2]) _.ops.pop();\r\n                    _.trys.pop(); continue;\r\n            }\r\n            op = body.call(thisArg, _);\r\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n    }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n    var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n    if (m) return m.call(o);\r\n    if (o && typeof o.length === \"number\") return {\r\n        next: function () {\r\n            if (o && i >= o.length) o = void 0;\r\n            return { value: o && o[i++], done: !o };\r\n        }\r\n    };\r\n    throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n    if (!m) return o;\r\n    var i = m.call(o), r, ar = [], e;\r\n    try {\r\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n    }\r\n    catch (error) { e = { error: error }; }\r\n    finally {\r\n        try {\r\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n        }\r\n        finally { if (e) throw e.error; }\r\n    }\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n    for (var ar = [], i = 0; i < arguments.length; i++)\r\n        ar = ar.concat(__read(arguments[i]));\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n    for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n            r[k] = a[j];\r\n    return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n        if (ar || !(i in from)) {\r\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n            ar[i] = from[i];\r\n        }\r\n    }\r\n    return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n    return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n    return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n    function fulfill(value) { resume(\"next\", value); }\r\n    function reject(value) { resume(\"throw\", value); }\r\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n    var i, p;\r\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var m = o[Symbol.asyncIterator], i;\r\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n    if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n    return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n    o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n    if (mod && mod.__esModule) return mod;\r\n    var result = {};\r\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n    __setModuleDefault(result, mod);\r\n    return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n    return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n    extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n    return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n    if (typeof b !== \"function\" && b !== null)\r\n        throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n    extendStatics(d, b);\r\n    function __() { this.constructor = d; }\r\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n    __assign = Object.assign || function __assign(t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    }\r\n    return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        t[p] = s[p];\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                t[p[i]] = s[p[i]];\r\n        }\r\n    return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n    return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n    if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n    return new (P || (P = Promise))(function (resolve, reject) {\r\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n    });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n    function verb(n) { return function (v) { return step([n, v]); }; }\r\n    function step(op) {\r\n        if (f) throw new TypeError(\"Generator is already executing.\");\r\n        while (_) try {\r\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n            if (y = 0, t) op = [op[0] & 2, t.value];\r\n            switch (op[0]) {\r\n                case 0: case 1: t = op; break;\r\n                case 4: _.label++; return { value: op[1], done: false };\r\n                case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                default:\r\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                    if (t[2]) _.ops.pop();\r\n                    _.trys.pop(); continue;\r\n            }\r\n            op = body.call(thisArg, _);\r\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n    }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n    var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n    if (m) return m.call(o);\r\n    if (o && typeof o.length === \"number\") return {\r\n        next: function () {\r\n            if (o && i >= o.length) o = void 0;\r\n            return { value: o && o[i++], done: !o };\r\n        }\r\n    };\r\n    throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n    if (!m) return o;\r\n    var i = m.call(o), r, ar = [], e;\r\n    try {\r\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n    }\r\n    catch (error) { e = { error: error }; }\r\n    finally {\r\n        try {\r\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n        }\r\n        finally { if (e) throw e.error; }\r\n    }\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n    for (var ar = [], i = 0; i < arguments.length; i++)\r\n        ar = ar.concat(__read(arguments[i]));\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n    for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n            r[k] = a[j];\r\n    return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n        if (ar || !(i in from)) {\r\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n            ar[i] = from[i];\r\n        }\r\n    }\r\n    return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n    return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n    return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n    function fulfill(value) { resume(\"next\", value); }\r\n    function reject(value) { resume(\"throw\", value); }\r\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n    var i, p;\r\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var m = o[Symbol.asyncIterator], i;\r\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n    if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n    return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n    o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n    if (mod && mod.__esModule) return mod;\r\n    var result = {};\r\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n    __setModuleDefault(result, mod);\r\n    return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n    return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","import { __extends } from \"tslib\";\nvar genericMessage = \"Invariant Violation\";\nvar _a = Object.setPrototypeOf, setPrototypeOf = _a === void 0 ? function (obj, proto) {\n    obj.__proto__ = proto;\n    return obj;\n} : _a;\nvar InvariantError = /** @class */ (function (_super) {\n    __extends(InvariantError, _super);\n    function InvariantError(message) {\n        if (message === void 0) { message = genericMessage; }\n        var _this = _super.call(this, typeof message === \"number\"\n            ? genericMessage + \": \" + message + \" (see https://github.com/apollographql/invariant-packages)\"\n            : message) || this;\n        _this.framesToPop = 1;\n        _this.name = genericMessage;\n        setPrototypeOf(_this, InvariantError.prototype);\n        return _this;\n    }\n    return InvariantError;\n}(Error));\nexport { InvariantError };\nexport function invariant(condition, message) {\n    if (!condition) {\n        throw new InvariantError(message);\n    }\n}\nvar verbosityLevels = [\"debug\", \"log\", \"warn\", \"error\", \"silent\"];\nvar verbosityLevel = verbosityLevels.indexOf(\"log\");\nfunction wrapConsoleMethod(name) {\n    return function () {\n        if (verbosityLevels.indexOf(name) >= verbosityLevel) {\n            // Default to console.log if this host environment happens not to provide\n            // all the console.* methods we need.\n            var method = console[name] || console.log;\n            return method.apply(console, arguments);\n        }\n    };\n}\n(function (invariant) {\n    invariant.debug = wrapConsoleMethod(\"debug\");\n    invariant.log = wrapConsoleMethod(\"log\");\n    invariant.warn = wrapConsoleMethod(\"warn\");\n    invariant.error = wrapConsoleMethod(\"error\");\n})(invariant || (invariant = {}));\nexport function setVerbosity(level) {\n    var old = verbosityLevels[verbosityLevel];\n    verbosityLevel = Math.max(0, verbosityLevels.indexOf(level));\n    return old;\n}\nexport default invariant;\n//# sourceMappingURL=invariant.js.map","export var version = \"3.11.8\";\n//# sourceMappingURL=version.js.map","export function maybe(thunk) {\n    try {\n        return thunk();\n    }\n    catch (_a) { }\n}\n//# sourceMappingURL=maybe.js.map","import { maybe } from \"./maybe.js\";\nexport default (maybe(function () { return globalThis; }) ||\n    maybe(function () { return window; }) ||\n    maybe(function () { return self; }) ||\n    maybe(function () { return global; }) || // We don't expect the Function constructor ever to be invoked at runtime, as\n// long as at least one of globalThis, window, self, or global is defined, so\n// we are under no obligation to make it easy for static analysis tools to\n// detect syntactic usage of the Function constructor. If you think you can\n// improve your static analysis to detect this obfuscation, think again. This\n// is an arms race you cannot win, at least not in JavaScript.\nmaybe(function () {\n    return maybe.constructor(\"return this\")();\n}));\n//# sourceMappingURL=global.js.map","var prefixCounts = new Map();\n// These IDs won't be globally unique, but they will be unique within this\n// process, thanks to the counter, and unguessable thanks to the random suffix.\nexport function makeUniqueId(prefix) {\n    var count = prefixCounts.get(prefix) || 1;\n    prefixCounts.set(prefix, count + 1);\n    return \"\".concat(prefix, \":\").concat(count, \":\").concat(Math.random().toString(36).slice(2));\n}\n//# sourceMappingURL=makeUniqueId.js.map","import { makeUniqueId } from \"./makeUniqueId.js\";\nexport function stringifyForDisplay(value, space) {\n    if (space === void 0) { space = 0; }\n    var undefId = makeUniqueId(\"stringifyForDisplay\");\n    return JSON.stringify(value, function (key, value) {\n        return value === void 0 ? undefId : value;\n    }, space)\n        .split(JSON.stringify(undefId))\n        .join(\"<undefined>\");\n}\n//# sourceMappingURL=stringifyForDisplay.js.map","import { invariant as originalInvariant, InvariantError } from \"ts-invariant\";\nimport { version } from \"../../version.js\";\nimport global from \"./global.js\";\nimport { stringifyForDisplay } from \"../common/stringifyForDisplay.js\";\nfunction wrap(fn) {\n    return function (message) {\n        var args = [];\n        for (var _i = 1; _i < arguments.length; _i++) {\n            args[_i - 1] = arguments[_i];\n        }\n        if (typeof message === \"number\") {\n            var arg0 = message;\n            message = getHandledErrorMsg(arg0);\n            if (!message) {\n                message = getFallbackErrorMsg(arg0, args);\n                args = [];\n            }\n        }\n        fn.apply(void 0, [message].concat(args));\n    };\n}\nvar invariant = Object.assign(function invariant(condition, message) {\n    var args = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        args[_i - 2] = arguments[_i];\n    }\n    if (!condition) {\n        originalInvariant(condition, getHandledErrorMsg(message, args) || getFallbackErrorMsg(message, args));\n    }\n}, {\n    debug: wrap(originalInvariant.debug),\n    log: wrap(originalInvariant.log),\n    warn: wrap(originalInvariant.warn),\n    error: wrap(originalInvariant.error),\n});\n/**\n * Returns an InvariantError.\n *\n * `message` can only be a string, a concatenation of strings, or a ternary statement\n * that results in a string. This will be enforced on build, where the message will\n * be replaced with a message number.\n * String substitutions with %s are supported and will also return\n * pretty-stringified objects.\n * Excess `optionalParams` will be swallowed.\n */\nfunction newInvariantError(message) {\n    var optionalParams = [];\n    for (var _i = 1; _i < arguments.length; _i++) {\n        optionalParams[_i - 1] = arguments[_i];\n    }\n    return new InvariantError(getHandledErrorMsg(message, optionalParams) ||\n        getFallbackErrorMsg(message, optionalParams));\n}\nvar ApolloErrorMessageHandler = Symbol.for(\"ApolloErrorMessageHandler_\" + version);\nfunction stringify(arg) {\n    if (typeof arg == \"string\") {\n        return arg;\n    }\n    try {\n        return stringifyForDisplay(arg, 2).slice(0, 1000);\n    }\n    catch (_a) {\n        return \"<non-serializable>\";\n    }\n}\nfunction getHandledErrorMsg(message, messageArgs) {\n    if (messageArgs === void 0) { messageArgs = []; }\n    if (!message)\n        return;\n    return (global[ApolloErrorMessageHandler] &&\n        global[ApolloErrorMessageHandler](message, messageArgs.map(stringify)));\n}\nfunction getFallbackErrorMsg(message, messageArgs) {\n    if (messageArgs === void 0) { messageArgs = []; }\n    if (!message)\n        return;\n    return \"An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#\".concat(encodeURIComponent(JSON.stringify({\n        version: version,\n        message: message,\n        args: messageArgs.map(stringify),\n    })));\n}\nexport { invariant, InvariantError, newInvariantError, ApolloErrorMessageHandler, };\n//# sourceMappingURL=invariantWrappers.js.map","export function devAssert(condition, message) {\n  const booleanCondition = Boolean(condition);\n\n  if (!booleanCondition) {\n    throw new Error(message);\n  }\n}\n","export function invariant(condition, message) {\n  const booleanCondition = Boolean(condition);\n\n  if (!booleanCondition) {\n    throw new Error(\n      message != null ? message : 'Unexpected invariant triggered.',\n    );\n  }\n}\n","import { invariant } from '../jsutils/invariant.mjs';\nconst LineRegExp = /\\r\\n|[\\n\\r]/g;\n/**\n * Represents a location in a Source.\n */\n\n/**\n * Takes a Source and a UTF-8 character offset, and returns the corresponding\n * line and column as a SourceLocation.\n */\nexport function getLocation(source, position) {\n  let lastLineStart = 0;\n  let line = 1;\n\n  for (const match of source.body.matchAll(LineRegExp)) {\n    typeof match.index === 'number' || invariant(false);\n\n    if (match.index >= position) {\n      break;\n    }\n\n    lastLineStart = match.index + match[0].length;\n    line += 1;\n  }\n\n  return {\n    line,\n    column: position + 1 - lastLineStart,\n  };\n}\n","import { getLocation } from './location.mjs';\n\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n */\nexport function printLocation(location) {\n  return printSourceLocation(\n    location.source,\n    getLocation(location.source, location.start),\n  );\n}\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n */\n\nexport function printSourceLocation(source, sourceLocation) {\n  const firstLineColumnOffset = source.locationOffset.column - 1;\n  const body = ''.padStart(firstLineColumnOffset) + source.body;\n  const lineIndex = sourceLocation.line - 1;\n  const lineOffset = source.locationOffset.line - 1;\n  const lineNum = sourceLocation.line + lineOffset;\n  const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;\n  const columnNum = sourceLocation.column + columnOffset;\n  const locationStr = `${source.name}:${lineNum}:${columnNum}\\n`;\n  const lines = body.split(/\\r\\n|[\\n\\r]/g);\n  const locationLine = lines[lineIndex]; // Special case for minified documents\n\n  if (locationLine.length > 120) {\n    const subLineIndex = Math.floor(columnNum / 80);\n    const subLineColumnNum = columnNum % 80;\n    const subLines = [];\n\n    for (let i = 0; i < locationLine.length; i += 80) {\n      subLines.push(locationLine.slice(i, i + 80));\n    }\n\n    return (\n      locationStr +\n      printPrefixedLines([\n        [`${lineNum} |`, subLines[0]],\n        ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]),\n        ['|', '^'.padStart(subLineColumnNum)],\n        ['|', subLines[subLineIndex + 1]],\n      ])\n    );\n  }\n\n  return (\n    locationStr +\n    printPrefixedLines([\n      // Lines specified like this: [\"prefix\", \"string\"],\n      [`${lineNum - 1} |`, lines[lineIndex - 1]],\n      [`${lineNum} |`, locationLine],\n      ['|', '^'.padStart(columnNum)],\n      [`${lineNum + 1} |`, lines[lineIndex + 1]],\n    ])\n  );\n}\n\nfunction printPrefixedLines(lines) {\n  const existingLines = lines.filter(([_, line]) => line !== undefined);\n  const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));\n  return existingLines\n    .map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : ''))\n    .join('\\n');\n}\n","import { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { getLocation } from '../language/location.mjs';\nimport {\n  printLocation,\n  printSourceLocation,\n} from '../language/printLocation.mjs';\n\nfunction toNormalizedOptions(args) {\n  const firstArg = args[0];\n\n  if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) {\n    return {\n      nodes: firstArg,\n      source: args[1],\n      positions: args[2],\n      path: args[3],\n      originalError: args[4],\n      extensions: args[5],\n    };\n  }\n\n  return firstArg;\n}\n/**\n * A GraphQLError describes an Error found during the parse, validate, or\n * execute phases of performing a GraphQL operation. In addition to a message\n * and stack trace, it also includes information about the locations in a\n * GraphQL document and/or execution result that correspond to the Error.\n */\n\nexport class GraphQLError extends Error {\n  /**\n   * An array of `{ line, column }` locations within the source GraphQL document\n   * which correspond to this error.\n   *\n   * Errors during validation often contain multiple locations, for example to\n   * point out two things with the same name. Errors during execution include a\n   * single location, the field which produced the error.\n   *\n   * Enumerable, and appears in the result of JSON.stringify().\n   */\n\n  /**\n   * An array describing the JSON-path into the execution response which\n   * corresponds to this error. Only included for errors during execution.\n   *\n   * Enumerable, and appears in the result of JSON.stringify().\n   */\n\n  /**\n   * An array of GraphQL AST Nodes corresponding to this error.\n   */\n\n  /**\n   * The source GraphQL document for the first location of this error.\n   *\n   * Note that if this Error represents more than one node, the source may not\n   * represent nodes after the first node.\n   */\n\n  /**\n   * An array of character offsets within the source GraphQL document\n   * which correspond to this error.\n   */\n\n  /**\n   * The original error thrown from a field resolver during execution.\n   */\n\n  /**\n   * Extension fields to add to the formatted error.\n   */\n\n  /**\n   * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.\n   */\n  constructor(message, ...rawArgs) {\n    var _this$nodes, _nodeLocations$, _ref;\n\n    const { nodes, source, positions, path, originalError, extensions } =\n      toNormalizedOptions(rawArgs);\n    super(message);\n    this.name = 'GraphQLError';\n    this.path = path !== null && path !== void 0 ? path : undefined;\n    this.originalError =\n      originalError !== null && originalError !== void 0\n        ? originalError\n        : undefined; // Compute list of blame nodes.\n\n    this.nodes = undefinedIfEmpty(\n      Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined,\n    );\n    const nodeLocations = undefinedIfEmpty(\n      (_this$nodes = this.nodes) === null || _this$nodes === void 0\n        ? void 0\n        : _this$nodes.map((node) => node.loc).filter((loc) => loc != null),\n    ); // Compute locations in the source for the given nodes/positions.\n\n    this.source =\n      source !== null && source !== void 0\n        ? source\n        : nodeLocations === null || nodeLocations === void 0\n        ? void 0\n        : (_nodeLocations$ = nodeLocations[0]) === null ||\n          _nodeLocations$ === void 0\n        ? void 0\n        : _nodeLocations$.source;\n    this.positions =\n      positions !== null && positions !== void 0\n        ? positions\n        : nodeLocations === null || nodeLocations === void 0\n        ? void 0\n        : nodeLocations.map((loc) => loc.start);\n    this.locations =\n      positions && source\n        ? positions.map((pos) => getLocation(source, pos))\n        : nodeLocations === null || nodeLocations === void 0\n        ? void 0\n        : nodeLocations.map((loc) => getLocation(loc.source, loc.start));\n    const originalExtensions = isObjectLike(\n      originalError === null || originalError === void 0\n        ? void 0\n        : originalError.extensions,\n    )\n      ? originalError === null || originalError === void 0\n        ? void 0\n        : originalError.extensions\n      : undefined;\n    this.extensions =\n      (_ref =\n        extensions !== null && extensions !== void 0\n          ? extensions\n          : originalExtensions) !== null && _ref !== void 0\n        ? _ref\n        : Object.create(null); // Only properties prescribed by the spec should be enumerable.\n    // Keep the rest as non-enumerable.\n\n    Object.defineProperties(this, {\n      message: {\n        writable: true,\n        enumerable: true,\n      },\n      name: {\n        enumerable: false,\n      },\n      nodes: {\n        enumerable: false,\n      },\n      source: {\n        enumerable: false,\n      },\n      positions: {\n        enumerable: false,\n      },\n      originalError: {\n        enumerable: false,\n      },\n    }); // Include (non-enumerable) stack trace.\n\n    /* c8 ignore start */\n    // FIXME: https://github.com/graphql/graphql-js/issues/2317\n\n    if (\n      originalError !== null &&\n      originalError !== void 0 &&\n      originalError.stack\n    ) {\n      Object.defineProperty(this, 'stack', {\n        value: originalError.stack,\n        writable: true,\n        configurable: true,\n      });\n    } else if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, GraphQLError);\n    } else {\n      Object.defineProperty(this, 'stack', {\n        value: Error().stack,\n        writable: true,\n        configurable: true,\n      });\n    }\n    /* c8 ignore stop */\n  }\n\n  get [Symbol.toStringTag]() {\n    return 'GraphQLError';\n  }\n\n  toString() {\n    let output = this.message;\n\n    if (this.nodes) {\n      for (const node of this.nodes) {\n        if (node.loc) {\n          output += '\\n\\n' + printLocation(node.loc);\n        }\n      }\n    } else if (this.source && this.locations) {\n      for (const location of this.locations) {\n        output += '\\n\\n' + printSourceLocation(this.source, location);\n      }\n    }\n\n    return output;\n  }\n\n  toJSON() {\n    const formattedError = {\n      message: this.message,\n    };\n\n    if (this.locations != null) {\n      formattedError.locations = this.locations;\n    }\n\n    if (this.path != null) {\n      formattedError.path = this.path;\n    }\n\n    if (this.extensions != null && Object.keys(this.extensions).length > 0) {\n      formattedError.extensions = this.extensions;\n    }\n\n    return formattedError;\n  }\n}\n\nfunction undefinedIfEmpty(array) {\n  return array === undefined || array.length === 0 ? undefined : array;\n}\n/**\n * See: https://spec.graphql.org/draft/#sec-Errors\n */\n\n/**\n * Prints a GraphQLError to a string, representing useful location information\n * about the error's position in the source.\n *\n * @deprecated Please use `error.toString` instead. Will be removed in v17\n */\nexport function printError(error) {\n  return error.toString();\n}\n/**\n * Given a GraphQLError, format it according to the rules described by the\n * Response Format, Errors section of the GraphQL Specification.\n *\n * @deprecated Please use `error.toJSON` instead. Will be removed in v17\n */\n\nexport function formatError(error) {\n  return error.toJSON();\n}\n","/**\n * Return true if `value` is object-like. A value is object-like if it's not\n * `null` and has a `typeof` result of \"object\".\n */\nexport function isObjectLike(value) {\n  return typeof value == 'object' && value !== null;\n}\n","import { GraphQLError } from './GraphQLError.mjs';\n/**\n * Produces a GraphQLError representing a syntax error, containing useful\n * descriptive information about the syntax error's position in the source.\n */\n\nexport function syntaxError(source, position, description) {\n  return new GraphQLError(`Syntax Error: ${description}`, {\n    source,\n    positions: [position],\n  });\n}\n","/**\n * Contains a range of UTF-8 character offsets and token references that\n * identify the region of the source from which the AST derived.\n */\nexport class Location {\n  /**\n   * The character offset at which this Node begins.\n   */\n\n  /**\n   * The character offset at which this Node ends.\n   */\n\n  /**\n   * The Token at which this Node begins.\n   */\n\n  /**\n   * The Token at which this Node ends.\n   */\n\n  /**\n   * The Source document the AST represents.\n   */\n  constructor(startToken, endToken, source) {\n    this.start = startToken.start;\n    this.end = endToken.end;\n    this.startToken = startToken;\n    this.endToken = endToken;\n    this.source = source;\n  }\n\n  get [Symbol.toStringTag]() {\n    return 'Location';\n  }\n\n  toJSON() {\n    return {\n      start: this.start,\n      end: this.end,\n    };\n  }\n}\n/**\n * Represents a range of characters represented by a lexical token\n * within a Source.\n */\n\nexport class Token {\n  /**\n   * The kind of Token.\n   */\n\n  /**\n   * The character offset at which this Node begins.\n   */\n\n  /**\n   * The character offset at which this Node ends.\n   */\n\n  /**\n   * The 1-indexed line number on which this Token appears.\n   */\n\n  /**\n   * The 1-indexed column number at which this Token begins.\n   */\n\n  /**\n   * For non-punctuation tokens, represents the interpreted value of the token.\n   *\n   * Note: is undefined for punctuation tokens, but typed as string for\n   * convenience in the parser.\n   */\n\n  /**\n   * Tokens exist as nodes in a double-linked-list amongst all tokens\n   * including ignored tokens. <SOF> is always the first node and <EOF>\n   * the last.\n   */\n  constructor(kind, start, end, line, column, value) {\n    this.kind = kind;\n    this.start = start;\n    this.end = end;\n    this.line = line;\n    this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\n    this.value = value;\n    this.prev = null;\n    this.next = null;\n  }\n\n  get [Symbol.toStringTag]() {\n    return 'Token';\n  }\n\n  toJSON() {\n    return {\n      kind: this.kind,\n      value: this.value,\n      line: this.line,\n      column: this.column,\n    };\n  }\n}\n/**\n * The list of all possible AST node types.\n */\n\n/**\n * @internal\n */\nexport const QueryDocumentKeys = {\n  Name: [],\n  Document: ['definitions'],\n  OperationDefinition: [\n    'name',\n    'variableDefinitions',\n    'directives',\n    'selectionSet',\n  ],\n  VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],\n  Variable: ['name'],\n  SelectionSet: ['selections'],\n  Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],\n  Argument: ['name', 'value'],\n  FragmentSpread: ['name', 'directives'],\n  InlineFragment: ['typeCondition', 'directives', 'selectionSet'],\n  FragmentDefinition: [\n    'name', // Note: fragment variable definitions are deprecated and will removed in v17.0.0\n    'variableDefinitions',\n    'typeCondition',\n    'directives',\n    'selectionSet',\n  ],\n  IntValue: [],\n  FloatValue: [],\n  StringValue: [],\n  BooleanValue: [],\n  NullValue: [],\n  EnumValue: [],\n  ListValue: ['values'],\n  ObjectValue: ['fields'],\n  ObjectField: ['name', 'value'],\n  Directive: ['name', 'arguments'],\n  NamedType: ['name'],\n  ListType: ['type'],\n  NonNullType: ['type'],\n  SchemaDefinition: ['description', 'directives', 'operationTypes'],\n  OperationTypeDefinition: ['type'],\n  ScalarTypeDefinition: ['description', 'name', 'directives'],\n  ObjectTypeDefinition: [\n    'description',\n    'name',\n    'interfaces',\n    'directives',\n    'fields',\n  ],\n  FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],\n  InputValueDefinition: [\n    'description',\n    'name',\n    'type',\n    'defaultValue',\n    'directives',\n  ],\n  InterfaceTypeDefinition: [\n    'description',\n    'name',\n    'interfaces',\n    'directives',\n    'fields',\n  ],\n  UnionTypeDefinition: ['description', 'name', 'directives', 'types'],\n  EnumTypeDefinition: ['description', 'name', 'directives', 'values'],\n  EnumValueDefinition: ['description', 'name', 'directives'],\n  InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],\n  DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],\n  SchemaExtension: ['directives', 'operationTypes'],\n  ScalarTypeExtension: ['name', 'directives'],\n  ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n  InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n  UnionTypeExtension: ['name', 'directives', 'types'],\n  EnumTypeExtension: ['name', 'directives', 'values'],\n  InputObjectTypeExtension: ['name', 'directives', 'fields'],\n};\nconst kindValues = new Set(Object.keys(QueryDocumentKeys));\n/**\n * @internal\n */\n\nexport function isNode(maybeNode) {\n  const maybeKind =\n    maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind;\n  return typeof maybeKind === 'string' && kindValues.has(maybeKind);\n}\n/** Name */\n\nvar OperationTypeNode;\n\n(function (OperationTypeNode) {\n  OperationTypeNode['QUERY'] = 'query';\n  OperationTypeNode['MUTATION'] = 'mutation';\n  OperationTypeNode['SUBSCRIPTION'] = 'subscription';\n})(OperationTypeNode || (OperationTypeNode = {}));\n\nexport { OperationTypeNode };\n","/**\n * The set of allowed directive location values.\n */\nvar DirectiveLocation;\n\n(function (DirectiveLocation) {\n  DirectiveLocation['QUERY'] = 'QUERY';\n  DirectiveLocation['MUTATION'] = 'MUTATION';\n  DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION';\n  DirectiveLocation['FIELD'] = 'FIELD';\n  DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION';\n  DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD';\n  DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT';\n  DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION';\n  DirectiveLocation['SCHEMA'] = 'SCHEMA';\n  DirectiveLocation['SCALAR'] = 'SCALAR';\n  DirectiveLocation['OBJECT'] = 'OBJECT';\n  DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION';\n  DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION';\n  DirectiveLocation['INTERFACE'] = 'INTERFACE';\n  DirectiveLocation['UNION'] = 'UNION';\n  DirectiveLocation['ENUM'] = 'ENUM';\n  DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE';\n  DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT';\n  DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION';\n})(DirectiveLocation || (DirectiveLocation = {}));\n\nexport { DirectiveLocation };\n/**\n * The enum type representing the directive location values.\n *\n * @deprecated Please use `DirectiveLocation`. Will be remove in v17.\n */\n","/**\n * The set of allowed kind values for AST nodes.\n */\nvar Kind;\n\n(function (Kind) {\n  Kind['NAME'] = 'Name';\n  Kind['DOCUMENT'] = 'Document';\n  Kind['OPERATION_DEFINITION'] = 'OperationDefinition';\n  Kind['VARIABLE_DEFINITION'] = 'VariableDefinition';\n  Kind['SELECTION_SET'] = 'SelectionSet';\n  Kind['FIELD'] = 'Field';\n  Kind['ARGUMENT'] = 'Argument';\n  Kind['FRAGMENT_SPREAD'] = 'FragmentSpread';\n  Kind['INLINE_FRAGMENT'] = 'InlineFragment';\n  Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition';\n  Kind['VARIABLE'] = 'Variable';\n  Kind['INT'] = 'IntValue';\n  Kind['FLOAT'] = 'FloatValue';\n  Kind['STRING'] = 'StringValue';\n  Kind['BOOLEAN'] = 'BooleanValue';\n  Kind['NULL'] = 'NullValue';\n  Kind['ENUM'] = 'EnumValue';\n  Kind['LIST'] = 'ListValue';\n  Kind['OBJECT'] = 'ObjectValue';\n  Kind['OBJECT_FIELD'] = 'ObjectField';\n  Kind['DIRECTIVE'] = 'Directive';\n  Kind['NAMED_TYPE'] = 'NamedType';\n  Kind['LIST_TYPE'] = 'ListType';\n  Kind['NON_NULL_TYPE'] = 'NonNullType';\n  Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition';\n  Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition';\n  Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition';\n  Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition';\n  Kind['FIELD_DEFINITION'] = 'FieldDefinition';\n  Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition';\n  Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition';\n  Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition';\n  Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition';\n  Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition';\n  Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition';\n  Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition';\n  Kind['SCHEMA_EXTENSION'] = 'SchemaExtension';\n  Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension';\n  Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension';\n  Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension';\n  Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension';\n  Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension';\n  Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension';\n})(Kind || (Kind = {}));\n\nexport { Kind };\n/**\n * The enum type representing the possible kind values of AST nodes.\n *\n * @deprecated Please use `Kind`. Will be remove in v17.\n */\n","/**\n * An exported enum describing the different kinds of tokens that the\n * lexer emits.\n */\nvar TokenKind;\n\n(function (TokenKind) {\n  TokenKind['SOF'] = '<SOF>';\n  TokenKind['EOF'] = '<EOF>';\n  TokenKind['BANG'] = '!';\n  TokenKind['DOLLAR'] = '$';\n  TokenKind['AMP'] = '&';\n  TokenKind['PAREN_L'] = '(';\n  TokenKind['PAREN_R'] = ')';\n  TokenKind['SPREAD'] = '...';\n  TokenKind['COLON'] = ':';\n  TokenKind['EQUALS'] = '=';\n  TokenKind['AT'] = '@';\n  TokenKind['BRACKET_L'] = '[';\n  TokenKind['BRACKET_R'] = ']';\n  TokenKind['BRACE_L'] = '{';\n  TokenKind['PIPE'] = '|';\n  TokenKind['BRACE_R'] = '}';\n  TokenKind['NAME'] = 'Name';\n  TokenKind['INT'] = 'Int';\n  TokenKind['FLOAT'] = 'Float';\n  TokenKind['STRING'] = 'String';\n  TokenKind['BLOCK_STRING'] = 'BlockString';\n  TokenKind['COMMENT'] = 'Comment';\n})(TokenKind || (TokenKind = {}));\n\nexport { TokenKind };\n/**\n * The enum type representing the token kinds values.\n *\n * @deprecated Please use `TokenKind`. Will be remove in v17.\n */\n","/**\n * ```\n * WhiteSpace ::\n *   - \"Horizontal Tab (U+0009)\"\n *   - \"Space (U+0020)\"\n * ```\n * @internal\n */\nexport function isWhiteSpace(code) {\n  return code === 0x0009 || code === 0x0020;\n}\n/**\n * ```\n * Digit :: one of\n *   - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`\n * ```\n * @internal\n */\n\nexport function isDigit(code) {\n  return code >= 0x0030 && code <= 0x0039;\n}\n/**\n * ```\n * Letter :: one of\n *   - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M`\n *   - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z`\n *   - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m`\n *   - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z`\n * ```\n * @internal\n */\n\nexport function isLetter(code) {\n  return (\n    (code >= 0x0061 && code <= 0x007a) || // A-Z\n    (code >= 0x0041 && code <= 0x005a) // a-z\n  );\n}\n/**\n * ```\n * NameStart ::\n *   - Letter\n *   - `_`\n * ```\n * @internal\n */\n\nexport function isNameStart(code) {\n  return isLetter(code) || code === 0x005f;\n}\n/**\n * ```\n * NameContinue ::\n *   - Letter\n *   - Digit\n *   - `_`\n * ```\n * @internal\n */\n\nexport function isNameContinue(code) {\n  return isLetter(code) || isDigit(code) || code === 0x005f;\n}\n","import { isWhiteSpace } from './characterClasses.mjs';\n/**\n * Produces the value of a block string from its parsed raw value, similar to\n * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.\n *\n * This implements the GraphQL spec's BlockStringValue() static algorithm.\n *\n * @internal\n */\n\nexport function dedentBlockStringLines(lines) {\n  var _firstNonEmptyLine2;\n\n  let commonIndent = Number.MAX_SAFE_INTEGER;\n  let firstNonEmptyLine = null;\n  let lastNonEmptyLine = -1;\n\n  for (let i = 0; i < lines.length; ++i) {\n    var _firstNonEmptyLine;\n\n    const line = lines[i];\n    const indent = leadingWhitespace(line);\n\n    if (indent === line.length) {\n      continue; // skip empty lines\n    }\n\n    firstNonEmptyLine =\n      (_firstNonEmptyLine = firstNonEmptyLine) !== null &&\n      _firstNonEmptyLine !== void 0\n        ? _firstNonEmptyLine\n        : i;\n    lastNonEmptyLine = i;\n\n    if (i !== 0 && indent < commonIndent) {\n      commonIndent = indent;\n    }\n  }\n\n  return lines // Remove common indentation from all lines but first.\n    .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines.\n    .slice(\n      (_firstNonEmptyLine2 = firstNonEmptyLine) !== null &&\n        _firstNonEmptyLine2 !== void 0\n        ? _firstNonEmptyLine2\n        : 0,\n      lastNonEmptyLine + 1,\n    );\n}\n\nfunction leadingWhitespace(str) {\n  let i = 0;\n\n  while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {\n    ++i;\n  }\n\n  return i;\n}\n/**\n * @internal\n */\n\nexport function isPrintableAsBlockString(value) {\n  if (value === '') {\n    return true; // empty string is printable\n  }\n\n  let isEmptyLine = true;\n  let hasIndent = false;\n  let hasCommonIndent = true;\n  let seenNonEmptyLine = false;\n\n  for (let i = 0; i < value.length; ++i) {\n    switch (value.codePointAt(i)) {\n      case 0x0000:\n      case 0x0001:\n      case 0x0002:\n      case 0x0003:\n      case 0x0004:\n      case 0x0005:\n      case 0x0006:\n      case 0x0007:\n      case 0x0008:\n      case 0x000b:\n      case 0x000c:\n      case 0x000e:\n      case 0x000f:\n        return false;\n      // Has non-printable characters\n\n      case 0x000d:\n        //  \\r\n        return false;\n      // Has \\r or \\r\\n which will be replaced as \\n\n\n      case 10:\n        //  \\n\n        if (isEmptyLine && !seenNonEmptyLine) {\n          return false; // Has leading new line\n        }\n\n        seenNonEmptyLine = true;\n        isEmptyLine = true;\n        hasIndent = false;\n        break;\n\n      case 9: //   \\t\n\n      case 32:\n        //  <space>\n        hasIndent || (hasIndent = isEmptyLine);\n        break;\n\n      default:\n        hasCommonIndent && (hasCommonIndent = hasIndent);\n        isEmptyLine = false;\n    }\n  }\n\n  if (isEmptyLine) {\n    return false; // Has trailing empty lines\n  }\n\n  if (hasCommonIndent && seenNonEmptyLine) {\n    return false; // Has internal indent\n  }\n\n  return true;\n}\n/**\n * Print a block string in the indented block form by adding a leading and\n * trailing blank line. However, if a block string starts with whitespace and is\n * a single-line, adding a leading blank line would strip that whitespace.\n *\n * @internal\n */\n\nexport function printBlockString(value, options) {\n  const escapedValue = value.replace(/\"\"\"/g, '\\\\\"\"\"'); // Expand a block string's raw value into independent lines.\n\n  const lines = escapedValue.split(/\\r\\n|[\\n\\r]/g);\n  const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line\n\n  const forceLeadingNewLine =\n    lines.length > 1 &&\n    lines\n      .slice(1)\n      .every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line\n\n  const hasTrailingTripleQuotes = escapedValue.endsWith('\\\\\"\"\"'); // Trailing quote (single or double) or slash forces trailing new line\n\n  const hasTrailingQuote = value.endsWith('\"') && !hasTrailingTripleQuotes;\n  const hasTrailingSlash = value.endsWith('\\\\');\n  const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;\n  const printAsMultipleLines =\n    !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability\n    (!isSingleLine ||\n      value.length > 70 ||\n      forceTrailingNewline ||\n      forceLeadingNewLine ||\n      hasTrailingTripleQuotes);\n  let result = ''; // Format a multi-line block quote to account for leading space.\n\n  const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));\n\n  if ((printAsMultipleLines && !skipLeadingNewLine) || forceLeadingNewLine) {\n    result += '\\n';\n  }\n\n  result += escapedValue;\n\n  if (printAsMultipleLines || forceTrailingNewline) {\n    result += '\\n';\n  }\n\n  return '\"\"\"' + result + '\"\"\"';\n}\n","import { syntaxError } from '../error/syntaxError.mjs';\nimport { Token } from './ast.mjs';\nimport { dedentBlockStringLines } from './blockString.mjs';\nimport { isDigit, isNameContinue, isNameStart } from './characterClasses.mjs';\nimport { TokenKind } from './tokenKind.mjs';\n/**\n * Given a Source object, creates a Lexer for that source.\n * A Lexer is a stateful stream generator in that every time\n * it is advanced, it returns the next token in the Source. Assuming the\n * source lexes, the final Token emitted by the lexer will be of kind\n * EOF, after which the lexer will repeatedly return the same EOF token\n * whenever called.\n */\n\nexport class Lexer {\n  /**\n   * The previously focused non-ignored token.\n   */\n\n  /**\n   * The currently focused non-ignored token.\n   */\n\n  /**\n   * The (1-indexed) line containing the current token.\n   */\n\n  /**\n   * The character offset at which the current line begins.\n   */\n  constructor(source) {\n    const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);\n    this.source = source;\n    this.lastToken = startOfFileToken;\n    this.token = startOfFileToken;\n    this.line = 1;\n    this.lineStart = 0;\n  }\n\n  get [Symbol.toStringTag]() {\n    return 'Lexer';\n  }\n  /**\n   * Advances the token stream to the next non-ignored token.\n   */\n\n  advance() {\n    this.lastToken = this.token;\n    const token = (this.token = this.lookahead());\n    return token;\n  }\n  /**\n   * Looks ahead and returns the next non-ignored token, but does not change\n   * the state of Lexer.\n   */\n\n  lookahead() {\n    let token = this.token;\n\n    if (token.kind !== TokenKind.EOF) {\n      do {\n        if (token.next) {\n          token = token.next;\n        } else {\n          // Read the next token and form a link in the token linked-list.\n          const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing.\n\n          token.next = nextToken; // @ts-expect-error prev is only mutable during parsing.\n\n          nextToken.prev = token;\n          token = nextToken;\n        }\n      } while (token.kind === TokenKind.COMMENT);\n    }\n\n    return token;\n  }\n}\n/**\n * @internal\n */\n\nexport function isPunctuatorTokenKind(kind) {\n  return (\n    kind === TokenKind.BANG ||\n    kind === TokenKind.DOLLAR ||\n    kind === TokenKind.AMP ||\n    kind === TokenKind.PAREN_L ||\n    kind === TokenKind.PAREN_R ||\n    kind === TokenKind.SPREAD ||\n    kind === TokenKind.COLON ||\n    kind === TokenKind.EQUALS ||\n    kind === TokenKind.AT ||\n    kind === TokenKind.BRACKET_L ||\n    kind === TokenKind.BRACKET_R ||\n    kind === TokenKind.BRACE_L ||\n    kind === TokenKind.PIPE ||\n    kind === TokenKind.BRACE_R\n  );\n}\n/**\n * A Unicode scalar value is any Unicode code point except surrogate code\n * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and\n * 0xE000 to 0x10FFFF.\n *\n * SourceCharacter ::\n *   - \"Any Unicode scalar value\"\n */\n\nfunction isUnicodeScalarValue(code) {\n  return (\n    (code >= 0x0000 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0x10ffff)\n  );\n}\n/**\n * The GraphQL specification defines source text as a sequence of unicode scalar\n * values (which Unicode defines to exclude surrogate code points). However\n * JavaScript defines strings as a sequence of UTF-16 code units which may\n * include surrogates. A surrogate pair is a valid source character as it\n * encodes a supplementary code point (above U+FFFF), but unpaired surrogate\n * code points are not valid source characters.\n */\n\nfunction isSupplementaryCodePoint(body, location) {\n  return (\n    isLeadingSurrogate(body.charCodeAt(location)) &&\n    isTrailingSurrogate(body.charCodeAt(location + 1))\n  );\n}\n\nfunction isLeadingSurrogate(code) {\n  return code >= 0xd800 && code <= 0xdbff;\n}\n\nfunction isTrailingSurrogate(code) {\n  return code >= 0xdc00 && code <= 0xdfff;\n}\n/**\n * Prints the code point (or end of file reference) at a given location in a\n * source for use in error messages.\n *\n * Printable ASCII is printed quoted, while other points are printed in Unicode\n * code point form (ie. U+1234).\n */\n\nfunction printCodePointAt(lexer, location) {\n  const code = lexer.source.body.codePointAt(location);\n\n  if (code === undefined) {\n    return TokenKind.EOF;\n  } else if (code >= 0x0020 && code <= 0x007e) {\n    // Printable ASCII\n    const char = String.fromCodePoint(code);\n    return char === '\"' ? \"'\\\"'\" : `\"${char}\"`;\n  } // Unicode code point\n\n  return 'U+' + code.toString(16).toUpperCase().padStart(4, '0');\n}\n/**\n * Create a token with line and column location information.\n */\n\nfunction createToken(lexer, kind, start, end, value) {\n  const line = lexer.line;\n  const col = 1 + start - lexer.lineStart;\n  return new Token(kind, start, end, line, col, value);\n}\n/**\n * Gets the next token from the source starting at the given position.\n *\n * This skips over whitespace until it finds the next lexable token, then lexes\n * punctuators immediately or calls the appropriate helper function for more\n * complicated tokens.\n */\n\nfunction readNextToken(lexer, start) {\n  const body = lexer.source.body;\n  const bodyLength = body.length;\n  let position = start;\n\n  while (position < bodyLength) {\n    const code = body.charCodeAt(position); // SourceCharacter\n\n    switch (code) {\n      // Ignored ::\n      //   - UnicodeBOM\n      //   - WhiteSpace\n      //   - LineTerminator\n      //   - Comment\n      //   - Comma\n      //\n      // UnicodeBOM :: \"Byte Order Mark (U+FEFF)\"\n      //\n      // WhiteSpace ::\n      //   - \"Horizontal Tab (U+0009)\"\n      //   - \"Space (U+0020)\"\n      //\n      // Comma :: ,\n      case 0xfeff: // <BOM>\n\n      case 0x0009: // \\t\n\n      case 0x0020: // <space>\n\n      case 0x002c:\n        // ,\n        ++position;\n        continue;\n      // LineTerminator ::\n      //   - \"New Line (U+000A)\"\n      //   - \"Carriage Return (U+000D)\" [lookahead != \"New Line (U+000A)\"]\n      //   - \"Carriage Return (U+000D)\" \"New Line (U+000A)\"\n\n      case 0x000a:\n        // \\n\n        ++position;\n        ++lexer.line;\n        lexer.lineStart = position;\n        continue;\n\n      case 0x000d:\n        // \\r\n        if (body.charCodeAt(position + 1) === 0x000a) {\n          position += 2;\n        } else {\n          ++position;\n        }\n\n        ++lexer.line;\n        lexer.lineStart = position;\n        continue;\n      // Comment\n\n      case 0x0023:\n        // #\n        return readComment(lexer, position);\n      // Token ::\n      //   - Punctuator\n      //   - Name\n      //   - IntValue\n      //   - FloatValue\n      //   - StringValue\n      //\n      // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | }\n\n      case 0x0021:\n        // !\n        return createToken(lexer, TokenKind.BANG, position, position + 1);\n\n      case 0x0024:\n        // $\n        return createToken(lexer, TokenKind.DOLLAR, position, position + 1);\n\n      case 0x0026:\n        // &\n        return createToken(lexer, TokenKind.AMP, position, position + 1);\n\n      case 0x0028:\n        // (\n        return createToken(lexer, TokenKind.PAREN_L, position, position + 1);\n\n      case 0x0029:\n        // )\n        return createToken(lexer, TokenKind.PAREN_R, position, position + 1);\n\n      case 0x002e:\n        // .\n        if (\n          body.charCodeAt(position + 1) === 0x002e &&\n          body.charCodeAt(position + 2) === 0x002e\n        ) {\n          return createToken(lexer, TokenKind.SPREAD, position, position + 3);\n        }\n\n        break;\n\n      case 0x003a:\n        // :\n        return createToken(lexer, TokenKind.COLON, position, position + 1);\n\n      case 0x003d:\n        // =\n        return createToken(lexer, TokenKind.EQUALS, position, position + 1);\n\n      case 0x0040:\n        // @\n        return createToken(lexer, TokenKind.AT, position, position + 1);\n\n      case 0x005b:\n        // [\n        return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);\n\n      case 0x005d:\n        // ]\n        return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);\n\n      case 0x007b:\n        // {\n        return createToken(lexer, TokenKind.BRACE_L, position, position + 1);\n\n      case 0x007c:\n        // |\n        return createToken(lexer, TokenKind.PIPE, position, position + 1);\n\n      case 0x007d:\n        // }\n        return createToken(lexer, TokenKind.BRACE_R, position, position + 1);\n      // StringValue\n\n      case 0x0022:\n        // \"\n        if (\n          body.charCodeAt(position + 1) === 0x0022 &&\n          body.charCodeAt(position + 2) === 0x0022\n        ) {\n          return readBlockString(lexer, position);\n        }\n\n        return readString(lexer, position);\n    } // IntValue | FloatValue (Digit | -)\n\n    if (isDigit(code) || code === 0x002d) {\n      return readNumber(lexer, position, code);\n    } // Name\n\n    if (isNameStart(code)) {\n      return readName(lexer, position);\n    }\n\n    throw syntaxError(\n      lexer.source,\n      position,\n      code === 0x0027\n        ? 'Unexpected single quote character (\\'), did you mean to use a double quote (\")?'\n        : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position)\n        ? `Unexpected character: ${printCodePointAt(lexer, position)}.`\n        : `Invalid character: ${printCodePointAt(lexer, position)}.`,\n    );\n  }\n\n  return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);\n}\n/**\n * Reads a comment token from the source file.\n *\n * ```\n * Comment :: # CommentChar* [lookahead != CommentChar]\n *\n * CommentChar :: SourceCharacter but not LineTerminator\n * ```\n */\n\nfunction readComment(lexer, start) {\n  const body = lexer.source.body;\n  const bodyLength = body.length;\n  let position = start + 1;\n\n  while (position < bodyLength) {\n    const code = body.charCodeAt(position); // LineTerminator (\\n | \\r)\n\n    if (code === 0x000a || code === 0x000d) {\n      break;\n    } // SourceCharacter\n\n    if (isUnicodeScalarValue(code)) {\n      ++position;\n    } else if (isSupplementaryCodePoint(body, position)) {\n      position += 2;\n    } else {\n      break;\n    }\n  }\n\n  return createToken(\n    lexer,\n    TokenKind.COMMENT,\n    start,\n    position,\n    body.slice(start + 1, position),\n  );\n}\n/**\n * Reads a number token from the source file, either a FloatValue or an IntValue\n * depending on whether a FractionalPart or ExponentPart is encountered.\n *\n * ```\n * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}]\n *\n * IntegerPart ::\n *   - NegativeSign? 0\n *   - NegativeSign? NonZeroDigit Digit*\n *\n * NegativeSign :: -\n *\n * NonZeroDigit :: Digit but not `0`\n *\n * FloatValue ::\n *   - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}]\n *   - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}]\n *   - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}]\n *\n * FractionalPart :: . Digit+\n *\n * ExponentPart :: ExponentIndicator Sign? Digit+\n *\n * ExponentIndicator :: one of `e` `E`\n *\n * Sign :: one of + -\n * ```\n */\n\nfunction readNumber(lexer, start, firstCode) {\n  const body = lexer.source.body;\n  let position = start;\n  let code = firstCode;\n  let isFloat = false; // NegativeSign (-)\n\n  if (code === 0x002d) {\n    code = body.charCodeAt(++position);\n  } // Zero (0)\n\n  if (code === 0x0030) {\n    code = body.charCodeAt(++position);\n\n    if (isDigit(code)) {\n      throw syntaxError(\n        lexer.source,\n        position,\n        `Invalid number, unexpected digit after 0: ${printCodePointAt(\n          lexer,\n          position,\n        )}.`,\n      );\n    }\n  } else {\n    position = readDigits(lexer, position, code);\n    code = body.charCodeAt(position);\n  } // Full stop (.)\n\n  if (code === 0x002e) {\n    isFloat = true;\n    code = body.charCodeAt(++position);\n    position = readDigits(lexer, position, code);\n    code = body.charCodeAt(position);\n  } // E e\n\n  if (code === 0x0045 || code === 0x0065) {\n    isFloat = true;\n    code = body.charCodeAt(++position); // + -\n\n    if (code === 0x002b || code === 0x002d) {\n      code = body.charCodeAt(++position);\n    }\n\n    position = readDigits(lexer, position, code);\n    code = body.charCodeAt(position);\n  } // Numbers cannot be followed by . or NameStart\n\n  if (code === 0x002e || isNameStart(code)) {\n    throw syntaxError(\n      lexer.source,\n      position,\n      `Invalid number, expected digit but got: ${printCodePointAt(\n        lexer,\n        position,\n      )}.`,\n    );\n  }\n\n  return createToken(\n    lexer,\n    isFloat ? TokenKind.FLOAT : TokenKind.INT,\n    start,\n    position,\n    body.slice(start, position),\n  );\n}\n/**\n * Returns the new position in the source after reading one or more digits.\n */\n\nfunction readDigits(lexer, start, firstCode) {\n  if (!isDigit(firstCode)) {\n    throw syntaxError(\n      lexer.source,\n      start,\n      `Invalid number, expected digit but got: ${printCodePointAt(\n        lexer,\n        start,\n      )}.`,\n    );\n  }\n\n  const body = lexer.source.body;\n  let position = start + 1; // +1 to skip first firstCode\n\n  while (isDigit(body.charCodeAt(position))) {\n    ++position;\n  }\n\n  return position;\n}\n/**\n * Reads a single-quote string token from the source file.\n *\n * ```\n * StringValue ::\n *   - `\"\"` [lookahead != `\"`]\n *   - `\"` StringCharacter+ `\"`\n *\n * StringCharacter ::\n *   - SourceCharacter but not `\"` or `\\` or LineTerminator\n *   - `\\u` EscapedUnicode\n *   - `\\` EscapedCharacter\n *\n * EscapedUnicode ::\n *   - `{` HexDigit+ `}`\n *   - HexDigit HexDigit HexDigit HexDigit\n *\n * EscapedCharacter :: one of `\"` `\\` `/` `b` `f` `n` `r` `t`\n * ```\n */\n\nfunction readString(lexer, start) {\n  const body = lexer.source.body;\n  const bodyLength = body.length;\n  let position = start + 1;\n  let chunkStart = position;\n  let value = '';\n\n  while (position < bodyLength) {\n    const code = body.charCodeAt(position); // Closing Quote (\")\n\n    if (code === 0x0022) {\n      value += body.slice(chunkStart, position);\n      return createToken(lexer, TokenKind.STRING, start, position + 1, value);\n    } // Escape Sequence (\\)\n\n    if (code === 0x005c) {\n      value += body.slice(chunkStart, position);\n      const escape =\n        body.charCodeAt(position + 1) === 0x0075 // u\n          ? body.charCodeAt(position + 2) === 0x007b // {\n            ? readEscapedUnicodeVariableWidth(lexer, position)\n            : readEscapedUnicodeFixedWidth(lexer, position)\n          : readEscapedCharacter(lexer, position);\n      value += escape.value;\n      position += escape.size;\n      chunkStart = position;\n      continue;\n    } // LineTerminator (\\n | \\r)\n\n    if (code === 0x000a || code === 0x000d) {\n      break;\n    } // SourceCharacter\n\n    if (isUnicodeScalarValue(code)) {\n      ++position;\n    } else if (isSupplementaryCodePoint(body, position)) {\n      position += 2;\n    } else {\n      throw syntaxError(\n        lexer.source,\n        position,\n        `Invalid character within String: ${printCodePointAt(\n          lexer,\n          position,\n        )}.`,\n      );\n    }\n  }\n\n  throw syntaxError(lexer.source, position, 'Unterminated string.');\n} // The string value and lexed size of an escape sequence.\n\nfunction readEscapedUnicodeVariableWidth(lexer, position) {\n  const body = lexer.source.body;\n  let point = 0;\n  let size = 3; // Cannot be larger than 12 chars (\\u{00000000}).\n\n  while (size < 12) {\n    const code = body.charCodeAt(position + size++); // Closing Brace (})\n\n    if (code === 0x007d) {\n      // Must be at least 5 chars (\\u{0}) and encode a Unicode scalar value.\n      if (size < 5 || !isUnicodeScalarValue(point)) {\n        break;\n      }\n\n      return {\n        value: String.fromCodePoint(point),\n        size,\n      };\n    } // Append this hex digit to the code point.\n\n    point = (point << 4) | readHexDigit(code);\n\n    if (point < 0) {\n      break;\n    }\n  }\n\n  throw syntaxError(\n    lexer.source,\n    position,\n    `Invalid Unicode escape sequence: \"${body.slice(\n      position,\n      position + size,\n    )}\".`,\n  );\n}\n\nfunction readEscapedUnicodeFixedWidth(lexer, position) {\n  const body = lexer.source.body;\n  const code = read16BitHexCode(body, position + 2);\n\n  if (isUnicodeScalarValue(code)) {\n    return {\n      value: String.fromCodePoint(code),\n      size: 6,\n    };\n  } // GraphQL allows JSON-style surrogate pair escape sequences, but only when\n  // a valid pair is formed.\n\n  if (isLeadingSurrogate(code)) {\n    // \\u\n    if (\n      body.charCodeAt(position + 6) === 0x005c &&\n      body.charCodeAt(position + 7) === 0x0075\n    ) {\n      const trailingCode = read16BitHexCode(body, position + 8);\n\n      if (isTrailingSurrogate(trailingCode)) {\n        // JavaScript defines strings as a sequence of UTF-16 code units and\n        // encodes Unicode code points above U+FFFF using a surrogate pair of\n        // code units. Since this is a surrogate pair escape sequence, just\n        // include both codes into the JavaScript string value. Had JavaScript\n        // not been internally based on UTF-16, then this surrogate pair would\n        // be decoded to retrieve the supplementary code point.\n        return {\n          value: String.fromCodePoint(code, trailingCode),\n          size: 12,\n        };\n      }\n    }\n  }\n\n  throw syntaxError(\n    lexer.source,\n    position,\n    `Invalid Unicode escape sequence: \"${body.slice(position, position + 6)}\".`,\n  );\n}\n/**\n * Reads four hexadecimal characters and returns the positive integer that 16bit\n * hexadecimal string represents. For example, \"000f\" will return 15, and \"dead\"\n * will return 57005.\n *\n * Returns a negative number if any char was not a valid hexadecimal digit.\n */\n\nfunction read16BitHexCode(body, position) {\n  // readHexDigit() returns -1 on error. ORing a negative value with any other\n  // value always produces a negative value.\n  return (\n    (readHexDigit(body.charCodeAt(position)) << 12) |\n    (readHexDigit(body.charCodeAt(position + 1)) << 8) |\n    (readHexDigit(body.charCodeAt(position + 2)) << 4) |\n    readHexDigit(body.charCodeAt(position + 3))\n  );\n}\n/**\n * Reads a hexadecimal character and returns its positive integer value (0-15).\n *\n * '0' becomes 0, '9' becomes 9\n * 'A' becomes 10, 'F' becomes 15\n * 'a' becomes 10, 'f' becomes 15\n *\n * Returns -1 if the provided character code was not a valid hexadecimal digit.\n *\n * HexDigit :: one of\n *   - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`\n *   - `A` `B` `C` `D` `E` `F`\n *   - `a` `b` `c` `d` `e` `f`\n */\n\nfunction readHexDigit(code) {\n  return code >= 0x0030 && code <= 0x0039 // 0-9\n    ? code - 0x0030\n    : code >= 0x0041 && code <= 0x0046 // A-F\n    ? code - 0x0037\n    : code >= 0x0061 && code <= 0x0066 // a-f\n    ? code - 0x0057\n    : -1;\n}\n/**\n * | Escaped Character | Code Point | Character Name               |\n * | ----------------- | ---------- | ---------------------------- |\n * | `\"`               | U+0022     | double quote                 |\n * | `\\`               | U+005C     | reverse solidus (back slash) |\n * | `/`               | U+002F     | solidus (forward slash)      |\n * | `b`               | U+0008     | backspace                    |\n * | `f`               | U+000C     | form feed                    |\n * | `n`               | U+000A     | line feed (new line)         |\n * | `r`               | U+000D     | carriage return              |\n * | `t`               | U+0009     | horizontal tab               |\n */\n\nfunction readEscapedCharacter(lexer, position) {\n  const body = lexer.source.body;\n  const code = body.charCodeAt(position + 1);\n\n  switch (code) {\n    case 0x0022:\n      // \"\n      return {\n        value: '\\u0022',\n        size: 2,\n      };\n\n    case 0x005c:\n      // \\\n      return {\n        value: '\\u005c',\n        size: 2,\n      };\n\n    case 0x002f:\n      // /\n      return {\n        value: '\\u002f',\n        size: 2,\n      };\n\n    case 0x0062:\n      // b\n      return {\n        value: '\\u0008',\n        size: 2,\n      };\n\n    case 0x0066:\n      // f\n      return {\n        value: '\\u000c',\n        size: 2,\n      };\n\n    case 0x006e:\n      // n\n      return {\n        value: '\\u000a',\n        size: 2,\n      };\n\n    case 0x0072:\n      // r\n      return {\n        value: '\\u000d',\n        size: 2,\n      };\n\n    case 0x0074:\n      // t\n      return {\n        value: '\\u0009',\n        size: 2,\n      };\n  }\n\n  throw syntaxError(\n    lexer.source,\n    position,\n    `Invalid character escape sequence: \"${body.slice(\n      position,\n      position + 2,\n    )}\".`,\n  );\n}\n/**\n * Reads a block string token from the source file.\n *\n * ```\n * StringValue ::\n *   - `\"\"\"` BlockStringCharacter* `\"\"\"`\n *\n * BlockStringCharacter ::\n *   - SourceCharacter but not `\"\"\"` or `\\\"\"\"`\n *   - `\\\"\"\"`\n * ```\n */\n\nfunction readBlockString(lexer, start) {\n  const body = lexer.source.body;\n  const bodyLength = body.length;\n  let lineStart = lexer.lineStart;\n  let position = start + 3;\n  let chunkStart = position;\n  let currentLine = '';\n  const blockLines = [];\n\n  while (position < bodyLength) {\n    const code = body.charCodeAt(position); // Closing Triple-Quote (\"\"\")\n\n    if (\n      code === 0x0022 &&\n      body.charCodeAt(position + 1) === 0x0022 &&\n      body.charCodeAt(position + 2) === 0x0022\n    ) {\n      currentLine += body.slice(chunkStart, position);\n      blockLines.push(currentLine);\n      const token = createToken(\n        lexer,\n        TokenKind.BLOCK_STRING,\n        start,\n        position + 3, // Return a string of the lines joined with U+000A.\n        dedentBlockStringLines(blockLines).join('\\n'),\n      );\n      lexer.line += blockLines.length - 1;\n      lexer.lineStart = lineStart;\n      return token;\n    } // Escaped Triple-Quote (\\\"\"\")\n\n    if (\n      code === 0x005c &&\n      body.charCodeAt(position + 1) === 0x0022 &&\n      body.charCodeAt(position + 2) === 0x0022 &&\n      body.charCodeAt(position + 3) === 0x0022\n    ) {\n      currentLine += body.slice(chunkStart, position);\n      chunkStart = position + 1; // skip only slash\n\n      position += 4;\n      continue;\n    } // LineTerminator\n\n    if (code === 0x000a || code === 0x000d) {\n      currentLine += body.slice(chunkStart, position);\n      blockLines.push(currentLine);\n\n      if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) {\n        position += 2;\n      } else {\n        ++position;\n      }\n\n      currentLine = '';\n      chunkStart = position;\n      lineStart = position;\n      continue;\n    } // SourceCharacter\n\n    if (isUnicodeScalarValue(code)) {\n      ++position;\n    } else if (isSupplementaryCodePoint(body, position)) {\n      position += 2;\n    } else {\n      throw syntaxError(\n        lexer.source,\n        position,\n        `Invalid character within String: ${printCodePointAt(\n          lexer,\n          position,\n        )}.`,\n      );\n    }\n  }\n\n  throw syntaxError(lexer.source, position, 'Unterminated string.');\n}\n/**\n * Reads an alphanumeric + underscore name from the source.\n *\n * ```\n * Name ::\n *   - NameStart NameContinue* [lookahead != NameContinue]\n * ```\n */\n\nfunction readName(lexer, start) {\n  const body = lexer.source.body;\n  const bodyLength = body.length;\n  let position = start + 1;\n\n  while (position < bodyLength) {\n    const code = body.charCodeAt(position);\n\n    if (isNameContinue(code)) {\n      ++position;\n    } else {\n      break;\n    }\n  }\n\n  return createToken(\n    lexer,\n    TokenKind.NAME,\n    start,\n    position,\n    body.slice(start, position),\n  );\n}\n","const MAX_ARRAY_LENGTH = 10;\nconst MAX_RECURSIVE_DEPTH = 2;\n/**\n * Used to print values in error messages.\n */\n\nexport function inspect(value) {\n  return formatValue(value, []);\n}\n\nfunction formatValue(value, seenValues) {\n  switch (typeof value) {\n    case 'string':\n      return JSON.stringify(value);\n\n    case 'function':\n      return value.name ? `[function ${value.name}]` : '[function]';\n\n    case 'object':\n      return formatObjectValue(value, seenValues);\n\n    default:\n      return String(value);\n  }\n}\n\nfunction formatObjectValue(value, previouslySeenValues) {\n  if (value === null) {\n    return 'null';\n  }\n\n  if (previouslySeenValues.includes(value)) {\n    return '[Circular]';\n  }\n\n  const seenValues = [...previouslySeenValues, value];\n\n  if (isJSONable(value)) {\n    const jsonValue = value.toJSON(); // check for infinite recursion\n\n    if (jsonValue !== value) {\n      return typeof jsonValue === 'string'\n        ? jsonValue\n        : formatValue(jsonValue, seenValues);\n    }\n  } else if (Array.isArray(value)) {\n    return formatArray(value, seenValues);\n  }\n\n  return formatObject(value, seenValues);\n}\n\nfunction isJSONable(value) {\n  return typeof value.toJSON === 'function';\n}\n\nfunction formatObject(object, seenValues) {\n  const entries = Object.entries(object);\n\n  if (entries.length === 0) {\n    return '{}';\n  }\n\n  if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n    return '[' + getObjectTag(object) + ']';\n  }\n\n  const properties = entries.map(\n    ([key, value]) => key + ': ' + formatValue(value, seenValues),\n  );\n  return '{ ' + properties.join(', ') + ' }';\n}\n\nfunction formatArray(array, seenValues) {\n  if (array.length === 0) {\n    return '[]';\n  }\n\n  if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n    return '[Array]';\n  }\n\n  const len = Math.min(MAX_ARRAY_LENGTH, array.length);\n  const remaining = array.length - len;\n  const items = [];\n\n  for (let i = 0; i < len; ++i) {\n    items.push(formatValue(array[i], seenValues));\n  }\n\n  if (remaining === 1) {\n    items.push('... 1 more item');\n  } else if (remaining > 1) {\n    items.push(`... ${remaining} more items`);\n  }\n\n  return '[' + items.join(', ') + ']';\n}\n\nfunction getObjectTag(object) {\n  const tag = Object.prototype.toString\n    .call(object)\n    .replace(/^\\[object /, '')\n    .replace(/]$/, '');\n\n  if (tag === 'Object' && typeof object.constructor === 'function') {\n    const name = object.constructor.name;\n\n    if (typeof name === 'string' && name !== '') {\n      return name;\n    }\n  }\n\n  return tag;\n}\n","import { inspect } from './inspect.mjs';\n/* c8 ignore next 3 */\n\nconst isProduction =\n  globalThis.process && // eslint-disable-next-line no-undef\n  process.env.NODE_ENV === 'production';\n/**\n * A replacement for instanceof which includes an error warning when multi-realm\n * constructors are detected.\n * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production\n * See: https://webpack.js.org/guides/production/\n */\n\nexport const instanceOf =\n  /* c8 ignore next 6 */\n  // FIXME: https://github.com/graphql/graphql-js/issues/2317\n  isProduction\n    ? function instanceOf(value, constructor) {\n        return value instanceof constructor;\n      }\n    : function instanceOf(value, constructor) {\n        if (value instanceof constructor) {\n          return true;\n        }\n\n        if (typeof value === 'object' && value !== null) {\n          var _value$constructor;\n\n          // Prefer Symbol.toStringTag since it is immune to minification.\n          const className = constructor.prototype[Symbol.toStringTag];\n          const valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library.\n            Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009\n              ? value[Symbol.toStringTag]\n              : (_value$constructor = value.constructor) === null ||\n                _value$constructor === void 0\n              ? void 0\n              : _value$constructor.name;\n\n          if (className === valueClassName) {\n            const stringifiedValue = inspect(value);\n            throw new Error(`Cannot use ${className} \"${stringifiedValue}\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.`);\n          }\n        }\n\n        return false;\n      };\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { instanceOf } from '../jsutils/instanceOf.mjs';\n\n/**\n * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are\n * optional, but they are useful for clients who store GraphQL documents in source files.\n * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might\n * be useful for `name` to be `\"Foo.graphql\"` and location to be `{ line: 40, column: 1 }`.\n * The `line` and `column` properties in `locationOffset` are 1-indexed.\n */\nexport class Source {\n  constructor(\n    body,\n    name = 'GraphQL request',\n    locationOffset = {\n      line: 1,\n      column: 1,\n    },\n  ) {\n    typeof body === 'string' ||\n      devAssert(false, `Body must be a string. Received: ${inspect(body)}.`);\n    this.body = body;\n    this.name = name;\n    this.locationOffset = locationOffset;\n    this.locationOffset.line > 0 ||\n      devAssert(\n        false,\n        'line in locationOffset is 1-indexed and must be positive.',\n      );\n    this.locationOffset.column > 0 ||\n      devAssert(\n        false,\n        'column in locationOffset is 1-indexed and must be positive.',\n      );\n  }\n\n  get [Symbol.toStringTag]() {\n    return 'Source';\n  }\n}\n/**\n * Test if the given value is a Source object.\n *\n * @internal\n */\n\nexport function isSource(source) {\n  return instanceOf(source, Source);\n}\n","import { syntaxError } from '../error/syntaxError.mjs';\nimport { Location, OperationTypeNode } from './ast.mjs';\nimport { DirectiveLocation } from './directiveLocation.mjs';\nimport { Kind } from './kinds.mjs';\nimport { isPunctuatorTokenKind, Lexer } from './lexer.mjs';\nimport { isSource, Source } from './source.mjs';\nimport { TokenKind } from './tokenKind.mjs';\n/**\n * Configuration options to control parser behavior\n */\n\n/**\n * Given a GraphQL source, parses it into a Document.\n * Throws GraphQLError if a syntax error is encountered.\n */\nexport function parse(source, options) {\n  const parser = new Parser(source, options);\n  return parser.parseDocument();\n}\n/**\n * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for\n * that value.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Values directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: valueFromAST().\n */\n\nexport function parseValue(source, options) {\n  const parser = new Parser(source, options);\n  parser.expectToken(TokenKind.SOF);\n  const value = parser.parseValueLiteral(false);\n  parser.expectToken(TokenKind.EOF);\n  return value;\n}\n/**\n * Similar to parseValue(), but raises a parse error if it encounters a\n * variable. The return type will be a constant value.\n */\n\nexport function parseConstValue(source, options) {\n  const parser = new Parser(source, options);\n  parser.expectToken(TokenKind.SOF);\n  const value = parser.parseConstValueLiteral();\n  parser.expectToken(TokenKind.EOF);\n  return value;\n}\n/**\n * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for\n * that type.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Types directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: typeFromAST().\n */\n\nexport function parseType(source, options) {\n  const parser = new Parser(source, options);\n  parser.expectToken(TokenKind.SOF);\n  const type = parser.parseTypeReference();\n  parser.expectToken(TokenKind.EOF);\n  return type;\n}\n/**\n * This class is exported only to assist people in implementing their own parsers\n * without duplicating too much code and should be used only as last resort for cases\n * such as experimental syntax or if certain features could not be contributed upstream.\n *\n * It is still part of the internal API and is versioned, so any changes to it are never\n * considered breaking changes. If you still need to support multiple versions of the\n * library, please use the `versionInfo` variable for version detection.\n *\n * @internal\n */\n\nexport class Parser {\n  constructor(source, options = {}) {\n    const sourceObj = isSource(source) ? source : new Source(source);\n    this._lexer = new Lexer(sourceObj);\n    this._options = options;\n    this._tokenCounter = 0;\n  }\n  /**\n   * Converts a name lex token into a name parse node.\n   */\n\n  parseName() {\n    const token = this.expectToken(TokenKind.NAME);\n    return this.node(token, {\n      kind: Kind.NAME,\n      value: token.value,\n    });\n  } // Implements the parsing rules in the Document section.\n\n  /**\n   * Document : Definition+\n   */\n\n  parseDocument() {\n    return this.node(this._lexer.token, {\n      kind: Kind.DOCUMENT,\n      definitions: this.many(\n        TokenKind.SOF,\n        this.parseDefinition,\n        TokenKind.EOF,\n      ),\n    });\n  }\n  /**\n   * Definition :\n   *   - ExecutableDefinition\n   *   - TypeSystemDefinition\n   *   - TypeSystemExtension\n   *\n   * ExecutableDefinition :\n   *   - OperationDefinition\n   *   - FragmentDefinition\n   *\n   * TypeSystemDefinition :\n   *   - SchemaDefinition\n   *   - TypeDefinition\n   *   - DirectiveDefinition\n   *\n   * TypeDefinition :\n   *   - ScalarTypeDefinition\n   *   - ObjectTypeDefinition\n   *   - InterfaceTypeDefinition\n   *   - UnionTypeDefinition\n   *   - EnumTypeDefinition\n   *   - InputObjectTypeDefinition\n   */\n\n  parseDefinition() {\n    if (this.peek(TokenKind.BRACE_L)) {\n      return this.parseOperationDefinition();\n    } // Many definitions begin with a description and require a lookahead.\n\n    const hasDescription = this.peekDescription();\n    const keywordToken = hasDescription\n      ? this._lexer.lookahead()\n      : this._lexer.token;\n\n    if (keywordToken.kind === TokenKind.NAME) {\n      switch (keywordToken.value) {\n        case 'schema':\n          return this.parseSchemaDefinition();\n\n        case 'scalar':\n          return this.parseScalarTypeDefinition();\n\n        case 'type':\n          return this.parseObjectTypeDefinition();\n\n        case 'interface':\n          return this.parseInterfaceTypeDefinition();\n\n        case 'union':\n          return this.parseUnionTypeDefinition();\n\n        case 'enum':\n          return this.parseEnumTypeDefinition();\n\n        case 'input':\n          return this.parseInputObjectTypeDefinition();\n\n        case 'directive':\n          return this.parseDirectiveDefinition();\n      }\n\n      if (hasDescription) {\n        throw syntaxError(\n          this._lexer.source,\n          this._lexer.token.start,\n          'Unexpected description, descriptions are supported only on type definitions.',\n        );\n      }\n\n      switch (keywordToken.value) {\n        case 'query':\n        case 'mutation':\n        case 'subscription':\n          return this.parseOperationDefinition();\n\n        case 'fragment':\n          return this.parseFragmentDefinition();\n\n        case 'extend':\n          return this.parseTypeSystemExtension();\n      }\n    }\n\n    throw this.unexpected(keywordToken);\n  } // Implements the parsing rules in the Operations section.\n\n  /**\n   * OperationDefinition :\n   *  - SelectionSet\n   *  - OperationType Name? VariableDefinitions? Directives? SelectionSet\n   */\n\n  parseOperationDefinition() {\n    const start = this._lexer.token;\n\n    if (this.peek(TokenKind.BRACE_L)) {\n      return this.node(start, {\n        kind: Kind.OPERATION_DEFINITION,\n        operation: OperationTypeNode.QUERY,\n        name: undefined,\n        variableDefinitions: [],\n        directives: [],\n        selectionSet: this.parseSelectionSet(),\n      });\n    }\n\n    const operation = this.parseOperationType();\n    let name;\n\n    if (this.peek(TokenKind.NAME)) {\n      name = this.parseName();\n    }\n\n    return this.node(start, {\n      kind: Kind.OPERATION_DEFINITION,\n      operation,\n      name,\n      variableDefinitions: this.parseVariableDefinitions(),\n      directives: this.parseDirectives(false),\n      selectionSet: this.parseSelectionSet(),\n    });\n  }\n  /**\n   * OperationType : one of query mutation subscription\n   */\n\n  parseOperationType() {\n    const operationToken = this.expectToken(TokenKind.NAME);\n\n    switch (operationToken.value) {\n      case 'query':\n        return OperationTypeNode.QUERY;\n\n      case 'mutation':\n        return OperationTypeNode.MUTATION;\n\n      case 'subscription':\n        return OperationTypeNode.SUBSCRIPTION;\n    }\n\n    throw this.unexpected(operationToken);\n  }\n  /**\n   * VariableDefinitions : ( VariableDefinition+ )\n   */\n\n  parseVariableDefinitions() {\n    return this.optionalMany(\n      TokenKind.PAREN_L,\n      this.parseVariableDefinition,\n      TokenKind.PAREN_R,\n    );\n  }\n  /**\n   * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?\n   */\n\n  parseVariableDefinition() {\n    return this.node(this._lexer.token, {\n      kind: Kind.VARIABLE_DEFINITION,\n      variable: this.parseVariable(),\n      type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),\n      defaultValue: this.expectOptionalToken(TokenKind.EQUALS)\n        ? this.parseConstValueLiteral()\n        : undefined,\n      directives: this.parseConstDirectives(),\n    });\n  }\n  /**\n   * Variable : $ Name\n   */\n\n  parseVariable() {\n    const start = this._lexer.token;\n    this.expectToken(TokenKind.DOLLAR);\n    return this.node(start, {\n      kind: Kind.VARIABLE,\n      name: this.parseName(),\n    });\n  }\n  /**\n   * ```\n   * SelectionSet : { Selection+ }\n   * ```\n   */\n\n  parseSelectionSet() {\n    return this.node(this._lexer.token, {\n      kind: Kind.SELECTION_SET,\n      selections: this.many(\n        TokenKind.BRACE_L,\n        this.parseSelection,\n        TokenKind.BRACE_R,\n      ),\n    });\n  }\n  /**\n   * Selection :\n   *   - Field\n   *   - FragmentSpread\n   *   - InlineFragment\n   */\n\n  parseSelection() {\n    return this.peek(TokenKind.SPREAD)\n      ? this.parseFragment()\n      : this.parseField();\n  }\n  /**\n   * Field : Alias? Name Arguments? Directives? SelectionSet?\n   *\n   * Alias : Name :\n   */\n\n  parseField() {\n    const start = this._lexer.token;\n    const nameOrAlias = this.parseName();\n    let alias;\n    let name;\n\n    if (this.expectOptionalToken(TokenKind.COLON)) {\n      alias = nameOrAlias;\n      name = this.parseName();\n    } else {\n      name = nameOrAlias;\n    }\n\n    return this.node(start, {\n      kind: Kind.FIELD,\n      alias,\n      name,\n      arguments: this.parseArguments(false),\n      directives: this.parseDirectives(false),\n      selectionSet: this.peek(TokenKind.BRACE_L)\n        ? this.parseSelectionSet()\n        : undefined,\n    });\n  }\n  /**\n   * Arguments[Const] : ( Argument[?Const]+ )\n   */\n\n  parseArguments(isConst) {\n    const item = isConst ? this.parseConstArgument : this.parseArgument;\n    return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);\n  }\n  /**\n   * Argument[Const] : Name : Value[?Const]\n   */\n\n  parseArgument(isConst = false) {\n    const start = this._lexer.token;\n    const name = this.parseName();\n    this.expectToken(TokenKind.COLON);\n    return this.node(start, {\n      kind: Kind.ARGUMENT,\n      name,\n      value: this.parseValueLiteral(isConst),\n    });\n  }\n\n  parseConstArgument() {\n    return this.parseArgument(true);\n  } // Implements the parsing rules in the Fragments section.\n\n  /**\n   * Corresponds to both FragmentSpread and InlineFragment in the spec.\n   *\n   * FragmentSpread : ... FragmentName Directives?\n   *\n   * InlineFragment : ... TypeCondition? Directives? SelectionSet\n   */\n\n  parseFragment() {\n    const start = this._lexer.token;\n    this.expectToken(TokenKind.SPREAD);\n    const hasTypeCondition = this.expectOptionalKeyword('on');\n\n    if (!hasTypeCondition && this.peek(TokenKind.NAME)) {\n      return this.node(start, {\n        kind: Kind.FRAGMENT_SPREAD,\n        name: this.parseFragmentName(),\n        directives: this.parseDirectives(false),\n      });\n    }\n\n    return this.node(start, {\n      kind: Kind.INLINE_FRAGMENT,\n      typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,\n      directives: this.parseDirectives(false),\n      selectionSet: this.parseSelectionSet(),\n    });\n  }\n  /**\n   * FragmentDefinition :\n   *   - fragment FragmentName on TypeCondition Directives? SelectionSet\n   *\n   * TypeCondition : NamedType\n   */\n\n  parseFragmentDefinition() {\n    const start = this._lexer.token;\n    this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes\n    // the grammar of FragmentDefinition:\n    //   - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet\n\n    if (this._options.allowLegacyFragmentVariables === true) {\n      return this.node(start, {\n        kind: Kind.FRAGMENT_DEFINITION,\n        name: this.parseFragmentName(),\n        variableDefinitions: this.parseVariableDefinitions(),\n        typeCondition: (this.expectKeyword('on'), this.parseNamedType()),\n        directives: this.parseDirectives(false),\n        selectionSet: this.parseSelectionSet(),\n      });\n    }\n\n    return this.node(start, {\n      kind: Kind.FRAGMENT_DEFINITION,\n      name: this.parseFragmentName(),\n      typeCondition: (this.expectKeyword('on'), this.parseNamedType()),\n      directives: this.parseDirectives(false),\n      selectionSet: this.parseSelectionSet(),\n    });\n  }\n  /**\n   * FragmentName : Name but not `on`\n   */\n\n  parseFragmentName() {\n    if (this._lexer.token.value === 'on') {\n      throw this.unexpected();\n    }\n\n    return this.parseName();\n  } // Implements the parsing rules in the Values section.\n\n  /**\n   * Value[Const] :\n   *   - [~Const] Variable\n   *   - IntValue\n   *   - FloatValue\n   *   - StringValue\n   *   - BooleanValue\n   *   - NullValue\n   *   - EnumValue\n   *   - ListValue[?Const]\n   *   - ObjectValue[?Const]\n   *\n   * BooleanValue : one of `true` `false`\n   *\n   * NullValue : `null`\n   *\n   * EnumValue : Name but not `true`, `false` or `null`\n   */\n\n  parseValueLiteral(isConst) {\n    const token = this._lexer.token;\n\n    switch (token.kind) {\n      case TokenKind.BRACKET_L:\n        return this.parseList(isConst);\n\n      case TokenKind.BRACE_L:\n        return this.parseObject(isConst);\n\n      case TokenKind.INT:\n        this.advanceLexer();\n        return this.node(token, {\n          kind: Kind.INT,\n          value: token.value,\n        });\n\n      case TokenKind.FLOAT:\n        this.advanceLexer();\n        return this.node(token, {\n          kind: Kind.FLOAT,\n          value: token.value,\n        });\n\n      case TokenKind.STRING:\n      case TokenKind.BLOCK_STRING:\n        return this.parseStringLiteral();\n\n      case TokenKind.NAME:\n        this.advanceLexer();\n\n        switch (token.value) {\n          case 'true':\n            return this.node(token, {\n              kind: Kind.BOOLEAN,\n              value: true,\n            });\n\n          case 'false':\n            return this.node(token, {\n              kind: Kind.BOOLEAN,\n              value: false,\n            });\n\n          case 'null':\n            return this.node(token, {\n              kind: Kind.NULL,\n            });\n\n          default:\n            return this.node(token, {\n              kind: Kind.ENUM,\n              value: token.value,\n            });\n        }\n\n      case TokenKind.DOLLAR:\n        if (isConst) {\n          this.expectToken(TokenKind.DOLLAR);\n\n          if (this._lexer.token.kind === TokenKind.NAME) {\n            const varName = this._lexer.token.value;\n            throw syntaxError(\n              this._lexer.source,\n              token.start,\n              `Unexpected variable \"$${varName}\" in constant value.`,\n            );\n          } else {\n            throw this.unexpected(token);\n          }\n        }\n\n        return this.parseVariable();\n\n      default:\n        throw this.unexpected();\n    }\n  }\n\n  parseConstValueLiteral() {\n    return this.parseValueLiteral(true);\n  }\n\n  parseStringLiteral() {\n    const token = this._lexer.token;\n    this.advanceLexer();\n    return this.node(token, {\n      kind: Kind.STRING,\n      value: token.value,\n      block: token.kind === TokenKind.BLOCK_STRING,\n    });\n  }\n  /**\n   * ListValue[Const] :\n   *   - [ ]\n   *   - [ Value[?Const]+ ]\n   */\n\n  parseList(isConst) {\n    const item = () => this.parseValueLiteral(isConst);\n\n    return this.node(this._lexer.token, {\n      kind: Kind.LIST,\n      values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),\n    });\n  }\n  /**\n   * ```\n   * ObjectValue[Const] :\n   *   - { }\n   *   - { ObjectField[?Const]+ }\n   * ```\n   */\n\n  parseObject(isConst) {\n    const item = () => this.parseObjectField(isConst);\n\n    return this.node(this._lexer.token, {\n      kind: Kind.OBJECT,\n      fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),\n    });\n  }\n  /**\n   * ObjectField[Const] : Name : Value[?Const]\n   */\n\n  parseObjectField(isConst) {\n    const start = this._lexer.token;\n    const name = this.parseName();\n    this.expectToken(TokenKind.COLON);\n    return this.node(start, {\n      kind: Kind.OBJECT_FIELD,\n      name,\n      value: this.parseValueLiteral(isConst),\n    });\n  } // Implements the parsing rules in the Directives section.\n\n  /**\n   * Directives[Const] : Directive[?Const]+\n   */\n\n  parseDirectives(isConst) {\n    const directives = [];\n\n    while (this.peek(TokenKind.AT)) {\n      directives.push(this.parseDirective(isConst));\n    }\n\n    return directives;\n  }\n\n  parseConstDirectives() {\n    return this.parseDirectives(true);\n  }\n  /**\n   * ```\n   * Directive[Const] : @ Name Arguments[?Const]?\n   * ```\n   */\n\n  parseDirective(isConst) {\n    const start = this._lexer.token;\n    this.expectToken(TokenKind.AT);\n    return this.node(start, {\n      kind: Kind.DIRECTIVE,\n      name: this.parseName(),\n      arguments: this.parseArguments(isConst),\n    });\n  } // Implements the parsing rules in the Types section.\n\n  /**\n   * Type :\n   *   - NamedType\n   *   - ListType\n   *   - NonNullType\n   */\n\n  parseTypeReference() {\n    const start = this._lexer.token;\n    let type;\n\n    if (this.expectOptionalToken(TokenKind.BRACKET_L)) {\n      const innerType = this.parseTypeReference();\n      this.expectToken(TokenKind.BRACKET_R);\n      type = this.node(start, {\n        kind: Kind.LIST_TYPE,\n        type: innerType,\n      });\n    } else {\n      type = this.parseNamedType();\n    }\n\n    if (this.expectOptionalToken(TokenKind.BANG)) {\n      return this.node(start, {\n        kind: Kind.NON_NULL_TYPE,\n        type,\n      });\n    }\n\n    return type;\n  }\n  /**\n   * NamedType : Name\n   */\n\n  parseNamedType() {\n    return this.node(this._lexer.token, {\n      kind: Kind.NAMED_TYPE,\n      name: this.parseName(),\n    });\n  } // Implements the parsing rules in the Type Definition section.\n\n  peekDescription() {\n    return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);\n  }\n  /**\n   * Description : StringValue\n   */\n\n  parseDescription() {\n    if (this.peekDescription()) {\n      return this.parseStringLiteral();\n    }\n  }\n  /**\n   * ```\n   * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }\n   * ```\n   */\n\n  parseSchemaDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    this.expectKeyword('schema');\n    const directives = this.parseConstDirectives();\n    const operationTypes = this.many(\n      TokenKind.BRACE_L,\n      this.parseOperationTypeDefinition,\n      TokenKind.BRACE_R,\n    );\n    return this.node(start, {\n      kind: Kind.SCHEMA_DEFINITION,\n      description,\n      directives,\n      operationTypes,\n    });\n  }\n  /**\n   * OperationTypeDefinition : OperationType : NamedType\n   */\n\n  parseOperationTypeDefinition() {\n    const start = this._lexer.token;\n    const operation = this.parseOperationType();\n    this.expectToken(TokenKind.COLON);\n    const type = this.parseNamedType();\n    return this.node(start, {\n      kind: Kind.OPERATION_TYPE_DEFINITION,\n      operation,\n      type,\n    });\n  }\n  /**\n   * ScalarTypeDefinition : Description? scalar Name Directives[Const]?\n   */\n\n  parseScalarTypeDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    this.expectKeyword('scalar');\n    const name = this.parseName();\n    const directives = this.parseConstDirectives();\n    return this.node(start, {\n      kind: Kind.SCALAR_TYPE_DEFINITION,\n      description,\n      name,\n      directives,\n    });\n  }\n  /**\n   * ObjectTypeDefinition :\n   *   Description?\n   *   type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?\n   */\n\n  parseObjectTypeDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    this.expectKeyword('type');\n    const name = this.parseName();\n    const interfaces = this.parseImplementsInterfaces();\n    const directives = this.parseConstDirectives();\n    const fields = this.parseFieldsDefinition();\n    return this.node(start, {\n      kind: Kind.OBJECT_TYPE_DEFINITION,\n      description,\n      name,\n      interfaces,\n      directives,\n      fields,\n    });\n  }\n  /**\n   * ImplementsInterfaces :\n   *   - implements `&`? NamedType\n   *   - ImplementsInterfaces & NamedType\n   */\n\n  parseImplementsInterfaces() {\n    return this.expectOptionalKeyword('implements')\n      ? this.delimitedMany(TokenKind.AMP, this.parseNamedType)\n      : [];\n  }\n  /**\n   * ```\n   * FieldsDefinition : { FieldDefinition+ }\n   * ```\n   */\n\n  parseFieldsDefinition() {\n    return this.optionalMany(\n      TokenKind.BRACE_L,\n      this.parseFieldDefinition,\n      TokenKind.BRACE_R,\n    );\n  }\n  /**\n   * FieldDefinition :\n   *   - Description? Name ArgumentsDefinition? : Type Directives[Const]?\n   */\n\n  parseFieldDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    const name = this.parseName();\n    const args = this.parseArgumentDefs();\n    this.expectToken(TokenKind.COLON);\n    const type = this.parseTypeReference();\n    const directives = this.parseConstDirectives();\n    return this.node(start, {\n      kind: Kind.FIELD_DEFINITION,\n      description,\n      name,\n      arguments: args,\n      type,\n      directives,\n    });\n  }\n  /**\n   * ArgumentsDefinition : ( InputValueDefinition+ )\n   */\n\n  parseArgumentDefs() {\n    return this.optionalMany(\n      TokenKind.PAREN_L,\n      this.parseInputValueDef,\n      TokenKind.PAREN_R,\n    );\n  }\n  /**\n   * InputValueDefinition :\n   *   - Description? Name : Type DefaultValue? Directives[Const]?\n   */\n\n  parseInputValueDef() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    const name = this.parseName();\n    this.expectToken(TokenKind.COLON);\n    const type = this.parseTypeReference();\n    let defaultValue;\n\n    if (this.expectOptionalToken(TokenKind.EQUALS)) {\n      defaultValue = this.parseConstValueLiteral();\n    }\n\n    const directives = this.parseConstDirectives();\n    return this.node(start, {\n      kind: Kind.INPUT_VALUE_DEFINITION,\n      description,\n      name,\n      type,\n      defaultValue,\n      directives,\n    });\n  }\n  /**\n   * InterfaceTypeDefinition :\n   *   - Description? interface Name Directives[Const]? FieldsDefinition?\n   */\n\n  parseInterfaceTypeDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    this.expectKeyword('interface');\n    const name = this.parseName();\n    const interfaces = this.parseImplementsInterfaces();\n    const directives = this.parseConstDirectives();\n    const fields = this.parseFieldsDefinition();\n    return this.node(start, {\n      kind: Kind.INTERFACE_TYPE_DEFINITION,\n      description,\n      name,\n      interfaces,\n      directives,\n      fields,\n    });\n  }\n  /**\n   * UnionTypeDefinition :\n   *   - Description? union Name Directives[Const]? UnionMemberTypes?\n   */\n\n  parseUnionTypeDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    this.expectKeyword('union');\n    const name = this.parseName();\n    const directives = this.parseConstDirectives();\n    const types = this.parseUnionMemberTypes();\n    return this.node(start, {\n      kind: Kind.UNION_TYPE_DEFINITION,\n      description,\n      name,\n      directives,\n      types,\n    });\n  }\n  /**\n   * UnionMemberTypes :\n   *   - = `|`? NamedType\n   *   - UnionMemberTypes | NamedType\n   */\n\n  parseUnionMemberTypes() {\n    return this.expectOptionalToken(TokenKind.EQUALS)\n      ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType)\n      : [];\n  }\n  /**\n   * EnumTypeDefinition :\n   *   - Description? enum Name Directives[Const]? EnumValuesDefinition?\n   */\n\n  parseEnumTypeDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    this.expectKeyword('enum');\n    const name = this.parseName();\n    const directives = this.parseConstDirectives();\n    const values = this.parseEnumValuesDefinition();\n    return this.node(start, {\n      kind: Kind.ENUM_TYPE_DEFINITION,\n      description,\n      name,\n      directives,\n      values,\n    });\n  }\n  /**\n   * ```\n   * EnumValuesDefinition : { EnumValueDefinition+ }\n   * ```\n   */\n\n  parseEnumValuesDefinition() {\n    return this.optionalMany(\n      TokenKind.BRACE_L,\n      this.parseEnumValueDefinition,\n      TokenKind.BRACE_R,\n    );\n  }\n  /**\n   * EnumValueDefinition : Description? EnumValue Directives[Const]?\n   */\n\n  parseEnumValueDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    const name = this.parseEnumValueName();\n    const directives = this.parseConstDirectives();\n    return this.node(start, {\n      kind: Kind.ENUM_VALUE_DEFINITION,\n      description,\n      name,\n      directives,\n    });\n  }\n  /**\n   * EnumValue : Name but not `true`, `false` or `null`\n   */\n\n  parseEnumValueName() {\n    if (\n      this._lexer.token.value === 'true' ||\n      this._lexer.token.value === 'false' ||\n      this._lexer.token.value === 'null'\n    ) {\n      throw syntaxError(\n        this._lexer.source,\n        this._lexer.token.start,\n        `${getTokenDesc(\n          this._lexer.token,\n        )} is reserved and cannot be used for an enum value.`,\n      );\n    }\n\n    return this.parseName();\n  }\n  /**\n   * InputObjectTypeDefinition :\n   *   - Description? input Name Directives[Const]? InputFieldsDefinition?\n   */\n\n  parseInputObjectTypeDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    this.expectKeyword('input');\n    const name = this.parseName();\n    const directives = this.parseConstDirectives();\n    const fields = this.parseInputFieldsDefinition();\n    return this.node(start, {\n      kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,\n      description,\n      name,\n      directives,\n      fields,\n    });\n  }\n  /**\n   * ```\n   * InputFieldsDefinition : { InputValueDefinition+ }\n   * ```\n   */\n\n  parseInputFieldsDefinition() {\n    return this.optionalMany(\n      TokenKind.BRACE_L,\n      this.parseInputValueDef,\n      TokenKind.BRACE_R,\n    );\n  }\n  /**\n   * TypeSystemExtension :\n   *   - SchemaExtension\n   *   - TypeExtension\n   *\n   * TypeExtension :\n   *   - ScalarTypeExtension\n   *   - ObjectTypeExtension\n   *   - InterfaceTypeExtension\n   *   - UnionTypeExtension\n   *   - EnumTypeExtension\n   *   - InputObjectTypeDefinition\n   */\n\n  parseTypeSystemExtension() {\n    const keywordToken = this._lexer.lookahead();\n\n    if (keywordToken.kind === TokenKind.NAME) {\n      switch (keywordToken.value) {\n        case 'schema':\n          return this.parseSchemaExtension();\n\n        case 'scalar':\n          return this.parseScalarTypeExtension();\n\n        case 'type':\n          return this.parseObjectTypeExtension();\n\n        case 'interface':\n          return this.parseInterfaceTypeExtension();\n\n        case 'union':\n          return this.parseUnionTypeExtension();\n\n        case 'enum':\n          return this.parseEnumTypeExtension();\n\n        case 'input':\n          return this.parseInputObjectTypeExtension();\n      }\n    }\n\n    throw this.unexpected(keywordToken);\n  }\n  /**\n   * ```\n   * SchemaExtension :\n   *  - extend schema Directives[Const]? { OperationTypeDefinition+ }\n   *  - extend schema Directives[Const]\n   * ```\n   */\n\n  parseSchemaExtension() {\n    const start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('schema');\n    const directives = this.parseConstDirectives();\n    const operationTypes = this.optionalMany(\n      TokenKind.BRACE_L,\n      this.parseOperationTypeDefinition,\n      TokenKind.BRACE_R,\n    );\n\n    if (directives.length === 0 && operationTypes.length === 0) {\n      throw this.unexpected();\n    }\n\n    return this.node(start, {\n      kind: Kind.SCHEMA_EXTENSION,\n      directives,\n      operationTypes,\n    });\n  }\n  /**\n   * ScalarTypeExtension :\n   *   - extend scalar Name Directives[Const]\n   */\n\n  parseScalarTypeExtension() {\n    const start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('scalar');\n    const name = this.parseName();\n    const directives = this.parseConstDirectives();\n\n    if (directives.length === 0) {\n      throw this.unexpected();\n    }\n\n    return this.node(start, {\n      kind: Kind.SCALAR_TYPE_EXTENSION,\n      name,\n      directives,\n    });\n  }\n  /**\n   * ObjectTypeExtension :\n   *  - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition\n   *  - extend type Name ImplementsInterfaces? Directives[Const]\n   *  - extend type Name ImplementsInterfaces\n   */\n\n  parseObjectTypeExtension() {\n    const start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('type');\n    const name = this.parseName();\n    const interfaces = this.parseImplementsInterfaces();\n    const directives = this.parseConstDirectives();\n    const fields = this.parseFieldsDefinition();\n\n    if (\n      interfaces.length === 0 &&\n      directives.length === 0 &&\n      fields.length === 0\n    ) {\n      throw this.unexpected();\n    }\n\n    return this.node(start, {\n      kind: Kind.OBJECT_TYPE_EXTENSION,\n      name,\n      interfaces,\n      directives,\n      fields,\n    });\n  }\n  /**\n   * InterfaceTypeExtension :\n   *  - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition\n   *  - extend interface Name ImplementsInterfaces? Directives[Const]\n   *  - extend interface Name ImplementsInterfaces\n   */\n\n  parseInterfaceTypeExtension() {\n    const start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('interface');\n    const name = this.parseName();\n    const interfaces = this.parseImplementsInterfaces();\n    const directives = this.parseConstDirectives();\n    const fields = this.parseFieldsDefinition();\n\n    if (\n      interfaces.length === 0 &&\n      directives.length === 0 &&\n      fields.length === 0\n    ) {\n      throw this.unexpected();\n    }\n\n    return this.node(start, {\n      kind: Kind.INTERFACE_TYPE_EXTENSION,\n      name,\n      interfaces,\n      directives,\n      fields,\n    });\n  }\n  /**\n   * UnionTypeExtension :\n   *   - extend union Name Directives[Const]? UnionMemberTypes\n   *   - extend union Name Directives[Const]\n   */\n\n  parseUnionTypeExtension() {\n    const start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('union');\n    const name = this.parseName();\n    const directives = this.parseConstDirectives();\n    const types = this.parseUnionMemberTypes();\n\n    if (directives.length === 0 && types.length === 0) {\n      throw this.unexpected();\n    }\n\n    return this.node(start, {\n      kind: Kind.UNION_TYPE_EXTENSION,\n      name,\n      directives,\n      types,\n    });\n  }\n  /**\n   * EnumTypeExtension :\n   *   - extend enum Name Directives[Const]? EnumValuesDefinition\n   *   - extend enum Name Directives[Const]\n   */\n\n  parseEnumTypeExtension() {\n    const start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('enum');\n    const name = this.parseName();\n    const directives = this.parseConstDirectives();\n    const values = this.parseEnumValuesDefinition();\n\n    if (directives.length === 0 && values.length === 0) {\n      throw this.unexpected();\n    }\n\n    return this.node(start, {\n      kind: Kind.ENUM_TYPE_EXTENSION,\n      name,\n      directives,\n      values,\n    });\n  }\n  /**\n   * InputObjectTypeExtension :\n   *   - extend input Name Directives[Const]? InputFieldsDefinition\n   *   - extend input Name Directives[Const]\n   */\n\n  parseInputObjectTypeExtension() {\n    const start = this._lexer.token;\n    this.expectKeyword('extend');\n    this.expectKeyword('input');\n    const name = this.parseName();\n    const directives = this.parseConstDirectives();\n    const fields = this.parseInputFieldsDefinition();\n\n    if (directives.length === 0 && fields.length === 0) {\n      throw this.unexpected();\n    }\n\n    return this.node(start, {\n      kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n      name,\n      directives,\n      fields,\n    });\n  }\n  /**\n   * ```\n   * DirectiveDefinition :\n   *   - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations\n   * ```\n   */\n\n  parseDirectiveDefinition() {\n    const start = this._lexer.token;\n    const description = this.parseDescription();\n    this.expectKeyword('directive');\n    this.expectToken(TokenKind.AT);\n    const name = this.parseName();\n    const args = this.parseArgumentDefs();\n    const repeatable = this.expectOptionalKeyword('repeatable');\n    this.expectKeyword('on');\n    const locations = this.parseDirectiveLocations();\n    return this.node(start, {\n      kind: Kind.DIRECTIVE_DEFINITION,\n      description,\n      name,\n      arguments: args,\n      repeatable,\n      locations,\n    });\n  }\n  /**\n   * DirectiveLocations :\n   *   - `|`? DirectiveLocation\n   *   - DirectiveLocations | DirectiveLocation\n   */\n\n  parseDirectiveLocations() {\n    return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);\n  }\n  /*\n   * DirectiveLocation :\n   *   - ExecutableDirectiveLocation\n   *   - TypeSystemDirectiveLocation\n   *\n   * ExecutableDirectiveLocation : one of\n   *   `QUERY`\n   *   `MUTATION`\n   *   `SUBSCRIPTION`\n   *   `FIELD`\n   *   `FRAGMENT_DEFINITION`\n   *   `FRAGMENT_SPREAD`\n   *   `INLINE_FRAGMENT`\n   *\n   * TypeSystemDirectiveLocation : one of\n   *   `SCHEMA`\n   *   `SCALAR`\n   *   `OBJECT`\n   *   `FIELD_DEFINITION`\n   *   `ARGUMENT_DEFINITION`\n   *   `INTERFACE`\n   *   `UNION`\n   *   `ENUM`\n   *   `ENUM_VALUE`\n   *   `INPUT_OBJECT`\n   *   `INPUT_FIELD_DEFINITION`\n   */\n\n  parseDirectiveLocation() {\n    const start = this._lexer.token;\n    const name = this.parseName();\n\n    if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name.value)) {\n      return name;\n    }\n\n    throw this.unexpected(start);\n  } // Core parsing utility functions\n\n  /**\n   * Returns a node that, if configured to do so, sets a \"loc\" field as a\n   * location object, used to identify the place in the source that created a\n   * given parsed object.\n   */\n\n  node(startToken, node) {\n    if (this._options.noLocation !== true) {\n      node.loc = new Location(\n        startToken,\n        this._lexer.lastToken,\n        this._lexer.source,\n      );\n    }\n\n    return node;\n  }\n  /**\n   * Determines if the next token is of a given kind\n   */\n\n  peek(kind) {\n    return this._lexer.token.kind === kind;\n  }\n  /**\n   * If the next token is of the given kind, return that token after advancing the lexer.\n   * Otherwise, do not change the parser state and throw an error.\n   */\n\n  expectToken(kind) {\n    const token = this._lexer.token;\n\n    if (token.kind === kind) {\n      this.advanceLexer();\n      return token;\n    }\n\n    throw syntaxError(\n      this._lexer.source,\n      token.start,\n      `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`,\n    );\n  }\n  /**\n   * If the next token is of the given kind, return \"true\" after advancing the lexer.\n   * Otherwise, do not change the parser state and return \"false\".\n   */\n\n  expectOptionalToken(kind) {\n    const token = this._lexer.token;\n\n    if (token.kind === kind) {\n      this.advanceLexer();\n      return true;\n    }\n\n    return false;\n  }\n  /**\n   * If the next token is a given keyword, advance the lexer.\n   * Otherwise, do not change the parser state and throw an error.\n   */\n\n  expectKeyword(value) {\n    const token = this._lexer.token;\n\n    if (token.kind === TokenKind.NAME && token.value === value) {\n      this.advanceLexer();\n    } else {\n      throw syntaxError(\n        this._lexer.source,\n        token.start,\n        `Expected \"${value}\", found ${getTokenDesc(token)}.`,\n      );\n    }\n  }\n  /**\n   * If the next token is a given keyword, return \"true\" after advancing the lexer.\n   * Otherwise, do not change the parser state and return \"false\".\n   */\n\n  expectOptionalKeyword(value) {\n    const token = this._lexer.token;\n\n    if (token.kind === TokenKind.NAME && token.value === value) {\n      this.advanceLexer();\n      return true;\n    }\n\n    return false;\n  }\n  /**\n   * Helper function for creating an error when an unexpected lexed token is encountered.\n   */\n\n  unexpected(atToken) {\n    const token =\n      atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;\n    return syntaxError(\n      this._lexer.source,\n      token.start,\n      `Unexpected ${getTokenDesc(token)}.`,\n    );\n  }\n  /**\n   * Returns a possibly empty list of parse nodes, determined by the parseFn.\n   * This list begins with a lex token of openKind and ends with a lex token of closeKind.\n   * Advances the parser to the next lex token after the closing token.\n   */\n\n  any(openKind, parseFn, closeKind) {\n    this.expectToken(openKind);\n    const nodes = [];\n\n    while (!this.expectOptionalToken(closeKind)) {\n      nodes.push(parseFn.call(this));\n    }\n\n    return nodes;\n  }\n  /**\n   * Returns a list of parse nodes, determined by the parseFn.\n   * It can be empty only if open token is missing otherwise it will always return non-empty list\n   * that begins with a lex token of openKind and ends with a lex token of closeKind.\n   * Advances the parser to the next lex token after the closing token.\n   */\n\n  optionalMany(openKind, parseFn, closeKind) {\n    if (this.expectOptionalToken(openKind)) {\n      const nodes = [];\n\n      do {\n        nodes.push(parseFn.call(this));\n      } while (!this.expectOptionalToken(closeKind));\n\n      return nodes;\n    }\n\n    return [];\n  }\n  /**\n   * Returns a non-empty list of parse nodes, determined by the parseFn.\n   * This list begins with a lex token of openKind and ends with a lex token of closeKind.\n   * Advances the parser to the next lex token after the closing token.\n   */\n\n  many(openKind, parseFn, closeKind) {\n    this.expectToken(openKind);\n    const nodes = [];\n\n    do {\n      nodes.push(parseFn.call(this));\n    } while (!this.expectOptionalToken(closeKind));\n\n    return nodes;\n  }\n  /**\n   * Returns a non-empty list of parse nodes, determined by the parseFn.\n   * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.\n   * Advances the parser to the next lex token after last item in the list.\n   */\n\n  delimitedMany(delimiterKind, parseFn) {\n    this.expectOptionalToken(delimiterKind);\n    const nodes = [];\n\n    do {\n      nodes.push(parseFn.call(this));\n    } while (this.expectOptionalToken(delimiterKind));\n\n    return nodes;\n  }\n\n  advanceLexer() {\n    const { maxTokens } = this._options;\n\n    const token = this._lexer.advance();\n\n    if (maxTokens !== undefined && token.kind !== TokenKind.EOF) {\n      ++this._tokenCounter;\n\n      if (this._tokenCounter > maxTokens) {\n        throw syntaxError(\n          this._lexer.source,\n          token.start,\n          `Document contains more that ${maxTokens} tokens. Parsing aborted.`,\n        );\n      }\n    }\n  }\n}\n/**\n * A helper function to describe a token as a string for debugging.\n */\n\nfunction getTokenDesc(token) {\n  const value = token.value;\n  return getTokenKindDesc(token.kind) + (value != null ? ` \"${value}\"` : '');\n}\n/**\n * A helper function to describe a token kind as a string for debugging.\n */\n\nfunction getTokenKindDesc(kind) {\n  return isPunctuatorTokenKind(kind) ? `\"${kind}\"` : kind;\n}\n","/**\n * Prints a string as a GraphQL StringValue literal. Replaces control characters\n * and excluded characters (\" U+0022 and \\\\ U+005C) with escape sequences.\n */\nexport function printString(str) {\n  return `\"${str.replace(escapedRegExp, escapedReplacer)}\"`;\n} // eslint-disable-next-line no-control-regex\n\nconst escapedRegExp = /[\\x00-\\x1f\\x22\\x5c\\x7f-\\x9f]/g;\n\nfunction escapedReplacer(str) {\n  return escapeSequences[str.charCodeAt(0)];\n} // prettier-ignore\n\nconst escapeSequences = [\n  '\\\\u0000',\n  '\\\\u0001',\n  '\\\\u0002',\n  '\\\\u0003',\n  '\\\\u0004',\n  '\\\\u0005',\n  '\\\\u0006',\n  '\\\\u0007',\n  '\\\\b',\n  '\\\\t',\n  '\\\\n',\n  '\\\\u000B',\n  '\\\\f',\n  '\\\\r',\n  '\\\\u000E',\n  '\\\\u000F',\n  '\\\\u0010',\n  '\\\\u0011',\n  '\\\\u0012',\n  '\\\\u0013',\n  '\\\\u0014',\n  '\\\\u0015',\n  '\\\\u0016',\n  '\\\\u0017',\n  '\\\\u0018',\n  '\\\\u0019',\n  '\\\\u001A',\n  '\\\\u001B',\n  '\\\\u001C',\n  '\\\\u001D',\n  '\\\\u001E',\n  '\\\\u001F',\n  '',\n  '',\n  '\\\\\"',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '', // 2F\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '', // 3F\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '', // 4F\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '\\\\\\\\',\n  '',\n  '',\n  '', // 5F\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '', // 6F\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '',\n  '\\\\u007F',\n  '\\\\u0080',\n  '\\\\u0081',\n  '\\\\u0082',\n  '\\\\u0083',\n  '\\\\u0084',\n  '\\\\u0085',\n  '\\\\u0086',\n  '\\\\u0087',\n  '\\\\u0088',\n  '\\\\u0089',\n  '\\\\u008A',\n  '\\\\u008B',\n  '\\\\u008C',\n  '\\\\u008D',\n  '\\\\u008E',\n  '\\\\u008F',\n  '\\\\u0090',\n  '\\\\u0091',\n  '\\\\u0092',\n  '\\\\u0093',\n  '\\\\u0094',\n  '\\\\u0095',\n  '\\\\u0096',\n  '\\\\u0097',\n  '\\\\u0098',\n  '\\\\u0099',\n  '\\\\u009A',\n  '\\\\u009B',\n  '\\\\u009C',\n  '\\\\u009D',\n  '\\\\u009E',\n  '\\\\u009F',\n];\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { isNode, QueryDocumentKeys } from './ast.mjs';\nimport { Kind } from './kinds.mjs';\n/**\n * A visitor is provided to visit, it contains the collection of\n * relevant functions to be called during the visitor's traversal.\n */\n\nexport const BREAK = Object.freeze({});\n/**\n * visit() will walk through an AST using a depth-first traversal, calling\n * the visitor's enter function at each node in the traversal, and calling the\n * leave function after visiting that node and all of its child nodes.\n *\n * By returning different values from the enter and leave functions, the\n * behavior of the visitor can be altered, including skipping over a sub-tree of\n * the AST (by returning false), editing the AST by returning a value or null\n * to remove the value, or to stop the whole traversal by returning BREAK.\n *\n * When using visit() to edit an AST, the original AST will not be modified, and\n * a new version of the AST with the changes applied will be returned from the\n * visit function.\n *\n * ```ts\n * const editedAST = visit(ast, {\n *   enter(node, key, parent, path, ancestors) {\n *     // @return\n *     //   undefined: no action\n *     //   false: skip visiting this node\n *     //   visitor.BREAK: stop visiting altogether\n *     //   null: delete this node\n *     //   any value: replace this node with the returned value\n *   },\n *   leave(node, key, parent, path, ancestors) {\n *     // @return\n *     //   undefined: no action\n *     //   false: no action\n *     //   visitor.BREAK: stop visiting altogether\n *     //   null: delete this node\n *     //   any value: replace this node with the returned value\n *   }\n * });\n * ```\n *\n * Alternatively to providing enter() and leave() functions, a visitor can\n * instead provide functions named the same as the kinds of AST nodes, or\n * enter/leave visitors at a named key, leading to three permutations of the\n * visitor API:\n *\n * 1) Named visitors triggered when entering a node of a specific kind.\n *\n * ```ts\n * visit(ast, {\n *   Kind(node) {\n *     // enter the \"Kind\" node\n *   }\n * })\n * ```\n *\n * 2) Named visitors that trigger upon entering and leaving a node of a specific kind.\n *\n * ```ts\n * visit(ast, {\n *   Kind: {\n *     enter(node) {\n *       // enter the \"Kind\" node\n *     }\n *     leave(node) {\n *       // leave the \"Kind\" node\n *     }\n *   }\n * })\n * ```\n *\n * 3) Generic visitors that trigger upon entering and leaving any node.\n *\n * ```ts\n * visit(ast, {\n *   enter(node) {\n *     // enter any node\n *   },\n *   leave(node) {\n *     // leave any node\n *   }\n * })\n * ```\n */\n\nexport function visit(root, visitor, visitorKeys = QueryDocumentKeys) {\n  const enterLeaveMap = new Map();\n\n  for (const kind of Object.values(Kind)) {\n    enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind));\n  }\n  /* eslint-disable no-undef-init */\n\n  let stack = undefined;\n  let inArray = Array.isArray(root);\n  let keys = [root];\n  let index = -1;\n  let edits = [];\n  let node = root;\n  let key = undefined;\n  let parent = undefined;\n  const path = [];\n  const ancestors = [];\n  /* eslint-enable no-undef-init */\n\n  do {\n    index++;\n    const isLeaving = index === keys.length;\n    const isEdited = isLeaving && edits.length !== 0;\n\n    if (isLeaving) {\n      key = ancestors.length === 0 ? undefined : path[path.length - 1];\n      node = parent;\n      parent = ancestors.pop();\n\n      if (isEdited) {\n        if (inArray) {\n          node = node.slice();\n          let editOffset = 0;\n\n          for (const [editKey, editValue] of edits) {\n            const arrayKey = editKey - editOffset;\n\n            if (editValue === null) {\n              node.splice(arrayKey, 1);\n              editOffset++;\n            } else {\n              node[arrayKey] = editValue;\n            }\n          }\n        } else {\n          node = Object.defineProperties(\n            {},\n            Object.getOwnPropertyDescriptors(node),\n          );\n\n          for (const [editKey, editValue] of edits) {\n            node[editKey] = editValue;\n          }\n        }\n      }\n\n      index = stack.index;\n      keys = stack.keys;\n      edits = stack.edits;\n      inArray = stack.inArray;\n      stack = stack.prev;\n    } else if (parent) {\n      key = inArray ? index : keys[index];\n      node = parent[key];\n\n      if (node === null || node === undefined) {\n        continue;\n      }\n\n      path.push(key);\n    }\n\n    let result;\n\n    if (!Array.isArray(node)) {\n      var _enterLeaveMap$get, _enterLeaveMap$get2;\n\n      isNode(node) || devAssert(false, `Invalid AST Node: ${inspect(node)}.`);\n      const visitFn = isLeaving\n        ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null ||\n          _enterLeaveMap$get === void 0\n          ? void 0\n          : _enterLeaveMap$get.leave\n        : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null ||\n          _enterLeaveMap$get2 === void 0\n        ? void 0\n        : _enterLeaveMap$get2.enter;\n      result =\n        visitFn === null || visitFn === void 0\n          ? void 0\n          : visitFn.call(visitor, node, key, parent, path, ancestors);\n\n      if (result === BREAK) {\n        break;\n      }\n\n      if (result === false) {\n        if (!isLeaving) {\n          path.pop();\n          continue;\n        }\n      } else if (result !== undefined) {\n        edits.push([key, result]);\n\n        if (!isLeaving) {\n          if (isNode(result)) {\n            node = result;\n          } else {\n            path.pop();\n            continue;\n          }\n        }\n      }\n    }\n\n    if (result === undefined && isEdited) {\n      edits.push([key, node]);\n    }\n\n    if (isLeaving) {\n      path.pop();\n    } else {\n      var _node$kind;\n\n      stack = {\n        inArray,\n        index,\n        keys,\n        edits,\n        prev: stack,\n      };\n      inArray = Array.isArray(node);\n      keys = inArray\n        ? node\n        : (_node$kind = visitorKeys[node.kind]) !== null &&\n          _node$kind !== void 0\n        ? _node$kind\n        : [];\n      index = -1;\n      edits = [];\n\n      if (parent) {\n        ancestors.push(parent);\n      }\n\n      parent = node;\n    }\n  } while (stack !== undefined);\n\n  if (edits.length !== 0) {\n    // New root\n    return edits[edits.length - 1][1];\n  }\n\n  return root;\n}\n/**\n * Creates a new visitor instance which delegates to many visitors to run in\n * parallel. Each visitor will be visited for each node before moving on.\n *\n * If a prior visitor edits a node, no following visitors will see that node.\n */\n\nexport function visitInParallel(visitors) {\n  const skipping = new Array(visitors.length).fill(null);\n  const mergedVisitor = Object.create(null);\n\n  for (const kind of Object.values(Kind)) {\n    let hasVisitor = false;\n    const enterList = new Array(visitors.length).fill(undefined);\n    const leaveList = new Array(visitors.length).fill(undefined);\n\n    for (let i = 0; i < visitors.length; ++i) {\n      const { enter, leave } = getEnterLeaveForKind(visitors[i], kind);\n      hasVisitor || (hasVisitor = enter != null || leave != null);\n      enterList[i] = enter;\n      leaveList[i] = leave;\n    }\n\n    if (!hasVisitor) {\n      continue;\n    }\n\n    const mergedEnterLeave = {\n      enter(...args) {\n        const node = args[0];\n\n        for (let i = 0; i < visitors.length; i++) {\n          if (skipping[i] === null) {\n            var _enterList$i;\n\n            const result =\n              (_enterList$i = enterList[i]) === null || _enterList$i === void 0\n                ? void 0\n                : _enterList$i.apply(visitors[i], args);\n\n            if (result === false) {\n              skipping[i] = node;\n            } else if (result === BREAK) {\n              skipping[i] = BREAK;\n            } else if (result !== undefined) {\n              return result;\n            }\n          }\n        }\n      },\n\n      leave(...args) {\n        const node = args[0];\n\n        for (let i = 0; i < visitors.length; i++) {\n          if (skipping[i] === null) {\n            var _leaveList$i;\n\n            const result =\n              (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0\n                ? void 0\n                : _leaveList$i.apply(visitors[i], args);\n\n            if (result === BREAK) {\n              skipping[i] = BREAK;\n            } else if (result !== undefined && result !== false) {\n              return result;\n            }\n          } else if (skipping[i] === node) {\n            skipping[i] = null;\n          }\n        }\n      },\n    };\n    mergedVisitor[kind] = mergedEnterLeave;\n  }\n\n  return mergedVisitor;\n}\n/**\n * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind.\n */\n\nexport function getEnterLeaveForKind(visitor, kind) {\n  const kindVisitor = visitor[kind];\n\n  if (typeof kindVisitor === 'object') {\n    // { Kind: { enter() {}, leave() {} } }\n    return kindVisitor;\n  } else if (typeof kindVisitor === 'function') {\n    // { Kind() {} }\n    return {\n      enter: kindVisitor,\n      leave: undefined,\n    };\n  } // { enter() {}, leave() {} }\n\n  return {\n    enter: visitor.enter,\n    leave: visitor.leave,\n  };\n}\n/**\n * Given a visitor instance, if it is leaving or not, and a node kind, return\n * the function the visitor runtime should call.\n *\n * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17\n */\n\n/* c8 ignore next 8 */\n\nexport function getVisitFn(visitor, kind, isLeaving) {\n  const { enter, leave } = getEnterLeaveForKind(visitor, kind);\n  return isLeaving ? leave : enter;\n}\n","import { printBlockString } from './blockString.mjs';\nimport { printString } from './printString.mjs';\nimport { visit } from './visitor.mjs';\n/**\n * Converts an AST into a string, using one set of reasonable\n * formatting rules.\n */\n\nexport function print(ast) {\n  return visit(ast, printDocASTReducer);\n}\nconst MAX_LINE_LENGTH = 80;\nconst printDocASTReducer = {\n  Name: {\n    leave: (node) => node.value,\n  },\n  Variable: {\n    leave: (node) => '$' + node.name,\n  },\n  // Document\n  Document: {\n    leave: (node) => join(node.definitions, '\\n\\n'),\n  },\n  OperationDefinition: {\n    leave(node) {\n      const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');\n      const prefix = join(\n        [\n          node.operation,\n          join([node.name, varDefs]),\n          join(node.directives, ' '),\n        ],\n        ' ',\n      ); // Anonymous queries with no directives or variable definitions can use\n      // the query short form.\n\n      return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet;\n    },\n  },\n  VariableDefinition: {\n    leave: ({ variable, type, defaultValue, directives }) =>\n      variable +\n      ': ' +\n      type +\n      wrap(' = ', defaultValue) +\n      wrap(' ', join(directives, ' ')),\n  },\n  SelectionSet: {\n    leave: ({ selections }) => block(selections),\n  },\n  Field: {\n    leave({ alias, name, arguments: args, directives, selectionSet }) {\n      const prefix = wrap('', alias, ': ') + name;\n      let argsLine = prefix + wrap('(', join(args, ', '), ')');\n\n      if (argsLine.length > MAX_LINE_LENGTH) {\n        argsLine = prefix + wrap('(\\n', indent(join(args, '\\n')), '\\n)');\n      }\n\n      return join([argsLine, join(directives, ' '), selectionSet], ' ');\n    },\n  },\n  Argument: {\n    leave: ({ name, value }) => name + ': ' + value,\n  },\n  // Fragments\n  FragmentSpread: {\n    leave: ({ name, directives }) =>\n      '...' + name + wrap(' ', join(directives, ' ')),\n  },\n  InlineFragment: {\n    leave: ({ typeCondition, directives, selectionSet }) =>\n      join(\n        [\n          '...',\n          wrap('on ', typeCondition),\n          join(directives, ' '),\n          selectionSet,\n        ],\n        ' ',\n      ),\n  },\n  FragmentDefinition: {\n    leave: (\n      { name, typeCondition, variableDefinitions, directives, selectionSet }, // Note: fragment variable definitions are experimental and may be changed\n    ) =>\n      // or removed in the future.\n      `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` +\n      `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` +\n      selectionSet,\n  },\n  // Value\n  IntValue: {\n    leave: ({ value }) => value,\n  },\n  FloatValue: {\n    leave: ({ value }) => value,\n  },\n  StringValue: {\n    leave: ({ value, block: isBlockString }) =>\n      isBlockString ? printBlockString(value) : printString(value),\n  },\n  BooleanValue: {\n    leave: ({ value }) => (value ? 'true' : 'false'),\n  },\n  NullValue: {\n    leave: () => 'null',\n  },\n  EnumValue: {\n    leave: ({ value }) => value,\n  },\n  ListValue: {\n    leave: ({ values }) => '[' + join(values, ', ') + ']',\n  },\n  ObjectValue: {\n    leave: ({ fields }) => '{' + join(fields, ', ') + '}',\n  },\n  ObjectField: {\n    leave: ({ name, value }) => name + ': ' + value,\n  },\n  // Directive\n  Directive: {\n    leave: ({ name, arguments: args }) =>\n      '@' + name + wrap('(', join(args, ', '), ')'),\n  },\n  // Type\n  NamedType: {\n    leave: ({ name }) => name,\n  },\n  ListType: {\n    leave: ({ type }) => '[' + type + ']',\n  },\n  NonNullType: {\n    leave: ({ type }) => type + '!',\n  },\n  // Type System Definitions\n  SchemaDefinition: {\n    leave: ({ description, directives, operationTypes }) =>\n      wrap('', description, '\\n') +\n      join(['schema', join(directives, ' '), block(operationTypes)], ' '),\n  },\n  OperationTypeDefinition: {\n    leave: ({ operation, type }) => operation + ': ' + type,\n  },\n  ScalarTypeDefinition: {\n    leave: ({ description, name, directives }) =>\n      wrap('', description, '\\n') +\n      join(['scalar', name, join(directives, ' ')], ' '),\n  },\n  ObjectTypeDefinition: {\n    leave: ({ description, name, interfaces, directives, fields }) =>\n      wrap('', description, '\\n') +\n      join(\n        [\n          'type',\n          name,\n          wrap('implements ', join(interfaces, ' & ')),\n          join(directives, ' '),\n          block(fields),\n        ],\n        ' ',\n      ),\n  },\n  FieldDefinition: {\n    leave: ({ description, name, arguments: args, type, directives }) =>\n      wrap('', description, '\\n') +\n      name +\n      (hasMultilineItems(args)\n        ? wrap('(\\n', indent(join(args, '\\n')), '\\n)')\n        : wrap('(', join(args, ', '), ')')) +\n      ': ' +\n      type +\n      wrap(' ', join(directives, ' ')),\n  },\n  InputValueDefinition: {\n    leave: ({ description, name, type, defaultValue, directives }) =>\n      wrap('', description, '\\n') +\n      join(\n        [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')],\n        ' ',\n      ),\n  },\n  InterfaceTypeDefinition: {\n    leave: ({ description, name, interfaces, directives, fields }) =>\n      wrap('', description, '\\n') +\n      join(\n        [\n          'interface',\n          name,\n          wrap('implements ', join(interfaces, ' & ')),\n          join(directives, ' '),\n          block(fields),\n        ],\n        ' ',\n      ),\n  },\n  UnionTypeDefinition: {\n    leave: ({ description, name, directives, types }) =>\n      wrap('', description, '\\n') +\n      join(\n        ['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))],\n        ' ',\n      ),\n  },\n  EnumTypeDefinition: {\n    leave: ({ description, name, directives, values }) =>\n      wrap('', description, '\\n') +\n      join(['enum', name, join(directives, ' '), block(values)], ' '),\n  },\n  EnumValueDefinition: {\n    leave: ({ description, name, directives }) =>\n      wrap('', description, '\\n') + join([name, join(directives, ' ')], ' '),\n  },\n  InputObjectTypeDefinition: {\n    leave: ({ description, name, directives, fields }) =>\n      wrap('', description, '\\n') +\n      join(['input', name, join(directives, ' '), block(fields)], ' '),\n  },\n  DirectiveDefinition: {\n    leave: ({ description, name, arguments: args, repeatable, locations }) =>\n      wrap('', description, '\\n') +\n      'directive @' +\n      name +\n      (hasMultilineItems(args)\n        ? wrap('(\\n', indent(join(args, '\\n')), '\\n)')\n        : wrap('(', join(args, ', '), ')')) +\n      (repeatable ? ' repeatable' : '') +\n      ' on ' +\n      join(locations, ' | '),\n  },\n  SchemaExtension: {\n    leave: ({ directives, operationTypes }) =>\n      join(\n        ['extend schema', join(directives, ' '), block(operationTypes)],\n        ' ',\n      ),\n  },\n  ScalarTypeExtension: {\n    leave: ({ name, directives }) =>\n      join(['extend scalar', name, join(directives, ' ')], ' '),\n  },\n  ObjectTypeExtension: {\n    leave: ({ name, interfaces, directives, fields }) =>\n      join(\n        [\n          'extend type',\n          name,\n          wrap('implements ', join(interfaces, ' & ')),\n          join(directives, ' '),\n          block(fields),\n        ],\n        ' ',\n      ),\n  },\n  InterfaceTypeExtension: {\n    leave: ({ name, interfaces, directives, fields }) =>\n      join(\n        [\n          'extend interface',\n          name,\n          wrap('implements ', join(interfaces, ' & ')),\n          join(directives, ' '),\n          block(fields),\n        ],\n        ' ',\n      ),\n  },\n  UnionTypeExtension: {\n    leave: ({ name, directives, types }) =>\n      join(\n        [\n          'extend union',\n          name,\n          join(directives, ' '),\n          wrap('= ', join(types, ' | ')),\n        ],\n        ' ',\n      ),\n  },\n  EnumTypeExtension: {\n    leave: ({ name, directives, values }) =>\n      join(['extend enum', name, join(directives, ' '), block(values)], ' '),\n  },\n  InputObjectTypeExtension: {\n    leave: ({ name, directives, fields }) =>\n      join(['extend input', name, join(directives, ' '), block(fields)], ' '),\n  },\n};\n/**\n * Given maybeArray, print an empty string if it is null or empty, otherwise\n * print all items together separated by separator if provided\n */\n\nfunction join(maybeArray, separator = '') {\n  var _maybeArray$filter$jo;\n\n  return (_maybeArray$filter$jo =\n    maybeArray === null || maybeArray === void 0\n      ? void 0\n      : maybeArray.filter((x) => x).join(separator)) !== null &&\n    _maybeArray$filter$jo !== void 0\n    ? _maybeArray$filter$jo\n    : '';\n}\n/**\n * Given array, print each item on its own line, wrapped in an indented `{ }` block.\n */\n\nfunction block(array) {\n  return wrap('{\\n', indent(join(array, '\\n')), '\\n}');\n}\n/**\n * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string.\n */\n\nfunction wrap(start, maybeString, end = '') {\n  return maybeString != null && maybeString !== ''\n    ? start + maybeString + end\n    : '';\n}\n\nfunction indent(str) {\n  return wrap('  ', str.replace(/\\n/g, '\\n  '));\n}\n\nfunction hasMultilineItems(maybeArray) {\n  var _maybeArray$some;\n\n  // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n  /* c8 ignore next */\n  return (_maybeArray$some =\n    maybeArray === null || maybeArray === void 0\n      ? void 0\n      : maybeArray.some((str) => str.includes('\\n'))) !== null &&\n    _maybeArray$some !== void 0\n    ? _maybeArray$some\n    : false;\n}\n","import { Kind } from './kinds.mjs';\nexport function isDefinitionNode(node) {\n  return (\n    isExecutableDefinitionNode(node) ||\n    isTypeSystemDefinitionNode(node) ||\n    isTypeSystemExtensionNode(node)\n  );\n}\nexport function isExecutableDefinitionNode(node) {\n  return (\n    node.kind === Kind.OPERATION_DEFINITION ||\n    node.kind === Kind.FRAGMENT_DEFINITION\n  );\n}\nexport function isSelectionNode(node) {\n  return (\n    node.kind === Kind.FIELD ||\n    node.kind === Kind.FRAGMENT_SPREAD ||\n    node.kind === Kind.INLINE_FRAGMENT\n  );\n}\nexport function isValueNode(node) {\n  return (\n    node.kind === Kind.VARIABLE ||\n    node.kind === Kind.INT ||\n    node.kind === Kind.FLOAT ||\n    node.kind === Kind.STRING ||\n    node.kind === Kind.BOOLEAN ||\n    node.kind === Kind.NULL ||\n    node.kind === Kind.ENUM ||\n    node.kind === Kind.LIST ||\n    node.kind === Kind.OBJECT\n  );\n}\nexport function isConstValueNode(node) {\n  return (\n    isValueNode(node) &&\n    (node.kind === Kind.LIST\n      ? node.values.some(isConstValueNode)\n      : node.kind === Kind.OBJECT\n      ? node.fields.some((field) => isConstValueNode(field.value))\n      : node.kind !== Kind.VARIABLE)\n  );\n}\nexport function isTypeNode(node) {\n  return (\n    node.kind === Kind.NAMED_TYPE ||\n    node.kind === Kind.LIST_TYPE ||\n    node.kind === Kind.NON_NULL_TYPE\n  );\n}\nexport function isTypeSystemDefinitionNode(node) {\n  return (\n    node.kind === Kind.SCHEMA_DEFINITION ||\n    isTypeDefinitionNode(node) ||\n    node.kind === Kind.DIRECTIVE_DEFINITION\n  );\n}\nexport function isTypeDefinitionNode(node) {\n  return (\n    node.kind === Kind.SCALAR_TYPE_DEFINITION ||\n    node.kind === Kind.OBJECT_TYPE_DEFINITION ||\n    node.kind === Kind.INTERFACE_TYPE_DEFINITION ||\n    node.kind === Kind.UNION_TYPE_DEFINITION ||\n    node.kind === Kind.ENUM_TYPE_DEFINITION ||\n    node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION\n  );\n}\nexport function isTypeSystemExtensionNode(node) {\n  return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);\n}\nexport function isTypeExtensionNode(node) {\n  return (\n    node.kind === Kind.SCALAR_TYPE_EXTENSION ||\n    node.kind === Kind.OBJECT_TYPE_EXTENSION ||\n    node.kind === Kind.INTERFACE_TYPE_EXTENSION ||\n    node.kind === Kind.UNION_TYPE_EXTENSION ||\n    node.kind === Kind.ENUM_TYPE_EXTENSION ||\n    node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION\n  );\n}\n","import { invariant } from \"../globals/index.js\";\nimport { visit, BREAK } from \"graphql\";\nexport function shouldInclude(_a, variables) {\n    var directives = _a.directives;\n    if (!directives || !directives.length) {\n        return true;\n    }\n    return getInclusionDirectives(directives).every(function (_a) {\n        var directive = _a.directive, ifArgument = _a.ifArgument;\n        var evaledValue = false;\n        if (ifArgument.value.kind === \"Variable\") {\n            evaledValue =\n                variables && variables[ifArgument.value.name.value];\n            invariant(evaledValue !== void 0, 70, directive.name.value);\n        }\n        else {\n            evaledValue = ifArgument.value.value;\n        }\n        return directive.name.value === \"skip\" ? !evaledValue : evaledValue;\n    });\n}\nexport function getDirectiveNames(root) {\n    var names = [];\n    visit(root, {\n        Directive: function (node) {\n            names.push(node.name.value);\n        },\n    });\n    return names;\n}\nexport var hasAnyDirectives = function (names, root) {\n    return hasDirectives(names, root, false);\n};\nexport var hasAllDirectives = function (names, root) {\n    return hasDirectives(names, root, true);\n};\nexport function hasDirectives(names, root, all) {\n    var nameSet = new Set(names);\n    var uniqueCount = nameSet.size;\n    visit(root, {\n        Directive: function (node) {\n            if (nameSet.delete(node.name.value) && (!all || !nameSet.size)) {\n                return BREAK;\n            }\n        },\n    });\n    // If we found all the names, nameSet will be empty. If we only care about\n    // finding some of them, the < condition is sufficient.\n    return all ? !nameSet.size : nameSet.size < uniqueCount;\n}\nexport function hasClientExports(document) {\n    return document && hasDirectives([\"client\", \"export\"], document, true);\n}\nfunction isInclusionDirective(_a) {\n    var value = _a.name.value;\n    return value === \"skip\" || value === \"include\";\n}\nexport function getInclusionDirectives(directives) {\n    var result = [];\n    if (directives && directives.length) {\n        directives.forEach(function (directive) {\n            if (!isInclusionDirective(directive))\n                return;\n            var directiveArguments = directive.arguments;\n            var directiveName = directive.name.value;\n            invariant(directiveArguments && directiveArguments.length === 1, 71, directiveName);\n            var ifArgument = directiveArguments[0];\n            invariant(ifArgument.name && ifArgument.name.value === \"if\", 72, directiveName);\n            var ifValue = ifArgument.value;\n            // means it has to be a variable value if this is a valid @skip or @include directive\n            invariant(ifValue &&\n                (ifValue.kind === \"Variable\" || ifValue.kind === \"BooleanValue\"), 73, directiveName);\n            result.push({ directive: directive, ifArgument: ifArgument });\n        });\n    }\n    return result;\n}\n//# sourceMappingURL=directives.js.map","// A [trie](https://en.wikipedia.org/wiki/Trie) data structure that holds\n// object keys weakly, yet can also hold non-object keys, unlike the\n// native `WeakMap`.\n// If no makeData function is supplied, the looked-up data will be an empty,\n// null-prototype Object.\nconst defaultMakeData = () => Object.create(null);\n// Useful for processing arguments objects as well as arrays.\nconst { forEach, slice } = Array.prototype;\nconst { hasOwnProperty } = Object.prototype;\nexport class Trie {\n    constructor(weakness = true, makeData = defaultMakeData) {\n        this.weakness = weakness;\n        this.makeData = makeData;\n    }\n    lookup() {\n        return this.lookupArray(arguments);\n    }\n    lookupArray(array) {\n        let node = this;\n        forEach.call(array, key => node = node.getChildTrie(key));\n        return hasOwnProperty.call(node, \"data\")\n            ? node.data\n            : node.data = this.makeData(slice.call(array));\n    }\n    peek() {\n        return this.peekArray(arguments);\n    }\n    peekArray(array) {\n        let node = this;\n        for (let i = 0, len = array.length; node && i < len; ++i) {\n            const map = node.mapFor(array[i], false);\n            node = map && map.get(array[i]);\n        }\n        return node && node.data;\n    }\n    remove() {\n        return this.removeArray(arguments);\n    }\n    removeArray(array) {\n        let data;\n        if (array.length) {\n            const head = array[0];\n            const map = this.mapFor(head, false);\n            const child = map && map.get(head);\n            if (child) {\n                data = child.removeArray(slice.call(array, 1));\n                if (!child.data && !child.weak && !(child.strong && child.strong.size)) {\n                    map.delete(head);\n                }\n            }\n        }\n        else {\n            data = this.data;\n            delete this.data;\n        }\n        return data;\n    }\n    getChildTrie(key) {\n        const map = this.mapFor(key, true);\n        let child = map.get(key);\n        if (!child)\n            map.set(key, child = new Trie(this.weakness, this.makeData));\n        return child;\n    }\n    mapFor(key, create) {\n        return this.weakness && isObjRef(key)\n            ? this.weak || (create ? this.weak = new WeakMap : void 0)\n            : this.strong || (create ? this.strong = new Map : void 0);\n    }\n}\nfunction isObjRef(value) {\n    switch (typeof value) {\n        case \"object\":\n            if (value === null)\n                break;\n        // Fall through to return true...\n        case \"function\":\n            return true;\n    }\n    return false;\n}\n//# sourceMappingURL=index.js.map","import { maybe } from \"../globals/index.js\";\nvar isReactNative = maybe(function () { return navigator.product; }) == \"ReactNative\";\nexport var canUseWeakMap = typeof WeakMap === \"function\" &&\n    !(isReactNative && !global.HermesInternal);\nexport var canUseWeakSet = typeof WeakSet === \"function\";\nexport var canUseSymbol = typeof Symbol === \"function\" && typeof Symbol.for === \"function\";\nexport var canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;\nexport var canUseDOM = typeof maybe(function () { return window.document.createElement; }) === \"function\";\nvar usingJSDOM = \n// Following advice found in this comment from @domenic (maintainer of jsdom):\n// https://github.com/jsdom/jsdom/issues/1537#issuecomment-229405327\n//\n// Since we control the version of Jest and jsdom used when running Apollo\n// Client tests, and that version is recent enought to include \" jsdom/x.y.z\"\n// at the end of the user agent string, I believe this case is all we need to\n// check. Testing for \"Node.js\" was recommended for backwards compatibility\n// with older version of jsdom, but we don't have that problem.\nmaybe(function () { return navigator.userAgent.indexOf(\"jsdom\") >= 0; }) || false;\n// Our tests should all continue to pass if we remove this !usingJSDOM\n// condition, thereby allowing useLayoutEffect when using jsdom. Unfortunately,\n// if we allow useLayoutEffect, then useSyncExternalStore generates many\n// warnings about useLayoutEffect doing nothing on the server. While these\n// warnings are harmless, this !usingJSDOM condition seems to be the best way to\n// prevent them (i.e. skipping useLayoutEffect when using jsdom).\nexport var canUseLayoutEffect = (canUseDOM || isReactNative) && !usingJSDOM;\n//# sourceMappingURL=canUse.js.map","export function isNonNullObject(obj) {\n    return obj !== null && typeof obj === \"object\";\n}\nexport function isPlainObject(obj) {\n    return (obj !== null &&\n        typeof obj === \"object\" &&\n        (Object.getPrototypeOf(obj) === Object.prototype ||\n            Object.getPrototypeOf(obj) === null));\n}\n//# sourceMappingURL=objects.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { invariant, newInvariantError } from \"../globals/index.js\";\n/**\n * Returns a query document which adds a single query operation that only\n * spreads the target fragment inside of it.\n *\n * So for example a document of:\n *\n * ```graphql\n * fragment foo on Foo { a b c }\n * ```\n *\n * Turns into:\n *\n * ```graphql\n * { ...foo }\n *\n * fragment foo on Foo { a b c }\n * ```\n *\n * The target fragment will either be the only fragment in the document, or a\n * fragment specified by the provided `fragmentName`. If there is more than one\n * fragment, but a `fragmentName` was not defined then an error will be thrown.\n */\nexport function getFragmentQueryDocument(document, fragmentName) {\n    var actualFragmentName = fragmentName;\n    // Build an array of all our fragment definitions that will be used for\n    // validations. We also do some validations on the other definitions in the\n    // document while building this list.\n    var fragments = [];\n    document.definitions.forEach(function (definition) {\n        // Throw an error if we encounter an operation definition because we will\n        // define our own operation definition later on.\n        if (definition.kind === \"OperationDefinition\") {\n            throw newInvariantError(\n                74,\n                definition.operation,\n                definition.name ? \" named '\".concat(definition.name.value, \"'\") : \"\"\n            );\n        }\n        // Add our definition to the fragments array if it is a fragment\n        // definition.\n        if (definition.kind === \"FragmentDefinition\") {\n            fragments.push(definition);\n        }\n    });\n    // If the user did not give us a fragment name then let us try to get a\n    // name from a single fragment in the definition.\n    if (typeof actualFragmentName === \"undefined\") {\n        invariant(fragments.length === 1, 75, fragments.length);\n        actualFragmentName = fragments[0].name.value;\n    }\n    // Generate a query document with an operation that simply spreads the\n    // fragment inside of it.\n    var query = __assign(__assign({}, document), { definitions: __spreadArray([\n            {\n                kind: \"OperationDefinition\",\n                // OperationTypeNode is an enum\n                operation: \"query\",\n                selectionSet: {\n                    kind: \"SelectionSet\",\n                    selections: [\n                        {\n                            kind: \"FragmentSpread\",\n                            name: {\n                                kind: \"Name\",\n                                value: actualFragmentName,\n                            },\n                        },\n                    ],\n                },\n            }\n        ], document.definitions, true) });\n    return query;\n}\n// Utility function that takes a list of fragment definitions and makes a hash out of them\n// that maps the name of the fragment to the fragment definition.\nexport function createFragmentMap(fragments) {\n    if (fragments === void 0) { fragments = []; }\n    var symTable = {};\n    fragments.forEach(function (fragment) {\n        symTable[fragment.name.value] = fragment;\n    });\n    return symTable;\n}\nexport function getFragmentFromSelection(selection, fragmentMap) {\n    switch (selection.kind) {\n        case \"InlineFragment\":\n            return selection;\n        case \"FragmentSpread\": {\n            var fragmentName = selection.name.value;\n            if (typeof fragmentMap === \"function\") {\n                return fragmentMap(fragmentName);\n            }\n            var fragment = fragmentMap && fragmentMap[fragmentName];\n            invariant(fragment, 76, fragmentName);\n            return fragment || null;\n        }\n        default:\n            return null;\n    }\n}\n//# sourceMappingURL=fragments.js.map","function defaultDispose() { }\nexport class StrongCache {\n    constructor(max = Infinity, dispose = defaultDispose) {\n        this.max = max;\n        this.dispose = dispose;\n        this.map = new Map();\n        this.newest = null;\n        this.oldest = null;\n    }\n    has(key) {\n        return this.map.has(key);\n    }\n    get(key) {\n        const node = this.getNode(key);\n        return node && node.value;\n    }\n    get size() {\n        return this.map.size;\n    }\n    getNode(key) {\n        const node = this.map.get(key);\n        if (node && node !== this.newest) {\n            const { older, newer } = node;\n            if (newer) {\n                newer.older = older;\n            }\n            if (older) {\n                older.newer = newer;\n            }\n            node.older = this.newest;\n            node.older.newer = node;\n            node.newer = null;\n            this.newest = node;\n            if (node === this.oldest) {\n                this.oldest = newer;\n            }\n        }\n        return node;\n    }\n    set(key, value) {\n        let node = this.getNode(key);\n        if (node) {\n            return node.value = value;\n        }\n        node = {\n            key,\n            value,\n            newer: null,\n            older: this.newest\n        };\n        if (this.newest) {\n            this.newest.newer = node;\n        }\n        this.newest = node;\n        this.oldest = this.oldest || node;\n        this.map.set(key, node);\n        return node.value;\n    }\n    clean() {\n        while (this.oldest && this.map.size > this.max) {\n            this.delete(this.oldest.key);\n        }\n    }\n    delete(key) {\n        const node = this.map.get(key);\n        if (node) {\n            if (node === this.newest) {\n                this.newest = node.older;\n            }\n            if (node === this.oldest) {\n                this.oldest = node.newer;\n            }\n            if (node.newer) {\n                node.newer.older = node.older;\n            }\n            if (node.older) {\n                node.older.newer = node.newer;\n            }\n            this.map.delete(key);\n            this.dispose(node.value, key);\n            return true;\n        }\n        return false;\n    }\n}\n//# sourceMappingURL=strong.js.map","function noop() { }\nconst defaultDispose = noop;\nconst _WeakRef = typeof WeakRef !== \"undefined\"\n    ? WeakRef\n    : function (value) {\n        return { deref: () => value };\n    };\nconst _WeakMap = typeof WeakMap !== \"undefined\" ? WeakMap : Map;\nconst _FinalizationRegistry = typeof FinalizationRegistry !== \"undefined\"\n    ? FinalizationRegistry\n    : function () {\n        return {\n            register: noop,\n            unregister: noop,\n        };\n    };\nconst finalizationBatchSize = 10024;\nexport class WeakCache {\n    constructor(max = Infinity, dispose = defaultDispose) {\n        this.max = max;\n        this.dispose = dispose;\n        this.map = new _WeakMap();\n        this.newest = null;\n        this.oldest = null;\n        this.unfinalizedNodes = new Set();\n        this.finalizationScheduled = false;\n        this.size = 0;\n        this.finalize = () => {\n            const iterator = this.unfinalizedNodes.values();\n            for (let i = 0; i < finalizationBatchSize; i++) {\n                const node = iterator.next().value;\n                if (!node)\n                    break;\n                this.unfinalizedNodes.delete(node);\n                const key = node.key;\n                delete node.key;\n                node.keyRef = new _WeakRef(key);\n                this.registry.register(key, node, node);\n            }\n            if (this.unfinalizedNodes.size > 0) {\n                queueMicrotask(this.finalize);\n            }\n            else {\n                this.finalizationScheduled = false;\n            }\n        };\n        this.registry = new _FinalizationRegistry(this.deleteNode.bind(this));\n    }\n    has(key) {\n        return this.map.has(key);\n    }\n    get(key) {\n        const node = this.getNode(key);\n        return node && node.value;\n    }\n    getNode(key) {\n        const node = this.map.get(key);\n        if (node && node !== this.newest) {\n            const { older, newer } = node;\n            if (newer) {\n                newer.older = older;\n            }\n            if (older) {\n                older.newer = newer;\n            }\n            node.older = this.newest;\n            node.older.newer = node;\n            node.newer = null;\n            this.newest = node;\n            if (node === this.oldest) {\n                this.oldest = newer;\n            }\n        }\n        return node;\n    }\n    set(key, value) {\n        let node = this.getNode(key);\n        if (node) {\n            return (node.value = value);\n        }\n        node = {\n            key,\n            value,\n            newer: null,\n            older: this.newest,\n        };\n        if (this.newest) {\n            this.newest.newer = node;\n        }\n        this.newest = node;\n        this.oldest = this.oldest || node;\n        this.scheduleFinalization(node);\n        this.map.set(key, node);\n        this.size++;\n        return node.value;\n    }\n    clean() {\n        while (this.oldest && this.size > this.max) {\n            this.deleteNode(this.oldest);\n        }\n    }\n    deleteNode(node) {\n        if (node === this.newest) {\n            this.newest = node.older;\n        }\n        if (node === this.oldest) {\n            this.oldest = node.newer;\n        }\n        if (node.newer) {\n            node.newer.older = node.older;\n        }\n        if (node.older) {\n            node.older.newer = node.newer;\n        }\n        this.size--;\n        const key = node.key || (node.keyRef && node.keyRef.deref());\n        this.dispose(node.value, key);\n        if (!node.keyRef) {\n            this.unfinalizedNodes.delete(node);\n        }\n        else {\n            this.registry.unregister(node);\n        }\n        if (key)\n            this.map.delete(key);\n    }\n    delete(key) {\n        const node = this.map.get(key);\n        if (node) {\n            this.deleteNode(node);\n            return true;\n        }\n        return false;\n    }\n    scheduleFinalization(node) {\n        this.unfinalizedNodes.add(node);\n        if (!this.finalizationScheduled) {\n            this.finalizationScheduled = true;\n            queueMicrotask(this.finalize);\n        }\n    }\n}\n//# sourceMappingURL=weak.js.map","import { WeakCache, StrongCache } from \"@wry/caches\";\nvar scheduledCleanup = new WeakSet();\nfunction schedule(cache) {\n    if (cache.size <= (cache.max || -1)) {\n        return;\n    }\n    if (!scheduledCleanup.has(cache)) {\n        scheduledCleanup.add(cache);\n        setTimeout(function () {\n            cache.clean();\n            scheduledCleanup.delete(cache);\n        }, 100);\n    }\n}\n/**\n * @internal\n * A version of WeakCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of WeakCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `WeakCache`.\n */\nexport var AutoCleanedWeakCache = function (max, dispose) {\n    /*\n    Some builds of `WeakCache` are function prototypes, some are classes.\n    This library still builds with an ES5 target, so we can't extend the\n    real classes.\n    Instead, we have to use this workaround until we switch to a newer build\n    target.\n    */\n    var cache = new WeakCache(max, dispose);\n    cache.set = function (key, value) {\n        var ret = WeakCache.prototype.set.call(this, key, value);\n        schedule(this);\n        return ret;\n    };\n    return cache;\n};\n/**\n * @internal\n * A version of StrongCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of StrongCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `StrongCache`.\n */\nexport var AutoCleanedStrongCache = function (max, dispose) {\n    /*\n    Some builds of `StrongCache` are function prototypes, some are classes.\n    This library still builds with an ES5 target, so we can't extend the\n    real classes.\n    Instead, we have to use this workaround until we switch to a newer build\n    target.\n    */\n    var cache = new StrongCache(max, dispose);\n    cache.set = function (key, value) {\n        var ret = StrongCache.prototype.set.call(this, key, value);\n        schedule(this);\n        return ret;\n    };\n    return cache;\n};\n//# sourceMappingURL=caches.js.map","import { __assign } from \"tslib\";\nimport { global } from \"../globals/index.js\";\nvar cacheSizeSymbol = Symbol.for(\"apollo.cacheSize\");\n/**\n *\n * The global cache size configuration for Apollo Client.\n *\n * @remarks\n *\n * You can directly modify this object, but any modification will\n * only have an effect on caches that are created after the modification.\n *\n * So for global caches, such as `parser`, `canonicalStringify` and `print`,\n * you might need to call `.reset` on them, which will essentially re-create them.\n *\n * Alternatively, you can set `globalThis[Symbol.for(\"apollo.cacheSize\")]` before\n * you load the Apollo Client package:\n *\n * @example\n * ```ts\n * globalThis[Symbol.for(\"apollo.cacheSize\")] = {\n *   parser: 100\n * } satisfies Partial<CacheSizes> // the `satisfies` is optional if using TypeScript\n * ```\n */\nexport var cacheSizes = __assign({}, global[cacheSizeSymbol]);\n//# sourceMappingURL=sizes.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { cacheSizes } from \"./sizes.js\";\nvar globalCaches = {};\nexport function registerGlobalCache(name, getSize) {\n    globalCaches[name] = getSize;\n}\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport var getApolloClientMemoryInternals = globalThis.__DEV__ !== false ?\n    _getApolloClientMemoryInternals\n    : undefined;\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport var getInMemoryCacheMemoryInternals = globalThis.__DEV__ !== false ?\n    _getInMemoryCacheMemoryInternals\n    : undefined;\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport var getApolloCacheMemoryInternals = globalThis.__DEV__ !== false ?\n    _getApolloCacheMemoryInternals\n    : undefined;\nfunction getCurrentCacheSizes() {\n    // `defaultCacheSizes` is a `const enum` that will be inlined during build, so we have to reconstruct it's shape here\n    var defaults = {\n        parser: 1000 /* defaultCacheSizes[\"parser\"] */,\n        canonicalStringify: 1000 /* defaultCacheSizes[\"canonicalStringify\"] */,\n        print: 2000 /* defaultCacheSizes[\"print\"] */,\n        \"documentTransform.cache\": 2000 /* defaultCacheSizes[\"documentTransform.cache\"] */,\n        \"queryManager.getDocumentInfo\": 2000 /* defaultCacheSizes[\"queryManager.getDocumentInfo\"] */,\n        \"PersistedQueryLink.persistedQueryHashes\": 2000 /* defaultCacheSizes[\"PersistedQueryLink.persistedQueryHashes\"] */,\n        \"fragmentRegistry.transform\": 2000 /* defaultCacheSizes[\"fragmentRegistry.transform\"] */,\n        \"fragmentRegistry.lookup\": 1000 /* defaultCacheSizes[\"fragmentRegistry.lookup\"] */,\n        \"fragmentRegistry.findFragmentSpreads\": 4000 /* defaultCacheSizes[\"fragmentRegistry.findFragmentSpreads\"] */,\n        \"cache.fragmentQueryDocuments\": 1000 /* defaultCacheSizes[\"cache.fragmentQueryDocuments\"] */,\n        \"removeTypenameFromVariables.getVariableDefinitions\": 2000 /* defaultCacheSizes[\"removeTypenameFromVariables.getVariableDefinitions\"] */,\n        \"inMemoryCache.maybeBroadcastWatch\": 5000 /* defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] */,\n        \"inMemoryCache.executeSelectionSet\": 50000 /* defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"] */,\n        \"inMemoryCache.executeSubSelectedArray\": 10000 /* defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"] */,\n    };\n    return Object.fromEntries(Object.entries(defaults).map(function (_a) {\n        var k = _a[0], v = _a[1];\n        return [\n            k,\n            cacheSizes[k] || v,\n        ];\n    }));\n}\nfunction _getApolloClientMemoryInternals() {\n    var _a, _b, _c, _d, _e;\n    if (!(globalThis.__DEV__ !== false))\n        throw new Error(\"only supported in development mode\");\n    return {\n        limits: getCurrentCacheSizes(),\n        sizes: __assign({ print: (_a = globalCaches.print) === null || _a === void 0 ? void 0 : _a.call(globalCaches), parser: (_b = globalCaches.parser) === null || _b === void 0 ? void 0 : _b.call(globalCaches), canonicalStringify: (_c = globalCaches.canonicalStringify) === null || _c === void 0 ? void 0 : _c.call(globalCaches), links: linkInfo(this.link), queryManager: {\n                getDocumentInfo: this[\"queryManager\"][\"transformCache\"].size,\n                documentTransforms: transformInfo(this[\"queryManager\"].documentTransform),\n            } }, (_e = (_d = this.cache).getMemoryInternals) === null || _e === void 0 ? void 0 : _e.call(_d)),\n    };\n}\nfunction _getApolloCacheMemoryInternals() {\n    return {\n        cache: {\n            fragmentQueryDocuments: getWrapperInformation(this[\"getFragmentDoc\"]),\n        },\n    };\n}\nfunction _getInMemoryCacheMemoryInternals() {\n    var fragments = this.config.fragments;\n    return __assign(__assign({}, _getApolloCacheMemoryInternals.apply(this)), { addTypenameDocumentTransform: transformInfo(this[\"addTypenameTransform\"]), inMemoryCache: {\n            executeSelectionSet: getWrapperInformation(this[\"storeReader\"][\"executeSelectionSet\"]),\n            executeSubSelectedArray: getWrapperInformation(this[\"storeReader\"][\"executeSubSelectedArray\"]),\n            maybeBroadcastWatch: getWrapperInformation(this[\"maybeBroadcastWatch\"]),\n        }, fragmentRegistry: {\n            findFragmentSpreads: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.findFragmentSpreads),\n            lookup: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.lookup),\n            transform: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.transform),\n        } });\n}\nfunction isWrapper(f) {\n    return !!f && \"dirtyKey\" in f;\n}\nfunction getWrapperInformation(f) {\n    return isWrapper(f) ? f.size : undefined;\n}\nfunction isDefined(value) {\n    return value != null;\n}\nfunction transformInfo(transform) {\n    return recurseTransformInfo(transform).map(function (cache) { return ({ cache: cache }); });\n}\nfunction recurseTransformInfo(transform) {\n    return transform ?\n        __spreadArray(__spreadArray([\n            getWrapperInformation(transform === null || transform === void 0 ? void 0 : transform[\"performWork\"])\n        ], recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform[\"left\"]), true), recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform[\"right\"]), true).filter(isDefined)\n        : [];\n}\nfunction linkInfo(link) {\n    var _a;\n    return link ?\n        __spreadArray(__spreadArray([\n            (_a = link === null || link === void 0 ? void 0 : link.getMemoryInternals) === null || _a === void 0 ? void 0 : _a.call(link)\n        ], linkInfo(link === null || link === void 0 ? void 0 : link.left), true), linkInfo(link === null || link === void 0 ? void 0 : link.right), true).filter(isDefined)\n        : [];\n}\n//# sourceMappingURL=getMemoryInternals.js.map","import { AutoCleanedStrongCache, cacheSizes, } from \"../../utilities/caching/index.js\";\nimport { registerGlobalCache } from \"../caching/getMemoryInternals.js\";\n/**\n * Like JSON.stringify, but with object keys always sorted in the same order.\n *\n * To achieve performant sorting, this function uses a Map from JSON-serialized\n * arrays of keys (in any order) to sorted arrays of the same keys, with a\n * single sorted array reference shared by all permutations of the keys.\n *\n * As a drawback, this function will add a little bit more memory for every\n * object encountered that has different (more, less, a different order of) keys\n * than in the past.\n *\n * In a typical application, this extra memory usage should not play a\n * significant role, as `canonicalStringify` will be called for only a limited\n * number of object shapes, and the cache will not grow beyond a certain point.\n * But in some edge cases, this could be a problem, so we provide\n * canonicalStringify.reset() as a way of clearing the cache.\n * */\nexport var canonicalStringify = Object.assign(function canonicalStringify(value) {\n    return JSON.stringify(value, stableObjectReplacer);\n}, {\n    reset: function () {\n        // Clearing the sortingMap will reclaim all cached memory, without\n        // affecting the logical results of canonicalStringify, but potentially\n        // sacrificing performance until the cache is refilled.\n        sortingMap = new AutoCleanedStrongCache(cacheSizes.canonicalStringify || 1000 /* defaultCacheSizes.canonicalStringify */);\n    },\n});\nif (globalThis.__DEV__ !== false) {\n    registerGlobalCache(\"canonicalStringify\", function () { return sortingMap.size; });\n}\n// Values are JSON-serialized arrays of object keys (in any order), and values\n// are sorted arrays of the same keys.\nvar sortingMap;\ncanonicalStringify.reset();\n// The JSON.stringify function takes an optional second argument called a\n// replacer function. This function is called for each key-value pair in the\n// object being stringified, and its return value is used instead of the\n// original value. If the replacer function returns a new value, that value is\n// stringified as JSON instead of the original value of the property.\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter\nfunction stableObjectReplacer(key, value) {\n    if (value && typeof value === \"object\") {\n        var proto = Object.getPrototypeOf(value);\n        // We don't want to mess with objects that are not \"plain\" objects, which\n        // means their prototype is either Object.prototype or null. This check also\n        // prevents needlessly rearranging the indices of arrays.\n        if (proto === Object.prototype || proto === null) {\n            var keys = Object.keys(value);\n            // If keys is already sorted, let JSON.stringify serialize the original\n            // value instead of creating a new object with keys in the same order.\n            if (keys.every(everyKeyInOrder))\n                return value;\n            var unsortedKey = JSON.stringify(keys);\n            var sortedKeys = sortingMap.get(unsortedKey);\n            if (!sortedKeys) {\n                keys.sort();\n                var sortedKey = JSON.stringify(keys);\n                // Checking for sortedKey in the sortingMap allows us to share the same\n                // sorted array reference for all permutations of the same set of keys.\n                sortedKeys = sortingMap.get(sortedKey) || keys;\n                sortingMap.set(unsortedKey, sortedKeys);\n                sortingMap.set(sortedKey, sortedKeys);\n            }\n            var sortedObject_1 = Object.create(proto);\n            // Reassigning the keys in sorted order will cause JSON.stringify to\n            // serialize them in sorted order.\n            sortedKeys.forEach(function (key) {\n                sortedObject_1[key] = value[key];\n            });\n            return sortedObject_1;\n        }\n    }\n    return value;\n}\n// Since everything that happens in stableObjectReplacer benefits from being as\n// efficient as possible, we use a static function as the callback for\n// keys.every in order to test if the provided keys are already sorted without\n// allocating extra memory for a callback.\nfunction everyKeyInOrder(key, i, keys) {\n    return i === 0 || keys[i - 1] <= key;\n}\n//# sourceMappingURL=canonicalStringify.js.map","import { newInvariantError } from \"../globals/index.js\";\nimport { isNonNullObject } from \"../common/objects.js\";\nimport { getFragmentFromSelection } from \"./fragments.js\";\nimport { canonicalStringify } from \"../common/canonicalStringify.js\";\nexport function makeReference(id) {\n    return { __ref: String(id) };\n}\nexport function isReference(obj) {\n    return Boolean(obj && typeof obj === \"object\" && typeof obj.__ref === \"string\");\n}\nexport function isDocumentNode(value) {\n    return (isNonNullObject(value) &&\n        value.kind === \"Document\" &&\n        Array.isArray(value.definitions));\n}\nfunction isStringValue(value) {\n    return value.kind === \"StringValue\";\n}\nfunction isBooleanValue(value) {\n    return value.kind === \"BooleanValue\";\n}\nfunction isIntValue(value) {\n    return value.kind === \"IntValue\";\n}\nfunction isFloatValue(value) {\n    return value.kind === \"FloatValue\";\n}\nfunction isVariable(value) {\n    return value.kind === \"Variable\";\n}\nfunction isObjectValue(value) {\n    return value.kind === \"ObjectValue\";\n}\nfunction isListValue(value) {\n    return value.kind === \"ListValue\";\n}\nfunction isEnumValue(value) {\n    return value.kind === \"EnumValue\";\n}\nfunction isNullValue(value) {\n    return value.kind === \"NullValue\";\n}\nexport function valueToObjectRepresentation(argObj, name, value, variables) {\n    if (isIntValue(value) || isFloatValue(value)) {\n        argObj[name.value] = Number(value.value);\n    }\n    else if (isBooleanValue(value) || isStringValue(value)) {\n        argObj[name.value] = value.value;\n    }\n    else if (isObjectValue(value)) {\n        var nestedArgObj_1 = {};\n        value.fields.map(function (obj) {\n            return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables);\n        });\n        argObj[name.value] = nestedArgObj_1;\n    }\n    else if (isVariable(value)) {\n        var variableValue = (variables || {})[value.name.value];\n        argObj[name.value] = variableValue;\n    }\n    else if (isListValue(value)) {\n        argObj[name.value] = value.values.map(function (listValue) {\n            var nestedArgArrayObj = {};\n            valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);\n            return nestedArgArrayObj[name.value];\n        });\n    }\n    else if (isEnumValue(value)) {\n        argObj[name.value] = value.value;\n    }\n    else if (isNullValue(value)) {\n        argObj[name.value] = null;\n    }\n    else {\n        throw newInvariantError(85, name.value, value.kind);\n    }\n}\nexport function storeKeyNameFromField(field, variables) {\n    var directivesObj = null;\n    if (field.directives) {\n        directivesObj = {};\n        field.directives.forEach(function (directive) {\n            directivesObj[directive.name.value] = {};\n            if (directive.arguments) {\n                directive.arguments.forEach(function (_a) {\n                    var name = _a.name, value = _a.value;\n                    return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables);\n                });\n            }\n        });\n    }\n    var argObj = null;\n    if (field.arguments && field.arguments.length) {\n        argObj = {};\n        field.arguments.forEach(function (_a) {\n            var name = _a.name, value = _a.value;\n            return valueToObjectRepresentation(argObj, name, value, variables);\n        });\n    }\n    return getStoreKeyName(field.name.value, argObj, directivesObj);\n}\nvar KNOWN_DIRECTIVES = [\n    \"connection\",\n    \"include\",\n    \"skip\",\n    \"client\",\n    \"rest\",\n    \"export\",\n    \"nonreactive\",\n];\n// Default stable JSON.stringify implementation used by getStoreKeyName. Can be\n// updated/replaced with something better by calling\n// getStoreKeyName.setStringify(newStringifyFunction).\nvar storeKeyNameStringify = canonicalStringify;\nexport var getStoreKeyName = Object.assign(function (fieldName, args, directives) {\n    if (args &&\n        directives &&\n        directives[\"connection\"] &&\n        directives[\"connection\"][\"key\"]) {\n        if (directives[\"connection\"][\"filter\"] &&\n            directives[\"connection\"][\"filter\"].length > 0) {\n            var filterKeys = directives[\"connection\"][\"filter\"] ?\n                directives[\"connection\"][\"filter\"]\n                : [];\n            filterKeys.sort();\n            var filteredArgs_1 = {};\n            filterKeys.forEach(function (key) {\n                filteredArgs_1[key] = args[key];\n            });\n            return \"\".concat(directives[\"connection\"][\"key\"], \"(\").concat(storeKeyNameStringify(filteredArgs_1), \")\");\n        }\n        else {\n            return directives[\"connection\"][\"key\"];\n        }\n    }\n    var completeFieldName = fieldName;\n    if (args) {\n        // We can't use `JSON.stringify` here since it's non-deterministic,\n        // and can lead to different store key names being created even though\n        // the `args` object used during creation has the same properties/values.\n        var stringifiedArgs = storeKeyNameStringify(args);\n        completeFieldName += \"(\".concat(stringifiedArgs, \")\");\n    }\n    if (directives) {\n        Object.keys(directives).forEach(function (key) {\n            if (KNOWN_DIRECTIVES.indexOf(key) !== -1)\n                return;\n            if (directives[key] && Object.keys(directives[key]).length) {\n                completeFieldName += \"@\".concat(key, \"(\").concat(storeKeyNameStringify(directives[key]), \")\");\n            }\n            else {\n                completeFieldName += \"@\".concat(key);\n            }\n        });\n    }\n    return completeFieldName;\n}, {\n    setStringify: function (s) {\n        var previous = storeKeyNameStringify;\n        storeKeyNameStringify = s;\n        return previous;\n    },\n});\nexport function argumentsObjectFromField(field, variables) {\n    if (field.arguments && field.arguments.length) {\n        var argObj_1 = {};\n        field.arguments.forEach(function (_a) {\n            var name = _a.name, value = _a.value;\n            return valueToObjectRepresentation(argObj_1, name, value, variables);\n        });\n        return argObj_1;\n    }\n    return null;\n}\nexport function resultKeyNameFromField(field) {\n    return field.alias ? field.alias.value : field.name.value;\n}\nexport function getTypenameFromResult(result, selectionSet, fragmentMap) {\n    var fragments;\n    for (var _i = 0, _a = selectionSet.selections; _i < _a.length; _i++) {\n        var selection = _a[_i];\n        if (isField(selection)) {\n            if (selection.name.value === \"__typename\") {\n                return result[resultKeyNameFromField(selection)];\n            }\n        }\n        else if (fragments) {\n            fragments.push(selection);\n        }\n        else {\n            fragments = [selection];\n        }\n    }\n    if (typeof result.__typename === \"string\") {\n        return result.__typename;\n    }\n    if (fragments) {\n        for (var _b = 0, fragments_1 = fragments; _b < fragments_1.length; _b++) {\n            var selection = fragments_1[_b];\n            var typename = getTypenameFromResult(result, getFragmentFromSelection(selection, fragmentMap).selectionSet, fragmentMap);\n            if (typeof typename === \"string\") {\n                return typename;\n            }\n        }\n    }\n}\nexport function isField(selection) {\n    return selection.kind === \"Field\";\n}\nexport function isInlineFragment(selection) {\n    return selection.kind === \"InlineFragment\";\n}\n//# sourceMappingURL=storeUtils.js.map","import { invariant, newInvariantError } from \"../globals/index.js\";\nimport { valueToObjectRepresentation } from \"./storeUtils.js\";\n// Checks the document for errors and throws an exception if there is an error.\nexport function checkDocument(doc) {\n    invariant(doc && doc.kind === \"Document\", 77);\n    var operations = doc.definitions\n        .filter(function (d) { return d.kind !== \"FragmentDefinition\"; })\n        .map(function (definition) {\n        if (definition.kind !== \"OperationDefinition\") {\n            throw newInvariantError(78, definition.kind);\n        }\n        return definition;\n    });\n    invariant(operations.length <= 1, 79, operations.length);\n    return doc;\n}\nexport function getOperationDefinition(doc) {\n    checkDocument(doc);\n    return doc.definitions.filter(function (definition) {\n        return definition.kind === \"OperationDefinition\";\n    })[0];\n}\nexport function getOperationName(doc) {\n    return (doc.definitions\n        .filter(function (definition) {\n        return definition.kind === \"OperationDefinition\" && !!definition.name;\n    })\n        .map(function (x) { return x.name.value; })[0] || null);\n}\n// Returns the FragmentDefinitions from a particular document as an array\nexport function getFragmentDefinitions(doc) {\n    return doc.definitions.filter(function (definition) {\n        return definition.kind === \"FragmentDefinition\";\n    });\n}\nexport function getQueryDefinition(doc) {\n    var queryDef = getOperationDefinition(doc);\n    invariant(queryDef && queryDef.operation === \"query\", 80);\n    return queryDef;\n}\nexport function getFragmentDefinition(doc) {\n    invariant(doc.kind === \"Document\", 81);\n    invariant(doc.definitions.length <= 1, 82);\n    var fragmentDef = doc.definitions[0];\n    invariant(fragmentDef.kind === \"FragmentDefinition\", 83);\n    return fragmentDef;\n}\n/**\n * Returns the first operation definition found in this document.\n * If no operation definition is found, the first fragment definition will be returned.\n * If no definitions are found, an error will be thrown.\n */\nexport function getMainDefinition(queryDoc) {\n    checkDocument(queryDoc);\n    var fragmentDefinition;\n    for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {\n        var definition = _a[_i];\n        if (definition.kind === \"OperationDefinition\") {\n            var operation = definition.operation;\n            if (operation === \"query\" ||\n                operation === \"mutation\" ||\n                operation === \"subscription\") {\n                return definition;\n            }\n        }\n        if (definition.kind === \"FragmentDefinition\" && !fragmentDefinition) {\n            // we do this because we want to allow multiple fragment definitions\n            // to precede an operation definition.\n            fragmentDefinition = definition;\n        }\n    }\n    if (fragmentDefinition) {\n        return fragmentDefinition;\n    }\n    throw newInvariantError(84);\n}\nexport function getDefaultValues(definition) {\n    var defaultValues = Object.create(null);\n    var defs = definition && definition.variableDefinitions;\n    if (defs && defs.length) {\n        defs.forEach(function (def) {\n            if (def.defaultValue) {\n                valueToObjectRepresentation(defaultValues, def.variable.name, def.defaultValue);\n            }\n        });\n    }\n    return defaultValues;\n}\n//# sourceMappingURL=getFromAST.js.map","// A [trie](https://en.wikipedia.org/wiki/Trie) data structure that holds\n// object keys weakly, yet can also hold non-object keys, unlike the\n// native `WeakMap`.\n// If no makeData function is supplied, the looked-up data will be an empty,\n// null-prototype Object.\nconst defaultMakeData = () => Object.create(null);\n// Useful for processing arguments objects as well as arrays.\nconst { forEach, slice } = Array.prototype;\nconst { hasOwnProperty } = Object.prototype;\nexport class Trie {\n    constructor(weakness = true, makeData = defaultMakeData) {\n        this.weakness = weakness;\n        this.makeData = makeData;\n    }\n    lookup(...array) {\n        return this.lookupArray(array);\n    }\n    lookupArray(array) {\n        let node = this;\n        forEach.call(array, key => node = node.getChildTrie(key));\n        return hasOwnProperty.call(node, \"data\")\n            ? node.data\n            : node.data = this.makeData(slice.call(array));\n    }\n    peek(...array) {\n        return this.peekArray(array);\n    }\n    peekArray(array) {\n        let node = this;\n        for (let i = 0, len = array.length; node && i < len; ++i) {\n            const map = this.weakness && isObjRef(array[i]) ? node.weak : node.strong;\n            node = map && map.get(array[i]);\n        }\n        return node && node.data;\n    }\n    getChildTrie(key) {\n        const map = this.weakness && isObjRef(key)\n            ? this.weak || (this.weak = new WeakMap())\n            : this.strong || (this.strong = new Map());\n        let child = map.get(key);\n        if (!child)\n            map.set(key, child = new Trie(this.weakness, this.makeData));\n        return child;\n    }\n}\nfunction isObjRef(value) {\n    switch (typeof value) {\n        case \"object\":\n            if (value === null)\n                break;\n        // Fall through to return true...\n        case \"function\":\n            return true;\n    }\n    return false;\n}\n//# sourceMappingURL=index.js.map","// This currentContext variable will only be used if the makeSlotClass\n// function is called, which happens only if this is the first copy of the\n// @wry/context package to be imported.\nlet currentContext = null;\n// This unique internal object is used to denote the absence of a value\n// for a given Slot, and is never exposed to outside code.\nconst MISSING_VALUE = {};\nlet idCounter = 1;\n// Although we can't do anything about the cost of duplicated code from\n// accidentally bundling multiple copies of the @wry/context package, we can\n// avoid creating the Slot class more than once using makeSlotClass.\nconst makeSlotClass = () => class Slot {\n    constructor() {\n        // If you have a Slot object, you can find out its slot.id, but you cannot\n        // guess the slot.id of a Slot you don't have access to, thanks to the\n        // randomized suffix.\n        this.id = [\n            \"slot\",\n            idCounter++,\n            Date.now(),\n            Math.random().toString(36).slice(2),\n        ].join(\":\");\n    }\n    hasValue() {\n        for (let context = currentContext; context; context = context.parent) {\n            // We use the Slot object iself as a key to its value, which means the\n            // value cannot be obtained without a reference to the Slot object.\n            if (this.id in context.slots) {\n                const value = context.slots[this.id];\n                if (value === MISSING_VALUE)\n                    break;\n                if (context !== currentContext) {\n                    // Cache the value in currentContext.slots so the next lookup will\n                    // be faster. This caching is safe because the tree of contexts and\n                    // the values of the slots are logically immutable.\n                    currentContext.slots[this.id] = value;\n                }\n                return true;\n            }\n        }\n        if (currentContext) {\n            // If a value was not found for this Slot, it's never going to be found\n            // no matter how many times we look it up, so we might as well cache\n            // the absence of the value, too.\n            currentContext.slots[this.id] = MISSING_VALUE;\n        }\n        return false;\n    }\n    getValue() {\n        if (this.hasValue()) {\n            return currentContext.slots[this.id];\n        }\n    }\n    withValue(value, callback, \n    // Given the prevalence of arrow functions, specifying arguments is likely\n    // to be much more common than specifying `this`, hence this ordering:\n    args, thisArg) {\n        const slots = {\n            __proto__: null,\n            [this.id]: value,\n        };\n        const parent = currentContext;\n        currentContext = { parent, slots };\n        try {\n            // Function.prototype.apply allows the arguments array argument to be\n            // omitted or undefined, so args! is fine here.\n            return callback.apply(thisArg, args);\n        }\n        finally {\n            currentContext = parent;\n        }\n    }\n    // Capture the current context and wrap a callback function so that it\n    // reestablishes the captured context when called.\n    static bind(callback) {\n        const context = currentContext;\n        return function () {\n            const saved = currentContext;\n            try {\n                currentContext = context;\n                return callback.apply(this, arguments);\n            }\n            finally {\n                currentContext = saved;\n            }\n        };\n    }\n    // Immediately run a callback function without any captured context.\n    static noContext(callback, \n    // Given the prevalence of arrow functions, specifying arguments is likely\n    // to be much more common than specifying `this`, hence this ordering:\n    args, thisArg) {\n        if (currentContext) {\n            const saved = currentContext;\n            try {\n                currentContext = null;\n                // Function.prototype.apply allows the arguments array argument to be\n                // omitted or undefined, so args! is fine here.\n                return callback.apply(thisArg, args);\n            }\n            finally {\n                currentContext = saved;\n            }\n        }\n        else {\n            return callback.apply(thisArg, args);\n        }\n    }\n};\nfunction maybe(fn) {\n    try {\n        return fn();\n    }\n    catch (ignored) { }\n}\n// We store a single global implementation of the Slot class as a permanent\n// non-enumerable property of the globalThis object. This obfuscation does\n// nothing to prevent access to the Slot class, but at least it ensures the\n// implementation (i.e. currentContext) cannot be tampered with, and all copies\n// of the @wry/context package (hopefully just one) will share the same Slot\n// implementation. Since the first copy of the @wry/context package to be\n// imported wins, this technique imposes a steep cost for any future breaking\n// changes to the Slot class.\nconst globalKey = \"@wry/context:Slot\";\nconst host = \n// Prefer globalThis when available.\n// https://github.com/benjamn/wryware/issues/347\nmaybe(() => globalThis) ||\n    // Fall back to global, which works in Node.js and may be converted by some\n    // bundlers to the appropriate identifier (window, self, ...) depending on the\n    // bundling target. https://github.com/endojs/endo/issues/576#issuecomment-1178515224\n    maybe(() => global) ||\n    // Otherwise, use a dummy host that's local to this module. We used to fall\n    // back to using the Array constructor as a namespace, but that was flagged in\n    // https://github.com/benjamn/wryware/issues/347, and can be avoided.\n    Object.create(null);\n// Whichever globalHost we're using, make TypeScript happy about the additional\n// globalKey property.\nconst globalHost = host;\nexport const Slot = globalHost[globalKey] ||\n    // Earlier versions of this package stored the globalKey property on the Array\n    // constructor, so we check there as well, to prevent Slot class duplication.\n    Array[globalKey] ||\n    (function (Slot) {\n        try {\n            Object.defineProperty(globalHost, globalKey, {\n                value: Slot,\n                enumerable: false,\n                writable: false,\n                // When it was possible for globalHost to be the Array constructor (a\n                // legacy Slot dedup strategy), it was important for the property to be\n                // configurable:true so it could be deleted. That does not seem to be as\n                // important when globalHost is the global object, but I don't want to\n                // cause similar problems again, and configurable:true seems safest.\n                // https://github.com/endojs/endo/issues/576#issuecomment-1178274008\n                configurable: true\n            });\n        }\n        finally {\n            return Slot;\n        }\n    })(makeSlotClass());\n//# sourceMappingURL=slot.js.map","import { Slot } from \"@wry/context\";\nexport const parentEntrySlot = new Slot();\nexport function nonReactive(fn) {\n    return parentEntrySlot.withValue(void 0, fn);\n}\nexport { Slot };\nexport { bind as bindContext, noContext, setTimeout, asyncFromGen, } from \"@wry/context\";\n//# sourceMappingURL=context.js.map","export const { hasOwnProperty, } = Object.prototype;\nexport const arrayFromSet = Array.from ||\n    function (set) {\n        const array = [];\n        set.forEach(item => array.push(item));\n        return array;\n    };\nexport function maybeUnsubscribe(entryOrDep) {\n    const { unsubscribe } = entryOrDep;\n    if (typeof unsubscribe === \"function\") {\n        entryOrDep.unsubscribe = void 0;\n        unsubscribe();\n    }\n}\n//# sourceMappingURL=helpers.js.map","import { parentEntrySlot } from \"./context.js\";\nimport { maybeUnsubscribe, arrayFromSet } from \"./helpers.js\";\nconst emptySetPool = [];\nconst POOL_TARGET_SIZE = 100;\n// Since this package might be used browsers, we should avoid using the\n// Node built-in assert module.\nfunction assert(condition, optionalMessage) {\n    if (!condition) {\n        throw new Error(optionalMessage || \"assertion failure\");\n    }\n}\nfunction valueIs(a, b) {\n    const len = a.length;\n    return (\n    // Unknown values are not equal to each other.\n    len > 0 &&\n        // Both values must be ordinary (or both exceptional) to be equal.\n        len === b.length &&\n        // The underlying value or exception must be the same.\n        a[len - 1] === b[len - 1]);\n}\nfunction valueGet(value) {\n    switch (value.length) {\n        case 0: throw new Error(\"unknown value\");\n        case 1: return value[0];\n        case 2: throw value[1];\n    }\n}\nfunction valueCopy(value) {\n    return value.slice(0);\n}\nexport class Entry {\n    constructor(fn) {\n        this.fn = fn;\n        this.parents = new Set();\n        this.childValues = new Map();\n        // When this Entry has children that are dirty, this property becomes\n        // a Set containing other Entry objects, borrowed from emptySetPool.\n        // When the set becomes empty, it gets recycled back to emptySetPool.\n        this.dirtyChildren = null;\n        this.dirty = true;\n        this.recomputing = false;\n        this.value = [];\n        this.deps = null;\n        ++Entry.count;\n    }\n    peek() {\n        if (this.value.length === 1 && !mightBeDirty(this)) {\n            rememberParent(this);\n            return this.value[0];\n        }\n    }\n    // This is the most important method of the Entry API, because it\n    // determines whether the cached this.value can be returned immediately,\n    // or must be recomputed. The overall performance of the caching system\n    // depends on the truth of the following observations: (1) this.dirty is\n    // usually false, (2) this.dirtyChildren is usually null/empty, and thus\n    // (3) valueGet(this.value) is usually returned without recomputation.\n    recompute(args) {\n        assert(!this.recomputing, \"already recomputing\");\n        rememberParent(this);\n        return mightBeDirty(this)\n            ? reallyRecompute(this, args)\n            : valueGet(this.value);\n    }\n    setDirty() {\n        if (this.dirty)\n            return;\n        this.dirty = true;\n        reportDirty(this);\n        // We can go ahead and unsubscribe here, since any further dirty\n        // notifications we receive will be redundant, and unsubscribing may\n        // free up some resources, e.g. file watchers.\n        maybeUnsubscribe(this);\n    }\n    dispose() {\n        this.setDirty();\n        // Sever any dependency relationships with our own children, so those\n        // children don't retain this parent Entry in their child.parents sets,\n        // thereby preventing it from being fully garbage collected.\n        forgetChildren(this);\n        // Because this entry has been kicked out of the cache (in index.js),\n        // we've lost the ability to find out if/when this entry becomes dirty,\n        // whether that happens through a subscription, because of a direct call\n        // to entry.setDirty(), or because one of its children becomes dirty.\n        // Because of this loss of future information, we have to assume the\n        // worst (that this entry might have become dirty very soon), so we must\n        // immediately mark this entry's parents as dirty. Normally we could\n        // just call entry.setDirty() rather than calling parent.setDirty() for\n        // each parent, but that would leave this entry in parent.childValues\n        // and parent.dirtyChildren, which would prevent the child from being\n        // truly forgotten.\n        eachParent(this, (parent, child) => {\n            parent.setDirty();\n            forgetChild(parent, this);\n        });\n    }\n    forget() {\n        // The code that creates Entry objects in index.ts will replace this method\n        // with one that actually removes the Entry from the cache, which will also\n        // trigger the entry.dispose method.\n        this.dispose();\n    }\n    dependOn(dep) {\n        dep.add(this);\n        if (!this.deps) {\n            this.deps = emptySetPool.pop() || new Set();\n        }\n        this.deps.add(dep);\n    }\n    forgetDeps() {\n        if (this.deps) {\n            arrayFromSet(this.deps).forEach(dep => dep.delete(this));\n            this.deps.clear();\n            emptySetPool.push(this.deps);\n            this.deps = null;\n        }\n    }\n}\nEntry.count = 0;\nfunction rememberParent(child) {\n    const parent = parentEntrySlot.getValue();\n    if (parent) {\n        child.parents.add(parent);\n        if (!parent.childValues.has(child)) {\n            parent.childValues.set(child, []);\n        }\n        if (mightBeDirty(child)) {\n            reportDirtyChild(parent, child);\n        }\n        else {\n            reportCleanChild(parent, child);\n        }\n        return parent;\n    }\n}\nfunction reallyRecompute(entry, args) {\n    forgetChildren(entry);\n    // Set entry as the parent entry while calling recomputeNewValue(entry).\n    parentEntrySlot.withValue(entry, recomputeNewValue, [entry, args]);\n    if (maybeSubscribe(entry, args)) {\n        // If we successfully recomputed entry.value and did not fail to\n        // (re)subscribe, then this Entry is no longer explicitly dirty.\n        setClean(entry);\n    }\n    return valueGet(entry.value);\n}\nfunction recomputeNewValue(entry, args) {\n    entry.recomputing = true;\n    const { normalizeResult } = entry;\n    let oldValueCopy;\n    if (normalizeResult && entry.value.length === 1) {\n        oldValueCopy = valueCopy(entry.value);\n    }\n    // Make entry.value an empty array, representing an unknown value.\n    entry.value.length = 0;\n    try {\n        // If entry.fn succeeds, entry.value will become a normal Value.\n        entry.value[0] = entry.fn.apply(null, args);\n        // If we have a viable oldValueCopy to compare with the (successfully\n        // recomputed) new entry.value, and they are not already === identical, give\n        // normalizeResult a chance to pick/choose/reuse parts of oldValueCopy[0]\n        // and/or entry.value[0] to determine the final cached entry.value.\n        if (normalizeResult && oldValueCopy && !valueIs(oldValueCopy, entry.value)) {\n            try {\n                entry.value[0] = normalizeResult(entry.value[0], oldValueCopy[0]);\n            }\n            catch (_a) {\n                // If normalizeResult throws, just use the newer value, rather than\n                // saving the exception as entry.value[1].\n            }\n        }\n    }\n    catch (e) {\n        // If entry.fn throws, entry.value will hold that exception.\n        entry.value[1] = e;\n    }\n    // Either way, this line is always reached.\n    entry.recomputing = false;\n}\nfunction mightBeDirty(entry) {\n    return entry.dirty || !!(entry.dirtyChildren && entry.dirtyChildren.size);\n}\nfunction setClean(entry) {\n    entry.dirty = false;\n    if (mightBeDirty(entry)) {\n        // This Entry may still have dirty children, in which case we can't\n        // let our parents know we're clean just yet.\n        return;\n    }\n    reportClean(entry);\n}\nfunction reportDirty(child) {\n    eachParent(child, reportDirtyChild);\n}\nfunction reportClean(child) {\n    eachParent(child, reportCleanChild);\n}\nfunction eachParent(child, callback) {\n    const parentCount = child.parents.size;\n    if (parentCount) {\n        const parents = arrayFromSet(child.parents);\n        for (let i = 0; i < parentCount; ++i) {\n            callback(parents[i], child);\n        }\n    }\n}\n// Let a parent Entry know that one of its children may be dirty.\nfunction reportDirtyChild(parent, child) {\n    // Must have called rememberParent(child) before calling\n    // reportDirtyChild(parent, child).\n    assert(parent.childValues.has(child));\n    assert(mightBeDirty(child));\n    const parentWasClean = !mightBeDirty(parent);\n    if (!parent.dirtyChildren) {\n        parent.dirtyChildren = emptySetPool.pop() || new Set;\n    }\n    else if (parent.dirtyChildren.has(child)) {\n        // If we already know this child is dirty, then we must have already\n        // informed our own parents that we are dirty, so we can terminate\n        // the recursion early.\n        return;\n    }\n    parent.dirtyChildren.add(child);\n    // If parent was clean before, it just became (possibly) dirty (according to\n    // mightBeDirty), since we just added child to parent.dirtyChildren.\n    if (parentWasClean) {\n        reportDirty(parent);\n    }\n}\n// Let a parent Entry know that one of its children is no longer dirty.\nfunction reportCleanChild(parent, child) {\n    // Must have called rememberChild(child) before calling\n    // reportCleanChild(parent, child).\n    assert(parent.childValues.has(child));\n    assert(!mightBeDirty(child));\n    const childValue = parent.childValues.get(child);\n    if (childValue.length === 0) {\n        parent.childValues.set(child, valueCopy(child.value));\n    }\n    else if (!valueIs(childValue, child.value)) {\n        parent.setDirty();\n    }\n    removeDirtyChild(parent, child);\n    if (mightBeDirty(parent)) {\n        return;\n    }\n    reportClean(parent);\n}\nfunction removeDirtyChild(parent, child) {\n    const dc = parent.dirtyChildren;\n    if (dc) {\n        dc.delete(child);\n        if (dc.size === 0) {\n            if (emptySetPool.length < POOL_TARGET_SIZE) {\n                emptySetPool.push(dc);\n            }\n            parent.dirtyChildren = null;\n        }\n    }\n}\n// Removes all children from this entry and returns an array of the\n// removed children.\nfunction forgetChildren(parent) {\n    if (parent.childValues.size > 0) {\n        parent.childValues.forEach((_value, child) => {\n            forgetChild(parent, child);\n        });\n    }\n    // Remove this parent Entry from any sets to which it was added by the\n    // addToSet method.\n    parent.forgetDeps();\n    // After we forget all our children, this.dirtyChildren must be empty\n    // and therefore must have been reset to null.\n    assert(parent.dirtyChildren === null);\n}\nfunction forgetChild(parent, child) {\n    child.parents.delete(parent);\n    parent.childValues.delete(child);\n    removeDirtyChild(parent, child);\n}\nfunction maybeSubscribe(entry, args) {\n    if (typeof entry.subscribe === \"function\") {\n        try {\n            maybeUnsubscribe(entry); // Prevent double subscriptions.\n            entry.unsubscribe = entry.subscribe.apply(null, args);\n        }\n        catch (e) {\n            // If this Entry has a subscribe function and it threw an exception\n            // (or an unsubscribe function it previously returned now throws),\n            // return false to indicate that we were not able to subscribe (or\n            // unsubscribe), and this Entry should remain dirty.\n            entry.setDirty();\n            return false;\n        }\n    }\n    // Returning true indicates either that there was no entry.subscribe\n    // function or that it succeeded.\n    return true;\n}\n//# sourceMappingURL=entry.js.map","import { parentEntrySlot } from \"./context.js\";\nimport { hasOwnProperty, maybeUnsubscribe, arrayFromSet, } from \"./helpers.js\";\nconst EntryMethods = {\n    setDirty: true,\n    dispose: true,\n    forget: true, // Fully remove parent Entry from LRU cache and computation graph\n};\nexport function dep(options) {\n    const depsByKey = new Map();\n    const subscribe = options && options.subscribe;\n    function depend(key) {\n        const parent = parentEntrySlot.getValue();\n        if (parent) {\n            let dep = depsByKey.get(key);\n            if (!dep) {\n                depsByKey.set(key, dep = new Set);\n            }\n            parent.dependOn(dep);\n            if (typeof subscribe === \"function\") {\n                maybeUnsubscribe(dep);\n                dep.unsubscribe = subscribe(key);\n            }\n        }\n    }\n    depend.dirty = function dirty(key, entryMethodName) {\n        const dep = depsByKey.get(key);\n        if (dep) {\n            const m = (entryMethodName &&\n                hasOwnProperty.call(EntryMethods, entryMethodName)) ? entryMethodName : \"setDirty\";\n            // We have to use arrayFromSet(dep).forEach instead of dep.forEach,\n            // because modifying a Set while iterating over it can cause elements in\n            // the Set to be removed from the Set before they've been iterated over.\n            arrayFromSet(dep).forEach(entry => entry[m]());\n            depsByKey.delete(key);\n            maybeUnsubscribe(dep);\n        }\n    };\n    return depend;\n}\n//# sourceMappingURL=dep.js.map","import { Trie } from \"@wry/trie\";\nimport { StrongCache } from \"@wry/caches\";\nimport { Entry } from \"./entry.js\";\nimport { parentEntrySlot } from \"./context.js\";\n// These helper functions are important for making optimism work with\n// asynchronous code. In order to register parent-child dependencies,\n// optimism needs to know about any currently active parent computations.\n// In ordinary synchronous code, the parent context is implicit in the\n// execution stack, but asynchronous code requires some extra guidance in\n// order to propagate context from one async task segment to the next.\nexport { bindContext, noContext, nonReactive, setTimeout, asyncFromGen, Slot, } from \"./context.js\";\n// A lighter-weight dependency, similar to OptimisticWrapperFunction, except\n// with only one argument, no makeCacheKey, no wrapped function to recompute,\n// and no result value. Useful for representing dependency leaves in the graph\n// of computation. Subscriptions are supported.\nexport { dep } from \"./dep.js\";\n// The defaultMakeCacheKey function is remarkably powerful, because it gives\n// a unique object for any shallow-identical list of arguments. If you need\n// to implement a custom makeCacheKey function, you may find it helpful to\n// delegate the final work to defaultMakeCacheKey, which is why we export it\n// here. However, you may want to avoid defaultMakeCacheKey if your runtime\n// does not support WeakMap, or you have the ability to return a string key.\n// In those cases, just write your own custom makeCacheKey functions.\nlet defaultKeyTrie;\nexport function defaultMakeCacheKey(...args) {\n    const trie = defaultKeyTrie || (defaultKeyTrie = new Trie(typeof WeakMap === \"function\"));\n    return trie.lookupArray(args);\n}\n// If you're paranoid about memory leaks, or you want to avoid using WeakMap\n// under the hood, but you still need the behavior of defaultMakeCacheKey,\n// import this constructor to create your own tries.\nexport { Trie as KeyTrie };\n;\nconst caches = new Set();\nexport function wrap(originalFunction, { max = Math.pow(2, 16), keyArgs, makeCacheKey = defaultMakeCacheKey, normalizeResult, subscribe, cache: cacheOption = StrongCache, } = Object.create(null)) {\n    const cache = typeof cacheOption === \"function\"\n        ? new cacheOption(max, entry => entry.dispose())\n        : cacheOption;\n    const optimistic = function () {\n        const key = makeCacheKey.apply(null, keyArgs ? keyArgs.apply(null, arguments) : arguments);\n        if (key === void 0) {\n            return originalFunction.apply(null, arguments);\n        }\n        let entry = cache.get(key);\n        if (!entry) {\n            cache.set(key, entry = new Entry(originalFunction));\n            entry.normalizeResult = normalizeResult;\n            entry.subscribe = subscribe;\n            // Give the Entry the ability to trigger cache.delete(key), even though\n            // the Entry itself does not know about key or cache.\n            entry.forget = () => cache.delete(key);\n        }\n        const value = entry.recompute(Array.prototype.slice.call(arguments));\n        // Move this entry to the front of the least-recently used queue,\n        // since we just finished computing its value.\n        cache.set(key, entry);\n        caches.add(cache);\n        // Clean up any excess entries in the cache, but only if there is no\n        // active parent entry, meaning we're not in the middle of a larger\n        // computation that might be flummoxed by the cleaning.\n        if (!parentEntrySlot.hasValue()) {\n            caches.forEach(cache => cache.clean());\n            caches.clear();\n        }\n        return value;\n    };\n    Object.defineProperty(optimistic, \"size\", {\n        get: () => cache.size,\n        configurable: false,\n        enumerable: false,\n    });\n    Object.freeze(optimistic.options = {\n        max,\n        keyArgs,\n        makeCacheKey,\n        normalizeResult,\n        subscribe,\n        cache,\n    });\n    function dirtyKey(key) {\n        const entry = key && cache.get(key);\n        if (entry) {\n            entry.setDirty();\n        }\n    }\n    optimistic.dirtyKey = dirtyKey;\n    optimistic.dirty = function dirty() {\n        dirtyKey(makeCacheKey.apply(null, arguments));\n    };\n    function peekKey(key) {\n        const entry = key && cache.get(key);\n        if (entry) {\n            return entry.peek();\n        }\n    }\n    optimistic.peekKey = peekKey;\n    optimistic.peek = function peek() {\n        return peekKey(makeCacheKey.apply(null, arguments));\n    };\n    function forgetKey(key) {\n        return key ? cache.delete(key) : false;\n    }\n    optimistic.forgetKey = forgetKey;\n    optimistic.forget = function forget() {\n        return forgetKey(makeCacheKey.apply(null, arguments));\n    };\n    optimistic.makeCacheKey = makeCacheKey;\n    optimistic.getKey = keyArgs ? function getKey() {\n        return makeCacheKey.apply(null, keyArgs.apply(null, arguments));\n    } : makeCacheKey;\n    return Object.freeze(optimistic);\n}\n//# sourceMappingURL=index.js.map","import { Trie } from \"@wry/trie\";\nimport { canUseWeakMap, canUseWeakSet } from \"../common/canUse.js\";\nimport { checkDocument } from \"./getFromAST.js\";\nimport { invariant } from \"../globals/index.js\";\nimport { WeakCache } from \"@wry/caches\";\nimport { wrap } from \"optimism\";\nimport { cacheSizes } from \"../caching/index.js\";\nfunction identity(document) {\n    return document;\n}\nvar DocumentTransform = /** @class */ (function () {\n    function DocumentTransform(transform, options) {\n        if (options === void 0) { options = Object.create(null); }\n        this.resultCache = canUseWeakSet ? new WeakSet() : new Set();\n        this.transform = transform;\n        if (options.getCacheKey) {\n            // Override default `getCacheKey` function, which returns [document].\n            this.getCacheKey = options.getCacheKey;\n        }\n        this.cached = options.cache !== false;\n        this.resetCache();\n    }\n    // This default implementation of getCacheKey can be overridden by providing\n    // options.getCacheKey to the DocumentTransform constructor. In general, a\n    // getCacheKey function may either return an array of keys (often including\n    // the document) to be used as a cache key, or undefined to indicate the\n    // transform for this document should not be cached.\n    DocumentTransform.prototype.getCacheKey = function (document) {\n        return [document];\n    };\n    DocumentTransform.identity = function () {\n        // No need to cache this transform since it just returns the document\n        // unchanged. This should save a bit of memory that would otherwise be\n        // needed to populate the `documentCache` of this transform.\n        return new DocumentTransform(identity, { cache: false });\n    };\n    DocumentTransform.split = function (predicate, left, right) {\n        if (right === void 0) { right = DocumentTransform.identity(); }\n        return Object.assign(new DocumentTransform(function (document) {\n            var documentTransform = predicate(document) ? left : right;\n            return documentTransform.transformDocument(document);\n        }, \n        // Reasonably assume both `left` and `right` transforms handle their own caching\n        { cache: false }), { left: left, right: right });\n    };\n    /**\n     * Resets the internal cache of this transform, if it has one.\n     */\n    DocumentTransform.prototype.resetCache = function () {\n        var _this = this;\n        if (this.cached) {\n            var stableCacheKeys_1 = new Trie(canUseWeakMap);\n            this.performWork = wrap(DocumentTransform.prototype.performWork.bind(this), {\n                makeCacheKey: function (document) {\n                    var cacheKeys = _this.getCacheKey(document);\n                    if (cacheKeys) {\n                        invariant(Array.isArray(cacheKeys), 69);\n                        return stableCacheKeys_1.lookupArray(cacheKeys);\n                    }\n                },\n                max: cacheSizes[\"documentTransform.cache\"],\n                cache: (WeakCache),\n            });\n        }\n    };\n    DocumentTransform.prototype.performWork = function (document) {\n        checkDocument(document);\n        return this.transform(document);\n    };\n    DocumentTransform.prototype.transformDocument = function (document) {\n        // If a user passes an already transformed result back to this function,\n        // immediately return it.\n        if (this.resultCache.has(document)) {\n            return document;\n        }\n        var transformedDocument = this.performWork(document);\n        this.resultCache.add(transformedDocument);\n        return transformedDocument;\n    };\n    DocumentTransform.prototype.concat = function (otherTransform) {\n        var _this = this;\n        return Object.assign(new DocumentTransform(function (document) {\n            return otherTransform.transformDocument(_this.transformDocument(document));\n        }, \n        // Reasonably assume both transforms handle their own caching\n        { cache: false }), {\n            left: this,\n            right: otherTransform,\n        });\n    };\n    return DocumentTransform;\n}());\nexport { DocumentTransform };\n//# sourceMappingURL=DocumentTransform.js.map","import { print as origPrint } from \"graphql\";\nimport { AutoCleanedWeakCache, cacheSizes, } from \"../caching/index.js\";\nimport { registerGlobalCache } from \"../caching/getMemoryInternals.js\";\nvar printCache;\nexport var print = Object.assign(function (ast) {\n    var result = printCache.get(ast);\n    if (!result) {\n        result = origPrint(ast);\n        printCache.set(ast, result);\n    }\n    return result;\n}, {\n    reset: function () {\n        printCache = new AutoCleanedWeakCache(cacheSizes.print || 2000 /* defaultCacheSizes.print */);\n    },\n});\nprint.reset();\nif (globalThis.__DEV__ !== false) {\n    registerGlobalCache(\"print\", function () { return (printCache ? printCache.size : 0); });\n}\n//# sourceMappingURL=print.js.map","// A version of Array.isArray that works better with readonly arrays.\nexport var isArray = Array.isArray;\nexport function isNonEmptyArray(value) {\n    return Array.isArray(value) && value.length > 0;\n}\n//# sourceMappingURL=arrays.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { invariant } from \"../globals/index.js\";\nimport { visit, Kind } from \"graphql\";\nimport { checkDocument, getOperationDefinition, getFragmentDefinition, getFragmentDefinitions, getMainDefinition, } from \"./getFromAST.js\";\nimport { isField } from \"./storeUtils.js\";\nimport { createFragmentMap } from \"./fragments.js\";\nimport { isArray, isNonEmptyArray } from \"../common/arrays.js\";\nvar TYPENAME_FIELD = {\n    kind: Kind.FIELD,\n    name: {\n        kind: Kind.NAME,\n        value: \"__typename\",\n    },\n};\nfunction isEmpty(op, fragmentMap) {\n    return (!op ||\n        op.selectionSet.selections.every(function (selection) {\n            return selection.kind === Kind.FRAGMENT_SPREAD &&\n                isEmpty(fragmentMap[selection.name.value], fragmentMap);\n        }));\n}\nfunction nullIfDocIsEmpty(doc) {\n    return (isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))) ?\n        null\n        : doc;\n}\nfunction getDirectiveMatcher(configs) {\n    var names = new Map();\n    var tests = new Map();\n    configs.forEach(function (directive) {\n        if (directive) {\n            if (directive.name) {\n                names.set(directive.name, directive);\n            }\n            else if (directive.test) {\n                tests.set(directive.test, directive);\n            }\n        }\n    });\n    return function (directive) {\n        var config = names.get(directive.name.value);\n        if (!config && tests.size) {\n            tests.forEach(function (testConfig, test) {\n                if (test(directive)) {\n                    config = testConfig;\n                }\n            });\n        }\n        return config;\n    };\n}\nfunction makeInUseGetterFunction(defaultKey) {\n    var map = new Map();\n    return function inUseGetterFunction(key) {\n        if (key === void 0) { key = defaultKey; }\n        var inUse = map.get(key);\n        if (!inUse) {\n            map.set(key, (inUse = {\n                // Variable and fragment spread names used directly within this\n                // operation or fragment definition, as identified by key. These sets\n                // will be populated during the first traversal of the document in\n                // removeDirectivesFromDocument below.\n                variables: new Set(),\n                fragmentSpreads: new Set(),\n            }));\n        }\n        return inUse;\n    };\n}\nexport function removeDirectivesFromDocument(directives, doc) {\n    checkDocument(doc);\n    // Passing empty strings to makeInUseGetterFunction means we handle anonymous\n    // operations as if their names were \"\". Anonymous fragment definitions are\n    // not supposed to be possible, but the same default naming strategy seems\n    // appropriate for that case as well.\n    var getInUseByOperationName = makeInUseGetterFunction(\"\");\n    var getInUseByFragmentName = makeInUseGetterFunction(\"\");\n    var getInUse = function (ancestors) {\n        for (var p = 0, ancestor = void 0; p < ancestors.length && (ancestor = ancestors[p]); ++p) {\n            if (isArray(ancestor))\n                continue;\n            if (ancestor.kind === Kind.OPERATION_DEFINITION) {\n                // If an operation is anonymous, we use the empty string as its key.\n                return getInUseByOperationName(ancestor.name && ancestor.name.value);\n            }\n            if (ancestor.kind === Kind.FRAGMENT_DEFINITION) {\n                return getInUseByFragmentName(ancestor.name.value);\n            }\n        }\n        globalThis.__DEV__ !== false && invariant.error(86);\n        return null;\n    };\n    var operationCount = 0;\n    for (var i = doc.definitions.length - 1; i >= 0; --i) {\n        if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {\n            ++operationCount;\n        }\n    }\n    var directiveMatcher = getDirectiveMatcher(directives);\n    var shouldRemoveField = function (nodeDirectives) {\n        return isNonEmptyArray(nodeDirectives) &&\n            nodeDirectives\n                .map(directiveMatcher)\n                .some(function (config) { return config && config.remove; });\n    };\n    var originalFragmentDefsByPath = new Map();\n    // Any time the first traversal of the document below makes a change like\n    // removing a fragment (by returning null), this variable should be set to\n    // true. Once it becomes true, it should never be set to false again. If this\n    // variable remains false throughout the traversal, then we can return the\n    // original doc immediately without any modifications.\n    var firstVisitMadeChanges = false;\n    var fieldOrInlineFragmentVisitor = {\n        enter: function (node) {\n            if (shouldRemoveField(node.directives)) {\n                firstVisitMadeChanges = true;\n                return null;\n            }\n        },\n    };\n    var docWithoutDirectiveSubtrees = visit(doc, {\n        // These two AST node types share the same implementation, defined above.\n        Field: fieldOrInlineFragmentVisitor,\n        InlineFragment: fieldOrInlineFragmentVisitor,\n        VariableDefinition: {\n            enter: function () {\n                // VariableDefinition nodes do not count as variables in use, though\n                // they do contain Variable nodes that might be visited below. To avoid\n                // counting variable declarations as usages, we skip visiting the\n                // contents of this VariableDefinition node by returning false.\n                return false;\n            },\n        },\n        Variable: {\n            enter: function (node, _key, _parent, _path, ancestors) {\n                var inUse = getInUse(ancestors);\n                if (inUse) {\n                    inUse.variables.add(node.name.value);\n                }\n            },\n        },\n        FragmentSpread: {\n            enter: function (node, _key, _parent, _path, ancestors) {\n                if (shouldRemoveField(node.directives)) {\n                    firstVisitMadeChanges = true;\n                    return null;\n                }\n                var inUse = getInUse(ancestors);\n                if (inUse) {\n                    inUse.fragmentSpreads.add(node.name.value);\n                }\n                // We might like to remove this FragmentSpread by returning null here if\n                // the corresponding FragmentDefinition node is also going to be removed\n                // by the logic below, but we can't control the relative order of those\n                // events, so we have to postpone the removal of dangling FragmentSpread\n                // nodes until after the current visit of the document has finished.\n            },\n        },\n        FragmentDefinition: {\n            enter: function (node, _key, _parent, path) {\n                originalFragmentDefsByPath.set(JSON.stringify(path), node);\n            },\n            leave: function (node, _key, _parent, path) {\n                var originalNode = originalFragmentDefsByPath.get(JSON.stringify(path));\n                if (node === originalNode) {\n                    // If the FragmentNode received by this leave function is identical to\n                    // the one received by the corresponding enter function (above), then\n                    // the visitor must not have made any changes within this\n                    // FragmentDefinition node. This fragment definition may still be\n                    // removed if there are no ...spread references to it, but it won't be\n                    // removed just because it has only a __typename field.\n                    return node;\n                }\n                if (\n                // This logic applies only if the document contains one or more\n                // operations, since removing all fragments from a document containing\n                // only fragments makes the document useless.\n                operationCount > 0 &&\n                    node.selectionSet.selections.every(function (selection) {\n                        return selection.kind === Kind.FIELD &&\n                            selection.name.value === \"__typename\";\n                    })) {\n                    // This is a somewhat opinionated choice: if a FragmentDefinition ends\n                    // up having no fields other than __typename, we remove the whole\n                    // fragment definition, and later prune ...spread references to it.\n                    getInUseByFragmentName(node.name.value).removed = true;\n                    firstVisitMadeChanges = true;\n                    return null;\n                }\n            },\n        },\n        Directive: {\n            leave: function (node) {\n                // If a matching directive is found, remove the directive itself. Note\n                // that this does not remove the target (field, argument, etc) of the\n                // directive, but only the directive itself.\n                if (directiveMatcher(node)) {\n                    firstVisitMadeChanges = true;\n                    return null;\n                }\n            },\n        },\n    });\n    if (!firstVisitMadeChanges) {\n        // If our first pass did not change anything about the document, then there\n        // is no cleanup we need to do, and we can return the original doc.\n        return doc;\n    }\n    // Utility for making sure inUse.transitiveVars is recursively populated.\n    // Because this logic assumes inUse.fragmentSpreads has been completely\n    // populated and inUse.removed has been set if appropriate,\n    // populateTransitiveVars must be called after that information has been\n    // collected by the first traversal of the document.\n    var populateTransitiveVars = function (inUse) {\n        if (!inUse.transitiveVars) {\n            inUse.transitiveVars = new Set(inUse.variables);\n            if (!inUse.removed) {\n                inUse.fragmentSpreads.forEach(function (childFragmentName) {\n                    populateTransitiveVars(getInUseByFragmentName(childFragmentName)).transitiveVars.forEach(function (varName) {\n                        inUse.transitiveVars.add(varName);\n                    });\n                });\n            }\n        }\n        return inUse;\n    };\n    // Since we've been keeping track of fragment spreads used by particular\n    // operations and fragment definitions, we now need to compute the set of all\n    // spreads used (transitively) by any operations in the document.\n    var allFragmentNamesUsed = new Set();\n    docWithoutDirectiveSubtrees.definitions.forEach(function (def) {\n        if (def.kind === Kind.OPERATION_DEFINITION) {\n            populateTransitiveVars(getInUseByOperationName(def.name && def.name.value)).fragmentSpreads.forEach(function (childFragmentName) {\n                allFragmentNamesUsed.add(childFragmentName);\n            });\n        }\n        else if (def.kind === Kind.FRAGMENT_DEFINITION &&\n            // If there are no operations in the document, then all fragment\n            // definitions count as usages of their own fragment names. This heuristic\n            // prevents accidentally removing all fragment definitions from the\n            // document just because it contains no operations that use the fragments.\n            operationCount === 0 &&\n            !getInUseByFragmentName(def.name.value).removed) {\n            allFragmentNamesUsed.add(def.name.value);\n        }\n    });\n    // Now that we have added all fragment spreads used by operations to the\n    // allFragmentNamesUsed set, we can complete the set by transitively adding\n    // all fragment spreads used by those fragments, and so on.\n    allFragmentNamesUsed.forEach(function (fragmentName) {\n        // Once all the childFragmentName strings added here have been seen already,\n        // the top-level allFragmentNamesUsed.forEach loop will terminate.\n        populateTransitiveVars(getInUseByFragmentName(fragmentName)).fragmentSpreads.forEach(function (childFragmentName) {\n            allFragmentNamesUsed.add(childFragmentName);\n        });\n    });\n    var fragmentWillBeRemoved = function (fragmentName) {\n        return !!(\n        // A fragment definition will be removed if there are no spreads that refer\n        // to it, or the fragment was explicitly removed because it had no fields\n        // other than __typename.\n        (!allFragmentNamesUsed.has(fragmentName) ||\n            getInUseByFragmentName(fragmentName).removed));\n    };\n    var enterVisitor = {\n        enter: function (node) {\n            if (fragmentWillBeRemoved(node.name.value)) {\n                return null;\n            }\n        },\n    };\n    return nullIfDocIsEmpty(visit(docWithoutDirectiveSubtrees, {\n        // If the fragment is going to be removed, then leaving any dangling\n        // FragmentSpread nodes with the same name would be a mistake.\n        FragmentSpread: enterVisitor,\n        // This is where the fragment definition is actually removed.\n        FragmentDefinition: enterVisitor,\n        OperationDefinition: {\n            leave: function (node) {\n                // Upon leaving each operation in the depth-first AST traversal, prune\n                // any variables that are declared by the operation but unused within.\n                if (node.variableDefinitions) {\n                    var usedVariableNames_1 = populateTransitiveVars(\n                    // If an operation is anonymous, we use the empty string as its key.\n                    getInUseByOperationName(node.name && node.name.value)).transitiveVars;\n                    // According to the GraphQL spec, all variables declared by an\n                    // operation must either be used by that operation or used by some\n                    // fragment included transitively into that operation:\n                    // https://spec.graphql.org/draft/#sec-All-Variables-Used\n                    //\n                    // To stay on the right side of this validation rule, if/when we\n                    // remove the last $var references from an operation or its fragments,\n                    // we must also remove the corresponding $var declaration from the\n                    // enclosing operation. This pruning applies only to operations and\n                    // not fragment definitions, at the moment. Fragments may be able to\n                    // declare variables eventually, but today they can only consume them.\n                    if (usedVariableNames_1.size < node.variableDefinitions.length) {\n                        return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions.filter(function (varDef) {\n                                return usedVariableNames_1.has(varDef.variable.name.value);\n                            }) });\n                    }\n                }\n            },\n        },\n    }));\n}\nexport var addTypenameToDocument = Object.assign(function (doc) {\n    return visit(doc, {\n        SelectionSet: {\n            enter: function (node, _key, parent) {\n                // Don't add __typename to OperationDefinitions.\n                if (parent &&\n                    parent.kind ===\n                        Kind.OPERATION_DEFINITION) {\n                    return;\n                }\n                // No changes if no selections.\n                var selections = node.selections;\n                if (!selections) {\n                    return;\n                }\n                // If selections already have a __typename, or are part of an\n                // introspection query, do nothing.\n                var skip = selections.some(function (selection) {\n                    return (isField(selection) &&\n                        (selection.name.value === \"__typename\" ||\n                            selection.name.value.lastIndexOf(\"__\", 0) === 0));\n                });\n                if (skip) {\n                    return;\n                }\n                // If this SelectionSet is @export-ed as an input variable, it should\n                // not have a __typename field (see issue #4691).\n                var field = parent;\n                if (isField(field) &&\n                    field.directives &&\n                    field.directives.some(function (d) { return d.name.value === \"export\"; })) {\n                    return;\n                }\n                // Create and return a new SelectionSet with a __typename Field.\n                return __assign(__assign({}, node), { selections: __spreadArray(__spreadArray([], selections, true), [TYPENAME_FIELD], false) });\n            },\n        },\n    });\n}, {\n    added: function (field) {\n        return field === TYPENAME_FIELD;\n    },\n});\nvar connectionRemoveConfig = {\n    test: function (directive) {\n        var willRemove = directive.name.value === \"connection\";\n        if (willRemove) {\n            if (!directive.arguments ||\n                !directive.arguments.some(function (arg) { return arg.name.value === \"key\"; })) {\n                globalThis.__DEV__ !== false && invariant.warn(87);\n            }\n        }\n        return willRemove;\n    },\n};\nexport function removeConnectionDirectiveFromDocument(doc) {\n    return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));\n}\nfunction hasDirectivesInSelectionSet(directives, selectionSet, nestedCheck) {\n    if (nestedCheck === void 0) { nestedCheck = true; }\n    return (!!selectionSet &&\n        selectionSet.selections &&\n        selectionSet.selections.some(function (selection) {\n            return hasDirectivesInSelection(directives, selection, nestedCheck);\n        }));\n}\nfunction hasDirectivesInSelection(directives, selection, nestedCheck) {\n    if (nestedCheck === void 0) { nestedCheck = true; }\n    if (!isField(selection)) {\n        return true;\n    }\n    if (!selection.directives) {\n        return false;\n    }\n    return (selection.directives.some(getDirectiveMatcher(directives)) ||\n        (nestedCheck &&\n            hasDirectivesInSelectionSet(directives, selection.selectionSet, nestedCheck)));\n}\nfunction getArgumentMatcher(config) {\n    return function argumentMatcher(argument) {\n        return config.some(function (aConfig) {\n            return argument.value &&\n                argument.value.kind === Kind.VARIABLE &&\n                argument.value.name &&\n                (aConfig.name === argument.value.name.value ||\n                    (aConfig.test && aConfig.test(argument)));\n        });\n    };\n}\nexport function removeArgumentsFromDocument(config, doc) {\n    var argMatcher = getArgumentMatcher(config);\n    return nullIfDocIsEmpty(visit(doc, {\n        OperationDefinition: {\n            enter: function (node) {\n                return __assign(__assign({}, node), { \n                    // Remove matching top level variables definitions.\n                    variableDefinitions: node.variableDefinitions ?\n                        node.variableDefinitions.filter(function (varDef) {\n                            return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });\n                        })\n                        : [] });\n            },\n        },\n        Field: {\n            enter: function (node) {\n                // If `remove` is set to true for an argument, and an argument match\n                // is found for a field, remove the field as well.\n                var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });\n                if (shouldRemoveField) {\n                    var argMatchCount_1 = 0;\n                    if (node.arguments) {\n                        node.arguments.forEach(function (arg) {\n                            if (argMatcher(arg)) {\n                                argMatchCount_1 += 1;\n                            }\n                        });\n                    }\n                    if (argMatchCount_1 === 1) {\n                        return null;\n                    }\n                }\n            },\n        },\n        Argument: {\n            enter: function (node) {\n                // Remove all matching arguments.\n                if (argMatcher(node)) {\n                    return null;\n                }\n            },\n        },\n    }));\n}\nexport function removeFragmentSpreadFromDocument(config, doc) {\n    function enter(node) {\n        if (config.some(function (def) { return def.name === node.name.value; })) {\n            return null;\n        }\n    }\n    return nullIfDocIsEmpty(visit(doc, {\n        FragmentSpread: { enter: enter },\n        FragmentDefinition: { enter: enter },\n    }));\n}\n// If the incoming document is a query, return it as is. Otherwise, build a\n// new document containing a query operation based on the selection set\n// of the previous main operation.\nexport function buildQueryFromSelectionSet(document) {\n    var definition = getMainDefinition(document);\n    var definitionOperation = definition.operation;\n    if (definitionOperation === \"query\") {\n        // Already a query, so return the existing document.\n        return document;\n    }\n    // Build a new query using the selection set of the main operation.\n    var modifiedDoc = visit(document, {\n        OperationDefinition: {\n            enter: function (node) {\n                return __assign(__assign({}, node), { operation: \"query\" });\n            },\n        },\n    });\n    return modifiedDoc;\n}\n// Remove fields / selection sets that include an @client directive.\nexport function removeClientSetsFromDocument(document) {\n    checkDocument(document);\n    var modifiedDoc = removeDirectivesFromDocument([\n        {\n            test: function (directive) { return directive.name.value === \"client\"; },\n            remove: true,\n        },\n    ], document);\n    return modifiedDoc;\n}\n//# sourceMappingURL=transform.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { isNonNullObject } from \"./objects.js\";\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function mergeDeep() {\n    var sources = [];\n    for (var _i = 0; _i < arguments.length; _i++) {\n        sources[_i] = arguments[_i];\n    }\n    return mergeDeepArray(sources);\n}\n// In almost any situation where you could succeed in getting the\n// TypeScript compiler to infer a tuple type for the sources array, you\n// could just use mergeDeep instead of mergeDeepArray, so instead of\n// trying to convert T[] to an intersection type we just infer the array\n// element type, which works perfectly when the sources array has a\n// consistent element type.\nexport function mergeDeepArray(sources) {\n    var target = sources[0] || {};\n    var count = sources.length;\n    if (count > 1) {\n        var merger = new DeepMerger();\n        for (var i = 1; i < count; ++i) {\n            target = merger.merge(target, sources[i]);\n        }\n    }\n    return target;\n}\nvar defaultReconciler = function (target, source, property) {\n    return this.merge(target[property], source[property]);\n};\nvar DeepMerger = /** @class */ (function () {\n    function DeepMerger(reconciler) {\n        if (reconciler === void 0) { reconciler = defaultReconciler; }\n        this.reconciler = reconciler;\n        this.isObject = isNonNullObject;\n        this.pastCopies = new Set();\n    }\n    DeepMerger.prototype.merge = function (target, source) {\n        var _this = this;\n        var context = [];\n        for (var _i = 2; _i < arguments.length; _i++) {\n            context[_i - 2] = arguments[_i];\n        }\n        if (isNonNullObject(source) && isNonNullObject(target)) {\n            Object.keys(source).forEach(function (sourceKey) {\n                if (hasOwnProperty.call(target, sourceKey)) {\n                    var targetValue = target[sourceKey];\n                    if (source[sourceKey] !== targetValue) {\n                        var result = _this.reconciler.apply(_this, __spreadArray([target,\n                            source,\n                            sourceKey], context, false));\n                        // A well-implemented reconciler may return targetValue to indicate\n                        // the merge changed nothing about the structure of the target.\n                        if (result !== targetValue) {\n                            target = _this.shallowCopyForMerge(target);\n                            target[sourceKey] = result;\n                        }\n                    }\n                }\n                else {\n                    // If there is no collision, the target can safely share memory with\n                    // the source, and the recursion can terminate here.\n                    target = _this.shallowCopyForMerge(target);\n                    target[sourceKey] = source[sourceKey];\n                }\n            });\n            return target;\n        }\n        // If source (or target) is not an object, let source replace target.\n        return source;\n    };\n    DeepMerger.prototype.shallowCopyForMerge = function (value) {\n        if (isNonNullObject(value)) {\n            if (!this.pastCopies.has(value)) {\n                if (Array.isArray(value)) {\n                    value = value.slice(0);\n                }\n                else {\n                    value = __assign({ __proto__: Object.getPrototypeOf(value) }, value);\n                }\n                this.pastCopies.add(value);\n            }\n        }\n        return value;\n    };\n    return DeepMerger;\n}());\nexport { DeepMerger };\n//# sourceMappingURL=mergeDeep.js.map","function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n// === Symbol Support ===\nvar hasSymbols = function () {\n  return typeof Symbol === 'function';\n};\n\nvar hasSymbol = function (name) {\n  return hasSymbols() && Boolean(Symbol[name]);\n};\n\nvar getSymbol = function (name) {\n  return hasSymbol(name) ? Symbol[name] : '@@' + name;\n};\n\nif (hasSymbols() && !hasSymbol('observable')) {\n  Symbol.observable = Symbol('observable');\n}\n\nvar SymbolIterator = getSymbol('iterator');\nvar SymbolObservable = getSymbol('observable');\nvar SymbolSpecies = getSymbol('species'); // === Abstract Operations ===\n\nfunction getMethod(obj, key) {\n  var value = obj[key];\n  if (value == null) return undefined;\n  if (typeof value !== 'function') throw new TypeError(value + ' is not a function');\n  return value;\n}\n\nfunction getSpecies(obj) {\n  var ctor = obj.constructor;\n\n  if (ctor !== undefined) {\n    ctor = ctor[SymbolSpecies];\n\n    if (ctor === null) {\n      ctor = undefined;\n    }\n  }\n\n  return ctor !== undefined ? ctor : Observable;\n}\n\nfunction isObservable(x) {\n  return x instanceof Observable; // SPEC: Brand check\n}\n\nfunction hostReportError(e) {\n  if (hostReportError.log) {\n    hostReportError.log(e);\n  } else {\n    setTimeout(function () {\n      throw e;\n    });\n  }\n}\n\nfunction enqueue(fn) {\n  Promise.resolve().then(function () {\n    try {\n      fn();\n    } catch (e) {\n      hostReportError(e);\n    }\n  });\n}\n\nfunction cleanupSubscription(subscription) {\n  var cleanup = subscription._cleanup;\n  if (cleanup === undefined) return;\n  subscription._cleanup = undefined;\n\n  if (!cleanup) {\n    return;\n  }\n\n  try {\n    if (typeof cleanup === 'function') {\n      cleanup();\n    } else {\n      var unsubscribe = getMethod(cleanup, 'unsubscribe');\n\n      if (unsubscribe) {\n        unsubscribe.call(cleanup);\n      }\n    }\n  } catch (e) {\n    hostReportError(e);\n  }\n}\n\nfunction closeSubscription(subscription) {\n  subscription._observer = undefined;\n  subscription._queue = undefined;\n  subscription._state = 'closed';\n}\n\nfunction flushSubscription(subscription) {\n  var queue = subscription._queue;\n\n  if (!queue) {\n    return;\n  }\n\n  subscription._queue = undefined;\n  subscription._state = 'ready';\n\n  for (var i = 0; i < queue.length; ++i) {\n    notifySubscription(subscription, queue[i].type, queue[i].value);\n    if (subscription._state === 'closed') break;\n  }\n}\n\nfunction notifySubscription(subscription, type, value) {\n  subscription._state = 'running';\n  var observer = subscription._observer;\n\n  try {\n    var m = getMethod(observer, type);\n\n    switch (type) {\n      case 'next':\n        if (m) m.call(observer, value);\n        break;\n\n      case 'error':\n        closeSubscription(subscription);\n        if (m) m.call(observer, value);else throw value;\n        break;\n\n      case 'complete':\n        closeSubscription(subscription);\n        if (m) m.call(observer);\n        break;\n    }\n  } catch (e) {\n    hostReportError(e);\n  }\n\n  if (subscription._state === 'closed') cleanupSubscription(subscription);else if (subscription._state === 'running') subscription._state = 'ready';\n}\n\nfunction onNotify(subscription, type, value) {\n  if (subscription._state === 'closed') return;\n\n  if (subscription._state === 'buffering') {\n    subscription._queue.push({\n      type: type,\n      value: value\n    });\n\n    return;\n  }\n\n  if (subscription._state !== 'ready') {\n    subscription._state = 'buffering';\n    subscription._queue = [{\n      type: type,\n      value: value\n    }];\n    enqueue(function () {\n      return flushSubscription(subscription);\n    });\n    return;\n  }\n\n  notifySubscription(subscription, type, value);\n}\n\nvar Subscription = /*#__PURE__*/function () {\n  function Subscription(observer, subscriber) {\n    // ASSERT: observer is an object\n    // ASSERT: subscriber is callable\n    this._cleanup = undefined;\n    this._observer = observer;\n    this._queue = undefined;\n    this._state = 'initializing';\n    var subscriptionObserver = new SubscriptionObserver(this);\n\n    try {\n      this._cleanup = subscriber.call(undefined, subscriptionObserver);\n    } catch (e) {\n      subscriptionObserver.error(e);\n    }\n\n    if (this._state === 'initializing') this._state = 'ready';\n  }\n\n  var _proto = Subscription.prototype;\n\n  _proto.unsubscribe = function unsubscribe() {\n    if (this._state !== 'closed') {\n      closeSubscription(this);\n      cleanupSubscription(this);\n    }\n  };\n\n  _createClass(Subscription, [{\n    key: \"closed\",\n    get: function () {\n      return this._state === 'closed';\n    }\n  }]);\n\n  return Subscription;\n}();\n\nvar SubscriptionObserver = /*#__PURE__*/function () {\n  function SubscriptionObserver(subscription) {\n    this._subscription = subscription;\n  }\n\n  var _proto2 = SubscriptionObserver.prototype;\n\n  _proto2.next = function next(value) {\n    onNotify(this._subscription, 'next', value);\n  };\n\n  _proto2.error = function error(value) {\n    onNotify(this._subscription, 'error', value);\n  };\n\n  _proto2.complete = function complete() {\n    onNotify(this._subscription, 'complete');\n  };\n\n  _createClass(SubscriptionObserver, [{\n    key: \"closed\",\n    get: function () {\n      return this._subscription._state === 'closed';\n    }\n  }]);\n\n  return SubscriptionObserver;\n}();\n\nvar Observable = /*#__PURE__*/function () {\n  function Observable(subscriber) {\n    if (!(this instanceof Observable)) throw new TypeError('Observable cannot be called as a function');\n    if (typeof subscriber !== 'function') throw new TypeError('Observable initializer must be a function');\n    this._subscriber = subscriber;\n  }\n\n  var _proto3 = Observable.prototype;\n\n  _proto3.subscribe = function subscribe(observer) {\n    if (typeof observer !== 'object' || observer === null) {\n      observer = {\n        next: observer,\n        error: arguments[1],\n        complete: arguments[2]\n      };\n    }\n\n    return new Subscription(observer, this._subscriber);\n  };\n\n  _proto3.forEach = function forEach(fn) {\n    var _this = this;\n\n    return new Promise(function (resolve, reject) {\n      if (typeof fn !== 'function') {\n        reject(new TypeError(fn + ' is not a function'));\n        return;\n      }\n\n      function done() {\n        subscription.unsubscribe();\n        resolve();\n      }\n\n      var subscription = _this.subscribe({\n        next: function (value) {\n          try {\n            fn(value, done);\n          } catch (e) {\n            reject(e);\n            subscription.unsubscribe();\n          }\n        },\n        error: reject,\n        complete: resolve\n      });\n    });\n  };\n\n  _proto3.map = function map(fn) {\n    var _this2 = this;\n\n    if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');\n    var C = getSpecies(this);\n    return new C(function (observer) {\n      return _this2.subscribe({\n        next: function (value) {\n          try {\n            value = fn(value);\n          } catch (e) {\n            return observer.error(e);\n          }\n\n          observer.next(value);\n        },\n        error: function (e) {\n          observer.error(e);\n        },\n        complete: function () {\n          observer.complete();\n        }\n      });\n    });\n  };\n\n  _proto3.filter = function filter(fn) {\n    var _this3 = this;\n\n    if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');\n    var C = getSpecies(this);\n    return new C(function (observer) {\n      return _this3.subscribe({\n        next: function (value) {\n          try {\n            if (!fn(value)) return;\n          } catch (e) {\n            return observer.error(e);\n          }\n\n          observer.next(value);\n        },\n        error: function (e) {\n          observer.error(e);\n        },\n        complete: function () {\n          observer.complete();\n        }\n      });\n    });\n  };\n\n  _proto3.reduce = function reduce(fn) {\n    var _this4 = this;\n\n    if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');\n    var C = getSpecies(this);\n    var hasSeed = arguments.length > 1;\n    var hasValue = false;\n    var seed = arguments[1];\n    var acc = seed;\n    return new C(function (observer) {\n      return _this4.subscribe({\n        next: function (value) {\n          var first = !hasValue;\n          hasValue = true;\n\n          if (!first || hasSeed) {\n            try {\n              acc = fn(acc, value);\n            } catch (e) {\n              return observer.error(e);\n            }\n          } else {\n            acc = value;\n          }\n        },\n        error: function (e) {\n          observer.error(e);\n        },\n        complete: function () {\n          if (!hasValue && !hasSeed) return observer.error(new TypeError('Cannot reduce an empty sequence'));\n          observer.next(acc);\n          observer.complete();\n        }\n      });\n    });\n  };\n\n  _proto3.concat = function concat() {\n    var _this5 = this;\n\n    for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {\n      sources[_key] = arguments[_key];\n    }\n\n    var C = getSpecies(this);\n    return new C(function (observer) {\n      var subscription;\n      var index = 0;\n\n      function startNext(next) {\n        subscription = next.subscribe({\n          next: function (v) {\n            observer.next(v);\n          },\n          error: function (e) {\n            observer.error(e);\n          },\n          complete: function () {\n            if (index === sources.length) {\n              subscription = undefined;\n              observer.complete();\n            } else {\n              startNext(C.from(sources[index++]));\n            }\n          }\n        });\n      }\n\n      startNext(_this5);\n      return function () {\n        if (subscription) {\n          subscription.unsubscribe();\n          subscription = undefined;\n        }\n      };\n    });\n  };\n\n  _proto3.flatMap = function flatMap(fn) {\n    var _this6 = this;\n\n    if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');\n    var C = getSpecies(this);\n    return new C(function (observer) {\n      var subscriptions = [];\n\n      var outer = _this6.subscribe({\n        next: function (value) {\n          if (fn) {\n            try {\n              value = fn(value);\n            } catch (e) {\n              return observer.error(e);\n            }\n          }\n\n          var inner = C.from(value).subscribe({\n            next: function (value) {\n              observer.next(value);\n            },\n            error: function (e) {\n              observer.error(e);\n            },\n            complete: function () {\n              var i = subscriptions.indexOf(inner);\n              if (i >= 0) subscriptions.splice(i, 1);\n              completeIfDone();\n            }\n          });\n          subscriptions.push(inner);\n        },\n        error: function (e) {\n          observer.error(e);\n        },\n        complete: function () {\n          completeIfDone();\n        }\n      });\n\n      function completeIfDone() {\n        if (outer.closed && subscriptions.length === 0) observer.complete();\n      }\n\n      return function () {\n        subscriptions.forEach(function (s) {\n          return s.unsubscribe();\n        });\n        outer.unsubscribe();\n      };\n    });\n  };\n\n  _proto3[SymbolObservable] = function () {\n    return this;\n  };\n\n  Observable.from = function from(x) {\n    var C = typeof this === 'function' ? this : Observable;\n    if (x == null) throw new TypeError(x + ' is not an object');\n    var method = getMethod(x, SymbolObservable);\n\n    if (method) {\n      var observable = method.call(x);\n      if (Object(observable) !== observable) throw new TypeError(observable + ' is not an object');\n      if (isObservable(observable) && observable.constructor === C) return observable;\n      return new C(function (observer) {\n        return observable.subscribe(observer);\n      });\n    }\n\n    if (hasSymbol('iterator')) {\n      method = getMethod(x, SymbolIterator);\n\n      if (method) {\n        return new C(function (observer) {\n          enqueue(function () {\n            if (observer.closed) return;\n\n            for (var _iterator = _createForOfIteratorHelperLoose(method.call(x)), _step; !(_step = _iterator()).done;) {\n              var item = _step.value;\n              observer.next(item);\n              if (observer.closed) return;\n            }\n\n            observer.complete();\n          });\n        });\n      }\n    }\n\n    if (Array.isArray(x)) {\n      return new C(function (observer) {\n        enqueue(function () {\n          if (observer.closed) return;\n\n          for (var i = 0; i < x.length; ++i) {\n            observer.next(x[i]);\n            if (observer.closed) return;\n          }\n\n          observer.complete();\n        });\n      });\n    }\n\n    throw new TypeError(x + ' is not observable');\n  };\n\n  Observable.of = function of() {\n    for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n      items[_key2] = arguments[_key2];\n    }\n\n    var C = typeof this === 'function' ? this : Observable;\n    return new C(function (observer) {\n      enqueue(function () {\n        if (observer.closed) return;\n\n        for (var i = 0; i < items.length; ++i) {\n          observer.next(items[i]);\n          if (observer.closed) return;\n        }\n\n        observer.complete();\n      });\n    });\n  };\n\n  _createClass(Observable, null, [{\n    key: SymbolSpecies,\n    get: function () {\n      return this;\n    }\n  }]);\n\n  return Observable;\n}();\n\nif (hasSymbols()) {\n  Object.defineProperty(Observable, Symbol('extensions'), {\n    value: {\n      symbol: SymbolObservable,\n      hostReportError: hostReportError\n    },\n    configurable: true\n  });\n}\n\nexport { Observable };\n","export default function symbolObservablePonyfill(root) {\n\tvar result;\n\tvar Symbol = root.Symbol;\n\n\tif (typeof Symbol === 'function') {\n\t\tif (Symbol.observable) {\n\t\t\tresult = Symbol.observable;\n\t\t} else {\n\n\t\t\tif (typeof Symbol.for === 'function') {\n\t\t\t\t// This just needs to be something that won't trample other user's Symbol.for use\n\t\t\t\t// It also will guide people to the source of their issues, if this is problematic.\n\t\t\t\t// META: It's a resource locator!\n\t\t\t\tresult = Symbol.for('https://github.com/benlesh/symbol-observable');\n\t\t\t} else {\n\t\t\t\t// Symbol.for didn't exist! The best we can do at this point is a totally \n\t\t\t\t// unique symbol. Note that the string argument here is a descriptor, not\n\t\t\t\t// an identifier. This symbol is unique.\n\t\t\t\tresult = Symbol('https://github.com/benlesh/symbol-observable');\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tSymbol.observable = result;\n\t\t\t} catch (err) {\n\t\t\t\t// Do nothing. In some environments, users have frozen `Symbol` for security reasons,\n\t\t\t\t// if it is frozen assigning to it will throw. In this case, we don't care, because\n\t\t\t\t// they will need to use the returned value from the ponyfill.\n\t\t\t}\n\t\t}\n\t} else {\n\t\tresult = '@@observable';\n\t}\n\n\treturn result;\n};\n","/* global window */\nimport ponyfill from './ponyfill.js';\n\nvar root;\n\nif (typeof self !== 'undefined') {\n  root = self;\n} else if (typeof window !== 'undefined') {\n  root = window;\n} else if (typeof global !== 'undefined') {\n  root = global;\n} else if (typeof module !== 'undefined') {\n  root = module;\n} else {\n  root = Function('return this')();\n}\n\nvar result = ponyfill(root);\nexport default result;\n","import { Observable } from \"zen-observable-ts\";\n// This simplified polyfill attempts to follow the ECMAScript Observable\n// proposal (https://github.com/zenparsing/es-observable)\nimport \"symbol-observable\";\n// The zen-observable package defines Observable.prototype[Symbol.observable]\n// when Symbol is supported, but RxJS interop depends on also setting this fake\n// '@@observable' string as a polyfill for Symbol.observable.\nvar prototype = Observable.prototype;\nvar fakeObsSymbol = \"@@observable\";\nif (!prototype[fakeObsSymbol]) {\n    // @ts-expect-error\n    prototype[fakeObsSymbol] = function () {\n        return this;\n    };\n}\nexport { Observable };\n//# sourceMappingURL=Observable.js.map","var toString = Object.prototype.toString;\n/**\n * Deeply clones a value to create a new instance.\n */\nexport function cloneDeep(value) {\n    return cloneDeepHelper(value);\n}\nfunction cloneDeepHelper(val, seen) {\n    switch (toString.call(val)) {\n        case \"[object Array]\": {\n            seen = seen || new Map();\n            if (seen.has(val))\n                return seen.get(val);\n            var copy_1 = val.slice(0);\n            seen.set(val, copy_1);\n            copy_1.forEach(function (child, i) {\n                copy_1[i] = cloneDeepHelper(child, seen);\n            });\n            return copy_1;\n        }\n        case \"[object Object]\": {\n            seen = seen || new Map();\n            if (seen.has(val))\n                return seen.get(val);\n            // High fidelity polyfills of Object.create and Object.getPrototypeOf are\n            // possible in all JS environments, so we will assume they exist/work.\n            var copy_2 = Object.create(Object.getPrototypeOf(val));\n            seen.set(val, copy_2);\n            Object.keys(val).forEach(function (key) {\n                copy_2[key] = cloneDeepHelper(val[key], seen);\n            });\n            return copy_2;\n        }\n        default:\n            return val;\n    }\n}\n//# sourceMappingURL=cloneDeep.js.map","import { isNonNullObject } from \"./objects.js\";\nfunction deepFreeze(value) {\n    var workSet = new Set([value]);\n    workSet.forEach(function (obj) {\n        if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {\n            Object.getOwnPropertyNames(obj).forEach(function (name) {\n                if (isNonNullObject(obj[name]))\n                    workSet.add(obj[name]);\n            });\n        }\n    });\n    return value;\n}\nfunction shallowFreeze(obj) {\n    if (globalThis.__DEV__ !== false && !Object.isFrozen(obj)) {\n        try {\n            Object.freeze(obj);\n        }\n        catch (e) {\n            // Some types like Uint8Array and Node.js's Buffer cannot be frozen, but\n            // they all throw a TypeError when you try, so we re-throw any exceptions\n            // that are not TypeErrors, since that would be unexpected.\n            if (e instanceof TypeError)\n                return null;\n            throw e;\n        }\n    }\n    return obj;\n}\nexport function maybeDeepFreeze(obj) {\n    if (globalThis.__DEV__ !== false) {\n        deepFreeze(obj);\n    }\n    return obj;\n}\n//# sourceMappingURL=maybeDeepFreeze.js.map","export function iterateObserversSafely(observers, method, argument) {\n    // In case observers is modified during iteration, we need to commit to the\n    // original elements, which also provides an opportunity to filter them down\n    // to just the observers with the given method.\n    var observersWithMethod = [];\n    observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });\n    observersWithMethod.forEach(function (obs) { return obs[method](argument); });\n}\n//# sourceMappingURL=iteration.js.map","import { Observable } from \"./Observable.js\";\n// Like Observable.prototype.map, except that the mapping function can\n// optionally return a Promise (or be async).\nexport function asyncMap(observable, mapFn, catchFn) {\n    return new Observable(function (observer) {\n        var promiseQueue = {\n            // Normally we would initialize promiseQueue to Promise.resolve(), but\n            // in this case, for backwards compatibility, we need to be careful to\n            // invoke the first callback synchronously.\n            then: function (callback) {\n                return new Promise(function (resolve) { return resolve(callback()); });\n            },\n        };\n        function makeCallback(examiner, key) {\n            return function (arg) {\n                if (examiner) {\n                    var both = function () {\n                        // If the observer is closed, we don't want to continue calling the\n                        // mapping function - it's result will be swallowed anyways.\n                        return observer.closed ?\n                            /* will be swallowed */ 0\n                            : examiner(arg);\n                    };\n                    promiseQueue = promiseQueue.then(both, both).then(function (result) { return observer.next(result); }, function (error) { return observer.error(error); });\n                }\n                else {\n                    observer[key](arg);\n                }\n            };\n        }\n        var handler = {\n            next: makeCallback(mapFn, \"next\"),\n            error: makeCallback(catchFn, \"error\"),\n            complete: function () {\n                // no need to reassign `promiseQueue`, after `observer.complete`,\n                // the observer will be closed and short-circuit everything anyways\n                /*promiseQueue = */ promiseQueue.then(function () { return observer.complete(); });\n            },\n        };\n        var sub = observable.subscribe(handler);\n        return function () { return sub.unsubscribe(); };\n    });\n}\n//# sourceMappingURL=asyncMap.js.map","import { Observable } from \"./Observable.js\";\nimport { canUseSymbol } from \"../common/canUse.js\";\n// Generic implementations of Observable.prototype methods like map and\n// filter need to know how to create a new Observable from an Observable\n// subclass (like Concast or ObservableQuery). Those methods assume\n// (perhaps unwisely?) that they can call the subtype's constructor with a\n// Subscriber function, even though the subclass constructor might expect\n// different parameters. Defining this static Symbol.species property on\n// the subclass is a hint to generic Observable code to use the default\n// constructor instead of trying to do `new Subclass(observer => ...)`.\nexport function fixObservableSubclass(subclass) {\n    function set(key) {\n        // Object.defineProperty is necessary because the Symbol.species\n        // property is a getter by default in modern JS environments, so we\n        // can't assign to it with a normal assignment expression.\n        Object.defineProperty(subclass, key, { value: Observable });\n    }\n    if (canUseSymbol && Symbol.species) {\n        set(Symbol.species);\n    }\n    // The \"@@species\" string is used as a fake Symbol.species value in some\n    // polyfill systems (including the SymbolSpecies variable used by\n    // zen-observable), so we should set it as well, to be safe.\n    set(\"@@species\");\n    return subclass;\n}\n//# sourceMappingURL=subclassing.js.map","import { __extends } from \"tslib\";\nimport { Observable } from \"./Observable.js\";\nimport { iterateObserversSafely } from \"./iteration.js\";\nimport { fixObservableSubclass } from \"./subclassing.js\";\nfunction isPromiseLike(value) {\n    return value && typeof value.then === \"function\";\n}\n// A Concast<T> observable concatenates the given sources into a single\n// non-overlapping sequence of Ts, automatically unwrapping any promises,\n// and broadcasts the T elements of that sequence to any number of\n// subscribers, all without creating a bunch of intermediary Observable\n// wrapper objects.\n//\n// Even though any number of observers can subscribe to the Concast, each\n// source observable is guaranteed to receive at most one subscribe call,\n// and the results are multicast to all observers.\n//\n// In addition to broadcasting every next/error message to this.observers,\n// the Concast stores the most recent message using this.latest, so any\n// new observers can immediately receive the latest message, even if it\n// was originally delivered in the past. This behavior means we can assume\n// every active observer in this.observers has received the same most\n// recent message.\n//\n// With the exception of this.latest replay, a Concast is a \"hot\"\n// observable in the sense that it does not replay past results from the\n// beginning of time for each new observer.\n//\n// Could we have used some existing RxJS class instead? Concast<T> is\n// similar to a BehaviorSubject<T>, because it is multicast and redelivers\n// the latest next/error message to new subscribers. Unlike Subject<T>,\n// Concast<T> does not expose an Observer<T> interface (this.handlers is\n// intentionally private), since Concast<T> gets its inputs from the\n// concatenated sources. If we ever switch to RxJS, there may be some\n// value in reusing their code, but for now we use zen-observable, which\n// does not contain any Subject implementations.\nvar Concast = /** @class */ (function (_super) {\n    __extends(Concast, _super);\n    // Not only can the individual elements of the iterable be promises, but\n    // also the iterable itself can be wrapped in a promise.\n    function Concast(sources) {\n        var _this = _super.call(this, function (observer) {\n            _this.addObserver(observer);\n            return function () { return _this.removeObserver(observer); };\n        }) || this;\n        // Active observers receiving broadcast messages. Thanks to this.latest,\n        // we can assume all observers in this Set have received the same most\n        // recent message, though possibly at different times in the past.\n        _this.observers = new Set();\n        _this.promise = new Promise(function (resolve, reject) {\n            _this.resolve = resolve;\n            _this.reject = reject;\n        });\n        // Bound handler functions that can be reused for every internal\n        // subscription.\n        _this.handlers = {\n            next: function (result) {\n                if (_this.sub !== null) {\n                    _this.latest = [\"next\", result];\n                    _this.notify(\"next\", result);\n                    iterateObserversSafely(_this.observers, \"next\", result);\n                }\n            },\n            error: function (error) {\n                var sub = _this.sub;\n                if (sub !== null) {\n                    // Delay unsubscribing from the underlying subscription slightly,\n                    // so that immediately subscribing another observer can keep the\n                    // subscription active.\n                    if (sub)\n                        setTimeout(function () { return sub.unsubscribe(); });\n                    _this.sub = null;\n                    _this.latest = [\"error\", error];\n                    _this.reject(error);\n                    _this.notify(\"error\", error);\n                    iterateObserversSafely(_this.observers, \"error\", error);\n                }\n            },\n            complete: function () {\n                var _a = _this, sub = _a.sub, _b = _a.sources, sources = _b === void 0 ? [] : _b;\n                if (sub !== null) {\n                    // If complete is called before concast.start, this.sources may be\n                    // undefined, so we use a default value of [] for sources. That works\n                    // here because it falls into the if (!value) {...} block, which\n                    // appropriately terminates the Concast, even if this.sources might\n                    // eventually have been initialized to a non-empty array.\n                    var value = sources.shift();\n                    if (!value) {\n                        if (sub)\n                            setTimeout(function () { return sub.unsubscribe(); });\n                        _this.sub = null;\n                        if (_this.latest && _this.latest[0] === \"next\") {\n                            _this.resolve(_this.latest[1]);\n                        }\n                        else {\n                            _this.resolve();\n                        }\n                        _this.notify(\"complete\");\n                        // We do not store this.latest = [\"complete\"], because doing so\n                        // discards useful information about the previous next (or\n                        // error) message. Instead, if new observers subscribe after\n                        // this Concast has completed, they will receive the final\n                        // 'next' message (unless there was an error) immediately\n                        // followed by a 'complete' message (see addObserver).\n                        iterateObserversSafely(_this.observers, \"complete\");\n                    }\n                    else if (isPromiseLike(value)) {\n                        value.then(function (obs) { return (_this.sub = obs.subscribe(_this.handlers)); }, _this.handlers.error);\n                    }\n                    else {\n                        _this.sub = value.subscribe(_this.handlers);\n                    }\n                }\n            },\n        };\n        _this.nextResultListeners = new Set();\n        // A public way to abort observation and broadcast.\n        _this.cancel = function (reason) {\n            _this.reject(reason);\n            _this.sources = [];\n            _this.handlers.error(reason);\n        };\n        // Suppress rejection warnings for this.promise, since it's perfectly\n        // acceptable to pay no attention to this.promise if you're consuming\n        // the results through the normal observable API.\n        _this.promise.catch(function (_) { });\n        // If someone accidentally tries to create a Concast using a subscriber\n        // function, recover by creating an Observable from that subscriber and\n        // using it as the source.\n        if (typeof sources === \"function\") {\n            sources = [new Observable(sources)];\n        }\n        if (isPromiseLike(sources)) {\n            sources.then(function (iterable) { return _this.start(iterable); }, _this.handlers.error);\n        }\n        else {\n            _this.start(sources);\n        }\n        return _this;\n    }\n    Concast.prototype.start = function (sources) {\n        if (this.sub !== void 0)\n            return;\n        // In practice, sources is most often simply an Array of observables.\n        // TODO Consider using sources[Symbol.iterator]() to take advantage\n        // of the laziness of non-Array iterables.\n        this.sources = Array.from(sources);\n        // Calling this.handlers.complete() kicks off consumption of the first\n        // source observable. It's tempting to do this step lazily in\n        // addObserver, but this.promise can be accessed without calling\n        // addObserver, so consumption needs to begin eagerly.\n        this.handlers.complete();\n    };\n    Concast.prototype.deliverLastMessage = function (observer) {\n        if (this.latest) {\n            var nextOrError = this.latest[0];\n            var method = observer[nextOrError];\n            if (method) {\n                method.call(observer, this.latest[1]);\n            }\n            // If the subscription is already closed, and the last message was\n            // a 'next' message, simulate delivery of the final 'complete'\n            // message again.\n            if (this.sub === null && nextOrError === \"next\" && observer.complete) {\n                observer.complete();\n            }\n        }\n    };\n    Concast.prototype.addObserver = function (observer) {\n        if (!this.observers.has(observer)) {\n            // Immediately deliver the most recent message, so we can always\n            // be sure all observers have the latest information.\n            this.deliverLastMessage(observer);\n            this.observers.add(observer);\n        }\n    };\n    Concast.prototype.removeObserver = function (observer) {\n        if (this.observers.delete(observer) && this.observers.size < 1) {\n            // In case there are still any listeners in this.nextResultListeners, and\n            // no error or completion has been broadcast yet, make sure those\n            // observers have a chance to run and then remove themselves from\n            // this.observers.\n            this.handlers.complete();\n        }\n    };\n    Concast.prototype.notify = function (method, arg) {\n        var nextResultListeners = this.nextResultListeners;\n        if (nextResultListeners.size) {\n            // Replacing this.nextResultListeners first ensures it does not grow while\n            // we are iterating over it, potentially leading to infinite loops.\n            this.nextResultListeners = new Set();\n            nextResultListeners.forEach(function (listener) { return listener(method, arg); });\n        }\n    };\n    // We need a way to run callbacks just *before* the next result (or error or\n    // completion) is delivered by this Concast, so we can be sure any code that\n    // runs as a result of delivering that result/error observes the effects of\n    // running the callback(s). It was tempting to reuse the Observer type instead\n    // of introducing NextResultListener, but that messes with the sizing and\n    // maintenance of this.observers, and ends up being more code overall.\n    Concast.prototype.beforeNext = function (callback) {\n        var called = false;\n        this.nextResultListeners.add(function (method, arg) {\n            if (!called) {\n                called = true;\n                callback(method, arg);\n            }\n        });\n    };\n    return Concast;\n}(Observable));\nexport { Concast };\n// Necessary because the Concast constructor has a different signature\n// than the Observable constructor.\nfixObservableSubclass(Concast);\n//# sourceMappingURL=Concast.js.map","import { isNonNullObject } from \"./objects.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { DeepMerger } from \"./mergeDeep.js\";\nexport function isExecutionPatchIncrementalResult(value) {\n    return \"incremental\" in value;\n}\nexport function isExecutionPatchInitialResult(value) {\n    return \"hasNext\" in value && \"data\" in value;\n}\nexport function isExecutionPatchResult(value) {\n    return (isExecutionPatchIncrementalResult(value) ||\n        isExecutionPatchInitialResult(value));\n}\n// This function detects an Apollo payload result before it is transformed\n// into a FetchResult via HttpLink; it cannot detect an ApolloPayloadResult\n// once it leaves the link chain.\nexport function isApolloPayloadResult(value) {\n    return isNonNullObject(value) && \"payload\" in value;\n}\nexport function mergeIncrementalData(prevResult, result) {\n    var mergedData = prevResult;\n    var merger = new DeepMerger();\n    if (isExecutionPatchIncrementalResult(result) &&\n        isNonEmptyArray(result.incremental)) {\n        result.incremental.forEach(function (_a) {\n            var data = _a.data, path = _a.path;\n            for (var i = path.length - 1; i >= 0; --i) {\n                var key = path[i];\n                var isNumericKey = !isNaN(+key);\n                var parent_1 = isNumericKey ? [] : {};\n                parent_1[key] = data;\n                data = parent_1;\n            }\n            mergedData = merger.merge(mergedData, data);\n        });\n    }\n    return mergedData;\n}\n//# sourceMappingURL=incrementalResult.js.map","import { isNonEmptyArray } from \"./arrays.js\";\nimport { isExecutionPatchIncrementalResult } from \"./incrementalResult.js\";\nexport function graphQLResultHasError(result) {\n    var errors = getGraphQLErrorsFromResult(result);\n    return isNonEmptyArray(errors);\n}\nexport function getGraphQLErrorsFromResult(result) {\n    var graphQLErrors = isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\n    if (isExecutionPatchIncrementalResult(result) &&\n        isNonEmptyArray(result.incremental)) {\n        result.incremental.forEach(function (incrementalResult) {\n            if (incrementalResult.errors) {\n                graphQLErrors.push.apply(graphQLErrors, incrementalResult.errors);\n            }\n        });\n    }\n    return graphQLErrors;\n}\n//# sourceMappingURL=errorHandling.js.map","/**\n * Merges the provided objects shallowly and removes\n * all properties with an `undefined` value\n */\nexport function compact() {\n    var objects = [];\n    for (var _i = 0; _i < arguments.length; _i++) {\n        objects[_i] = arguments[_i];\n    }\n    var result = Object.create(null);\n    objects.forEach(function (obj) {\n        if (!obj)\n            return;\n        Object.keys(obj).forEach(function (key) {\n            var value = obj[key];\n            if (value !== void 0) {\n                result[key] = value;\n            }\n        });\n    });\n    return result;\n}\n//# sourceMappingURL=compact.js.map","import { __assign } from \"tslib\";\nimport { compact } from \"./compact.js\";\nexport function mergeOptions(defaults, options) {\n    return compact(defaults, options, options.variables && {\n        variables: compact(__assign(__assign({}, (defaults && defaults.variables)), options.variables)),\n    });\n}\n//# sourceMappingURL=mergeOptions.js.map","import { Observable } from \"../../utilities/index.js\";\nexport function fromError(errorValue) {\n    return new Observable(function (observer) {\n        observer.error(errorValue);\n    });\n}\n//# sourceMappingURL=fromError.js.map","export var throwServerError = function (response, result, message) {\n    var error = new Error(message);\n    error.name = \"ServerError\";\n    error.response = response;\n    error.statusCode = response.status;\n    error.result = result;\n    throw error;\n};\n//# sourceMappingURL=throwServerError.js.map","import { newInvariantError, invariant } from \"../../utilities/globals/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nimport { validateOperation, createOperation, transformOperation, } from \"../utils/index.js\";\nfunction passthrough(op, forward) {\n    return (forward ? forward(op) : Observable.of());\n}\nfunction toLink(handler) {\n    return typeof handler === \"function\" ? new ApolloLink(handler) : handler;\n}\nfunction isTerminating(link) {\n    return link.request.length <= 1;\n}\nvar ApolloLink = /** @class */ (function () {\n    function ApolloLink(request) {\n        if (request)\n            this.request = request;\n    }\n    ApolloLink.empty = function () {\n        return new ApolloLink(function () { return Observable.of(); });\n    };\n    ApolloLink.from = function (links) {\n        if (links.length === 0)\n            return ApolloLink.empty();\n        return links.map(toLink).reduce(function (x, y) { return x.concat(y); });\n    };\n    ApolloLink.split = function (test, left, right) {\n        var leftLink = toLink(left);\n        var rightLink = toLink(right || new ApolloLink(passthrough));\n        var ret;\n        if (isTerminating(leftLink) && isTerminating(rightLink)) {\n            ret = new ApolloLink(function (operation) {\n                return test(operation) ?\n                    leftLink.request(operation) || Observable.of()\n                    : rightLink.request(operation) || Observable.of();\n            });\n        }\n        else {\n            ret = new ApolloLink(function (operation, forward) {\n                return test(operation) ?\n                    leftLink.request(operation, forward) || Observable.of()\n                    : rightLink.request(operation, forward) || Observable.of();\n            });\n        }\n        return Object.assign(ret, { left: leftLink, right: rightLink });\n    };\n    ApolloLink.execute = function (link, operation) {\n        return (link.request(createOperation(operation.context, transformOperation(validateOperation(operation)))) || Observable.of());\n    };\n    ApolloLink.concat = function (first, second) {\n        var firstLink = toLink(first);\n        if (isTerminating(firstLink)) {\n            globalThis.__DEV__ !== false && invariant.warn(36, firstLink);\n            return firstLink;\n        }\n        var nextLink = toLink(second);\n        var ret;\n        if (isTerminating(nextLink)) {\n            ret = new ApolloLink(function (operation) {\n                return firstLink.request(operation, function (op) { return nextLink.request(op) || Observable.of(); }) || Observable.of();\n            });\n        }\n        else {\n            ret = new ApolloLink(function (operation, forward) {\n                return (firstLink.request(operation, function (op) {\n                    return nextLink.request(op, forward) || Observable.of();\n                }) || Observable.of());\n            });\n        }\n        return Object.assign(ret, { left: firstLink, right: nextLink });\n    };\n    ApolloLink.prototype.split = function (test, left, right) {\n        return this.concat(ApolloLink.split(test, left, right || new ApolloLink(passthrough)));\n    };\n    ApolloLink.prototype.concat = function (next) {\n        return ApolloLink.concat(this, next);\n    };\n    ApolloLink.prototype.request = function (operation, forward) {\n        throw newInvariantError(37);\n    };\n    ApolloLink.prototype.onError = function (error, observer) {\n        if (observer && observer.error) {\n            observer.error(error);\n            // Returning false indicates that observer.error does not need to be\n            // called again, since it was already called (on the previous line).\n            // Calling observer.error again would not cause any real problems,\n            // since only the first call matters, but custom onError functions\n            // might have other reasons for wanting to prevent the default\n            // behavior by returning false.\n            return false;\n        }\n        // Throw errors will be passed to observer.error.\n        throw error;\n    };\n    ApolloLink.prototype.setOnError = function (fn) {\n        this.onError = fn;\n        return this;\n    };\n    return ApolloLink;\n}());\nexport { ApolloLink };\n//# sourceMappingURL=ApolloLink.js.map","import { __assign } from \"tslib\";\nexport function createOperation(starting, operation) {\n    var context = __assign({}, starting);\n    var setContext = function (next) {\n        if (typeof next === \"function\") {\n            context = __assign(__assign({}, context), next(context));\n        }\n        else {\n            context = __assign(__assign({}, context), next);\n        }\n    };\n    var getContext = function () { return (__assign({}, context)); };\n    Object.defineProperty(operation, \"setContext\", {\n        enumerable: false,\n        value: setContext,\n    });\n    Object.defineProperty(operation, \"getContext\", {\n        enumerable: false,\n        value: getContext,\n    });\n    return operation;\n}\n//# sourceMappingURL=createOperation.js.map","import { getOperationName } from \"../../utilities/index.js\";\nexport function transformOperation(operation) {\n    var transformedOperation = {\n        variables: operation.variables || {},\n        extensions: operation.extensions || {},\n        operationName: operation.operationName,\n        query: operation.query,\n    };\n    // Best guess at an operation name\n    if (!transformedOperation.operationName) {\n        transformedOperation.operationName =\n            typeof transformedOperation.query !== \"string\" ?\n                getOperationName(transformedOperation.query) || undefined\n                : \"\";\n    }\n    return transformedOperation;\n}\n//# sourceMappingURL=transformOperation.js.map","import { newInvariantError } from \"../../utilities/globals/index.js\";\nexport function validateOperation(operation) {\n    var OPERATION_FIELDS = [\n        \"query\",\n        \"operationName\",\n        \"variables\",\n        \"extensions\",\n        \"context\",\n    ];\n    for (var _i = 0, _a = Object.keys(operation); _i < _a.length; _i++) {\n        var key = _a[_i];\n        if (OPERATION_FIELDS.indexOf(key) < 0) {\n            throw newInvariantError(44, key);\n        }\n    }\n    return operation;\n}\n//# sourceMappingURL=validateOperation.js.map","import { ApolloLink } from \"./ApolloLink.js\";\nexport var from = ApolloLink.from;\n//# sourceMappingURL=from.js.map","import { ApolloLink } from \"./ApolloLink.js\";\nexport var execute = ApolloLink.execute;\n//# sourceMappingURL=execute.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/reader.ts\n */\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\nexport default function readerIterator(reader) {\n    var iterator = {\n        next: function () {\n            return reader.read();\n        },\n    };\n    if (canUseAsyncIteratorSymbol) {\n        iterator[Symbol.asyncIterator] = function () {\n            return this;\n        };\n    }\n    return iterator;\n}\n//# sourceMappingURL=reader.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/index.ts\n */\nimport { canUseAsyncIteratorSymbol } from \"../../utilities/index.js\";\nimport asyncIterator from \"./iterators/async.js\";\nimport nodeStreamIterator from \"./iterators/nodeStream.js\";\nimport promiseIterator from \"./iterators/promise.js\";\nimport readerIterator from \"./iterators/reader.js\";\nfunction isNodeResponse(value) {\n    return !!value.body;\n}\nfunction isReadableStream(value) {\n    return !!value.getReader;\n}\nfunction isAsyncIterableIterator(value) {\n    return !!(canUseAsyncIteratorSymbol &&\n        value[Symbol.asyncIterator]);\n}\nfunction isStreamableBlob(value) {\n    return !!value.stream;\n}\nfunction isBlob(value) {\n    return !!value.arrayBuffer;\n}\nfunction isNodeReadableStream(value) {\n    return !!value.pipe;\n}\nexport function responseIterator(response) {\n    var body = response;\n    if (isNodeResponse(response))\n        body = response.body;\n    if (isAsyncIterableIterator(body))\n        return asyncIterator(body);\n    if (isReadableStream(body))\n        return readerIterator(body.getReader());\n    // this errors without casting to ReadableStream<T>\n    // because Blob.stream() returns a NodeJS ReadableStream\n    if (isStreamableBlob(body)) {\n        return readerIterator(body.stream().getReader());\n    }\n    if (isBlob(body))\n        return promiseIterator(body.arrayBuffer());\n    if (isNodeReadableStream(body))\n        return nodeStreamIterator(body);\n    throw new Error(\"Unknown body type for responseIterator. Please pass a streamable response.\");\n}\n//# sourceMappingURL=responseIterator.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/promise.ts\n */\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\nexport default function promiseIterator(promise) {\n    var resolved = false;\n    var iterator = {\n        next: function () {\n            if (resolved)\n                return Promise.resolve({\n                    value: undefined,\n                    done: true,\n                });\n            resolved = true;\n            return new Promise(function (resolve, reject) {\n                promise\n                    .then(function (value) {\n                    resolve({ value: value, done: false });\n                })\n                    .catch(reject);\n            });\n        },\n    };\n    if (canUseAsyncIteratorSymbol) {\n        iterator[Symbol.asyncIterator] = function () {\n            return this;\n        };\n    }\n    return iterator;\n}\n//# sourceMappingURL=promise.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts\n */\nexport default function asyncIterator(source) {\n    var _a;\n    var iterator = source[Symbol.asyncIterator]();\n    return _a = {\n            next: function () {\n                return iterator.next();\n            }\n        },\n        _a[Symbol.asyncIterator] = function () {\n            return this;\n        },\n        _a;\n}\n//# sourceMappingURL=async.js.map","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/nodeStream.ts\n */\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\nexport default function nodeStreamIterator(stream) {\n    var cleanup = null;\n    var error = null;\n    var done = false;\n    var data = [];\n    var waiting = [];\n    function onData(chunk) {\n        if (error)\n            return;\n        if (waiting.length) {\n            var shiftedArr = waiting.shift();\n            if (Array.isArray(shiftedArr) && shiftedArr[0]) {\n                return shiftedArr[0]({ value: chunk, done: false });\n            }\n        }\n        data.push(chunk);\n    }\n    function onError(err) {\n        error = err;\n        var all = waiting.slice();\n        all.forEach(function (pair) {\n            pair[1](err);\n        });\n        !cleanup || cleanup();\n    }\n    function onEnd() {\n        done = true;\n        var all = waiting.slice();\n        all.forEach(function (pair) {\n            pair[0]({ value: undefined, done: true });\n        });\n        !cleanup || cleanup();\n    }\n    cleanup = function () {\n        cleanup = null;\n        stream.removeListener(\"data\", onData);\n        stream.removeListener(\"error\", onError);\n        stream.removeListener(\"end\", onEnd);\n        stream.removeListener(\"finish\", onEnd);\n        stream.removeListener(\"close\", onEnd);\n    };\n    stream.on(\"data\", onData);\n    stream.on(\"error\", onError);\n    stream.on(\"end\", onEnd);\n    stream.on(\"finish\", onEnd);\n    stream.on(\"close\", onEnd);\n    function getNext() {\n        return new Promise(function (resolve, reject) {\n            if (error)\n                return reject(error);\n            if (data.length)\n                return resolve({ value: data.shift(), done: false });\n            if (done)\n                return resolve({ value: undefined, done: true });\n            waiting.push([resolve, reject]);\n        });\n    }\n    var iterator = {\n        next: function () {\n            return getNext();\n        },\n    };\n    if (canUseAsyncIteratorSymbol) {\n        iterator[Symbol.asyncIterator] = function () {\n            return this;\n        };\n    }\n    return iterator;\n}\n//# sourceMappingURL=nodeStream.js.map","import { __extends, __spreadArray } from \"tslib\";\nimport \"../utilities/globals/index.js\";\nimport { isNonNullObject } from \"../utilities/index.js\";\n// This Symbol allows us to pass transport-specific errors from the link chain\n// into QueryManager/client internals without risking a naming collision within\n// extensions (which implementers can use as they see fit).\nexport var PROTOCOL_ERRORS_SYMBOL = Symbol();\nexport function graphQLResultHasProtocolErrors(result) {\n    if (result.extensions) {\n        return Array.isArray(result.extensions[PROTOCOL_ERRORS_SYMBOL]);\n    }\n    return false;\n}\nexport function isApolloError(err) {\n    return err.hasOwnProperty(\"graphQLErrors\");\n}\n// Sets the error message on this error according to the\n// the GraphQL and network errors that are present.\n// If the error message has already been set through the\n// constructor or otherwise, this function is a nop.\nvar generateErrorMessage = function (err) {\n    var errors = __spreadArray(__spreadArray(__spreadArray([], err.graphQLErrors, true), err.clientErrors, true), err.protocolErrors, true);\n    if (err.networkError)\n        errors.push(err.networkError);\n    return (errors\n        // The rest of the code sometimes unsafely types non-Error objects as GraphQLErrors\n        .map(function (err) {\n        return (isNonNullObject(err) && err.message) || \"Error message not found.\";\n    })\n        .join(\"\\n\"));\n};\nvar ApolloError = /** @class */ (function (_super) {\n    __extends(ApolloError, _super);\n    // Constructs an instance of ApolloError given serialized GraphQL errors,\n    // client errors, protocol errors or network errors.\n    // Note that one of these has to be a valid\n    // value or the constructed error will be meaningless.\n    function ApolloError(_a) {\n        var graphQLErrors = _a.graphQLErrors, protocolErrors = _a.protocolErrors, clientErrors = _a.clientErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;\n        var _this = _super.call(this, errorMessage) || this;\n        _this.name = \"ApolloError\";\n        _this.graphQLErrors = graphQLErrors || [];\n        _this.protocolErrors = protocolErrors || [];\n        _this.clientErrors = clientErrors || [];\n        _this.networkError = networkError || null;\n        _this.message = errorMessage || generateErrorMessage(_this);\n        _this.extraInfo = extraInfo;\n        _this.cause =\n            __spreadArray(__spreadArray(__spreadArray([\n                networkError\n            ], (graphQLErrors || []), true), (protocolErrors || []), true), (clientErrors || []), true).find(function (e) { return !!e; }) || null;\n        // We're not using `Object.setPrototypeOf` here as it isn't fully\n        // supported on Android (see issue #3236).\n        _this.__proto__ = ApolloError.prototype;\n        return _this;\n    }\n    return ApolloError;\n}(Error));\nexport { ApolloError };\n//# sourceMappingURL=index.js.map","import { __assign, __awaiter, __generator } from \"tslib\";\nimport { responseIterator } from \"./responseIterator.js\";\nimport { throwServerError } from \"../utils/index.js\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"../../errors/index.js\";\nimport { isApolloPayloadResult } from \"../../utilities/common/incrementalResult.js\";\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function readMultipartBody(response, nextValue) {\n    return __awaiter(this, void 0, void 0, function () {\n        var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _a, value, done, chunk, searchFrom, bi, message, i, headers, contentType_1, body, result, next;\n        var _b, _c;\n        var _d;\n        return __generator(this, function (_e) {\n            switch (_e.label) {\n                case 0:\n                    if (TextDecoder === undefined) {\n                        throw new Error(\"TextDecoder must be defined in the environment: please import a polyfill.\");\n                    }\n                    decoder = new TextDecoder(\"utf-8\");\n                    contentType = (_d = response.headers) === null || _d === void 0 ? void 0 : _d.get(\"content-type\");\n                    delimiter = \"boundary=\";\n                    boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter)) ?\n                        contentType === null || contentType === void 0 ? void 0 : contentType.substring((contentType === null || contentType === void 0 ? void 0 : contentType.indexOf(delimiter)) + delimiter.length).replace(/['\"]/g, \"\").replace(/\\;(.*)/gm, \"\").trim()\n                        : \"-\";\n                    boundary = \"\\r\\n--\".concat(boundaryVal);\n                    buffer = \"\";\n                    iterator = responseIterator(response);\n                    running = true;\n                    _e.label = 1;\n                case 1:\n                    if (!running) return [3 /*break*/, 3];\n                    return [4 /*yield*/, iterator.next()];\n                case 2:\n                    _a = _e.sent(), value = _a.value, done = _a.done;\n                    chunk = typeof value === \"string\" ? value : decoder.decode(value);\n                    searchFrom = buffer.length - boundary.length + 1;\n                    running = !done;\n                    buffer += chunk;\n                    bi = buffer.indexOf(boundary, searchFrom);\n                    while (bi > -1) {\n                        message = void 0;\n                        _b = [\n                            buffer.slice(0, bi),\n                            buffer.slice(bi + boundary.length),\n                        ], message = _b[0], buffer = _b[1];\n                        i = message.indexOf(\"\\r\\n\\r\\n\");\n                        headers = parseHeaders(message.slice(0, i));\n                        contentType_1 = headers[\"content-type\"];\n                        if (contentType_1 &&\n                            contentType_1.toLowerCase().indexOf(\"application/json\") === -1) {\n                            throw new Error(\"Unsupported patch content type: application/json is required.\");\n                        }\n                        body = message.slice(i);\n                        if (body) {\n                            result = parseJsonBody(response, body);\n                            if (Object.keys(result).length > 1 ||\n                                \"data\" in result ||\n                                \"incremental\" in result ||\n                                \"errors\" in result ||\n                                \"payload\" in result) {\n                                if (isApolloPayloadResult(result)) {\n                                    next = {};\n                                    if (\"payload\" in result) {\n                                        if (Object.keys(result).length === 1 && result.payload === null) {\n                                            return [2 /*return*/];\n                                        }\n                                        next = __assign({}, result.payload);\n                                    }\n                                    if (\"errors\" in result) {\n                                        next = __assign(__assign({}, next), { extensions: __assign(__assign({}, (\"extensions\" in next ? next.extensions : null)), (_c = {}, _c[PROTOCOL_ERRORS_SYMBOL] = result.errors, _c)) });\n                                    }\n                                    nextValue(next);\n                                }\n                                else {\n                                    // for the last chunk with only `hasNext: false`\n                                    // we don't need to call observer.next as there is no data/errors\n                                    nextValue(result);\n                                }\n                            }\n                            else if (\n                            // If the chunk contains only a \"hasNext: false\", we can call\n                            // observer.complete() immediately.\n                            Object.keys(result).length === 1 &&\n                                \"hasNext\" in result &&\n                                !result.hasNext) {\n                                return [2 /*return*/];\n                            }\n                        }\n                        bi = buffer.indexOf(boundary);\n                    }\n                    return [3 /*break*/, 1];\n                case 3: return [2 /*return*/];\n            }\n        });\n    });\n}\nexport function parseHeaders(headerText) {\n    var headersInit = {};\n    headerText.split(\"\\n\").forEach(function (line) {\n        var i = line.indexOf(\":\");\n        if (i > -1) {\n            // normalize headers to lowercase\n            var name_1 = line.slice(0, i).trim().toLowerCase();\n            var value = line.slice(i + 1).trim();\n            headersInit[name_1] = value;\n        }\n    });\n    return headersInit;\n}\nexport function parseJsonBody(response, bodyText) {\n    if (response.status >= 300) {\n        // Network error\n        var getResult = function () {\n            try {\n                return JSON.parse(bodyText);\n            }\n            catch (err) {\n                return bodyText;\n            }\n        };\n        throwServerError(response, getResult(), \"Response not successful: Received status code \".concat(response.status));\n    }\n    try {\n        return JSON.parse(bodyText);\n    }\n    catch (err) {\n        var parseError = err;\n        parseError.name = \"ServerParseError\";\n        parseError.response = response;\n        parseError.statusCode = response.status;\n        parseError.bodyText = bodyText;\n        throw parseError;\n    }\n}\nexport function handleError(err, observer) {\n    // if it is a network error, BUT there is graphql result info fire\n    // the next observer before calling error this gives apollo-client\n    // (and react-apollo) the `graphqlErrors` and `networkErrors` to\n    // pass to UI this should only happen if we *also* have data as\n    // part of the response key per the spec\n    if (err.result && err.result.errors && err.result.data) {\n        // if we don't call next, the UI can only show networkError\n        // because AC didn't get any graphqlErrors this is graphql\n        // execution result info (i.e errors and possibly data) this is\n        // because there is no formal spec how errors should translate to\n        // http status codes. So an auth error (401) could have both data\n        // from a public field, errors from a private field, and a status\n        // of 401\n        // {\n        //  user { // this will have errors\n        //    firstName\n        //  }\n        //  products { // this is public so will have data\n        //    cost\n        //  }\n        // }\n        //\n        // the result of above *could* look like this:\n        // {\n        //   data: { products: [{ cost: \"$10\" }] },\n        //   errors: [{\n        //      message: 'your session has timed out',\n        //      path: []\n        //   }]\n        // }\n        // status code of above would be a 401\n        // in the UI you want to show data where you can, errors as data where you can\n        // and use correct http status codes\n        observer.next(err.result);\n    }\n    observer.error(err);\n}\nexport function parseAndCheckHttpResponse(operations) {\n    return function (response) {\n        return response\n            .text()\n            .then(function (bodyText) { return parseJsonBody(response, bodyText); })\n            .then(function (result) {\n            if (!Array.isArray(result) &&\n                !hasOwnProperty.call(result, \"data\") &&\n                !hasOwnProperty.call(result, \"errors\")) {\n                // Data error\n                throwServerError(response, result, \"Server response was missing for query '\".concat(Array.isArray(operations) ?\n                    operations.map(function (op) { return op.operationName; })\n                    : operations.operationName, \"'.\"));\n            }\n            return result;\n        });\n    };\n}\n//# sourceMappingURL=parseAndCheckHttpResponse.js.map","import { newInvariantError } from \"../../utilities/globals/index.js\";\nexport var serializeFetchParameter = function (p, label) {\n    var serialized;\n    try {\n        serialized = JSON.stringify(p);\n    }\n    catch (e) {\n        var parseError = newInvariantError(40, label, e.message);\n        parseError.parseError = e;\n        throw parseError;\n    }\n    return serialized;\n};\n//# sourceMappingURL=serializeFetchParameter.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { print } from \"../../utilities/index.js\";\nvar defaultHttpOptions = {\n    includeQuery: true,\n    includeExtensions: false,\n    preserveHeaderCase: false,\n};\nvar defaultHeaders = {\n    // headers are case insensitive (https://stackoverflow.com/a/5259004)\n    accept: \"*/*\",\n    // The content-type header describes the type of the body of the request, and\n    // so it typically only is sent with requests that actually have bodies. One\n    // could imagine that Apollo Client would remove this header when constructing\n    // a GET request (which has no body), but we historically have not done that.\n    // This means that browsers will preflight all Apollo Client requests (even\n    // GET requests). Apollo Server's CSRF prevention feature (introduced in\n    // AS3.7) takes advantage of this fact and does not block requests with this\n    // header. If you want to drop this header from GET requests, then you should\n    // probably replace it with a `apollo-require-preflight` header, or servers\n    // with CSRF prevention enabled might block your GET request. See\n    // https://www.apollographql.com/docs/apollo-server/security/cors/#preventing-cross-site-request-forgery-csrf\n    // for more details.\n    \"content-type\": \"application/json\",\n};\nvar defaultOptions = {\n    method: \"POST\",\n};\nexport var fallbackHttpConfig = {\n    http: defaultHttpOptions,\n    headers: defaultHeaders,\n    options: defaultOptions,\n};\nexport var defaultPrinter = function (ast, printer) { return printer(ast); };\nexport function selectHttpOptionsAndBody(operation, fallbackConfig) {\n    var configs = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        configs[_i - 2] = arguments[_i];\n    }\n    configs.unshift(fallbackConfig);\n    return selectHttpOptionsAndBodyInternal.apply(void 0, __spreadArray([operation,\n        defaultPrinter], configs, false));\n}\nexport function selectHttpOptionsAndBodyInternal(operation, printer) {\n    var configs = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        configs[_i - 2] = arguments[_i];\n    }\n    var options = {};\n    var http = {};\n    configs.forEach(function (config) {\n        options = __assign(__assign(__assign({}, options), config.options), { headers: __assign(__assign({}, options.headers), config.headers) });\n        if (config.credentials) {\n            options.credentials = config.credentials;\n        }\n        http = __assign(__assign({}, http), config.http);\n    });\n    if (options.headers) {\n        options.headers = removeDuplicateHeaders(options.headers, http.preserveHeaderCase);\n    }\n    //The body depends on the http options\n    var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;\n    var body = { operationName: operationName, variables: variables };\n    if (http.includeExtensions)\n        body.extensions = extensions;\n    // not sending the query (i.e persisted queries)\n    if (http.includeQuery)\n        body.query = printer(query, print);\n    return {\n        options: options,\n        body: body,\n    };\n}\n// Remove potential duplicate header names, preserving last (by insertion order).\n// This is done to prevent unintentionally duplicating a header instead of\n// overwriting it (See #8447 and #8449).\nfunction removeDuplicateHeaders(headers, preserveHeaderCase) {\n    // If we're not preserving the case, just remove duplicates w/ normalization.\n    if (!preserveHeaderCase) {\n        var normalizedHeaders_1 = {};\n        Object.keys(Object(headers)).forEach(function (name) {\n            normalizedHeaders_1[name.toLowerCase()] = headers[name];\n        });\n        return normalizedHeaders_1;\n    }\n    // If we are preserving the case, remove duplicates w/ normalization,\n    // preserving the original name.\n    // This allows for non-http-spec-compliant servers that expect intentionally\n    // capitalized header names (See #6741).\n    var headerData = {};\n    Object.keys(Object(headers)).forEach(function (name) {\n        headerData[name.toLowerCase()] = {\n            originalName: name,\n            value: headers[name],\n        };\n    });\n    var normalizedHeaders = {};\n    Object.keys(headerData).forEach(function (name) {\n        normalizedHeaders[headerData[name].originalName] = headerData[name].value;\n    });\n    return normalizedHeaders;\n}\n//# sourceMappingURL=selectHttpOptionsAndBody.js.map","import { __assign, __rest } from \"tslib\";\nimport { invariant } from \"../../utilities/globals/index.js\";\nimport { ApolloLink } from \"../core/index.js\";\nimport { Observable, hasDirectives } from \"../../utilities/index.js\";\nimport { serializeFetchParameter } from \"./serializeFetchParameter.js\";\nimport { selectURI } from \"./selectURI.js\";\nimport { handleError, readMultipartBody, parseAndCheckHttpResponse, } from \"./parseAndCheckHttpResponse.js\";\nimport { checkFetcher } from \"./checkFetcher.js\";\nimport { selectHttpOptionsAndBodyInternal, defaultPrinter, fallbackHttpConfig, } from \"./selectHttpOptionsAndBody.js\";\nimport { rewriteURIForGET } from \"./rewriteURIForGET.js\";\nimport { fromError, filterOperationVariables } from \"../utils/index.js\";\nimport { maybe, getMainDefinition, removeClientSetsFromDocument, } from \"../../utilities/index.js\";\nvar backupFetch = maybe(function () { return fetch; });\nexport var createHttpLink = function (linkOptions) {\n    if (linkOptions === void 0) { linkOptions = {}; }\n    var _a = linkOptions.uri, uri = _a === void 0 ? \"/graphql\" : _a, \n    // use default global fetch if nothing passed in\n    preferredFetch = linkOptions.fetch, _b = linkOptions.print, print = _b === void 0 ? defaultPrinter : _b, includeExtensions = linkOptions.includeExtensions, preserveHeaderCase = linkOptions.preserveHeaderCase, useGETForQueries = linkOptions.useGETForQueries, _c = linkOptions.includeUnusedVariables, includeUnusedVariables = _c === void 0 ? false : _c, requestOptions = __rest(linkOptions, [\"uri\", \"fetch\", \"print\", \"includeExtensions\", \"preserveHeaderCase\", \"useGETForQueries\", \"includeUnusedVariables\"]);\n    if (globalThis.__DEV__ !== false) {\n        // Make sure at least one of preferredFetch, window.fetch, or backupFetch is\n        // defined, so requests won't fail at runtime.\n        checkFetcher(preferredFetch || backupFetch);\n    }\n    var linkConfig = {\n        http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },\n        options: requestOptions.fetchOptions,\n        credentials: requestOptions.credentials,\n        headers: requestOptions.headers,\n    };\n    return new ApolloLink(function (operation) {\n        var chosenURI = selectURI(operation, uri);\n        var context = operation.getContext();\n        // `apollographql-client-*` headers are automatically set if a\n        // `clientAwareness` object is found in the context. These headers are\n        // set first, followed by the rest of the headers pulled from\n        // `context.headers`. If desired, `apollographql-client-*` headers set by\n        // the `clientAwareness` object can be overridden by\n        // `apollographql-client-*` headers set in `context.headers`.\n        var clientAwarenessHeaders = {};\n        if (context.clientAwareness) {\n            var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;\n            if (name_1) {\n                clientAwarenessHeaders[\"apollographql-client-name\"] = name_1;\n            }\n            if (version) {\n                clientAwarenessHeaders[\"apollographql-client-version\"] = version;\n            }\n        }\n        var contextHeaders = __assign(__assign({}, clientAwarenessHeaders), context.headers);\n        var contextConfig = {\n            http: context.http,\n            options: context.fetchOptions,\n            credentials: context.credentials,\n            headers: contextHeaders,\n        };\n        if (hasDirectives([\"client\"], operation.query)) {\n            var transformedQuery = removeClientSetsFromDocument(operation.query);\n            if (!transformedQuery) {\n                return fromError(new Error(\"HttpLink: Trying to send a client-only query to the server. To send to the server, ensure a non-client field is added to the query or set the `transformOptions.removeClientFields` option to `true`.\"));\n            }\n            operation.query = transformedQuery;\n        }\n        //uses fallback, link, and then context to build options\n        var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;\n        if (body.variables && !includeUnusedVariables) {\n            body.variables = filterOperationVariables(body.variables, operation.query);\n        }\n        var controller;\n        if (!options.signal && typeof AbortController !== \"undefined\") {\n            controller = new AbortController();\n            options.signal = controller.signal;\n        }\n        // If requested, set method to GET if there are no mutations.\n        var definitionIsMutation = function (d) {\n            return d.kind === \"OperationDefinition\" && d.operation === \"mutation\";\n        };\n        var definitionIsSubscription = function (d) {\n            return d.kind === \"OperationDefinition\" && d.operation === \"subscription\";\n        };\n        var isSubscription = definitionIsSubscription(getMainDefinition(operation.query));\n        // does not match custom directives beginning with @defer\n        var hasDefer = hasDirectives([\"defer\"], operation.query);\n        if (useGETForQueries &&\n            !operation.query.definitions.some(definitionIsMutation)) {\n            options.method = \"GET\";\n        }\n        if (hasDefer || isSubscription) {\n            options.headers = options.headers || {};\n            var acceptHeader = \"multipart/mixed;\";\n            // Omit defer-specific headers if the user attempts to defer a selection\n            // set on a subscription and log a warning.\n            if (isSubscription && hasDefer) {\n                globalThis.__DEV__ !== false && invariant.warn(39);\n            }\n            if (isSubscription) {\n                acceptHeader +=\n                    \"boundary=graphql;subscriptionSpec=1.0,application/json\";\n            }\n            else if (hasDefer) {\n                acceptHeader += \"deferSpec=20220824,application/json\";\n            }\n            options.headers.accept = acceptHeader;\n        }\n        if (options.method === \"GET\") {\n            var _c = rewriteURIForGET(chosenURI, body), newURI = _c.newURI, parseError = _c.parseError;\n            if (parseError) {\n                return fromError(parseError);\n            }\n            chosenURI = newURI;\n        }\n        else {\n            try {\n                options.body = serializeFetchParameter(body, \"Payload\");\n            }\n            catch (parseError) {\n                return fromError(parseError);\n            }\n        }\n        return new Observable(function (observer) {\n            // Prefer linkOptions.fetch (preferredFetch) if provided, and otherwise\n            // fall back to the *current* global window.fetch function (see issue\n            // #7832), or (if all else fails) the backupFetch function we saved when\n            // this module was first evaluated. This last option protects against the\n            // removal of window.fetch, which is unlikely but not impossible.\n            var currentFetch = preferredFetch || maybe(function () { return fetch; }) || backupFetch;\n            var observerNext = observer.next.bind(observer);\n            currentFetch(chosenURI, options)\n                .then(function (response) {\n                var _a;\n                operation.setContext({ response: response });\n                var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get(\"content-type\");\n                if (ctype !== null && /^multipart\\/mixed/i.test(ctype)) {\n                    return readMultipartBody(response, observerNext);\n                }\n                else {\n                    return parseAndCheckHttpResponse(operation)(response).then(observerNext);\n                }\n            })\n                .then(function () {\n                controller = undefined;\n                observer.complete();\n            })\n                .catch(function (err) {\n                controller = undefined;\n                handleError(err, observer);\n            });\n            return function () {\n                // XXX support canceling this request\n                // https://developers.google.com/web/updates/2017/09/abortable-fetch\n                if (controller)\n                    controller.abort();\n            };\n        });\n    });\n};\n//# sourceMappingURL=createHttpLink.js.map","import { __extends } from \"tslib\";\nimport { ApolloLink } from \"../core/index.js\";\nimport { createHttpLink } from \"./createHttpLink.js\";\nvar HttpLink = /** @class */ (function (_super) {\n    __extends(HttpLink, _super);\n    function HttpLink(options) {\n        if (options === void 0) { options = {}; }\n        var _this = _super.call(this, createHttpLink(options).request) || this;\n        _this.options = options;\n        return _this;\n    }\n    return HttpLink;\n}(ApolloLink));\nexport { HttpLink };\n//# sourceMappingURL=HttpLink.js.map","import { newInvariantError } from \"../../utilities/globals/index.js\";\nexport var checkFetcher = function (fetcher) {\n    if (!fetcher && typeof fetch === \"undefined\") {\n        throw newInvariantError(38);\n    }\n};\n//# sourceMappingURL=checkFetcher.js.map","export var selectURI = function (operation, fallbackURI) {\n    var context = operation.getContext();\n    var contextURI = context.uri;\n    if (contextURI) {\n        return contextURI;\n    }\n    else if (typeof fallbackURI === \"function\") {\n        return fallbackURI(operation);\n    }\n    else {\n        return fallbackURI || \"/graphql\";\n    }\n};\n//# sourceMappingURL=selectURI.js.map","import { __assign } from \"tslib\";\nimport { visit } from \"graphql\";\nexport function filterOperationVariables(variables, query) {\n    var result = __assign({}, variables);\n    var unusedNames = new Set(Object.keys(variables));\n    visit(query, {\n        Variable: function (node, _key, parent) {\n            // A variable type definition at the top level of a query is not\n            // enough to silence server-side errors about the variable being\n            // unused, so variable definitions do not count as usage.\n            // https://spec.graphql.org/draft/#sec-All-Variables-Used\n            if (parent &&\n                parent.kind !== \"VariableDefinition\") {\n                unusedNames.delete(node.name.value);\n            }\n        },\n    });\n    unusedNames.forEach(function (name) {\n        delete result[name];\n    });\n    return result;\n}\n//# sourceMappingURL=filterOperationVariables.js.map","import { serializeFetchParameter } from \"./serializeFetchParameter.js\";\n// For GET operations, returns the given URI rewritten with parameters, or a\n// parse error.\nexport function rewriteURIForGET(chosenURI, body) {\n    // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n    // the extra level of JSON serialization!\n    var queryParams = [];\n    var addQueryParam = function (key, value) {\n        queryParams.push(\"\".concat(key, \"=\").concat(encodeURIComponent(value)));\n    };\n    if (\"query\" in body) {\n        addQueryParam(\"query\", body.query);\n    }\n    if (body.operationName) {\n        addQueryParam(\"operationName\", body.operationName);\n    }\n    if (body.variables) {\n        var serializedVariables = void 0;\n        try {\n            serializedVariables = serializeFetchParameter(body.variables, \"Variables map\");\n        }\n        catch (parseError) {\n            return { parseError: parseError };\n        }\n        addQueryParam(\"variables\", serializedVariables);\n    }\n    if (body.extensions) {\n        var serializedExtensions = void 0;\n        try {\n            serializedExtensions = serializeFetchParameter(body.extensions, \"Extensions map\");\n        }\n        catch (parseError) {\n            return { parseError: parseError };\n        }\n        addQueryParam(\"extensions\", serializedExtensions);\n    }\n    // Reconstruct the URI with added query params.\n    // XXX This assumes that the URI is well-formed and that it doesn't\n    //     already contain any of these query params. We could instead use the\n    //     URL API and take a polyfill (whatwg-url@6) for older browsers that\n    //     don't support URLSearchParams. Note that some browsers (and\n    //     versions of whatwg-url) support URL but not URLSearchParams!\n    var fragment = \"\", preFragment = chosenURI;\n    var fragmentStart = chosenURI.indexOf(\"#\");\n    if (fragmentStart !== -1) {\n        fragment = chosenURI.substr(fragmentStart);\n        preFragment = chosenURI.substr(0, fragmentStart);\n    }\n    var queryParamsPrefix = preFragment.indexOf(\"?\") === -1 ? \"?\" : \"&\";\n    var newURI = preFragment + queryParamsPrefix + queryParams.join(\"&\") + fragment;\n    return { newURI: newURI };\n}\n//# sourceMappingURL=rewriteURIForGET.js.map","const { toString, hasOwnProperty } = Object.prototype;\nconst fnToStr = Function.prototype.toString;\nconst previousComparisons = new Map();\n/**\n * Performs a deep equality check on two JavaScript values, tolerating cycles.\n */\nexport function equal(a, b) {\n    try {\n        return check(a, b);\n    }\n    finally {\n        previousComparisons.clear();\n    }\n}\n// Allow default imports as well.\nexport default equal;\nfunction check(a, b) {\n    // If the two values are strictly equal, our job is easy.\n    if (a === b) {\n        return true;\n    }\n    // Object.prototype.toString returns a representation of the runtime type of\n    // the given value that is considerably more precise than typeof.\n    const aTag = toString.call(a);\n    const bTag = toString.call(b);\n    // If the runtime types of a and b are different, they could maybe be equal\n    // under some interpretation of equality, but for simplicity and performance\n    // we just return false instead.\n    if (aTag !== bTag) {\n        return false;\n    }\n    switch (aTag) {\n        case '[object Array]':\n            // Arrays are a lot like other objects, but we can cheaply compare their\n            // lengths as a short-cut before comparing their elements.\n            if (a.length !== b.length)\n                return false;\n        // Fall through to object case...\n        case '[object Object]': {\n            if (previouslyCompared(a, b))\n                return true;\n            const aKeys = definedKeys(a);\n            const bKeys = definedKeys(b);\n            // If `a` and `b` have a different number of enumerable keys, they\n            // must be different.\n            const keyCount = aKeys.length;\n            if (keyCount !== bKeys.length)\n                return false;\n            // Now make sure they have the same keys.\n            for (let k = 0; k < keyCount; ++k) {\n                if (!hasOwnProperty.call(b, aKeys[k])) {\n                    return false;\n                }\n            }\n            // Finally, check deep equality of all child properties.\n            for (let k = 0; k < keyCount; ++k) {\n                const key = aKeys[k];\n                if (!check(a[key], b[key])) {\n                    return false;\n                }\n            }\n            return true;\n        }\n        case '[object Error]':\n            return a.name === b.name && a.message === b.message;\n        case '[object Number]':\n            // Handle NaN, which is !== itself.\n            if (a !== a)\n                return b !== b;\n        // Fall through to shared +a === +b case...\n        case '[object Boolean]':\n        case '[object Date]':\n            return +a === +b;\n        case '[object RegExp]':\n        case '[object String]':\n            return a == `${b}`;\n        case '[object Map]':\n        case '[object Set]': {\n            if (a.size !== b.size)\n                return false;\n            if (previouslyCompared(a, b))\n                return true;\n            const aIterator = a.entries();\n            const isMap = aTag === '[object Map]';\n            while (true) {\n                const info = aIterator.next();\n                if (info.done)\n                    break;\n                // If a instanceof Set, aValue === aKey.\n                const [aKey, aValue] = info.value;\n                // So this works the same way for both Set and Map.\n                if (!b.has(aKey)) {\n                    return false;\n                }\n                // However, we care about deep equality of values only when dealing\n                // with Map structures.\n                if (isMap && !check(aValue, b.get(aKey))) {\n                    return false;\n                }\n            }\n            return true;\n        }\n        case '[object Uint16Array]':\n        case '[object Uint8Array]': // Buffer, in Node.js.\n        case '[object Uint32Array]':\n        case '[object Int32Array]':\n        case '[object Int8Array]':\n        case '[object Int16Array]':\n        case '[object ArrayBuffer]':\n            // DataView doesn't need these conversions, but the equality check is\n            // otherwise the same.\n            a = new Uint8Array(a);\n            b = new Uint8Array(b);\n        // Fall through...\n        case '[object DataView]': {\n            let len = a.byteLength;\n            if (len === b.byteLength) {\n                while (len-- && a[len] === b[len]) {\n                    // Keep looping as long as the bytes are equal.\n                }\n            }\n            return len === -1;\n        }\n        case '[object AsyncFunction]':\n        case '[object GeneratorFunction]':\n        case '[object AsyncGeneratorFunction]':\n        case '[object Function]': {\n            const aCode = fnToStr.call(a);\n            if (aCode !== fnToStr.call(b)) {\n                return false;\n            }\n            // We consider non-native functions equal if they have the same code\n            // (native functions require === because their code is censored).\n            // Note that this behavior is not entirely sound, since !== function\n            // objects with the same code can behave differently depending on\n            // their closure scope. However, any function can behave differently\n            // depending on the values of its input arguments (including this)\n            // and its calling context (including its closure scope), even\n            // though the function object is === to itself; and it is entirely\n            // possible for functions that are not === to behave exactly the\n            // same under all conceivable circumstances. Because none of these\n            // factors are statically decidable in JavaScript, JS function\n            // equality is not well-defined. This ambiguity allows us to\n            // consider the best possible heuristic among various imperfect\n            // options, and equating non-native functions that have the same\n            // code has enormous practical benefits, such as when comparing\n            // functions that are repeatedly passed as fresh function\n            // expressions within objects that are otherwise deeply equal. Since\n            // any function created from the same syntactic expression (in the\n            // same code location) will always stringify to the same code\n            // according to fnToStr.call, we can reasonably expect these\n            // repeatedly passed function expressions to have the same code, and\n            // thus behave \"the same\" (with all the caveats mentioned above),\n            // even though the runtime function objects are !== to one another.\n            return !endsWith(aCode, nativeCodeSuffix);\n        }\n    }\n    // Otherwise the values are not equal.\n    return false;\n}\nfunction definedKeys(obj) {\n    // Remember that the second argument to Array.prototype.filter will be\n    // used as `this` within the callback function.\n    return Object.keys(obj).filter(isDefinedKey, obj);\n}\nfunction isDefinedKey(key) {\n    return this[key] !== void 0;\n}\nconst nativeCodeSuffix = \"{ [native code] }\";\nfunction endsWith(full, suffix) {\n    const fromIndex = full.length - suffix.length;\n    return fromIndex >= 0 &&\n        full.indexOf(suffix, fromIndex) === fromIndex;\n}\nfunction previouslyCompared(a, b) {\n    // Though cyclic references can make an object graph appear infinite from the\n    // perspective of a depth-first traversal, the graph still contains a finite\n    // number of distinct object references. We use the previousComparisons cache\n    // to avoid comparing the same pair of object references more than once, which\n    // guarantees termination (even if we end up comparing every object in one\n    // graph to every object in the other graph, which is extremely unlikely),\n    // while still allowing weird isomorphic structures (like rings with different\n    // lengths) a chance to pass the equality test.\n    let bSet = previousComparisons.get(a);\n    if (bSet) {\n        // Return true here because we can be sure false will be returned somewhere\n        // else if the objects are not equivalent.\n        if (bSet.has(b))\n            return true;\n    }\n    else {\n        previousComparisons.set(a, bSet = new Set);\n    }\n    bSet.add(b);\n    return false;\n}\n//# sourceMappingURL=index.js.map","import { __rest } from \"tslib\";\nimport equal from \"@wry/equality\";\nimport { createFragmentMap, getFragmentDefinitions, getFragmentFromSelection, getMainDefinition, isField, resultKeyNameFromField, shouldInclude, } from \"../utilities/index.js\";\n// Returns true if aResult and bResult are deeply equal according to the fields\n// selected by the given query, ignoring any fields marked as @nonreactive.\nexport function equalByQuery(query, _a, _b, variables) {\n    var aData = _a.data, aRest = __rest(_a, [\"data\"]);\n    var bData = _b.data, bRest = __rest(_b, [\"data\"]);\n    return (equal(aRest, bRest) &&\n        equalBySelectionSet(getMainDefinition(query).selectionSet, aData, bData, {\n            fragmentMap: createFragmentMap(getFragmentDefinitions(query)),\n            variables: variables,\n        }));\n}\nfunction equalBySelectionSet(selectionSet, aResult, bResult, context) {\n    if (aResult === bResult) {\n        return true;\n    }\n    var seenSelections = new Set();\n    // Returning true from this Array.prototype.every callback function skips the\n    // current field/subtree. Returning false aborts the entire traversal\n    // immediately, causing equalBySelectionSet to return false.\n    return selectionSet.selections.every(function (selection) {\n        // Avoid re-processing the same selection at the same level of recursion, in\n        // case the same field gets included via multiple indirect fragment spreads.\n        if (seenSelections.has(selection))\n            return true;\n        seenSelections.add(selection);\n        // Ignore @skip(if: true) and @include(if: false) fields.\n        if (!shouldInclude(selection, context.variables))\n            return true;\n        // If the field or (named) fragment spread has a @nonreactive directive on\n        // it, we don't care if it's different, so we pretend it's the same.\n        if (selectionHasNonreactiveDirective(selection))\n            return true;\n        if (isField(selection)) {\n            var resultKey = resultKeyNameFromField(selection);\n            var aResultChild = aResult && aResult[resultKey];\n            var bResultChild = bResult && bResult[resultKey];\n            var childSelectionSet = selection.selectionSet;\n            if (!childSelectionSet) {\n                // These are scalar values, so we can compare them with deep equal\n                // without redoing the main recursive work.\n                return equal(aResultChild, bResultChild);\n            }\n            var aChildIsArray = Array.isArray(aResultChild);\n            var bChildIsArray = Array.isArray(bResultChild);\n            if (aChildIsArray !== bChildIsArray)\n                return false;\n            if (aChildIsArray && bChildIsArray) {\n                var length_1 = aResultChild.length;\n                if (bResultChild.length !== length_1) {\n                    return false;\n                }\n                for (var i = 0; i < length_1; ++i) {\n                    if (!equalBySelectionSet(childSelectionSet, aResultChild[i], bResultChild[i], context)) {\n                        return false;\n                    }\n                }\n                return true;\n            }\n            return equalBySelectionSet(childSelectionSet, aResultChild, bResultChild, context);\n        }\n        else {\n            var fragment = getFragmentFromSelection(selection, context.fragmentMap);\n            if (fragment) {\n                // The fragment might === selection if it's an inline fragment, but\n                // could be !== if it's a named fragment ...spread.\n                if (selectionHasNonreactiveDirective(fragment))\n                    return true;\n                return equalBySelectionSet(fragment.selectionSet, \n                // Notice that we reuse the same aResult and bResult values here,\n                // since the fragment ...spread does not specify a field name, but\n                // consists of multiple fields (within the fragment's selection set)\n                // that should be applied to the current result value(s).\n                aResult, bResult, context);\n            }\n        }\n    });\n}\nfunction selectionHasNonreactiveDirective(selection) {\n    return (!!selection.directives && selection.directives.some(directiveIsNonreactive));\n}\nfunction directiveIsNonreactive(dir) {\n    return dir.name.value === \"nonreactive\";\n}\n//# sourceMappingURL=equalByQuery.js.map","import { __assign, __rest } from \"tslib\";\nimport { wrap } from \"optimism\";\nimport { Observable, cacheSizes, getFragmentQueryDocument, mergeDeepArray, } from \"../../utilities/index.js\";\nimport { WeakCache } from \"@wry/caches\";\nimport { getApolloCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\nimport { equalByQuery } from \"../../core/equalByQuery.js\";\nvar ApolloCache = /** @class */ (function () {\n    function ApolloCache() {\n        this.assumeImmutableResults = false;\n        // Make sure we compute the same (===) fragment query document every\n        // time we receive the same fragment in readFragment.\n        this.getFragmentDoc = wrap(getFragmentQueryDocument, {\n            max: cacheSizes[\"cache.fragmentQueryDocuments\"] ||\n                1000 /* defaultCacheSizes[\"cache.fragmentQueryDocuments\"] */,\n            cache: WeakCache,\n        });\n    }\n    // Transactional API\n    // The batch method is intended to replace/subsume both performTransaction\n    // and recordOptimisticTransaction, but performTransaction came first, so we\n    // provide a default batch implementation that's just another way of calling\n    // performTransaction. Subclasses of ApolloCache (such as InMemoryCache) can\n    // override the batch method to do more interesting things with its options.\n    ApolloCache.prototype.batch = function (options) {\n        var _this = this;\n        var optimisticId = typeof options.optimistic === \"string\" ? options.optimistic\n            : options.optimistic === false ? null\n                : void 0;\n        var updateResult;\n        this.performTransaction(function () { return (updateResult = options.update(_this)); }, optimisticId);\n        return updateResult;\n    };\n    ApolloCache.prototype.recordOptimisticTransaction = function (transaction, optimisticId) {\n        this.performTransaction(transaction, optimisticId);\n    };\n    // Optional API\n    // Called once per input document, allowing the cache to make static changes\n    // to the query, such as adding __typename fields.\n    ApolloCache.prototype.transformDocument = function (document) {\n        return document;\n    };\n    // Called before each ApolloLink request, allowing the cache to make dynamic\n    // changes to the query, such as filling in missing fragment definitions.\n    ApolloCache.prototype.transformForLink = function (document) {\n        return document;\n    };\n    ApolloCache.prototype.identify = function (object) {\n        return;\n    };\n    ApolloCache.prototype.gc = function () {\n        return [];\n    };\n    ApolloCache.prototype.modify = function (options) {\n        return false;\n    };\n    // DataProxy API\n    ApolloCache.prototype.readQuery = function (options, optimistic) {\n        if (optimistic === void 0) { optimistic = !!options.optimistic; }\n        return this.read(__assign(__assign({}, options), { rootId: options.id || \"ROOT_QUERY\", optimistic: optimistic }));\n    };\n    /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n    ApolloCache.prototype.watchFragment = function (options) {\n        var _this = this;\n        var fragment = options.fragment, fragmentName = options.fragmentName, from = options.from, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, otherOptions = __rest(options, [\"fragment\", \"fragmentName\", \"from\", \"optimistic\"]);\n        var query = this.getFragmentDoc(fragment, fragmentName);\n        var diffOptions = __assign(__assign({}, otherOptions), { returnPartialData: true, id: \n            // While our TypeScript types do not allow for `undefined` as a valid\n            // `from`, its possible `useFragment` gives us an `undefined` since it\n            // calls` cache.identify` and provides that value to `from`. We are\n            // adding this fix here however to ensure those using plain JavaScript\n            // and using `cache.identify` themselves will avoid seeing the obscure\n            // warning.\n            typeof from === \"undefined\" || typeof from === \"string\" ?\n                from\n                : this.identify(from), query: query, optimistic: optimistic });\n        var latestDiff;\n        return new Observable(function (observer) {\n            return _this.watch(__assign(__assign({}, diffOptions), { immediate: true, callback: function (diff) {\n                    if (\n                    // Always ensure we deliver the first result\n                    latestDiff &&\n                        equalByQuery(query, { data: latestDiff === null || latestDiff === void 0 ? void 0 : latestDiff.result }, { data: diff.result })) {\n                        return;\n                    }\n                    var result = {\n                        data: diff.result,\n                        complete: !!diff.complete,\n                    };\n                    if (diff.missing) {\n                        result.missing = mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));\n                    }\n                    latestDiff = diff;\n                    observer.next(result);\n                } }));\n        });\n    };\n    ApolloCache.prototype.readFragment = function (options, optimistic) {\n        if (optimistic === void 0) { optimistic = !!options.optimistic; }\n        return this.read(__assign(__assign({}, options), { query: this.getFragmentDoc(options.fragment, options.fragmentName), rootId: options.id, optimistic: optimistic }));\n    };\n    ApolloCache.prototype.writeQuery = function (_a) {\n        var id = _a.id, data = _a.data, options = __rest(_a, [\"id\", \"data\"]);\n        return this.write(Object.assign(options, {\n            dataId: id || \"ROOT_QUERY\",\n            result: data,\n        }));\n    };\n    ApolloCache.prototype.writeFragment = function (_a) {\n        var id = _a.id, data = _a.data, fragment = _a.fragment, fragmentName = _a.fragmentName, options = __rest(_a, [\"id\", \"data\", \"fragment\", \"fragmentName\"]);\n        return this.write(Object.assign(options, {\n            query: this.getFragmentDoc(fragment, fragmentName),\n            dataId: id,\n            result: data,\n        }));\n    };\n    ApolloCache.prototype.updateQuery = function (options, update) {\n        return this.batch({\n            update: function (cache) {\n                var value = cache.readQuery(options);\n                var data = update(value);\n                if (data === void 0 || data === null)\n                    return value;\n                cache.writeQuery(__assign(__assign({}, options), { data: data }));\n                return data;\n            },\n        });\n    };\n    ApolloCache.prototype.updateFragment = function (options, update) {\n        return this.batch({\n            update: function (cache) {\n                var value = cache.readFragment(options);\n                var data = update(value);\n                if (data === void 0 || data === null)\n                    return value;\n                cache.writeFragment(__assign(__assign({}, options), { data: data }));\n                return data;\n            },\n        });\n    };\n    return ApolloCache;\n}());\nexport { ApolloCache };\nif (globalThis.__DEV__ !== false) {\n    ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;\n}\n//# sourceMappingURL=cache.js.map","import { __extends } from \"tslib\";\nvar MissingFieldError = /** @class */ (function (_super) {\n    __extends(MissingFieldError, _super);\n    function MissingFieldError(message, path, query, variables) {\n        var _a;\n        // 'Error' breaks prototype chain here\n        var _this = _super.call(this, message) || this;\n        _this.message = message;\n        _this.path = path;\n        _this.query = query;\n        _this.variables = variables;\n        if (Array.isArray(_this.path)) {\n            _this.missing = _this.message;\n            for (var i = _this.path.length - 1; i >= 0; --i) {\n                _this.missing = (_a = {}, _a[_this.path[i]] = _this.missing, _a);\n            }\n        }\n        else {\n            _this.missing = _this.path;\n        }\n        // We're not using `Object.setPrototypeOf` here as it isn't fully supported\n        // on Android (see issue #3236).\n        _this.__proto__ = MissingFieldError.prototype;\n        return _this;\n    }\n    return MissingFieldError;\n}(Error));\nexport { MissingFieldError };\n//# sourceMappingURL=common.js.map","import { isReference, isField, DeepMerger, resultKeyNameFromField, shouldInclude, isNonNullObject, compact, createFragmentMap, getFragmentDefinitions, isArray, } from \"../../utilities/index.js\";\nexport var hasOwn = Object.prototype.hasOwnProperty;\nexport function isNullish(value) {\n    return value === null || value === void 0;\n}\nexport { isArray };\nexport function defaultDataIdFromObject(_a, context) {\n    var __typename = _a.__typename, id = _a.id, _id = _a._id;\n    if (typeof __typename === \"string\") {\n        if (context) {\n            context.keyObject =\n                !isNullish(id) ? { id: id }\n                    : !isNullish(_id) ? { _id: _id }\n                        : void 0;\n        }\n        // If there is no object.id, fall back to object._id.\n        if (isNullish(id) && !isNullish(_id)) {\n            id = _id;\n        }\n        if (!isNullish(id)) {\n            return \"\".concat(__typename, \":\").concat(typeof id === \"number\" || typeof id === \"string\" ?\n                id\n                : JSON.stringify(id));\n        }\n    }\n}\nvar defaultConfig = {\n    dataIdFromObject: defaultDataIdFromObject,\n    addTypename: true,\n    resultCaching: true,\n    // Thanks to the shouldCanonizeResults helper, this should be the only line\n    // you have to change to reenable canonization by default in the future.\n    canonizeResults: false,\n};\nexport function normalizeConfig(config) {\n    return compact(defaultConfig, config);\n}\nexport function shouldCanonizeResults(config) {\n    var value = config.canonizeResults;\n    return value === void 0 ? defaultConfig.canonizeResults : value;\n}\nexport function getTypenameFromStoreObject(store, objectOrReference) {\n    return isReference(objectOrReference) ?\n        store.get(objectOrReference.__ref, \"__typename\")\n        : objectOrReference && objectOrReference.__typename;\n}\nexport var TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;\nexport function fieldNameFromStoreName(storeFieldName) {\n    var match = storeFieldName.match(TypeOrFieldNameRegExp);\n    return match ? match[0] : storeFieldName;\n}\nexport function selectionSetMatchesResult(selectionSet, result, variables) {\n    if (isNonNullObject(result)) {\n        return isArray(result) ?\n            result.every(function (item) {\n                return selectionSetMatchesResult(selectionSet, item, variables);\n            })\n            : selectionSet.selections.every(function (field) {\n                if (isField(field) && shouldInclude(field, variables)) {\n                    var key = resultKeyNameFromField(field);\n                    return (hasOwn.call(result, key) &&\n                        (!field.selectionSet ||\n                            selectionSetMatchesResult(field.selectionSet, result[key], variables)));\n                }\n                // If the selection has been skipped with @skip(true) or\n                // @include(false), it should not count against the matching. If\n                // the selection is not a field, it must be a fragment (inline or\n                // named). We will determine if selectionSetMatchesResult for that\n                // fragment when we get to it, so for now we return true.\n                return true;\n            });\n    }\n    return false;\n}\nexport function storeValueIsStoreObject(value) {\n    return isNonNullObject(value) && !isReference(value) && !isArray(value);\n}\nexport function makeProcessedFieldsMerger() {\n    return new DeepMerger();\n}\nexport function extractFragmentContext(document, fragments) {\n    // FragmentMap consisting only of fragments defined directly in document, not\n    // including other fragments registered in the FragmentRegistry.\n    var fragmentMap = createFragmentMap(getFragmentDefinitions(document));\n    return {\n        fragmentMap: fragmentMap,\n        lookupFragment: function (name) {\n            var def = fragmentMap[name];\n            if (!def && fragments) {\n                def = fragments.lookup(name);\n            }\n            return def || null;\n        },\n    };\n}\n//# sourceMappingURL=helpers.js.map","import { __assign, __extends, __rest } from \"tslib\";\nimport { invariant } from \"../../utilities/globals/index.js\";\nimport { dep } from \"optimism\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport { isReference, makeReference, DeepMerger, maybeDeepFreeze, canUseWeakMap, isNonNullObject, } from \"../../utilities/index.js\";\nimport { hasOwn, fieldNameFromStoreName } from \"./helpers.js\";\nvar DELETE = Object.create(null);\nvar delModifier = function () { return DELETE; };\nvar INVALIDATE = Object.create(null);\nvar EntityStore = /** @class */ (function () {\n    function EntityStore(policies, group) {\n        var _this = this;\n        this.policies = policies;\n        this.group = group;\n        this.data = Object.create(null);\n        // Maps root entity IDs to the number of times they have been retained, minus\n        // the number of times they have been released. Retained entities keep other\n        // entities they reference (even indirectly) from being garbage collected.\n        this.rootIds = Object.create(null);\n        // Lazily tracks { __ref: <dataId> } strings contained by this.data[dataId].\n        this.refs = Object.create(null);\n        // Bound function that can be passed around to provide easy access to fields\n        // of Reference objects as well as ordinary objects.\n        this.getFieldValue = function (objectOrReference, storeFieldName) {\n            return maybeDeepFreeze(isReference(objectOrReference) ?\n                _this.get(objectOrReference.__ref, storeFieldName)\n                : objectOrReference && objectOrReference[storeFieldName]);\n        };\n        // Returns true for non-normalized StoreObjects and non-dangling\n        // References, indicating that readField(name, objOrRef) has a chance of\n        // working. Useful for filtering out dangling references from lists.\n        this.canRead = function (objOrRef) {\n            return isReference(objOrRef) ?\n                _this.has(objOrRef.__ref)\n                : typeof objOrRef === \"object\";\n        };\n        // Bound function that converts an id or an object with a __typename and\n        // primary key fields to a Reference object. If called with a Reference object,\n        // that same Reference object is returned. Pass true for mergeIntoStore to persist\n        // an object into the store.\n        this.toReference = function (objOrIdOrRef, mergeIntoStore) {\n            if (typeof objOrIdOrRef === \"string\") {\n                return makeReference(objOrIdOrRef);\n            }\n            if (isReference(objOrIdOrRef)) {\n                return objOrIdOrRef;\n            }\n            var id = _this.policies.identify(objOrIdOrRef)[0];\n            if (id) {\n                var ref = makeReference(id);\n                if (mergeIntoStore) {\n                    _this.merge(id, objOrIdOrRef);\n                }\n                return ref;\n            }\n        };\n    }\n    // Although the EntityStore class is abstract, it contains concrete\n    // implementations of the various NormalizedCache interface methods that\n    // are inherited by the Root and Layer subclasses.\n    EntityStore.prototype.toObject = function () {\n        return __assign({}, this.data);\n    };\n    EntityStore.prototype.has = function (dataId) {\n        return this.lookup(dataId, true) !== void 0;\n    };\n    EntityStore.prototype.get = function (dataId, fieldName) {\n        this.group.depend(dataId, fieldName);\n        if (hasOwn.call(this.data, dataId)) {\n            var storeObject = this.data[dataId];\n            if (storeObject && hasOwn.call(storeObject, fieldName)) {\n                return storeObject[fieldName];\n            }\n        }\n        if (fieldName === \"__typename\" &&\n            hasOwn.call(this.policies.rootTypenamesById, dataId)) {\n            return this.policies.rootTypenamesById[dataId];\n        }\n        if (this instanceof Layer) {\n            return this.parent.get(dataId, fieldName);\n        }\n    };\n    EntityStore.prototype.lookup = function (dataId, dependOnExistence) {\n        // The has method (above) calls lookup with dependOnExistence = true, so\n        // that it can later be invalidated when we add or remove a StoreObject for\n        // this dataId. Any consumer who cares about the contents of the StoreObject\n        // should not rely on this dependency, since the contents could change\n        // without the object being added or removed.\n        if (dependOnExistence)\n            this.group.depend(dataId, \"__exists\");\n        if (hasOwn.call(this.data, dataId)) {\n            return this.data[dataId];\n        }\n        if (this instanceof Layer) {\n            return this.parent.lookup(dataId, dependOnExistence);\n        }\n        if (this.policies.rootTypenamesById[dataId]) {\n            return Object.create(null);\n        }\n    };\n    EntityStore.prototype.merge = function (older, newer) {\n        var _this = this;\n        var dataId;\n        // Convert unexpected references to ID strings.\n        if (isReference(older))\n            older = older.__ref;\n        if (isReference(newer))\n            newer = newer.__ref;\n        var existing = typeof older === \"string\" ? this.lookup((dataId = older)) : older;\n        var incoming = typeof newer === \"string\" ? this.lookup((dataId = newer)) : newer;\n        // If newer was a string ID, but that ID was not defined in this store,\n        // then there are no fields to be merged, so we're done.\n        if (!incoming)\n            return;\n        invariant(typeof dataId === \"string\", 1);\n        var merged = new DeepMerger(storeObjectReconciler).merge(existing, incoming);\n        // Even if merged === existing, existing may have come from a lower\n        // layer, so we always need to set this.data[dataId] on this level.\n        this.data[dataId] = merged;\n        if (merged !== existing) {\n            delete this.refs[dataId];\n            if (this.group.caching) {\n                var fieldsToDirty_1 = Object.create(null);\n                // If we added a new StoreObject where there was previously none, dirty\n                // anything that depended on the existence of this dataId, such as the\n                // EntityStore#has method.\n                if (!existing)\n                    fieldsToDirty_1.__exists = 1;\n                // Now invalidate dependents who called getFieldValue for any fields\n                // that are changing as a result of this merge.\n                Object.keys(incoming).forEach(function (storeFieldName) {\n                    if (!existing ||\n                        existing[storeFieldName] !== merged[storeFieldName]) {\n                        // Always dirty the full storeFieldName, which may include\n                        // serialized arguments following the fieldName prefix.\n                        fieldsToDirty_1[storeFieldName] = 1;\n                        // Also dirty fieldNameFromStoreName(storeFieldName) if it's\n                        // different from storeFieldName and this field does not have\n                        // keyArgs configured, because that means the cache can't make\n                        // any assumptions about how field values with the same field\n                        // name but different arguments might be interrelated, so it\n                        // must err on the side of invalidating all field values that\n                        // share the same short fieldName, regardless of arguments.\n                        var fieldName = fieldNameFromStoreName(storeFieldName);\n                        if (fieldName !== storeFieldName &&\n                            !_this.policies.hasKeyArgs(merged.__typename, fieldName)) {\n                            fieldsToDirty_1[fieldName] = 1;\n                        }\n                        // If merged[storeFieldName] has become undefined, and this is the\n                        // Root layer, actually delete the property from the merged object,\n                        // which is guaranteed to have been created fresh in this method.\n                        if (merged[storeFieldName] === void 0 && !(_this instanceof Layer)) {\n                            delete merged[storeFieldName];\n                        }\n                    }\n                });\n                if (fieldsToDirty_1.__typename &&\n                    !(existing && existing.__typename) &&\n                    // Since we return default root __typename strings\n                    // automatically from store.get, we don't need to dirty the\n                    // ROOT_QUERY.__typename field if merged.__typename is equal\n                    // to the default string (usually \"Query\").\n                    this.policies.rootTypenamesById[dataId] === merged.__typename) {\n                    delete fieldsToDirty_1.__typename;\n                }\n                Object.keys(fieldsToDirty_1).forEach(function (fieldName) {\n                    return _this.group.dirty(dataId, fieldName);\n                });\n            }\n        }\n    };\n    EntityStore.prototype.modify = function (dataId, fields) {\n        var _this = this;\n        var storeObject = this.lookup(dataId);\n        if (storeObject) {\n            var changedFields_1 = Object.create(null);\n            var needToMerge_1 = false;\n            var allDeleted_1 = true;\n            var sharedDetails_1 = {\n                DELETE: DELETE,\n                INVALIDATE: INVALIDATE,\n                isReference: isReference,\n                toReference: this.toReference,\n                canRead: this.canRead,\n                readField: function (fieldNameOrOptions, from) {\n                    return _this.policies.readField(typeof fieldNameOrOptions === \"string\" ?\n                        {\n                            fieldName: fieldNameOrOptions,\n                            from: from || makeReference(dataId),\n                        }\n                        : fieldNameOrOptions, { store: _this });\n                },\n            };\n            Object.keys(storeObject).forEach(function (storeFieldName) {\n                var fieldName = fieldNameFromStoreName(storeFieldName);\n                var fieldValue = storeObject[storeFieldName];\n                if (fieldValue === void 0)\n                    return;\n                var modify = typeof fields === \"function\" ? fields : (fields[storeFieldName] || fields[fieldName]);\n                if (modify) {\n                    var newValue = modify === delModifier ? DELETE : (modify(maybeDeepFreeze(fieldValue), __assign(__assign({}, sharedDetails_1), { fieldName: fieldName, storeFieldName: storeFieldName, storage: _this.getStorage(dataId, storeFieldName) })));\n                    if (newValue === INVALIDATE) {\n                        _this.group.dirty(dataId, storeFieldName);\n                    }\n                    else {\n                        if (newValue === DELETE)\n                            newValue = void 0;\n                        if (newValue !== fieldValue) {\n                            changedFields_1[storeFieldName] = newValue;\n                            needToMerge_1 = true;\n                            fieldValue = newValue;\n                            if (globalThis.__DEV__ !== false) {\n                                var checkReference = function (ref) {\n                                    if (_this.lookup(ref.__ref) === undefined) {\n                                        globalThis.__DEV__ !== false && invariant.warn(2, ref);\n                                        return true;\n                                    }\n                                };\n                                if (isReference(newValue)) {\n                                    checkReference(newValue);\n                                }\n                                else if (Array.isArray(newValue)) {\n                                    // Warn about writing \"mixed\" arrays of Reference and non-Reference objects\n                                    var seenReference = false;\n                                    var someNonReference = void 0;\n                                    for (var _i = 0, newValue_1 = newValue; _i < newValue_1.length; _i++) {\n                                        var value = newValue_1[_i];\n                                        if (isReference(value)) {\n                                            seenReference = true;\n                                            if (checkReference(value))\n                                                break;\n                                        }\n                                        else {\n                                            // Do not warn on primitive values, since those could never be represented\n                                            // by a reference. This is a valid (albeit uncommon) use case.\n                                            if (typeof value === \"object\" && !!value) {\n                                                var id = _this.policies.identify(value)[0];\n                                                // check if object could even be referenced, otherwise we are not interested in it for this warning\n                                                if (id) {\n                                                    someNonReference = value;\n                                                }\n                                            }\n                                        }\n                                        if (seenReference && someNonReference !== undefined) {\n                                            globalThis.__DEV__ !== false && invariant.warn(3, someNonReference);\n                                            break;\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n                if (fieldValue !== void 0) {\n                    allDeleted_1 = false;\n                }\n            });\n            if (needToMerge_1) {\n                this.merge(dataId, changedFields_1);\n                if (allDeleted_1) {\n                    if (this instanceof Layer) {\n                        this.data[dataId] = void 0;\n                    }\n                    else {\n                        delete this.data[dataId];\n                    }\n                    this.group.dirty(dataId, \"__exists\");\n                }\n                return true;\n            }\n        }\n        return false;\n    };\n    // If called with only one argument, removes the entire entity\n    // identified by dataId. If called with a fieldName as well, removes all\n    // fields of that entity whose names match fieldName according to the\n    // fieldNameFromStoreName helper function. If called with a fieldName\n    // and variables, removes all fields of that entity whose names match fieldName\n    // and whose arguments when cached exactly match the variables passed.\n    EntityStore.prototype.delete = function (dataId, fieldName, args) {\n        var _a;\n        var storeObject = this.lookup(dataId);\n        if (storeObject) {\n            var typename = this.getFieldValue(storeObject, \"__typename\");\n            var storeFieldName = fieldName && args ?\n                this.policies.getStoreFieldName({ typename: typename, fieldName: fieldName, args: args })\n                : fieldName;\n            return this.modify(dataId, storeFieldName ? (_a = {},\n                _a[storeFieldName] = delModifier,\n                _a) : delModifier);\n        }\n        return false;\n    };\n    EntityStore.prototype.evict = function (options, limit) {\n        var evicted = false;\n        if (options.id) {\n            if (hasOwn.call(this.data, options.id)) {\n                evicted = this.delete(options.id, options.fieldName, options.args);\n            }\n            if (this instanceof Layer && this !== limit) {\n                evicted = this.parent.evict(options, limit) || evicted;\n            }\n            // Always invalidate the field to trigger rereading of watched\n            // queries, even if no cache data was modified by the eviction,\n            // because queries may depend on computed fields with custom read\n            // functions, whose values are not stored in the EntityStore.\n            if (options.fieldName || evicted) {\n                this.group.dirty(options.id, options.fieldName || \"__exists\");\n            }\n        }\n        return evicted;\n    };\n    EntityStore.prototype.clear = function () {\n        this.replace(null);\n    };\n    EntityStore.prototype.extract = function () {\n        var _this = this;\n        var obj = this.toObject();\n        var extraRootIds = [];\n        this.getRootIdSet().forEach(function (id) {\n            if (!hasOwn.call(_this.policies.rootTypenamesById, id)) {\n                extraRootIds.push(id);\n            }\n        });\n        if (extraRootIds.length) {\n            obj.__META = { extraRootIds: extraRootIds.sort() };\n        }\n        return obj;\n    };\n    EntityStore.prototype.replace = function (newData) {\n        var _this = this;\n        Object.keys(this.data).forEach(function (dataId) {\n            if (!(newData && hasOwn.call(newData, dataId))) {\n                _this.delete(dataId);\n            }\n        });\n        if (newData) {\n            var __META = newData.__META, rest_1 = __rest(newData, [\"__META\"]);\n            Object.keys(rest_1).forEach(function (dataId) {\n                _this.merge(dataId, rest_1[dataId]);\n            });\n            if (__META) {\n                __META.extraRootIds.forEach(this.retain, this);\n            }\n        }\n    };\n    EntityStore.prototype.retain = function (rootId) {\n        return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);\n    };\n    EntityStore.prototype.release = function (rootId) {\n        if (this.rootIds[rootId] > 0) {\n            var count = --this.rootIds[rootId];\n            if (!count)\n                delete this.rootIds[rootId];\n            return count;\n        }\n        return 0;\n    };\n    // Return a Set<string> of all the ID strings that have been retained by\n    // this layer/root *and* any layers/roots beneath it.\n    EntityStore.prototype.getRootIdSet = function (ids) {\n        if (ids === void 0) { ids = new Set(); }\n        Object.keys(this.rootIds).forEach(ids.add, ids);\n        if (this instanceof Layer) {\n            this.parent.getRootIdSet(ids);\n        }\n        else {\n            // Official singleton IDs like ROOT_QUERY and ROOT_MUTATION are\n            // always considered roots for garbage collection, regardless of\n            // their retainment counts in this.rootIds.\n            Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);\n        }\n        return ids;\n    };\n    // The goal of garbage collection is to remove IDs from the Root layer of the\n    // store that are no longer reachable starting from any IDs that have been\n    // explicitly retained (see retain and release, above). Returns an array of\n    // dataId strings that were removed from the store.\n    EntityStore.prototype.gc = function () {\n        var _this = this;\n        var ids = this.getRootIdSet();\n        var snapshot = this.toObject();\n        ids.forEach(function (id) {\n            if (hasOwn.call(snapshot, id)) {\n                // Because we are iterating over an ECMAScript Set, the IDs we add here\n                // will be visited in later iterations of the forEach loop only if they\n                // were not previously contained by the Set.\n                Object.keys(_this.findChildRefIds(id)).forEach(ids.add, ids);\n                // By removing IDs from the snapshot object here, we protect them from\n                // getting removed from the root store layer below.\n                delete snapshot[id];\n            }\n        });\n        var idsToRemove = Object.keys(snapshot);\n        if (idsToRemove.length) {\n            var root_1 = this;\n            while (root_1 instanceof Layer)\n                root_1 = root_1.parent;\n            idsToRemove.forEach(function (id) { return root_1.delete(id); });\n        }\n        return idsToRemove;\n    };\n    EntityStore.prototype.findChildRefIds = function (dataId) {\n        if (!hasOwn.call(this.refs, dataId)) {\n            var found_1 = (this.refs[dataId] = Object.create(null));\n            var root = this.data[dataId];\n            if (!root)\n                return found_1;\n            var workSet_1 = new Set([root]);\n            // Within the store, only arrays and objects can contain child entity\n            // references, so we can prune the traversal using this predicate:\n            workSet_1.forEach(function (obj) {\n                if (isReference(obj)) {\n                    found_1[obj.__ref] = true;\n                    // In rare cases, a { __ref } Reference object may have other fields.\n                    // This often indicates a mismerging of References with StoreObjects,\n                    // but garbage collection should not be fooled by a stray __ref\n                    // property in a StoreObject (ignoring all the other fields just\n                    // because the StoreObject looks like a Reference). To avoid this\n                    // premature termination of findChildRefIds recursion, we fall through\n                    // to the code below, which will handle any other properties of obj.\n                }\n                if (isNonNullObject(obj)) {\n                    Object.keys(obj).forEach(function (key) {\n                        var child = obj[key];\n                        // No need to add primitive values to the workSet, since they cannot\n                        // contain reference objects.\n                        if (isNonNullObject(child)) {\n                            workSet_1.add(child);\n                        }\n                    });\n                }\n            });\n        }\n        return this.refs[dataId];\n    };\n    EntityStore.prototype.makeCacheKey = function () {\n        return this.group.keyMaker.lookupArray(arguments);\n    };\n    return EntityStore;\n}());\nexport { EntityStore };\n// A single CacheGroup represents a set of one or more EntityStore objects,\n// typically the Root store in a CacheGroup by itself, and all active Layer\n// stores in a group together. A single EntityStore object belongs to only\n// one CacheGroup, store.group. The CacheGroup is responsible for tracking\n// dependencies, so store.group is helpful for generating unique keys for\n// cached results that need to be invalidated when/if those dependencies\n// change. If we used the EntityStore objects themselves as cache keys (that\n// is, store rather than store.group), the cache would become unnecessarily\n// fragmented by all the different Layer objects. Instead, the CacheGroup\n// approach allows all optimistic Layer objects in the same linked list to\n// belong to one CacheGroup, with the non-optimistic Root object belonging\n// to another CacheGroup, allowing resultCaching dependencies to be tracked\n// separately for optimistic and non-optimistic entity data.\nvar CacheGroup = /** @class */ (function () {\n    function CacheGroup(caching, parent) {\n        if (parent === void 0) { parent = null; }\n        this.caching = caching;\n        this.parent = parent;\n        this.d = null;\n        this.resetCaching();\n    }\n    CacheGroup.prototype.resetCaching = function () {\n        this.d = this.caching ? dep() : null;\n        this.keyMaker = new Trie(canUseWeakMap);\n    };\n    CacheGroup.prototype.depend = function (dataId, storeFieldName) {\n        if (this.d) {\n            this.d(makeDepKey(dataId, storeFieldName));\n            var fieldName = fieldNameFromStoreName(storeFieldName);\n            if (fieldName !== storeFieldName) {\n                // Fields with arguments that contribute extra identifying\n                // information to the fieldName (thus forming the storeFieldName)\n                // depend not only on the full storeFieldName but also on the\n                // short fieldName, so the field can be invalidated using either\n                // level of specificity.\n                this.d(makeDepKey(dataId, fieldName));\n            }\n            if (this.parent) {\n                this.parent.depend(dataId, storeFieldName);\n            }\n        }\n    };\n    CacheGroup.prototype.dirty = function (dataId, storeFieldName) {\n        if (this.d) {\n            this.d.dirty(makeDepKey(dataId, storeFieldName), \n            // When storeFieldName === \"__exists\", that means the entity identified\n            // by dataId has either disappeared from the cache or was newly added,\n            // so the result caching system would do well to \"forget everything it\n            // knows\" about that object. To achieve that kind of invalidation, we\n            // not only dirty the associated result cache entry, but also remove it\n            // completely from the dependency graph. For the optimism implementation\n            // details, see https://github.com/benjamn/optimism/pull/195.\n            storeFieldName === \"__exists\" ? \"forget\" : \"setDirty\");\n        }\n    };\n    return CacheGroup;\n}());\nfunction makeDepKey(dataId, storeFieldName) {\n    // Since field names cannot have '#' characters in them, this method\n    // of joining the field name and the ID should be unambiguous, and much\n    // cheaper than JSON.stringify([dataId, fieldName]).\n    return storeFieldName + \"#\" + dataId;\n}\nexport function maybeDependOnExistenceOfEntity(store, entityId) {\n    if (supportsResultCaching(store)) {\n        // We use this pseudo-field __exists elsewhere in the EntityStore code to\n        // represent changes in the existence of the entity object identified by\n        // entityId. This dependency gets reliably dirtied whenever an object with\n        // this ID is deleted (or newly created) within this group, so any result\n        // cache entries (for example, StoreReader#executeSelectionSet results) that\n        // depend on __exists for this entityId will get dirtied as well, leading to\n        // the eventual recomputation (instead of reuse) of those result objects the\n        // next time someone reads them from the cache.\n        store.group.depend(entityId, \"__exists\");\n    }\n}\n(function (EntityStore) {\n    // Refer to this class as EntityStore.Root outside this namespace.\n    var Root = /** @class */ (function (_super) {\n        __extends(Root, _super);\n        function Root(_a) {\n            var policies = _a.policies, _b = _a.resultCaching, resultCaching = _b === void 0 ? true : _b, seed = _a.seed;\n            var _this = _super.call(this, policies, new CacheGroup(resultCaching)) || this;\n            _this.stump = new Stump(_this);\n            _this.storageTrie = new Trie(canUseWeakMap);\n            if (seed)\n                _this.replace(seed);\n            return _this;\n        }\n        Root.prototype.addLayer = function (layerId, replay) {\n            // Adding an optimistic Layer on top of the Root actually adds the Layer\n            // on top of the Stump, so the Stump always comes between the Root and\n            // any Layer objects that we've added.\n            return this.stump.addLayer(layerId, replay);\n        };\n        Root.prototype.removeLayer = function () {\n            // Never remove the root layer.\n            return this;\n        };\n        Root.prototype.getStorage = function () {\n            return this.storageTrie.lookupArray(arguments);\n        };\n        return Root;\n    }(EntityStore));\n    EntityStore.Root = Root;\n})(EntityStore || (EntityStore = {}));\n// Not exported, since all Layer instances are created by the addLayer method\n// of the EntityStore.Root class.\nvar Layer = /** @class */ (function (_super) {\n    __extends(Layer, _super);\n    function Layer(id, parent, replay, group) {\n        var _this = _super.call(this, parent.policies, group) || this;\n        _this.id = id;\n        _this.parent = parent;\n        _this.replay = replay;\n        _this.group = group;\n        replay(_this);\n        return _this;\n    }\n    Layer.prototype.addLayer = function (layerId, replay) {\n        return new Layer(layerId, this, replay, this.group);\n    };\n    Layer.prototype.removeLayer = function (layerId) {\n        var _this = this;\n        // Remove all instances of the given id, not just the first one.\n        var parent = this.parent.removeLayer(layerId);\n        if (layerId === this.id) {\n            if (this.group.caching) {\n                // Dirty every ID we're removing. Technically we might be able to avoid\n                // dirtying fields that have values in higher layers, but we don't have\n                // easy access to higher layers here, and we're about to recreate those\n                // layers anyway (see parent.addLayer below).\n                Object.keys(this.data).forEach(function (dataId) {\n                    var ownStoreObject = _this.data[dataId];\n                    var parentStoreObject = parent[\"lookup\"](dataId);\n                    if (!parentStoreObject) {\n                        // The StoreObject identified by dataId was defined in this layer\n                        // but will be undefined in the parent layer, so we can delete the\n                        // whole entity using this.delete(dataId). Since we're about to\n                        // throw this layer away, the only goal of this deletion is to dirty\n                        // the removed fields.\n                        _this.delete(dataId);\n                    }\n                    else if (!ownStoreObject) {\n                        // This layer had an entry for dataId but it was undefined, which\n                        // means the entity was deleted in this layer, and it's about to\n                        // become undeleted when we remove this layer, so we need to dirty\n                        // all fields that are about to be reexposed.\n                        _this.group.dirty(dataId, \"__exists\");\n                        Object.keys(parentStoreObject).forEach(function (storeFieldName) {\n                            _this.group.dirty(dataId, storeFieldName);\n                        });\n                    }\n                    else if (ownStoreObject !== parentStoreObject) {\n                        // If ownStoreObject is not exactly the same as parentStoreObject,\n                        // dirty any fields whose values will change as a result of this\n                        // removal.\n                        Object.keys(ownStoreObject).forEach(function (storeFieldName) {\n                            if (!equal(ownStoreObject[storeFieldName], parentStoreObject[storeFieldName])) {\n                                _this.group.dirty(dataId, storeFieldName);\n                            }\n                        });\n                    }\n                });\n            }\n            return parent;\n        }\n        // No changes are necessary if the parent chain remains identical.\n        if (parent === this.parent)\n            return this;\n        // Recreate this layer on top of the new parent.\n        return parent.addLayer(this.id, this.replay);\n    };\n    Layer.prototype.toObject = function () {\n        return __assign(__assign({}, this.parent.toObject()), this.data);\n    };\n    Layer.prototype.findChildRefIds = function (dataId) {\n        var fromParent = this.parent.findChildRefIds(dataId);\n        return hasOwn.call(this.data, dataId) ? __assign(__assign({}, fromParent), _super.prototype.findChildRefIds.call(this, dataId)) : fromParent;\n    };\n    Layer.prototype.getStorage = function () {\n        var p = this.parent;\n        while (p.parent)\n            p = p.parent;\n        return p.getStorage.apply(p, \n        // @ts-expect-error\n        arguments);\n    };\n    return Layer;\n}(EntityStore));\n// Represents a Layer permanently installed just above the Root, which allows\n// reading optimistically (and registering optimistic dependencies) even when\n// no optimistic layers are currently active. The stump.group CacheGroup object\n// is shared by any/all Layer objects added on top of the Stump.\nvar Stump = /** @class */ (function (_super) {\n    __extends(Stump, _super);\n    function Stump(root) {\n        return _super.call(this, \"EntityStore.Stump\", root, function () { }, new CacheGroup(root.group.caching, root.group)) || this;\n    }\n    Stump.prototype.removeLayer = function () {\n        // Never remove the Stump layer.\n        return this;\n    };\n    Stump.prototype.merge = function (older, newer) {\n        // We never want to write any data into the Stump, so we forward any merge\n        // calls to the Root instead. Another option here would be to throw an\n        // exception, but the toReference(object, true) function can sometimes\n        // trigger Stump writes (which used to be Root writes, before the Stump\n        // concept was introduced).\n        return this.parent.merge(older, newer);\n    };\n    return Stump;\n}(Layer));\nfunction storeObjectReconciler(existingObject, incomingObject, property) {\n    var existingValue = existingObject[property];\n    var incomingValue = incomingObject[property];\n    // Wherever there is a key collision, prefer the incoming value, unless\n    // it is deeply equal to the existing value. It's worth checking deep\n    // equality here (even though blindly returning incoming would be\n    // logically correct) because preserving the referential identity of\n    // existing data can prevent needless rereading and rerendering.\n    return equal(existingValue, incomingValue) ? existingValue : incomingValue;\n}\nexport function supportsResultCaching(store) {\n    // When result caching is disabled, store.depend will be null.\n    return !!(store instanceof EntityStore && store.group.caching);\n}\n//# sourceMappingURL=entityStore.js.map","import { __assign } from \"tslib\";\nimport { Trie } from \"@wry/trie\";\nimport { canUseWeakMap, canUseWeakSet, isNonNullObject as isObjectOrArray, } from \"../../utilities/index.js\";\nimport { isArray } from \"./helpers.js\";\nfunction shallowCopy(value) {\n    if (isObjectOrArray(value)) {\n        return isArray(value) ?\n            value.slice(0)\n            : __assign({ __proto__: Object.getPrototypeOf(value) }, value);\n    }\n    return value;\n}\n// When programmers talk about the \"canonical form\" of an object, they\n// usually have the following meaning in mind, which I've copied from\n// https://en.wiktionary.org/wiki/canonical_form:\n//\n// 1. A standard or normal presentation of a mathematical entity [or\n//    object]. A canonical form is an element of a set of representatives\n//    of equivalence classes of forms such that there is a function or\n//    procedure which projects every element of each equivalence class\n//    onto that one element, the canonical form of that equivalence\n//    class. The canonical form is expected to be simpler than the rest of\n//    the forms in some way.\n//\n// That's a long-winded way of saying any two objects that have the same\n// canonical form may be considered equivalent, even if they are !==,\n// which usually means the objects are structurally equivalent (deeply\n// equal), but don't necessarily use the same memory.\n//\n// Like a literary or musical canon, this ObjectCanon class represents a\n// collection of unique canonical items (JavaScript objects), with the\n// important property that canon.admit(a) === canon.admit(b) if a and b\n// are deeply equal to each other. In terms of the definition above, the\n// canon.admit method is the \"function or procedure which projects every\"\n// object \"onto that one element, the canonical form.\"\n//\n// In the worst case, the canonicalization process may involve looking at\n// every property in the provided object tree, so it takes the same order\n// of time as deep equality checking. Fortunately, already-canonicalized\n// objects are returned immediately from canon.admit, so the presence of\n// canonical subtrees tends to speed up canonicalization.\n//\n// Since consumers of canonical objects can check for deep equality in\n// constant time, canonicalizing cache results can massively improve the\n// performance of application code that skips re-rendering unchanged\n// results, such as \"pure\" UI components in a framework like React.\n//\n// Of course, since canonical objects may be shared widely between\n// unrelated consumers, it's important to think of them as immutable, even\n// though they are not actually frozen with Object.freeze in production,\n// due to the extra performance overhead that comes with frozen objects.\n//\n// Custom scalar objects whose internal class name is neither Array nor\n// Object can be included safely in the admitted tree, but they will not\n// be replaced with a canonical version (to put it another way, they are\n// assumed to be canonical already).\n//\n// If we ignore custom objects, no detection of cycles or repeated object\n// references is currently required by the StoreReader class, since\n// GraphQL result objects are JSON-serializable trees (and thus contain\n// neither cycles nor repeated subtrees), so we can avoid the complexity\n// of keeping track of objects we've already seen during the recursion of\n// the admit method.\n//\n// In the future, we may consider adding additional cases to the switch\n// statement to handle other common object types, such as \"[object Date]\"\n// objects, as needed.\nvar ObjectCanon = /** @class */ (function () {\n    function ObjectCanon() {\n        // Set of all canonical objects this ObjectCanon has admitted, allowing\n        // canon.admit to return previously-canonicalized objects immediately.\n        this.known = new (canUseWeakSet ? WeakSet : Set)();\n        // Efficient storage/lookup structure for canonical objects.\n        this.pool = new Trie(canUseWeakMap);\n        // Make the ObjectCanon assume this value has already been\n        // canonicalized.\n        this.passes = new WeakMap();\n        // Arrays that contain the same elements in a different order can share\n        // the same SortedKeysInfo object, to save memory.\n        this.keysByJSON = new Map();\n        // This has to come last because it depends on keysByJSON.\n        this.empty = this.admit({});\n    }\n    ObjectCanon.prototype.isKnown = function (value) {\n        return isObjectOrArray(value) && this.known.has(value);\n    };\n    ObjectCanon.prototype.pass = function (value) {\n        if (isObjectOrArray(value)) {\n            var copy = shallowCopy(value);\n            this.passes.set(copy, value);\n            return copy;\n        }\n        return value;\n    };\n    ObjectCanon.prototype.admit = function (value) {\n        var _this = this;\n        if (isObjectOrArray(value)) {\n            var original = this.passes.get(value);\n            if (original)\n                return original;\n            var proto = Object.getPrototypeOf(value);\n            switch (proto) {\n                case Array.prototype: {\n                    if (this.known.has(value))\n                        return value;\n                    var array = value.map(this.admit, this);\n                    // Arrays are looked up in the Trie using their recursively\n                    // canonicalized elements, and the known version of the array is\n                    // preserved as node.array.\n                    var node = this.pool.lookupArray(array);\n                    if (!node.array) {\n                        this.known.add((node.array = array));\n                        // Since canonical arrays may be shared widely between\n                        // unrelated consumers, it's important to regard them as\n                        // immutable, even if they are not frozen in production.\n                        if (globalThis.__DEV__ !== false) {\n                            Object.freeze(array);\n                        }\n                    }\n                    return node.array;\n                }\n                case null:\n                case Object.prototype: {\n                    if (this.known.has(value))\n                        return value;\n                    var proto_1 = Object.getPrototypeOf(value);\n                    var array_1 = [proto_1];\n                    var keys = this.sortedKeys(value);\n                    array_1.push(keys.json);\n                    var firstValueIndex_1 = array_1.length;\n                    keys.sorted.forEach(function (key) {\n                        array_1.push(_this.admit(value[key]));\n                    });\n                    // Objects are looked up in the Trie by their prototype (which\n                    // is *not* recursively canonicalized), followed by a JSON\n                    // representation of their (sorted) keys, followed by the\n                    // sequence of recursively canonicalized values corresponding to\n                    // those keys. To keep the final results unambiguous with other\n                    // sequences (such as arrays that just happen to contain [proto,\n                    // keys.json, value1, value2, ...]), the known version of the\n                    // object is stored as node.object.\n                    var node = this.pool.lookupArray(array_1);\n                    if (!node.object) {\n                        var obj_1 = (node.object = Object.create(proto_1));\n                        this.known.add(obj_1);\n                        keys.sorted.forEach(function (key, i) {\n                            obj_1[key] = array_1[firstValueIndex_1 + i];\n                        });\n                        // Since canonical objects may be shared widely between\n                        // unrelated consumers, it's important to regard them as\n                        // immutable, even if they are not frozen in production.\n                        if (globalThis.__DEV__ !== false) {\n                            Object.freeze(obj_1);\n                        }\n                    }\n                    return node.object;\n                }\n            }\n        }\n        return value;\n    };\n    // It's worthwhile to cache the sorting of arrays of strings, since the\n    // same initial unsorted arrays tend to be encountered many times.\n    // Fortunately, we can reuse the Trie machinery to look up the sorted\n    // arrays in linear time (which is faster than sorting large arrays).\n    ObjectCanon.prototype.sortedKeys = function (obj) {\n        var keys = Object.keys(obj);\n        var node = this.pool.lookupArray(keys);\n        if (!node.keys) {\n            keys.sort();\n            var json = JSON.stringify(keys);\n            if (!(node.keys = this.keysByJSON.get(json))) {\n                this.keysByJSON.set(json, (node.keys = { sorted: keys, json: json }));\n            }\n        }\n        return node.keys;\n    };\n    return ObjectCanon;\n}());\nexport { ObjectCanon };\n//# sourceMappingURL=object-canon.js.map","import { __assign } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { Kind } from \"graphql\";\nimport { wrap } from \"optimism\";\nimport { isField, resultKeyNameFromField, isReference, makeReference, shouldInclude, addTypenameToDocument, getDefaultValues, getMainDefinition, getQueryDefinition, getFragmentFromSelection, maybeDeepFreeze, mergeDeepArray, DeepMerger, isNonNullObject, canUseWeakMap, compact, canonicalStringify, cacheSizes, } from \"../../utilities/index.js\";\nimport { maybeDependOnExistenceOfEntity, supportsResultCaching, } from \"./entityStore.js\";\nimport { isArray, extractFragmentContext, getTypenameFromStoreObject, shouldCanonizeResults, } from \"./helpers.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport { ObjectCanon } from \"./object-canon.js\";\nfunction execSelectionSetKeyArgs(options) {\n    return [\n        options.selectionSet,\n        options.objectOrReference,\n        options.context,\n        // We split out this property so we can pass different values\n        // independently without modifying options.context itself.\n        options.context.canonizeResults,\n    ];\n}\nvar StoreReader = /** @class */ (function () {\n    function StoreReader(config) {\n        var _this = this;\n        this.knownResults = new (canUseWeakMap ? WeakMap : Map)();\n        this.config = compact(config, {\n            addTypename: config.addTypename !== false,\n            canonizeResults: shouldCanonizeResults(config),\n        });\n        this.canon = config.canon || new ObjectCanon();\n        // memoized functions in this class will be \"garbage-collected\"\n        // by recreating the whole `StoreReader` in\n        // `InMemoryCache.resetResultsCache`\n        // (triggered from `InMemoryCache.gc` with `resetResultCache: true`)\n        this.executeSelectionSet = wrap(function (options) {\n            var _a;\n            var canonizeResults = options.context.canonizeResults;\n            var peekArgs = execSelectionSetKeyArgs(options);\n            // Negate this boolean option so we can find out if we've already read\n            // this result using the other boolean value.\n            peekArgs[3] = !canonizeResults;\n            var other = (_a = _this.executeSelectionSet).peek.apply(_a, peekArgs);\n            if (other) {\n                if (canonizeResults) {\n                    return __assign(__assign({}, other), { \n                        // If we previously read this result without canonizing it, we can\n                        // reuse that result simply by canonizing it now.\n                        result: _this.canon.admit(other.result) });\n                }\n                // If we previously read this result with canonization enabled, we can\n                // return that canonized result as-is.\n                return other;\n            }\n            maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);\n            // Finally, if we didn't find any useful previous results, run the real\n            // execSelectionSetImpl method with the given options.\n            return _this.execSelectionSetImpl(options);\n        }, {\n            max: this.config.resultCacheMaxSize ||\n                cacheSizes[\"inMemoryCache.executeSelectionSet\"] ||\n                50000 /* defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"] */,\n            keyArgs: execSelectionSetKeyArgs,\n            // Note that the parameters of makeCacheKey are determined by the\n            // array returned by keyArgs.\n            makeCacheKey: function (selectionSet, parent, context, canonizeResults) {\n                if (supportsResultCaching(context.store)) {\n                    return context.store.makeCacheKey(selectionSet, isReference(parent) ? parent.__ref : parent, context.varString, canonizeResults);\n                }\n            },\n        });\n        this.executeSubSelectedArray = wrap(function (options) {\n            maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);\n            return _this.execSubSelectedArrayImpl(options);\n        }, {\n            max: this.config.resultCacheMaxSize ||\n                cacheSizes[\"inMemoryCache.executeSubSelectedArray\"] ||\n                10000 /* defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"] */,\n            makeCacheKey: function (_a) {\n                var field = _a.field, array = _a.array, context = _a.context;\n                if (supportsResultCaching(context.store)) {\n                    return context.store.makeCacheKey(field, array, context.varString);\n                }\n            },\n        });\n    }\n    StoreReader.prototype.resetCanon = function () {\n        this.canon = new ObjectCanon();\n    };\n    /**\n     * Given a store and a query, return as much of the result as possible and\n     * identify if any data was missing from the store.\n     */\n    StoreReader.prototype.diffQueryAgainstStore = function (_a) {\n        var store = _a.store, query = _a.query, _b = _a.rootId, rootId = _b === void 0 ? \"ROOT_QUERY\" : _b, variables = _a.variables, _c = _a.returnPartialData, returnPartialData = _c === void 0 ? true : _c, _d = _a.canonizeResults, canonizeResults = _d === void 0 ? this.config.canonizeResults : _d;\n        var policies = this.config.cache.policies;\n        variables = __assign(__assign({}, getDefaultValues(getQueryDefinition(query))), variables);\n        var rootRef = makeReference(rootId);\n        var execResult = this.executeSelectionSet({\n            selectionSet: getMainDefinition(query).selectionSet,\n            objectOrReference: rootRef,\n            enclosingRef: rootRef,\n            context: __assign({ store: store, query: query, policies: policies, variables: variables, varString: canonicalStringify(variables), canonizeResults: canonizeResults }, extractFragmentContext(query, this.config.fragments)),\n        });\n        var missing;\n        if (execResult.missing) {\n            // For backwards compatibility we still report an array of\n            // MissingFieldError objects, even though there will only ever be at most\n            // one of them, now that all missing field error messages are grouped\n            // together in the execResult.missing tree.\n            missing = [\n                new MissingFieldError(firstMissing(execResult.missing), execResult.missing, query, variables),\n            ];\n            if (!returnPartialData) {\n                throw missing[0];\n            }\n        }\n        return {\n            result: execResult.result,\n            complete: !missing,\n            missing: missing,\n        };\n    };\n    StoreReader.prototype.isFresh = function (result, parent, selectionSet, context) {\n        if (supportsResultCaching(context.store) &&\n            this.knownResults.get(result) === selectionSet) {\n            var latest = this.executeSelectionSet.peek(selectionSet, parent, context, \n            // If result is canonical, then it could only have been previously\n            // cached by the canonizing version of executeSelectionSet, so we can\n            // avoid checking both possibilities here.\n            this.canon.isKnown(result));\n            if (latest && result === latest.result) {\n                return true;\n            }\n        }\n        return false;\n    };\n    // Uncached version of executeSelectionSet.\n    StoreReader.prototype.execSelectionSetImpl = function (_a) {\n        var _this = this;\n        var selectionSet = _a.selectionSet, objectOrReference = _a.objectOrReference, enclosingRef = _a.enclosingRef, context = _a.context;\n        if (isReference(objectOrReference) &&\n            !context.policies.rootTypenamesById[objectOrReference.__ref] &&\n            !context.store.has(objectOrReference.__ref)) {\n            return {\n                result: this.canon.empty,\n                missing: \"Dangling reference to missing \".concat(objectOrReference.__ref, \" object\"),\n            };\n        }\n        var variables = context.variables, policies = context.policies, store = context.store;\n        var typename = store.getFieldValue(objectOrReference, \"__typename\");\n        var objectsToMerge = [];\n        var missing;\n        var missingMerger = new DeepMerger();\n        if (this.config.addTypename &&\n            typeof typename === \"string\" &&\n            !policies.rootIdsByTypename[typename]) {\n            // Ensure we always include a default value for the __typename\n            // field, if we have one, and this.config.addTypename is true. Note\n            // that this field can be overridden by other merged objects.\n            objectsToMerge.push({ __typename: typename });\n        }\n        function handleMissing(result, resultName) {\n            var _a;\n            if (result.missing) {\n                missing = missingMerger.merge(missing, (_a = {},\n                    _a[resultName] = result.missing,\n                    _a));\n            }\n            return result.result;\n        }\n        var workSet = new Set(selectionSet.selections);\n        workSet.forEach(function (selection) {\n            var _a, _b;\n            // Omit fields with directives @skip(if: <truthy value>) or\n            // @include(if: <falsy value>).\n            if (!shouldInclude(selection, variables))\n                return;\n            if (isField(selection)) {\n                var fieldValue = policies.readField({\n                    fieldName: selection.name.value,\n                    field: selection,\n                    variables: context.variables,\n                    from: objectOrReference,\n                }, context);\n                var resultName = resultKeyNameFromField(selection);\n                if (fieldValue === void 0) {\n                    if (!addTypenameToDocument.added(selection)) {\n                        missing = missingMerger.merge(missing, (_a = {},\n                            _a[resultName] = \"Can't find field '\".concat(selection.name.value, \"' on \").concat(isReference(objectOrReference) ?\n                                objectOrReference.__ref + \" object\"\n                                : \"object \" + JSON.stringify(objectOrReference, null, 2)),\n                            _a));\n                    }\n                }\n                else if (isArray(fieldValue)) {\n                    if (fieldValue.length > 0) {\n                        fieldValue = handleMissing(_this.executeSubSelectedArray({\n                            field: selection,\n                            array: fieldValue,\n                            enclosingRef: enclosingRef,\n                            context: context,\n                        }), resultName);\n                    }\n                }\n                else if (!selection.selectionSet) {\n                    // If the field does not have a selection set, then we handle it\n                    // as a scalar value. To keep this.canon from canonicalizing\n                    // this value, we use this.canon.pass to wrap fieldValue in a\n                    // Pass object that this.canon.admit will later unwrap as-is.\n                    if (context.canonizeResults) {\n                        fieldValue = _this.canon.pass(fieldValue);\n                    }\n                }\n                else if (fieldValue != null) {\n                    // In this case, because we know the field has a selection set,\n                    // it must be trying to query a GraphQLObjectType, which is why\n                    // fieldValue must be != null.\n                    fieldValue = handleMissing(_this.executeSelectionSet({\n                        selectionSet: selection.selectionSet,\n                        objectOrReference: fieldValue,\n                        enclosingRef: isReference(fieldValue) ? fieldValue : enclosingRef,\n                        context: context,\n                    }), resultName);\n                }\n                if (fieldValue !== void 0) {\n                    objectsToMerge.push((_b = {}, _b[resultName] = fieldValue, _b));\n                }\n            }\n            else {\n                var fragment = getFragmentFromSelection(selection, context.lookupFragment);\n                if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n                    throw newInvariantError(9, selection.name.value);\n                }\n                if (fragment && policies.fragmentMatches(fragment, typename)) {\n                    fragment.selectionSet.selections.forEach(workSet.add, workSet);\n                }\n            }\n        });\n        var result = mergeDeepArray(objectsToMerge);\n        var finalResult = { result: result, missing: missing };\n        var frozen = context.canonizeResults ?\n            this.canon.admit(finalResult)\n            // Since this.canon is normally responsible for freezing results (only in\n            // development), freeze them manually if canonization is disabled.\n            : maybeDeepFreeze(finalResult);\n        // Store this result with its selection set so that we can quickly\n        // recognize it again in the StoreReader#isFresh method.\n        if (frozen.result) {\n            this.knownResults.set(frozen.result, selectionSet);\n        }\n        return frozen;\n    };\n    // Uncached version of executeSubSelectedArray.\n    StoreReader.prototype.execSubSelectedArrayImpl = function (_a) {\n        var _this = this;\n        var field = _a.field, array = _a.array, enclosingRef = _a.enclosingRef, context = _a.context;\n        var missing;\n        var missingMerger = new DeepMerger();\n        function handleMissing(childResult, i) {\n            var _a;\n            if (childResult.missing) {\n                missing = missingMerger.merge(missing, (_a = {}, _a[i] = childResult.missing, _a));\n            }\n            return childResult.result;\n        }\n        if (field.selectionSet) {\n            array = array.filter(context.store.canRead);\n        }\n        array = array.map(function (item, i) {\n            // null value in array\n            if (item === null) {\n                return null;\n            }\n            // This is a nested array, recurse\n            if (isArray(item)) {\n                return handleMissing(_this.executeSubSelectedArray({\n                    field: field,\n                    array: item,\n                    enclosingRef: enclosingRef,\n                    context: context,\n                }), i);\n            }\n            // This is an object, run the selection set on it\n            if (field.selectionSet) {\n                return handleMissing(_this.executeSelectionSet({\n                    selectionSet: field.selectionSet,\n                    objectOrReference: item,\n                    enclosingRef: isReference(item) ? item : enclosingRef,\n                    context: context,\n                }), i);\n            }\n            if (globalThis.__DEV__ !== false) {\n                assertSelectionSetForIdValue(context.store, field, item);\n            }\n            return item;\n        });\n        return {\n            result: context.canonizeResults ? this.canon.admit(array) : array,\n            missing: missing,\n        };\n    };\n    return StoreReader;\n}());\nexport { StoreReader };\nfunction firstMissing(tree) {\n    try {\n        JSON.stringify(tree, function (_, value) {\n            if (typeof value === \"string\")\n                throw value;\n            return value;\n        });\n    }\n    catch (result) {\n        return result;\n    }\n}\nfunction assertSelectionSetForIdValue(store, field, fieldValue) {\n    if (!field.selectionSet) {\n        var workSet_1 = new Set([fieldValue]);\n        workSet_1.forEach(function (value) {\n            if (isNonNullObject(value)) {\n                invariant(\n                    !isReference(value),\n                    10,\n                    getTypenameFromStoreObject(store, value),\n                    field.name.value\n                );\n                Object.values(value).forEach(workSet_1.add, workSet_1);\n            }\n        });\n    }\n}\n//# sourceMappingURL=readFromStore.js.map","import { dep, Slot } from \"optimism\";\n// Contextual Slot that acquires its value when custom read functions are\n// called in Policies#readField.\nexport var cacheSlot = new Slot();\nvar cacheInfoMap = new WeakMap();\nfunction getCacheInfo(cache) {\n    var info = cacheInfoMap.get(cache);\n    if (!info) {\n        cacheInfoMap.set(cache, (info = {\n            vars: new Set(),\n            dep: dep(),\n        }));\n    }\n    return info;\n}\nexport function forgetCache(cache) {\n    getCacheInfo(cache).vars.forEach(function (rv) { return rv.forgetCache(cache); });\n}\n// Calling forgetCache(cache) serves to silence broadcasts and allows the\n// cache to be garbage collected. However, the varsByCache WeakMap\n// preserves the set of reactive variables that were previously associated\n// with this cache, which makes it possible to \"recall\" the cache at a\n// later time, by reattaching it to those variables. If the cache has been\n// garbage collected in the meantime, because it is no longer reachable,\n// you won't be able to call recallCache(cache), and the cache will\n// automatically disappear from the varsByCache WeakMap.\nexport function recallCache(cache) {\n    getCacheInfo(cache).vars.forEach(function (rv) { return rv.attachCache(cache); });\n}\nexport function makeVar(value) {\n    var caches = new Set();\n    var listeners = new Set();\n    var rv = function (newValue) {\n        if (arguments.length > 0) {\n            if (value !== newValue) {\n                value = newValue;\n                caches.forEach(function (cache) {\n                    // Invalidate any fields with custom read functions that\n                    // consumed this variable, so query results involving those\n                    // fields will be recomputed the next time we read them.\n                    getCacheInfo(cache).dep.dirty(rv);\n                    // Broadcast changes to any caches that have previously read\n                    // from this variable.\n                    broadcast(cache);\n                });\n                // Finally, notify any listeners added via rv.onNextChange.\n                var oldListeners = Array.from(listeners);\n                listeners.clear();\n                oldListeners.forEach(function (listener) { return listener(value); });\n            }\n        }\n        else {\n            // When reading from the variable, obtain the current cache from\n            // context via cacheSlot. This isn't entirely foolproof, but it's\n            // the same system that powers varDep.\n            var cache = cacheSlot.getValue();\n            if (cache) {\n                attach(cache);\n                getCacheInfo(cache).dep(rv);\n            }\n        }\n        return value;\n    };\n    rv.onNextChange = function (listener) {\n        listeners.add(listener);\n        return function () {\n            listeners.delete(listener);\n        };\n    };\n    var attach = (rv.attachCache = function (cache) {\n        caches.add(cache);\n        getCacheInfo(cache).vars.add(rv);\n        return rv;\n    });\n    rv.forgetCache = function (cache) { return caches.delete(cache); };\n    return rv;\n}\nfunction broadcast(cache) {\n    if (cache.broadcastWatches) {\n        cache.broadcastWatches();\n    }\n}\n//# sourceMappingURL=reactiveVars.js.map","import { invariant } from \"../../utilities/globals/index.js\";\nimport { argumentsObjectFromField, DeepMerger, isNonEmptyArray, isNonNullObject, } from \"../../utilities/index.js\";\nimport { hasOwn, isArray } from \"./helpers.js\";\n// Mapping from JSON-encoded KeySpecifier strings to associated information.\nvar specifierInfoCache = Object.create(null);\nfunction lookupSpecifierInfo(spec) {\n    // It's safe to encode KeySpecifier arrays with JSON.stringify, since they're\n    // just arrays of strings or nested KeySpecifier arrays, and the order of the\n    // array elements is important (and suitably preserved by JSON.stringify).\n    var cacheKey = JSON.stringify(spec);\n    return (specifierInfoCache[cacheKey] ||\n        (specifierInfoCache[cacheKey] = Object.create(null)));\n}\nexport function keyFieldsFnFromSpecifier(specifier) {\n    var info = lookupSpecifierInfo(specifier);\n    return (info.keyFieldsFn || (info.keyFieldsFn = function (object, context) {\n            var extract = function (from, key) {\n                return context.readField(key, from);\n            };\n            var keyObject = (context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {\n                var extracted = extractKeyPath(context.storeObject, schemaKeyPath, \n                // Using context.readField to extract paths from context.storeObject\n                // allows the extraction to see through Reference objects and respect\n                // custom read functions.\n                extract);\n                if (extracted === void 0 &&\n                    object !== context.storeObject &&\n                    hasOwn.call(object, schemaKeyPath[0])) {\n                    // If context.storeObject fails to provide a value for the requested\n                    // path, fall back to the raw result object, if it has a top-level key\n                    // matching the first key in the path (schemaKeyPath[0]). This allows\n                    // key fields included in the written data to be saved in the cache\n                    // even if they are not selected explicitly in context.selectionSet.\n                    // Not being mentioned by context.selectionSet is convenient here,\n                    // since it means these extra fields cannot be affected by field\n                    // aliasing, which is why we can use extractKey instead of\n                    // context.readField for this extraction.\n                    extracted = extractKeyPath(object, schemaKeyPath, extractKey);\n                }\n                invariant(extracted !== void 0, 4, schemaKeyPath.join(\".\"), object);\n                return extracted;\n            }));\n            return \"\".concat(context.typename, \":\").concat(JSON.stringify(keyObject));\n        }));\n}\n// The keyArgs extraction process is roughly analogous to keyFields extraction,\n// but there are no aliases involved, missing fields are tolerated (by merely\n// omitting them from the key), and drawing from field.directives or variables\n// is allowed (in addition to drawing from the field's arguments object).\n// Concretely, these differences mean passing a different key path extractor\n// function to collectSpecifierPaths, reusing the shared extractKeyPath helper\n// wherever possible.\nexport function keyArgsFnFromSpecifier(specifier) {\n    var info = lookupSpecifierInfo(specifier);\n    return (info.keyArgsFn ||\n        (info.keyArgsFn = function (args, _a) {\n            var field = _a.field, variables = _a.variables, fieldName = _a.fieldName;\n            var collected = collectSpecifierPaths(specifier, function (keyPath) {\n                var firstKey = keyPath[0];\n                var firstChar = firstKey.charAt(0);\n                if (firstChar === \"@\") {\n                    if (field && isNonEmptyArray(field.directives)) {\n                        var directiveName_1 = firstKey.slice(1);\n                        // If the directive appears multiple times, only the first\n                        // occurrence's arguments will be used. TODO Allow repetition?\n                        // TODO Cache this work somehow, a la aliasMap?\n                        var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });\n                        // Fortunately argumentsObjectFromField works for DirectiveNode!\n                        var directiveArgs = d && argumentsObjectFromField(d, variables);\n                        // For directives without arguments (d defined, but directiveArgs ===\n                        // null), the presence or absence of the directive still counts as\n                        // part of the field key, so we return null in those cases. If no\n                        // directive with this name was found for this field (d undefined and\n                        // thus directiveArgs undefined), we return undefined, which causes\n                        // this value to be omitted from the key object returned by\n                        // collectSpecifierPaths.\n                        return (directiveArgs &&\n                            extractKeyPath(directiveArgs, \n                            // If keyPath.length === 1, this code calls extractKeyPath with an\n                            // empty path, which works because it uses directiveArgs as the\n                            // extracted value.\n                            keyPath.slice(1)));\n                    }\n                    // If the key started with @ but there was no corresponding directive,\n                    // we want to omit this value from the key object, not fall through to\n                    // treating @whatever as a normal argument name.\n                    return;\n                }\n                if (firstChar === \"$\") {\n                    var variableName = firstKey.slice(1);\n                    if (variables && hasOwn.call(variables, variableName)) {\n                        var varKeyPath = keyPath.slice(0);\n                        varKeyPath[0] = variableName;\n                        return extractKeyPath(variables, varKeyPath);\n                    }\n                    // If the key started with $ but there was no corresponding variable, we\n                    // want to omit this value from the key object, not fall through to\n                    // treating $whatever as a normal argument name.\n                    return;\n                }\n                if (args) {\n                    return extractKeyPath(args, keyPath);\n                }\n            });\n            var suffix = JSON.stringify(collected);\n            // If no arguments were passed to this field, and it didn't have any other\n            // field key contributions from directives or variables, hide the empty\n            // :{} suffix from the field key. However, a field passed no arguments can\n            // still end up with a non-empty :{...} suffix if its key configuration\n            // refers to directives or variables.\n            if (args || suffix !== \"{}\") {\n                fieldName += \":\" + suffix;\n            }\n            return fieldName;\n        }));\n}\nexport function collectSpecifierPaths(specifier, extractor) {\n    // For each path specified by specifier, invoke the extractor, and repeatedly\n    // merge the results together, with appropriate ancestor context.\n    var merger = new DeepMerger();\n    return getSpecifierPaths(specifier).reduce(function (collected, path) {\n        var _a;\n        var toMerge = extractor(path);\n        if (toMerge !== void 0) {\n            // This path is not expected to contain array indexes, so the toMerge\n            // reconstruction will not contain arrays. TODO Fix this?\n            for (var i = path.length - 1; i >= 0; --i) {\n                toMerge = (_a = {}, _a[path[i]] = toMerge, _a);\n            }\n            collected = merger.merge(collected, toMerge);\n        }\n        return collected;\n    }, Object.create(null));\n}\nexport function getSpecifierPaths(spec) {\n    var info = lookupSpecifierInfo(spec);\n    if (!info.paths) {\n        var paths_1 = (info.paths = []);\n        var currentPath_1 = [];\n        spec.forEach(function (s, i) {\n            if (isArray(s)) {\n                getSpecifierPaths(s).forEach(function (p) { return paths_1.push(currentPath_1.concat(p)); });\n                currentPath_1.length = 0;\n            }\n            else {\n                currentPath_1.push(s);\n                if (!isArray(spec[i + 1])) {\n                    paths_1.push(currentPath_1.slice(0));\n                    currentPath_1.length = 0;\n                }\n            }\n        });\n    }\n    return info.paths;\n}\nfunction extractKey(object, key) {\n    return object[key];\n}\nexport function extractKeyPath(object, path, extract) {\n    // For each key in path, extract the corresponding child property from obj,\n    // flattening arrays if encountered (uncommon for keyFields and keyArgs, but\n    // possible). The final result of path.reduce is normalized so unexpected leaf\n    // objects have their keys safely sorted. That final result is difficult to\n    // type as anything other than any. You're welcome to try to improve the\n    // return type, but keep in mind extractKeyPath is not a public function\n    // (exported only for testing), so the effort may not be worthwhile unless the\n    // limited set of actual callers (see above) pass arguments that TypeScript\n    // can statically type. If we know only that path is some array of strings\n    // (and not, say, a specific tuple of statically known strings), any (or\n    // possibly unknown) is the honest answer.\n    extract = extract || extractKey;\n    return normalize(path.reduce(function reducer(obj, key) {\n        return isArray(obj) ?\n            obj.map(function (child) { return reducer(child, key); })\n            : obj && extract(obj, key);\n    }, object));\n}\nfunction normalize(value) {\n    // Usually the extracted value will be a scalar value, since most primary\n    // key fields are scalar, but just in case we get an object or an array, we\n    // need to do some normalization of the order of (nested) keys.\n    if (isNonNullObject(value)) {\n        if (isArray(value)) {\n            return value.map(normalize);\n        }\n        return collectSpecifierPaths(Object.keys(value).sort(), function (path) {\n            return extractKeyPath(value, path);\n        });\n    }\n    return value;\n}\n//# sourceMappingURL=key-extractor.js.map","import { __assign, __rest } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { storeKeyNameFromField, argumentsObjectFromField, isReference, getStoreKeyName, isNonNullObject, stringifyForDisplay, } from \"../../utilities/index.js\";\nimport { hasOwn, fieldNameFromStoreName, storeValueIsStoreObject, selectionSetMatchesResult, TypeOrFieldNameRegExp, defaultDataIdFromObject, isArray, } from \"./helpers.js\";\nimport { cacheSlot } from \"./reactiveVars.js\";\nimport { keyArgsFnFromSpecifier, keyFieldsFnFromSpecifier, } from \"./key-extractor.js\";\nfunction argsFromFieldSpecifier(spec) {\n    return (spec.args !== void 0 ? spec.args\n        : spec.field ? argumentsObjectFromField(spec.field, spec.variables)\n            : null);\n}\nvar nullKeyFieldsFn = function () { return void 0; };\nvar simpleKeyArgsFn = function (_args, context) { return context.fieldName; };\n// These merge functions can be selected by specifying merge:true or\n// merge:false in a field policy.\nvar mergeTrueFn = function (existing, incoming, _a) {\n    var mergeObjects = _a.mergeObjects;\n    return mergeObjects(existing, incoming);\n};\nvar mergeFalseFn = function (_, incoming) { return incoming; };\nvar Policies = /** @class */ (function () {\n    function Policies(config) {\n        this.config = config;\n        this.typePolicies = Object.create(null);\n        this.toBeAdded = Object.create(null);\n        // Map from subtype names to sets of supertype names. Note that this\n        // representation inverts the structure of possibleTypes (whose keys are\n        // supertypes and whose values are arrays of subtypes) because it tends\n        // to be much more efficient to search upwards than downwards.\n        this.supertypeMap = new Map();\n        // Any fuzzy subtypes specified by possibleTypes will be converted to\n        // RegExp objects and recorded here. Every key of this map can also be\n        // found in supertypeMap. In many cases this Map will be empty, which\n        // means no fuzzy subtype checking will happen in fragmentMatches.\n        this.fuzzySubtypes = new Map();\n        this.rootIdsByTypename = Object.create(null);\n        this.rootTypenamesById = Object.create(null);\n        this.usingPossibleTypes = false;\n        this.config = __assign({ dataIdFromObject: defaultDataIdFromObject }, config);\n        this.cache = this.config.cache;\n        this.setRootTypename(\"Query\");\n        this.setRootTypename(\"Mutation\");\n        this.setRootTypename(\"Subscription\");\n        if (config.possibleTypes) {\n            this.addPossibleTypes(config.possibleTypes);\n        }\n        if (config.typePolicies) {\n            this.addTypePolicies(config.typePolicies);\n        }\n    }\n    Policies.prototype.identify = function (object, partialContext) {\n        var _a;\n        var policies = this;\n        var typename = (partialContext &&\n            (partialContext.typename || ((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename))) ||\n            object.__typename;\n        // It should be possible to write root Query fields with writeFragment,\n        // using { __typename: \"Query\", ... } as the data, but it does not make\n        // sense to allow the same identification behavior for the Mutation and\n        // Subscription types, since application code should never be writing\n        // directly to (or reading directly from) those root objects.\n        if (typename === this.rootTypenamesById.ROOT_QUERY) {\n            return [\"ROOT_QUERY\"];\n        }\n        // Default context.storeObject to object if not otherwise provided.\n        var storeObject = (partialContext && partialContext.storeObject) || object;\n        var context = __assign(__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: (partialContext && partialContext.readField) ||\n                function () {\n                    var options = normalizeReadFieldOptions(arguments, storeObject);\n                    return policies.readField(options, {\n                        store: policies.cache[\"data\"],\n                        variables: options.variables,\n                    });\n                } });\n        var id;\n        var policy = typename && this.getTypePolicy(typename);\n        var keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;\n        while (keyFn) {\n            var specifierOrId = keyFn(__assign(__assign({}, object), storeObject), context);\n            if (isArray(specifierOrId)) {\n                keyFn = keyFieldsFnFromSpecifier(specifierOrId);\n            }\n            else {\n                id = specifierOrId;\n                break;\n            }\n        }\n        id = id ? String(id) : void 0;\n        return context.keyObject ? [id, context.keyObject] : [id];\n    };\n    Policies.prototype.addTypePolicies = function (typePolicies) {\n        var _this = this;\n        Object.keys(typePolicies).forEach(function (typename) {\n            var _a = typePolicies[typename], queryType = _a.queryType, mutationType = _a.mutationType, subscriptionType = _a.subscriptionType, incoming = __rest(_a, [\"queryType\", \"mutationType\", \"subscriptionType\"]);\n            // Though {query,mutation,subscription}Type configurations are rare,\n            // it's important to call setRootTypename as early as possible,\n            // since these configurations should apply consistently for the\n            // entire lifetime of the cache. Also, since only one __typename can\n            // qualify as one of these root types, these three properties cannot\n            // be inherited, unlike the rest of the incoming properties. That\n            // restriction is convenient, because the purpose of this.toBeAdded\n            // is to delay the processing of type/field policies until the first\n            // time they're used, allowing policies to be added in any order as\n            // long as all relevant policies (including policies for supertypes)\n            // have been added by the time a given policy is used for the first\n            // time. In other words, since inheritance doesn't matter for these\n            // properties, there's also no need to delay their processing using\n            // the this.toBeAdded queue.\n            if (queryType)\n                _this.setRootTypename(\"Query\", typename);\n            if (mutationType)\n                _this.setRootTypename(\"Mutation\", typename);\n            if (subscriptionType)\n                _this.setRootTypename(\"Subscription\", typename);\n            if (hasOwn.call(_this.toBeAdded, typename)) {\n                _this.toBeAdded[typename].push(incoming);\n            }\n            else {\n                _this.toBeAdded[typename] = [incoming];\n            }\n        });\n    };\n    Policies.prototype.updateTypePolicy = function (typename, incoming) {\n        var _this = this;\n        var existing = this.getTypePolicy(typename);\n        var keyFields = incoming.keyFields, fields = incoming.fields;\n        function setMerge(existing, merge) {\n            existing.merge =\n                typeof merge === \"function\" ? merge\n                    // Pass merge:true as a shorthand for a merge implementation\n                    // that returns options.mergeObjects(existing, incoming).\n                    : merge === true ? mergeTrueFn\n                        // Pass merge:false to make incoming always replace existing\n                        // without any warnings about data clobbering.\n                        : merge === false ? mergeFalseFn\n                            : existing.merge;\n        }\n        // Type policies can define merge functions, as an alternative to\n        // using field policies to merge child objects.\n        setMerge(existing, incoming.merge);\n        existing.keyFn =\n            // Pass false to disable normalization for this typename.\n            keyFields === false ? nullKeyFieldsFn\n                // Pass an array of strings to use those fields to compute a\n                // composite ID for objects of this typename.\n                : isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields)\n                    // Pass a function to take full control over identification.\n                    : typeof keyFields === \"function\" ? keyFields\n                        // Leave existing.keyFn unchanged if above cases fail.\n                        : existing.keyFn;\n        if (fields) {\n            Object.keys(fields).forEach(function (fieldName) {\n                var existing = _this.getFieldPolicy(typename, fieldName, true);\n                var incoming = fields[fieldName];\n                if (typeof incoming === \"function\") {\n                    existing.read = incoming;\n                }\n                else {\n                    var keyArgs = incoming.keyArgs, read = incoming.read, merge = incoming.merge;\n                    existing.keyFn =\n                        // Pass false to disable argument-based differentiation of\n                        // field identities.\n                        keyArgs === false ? simpleKeyArgsFn\n                            // Pass an array of strings to use named arguments to\n                            // compute a composite identity for the field.\n                            : isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs)\n                                // Pass a function to take full control over field identity.\n                                : typeof keyArgs === \"function\" ? keyArgs\n                                    // Leave existing.keyFn unchanged if above cases fail.\n                                    : existing.keyFn;\n                    if (typeof read === \"function\") {\n                        existing.read = read;\n                    }\n                    setMerge(existing, merge);\n                }\n                if (existing.read && existing.merge) {\n                    // If we have both a read and a merge function, assume\n                    // keyArgs:false, because read and merge together can take\n                    // responsibility for interpreting arguments in and out. This\n                    // default assumption can always be overridden by specifying\n                    // keyArgs explicitly in the FieldPolicy.\n                    existing.keyFn = existing.keyFn || simpleKeyArgsFn;\n                }\n            });\n        }\n    };\n    Policies.prototype.setRootTypename = function (which, typename) {\n        if (typename === void 0) { typename = which; }\n        var rootId = \"ROOT_\" + which.toUpperCase();\n        var old = this.rootTypenamesById[rootId];\n        if (typename !== old) {\n            invariant(!old || old === which, 5, which);\n            // First, delete any old __typename associated with this rootId from\n            // rootIdsByTypename.\n            if (old)\n                delete this.rootIdsByTypename[old];\n            // Now make this the only __typename that maps to this rootId.\n            this.rootIdsByTypename[typename] = rootId;\n            // Finally, update the __typename associated with this rootId.\n            this.rootTypenamesById[rootId] = typename;\n        }\n    };\n    Policies.prototype.addPossibleTypes = function (possibleTypes) {\n        var _this = this;\n        this.usingPossibleTypes = true;\n        Object.keys(possibleTypes).forEach(function (supertype) {\n            // Make sure all types have an entry in this.supertypeMap, even if\n            // their supertype set is empty, so we can return false immediately\n            // from policies.fragmentMatches for unknown supertypes.\n            _this.getSupertypeSet(supertype, true);\n            possibleTypes[supertype].forEach(function (subtype) {\n                _this.getSupertypeSet(subtype, true).add(supertype);\n                var match = subtype.match(TypeOrFieldNameRegExp);\n                if (!match || match[0] !== subtype) {\n                    // TODO Don't interpret just any invalid typename as a RegExp.\n                    _this.fuzzySubtypes.set(subtype, new RegExp(subtype));\n                }\n            });\n        });\n    };\n    Policies.prototype.getTypePolicy = function (typename) {\n        var _this = this;\n        if (!hasOwn.call(this.typePolicies, typename)) {\n            var policy_1 = (this.typePolicies[typename] = Object.create(null));\n            policy_1.fields = Object.create(null);\n            // When the TypePolicy for typename is first accessed, instead of\n            // starting with an empty policy object, inherit any properties or\n            // fields from the type policies of the supertypes of typename.\n            //\n            // Any properties or fields defined explicitly within the TypePolicy\n            // for typename will take precedence, and if there are multiple\n            // supertypes, the properties of policies whose types were added\n            // later via addPossibleTypes will take precedence over those of\n            // earlier supertypes. TODO Perhaps we should warn about these\n            // conflicts in development, and recommend defining the property\n            // explicitly in the subtype policy?\n            //\n            // Field policy inheritance is atomic/shallow: you can't inherit a\n            // field policy and then override just its read function, since read\n            // and merge functions often need to cooperate, so changing only one\n            // of them would be a recipe for inconsistency.\n            //\n            // Once the TypePolicy for typename has been accessed, its properties can\n            // still be updated directly using addTypePolicies, but future changes to\n            // inherited supertype policies will not be reflected in this subtype\n            // policy, because this code runs at most once per typename.\n            var supertypes_1 = this.supertypeMap.get(typename);\n            if (!supertypes_1 && this.fuzzySubtypes.size) {\n                // To make the inheritance logic work for unknown typename strings that\n                // may have fuzzy supertypes, we give this typename an empty supertype\n                // set and then populate it with any fuzzy supertypes that match.\n                supertypes_1 = this.getSupertypeSet(typename, true);\n                // This only works for typenames that are directly matched by a fuzzy\n                // supertype. What if there is an intermediate chain of supertypes?\n                // While possible, that situation can only be solved effectively by\n                // specifying the intermediate relationships via possibleTypes, manually\n                // and in a non-fuzzy way.\n                this.fuzzySubtypes.forEach(function (regExp, fuzzy) {\n                    if (regExp.test(typename)) {\n                        // The fuzzy parameter is just the original string version of regExp\n                        // (not a valid __typename string), but we can look up the\n                        // associated supertype(s) in this.supertypeMap.\n                        var fuzzySupertypes = _this.supertypeMap.get(fuzzy);\n                        if (fuzzySupertypes) {\n                            fuzzySupertypes.forEach(function (supertype) {\n                                return supertypes_1.add(supertype);\n                            });\n                        }\n                    }\n                });\n            }\n            if (supertypes_1 && supertypes_1.size) {\n                supertypes_1.forEach(function (supertype) {\n                    var _a = _this.getTypePolicy(supertype), fields = _a.fields, rest = __rest(_a, [\"fields\"]);\n                    Object.assign(policy_1, rest);\n                    Object.assign(policy_1.fields, fields);\n                });\n            }\n        }\n        var inbox = this.toBeAdded[typename];\n        if (inbox && inbox.length) {\n            // Merge the pending policies into this.typePolicies, in the order they\n            // were originally passed to addTypePolicy.\n            inbox.splice(0).forEach(function (policy) {\n                _this.updateTypePolicy(typename, policy);\n            });\n        }\n        return this.typePolicies[typename];\n    };\n    Policies.prototype.getFieldPolicy = function (typename, fieldName, createIfMissing) {\n        if (typename) {\n            var fieldPolicies = this.getTypePolicy(typename).fields;\n            return (fieldPolicies[fieldName] ||\n                (createIfMissing && (fieldPolicies[fieldName] = Object.create(null))));\n        }\n    };\n    Policies.prototype.getSupertypeSet = function (subtype, createIfMissing) {\n        var supertypeSet = this.supertypeMap.get(subtype);\n        if (!supertypeSet && createIfMissing) {\n            this.supertypeMap.set(subtype, (supertypeSet = new Set()));\n        }\n        return supertypeSet;\n    };\n    Policies.prototype.fragmentMatches = function (fragment, typename, result, variables) {\n        var _this = this;\n        if (!fragment.typeCondition)\n            return true;\n        // If the fragment has a type condition but the object we're matching\n        // against does not have a __typename, the fragment cannot match.\n        if (!typename)\n            return false;\n        var supertype = fragment.typeCondition.name.value;\n        // Common case: fragment type condition and __typename are the same.\n        if (typename === supertype)\n            return true;\n        if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {\n            var typenameSupertypeSet = this.getSupertypeSet(typename, true);\n            var workQueue_1 = [typenameSupertypeSet];\n            var maybeEnqueue_1 = function (subtype) {\n                var supertypeSet = _this.getSupertypeSet(subtype, false);\n                if (supertypeSet &&\n                    supertypeSet.size &&\n                    workQueue_1.indexOf(supertypeSet) < 0) {\n                    workQueue_1.push(supertypeSet);\n                }\n            };\n            // We need to check fuzzy subtypes only if we encountered fuzzy\n            // subtype strings in addPossibleTypes, and only while writing to\n            // the cache, since that's when selectionSetMatchesResult gives a\n            // strong signal of fragment matching. The StoreReader class calls\n            // policies.fragmentMatches without passing a result object, so\n            // needToCheckFuzzySubtypes is always false while reading.\n            var needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);\n            var checkingFuzzySubtypes = false;\n            // It's important to keep evaluating workQueue.length each time through\n            // the loop, because the queue can grow while we're iterating over it.\n            for (var i = 0; i < workQueue_1.length; ++i) {\n                var supertypeSet = workQueue_1[i];\n                if (supertypeSet.has(supertype)) {\n                    if (!typenameSupertypeSet.has(supertype)) {\n                        if (checkingFuzzySubtypes) {\n                            globalThis.__DEV__ !== false && invariant.warn(6, typename, supertype);\n                        }\n                        // Record positive results for faster future lookup.\n                        // Unfortunately, we cannot safely cache negative results,\n                        // because new possibleTypes data could always be added to the\n                        // Policies class.\n                        typenameSupertypeSet.add(supertype);\n                    }\n                    return true;\n                }\n                supertypeSet.forEach(maybeEnqueue_1);\n                if (needToCheckFuzzySubtypes &&\n                    // Start checking fuzzy subtypes only after exhausting all\n                    // non-fuzzy subtypes (after the final iteration of the loop).\n                    i === workQueue_1.length - 1 &&\n                    // We could wait to compare fragment.selectionSet to result\n                    // after we verify the supertype, but this check is often less\n                    // expensive than that search, and we will have to do the\n                    // comparison anyway whenever we find a potential match.\n                    selectionSetMatchesResult(fragment.selectionSet, result, variables)) {\n                    // We don't always need to check fuzzy subtypes (if no result\n                    // was provided, or !this.fuzzySubtypes.size), but, when we do,\n                    // we only want to check them once.\n                    needToCheckFuzzySubtypes = false;\n                    checkingFuzzySubtypes = true;\n                    // If we find any fuzzy subtypes that match typename, extend the\n                    // workQueue to search through the supertypes of those fuzzy\n                    // subtypes. Otherwise the for-loop will terminate and we'll\n                    // return false below.\n                    this.fuzzySubtypes.forEach(function (regExp, fuzzyString) {\n                        var match = typename.match(regExp);\n                        if (match && match[0] === typename) {\n                            maybeEnqueue_1(fuzzyString);\n                        }\n                    });\n                }\n            }\n        }\n        return false;\n    };\n    Policies.prototype.hasKeyArgs = function (typename, fieldName) {\n        var policy = this.getFieldPolicy(typename, fieldName, false);\n        return !!(policy && policy.keyFn);\n    };\n    Policies.prototype.getStoreFieldName = function (fieldSpec) {\n        var typename = fieldSpec.typename, fieldName = fieldSpec.fieldName;\n        var policy = this.getFieldPolicy(typename, fieldName, false);\n        var storeFieldName;\n        var keyFn = policy && policy.keyFn;\n        if (keyFn && typename) {\n            var context = {\n                typename: typename,\n                fieldName: fieldName,\n                field: fieldSpec.field || null,\n                variables: fieldSpec.variables,\n            };\n            var args = argsFromFieldSpecifier(fieldSpec);\n            while (keyFn) {\n                var specifierOrString = keyFn(args, context);\n                if (isArray(specifierOrString)) {\n                    keyFn = keyArgsFnFromSpecifier(specifierOrString);\n                }\n                else {\n                    // If the custom keyFn returns a falsy value, fall back to\n                    // fieldName instead.\n                    storeFieldName = specifierOrString || fieldName;\n                    break;\n                }\n            }\n        }\n        if (storeFieldName === void 0) {\n            storeFieldName =\n                fieldSpec.field ?\n                    storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)\n                    : getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));\n        }\n        // Returning false from a keyArgs function is like configuring\n        // keyArgs: false, but more dynamic.\n        if (storeFieldName === false) {\n            return fieldName;\n        }\n        // Make sure custom field names start with the actual field.name.value\n        // of the field, so we can always figure out which properties of a\n        // StoreObject correspond to which original field names.\n        return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName\n            : fieldName + \":\" + storeFieldName;\n    };\n    Policies.prototype.readField = function (options, context) {\n        var objectOrReference = options.from;\n        if (!objectOrReference)\n            return;\n        var nameOrField = options.field || options.fieldName;\n        if (!nameOrField)\n            return;\n        if (options.typename === void 0) {\n            var typename = context.store.getFieldValue(objectOrReference, \"__typename\");\n            if (typename)\n                options.typename = typename;\n        }\n        var storeFieldName = this.getStoreFieldName(options);\n        var fieldName = fieldNameFromStoreName(storeFieldName);\n        var existing = context.store.getFieldValue(objectOrReference, storeFieldName);\n        var policy = this.getFieldPolicy(options.typename, fieldName, false);\n        var read = policy && policy.read;\n        if (read) {\n            var readOptions = makeFieldFunctionOptions(this, objectOrReference, options, context, context.store.getStorage(isReference(objectOrReference) ?\n                objectOrReference.__ref\n                : objectOrReference, storeFieldName));\n            // Call read(existing, readOptions) with cacheSlot holding this.cache.\n            return cacheSlot.withValue(this.cache, read, [\n                existing,\n                readOptions,\n            ]);\n        }\n        return existing;\n    };\n    Policies.prototype.getReadFunction = function (typename, fieldName) {\n        var policy = this.getFieldPolicy(typename, fieldName, false);\n        return policy && policy.read;\n    };\n    Policies.prototype.getMergeFunction = function (parentTypename, fieldName, childTypename) {\n        var policy = this.getFieldPolicy(parentTypename, fieldName, false);\n        var merge = policy && policy.merge;\n        if (!merge && childTypename) {\n            policy = this.getTypePolicy(childTypename);\n            merge = policy && policy.merge;\n        }\n        return merge;\n    };\n    Policies.prototype.runMergeFunction = function (existing, incoming, _a, context, storage) {\n        var field = _a.field, typename = _a.typename, merge = _a.merge;\n        if (merge === mergeTrueFn) {\n            // Instead of going to the trouble of creating a full\n            // FieldFunctionOptions object and calling mergeTrueFn, we can\n            // simply call mergeObjects, as mergeTrueFn would.\n            return makeMergeObjectsFunction(context.store)(existing, incoming);\n        }\n        if (merge === mergeFalseFn) {\n            // Likewise for mergeFalseFn, whose implementation is even simpler.\n            return incoming;\n        }\n        // If cache.writeQuery or cache.writeFragment was called with\n        // options.overwrite set to true, we still call merge functions, but\n        // the existing data is always undefined, so the merge function will\n        // not attempt to combine the incoming data with the existing data.\n        if (context.overwrite) {\n            existing = void 0;\n        }\n        return merge(existing, incoming, makeFieldFunctionOptions(this, \n        // Unlike options.readField for read functions, we do not fall\n        // back to the current object if no foreignObjOrRef is provided,\n        // because it's not clear what the current object should be for\n        // merge functions: the (possibly undefined) existing object, or\n        // the incoming object? If you think your merge function needs\n        // to read sibling fields in order to produce a new value for\n        // the current field, you might want to rethink your strategy,\n        // because that's a recipe for making merge behavior sensitive\n        // to the order in which fields are written into the cache.\n        // However, readField(name, ref) is useful for merge functions\n        // that need to deduplicate child objects and references.\n        void 0, {\n            typename: typename,\n            fieldName: field.name.value,\n            field: field,\n            variables: context.variables,\n        }, context, storage || Object.create(null)));\n    };\n    return Policies;\n}());\nexport { Policies };\nfunction makeFieldFunctionOptions(policies, objectOrReference, fieldSpec, context, storage) {\n    var storeFieldName = policies.getStoreFieldName(fieldSpec);\n    var fieldName = fieldNameFromStoreName(storeFieldName);\n    var variables = fieldSpec.variables || context.variables;\n    var _a = context.store, toReference = _a.toReference, canRead = _a.canRead;\n    return {\n        args: argsFromFieldSpecifier(fieldSpec),\n        field: fieldSpec.field || null,\n        fieldName: fieldName,\n        storeFieldName: storeFieldName,\n        variables: variables,\n        isReference: isReference,\n        toReference: toReference,\n        storage: storage,\n        cache: policies.cache,\n        canRead: canRead,\n        readField: function () {\n            return policies.readField(normalizeReadFieldOptions(arguments, objectOrReference, variables), context);\n        },\n        mergeObjects: makeMergeObjectsFunction(context.store),\n    };\n}\nexport function normalizeReadFieldOptions(readFieldArgs, objectOrReference, variables) {\n    var fieldNameOrOptions = readFieldArgs[0], from = readFieldArgs[1], argc = readFieldArgs.length;\n    var options;\n    if (typeof fieldNameOrOptions === \"string\") {\n        options = {\n            fieldName: fieldNameOrOptions,\n            // Default to objectOrReference only when no second argument was\n            // passed for the from parameter, not when undefined is explicitly\n            // passed as the second argument.\n            from: argc > 1 ? from : objectOrReference,\n        };\n    }\n    else {\n        options = __assign({}, fieldNameOrOptions);\n        // Default to objectOrReference only when fieldNameOrOptions.from is\n        // actually omitted, rather than just undefined.\n        if (!hasOwn.call(options, \"from\")) {\n            options.from = objectOrReference;\n        }\n    }\n    if (globalThis.__DEV__ !== false && options.from === void 0) {\n        globalThis.__DEV__ !== false && invariant.warn(7, stringifyForDisplay(Array.from(readFieldArgs)));\n    }\n    if (void 0 === options.variables) {\n        options.variables = variables;\n    }\n    return options;\n}\nfunction makeMergeObjectsFunction(store) {\n    return function mergeObjects(existing, incoming) {\n        if (isArray(existing) || isArray(incoming)) {\n            throw newInvariantError(8);\n        }\n        // These dynamic checks are necessary because the parameters of a\n        // custom merge function can easily have the any type, so the type\n        // system cannot always enforce the StoreObject | Reference parameter\n        // types of options.mergeObjects.\n        if (isNonNullObject(existing) && isNonNullObject(incoming)) {\n            var eType = store.getFieldValue(existing, \"__typename\");\n            var iType = store.getFieldValue(incoming, \"__typename\");\n            var typesDiffer = eType && iType && eType !== iType;\n            if (typesDiffer) {\n                return incoming;\n            }\n            if (isReference(existing) && storeValueIsStoreObject(incoming)) {\n                // Update the normalized EntityStore for the entity identified by\n                // existing.__ref, preferring/overwriting any fields contributed by the\n                // newer incoming StoreObject.\n                store.merge(existing.__ref, incoming);\n                return existing;\n            }\n            if (storeValueIsStoreObject(existing) && isReference(incoming)) {\n                // Update the normalized EntityStore for the entity identified by\n                // incoming.__ref, taking fields from the older existing object only if\n                // those fields are not already present in the newer StoreObject\n                // identified by incoming.__ref.\n                store.merge(existing, incoming.__ref);\n                return incoming;\n            }\n            if (storeValueIsStoreObject(existing) &&\n                storeValueIsStoreObject(incoming)) {\n                return __assign(__assign({}, existing), incoming);\n            }\n        }\n        return incoming;\n    };\n}\n//# sourceMappingURL=policies.js.map","import { __assign } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport { Kind } from \"graphql\";\nimport { getFragmentFromSelection, getDefaultValues, getOperationDefinition, getTypenameFromResult, makeReference, isField, resultKeyNameFromField, isReference, shouldInclude, cloneDeep, addTypenameToDocument, isNonEmptyArray, argumentsObjectFromField, canonicalStringify, } from \"../../utilities/index.js\";\nimport { isArray, makeProcessedFieldsMerger, fieldNameFromStoreName, storeValueIsStoreObject, extractFragmentContext, } from \"./helpers.js\";\nimport { normalizeReadFieldOptions } from \"./policies.js\";\n// Since there are only four possible combinations of context.clientOnly and\n// context.deferred values, we should need at most four \"flavors\" of any given\n// WriteContext. To avoid creating multiple copies of the same context, we cache\n// the contexts in the context.flavors Map (shared by all flavors) according to\n// their clientOnly and deferred values (always in that order).\nfunction getContextFlavor(context, clientOnly, deferred) {\n    var key = \"\".concat(clientOnly).concat(deferred);\n    var flavored = context.flavors.get(key);\n    if (!flavored) {\n        context.flavors.set(key, (flavored =\n            context.clientOnly === clientOnly && context.deferred === deferred ?\n                context\n                : __assign(__assign({}, context), { clientOnly: clientOnly, deferred: deferred })));\n    }\n    return flavored;\n}\nvar StoreWriter = /** @class */ (function () {\n    function StoreWriter(cache, reader, fragments) {\n        this.cache = cache;\n        this.reader = reader;\n        this.fragments = fragments;\n    }\n    StoreWriter.prototype.writeToStore = function (store, _a) {\n        var _this = this;\n        var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;\n        var operationDefinition = getOperationDefinition(query);\n        var merger = makeProcessedFieldsMerger();\n        variables = __assign(__assign({}, getDefaultValues(operationDefinition)), variables);\n        var context = __assign(__assign({ store: store, written: Object.create(null), merge: function (existing, incoming) {\n                return merger.merge(existing, incoming);\n            }, variables: variables, varString: canonicalStringify(variables) }, extractFragmentContext(query, this.fragments)), { overwrite: !!overwrite, incomingById: new Map(), clientOnly: false, deferred: false, flavors: new Map() });\n        var ref = this.processSelectionSet({\n            result: result || Object.create(null),\n            dataId: dataId,\n            selectionSet: operationDefinition.selectionSet,\n            mergeTree: { map: new Map() },\n            context: context,\n        });\n        if (!isReference(ref)) {\n            throw newInvariantError(11, result);\n        }\n        // So far, the store has not been modified, so now it's time to process\n        // context.incomingById and merge those incoming fields into context.store.\n        context.incomingById.forEach(function (_a, dataId) {\n            var storeObject = _a.storeObject, mergeTree = _a.mergeTree, fieldNodeSet = _a.fieldNodeSet;\n            var entityRef = makeReference(dataId);\n            if (mergeTree && mergeTree.map.size) {\n                var applied = _this.applyMerges(mergeTree, entityRef, storeObject, context);\n                if (isReference(applied)) {\n                    // Assume References returned by applyMerges have already been merged\n                    // into the store. See makeMergeObjectsFunction in policies.ts for an\n                    // example of how this can happen.\n                    return;\n                }\n                // Otherwise, applyMerges returned a StoreObject, whose fields we should\n                // merge into the store (see store.merge statement below).\n                storeObject = applied;\n            }\n            if (globalThis.__DEV__ !== false && !context.overwrite) {\n                var fieldsWithSelectionSets_1 = Object.create(null);\n                fieldNodeSet.forEach(function (field) {\n                    if (field.selectionSet) {\n                        fieldsWithSelectionSets_1[field.name.value] = true;\n                    }\n                });\n                var hasSelectionSet_1 = function (storeFieldName) {\n                    return fieldsWithSelectionSets_1[fieldNameFromStoreName(storeFieldName)] ===\n                        true;\n                };\n                var hasMergeFunction_1 = function (storeFieldName) {\n                    var childTree = mergeTree && mergeTree.map.get(storeFieldName);\n                    return Boolean(childTree && childTree.info && childTree.info.merge);\n                };\n                Object.keys(storeObject).forEach(function (storeFieldName) {\n                    // If a merge function was defined for this field, trust that it\n                    // did the right thing about (not) clobbering data. If the field\n                    // has no selection set, it's a scalar field, so it doesn't need\n                    // a merge function (even if it's an object, like JSON data).\n                    if (hasSelectionSet_1(storeFieldName) &&\n                        !hasMergeFunction_1(storeFieldName)) {\n                        warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);\n                    }\n                });\n            }\n            store.merge(dataId, storeObject);\n        });\n        // Any IDs written explicitly to the cache will be retained as\n        // reachable root IDs for garbage collection purposes. Although this\n        // logic includes root IDs like ROOT_QUERY and ROOT_MUTATION, their\n        // retainment counts are effectively ignored because cache.gc() always\n        // includes them in its root ID set.\n        store.retain(ref.__ref);\n        return ref;\n    };\n    StoreWriter.prototype.processSelectionSet = function (_a) {\n        var _this = this;\n        var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context, \n        // This object allows processSelectionSet to report useful information\n        // to its callers without explicitly returning that information.\n        mergeTree = _a.mergeTree;\n        var policies = this.cache.policies;\n        // This variable will be repeatedly updated using context.merge to\n        // accumulate all fields that need to be written into the store.\n        var incoming = Object.create(null);\n        // If typename was not passed in, infer it. Note that typename is\n        // always passed in for tricky-to-infer cases such as \"Query\" for\n        // ROOT_QUERY.\n        var typename = (dataId && policies.rootTypenamesById[dataId]) ||\n            getTypenameFromResult(result, selectionSet, context.fragmentMap) ||\n            (dataId && context.store.get(dataId, \"__typename\"));\n        if (\"string\" === typeof typename) {\n            incoming.__typename = typename;\n        }\n        // This readField function will be passed as context.readField in the\n        // KeyFieldsContext object created within policies.identify (called below).\n        // In addition to reading from the existing context.store (thanks to the\n        // policies.readField(options, context) line at the very bottom), this\n        // version of readField can read from Reference objects that are currently\n        // pending in context.incomingById, which is important whenever keyFields\n        // need to be extracted from a child object that processSelectionSet has\n        // turned into a Reference.\n        var readField = function () {\n            var options = normalizeReadFieldOptions(arguments, incoming, context.variables);\n            if (isReference(options.from)) {\n                var info = context.incomingById.get(options.from.__ref);\n                if (info) {\n                    var result_1 = policies.readField(__assign(__assign({}, options), { from: info.storeObject }), context);\n                    if (result_1 !== void 0) {\n                        return result_1;\n                    }\n                }\n            }\n            return policies.readField(options, context);\n        };\n        var fieldNodeSet = new Set();\n        this.flattenFields(selectionSet, result, \n        // This WriteContext will be the default context value for fields returned\n        // by the flattenFields method, but some fields may be assigned a modified\n        // context, depending on the presence of @client and other directives.\n        context, typename).forEach(function (context, field) {\n            var _a;\n            var resultFieldKey = resultKeyNameFromField(field);\n            var value = result[resultFieldKey];\n            fieldNodeSet.add(field);\n            if (value !== void 0) {\n                var storeFieldName = policies.getStoreFieldName({\n                    typename: typename,\n                    fieldName: field.name.value,\n                    field: field,\n                    variables: context.variables,\n                });\n                var childTree = getChildMergeTree(mergeTree, storeFieldName);\n                var incomingValue = _this.processFieldValue(value, field, \n                // Reset context.clientOnly and context.deferred to their default\n                // values before processing nested selection sets.\n                field.selectionSet ?\n                    getContextFlavor(context, false, false)\n                    : context, childTree);\n                // To determine if this field holds a child object with a merge function\n                // defined in its type policy (see PR #7070), we need to figure out the\n                // child object's __typename.\n                var childTypename = void 0;\n                // The field's value can be an object that has a __typename only if the\n                // field has a selection set. Otherwise incomingValue is scalar.\n                if (field.selectionSet &&\n                    (isReference(incomingValue) || storeValueIsStoreObject(incomingValue))) {\n                    childTypename = readField(\"__typename\", incomingValue);\n                }\n                var merge = policies.getMergeFunction(typename, field.name.value, childTypename);\n                if (merge) {\n                    childTree.info = {\n                        // TODO Check compatibility against any existing childTree.field?\n                        field: field,\n                        typename: typename,\n                        merge: merge,\n                    };\n                }\n                else {\n                    maybeRecycleChildMergeTree(mergeTree, storeFieldName);\n                }\n                incoming = context.merge(incoming, (_a = {},\n                    _a[storeFieldName] = incomingValue,\n                    _a));\n            }\n            else if (globalThis.__DEV__ !== false &&\n                !context.clientOnly &&\n                !context.deferred &&\n                !addTypenameToDocument.added(field) &&\n                // If the field has a read function, it may be a synthetic field or\n                // provide a default value, so its absence from the written data should\n                // not be cause for alarm.\n                !policies.getReadFunction(typename, field.name.value)) {\n                globalThis.__DEV__ !== false && invariant.error(12, resultKeyNameFromField(field), result);\n            }\n        });\n        // Identify the result object, even if dataId was already provided,\n        // since we always need keyObject below.\n        try {\n            var _b = policies.identify(result, {\n                typename: typename,\n                selectionSet: selectionSet,\n                fragmentMap: context.fragmentMap,\n                storeObject: incoming,\n                readField: readField,\n            }), id = _b[0], keyObject = _b[1];\n            // If dataId was not provided, fall back to the id just generated by\n            // policies.identify.\n            dataId = dataId || id;\n            // Write any key fields that were used during identification, even if\n            // they were not mentioned in the original query.\n            if (keyObject) {\n                // TODO Reverse the order of the arguments?\n                incoming = context.merge(incoming, keyObject);\n            }\n        }\n        catch (e) {\n            // If dataId was provided, tolerate failure of policies.identify.\n            if (!dataId)\n                throw e;\n        }\n        if (\"string\" === typeof dataId) {\n            var dataRef = makeReference(dataId);\n            // Avoid processing the same entity object using the same selection\n            // set more than once. We use an array instead of a Set since most\n            // entity IDs will be written using only one selection set, so the\n            // size of this array is likely to be very small, meaning indexOf is\n            // likely to be faster than Set.prototype.has.\n            var sets = context.written[dataId] || (context.written[dataId] = []);\n            if (sets.indexOf(selectionSet) >= 0)\n                return dataRef;\n            sets.push(selectionSet);\n            // If we're about to write a result object into the store, but we\n            // happen to know that the exact same (===) result object would be\n            // returned if we were to reread the result with the same inputs,\n            // then we can skip the rest of the processSelectionSet work for\n            // this object, and immediately return a Reference to it.\n            if (this.reader &&\n                this.reader.isFresh(result, dataRef, selectionSet, context)) {\n                return dataRef;\n            }\n            var previous_1 = context.incomingById.get(dataId);\n            if (previous_1) {\n                previous_1.storeObject = context.merge(previous_1.storeObject, incoming);\n                previous_1.mergeTree = mergeMergeTrees(previous_1.mergeTree, mergeTree);\n                fieldNodeSet.forEach(function (field) { return previous_1.fieldNodeSet.add(field); });\n            }\n            else {\n                context.incomingById.set(dataId, {\n                    storeObject: incoming,\n                    // Save a reference to mergeTree only if it is not empty, because\n                    // empty MergeTrees may be recycled by maybeRecycleChildMergeTree and\n                    // reused for entirely different parts of the result tree.\n                    mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,\n                    fieldNodeSet: fieldNodeSet,\n                });\n            }\n            return dataRef;\n        }\n        return incoming;\n    };\n    StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {\n        var _this = this;\n        if (!field.selectionSet || value === null) {\n            // In development, we need to clone scalar values so that they can be\n            // safely frozen with maybeDeepFreeze in readFromStore.ts. In production,\n            // it's cheaper to store the scalar values directly in the cache.\n            return globalThis.__DEV__ !== false ? cloneDeep(value) : value;\n        }\n        if (isArray(value)) {\n            return value.map(function (item, i) {\n                var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));\n                maybeRecycleChildMergeTree(mergeTree, i);\n                return value;\n            });\n        }\n        return this.processSelectionSet({\n            result: value,\n            selectionSet: field.selectionSet,\n            context: context,\n            mergeTree: mergeTree,\n        });\n    };\n    // Implements https://spec.graphql.org/draft/#sec-Field-Collection, but with\n    // some additions for tracking @client and @defer directives.\n    StoreWriter.prototype.flattenFields = function (selectionSet, result, context, typename) {\n        if (typename === void 0) { typename = getTypenameFromResult(result, selectionSet, context.fragmentMap); }\n        var fieldMap = new Map();\n        var policies = this.cache.policies;\n        var limitingTrie = new Trie(false); // No need for WeakMap, since limitingTrie does not escape.\n        (function flatten(selectionSet, inheritedContext) {\n            var visitedNode = limitingTrie.lookup(selectionSet, \n            // Because we take inheritedClientOnly and inheritedDeferred into\n            // consideration here (in addition to selectionSet), it's possible for\n            // the same selection set to be flattened more than once, if it appears\n            // in the query with different @client and/or @directive configurations.\n            inheritedContext.clientOnly, inheritedContext.deferred);\n            if (visitedNode.visited)\n                return;\n            visitedNode.visited = true;\n            selectionSet.selections.forEach(function (selection) {\n                if (!shouldInclude(selection, context.variables))\n                    return;\n                var clientOnly = inheritedContext.clientOnly, deferred = inheritedContext.deferred;\n                if (\n                // Since the presence of @client or @defer on this field can only\n                // cause clientOnly or deferred to become true, we can skip the\n                // forEach loop if both clientOnly and deferred are already true.\n                !(clientOnly && deferred) &&\n                    isNonEmptyArray(selection.directives)) {\n                    selection.directives.forEach(function (dir) {\n                        var name = dir.name.value;\n                        if (name === \"client\")\n                            clientOnly = true;\n                        if (name === \"defer\") {\n                            var args = argumentsObjectFromField(dir, context.variables);\n                            // The @defer directive takes an optional args.if boolean\n                            // argument, similar to @include(if: boolean). Note that\n                            // @defer(if: false) does not make context.deferred false, but\n                            // instead behaves as if there was no @defer directive.\n                            if (!args || args.if !== false) {\n                                deferred = true;\n                            }\n                            // TODO In the future, we may want to record args.label using\n                            // context.deferred, if a label is specified.\n                        }\n                    });\n                }\n                if (isField(selection)) {\n                    var existing = fieldMap.get(selection);\n                    if (existing) {\n                        // If this field has been visited along another recursive path\n                        // before, the final context should have clientOnly or deferred set\n                        // to true only if *all* paths have the directive (hence the &&).\n                        clientOnly = clientOnly && existing.clientOnly;\n                        deferred = deferred && existing.deferred;\n                    }\n                    fieldMap.set(selection, getContextFlavor(context, clientOnly, deferred));\n                }\n                else {\n                    var fragment = getFragmentFromSelection(selection, context.lookupFragment);\n                    if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n                        throw newInvariantError(13, selection.name.value);\n                    }\n                    if (fragment &&\n                        policies.fragmentMatches(fragment, typename, result, context.variables)) {\n                        flatten(fragment.selectionSet, getContextFlavor(context, clientOnly, deferred));\n                    }\n                }\n            });\n        })(selectionSet, context);\n        return fieldMap;\n    };\n    StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {\n        var _a;\n        var _this = this;\n        if (mergeTree.map.size && !isReference(incoming)) {\n            var e_1 = \n            // Items in the same position in different arrays are not\n            // necessarily related to each other, so when incoming is an array\n            // we process its elements as if there was no existing data.\n            (!isArray(incoming) &&\n                // Likewise, existing must be either a Reference or a StoreObject\n                // in order for its fields to be safe to merge with the fields of\n                // the incoming object.\n                (isReference(existing) || storeValueIsStoreObject(existing))) ?\n                existing\n                : void 0;\n            // This narrowing is implied by mergeTree.map.size > 0 and\n            // !isReference(incoming), though TypeScript understandably cannot\n            // hope to infer this type.\n            var i_1 = incoming;\n            // The options.storage objects provided to read and merge functions\n            // are derived from the identity of the parent object plus a\n            // sequence of storeFieldName strings/numbers identifying the nested\n            // field name path of each field value to be merged.\n            if (e_1 && !getStorageArgs) {\n                getStorageArgs = [isReference(e_1) ? e_1.__ref : e_1];\n            }\n            // It's possible that applying merge functions to this subtree will\n            // not change the incoming data, so this variable tracks the fields\n            // that did change, so we can create a new incoming object when (and\n            // only when) at least one incoming field has changed. We use a Map\n            // to preserve the type of numeric keys.\n            var changedFields_1;\n            var getValue_1 = function (from, name) {\n                return (isArray(from) ?\n                    typeof name === \"number\" ?\n                        from[name]\n                        : void 0\n                    : context.store.getFieldValue(from, String(name)));\n            };\n            mergeTree.map.forEach(function (childTree, storeFieldName) {\n                var eVal = getValue_1(e_1, storeFieldName);\n                var iVal = getValue_1(i_1, storeFieldName);\n                // If we have no incoming data, leave any existing data untouched.\n                if (void 0 === iVal)\n                    return;\n                if (getStorageArgs) {\n                    getStorageArgs.push(storeFieldName);\n                }\n                var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);\n                if (aVal !== iVal) {\n                    changedFields_1 = changedFields_1 || new Map();\n                    changedFields_1.set(storeFieldName, aVal);\n                }\n                if (getStorageArgs) {\n                    invariant(getStorageArgs.pop() === storeFieldName);\n                }\n            });\n            if (changedFields_1) {\n                // Shallow clone i so we can add changed fields to it.\n                incoming = (isArray(i_1) ? i_1.slice(0) : __assign({}, i_1));\n                changedFields_1.forEach(function (value, name) {\n                    incoming[name] = value;\n                });\n            }\n        }\n        if (mergeTree.info) {\n            return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));\n        }\n        return incoming;\n    };\n    return StoreWriter;\n}());\nexport { StoreWriter };\nvar emptyMergeTreePool = [];\nfunction getChildMergeTree(_a, name) {\n    var map = _a.map;\n    if (!map.has(name)) {\n        map.set(name, emptyMergeTreePool.pop() || { map: new Map() });\n    }\n    return map.get(name);\n}\nfunction mergeMergeTrees(left, right) {\n    if (left === right || !right || mergeTreeIsEmpty(right))\n        return left;\n    if (!left || mergeTreeIsEmpty(left))\n        return right;\n    var info = left.info && right.info ? __assign(__assign({}, left.info), right.info) : left.info || right.info;\n    var needToMergeMaps = left.map.size && right.map.size;\n    var map = needToMergeMaps ? new Map()\n        : left.map.size ? left.map\n            : right.map;\n    var merged = { info: info, map: map };\n    if (needToMergeMaps) {\n        var remainingRightKeys_1 = new Set(right.map.keys());\n        left.map.forEach(function (leftTree, key) {\n            merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));\n            remainingRightKeys_1.delete(key);\n        });\n        remainingRightKeys_1.forEach(function (key) {\n            merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));\n        });\n    }\n    return merged;\n}\nfunction mergeTreeIsEmpty(tree) {\n    return !tree || !(tree.info || tree.map.size);\n}\nfunction maybeRecycleChildMergeTree(_a, name) {\n    var map = _a.map;\n    var childTree = map.get(name);\n    if (childTree && mergeTreeIsEmpty(childTree)) {\n        emptyMergeTreePool.push(childTree);\n        map.delete(name);\n    }\n}\nvar warnings = new Set();\n// Note that this function is unused in production, and thus should be\n// pruned by any well-configured minifier.\nfunction warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {\n    var getChild = function (objOrRef) {\n        var child = store.getFieldValue(objOrRef, storeFieldName);\n        return typeof child === \"object\" && child;\n    };\n    var existing = getChild(existingRef);\n    if (!existing)\n        return;\n    var incoming = getChild(incomingObj);\n    if (!incoming)\n        return;\n    // It's always safe to replace a reference, since it refers to data\n    // safely stored elsewhere.\n    if (isReference(existing))\n        return;\n    // If the values are structurally equivalent, we do not need to worry\n    // about incoming replacing existing.\n    if (equal(existing, incoming))\n        return;\n    // If we're replacing every key of the existing object, then the\n    // existing data would be overwritten even if the objects were\n    // normalized, so warning would not be helpful here.\n    if (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {\n        return;\n    }\n    var parentType = store.getFieldValue(existingRef, \"__typename\") ||\n        store.getFieldValue(incomingObj, \"__typename\");\n    var fieldName = fieldNameFromStoreName(storeFieldName);\n    var typeDotName = \"\".concat(parentType, \".\").concat(fieldName);\n    // Avoid warning more than once for the same type and field name.\n    if (warnings.has(typeDotName))\n        return;\n    warnings.add(typeDotName);\n    var childTypenames = [];\n    // Arrays do not have __typename fields, and always need a custom merge\n    // function, even if their elements are normalized entities.\n    if (!isArray(existing) && !isArray(incoming)) {\n        [existing, incoming].forEach(function (child) {\n            var typename = store.getFieldValue(child, \"__typename\");\n            if (typeof typename === \"string\" && !childTypenames.includes(typename)) {\n                childTypenames.push(typename);\n            }\n        });\n    }\n    globalThis.__DEV__ !== false && invariant.warn(14, fieldName, parentType, childTypenames.length ?\n        \"either ensure all objects of type \" +\n            childTypenames.join(\" and \") +\n            \" have an ID or a custom merge function, or \"\n        : \"\", typeDotName, __assign({}, existing), __assign({}, incoming));\n}\n//# sourceMappingURL=writeToStore.js.map","/**\n * The current status of a query’s execution in our system.\n */\nexport var NetworkStatus;\n(function (NetworkStatus) {\n    /**\n     * The query has never been run before and the query is now currently running. A query will still\n     * have this network status even if a partial data result was returned from the cache, but a\n     * query was dispatched anyway.\n     */\n    NetworkStatus[NetworkStatus[\"loading\"] = 1] = \"loading\";\n    /**\n     * If `setVariables` was called and a query was fired because of that then the network status\n     * will be `setVariables` until the result of that query comes back.\n     */\n    NetworkStatus[NetworkStatus[\"setVariables\"] = 2] = \"setVariables\";\n    /**\n     * Indicates that `fetchMore` was called on this query and that the query created is currently in\n     * flight.\n     */\n    NetworkStatus[NetworkStatus[\"fetchMore\"] = 3] = \"fetchMore\";\n    /**\n     * Similar to the `setVariables` network status. It means that `refetch` was called on a query\n     * and the refetch request is currently in flight.\n     */\n    NetworkStatus[NetworkStatus[\"refetch\"] = 4] = \"refetch\";\n    /**\n     * Indicates that a polling query is currently in flight. So for example if you are polling a\n     * query every 10 seconds then the network status will switch to `poll` every 10 seconds whenever\n     * a poll request has been sent but not resolved.\n     */\n    NetworkStatus[NetworkStatus[\"poll\"] = 6] = \"poll\";\n    /**\n     * No request is in flight for this query, and no errors happened. Everything is OK.\n     */\n    NetworkStatus[NetworkStatus[\"ready\"] = 7] = \"ready\";\n    /**\n     * No request is in flight for this query, but one or more errors were detected.\n     */\n    NetworkStatus[NetworkStatus[\"error\"] = 8] = \"error\";\n})(NetworkStatus || (NetworkStatus = {}));\n/**\n * Returns true if there is currently a network request in flight according to a given network\n * status.\n */\nexport function isNetworkRequestInFlight(networkStatus) {\n    return networkStatus ? networkStatus < 7 : false;\n}\n/**\n * Returns true if the network request is in ready or error state according to a given network\n * status.\n */\nexport function isNetworkRequestSettled(networkStatus) {\n    return networkStatus === 7 || networkStatus === 8;\n}\n//# sourceMappingURL=networkStatus.js.map","import { __assign, __extends } from \"tslib\";\nimport { invariant } from \"../../utilities/globals/index.js\";\n// Make builtins like Map and Set safe to use with non-extensible objects.\nimport \"./fixPolyfills.js\";\nimport { wrap } from \"optimism\";\nimport { equal } from \"@wry/equality\";\nimport { ApolloCache } from \"../core/cache.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport { addTypenameToDocument, isReference, DocumentTransform, canonicalStringify, print, cacheSizes, } from \"../../utilities/index.js\";\nimport { StoreReader } from \"./readFromStore.js\";\nimport { StoreWriter } from \"./writeToStore.js\";\nimport { EntityStore, supportsResultCaching } from \"./entityStore.js\";\nimport { makeVar, forgetCache, recallCache } from \"./reactiveVars.js\";\nimport { Policies } from \"./policies.js\";\nimport { hasOwn, normalizeConfig, shouldCanonizeResults } from \"./helpers.js\";\nimport { getInMemoryCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\nvar InMemoryCache = /** @class */ (function (_super) {\n    __extends(InMemoryCache, _super);\n    function InMemoryCache(config) {\n        if (config === void 0) { config = {}; }\n        var _this = _super.call(this) || this;\n        _this.watches = new Set();\n        _this.addTypenameTransform = new DocumentTransform(addTypenameToDocument);\n        // Override the default value, since InMemoryCache result objects are frozen\n        // in development and expected to remain logically immutable in production.\n        _this.assumeImmutableResults = true;\n        _this.makeVar = makeVar;\n        _this.txCount = 0;\n        _this.config = normalizeConfig(config);\n        _this.addTypename = !!_this.config.addTypename;\n        _this.policies = new Policies({\n            cache: _this,\n            dataIdFromObject: _this.config.dataIdFromObject,\n            possibleTypes: _this.config.possibleTypes,\n            typePolicies: _this.config.typePolicies,\n        });\n        _this.init();\n        return _this;\n    }\n    InMemoryCache.prototype.init = function () {\n        // Passing { resultCaching: false } in the InMemoryCache constructor options\n        // will completely disable dependency tracking, which will improve memory\n        // usage but worsen the performance of repeated reads.\n        var rootStore = (this.data = new EntityStore.Root({\n            policies: this.policies,\n            resultCaching: this.config.resultCaching,\n        }));\n        // When no optimistic writes are currently active, cache.optimisticData ===\n        // cache.data, so there are no additional layers on top of the actual data.\n        // When an optimistic update happens, this.optimisticData will become a\n        // linked list of EntityStore Layer objects that terminates with the\n        // original this.data cache object.\n        this.optimisticData = rootStore.stump;\n        this.resetResultCache();\n    };\n    InMemoryCache.prototype.resetResultCache = function (resetResultIdentities) {\n        var _this = this;\n        var previousReader = this.storeReader;\n        var fragments = this.config.fragments;\n        // The StoreWriter is mostly stateless and so doesn't really need to be\n        // reset, but it does need to have its writer.storeReader reference updated,\n        // so it's simpler to update this.storeWriter as well.\n        this.storeWriter = new StoreWriter(this, (this.storeReader = new StoreReader({\n            cache: this,\n            addTypename: this.addTypename,\n            resultCacheMaxSize: this.config.resultCacheMaxSize,\n            canonizeResults: shouldCanonizeResults(this.config),\n            canon: resetResultIdentities ? void 0 : (previousReader && previousReader.canon),\n            fragments: fragments,\n        })), fragments);\n        this.maybeBroadcastWatch = wrap(function (c, options) {\n            return _this.broadcastWatch(c, options);\n        }, {\n            max: this.config.resultCacheMaxSize ||\n                cacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] ||\n                5000 /* defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] */,\n            makeCacheKey: function (c) {\n                // Return a cache key (thus enabling result caching) only if we're\n                // currently using a data store that can track cache dependencies.\n                var store = c.optimistic ? _this.optimisticData : _this.data;\n                if (supportsResultCaching(store)) {\n                    var optimistic = c.optimistic, id = c.id, variables = c.variables;\n                    return store.makeCacheKey(c.query, \n                    // Different watches can have the same query, optimistic\n                    // status, rootId, and variables, but if their callbacks are\n                    // different, the (identical) result needs to be delivered to\n                    // each distinct callback. The easiest way to achieve that\n                    // separation is to include c.callback in the cache key for\n                    // maybeBroadcastWatch calls. See issue #5733.\n                    c.callback, canonicalStringify({ optimistic: optimistic, id: id, variables: variables }));\n                }\n            },\n        });\n        // Since we have thrown away all the cached functions that depend on the\n        // CacheGroup dependencies maintained by EntityStore, we should also reset\n        // all CacheGroup dependency information.\n        new Set([this.data.group, this.optimisticData.group]).forEach(function (group) {\n            return group.resetCaching();\n        });\n    };\n    InMemoryCache.prototype.restore = function (data) {\n        this.init();\n        // Since calling this.init() discards/replaces the entire StoreReader, along\n        // with the result caches it maintains, this.data.replace(data) won't have\n        // to bother deleting the old data.\n        if (data)\n            this.data.replace(data);\n        return this;\n    };\n    InMemoryCache.prototype.extract = function (optimistic) {\n        if (optimistic === void 0) { optimistic = false; }\n        return (optimistic ? this.optimisticData : this.data).extract();\n    };\n    InMemoryCache.prototype.read = function (options) {\n        var \n        // Since read returns data or null, without any additional metadata\n        // about whether/where there might have been missing fields, the\n        // default behavior cannot be returnPartialData = true (like it is\n        // for the diff method), since defaulting to true would violate the\n        // integrity of the T in the return type. However, partial data may\n        // be useful in some cases, so returnPartialData:true may be\n        // specified explicitly.\n        _a = options.returnPartialData, \n        // Since read returns data or null, without any additional metadata\n        // about whether/where there might have been missing fields, the\n        // default behavior cannot be returnPartialData = true (like it is\n        // for the diff method), since defaulting to true would violate the\n        // integrity of the T in the return type. However, partial data may\n        // be useful in some cases, so returnPartialData:true may be\n        // specified explicitly.\n        returnPartialData = _a === void 0 ? false : _a;\n        try {\n            return (this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, config: this.config, returnPartialData: returnPartialData })).result || null);\n        }\n        catch (e) {\n            if (e instanceof MissingFieldError) {\n                // Swallow MissingFieldError and return null, so callers do not need to\n                // worry about catching \"normal\" exceptions resulting from incomplete\n                // cache data. Unexpected errors will be re-thrown. If you need more\n                // information about which fields were missing, use cache.diff instead,\n                // and examine diffResult.missing.\n                return null;\n            }\n            throw e;\n        }\n    };\n    InMemoryCache.prototype.write = function (options) {\n        try {\n            ++this.txCount;\n            return this.storeWriter.writeToStore(this.data, options);\n        }\n        finally {\n            if (!--this.txCount && options.broadcast !== false) {\n                this.broadcastWatches();\n            }\n        }\n    };\n    InMemoryCache.prototype.modify = function (options) {\n        if (hasOwn.call(options, \"id\") && !options.id) {\n            // To my knowledge, TypeScript does not currently provide a way to\n            // enforce that an optional property?:type must *not* be undefined\n            // when present. That ability would be useful here, because we want\n            // options.id to default to ROOT_QUERY only when no options.id was\n            // provided. If the caller attempts to pass options.id with a\n            // falsy/undefined value (perhaps because cache.identify failed), we\n            // should not assume the goal was to modify the ROOT_QUERY object.\n            // We could throw, but it seems natural to return false to indicate\n            // that nothing was modified.\n            return false;\n        }\n        var store = ((options.optimistic) // Defaults to false.\n        ) ?\n            this.optimisticData\n            : this.data;\n        try {\n            ++this.txCount;\n            return store.modify(options.id || \"ROOT_QUERY\", options.fields);\n        }\n        finally {\n            if (!--this.txCount && options.broadcast !== false) {\n                this.broadcastWatches();\n            }\n        }\n    };\n    InMemoryCache.prototype.diff = function (options) {\n        return this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, rootId: options.id || \"ROOT_QUERY\", config: this.config }));\n    };\n    InMemoryCache.prototype.watch = function (watch) {\n        var _this = this;\n        if (!this.watches.size) {\n            // In case we previously called forgetCache(this) because\n            // this.watches became empty (see below), reattach this cache to any\n            // reactive variables on which it previously depended. It might seem\n            // paradoxical that we're able to recall something we supposedly\n            // forgot, but the point of calling forgetCache(this) is to silence\n            // useless broadcasts while this.watches is empty, and to allow the\n            // cache to be garbage collected. If, however, we manage to call\n            // recallCache(this) here, this cache object must not have been\n            // garbage collected yet, and should resume receiving updates from\n            // reactive variables, now that it has a watcher to notify.\n            recallCache(this);\n        }\n        this.watches.add(watch);\n        if (watch.immediate) {\n            this.maybeBroadcastWatch(watch);\n        }\n        return function () {\n            // Once we remove the last watch from this.watches, cache.broadcastWatches\n            // no longer does anything, so we preemptively tell the reactive variable\n            // system to exclude this cache from future broadcasts.\n            if (_this.watches.delete(watch) && !_this.watches.size) {\n                forgetCache(_this);\n            }\n            // Remove this watch from the LRU cache managed by the\n            // maybeBroadcastWatch OptimisticWrapperFunction, to prevent memory\n            // leaks involving the closure of watch.callback.\n            _this.maybeBroadcastWatch.forget(watch);\n        };\n    };\n    InMemoryCache.prototype.gc = function (options) {\n        var _a;\n        canonicalStringify.reset();\n        print.reset();\n        this.addTypenameTransform.resetCache();\n        (_a = this.config.fragments) === null || _a === void 0 ? void 0 : _a.resetCaches();\n        var ids = this.optimisticData.gc();\n        if (options && !this.txCount) {\n            if (options.resetResultCache) {\n                this.resetResultCache(options.resetResultIdentities);\n            }\n            else if (options.resetResultIdentities) {\n                this.storeReader.resetCanon();\n            }\n        }\n        return ids;\n    };\n    // Call this method to ensure the given root ID remains in the cache after\n    // garbage collection, along with its transitive child entities. Note that\n    // the cache automatically retains all directly written entities. By default,\n    // the retainment persists after optimistic updates are removed. Pass true\n    // for the optimistic argument if you would prefer for the retainment to be\n    // discarded when the top-most optimistic layer is removed. Returns the\n    // resulting (non-negative) retainment count.\n    InMemoryCache.prototype.retain = function (rootId, optimistic) {\n        return (optimistic ? this.optimisticData : this.data).retain(rootId);\n    };\n    // Call this method to undo the effect of the retain method, above. Once the\n    // retainment count falls to zero, the given ID will no longer be preserved\n    // during garbage collection, though it may still be preserved by other safe\n    // entities that refer to it. Returns the resulting (non-negative) retainment\n    // count, in case that's useful.\n    InMemoryCache.prototype.release = function (rootId, optimistic) {\n        return (optimistic ? this.optimisticData : this.data).release(rootId);\n    };\n    // Returns the canonical ID for a given StoreObject, obeying typePolicies\n    // and keyFields (and dataIdFromObject, if you still use that). At minimum,\n    // the object must contain a __typename and any primary key fields required\n    // to identify entities of that type. If you pass a query result object, be\n    // sure that none of the primary key fields have been renamed by aliasing.\n    // If you pass a Reference object, its __ref ID string will be returned.\n    InMemoryCache.prototype.identify = function (object) {\n        if (isReference(object))\n            return object.__ref;\n        try {\n            return this.policies.identify(object)[0];\n        }\n        catch (e) {\n            globalThis.__DEV__ !== false && invariant.warn(e);\n        }\n    };\n    InMemoryCache.prototype.evict = function (options) {\n        if (!options.id) {\n            if (hasOwn.call(options, \"id\")) {\n                // See comment in modify method about why we return false when\n                // options.id exists but is falsy/undefined.\n                return false;\n            }\n            options = __assign(__assign({}, options), { id: \"ROOT_QUERY\" });\n        }\n        try {\n            // It's unlikely that the eviction will end up invoking any other\n            // cache update operations while it's running, but {in,de}crementing\n            // this.txCount still seems like a good idea, for uniformity with\n            // the other update methods.\n            ++this.txCount;\n            // Pass this.data as a limit on the depth of the eviction, so evictions\n            // during optimistic updates (when this.data is temporarily set equal to\n            // this.optimisticData) do not escape their optimistic Layer.\n            return this.optimisticData.evict(options, this.data);\n        }\n        finally {\n            if (!--this.txCount && options.broadcast !== false) {\n                this.broadcastWatches();\n            }\n        }\n    };\n    InMemoryCache.prototype.reset = function (options) {\n        var _this = this;\n        this.init();\n        canonicalStringify.reset();\n        if (options && options.discardWatches) {\n            // Similar to what happens in the unsubscribe function returned by\n            // cache.watch, applied to all current watches.\n            this.watches.forEach(function (watch) { return _this.maybeBroadcastWatch.forget(watch); });\n            this.watches.clear();\n            forgetCache(this);\n        }\n        else {\n            // Calling this.init() above unblocks all maybeBroadcastWatch caching, so\n            // this.broadcastWatches() triggers a broadcast to every current watcher\n            // (letting them know their data is now missing). This default behavior is\n            // convenient because it means the watches do not have to be manually\n            // reestablished after resetting the cache. To prevent this broadcast and\n            // cancel all watches, pass true for options.discardWatches.\n            this.broadcastWatches();\n        }\n        return Promise.resolve();\n    };\n    InMemoryCache.prototype.removeOptimistic = function (idToRemove) {\n        var newOptimisticData = this.optimisticData.removeLayer(idToRemove);\n        if (newOptimisticData !== this.optimisticData) {\n            this.optimisticData = newOptimisticData;\n            this.broadcastWatches();\n        }\n    };\n    InMemoryCache.prototype.batch = function (options) {\n        var _this = this;\n        var update = options.update, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, removeOptimistic = options.removeOptimistic, onWatchUpdated = options.onWatchUpdated;\n        var updateResult;\n        var perform = function (layer) {\n            var _a = _this, data = _a.data, optimisticData = _a.optimisticData;\n            ++_this.txCount;\n            if (layer) {\n                _this.data = _this.optimisticData = layer;\n            }\n            try {\n                return (updateResult = update(_this));\n            }\n            finally {\n                --_this.txCount;\n                _this.data = data;\n                _this.optimisticData = optimisticData;\n            }\n        };\n        var alreadyDirty = new Set();\n        if (onWatchUpdated && !this.txCount) {\n            // If an options.onWatchUpdated callback is provided, we want to call it\n            // with only the Cache.WatchOptions objects affected by options.update,\n            // but there might be dirty watchers already waiting to be broadcast that\n            // have nothing to do with the update. To prevent including those watchers\n            // in the post-update broadcast, we perform this initial broadcast to\n            // collect the dirty watchers, so we can re-dirty them later, after the\n            // post-update broadcast, allowing them to receive their pending\n            // broadcasts the next time broadcastWatches is called, just as they would\n            // if we never called cache.batch.\n            this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch) {\n                    alreadyDirty.add(watch);\n                    return false;\n                } }));\n        }\n        if (typeof optimistic === \"string\") {\n            // Note that there can be multiple layers with the same optimistic ID.\n            // When removeOptimistic(id) is called for that id, all matching layers\n            // will be removed, and the remaining layers will be reapplied.\n            this.optimisticData = this.optimisticData.addLayer(optimistic, perform);\n        }\n        else if (optimistic === false) {\n            // Ensure both this.data and this.optimisticData refer to the root\n            // (non-optimistic) layer of the cache during the update. Note that\n            // this.data could be a Layer if we are currently executing an optimistic\n            // update function, but otherwise will always be an EntityStore.Root\n            // instance.\n            perform(this.data);\n        }\n        else {\n            // Otherwise, leave this.data and this.optimisticData unchanged and run\n            // the update with broadcast batching.\n            perform();\n        }\n        if (typeof removeOptimistic === \"string\") {\n            this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);\n        }\n        // Note: if this.txCount > 0, then alreadyDirty.size === 0, so this code\n        // takes the else branch and calls this.broadcastWatches(options), which\n        // does nothing when this.txCount > 0.\n        if (onWatchUpdated && alreadyDirty.size) {\n            this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch, diff) {\n                    var result = onWatchUpdated.call(this, watch, diff);\n                    if (result !== false) {\n                        // Since onWatchUpdated did not return false, this diff is\n                        // about to be broadcast to watch.callback, so we don't need\n                        // to re-dirty it with the other alreadyDirty watches below.\n                        alreadyDirty.delete(watch);\n                    }\n                    return result;\n                } }));\n            // Silently re-dirty any watches that were already dirty before the update\n            // was performed, and were not broadcast just now.\n            if (alreadyDirty.size) {\n                alreadyDirty.forEach(function (watch) { return _this.maybeBroadcastWatch.dirty(watch); });\n            }\n        }\n        else {\n            // If alreadyDirty is empty or we don't have an onWatchUpdated\n            // function, we don't need to go to the trouble of wrapping\n            // options.onWatchUpdated.\n            this.broadcastWatches(options);\n        }\n        return updateResult;\n    };\n    InMemoryCache.prototype.performTransaction = function (update, optimisticId) {\n        return this.batch({\n            update: update,\n            optimistic: optimisticId || optimisticId !== null,\n        });\n    };\n    InMemoryCache.prototype.transformDocument = function (document) {\n        return this.addTypenameToDocument(this.addFragmentsToDocument(document));\n    };\n    InMemoryCache.prototype.broadcastWatches = function (options) {\n        var _this = this;\n        if (!this.txCount) {\n            this.watches.forEach(function (c) { return _this.maybeBroadcastWatch(c, options); });\n        }\n    };\n    InMemoryCache.prototype.addFragmentsToDocument = function (document) {\n        var fragments = this.config.fragments;\n        return fragments ? fragments.transform(document) : document;\n    };\n    InMemoryCache.prototype.addTypenameToDocument = function (document) {\n        if (this.addTypename) {\n            return this.addTypenameTransform.transformDocument(document);\n        }\n        return document;\n    };\n    // This method is wrapped by maybeBroadcastWatch, which is called by\n    // broadcastWatches, so that we compute and broadcast results only when\n    // the data that would be broadcast might have changed. It would be\n    // simpler to check for changes after recomputing a result but before\n    // broadcasting it, but this wrapping approach allows us to skip both\n    // the recomputation and the broadcast, in most cases.\n    InMemoryCache.prototype.broadcastWatch = function (c, options) {\n        var lastDiff = c.lastDiff;\n        // Both WatchOptions and DiffOptions extend ReadOptions, and DiffOptions\n        // currently requires no additional properties, so we can use c (a\n        // WatchOptions object) as DiffOptions, without having to allocate a new\n        // object, and without having to enumerate the relevant properties (query,\n        // variables, etc.) explicitly. There will be some additional properties\n        // (lastDiff, callback, etc.), but cache.diff ignores them.\n        var diff = this.diff(c);\n        if (options) {\n            if (c.optimistic && typeof options.optimistic === \"string\") {\n                diff.fromOptimisticTransaction = true;\n            }\n            if (options.onWatchUpdated &&\n                options.onWatchUpdated.call(this, c, diff, lastDiff) === false) {\n                // Returning false from the onWatchUpdated callback will prevent\n                // calling c.callback(diff) for this watcher.\n                return;\n            }\n        }\n        if (!lastDiff || !equal(lastDiff.result, diff.result)) {\n            c.callback((c.lastDiff = diff), lastDiff);\n        }\n    };\n    return InMemoryCache;\n}(ApolloCache));\nexport { InMemoryCache };\nif (globalThis.__DEV__ !== false) {\n    InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;\n}\n//# sourceMappingURL=inMemoryCache.js.map","import { __assign, __extends } from \"tslib\";\nimport { invariant } from \"../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport { cloneDeep, compact, getOperationDefinition, Observable, iterateObserversSafely, fixObservableSubclass, getQueryDefinition, } from \"../utilities/index.js\";\nimport { ApolloError, isApolloError } from \"../errors/index.js\";\nimport { equalByQuery } from \"./equalByQuery.js\";\nvar assign = Object.assign, hasOwnProperty = Object.hasOwnProperty;\nvar ObservableQuery = /** @class */ (function (_super) {\n    __extends(ObservableQuery, _super);\n    function ObservableQuery(_a) {\n        var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;\n        var _this = _super.call(this, function (observer) {\n            // Zen Observable has its own error function, so in order to log correctly\n            // we need to provide a custom error callback.\n            try {\n                var subObserver = observer._subscription._observer;\n                if (subObserver && !subObserver.error) {\n                    subObserver.error = defaultSubscriptionObserverErrorCallback;\n                }\n            }\n            catch (_a) { }\n            var first = !_this.observers.size;\n            _this.observers.add(observer);\n            // Deliver most recent error or result.\n            var last = _this.last;\n            if (last && last.error) {\n                observer.error && observer.error(last.error);\n            }\n            else if (last && last.result) {\n                observer.next && observer.next(last.result);\n            }\n            // Initiate observation of this query if it hasn't been reported to\n            // the QueryManager yet.\n            if (first) {\n                // Blindly catching here prevents unhandled promise rejections,\n                // and is safe because the ObservableQuery handles this error with\n                // this.observer.error, so we're not just swallowing the error by\n                // ignoring it here.\n                _this.reobserve().catch(function () { });\n            }\n            return function () {\n                if (_this.observers.delete(observer) && !_this.observers.size) {\n                    _this.tearDownQuery();\n                }\n            };\n        }) || this;\n        _this.observers = new Set();\n        _this.subscriptions = new Set();\n        // related classes\n        _this.queryInfo = queryInfo;\n        _this.queryManager = queryManager;\n        // active state\n        _this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);\n        _this.isTornDown = false;\n        _this.subscribeToMore = _this.subscribeToMore.bind(_this);\n        var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? \"cache-first\" : _d;\n        var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e, \n        // Make sure we don't store \"standby\" as the initialFetchPolicy.\n        _f = options.initialFetchPolicy, \n        // Make sure we don't store \"standby\" as the initialFetchPolicy.\n        initialFetchPolicy = _f === void 0 ? fetchPolicy === \"standby\" ? defaultFetchPolicy : (fetchPolicy) : _f;\n        _this.options = __assign(__assign({}, options), { \n            // Remember the initial options.fetchPolicy so we can revert back to this\n            // policy when variables change. This information can also be specified\n            // (or overridden) by providing options.initialFetchPolicy explicitly.\n            initialFetchPolicy: initialFetchPolicy, \n            // This ensures this.options.fetchPolicy always has a string value, in\n            // case options.fetchPolicy was not provided.\n            fetchPolicy: fetchPolicy });\n        _this.queryId = queryInfo.queryId || queryManager.generateQueryId();\n        var opDef = getOperationDefinition(_this.query);\n        _this.queryName = opDef && opDef.name && opDef.name.value;\n        return _this;\n    }\n    Object.defineProperty(ObservableQuery.prototype, \"query\", {\n        // The `query` computed property will always reflect the document transformed\n        // by the last run query. `this.options.query` will always reflect the raw\n        // untransformed query to ensure document transforms with runtime conditionals\n        // are run on the original document.\n        get: function () {\n            return this.lastQuery || this.options.query;\n        },\n        enumerable: false,\n        configurable: true\n    });\n    Object.defineProperty(ObservableQuery.prototype, \"variables\", {\n        // Computed shorthand for this.options.variables, preserved for\n        // backwards compatibility.\n        /**\n         * An object containing the variables that were provided for the query.\n         */\n        get: function () {\n            return this.options.variables;\n        },\n        enumerable: false,\n        configurable: true\n    });\n    ObservableQuery.prototype.result = function () {\n        var _this = this;\n        return new Promise(function (resolve, reject) {\n            // TODO: this code doesn’t actually make sense insofar as the observer\n            // will never exist in this.observers due how zen-observable wraps observables.\n            // https://github.com/zenparsing/zen-observable/blob/master/src/Observable.js#L169\n            var observer = {\n                next: function (result) {\n                    resolve(result);\n                    // Stop the query within the QueryManager if we can before\n                    // this function returns.\n                    //\n                    // We do this in order to prevent observers piling up within\n                    // the QueryManager. Notice that we only fully unsubscribe\n                    // from the subscription in a setTimeout(..., 0)  call. This call can\n                    // actually be handled by the browser at a much later time. If queries\n                    // are fired in the meantime, observers that should have been removed\n                    // from the QueryManager will continue to fire, causing an unnecessary\n                    // performance hit.\n                    _this.observers.delete(observer);\n                    if (!_this.observers.size) {\n                        _this.queryManager.removeQuery(_this.queryId);\n                    }\n                    setTimeout(function () {\n                        subscription.unsubscribe();\n                    }, 0);\n                },\n                error: reject,\n            };\n            var subscription = _this.subscribe(observer);\n        });\n    };\n    /** @internal */\n    ObservableQuery.prototype.resetDiff = function () {\n        this.queryInfo.resetDiff();\n    };\n    ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {\n        if (saveAsLastResult === void 0) { saveAsLastResult = true; }\n        // Use the last result as long as the variables match this.variables.\n        var lastResult = this.getLastResult(true);\n        var networkStatus = this.queryInfo.networkStatus ||\n            (lastResult && lastResult.networkStatus) ||\n            NetworkStatus.ready;\n        var result = __assign(__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });\n        var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? \"cache-first\" : _a;\n        if (\n        // These fetch policies should never deliver data from the cache, unless\n        // redelivering a previously delivered result.\n        skipCacheDataFor(fetchPolicy) ||\n            // If this.options.query has @client(always: true) fields, we cannot\n            // trust diff.result, since it was read from the cache without running\n            // local resolvers (and it's too late to run resolvers now, since we must\n            // return a result synchronously).\n            this.queryManager.getDocumentInfo(this.query).hasForcedResolvers) {\n            // Fall through.\n        }\n        else if (this.waitForOwnResult) {\n            // This would usually be a part of `QueryInfo.getDiff()`.\n            // which we skip in the waitForOwnResult case since we are not\n            // interested in the diff.\n            this.queryInfo[\"updateWatch\"]();\n        }\n        else {\n            var diff = this.queryInfo.getDiff();\n            if (diff.complete || this.options.returnPartialData) {\n                result.data = diff.result;\n            }\n            if (equal(result.data, {})) {\n                result.data = void 0;\n            }\n            if (diff.complete) {\n                // Similar to setting result.partial to false, but taking advantage of the\n                // falsiness of missing fields.\n                delete result.partial;\n                // If the diff is complete, and we're using a FetchPolicy that\n                // terminates after a complete cache read, we can assume the next result\n                // we receive will have NetworkStatus.ready and !loading.\n                if (diff.complete &&\n                    result.networkStatus === NetworkStatus.loading &&\n                    (fetchPolicy === \"cache-first\" || fetchPolicy === \"cache-only\")) {\n                    result.networkStatus = NetworkStatus.ready;\n                    result.loading = false;\n                }\n            }\n            else {\n                result.partial = true;\n            }\n            if (globalThis.__DEV__ !== false &&\n                !diff.complete &&\n                !this.options.partialRefetch &&\n                !result.loading &&\n                !result.data &&\n                !result.error) {\n                logMissingFieldErrors(diff.missing);\n            }\n        }\n        if (saveAsLastResult) {\n            this.updateLastResult(result);\n        }\n        return result;\n    };\n    // Compares newResult to the snapshot we took of this.lastResult when it was\n    // first received.\n    ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {\n        if (!this.last) {\n            return true;\n        }\n        var resultIsDifferent = this.queryManager.getDocumentInfo(this.query).hasNonreactiveDirective ?\n            !equalByQuery(this.query, this.last.result, newResult, this.variables)\n            : !equal(this.last.result, newResult);\n        return (resultIsDifferent || (variables && !equal(this.last.variables, variables)));\n    };\n    ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {\n        var last = this.last;\n        if (last &&\n            last[key] &&\n            (!variablesMustMatch || equal(last.variables, this.variables))) {\n            return last[key];\n        }\n    };\n    ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {\n        return this.getLast(\"result\", variablesMustMatch);\n    };\n    ObservableQuery.prototype.getLastError = function (variablesMustMatch) {\n        return this.getLast(\"error\", variablesMustMatch);\n    };\n    ObservableQuery.prototype.resetLastResults = function () {\n        delete this.last;\n        this.isTornDown = false;\n    };\n    ObservableQuery.prototype.resetQueryStoreErrors = function () {\n        this.queryManager.resetErrors(this.queryId);\n    };\n    /**\n     * Update the variables of this observable query, and fetch the new results.\n     * This method should be preferred over `setVariables` in most use cases.\n     *\n     * @param variables - The new set of variables. If there are missing variables,\n     * the previous values of those variables will be used.\n     */\n    ObservableQuery.prototype.refetch = function (variables) {\n        var _a;\n        var reobserveOptions = {\n            // Always disable polling for refetches.\n            pollInterval: 0,\n        };\n        // Unless the provided fetchPolicy always consults the network\n        // (no-cache, network-only, or cache-and-network), override it with\n        // network-only to force the refetch for this fetchQuery call.\n        var fetchPolicy = this.options.fetchPolicy;\n        if (fetchPolicy === \"cache-and-network\") {\n            reobserveOptions.fetchPolicy = fetchPolicy;\n        }\n        else if (fetchPolicy === \"no-cache\") {\n            reobserveOptions.fetchPolicy = \"no-cache\";\n        }\n        else {\n            reobserveOptions.fetchPolicy = \"network-only\";\n        }\n        if (globalThis.__DEV__ !== false && variables && hasOwnProperty.call(variables, \"variables\")) {\n            var queryDef = getQueryDefinition(this.query);\n            var vars = queryDef.variableDefinitions;\n            if (!vars || !vars.some(function (v) { return v.variable.name.value === \"variables\"; })) {\n                globalThis.__DEV__ !== false && invariant.warn(\n                    20,\n                    variables,\n                    ((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || queryDef\n                );\n            }\n        }\n        if (variables && !equal(this.options.variables, variables)) {\n            // Update the existing options with new variables\n            reobserveOptions.variables = this.options.variables = __assign(__assign({}, this.options.variables), variables);\n        }\n        this.queryInfo.resetLastWrite();\n        return this.reobserve(reobserveOptions, NetworkStatus.refetch);\n    };\n    /**\n     * A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).\n     */\n    ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {\n        var _this = this;\n        var combinedOptions = __assign(__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : (__assign(__assign(__assign(__assign({}, this.options), { query: this.options.query }), fetchMoreOptions), { variables: __assign(__assign({}, this.options.variables), fetchMoreOptions.variables) })))), { \n            // The fetchMore request goes immediately to the network and does\n            // not automatically write its result to the cache (hence no-cache\n            // instead of network-only), because we allow the caller of\n            // fetchMore to provide an updateQuery callback that determines how\n            // the data gets written to the cache.\n            fetchPolicy: \"no-cache\" });\n        combinedOptions.query = this.transformDocument(combinedOptions.query);\n        var qid = this.queryManager.generateQueryId();\n        // If a temporary query is passed to `fetchMore`, we don't want to store\n        // it as the last query result since it may be an optimized query for\n        // pagination. We will however run the transforms on the original document\n        // as well as the document passed in `fetchMoreOptions` to ensure the cache\n        // uses the most up-to-date document which may rely on runtime conditionals.\n        this.lastQuery =\n            fetchMoreOptions.query ?\n                this.transformDocument(this.options.query)\n                : combinedOptions.query;\n        // Simulate a loading result for the original query with\n        // result.networkStatus === NetworkStatus.fetchMore.\n        var queryInfo = this.queryInfo;\n        var originalNetworkStatus = queryInfo.networkStatus;\n        queryInfo.networkStatus = NetworkStatus.fetchMore;\n        if (combinedOptions.notifyOnNetworkStatusChange) {\n            this.observe();\n        }\n        var updatedQuerySet = new Set();\n        var updateQuery = fetchMoreOptions === null || fetchMoreOptions === void 0 ? void 0 : fetchMoreOptions.updateQuery;\n        var isCached = this.options.fetchPolicy !== \"no-cache\";\n        if (!isCached) {\n            invariant(updateQuery, 21);\n        }\n        return this.queryManager\n            .fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore)\n            .then(function (fetchMoreResult) {\n            _this.queryManager.removeQuery(qid);\n            if (queryInfo.networkStatus === NetworkStatus.fetchMore) {\n                queryInfo.networkStatus = originalNetworkStatus;\n            }\n            if (isCached) {\n                // Performing this cache update inside a cache.batch transaction ensures\n                // any affected cache.watch watchers are notified at most once about any\n                // updates. Most watchers will be using the QueryInfo class, which\n                // responds to notifications by calling reobserveCacheFirst to deliver\n                // fetchMore cache results back to this ObservableQuery.\n                _this.queryManager.cache.batch({\n                    update: function (cache) {\n                        var updateQuery = fetchMoreOptions.updateQuery;\n                        if (updateQuery) {\n                            cache.updateQuery({\n                                query: _this.query,\n                                variables: _this.variables,\n                                returnPartialData: true,\n                                optimistic: false,\n                            }, function (previous) {\n                                return updateQuery(previous, {\n                                    fetchMoreResult: fetchMoreResult.data,\n                                    variables: combinedOptions.variables,\n                                });\n                            });\n                        }\n                        else {\n                            // If we're using a field policy instead of updateQuery, the only\n                            // thing we need to do is write the new data to the cache using\n                            // combinedOptions.variables (instead of this.variables, which is\n                            // what this.updateQuery uses, because it works by abusing the\n                            // original field value, keyed by the original variables).\n                            cache.writeQuery({\n                                query: combinedOptions.query,\n                                variables: combinedOptions.variables,\n                                data: fetchMoreResult.data,\n                            });\n                        }\n                    },\n                    onWatchUpdated: function (watch) {\n                        // Record the DocumentNode associated with any watched query whose\n                        // data were updated by the cache writes above.\n                        updatedQuerySet.add(watch.query);\n                    },\n                });\n            }\n            else {\n                // There is a possibility `lastResult` may not be set when\n                // `fetchMore` is called which would cause this to crash. This should\n                // only happen if we haven't previously reported a result. We don't\n                // quite know what the right behavior should be here since this block\n                // of code runs after the fetch result has executed on the network.\n                // We plan to let it crash in the meantime.\n                //\n                // If we get bug reports due to the `data` property access on\n                // undefined, this should give us a real-world scenario that we can\n                // use to test against and determine the right behavior. If we do end\n                // up changing this behavior, this may require, for example, an\n                // adjustment to the types on `updateQuery` since that function\n                // expects that the first argument always contains previous result\n                // data, but not `undefined`.\n                var lastResult = _this.getLast(\"result\");\n                var data = updateQuery(lastResult.data, {\n                    fetchMoreResult: fetchMoreResult.data,\n                    variables: combinedOptions.variables,\n                });\n                _this.reportResult(__assign(__assign({}, lastResult), { data: data }), _this.variables);\n            }\n            return fetchMoreResult;\n        })\n            .finally(function () {\n            // In case the cache writes above did not generate a broadcast\n            // notification (which would have been intercepted by onWatchUpdated),\n            // likely because the written data were the same as what was already in\n            // the cache, we still want fetchMore to deliver its final loading:false\n            // result with the unchanged data.\n            if (isCached && !updatedQuerySet.has(_this.query)) {\n                reobserveCacheFirst(_this);\n            }\n        });\n    };\n    // XXX the subscription variables are separate from the query variables.\n    // if you want to update subscription variables, right now you have to do that separately,\n    // and you can only do it by stopping the subscription and then subscribing again with new variables.\n    /**\n     * A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), usually to subscribe to specific fields that were included in the query.\n     *\n     * This function returns _another_ function that you can call to terminate the subscription.\n     */\n    ObservableQuery.prototype.subscribeToMore = function (options) {\n        var _this = this;\n        var subscription = this.queryManager\n            .startGraphQLSubscription({\n            query: options.document,\n            variables: options.variables,\n            context: options.context,\n        })\n            .subscribe({\n            next: function (subscriptionData) {\n                var updateQuery = options.updateQuery;\n                if (updateQuery) {\n                    _this.updateQuery(function (previous, _a) {\n                        var variables = _a.variables;\n                        return updateQuery(previous, {\n                            subscriptionData: subscriptionData,\n                            variables: variables,\n                        });\n                    });\n                }\n            },\n            error: function (err) {\n                if (options.onError) {\n                    options.onError(err);\n                    return;\n                }\n                globalThis.__DEV__ !== false && invariant.error(22, err);\n            },\n        });\n        this.subscriptions.add(subscription);\n        return function () {\n            if (_this.subscriptions.delete(subscription)) {\n                subscription.unsubscribe();\n            }\n        };\n    };\n    ObservableQuery.prototype.setOptions = function (newOptions) {\n        return this.reobserve(newOptions);\n    };\n    ObservableQuery.prototype.silentSetOptions = function (newOptions) {\n        var mergedOptions = compact(this.options, newOptions || {});\n        assign(this.options, mergedOptions);\n    };\n    /**\n     * Update the variables of this observable query, and fetch the new results\n     * if they've changed. Most users should prefer `refetch` instead of\n     * `setVariables` in order to to be properly notified of results even when\n     * they come from the cache.\n     *\n     * Note: the `next` callback will *not* fire if the variables have not changed\n     * or if the result is coming from cache.\n     *\n     * Note: the promise will return the old results immediately if the variables\n     * have not changed.\n     *\n     * Note: the promise will return null immediately if the query is not active\n     * (there are no subscribers).\n     *\n     * @param variables - The new set of variables. If there are missing variables,\n     * the previous values of those variables will be used.\n     */\n    ObservableQuery.prototype.setVariables = function (variables) {\n        if (equal(this.variables, variables)) {\n            // If we have no observers, then we don't actually want to make a network\n            // request. As soon as someone observes the query, the request will kick\n            // off. For now, we just store any changes. (See #1077)\n            return this.observers.size ? this.result() : Promise.resolve();\n        }\n        this.options.variables = variables;\n        // See comment above\n        if (!this.observers.size) {\n            return Promise.resolve();\n        }\n        return this.reobserve({\n            // Reset options.fetchPolicy to its original value.\n            fetchPolicy: this.options.initialFetchPolicy,\n            variables: variables,\n        }, NetworkStatus.setVariables);\n    };\n    /**\n     * A function that enables you to update the query's cached result without executing a followup GraphQL operation.\n     *\n     * See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.\n     */\n    ObservableQuery.prototype.updateQuery = function (mapFn) {\n        var queryManager = this.queryManager;\n        var result = queryManager.cache.diff({\n            query: this.options.query,\n            variables: this.variables,\n            returnPartialData: true,\n            optimistic: false,\n        }).result;\n        var newResult = mapFn(result, {\n            variables: this.variables,\n        });\n        if (newResult) {\n            queryManager.cache.writeQuery({\n                query: this.options.query,\n                data: newResult,\n                variables: this.variables,\n            });\n            queryManager.broadcastQueries();\n        }\n    };\n    /**\n     * A function that instructs the query to begin re-executing at a specified interval (in milliseconds).\n     */\n    ObservableQuery.prototype.startPolling = function (pollInterval) {\n        this.options.pollInterval = pollInterval;\n        this.updatePolling();\n    };\n    /**\n     * A function that instructs the query to stop polling after a previous call to `startPolling`.\n     */\n    ObservableQuery.prototype.stopPolling = function () {\n        this.options.pollInterval = 0;\n        this.updatePolling();\n    };\n    // Update options.fetchPolicy according to options.nextFetchPolicy.\n    ObservableQuery.prototype.applyNextFetchPolicy = function (reason, \n    // It's possible to use this method to apply options.nextFetchPolicy to\n    // options.fetchPolicy even if options !== this.options, though that happens\n    // most often when the options are temporary, used for only one request and\n    // then thrown away, so nextFetchPolicy may not end up mattering.\n    options) {\n        if (options.nextFetchPolicy) {\n            var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? \"cache-first\" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;\n            if (fetchPolicy === \"standby\") {\n                // Do nothing, leaving options.fetchPolicy unchanged.\n            }\n            else if (typeof options.nextFetchPolicy === \"function\") {\n                // When someone chooses \"cache-and-network\" or \"network-only\" as their\n                // initial FetchPolicy, they often do not want future cache updates to\n                // trigger unconditional network requests, which is what repeatedly\n                // applying the \"cache-and-network\" or \"network-only\" policies would\n                // seem to imply. Instead, when the cache reports an update after the\n                // initial network request, it may be desirable for subsequent network\n                // requests to be triggered only if the cache result is incomplete. To\n                // that end, the options.nextFetchPolicy option provides an easy way to\n                // update options.fetchPolicy after the initial network request, without\n                // having to call observableQuery.setOptions.\n                options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {\n                    reason: reason,\n                    options: options,\n                    observable: this,\n                    initialFetchPolicy: initialFetchPolicy,\n                });\n            }\n            else if (reason === \"variables-changed\") {\n                options.fetchPolicy = initialFetchPolicy;\n            }\n            else {\n                options.fetchPolicy = options.nextFetchPolicy;\n            }\n        }\n        return options.fetchPolicy;\n    };\n    ObservableQuery.prototype.fetch = function (options, newNetworkStatus, query) {\n        // TODO Make sure we update the networkStatus (and infer fetchVariables)\n        // before actually committing to the fetch.\n        this.queryManager.setObservableQuery(this);\n        return this.queryManager[\"fetchConcastWithInfo\"](this.queryId, options, newNetworkStatus, query);\n    };\n    // Turns polling on or off based on this.options.pollInterval.\n    ObservableQuery.prototype.updatePolling = function () {\n        var _this = this;\n        // Avoid polling in SSR mode\n        if (this.queryManager.ssrMode) {\n            return;\n        }\n        var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;\n        if (!pollInterval || !this.hasObservers()) {\n            if (pollingInfo) {\n                clearTimeout(pollingInfo.timeout);\n                delete this.pollingInfo;\n            }\n            return;\n        }\n        if (pollingInfo && pollingInfo.interval === pollInterval) {\n            return;\n        }\n        invariant(pollInterval, 23);\n        var info = pollingInfo || (this.pollingInfo = {});\n        info.interval = pollInterval;\n        var maybeFetch = function () {\n            var _a, _b;\n            if (_this.pollingInfo) {\n                if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus) &&\n                    !((_b = (_a = _this.options).skipPollAttempt) === null || _b === void 0 ? void 0 : _b.call(_a))) {\n                    _this.reobserve({\n                        // Most fetchPolicy options don't make sense to use in a polling context, as\n                        // users wouldn't want to be polling the cache directly. However, network-only and\n                        // no-cache are both useful for when the user wants to control whether or not the\n                        // polled results are written to the cache.\n                        fetchPolicy: _this.options.initialFetchPolicy === \"no-cache\" ?\n                            \"no-cache\"\n                            : \"network-only\",\n                    }, NetworkStatus.poll).then(poll, poll);\n                }\n                else {\n                    poll();\n                }\n            }\n        };\n        var poll = function () {\n            var info = _this.pollingInfo;\n            if (info) {\n                clearTimeout(info.timeout);\n                info.timeout = setTimeout(maybeFetch, info.interval);\n            }\n        };\n        poll();\n    };\n    ObservableQuery.prototype.updateLastResult = function (newResult, variables) {\n        if (variables === void 0) { variables = this.variables; }\n        var error = this.getLastError();\n        // Preserve this.last.error unless the variables have changed.\n        if (error && this.last && !equal(variables, this.last.variables)) {\n            error = void 0;\n        }\n        return (this.last = __assign({ result: this.queryManager.assumeImmutableResults ?\n                newResult\n                : cloneDeep(newResult), variables: variables }, (error ? { error: error } : null)));\n    };\n    ObservableQuery.prototype.reobserveAsConcast = function (newOptions, newNetworkStatus) {\n        var _this = this;\n        this.isTornDown = false;\n        var useDisposableConcast = \n        // Refetching uses a disposable Concast to allow refetches using different\n        // options/variables, without permanently altering the options of the\n        // original ObservableQuery.\n        newNetworkStatus === NetworkStatus.refetch ||\n            // The fetchMore method does not actually call the reobserve method, but,\n            // if it did, it would definitely use a disposable Concast.\n            newNetworkStatus === NetworkStatus.fetchMore ||\n            // Polling uses a disposable Concast so the polling options (which force\n            // fetchPolicy to be \"network-only\" or \"no-cache\") won't override the original options.\n            newNetworkStatus === NetworkStatus.poll;\n        // Save the old variables, since Object.assign may modify them below.\n        var oldVariables = this.options.variables;\n        var oldFetchPolicy = this.options.fetchPolicy;\n        var mergedOptions = compact(this.options, newOptions || {});\n        var options = useDisposableConcast ?\n            // Disposable Concast fetches receive a shallow copy of this.options\n            // (merged with newOptions), leaving this.options unmodified.\n            mergedOptions\n            : assign(this.options, mergedOptions);\n        // Don't update options.query with the transformed query to avoid\n        // overwriting this.options.query when we aren't using a disposable concast.\n        // We want to ensure we can re-run the custom document transforms the next\n        // time a request is made against the original query.\n        var query = this.transformDocument(options.query);\n        this.lastQuery = query;\n        if (!useDisposableConcast) {\n            // We can skip calling updatePolling if we're not changing this.options.\n            this.updatePolling();\n            // Reset options.fetchPolicy to its original value when variables change,\n            // unless a new fetchPolicy was provided by newOptions.\n            if (newOptions &&\n                newOptions.variables &&\n                !equal(newOptions.variables, oldVariables) &&\n                // Don't mess with the fetchPolicy if it's currently \"standby\".\n                options.fetchPolicy !== \"standby\" &&\n                // If we're changing the fetchPolicy anyway, don't try to change it here\n                // using applyNextFetchPolicy. The explicit options.fetchPolicy wins.\n                (options.fetchPolicy === oldFetchPolicy ||\n                    // A `nextFetchPolicy` function has even higher priority, though,\n                    // so in that case `applyNextFetchPolicy` must be called.\n                    typeof options.nextFetchPolicy === \"function\")) {\n                this.applyNextFetchPolicy(\"variables-changed\", options);\n                if (newNetworkStatus === void 0) {\n                    newNetworkStatus = NetworkStatus.setVariables;\n                }\n            }\n        }\n        this.waitForOwnResult && (this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy));\n        var finishWaitingForOwnResult = function () {\n            if (_this.concast === concast) {\n                _this.waitForOwnResult = false;\n            }\n        };\n        var variables = options.variables && __assign({}, options.variables);\n        var _a = this.fetch(options, newNetworkStatus, query), concast = _a.concast, fromLink = _a.fromLink;\n        var observer = {\n            next: function (result) {\n                if (equal(_this.variables, variables)) {\n                    finishWaitingForOwnResult();\n                    _this.reportResult(result, variables);\n                }\n            },\n            error: function (error) {\n                if (equal(_this.variables, variables)) {\n                    // Coming from `getResultsFromLink`, `error` here should always be an `ApolloError`.\n                    // However, calling `concast.cancel` can inject another type of error, so we have to\n                    // wrap it again here.\n                    if (!isApolloError(error)) {\n                        error = new ApolloError({ networkError: error });\n                    }\n                    finishWaitingForOwnResult();\n                    _this.reportError(error, variables);\n                }\n            },\n        };\n        if (!useDisposableConcast && (fromLink || !this.concast)) {\n            // We use the {add,remove}Observer methods directly to avoid wrapping\n            // observer with an unnecessary SubscriptionObserver object.\n            if (this.concast && this.observer) {\n                this.concast.removeObserver(this.observer);\n            }\n            this.concast = concast;\n            this.observer = observer;\n        }\n        concast.addObserver(observer);\n        return concast;\n    };\n    ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {\n        return this.reobserveAsConcast(newOptions, newNetworkStatus)\n            .promise;\n    };\n    ObservableQuery.prototype.resubscribeAfterError = function () {\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        // If `lastError` is set in the current when the subscription is re-created,\n        // the subscription will immediately receive the error, which will\n        // cause it to terminate again. To avoid this, we first clear\n        // the last error/result from the `observableQuery` before re-starting\n        // the subscription, and restore the last value afterwards so that the\n        // subscription has a chance to stay open.\n        var last = this.last;\n        this.resetLastResults();\n        var subscription = this.subscribe.apply(this, args);\n        this.last = last;\n        return subscription;\n    };\n    // (Re)deliver the current result to this.observers without applying fetch\n    // policies or making network requests.\n    ObservableQuery.prototype.observe = function () {\n        this.reportResult(\n        // Passing false is important so that this.getCurrentResult doesn't\n        // save the fetchMore result as this.lastResult, causing it to be\n        // ignored due to the this.isDifferentFromLastResult check in\n        // this.reportResult.\n        this.getCurrentResult(false), this.variables);\n    };\n    ObservableQuery.prototype.reportResult = function (result, variables) {\n        var lastError = this.getLastError();\n        var isDifferent = this.isDifferentFromLastResult(result, variables);\n        // Update the last result even when isDifferentFromLastResult returns false,\n        // because the query may be using the @nonreactive directive, and we want to\n        // save the the latest version of any nonreactive subtrees (in case\n        // getCurrentResult is called), even though we skip broadcasting changes.\n        if (lastError || !result.partial || this.options.returnPartialData) {\n            this.updateLastResult(result, variables);\n        }\n        if (lastError || isDifferent) {\n            iterateObserversSafely(this.observers, \"next\", result);\n        }\n    };\n    ObservableQuery.prototype.reportError = function (error, variables) {\n        // Since we don't get the current result on errors, only the error, we\n        // must mirror the updates that occur in QueryStore.markQueryError here\n        var errorResult = __assign(__assign({}, this.getLastResult()), { error: error, errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false });\n        this.updateLastResult(errorResult, variables);\n        iterateObserversSafely(this.observers, \"error\", (this.last.error = error));\n    };\n    ObservableQuery.prototype.hasObservers = function () {\n        return this.observers.size > 0;\n    };\n    ObservableQuery.prototype.tearDownQuery = function () {\n        if (this.isTornDown)\n            return;\n        if (this.concast && this.observer) {\n            this.concast.removeObserver(this.observer);\n            delete this.concast;\n            delete this.observer;\n        }\n        this.stopPolling();\n        // stop all active GraphQL subscriptions\n        this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });\n        this.subscriptions.clear();\n        this.queryManager.stopQuery(this.queryId);\n        this.observers.clear();\n        this.isTornDown = true;\n    };\n    ObservableQuery.prototype.transformDocument = function (document) {\n        return this.queryManager.transform(document);\n    };\n    return ObservableQuery;\n}(Observable));\nexport { ObservableQuery };\n// Necessary because the ObservableQuery constructor has a different\n// signature than the Observable constructor.\nfixObservableSubclass(ObservableQuery);\n// Reobserve with fetchPolicy effectively set to \"cache-first\", triggering\n// delivery of any new data from the cache, possibly falling back to the network\n// if any cache data are missing. This allows _complete_ cache results to be\n// delivered without also kicking off unnecessary network requests when\n// this.options.fetchPolicy is \"cache-and-network\" or \"network-only\". When\n// this.options.fetchPolicy is any other policy (\"cache-first\", \"cache-only\",\n// \"standby\", or \"no-cache\"), we call this.reobserve() as usual.\nexport function reobserveCacheFirst(obsQuery) {\n    var _a = obsQuery.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;\n    if (fetchPolicy === \"cache-and-network\" || fetchPolicy === \"network-only\") {\n        return obsQuery.reobserve({\n            fetchPolicy: \"cache-first\",\n            // Use a temporary nextFetchPolicy function that replaces itself with the\n            // previous nextFetchPolicy value and returns the original fetchPolicy.\n            nextFetchPolicy: function (currentFetchPolicy, context) {\n                // Replace this nextFetchPolicy function in the options object with the\n                // original this.options.nextFetchPolicy value.\n                this.nextFetchPolicy = nextFetchPolicy;\n                // If the original nextFetchPolicy value was a function, give it a\n                // chance to decide what happens here.\n                if (typeof this.nextFetchPolicy === \"function\") {\n                    return this.nextFetchPolicy(currentFetchPolicy, context);\n                }\n                // Otherwise go back to the original this.options.fetchPolicy.\n                return fetchPolicy;\n            },\n        });\n    }\n    return obsQuery.reobserve();\n}\nfunction defaultSubscriptionObserverErrorCallback(error) {\n    globalThis.__DEV__ !== false && invariant.error(24, error.message, error.stack);\n}\nexport function logMissingFieldErrors(missing) {\n    if (globalThis.__DEV__ !== false && missing) {\n        globalThis.__DEV__ !== false && invariant.debug(25, missing);\n    }\n}\nfunction skipCacheDataFor(fetchPolicy /* `undefined` would mean `\"cache-first\"` */) {\n    return (fetchPolicy === \"network-only\" ||\n        fetchPolicy === \"no-cache\" ||\n        fetchPolicy === \"standby\");\n}\n//# sourceMappingURL=ObservableQuery.js.map","import { __assign } from \"tslib\";\nimport { equal } from \"@wry/equality\";\nimport { DeepMerger } from \"../utilities/index.js\";\nimport { mergeIncrementalData } from \"../utilities/index.js\";\nimport { reobserveCacheFirst } from \"./ObservableQuery.js\";\nimport { isNonEmptyArray, graphQLResultHasError, canUseWeakMap, } from \"../utilities/index.js\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nvar destructiveMethodCounts = new (canUseWeakMap ? WeakMap : Map)();\nfunction wrapDestructiveCacheMethod(cache, methodName) {\n    var original = cache[methodName];\n    if (typeof original === \"function\") {\n        // @ts-expect-error this is just too generic to be typed correctly\n        cache[methodName] = function () {\n            destructiveMethodCounts.set(cache, \n            // The %1e15 allows the count to wrap around to 0 safely every\n            // quadrillion evictions, so there's no risk of overflow. To be\n            // clear, this is more of a pedantic principle than something\n            // that matters in any conceivable practical scenario.\n            (destructiveMethodCounts.get(cache) + 1) % 1e15);\n            // @ts-expect-error this is just too generic to be typed correctly\n            return original.apply(this, arguments);\n        };\n    }\n}\nfunction cancelNotifyTimeout(info) {\n    if (info[\"notifyTimeout\"]) {\n        clearTimeout(info[\"notifyTimeout\"]);\n        info[\"notifyTimeout\"] = void 0;\n    }\n}\n// A QueryInfo object represents a single query managed by the\n// QueryManager, which tracks all QueryInfo objects by queryId in its\n// this.queries Map. QueryInfo objects store the latest results and errors\n// for the given query, and are responsible for reporting those results to\n// the corresponding ObservableQuery, via the QueryInfo.notify method.\n// Results are reported asynchronously whenever setDiff marks the\n// QueryInfo object as dirty, though a call to the QueryManager's\n// broadcastQueries method may trigger the notification before it happens\n// automatically. This class used to be a simple interface type without\n// any field privacy or meaningful methods, which is why it still has so\n// many public fields. The effort to lock down and simplify the QueryInfo\n// interface is ongoing, and further improvements are welcome.\nvar QueryInfo = /** @class */ (function () {\n    function QueryInfo(queryManager, queryId) {\n        if (queryId === void 0) { queryId = queryManager.generateQueryId(); }\n        this.queryId = queryId;\n        this.listeners = new Set();\n        this.document = null;\n        this.lastRequestId = 1;\n        this.stopped = false;\n        this.dirty = false;\n        this.observableQuery = null;\n        var cache = (this.cache = queryManager.cache);\n        // Track how often cache.evict is called, since we want eviction to\n        // override the feud-stopping logic in the markResult method, by\n        // causing shouldWrite to return true. Wrapping the cache.evict method\n        // is a bit of a hack, but it saves us from having to make eviction\n        // counting an official part of the ApolloCache API.\n        if (!destructiveMethodCounts.has(cache)) {\n            destructiveMethodCounts.set(cache, 0);\n            wrapDestructiveCacheMethod(cache, \"evict\");\n            wrapDestructiveCacheMethod(cache, \"modify\");\n            wrapDestructiveCacheMethod(cache, \"reset\");\n        }\n    }\n    QueryInfo.prototype.init = function (query) {\n        var networkStatus = query.networkStatus || NetworkStatus.loading;\n        if (this.variables &&\n            this.networkStatus !== NetworkStatus.loading &&\n            !equal(this.variables, query.variables)) {\n            networkStatus = NetworkStatus.setVariables;\n        }\n        if (!equal(query.variables, this.variables)) {\n            this.lastDiff = void 0;\n        }\n        Object.assign(this, {\n            document: query.document,\n            variables: query.variables,\n            networkError: null,\n            graphQLErrors: this.graphQLErrors || [],\n            networkStatus: networkStatus,\n        });\n        if (query.observableQuery) {\n            this.setObservableQuery(query.observableQuery);\n        }\n        if (query.lastRequestId) {\n            this.lastRequestId = query.lastRequestId;\n        }\n        return this;\n    };\n    QueryInfo.prototype.reset = function () {\n        cancelNotifyTimeout(this);\n        this.dirty = false;\n    };\n    QueryInfo.prototype.resetDiff = function () {\n        this.lastDiff = void 0;\n    };\n    QueryInfo.prototype.getDiff = function () {\n        var options = this.getDiffOptions();\n        if (this.lastDiff && equal(options, this.lastDiff.options)) {\n            return this.lastDiff.diff;\n        }\n        this.updateWatch(this.variables);\n        var oq = this.observableQuery;\n        if (oq && oq.options.fetchPolicy === \"no-cache\") {\n            return { complete: false };\n        }\n        var diff = this.cache.diff(options);\n        this.updateLastDiff(diff, options);\n        return diff;\n    };\n    QueryInfo.prototype.updateLastDiff = function (diff, options) {\n        this.lastDiff =\n            diff ?\n                {\n                    diff: diff,\n                    options: options || this.getDiffOptions(),\n                }\n                : void 0;\n    };\n    QueryInfo.prototype.getDiffOptions = function (variables) {\n        var _a;\n        if (variables === void 0) { variables = this.variables; }\n        return {\n            query: this.document,\n            variables: variables,\n            returnPartialData: true,\n            optimistic: true,\n            canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,\n        };\n    };\n    QueryInfo.prototype.setDiff = function (diff) {\n        var _this = this;\n        var _a;\n        var oldDiff = this.lastDiff && this.lastDiff.diff;\n        // If we are trying to deliver an incomplete cache result, we avoid\n        // reporting it if the query has errored, otherwise we let the broadcast try\n        // and repair the partial result by refetching the query. This check avoids\n        // a situation where a query that errors and another succeeds with\n        // overlapping data does not report the partial data result to the errored\n        // query.\n        //\n        // See https://github.com/apollographql/apollo-client/issues/11400 for more\n        // information on this issue.\n        if (diff && !diff.complete && ((_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.getLastError())) {\n            return;\n        }\n        this.updateLastDiff(diff);\n        if (!this.dirty && !equal(oldDiff && oldDiff.result, diff && diff.result)) {\n            this.dirty = true;\n            if (!this.notifyTimeout) {\n                this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);\n            }\n        }\n    };\n    QueryInfo.prototype.setObservableQuery = function (oq) {\n        var _this = this;\n        if (oq === this.observableQuery)\n            return;\n        if (this.oqListener) {\n            this.listeners.delete(this.oqListener);\n        }\n        this.observableQuery = oq;\n        if (oq) {\n            oq[\"queryInfo\"] = this;\n            this.listeners.add((this.oqListener = function () {\n                var diff = _this.getDiff();\n                if (diff.fromOptimisticTransaction) {\n                    // If this diff came from an optimistic transaction, deliver the\n                    // current cache data to the ObservableQuery, but don't perform a\n                    // reobservation, since oq.reobserveCacheFirst might make a network\n                    // request, and we never want to trigger network requests in the\n                    // middle of optimistic updates.\n                    oq[\"observe\"]();\n                }\n                else {\n                    // Otherwise, make the ObservableQuery \"reobserve\" the latest data\n                    // using a temporary fetch policy of \"cache-first\", so complete cache\n                    // results have a chance to be delivered without triggering additional\n                    // network requests, even when options.fetchPolicy is \"network-only\"\n                    // or \"cache-and-network\". All other fetch policies are preserved by\n                    // this method, and are handled by calling oq.reobserve(). If this\n                    // reobservation is spurious, isDifferentFromLastResult still has a\n                    // chance to catch it before delivery to ObservableQuery subscribers.\n                    reobserveCacheFirst(oq);\n                }\n            }));\n        }\n        else {\n            delete this.oqListener;\n        }\n    };\n    QueryInfo.prototype.notify = function () {\n        var _this = this;\n        cancelNotifyTimeout(this);\n        if (this.shouldNotify()) {\n            this.listeners.forEach(function (listener) { return listener(_this); });\n        }\n        this.dirty = false;\n    };\n    QueryInfo.prototype.shouldNotify = function () {\n        if (!this.dirty || !this.listeners.size) {\n            return false;\n        }\n        if (isNetworkRequestInFlight(this.networkStatus) && this.observableQuery) {\n            var fetchPolicy = this.observableQuery.options.fetchPolicy;\n            if (fetchPolicy !== \"cache-only\" && fetchPolicy !== \"cache-and-network\") {\n                return false;\n            }\n        }\n        return true;\n    };\n    QueryInfo.prototype.stop = function () {\n        if (!this.stopped) {\n            this.stopped = true;\n            // Cancel the pending notify timeout\n            this.reset();\n            this.cancel();\n            // Revert back to the no-op version of cancel inherited from\n            // QueryInfo.prototype.\n            this.cancel = QueryInfo.prototype.cancel;\n            var oq = this.observableQuery;\n            if (oq)\n                oq.stopPolling();\n        }\n    };\n    // This method is a no-op by default, until/unless overridden by the\n    // updateWatch method.\n    QueryInfo.prototype.cancel = function () { };\n    QueryInfo.prototype.updateWatch = function (variables) {\n        var _this = this;\n        if (variables === void 0) { variables = this.variables; }\n        var oq = this.observableQuery;\n        if (oq && oq.options.fetchPolicy === \"no-cache\") {\n            return;\n        }\n        var watchOptions = __assign(__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });\n        if (!this.lastWatch || !equal(watchOptions, this.lastWatch)) {\n            this.cancel();\n            this.cancel = this.cache.watch((this.lastWatch = watchOptions));\n        }\n    };\n    QueryInfo.prototype.resetLastWrite = function () {\n        this.lastWrite = void 0;\n    };\n    QueryInfo.prototype.shouldWrite = function (result, variables) {\n        var lastWrite = this.lastWrite;\n        return !(lastWrite &&\n            // If cache.evict has been called since the last time we wrote this\n            // data into the cache, there's a chance writing this result into\n            // the cache will repair what was evicted.\n            lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&\n            equal(variables, lastWrite.variables) &&\n            equal(result.data, lastWrite.result.data));\n    };\n    QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {\n        var _this = this;\n        var merger = new DeepMerger();\n        var graphQLErrors = isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\n        // Cancel the pending notify timeout (if it exists) to prevent extraneous network\n        // requests. To allow future notify timeouts, diff and dirty are reset as well.\n        this.reset();\n        if (\"incremental\" in result && isNonEmptyArray(result.incremental)) {\n            var mergedData = mergeIncrementalData(this.getDiff().result, result);\n            result.data = mergedData;\n            // Detect the first chunk of a deferred query and merge it with existing\n            // cache data. This ensures a `cache-first` fetch policy that returns\n            // partial cache data or a `cache-and-network` fetch policy that already\n            // has full data in the cache does not complain when trying to merge the\n            // initial deferred server data with existing cache data.\n        }\n        else if (\"hasNext\" in result && result.hasNext) {\n            var diff = this.getDiff();\n            result.data = merger.merge(diff.result, result.data);\n        }\n        this.graphQLErrors = graphQLErrors;\n        if (options.fetchPolicy === \"no-cache\") {\n            this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));\n        }\n        else if (cacheWriteBehavior !== 0 /* CacheWriteBehavior.FORBID */) {\n            if (shouldWriteResult(result, options.errorPolicy)) {\n                // Using a transaction here so we have a chance to read the result\n                // back from the cache before the watch callback fires as a result\n                // of writeQuery, so we can store the new diff quietly and ignore\n                // it when we receive it redundantly from the watch callback.\n                this.cache.performTransaction(function (cache) {\n                    if (_this.shouldWrite(result, options.variables)) {\n                        cache.writeQuery({\n                            query: document,\n                            data: result.data,\n                            variables: options.variables,\n                            overwrite: cacheWriteBehavior === 1 /* CacheWriteBehavior.OVERWRITE */,\n                        });\n                        _this.lastWrite = {\n                            result: result,\n                            variables: options.variables,\n                            dmCount: destructiveMethodCounts.get(_this.cache),\n                        };\n                    }\n                    else {\n                        // If result is the same as the last result we received from\n                        // the network (and the variables match too), avoid writing\n                        // result into the cache again. The wisdom of skipping this\n                        // cache write is far from obvious, since any cache write\n                        // could be the one that puts the cache back into a desired\n                        // state, fixing corruption or missing data. However, if we\n                        // always write every network result into the cache, we enable\n                        // feuds between queries competing to update the same data in\n                        // incompatible ways, which can lead to an endless cycle of\n                        // cache broadcasts and useless network requests. As with any\n                        // feud, eventually one side must step back from the brink,\n                        // letting the other side(s) have the last word(s). There may\n                        // be other points where we could break this cycle, such as\n                        // silencing the broadcast for cache.writeQuery (not a good\n                        // idea, since it just delays the feud a bit) or somehow\n                        // avoiding the network request that just happened (also bad,\n                        // because the server could return useful new data). All\n                        // options considered, skipping this cache write seems to be\n                        // the least damaging place to break the cycle, because it\n                        // reflects the intuition that we recently wrote this exact\n                        // result into the cache, so the cache *should* already/still\n                        // contain this data. If some other query has clobbered that\n                        // data in the meantime, that's too bad, but there will be no\n                        // winners if every query blindly reverts to its own version\n                        // of the data. This approach also gives the network a chance\n                        // to return new data, which will be written into the cache as\n                        // usual, notifying only those queries that are directly\n                        // affected by the cache updates, as usual. In the future, an\n                        // even more sophisticated cache could perhaps prevent or\n                        // mitigate the clobbering somehow, but that would make this\n                        // particular cache write even less important, and thus\n                        // skipping it would be even safer than it is today.\n                        if (_this.lastDiff && _this.lastDiff.diff.complete) {\n                            // Reuse data from the last good (complete) diff that we\n                            // received, when possible.\n                            result.data = _this.lastDiff.diff.result;\n                            return;\n                        }\n                        // If the previous this.diff was incomplete, fall through to\n                        // re-reading the latest data with cache.diff, below.\n                    }\n                    var diffOptions = _this.getDiffOptions(options.variables);\n                    var diff = cache.diff(diffOptions);\n                    // In case the QueryManager stops this QueryInfo before its\n                    // results are delivered, it's important to avoid restarting the\n                    // cache watch when markResult is called. We also avoid updating\n                    // the watch if we are writing a result that doesn't match the current\n                    // variables to avoid race conditions from broadcasting the wrong\n                    // result.\n                    if (!_this.stopped && equal(_this.variables, options.variables)) {\n                        // Any time we're about to update this.diff, we need to make\n                        // sure we've started watching the cache.\n                        _this.updateWatch(options.variables);\n                    }\n                    // If we're allowed to write to the cache, and we can read a\n                    // complete result from the cache, update result.data to be the\n                    // result from the cache, rather than the raw network result.\n                    // Set without setDiff to avoid triggering a notify call, since\n                    // we have other ways of notifying for this result.\n                    _this.updateLastDiff(diff, diffOptions);\n                    if (diff.complete) {\n                        result.data = diff.result;\n                    }\n                });\n            }\n            else {\n                this.lastWrite = void 0;\n            }\n        }\n    };\n    QueryInfo.prototype.markReady = function () {\n        this.networkError = null;\n        return (this.networkStatus = NetworkStatus.ready);\n    };\n    QueryInfo.prototype.markError = function (error) {\n        this.networkStatus = NetworkStatus.error;\n        this.lastWrite = void 0;\n        this.reset();\n        if (error.graphQLErrors) {\n            this.graphQLErrors = error.graphQLErrors;\n        }\n        if (error.networkError) {\n            this.networkError = error.networkError;\n        }\n        return error;\n    };\n    return QueryInfo;\n}());\nexport { QueryInfo };\nexport function shouldWriteResult(result, errorPolicy) {\n    if (errorPolicy === void 0) { errorPolicy = \"none\"; }\n    var ignoreErrors = errorPolicy === \"ignore\" || errorPolicy === \"all\";\n    var writeWithErrors = !graphQLResultHasError(result);\n    if (!writeWithErrors && ignoreErrors && result.data) {\n        writeWithErrors = true;\n    }\n    return writeWithErrors;\n}\n//# sourceMappingURL=QueryInfo.js.map","import { __assign, __awaiter, __generator } from \"tslib\";\nimport { invariant, newInvariantError } from \"../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { execute } from \"../link/core/index.js\";\nimport { hasDirectives, isExecutionPatchIncrementalResult, isExecutionPatchResult, removeDirectivesFromDocument, } from \"../utilities/index.js\";\nimport { canonicalStringify } from \"../cache/index.js\";\nimport { getDefaultValues, getOperationDefinition, getOperationName, hasClientExports, graphQLResultHasError, getGraphQLErrorsFromResult, Observable, asyncMap, isNonEmptyArray, Concast, makeUniqueId, isDocumentNode, isNonNullObject, DocumentTransform, } from \"../utilities/index.js\";\nimport { mergeIncrementalData } from \"../utilities/common/incrementalResult.js\";\nimport { ApolloError, isApolloError, graphQLResultHasProtocolErrors, } from \"../errors/index.js\";\nimport { ObservableQuery, logMissingFieldErrors } from \"./ObservableQuery.js\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport { QueryInfo, shouldWriteResult, } from \"./QueryInfo.js\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"../errors/index.js\";\nimport { print } from \"../utilities/index.js\";\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar IGNORE = Object.create(null);\nimport { Trie } from \"@wry/trie\";\nimport { AutoCleanedWeakCache, cacheSizes } from \"../utilities/index.js\";\nvar QueryManager = /** @class */ (function () {\n    function QueryManager(options) {\n        var _this = this;\n        this.clientAwareness = {};\n        // All the queries that the QueryManager is currently managing (not\n        // including mutations and subscriptions).\n        this.queries = new Map();\n        // Maps from queryId strings to Promise rejection functions for\n        // currently active queries and fetches.\n        // Use protected instead of private field so\n        // @apollo/experimental-nextjs-app-support can access type info.\n        this.fetchCancelFns = new Map();\n        this.transformCache = new AutoCleanedWeakCache(cacheSizes[\"queryManager.getDocumentInfo\"] ||\n            2000 /* defaultCacheSizes[\"queryManager.getDocumentInfo\"] */);\n        this.queryIdCounter = 1;\n        this.requestIdCounter = 1;\n        this.mutationIdCounter = 1;\n        // Use protected instead of private field so\n        // @apollo/experimental-nextjs-app-support can access type info.\n        this.inFlightLinkObservables = new Trie(false);\n        var defaultDocumentTransform = new DocumentTransform(function (document) { return _this.cache.transformDocument(document); }, \n        // Allow the apollo cache to manage its own transform caches\n        { cache: false });\n        this.cache = options.cache;\n        this.link = options.link;\n        this.defaultOptions = options.defaultOptions;\n        this.queryDeduplication = options.queryDeduplication;\n        this.clientAwareness = options.clientAwareness;\n        this.localState = options.localState;\n        this.ssrMode = options.ssrMode;\n        this.assumeImmutableResults = options.assumeImmutableResults;\n        var documentTransform = options.documentTransform;\n        this.documentTransform =\n            documentTransform ?\n                defaultDocumentTransform\n                    .concat(documentTransform)\n                    // The custom document transform may add new fragment spreads or new\n                    // field selections, so we want to give the cache a chance to run\n                    // again. For example, the InMemoryCache adds __typename to field\n                    // selections and fragments from the fragment registry.\n                    .concat(defaultDocumentTransform)\n                : defaultDocumentTransform;\n        this.defaultContext = options.defaultContext || Object.create(null);\n        if ((this.onBroadcast = options.onBroadcast)) {\n            this.mutationStore = Object.create(null);\n        }\n    }\n    /**\n     * Call this method to terminate any active query processes, making it safe\n     * to dispose of this QueryManager instance.\n     */\n    QueryManager.prototype.stop = function () {\n        var _this = this;\n        this.queries.forEach(function (_info, queryId) {\n            _this.stopQueryNoBroadcast(queryId);\n        });\n        this.cancelPendingFetches(newInvariantError(26));\n    };\n    QueryManager.prototype.cancelPendingFetches = function (error) {\n        this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });\n        this.fetchCancelFns.clear();\n    };\n    QueryManager.prototype.mutate = function (_a) {\n        return __awaiter(this, arguments, void 0, function (_b) {\n            var mutationId, hasClientExports, mutationStoreValue, isOptimistic, self;\n            var _c, _d;\n            var mutation = _b.mutation, variables = _b.variables, optimisticResponse = _b.optimisticResponse, updateQueries = _b.updateQueries, _e = _b.refetchQueries, refetchQueries = _e === void 0 ? [] : _e, _f = _b.awaitRefetchQueries, awaitRefetchQueries = _f === void 0 ? false : _f, updateWithProxyFn = _b.update, onQueryUpdated = _b.onQueryUpdated, _g = _b.fetchPolicy, fetchPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.fetchPolicy) || \"network-only\" : _g, _h = _b.errorPolicy, errorPolicy = _h === void 0 ? ((_d = this.defaultOptions.mutate) === null || _d === void 0 ? void 0 : _d.errorPolicy) || \"none\" : _h, keepRootFields = _b.keepRootFields, context = _b.context;\n            return __generator(this, function (_j) {\n                switch (_j.label) {\n                    case 0:\n                        invariant(mutation, 27);\n                        invariant(fetchPolicy === \"network-only\" || fetchPolicy === \"no-cache\", 28);\n                        mutationId = this.generateMutationId();\n                        mutation = this.cache.transformForLink(this.transform(mutation));\n                        hasClientExports = this.getDocumentInfo(mutation).hasClientExports;\n                        variables = this.getVariables(mutation, variables);\n                        if (!hasClientExports) return [3 /*break*/, 2];\n                        return [4 /*yield*/, this.localState.addExportedVariables(mutation, variables, context)];\n                    case 1:\n                        variables = (_j.sent());\n                        _j.label = 2;\n                    case 2:\n                        mutationStoreValue = this.mutationStore &&\n                            (this.mutationStore[mutationId] = {\n                                mutation: mutation,\n                                variables: variables,\n                                loading: true,\n                                error: null,\n                            });\n                        isOptimistic = optimisticResponse &&\n                            this.markMutationOptimistic(optimisticResponse, {\n                                mutationId: mutationId,\n                                document: mutation,\n                                variables: variables,\n                                fetchPolicy: fetchPolicy,\n                                errorPolicy: errorPolicy,\n                                context: context,\n                                updateQueries: updateQueries,\n                                update: updateWithProxyFn,\n                                keepRootFields: keepRootFields,\n                            });\n                        this.broadcastQueries();\n                        self = this;\n                        return [2 /*return*/, new Promise(function (resolve, reject) {\n                                return asyncMap(self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: isOptimistic ? optimisticResponse : void 0 }), variables, {}, false), function (result) {\n                                    if (graphQLResultHasError(result) && errorPolicy === \"none\") {\n                                        throw new ApolloError({\n                                            graphQLErrors: getGraphQLErrorsFromResult(result),\n                                        });\n                                    }\n                                    if (mutationStoreValue) {\n                                        mutationStoreValue.loading = false;\n                                        mutationStoreValue.error = null;\n                                    }\n                                    var storeResult = __assign({}, result);\n                                    if (typeof refetchQueries === \"function\") {\n                                        refetchQueries = refetchQueries(storeResult);\n                                    }\n                                    if (errorPolicy === \"ignore\" && graphQLResultHasError(storeResult)) {\n                                        delete storeResult.errors;\n                                    }\n                                    return self.markMutationResult({\n                                        mutationId: mutationId,\n                                        result: storeResult,\n                                        document: mutation,\n                                        variables: variables,\n                                        fetchPolicy: fetchPolicy,\n                                        errorPolicy: errorPolicy,\n                                        context: context,\n                                        update: updateWithProxyFn,\n                                        updateQueries: updateQueries,\n                                        awaitRefetchQueries: awaitRefetchQueries,\n                                        refetchQueries: refetchQueries,\n                                        removeOptimistic: isOptimistic ? mutationId : void 0,\n                                        onQueryUpdated: onQueryUpdated,\n                                        keepRootFields: keepRootFields,\n                                    });\n                                }).subscribe({\n                                    next: function (storeResult) {\n                                        self.broadcastQueries();\n                                        // Since mutations might receive multiple payloads from the\n                                        // ApolloLink chain (e.g. when used with @defer),\n                                        // we resolve with a SingleExecutionResult or after the final\n                                        // ExecutionPatchResult has arrived and we have assembled the\n                                        // multipart response into a single result.\n                                        if (!(\"hasNext\" in storeResult) || storeResult.hasNext === false) {\n                                            resolve(storeResult);\n                                        }\n                                    },\n                                    error: function (err) {\n                                        if (mutationStoreValue) {\n                                            mutationStoreValue.loading = false;\n                                            mutationStoreValue.error = err;\n                                        }\n                                        if (isOptimistic) {\n                                            self.cache.removeOptimistic(mutationId);\n                                        }\n                                        self.broadcastQueries();\n                                        reject(err instanceof ApolloError ? err : (new ApolloError({\n                                            networkError: err,\n                                        })));\n                                    },\n                                });\n                            })];\n                }\n            });\n        });\n    };\n    QueryManager.prototype.markMutationResult = function (mutation, cache) {\n        var _this = this;\n        if (cache === void 0) { cache = this.cache; }\n        var result = mutation.result;\n        var cacheWrites = [];\n        var skipCache = mutation.fetchPolicy === \"no-cache\";\n        if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {\n            if (!isExecutionPatchIncrementalResult(result)) {\n                cacheWrites.push({\n                    result: result.data,\n                    dataId: \"ROOT_MUTATION\",\n                    query: mutation.document,\n                    variables: mutation.variables,\n                });\n            }\n            if (isExecutionPatchIncrementalResult(result) &&\n                isNonEmptyArray(result.incremental)) {\n                var diff = cache.diff({\n                    id: \"ROOT_MUTATION\",\n                    // The cache complains if passed a mutation where it expects a\n                    // query, so we transform mutations and subscriptions to queries\n                    // (only once, thanks to this.transformCache).\n                    query: this.getDocumentInfo(mutation.document).asQuery,\n                    variables: mutation.variables,\n                    optimistic: false,\n                    returnPartialData: true,\n                });\n                var mergedData = void 0;\n                if (diff.result) {\n                    mergedData = mergeIncrementalData(diff.result, result);\n                }\n                if (typeof mergedData !== \"undefined\") {\n                    // cast the ExecutionPatchResult to FetchResult here since\n                    // ExecutionPatchResult never has `data` when returned from the server\n                    result.data = mergedData;\n                    cacheWrites.push({\n                        result: mergedData,\n                        dataId: \"ROOT_MUTATION\",\n                        query: mutation.document,\n                        variables: mutation.variables,\n                    });\n                }\n            }\n            var updateQueries_1 = mutation.updateQueries;\n            if (updateQueries_1) {\n                this.queries.forEach(function (_a, queryId) {\n                    var observableQuery = _a.observableQuery;\n                    var queryName = observableQuery && observableQuery.queryName;\n                    if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {\n                        return;\n                    }\n                    var updater = updateQueries_1[queryName];\n                    var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;\n                    // Read the current query result from the store.\n                    var _c = cache.diff({\n                        query: document,\n                        variables: variables,\n                        returnPartialData: true,\n                        optimistic: false,\n                    }), currentQueryResult = _c.result, complete = _c.complete;\n                    if (complete && currentQueryResult) {\n                        // Run our reducer using the current query result and the mutation result.\n                        var nextQueryResult = updater(currentQueryResult, {\n                            mutationResult: result,\n                            queryName: (document && getOperationName(document)) || void 0,\n                            queryVariables: variables,\n                        });\n                        // Write the modified result back into the store if we got a new result.\n                        if (nextQueryResult) {\n                            cacheWrites.push({\n                                result: nextQueryResult,\n                                dataId: \"ROOT_QUERY\",\n                                query: document,\n                                variables: variables,\n                            });\n                        }\n                    }\n                });\n            }\n        }\n        if (cacheWrites.length > 0 ||\n            (mutation.refetchQueries || \"\").length > 0 ||\n            mutation.update ||\n            mutation.onQueryUpdated ||\n            mutation.removeOptimistic) {\n            var results_1 = [];\n            this.refetchQueries({\n                updateCache: function (cache) {\n                    if (!skipCache) {\n                        cacheWrites.forEach(function (write) { return cache.write(write); });\n                    }\n                    // If the mutation has some writes associated with it then we need to\n                    // apply those writes to the store by running this reducer again with\n                    // a write action.\n                    var update = mutation.update;\n                    // Determine whether result is a SingleExecutionResult,\n                    // or the final ExecutionPatchResult.\n                    var isFinalResult = !isExecutionPatchResult(result) ||\n                        (isExecutionPatchIncrementalResult(result) && !result.hasNext);\n                    if (update) {\n                        if (!skipCache) {\n                            // Re-read the ROOT_MUTATION data we just wrote into the cache\n                            // (the first cache.write call in the cacheWrites.forEach loop\n                            // above), so field read functions have a chance to run for\n                            // fields within mutation result objects.\n                            var diff = cache.diff({\n                                id: \"ROOT_MUTATION\",\n                                // The cache complains if passed a mutation where it expects a\n                                // query, so we transform mutations and subscriptions to queries\n                                // (only once, thanks to this.transformCache).\n                                query: _this.getDocumentInfo(mutation.document).asQuery,\n                                variables: mutation.variables,\n                                optimistic: false,\n                                returnPartialData: true,\n                            });\n                            if (diff.complete) {\n                                result = __assign(__assign({}, result), { data: diff.result });\n                                if (\"incremental\" in result) {\n                                    delete result.incremental;\n                                }\n                                if (\"hasNext\" in result) {\n                                    delete result.hasNext;\n                                }\n                            }\n                        }\n                        // If we've received the whole response,\n                        // either a SingleExecutionResult or the final ExecutionPatchResult,\n                        // call the update function.\n                        if (isFinalResult) {\n                            update(cache, result, {\n                                context: mutation.context,\n                                variables: mutation.variables,\n                            });\n                        }\n                    }\n                    // TODO Do this with cache.evict({ id: 'ROOT_MUTATION' }) but make it\n                    // shallow to allow rolling back optimistic evictions.\n                    if (!skipCache && !mutation.keepRootFields && isFinalResult) {\n                        cache.modify({\n                            id: \"ROOT_MUTATION\",\n                            fields: function (value, _a) {\n                                var fieldName = _a.fieldName, DELETE = _a.DELETE;\n                                return fieldName === \"__typename\" ? value : DELETE;\n                            },\n                        });\n                    }\n                },\n                include: mutation.refetchQueries,\n                // Write the final mutation.result to the root layer of the cache.\n                optimistic: false,\n                // Remove the corresponding optimistic layer at the same time as we\n                // write the final non-optimistic result.\n                removeOptimistic: mutation.removeOptimistic,\n                // Let the caller of client.mutate optionally determine the refetching\n                // behavior for watched queries after the mutation.update function runs.\n                // If no onQueryUpdated function was provided for this mutation, pass\n                // null instead of undefined to disable the default refetching behavior.\n                onQueryUpdated: mutation.onQueryUpdated || null,\n            }).forEach(function (result) { return results_1.push(result); });\n            if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {\n                // Returning a promise here makes the mutation await that promise, so we\n                // include results in that promise's work if awaitRefetchQueries or an\n                // onQueryUpdated function was specified.\n                return Promise.all(results_1).then(function () { return result; });\n            }\n        }\n        return Promise.resolve(result);\n    };\n    QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {\n        var _this = this;\n        var data = typeof optimisticResponse === \"function\" ?\n            optimisticResponse(mutation.variables, { IGNORE: IGNORE })\n            : optimisticResponse;\n        if (data === IGNORE) {\n            return false;\n        }\n        this.cache.recordOptimisticTransaction(function (cache) {\n            try {\n                _this.markMutationResult(__assign(__assign({}, mutation), { result: { data: data } }), cache);\n            }\n            catch (error) {\n                globalThis.__DEV__ !== false && invariant.error(error);\n            }\n        }, mutation.mutationId);\n        return true;\n    };\n    QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {\n        return this.fetchConcastWithInfo(queryId, options, networkStatus).concast\n            .promise;\n    };\n    QueryManager.prototype.getQueryStore = function () {\n        var store = Object.create(null);\n        this.queries.forEach(function (info, queryId) {\n            store[queryId] = {\n                variables: info.variables,\n                networkStatus: info.networkStatus,\n                networkError: info.networkError,\n                graphQLErrors: info.graphQLErrors,\n            };\n        });\n        return store;\n    };\n    QueryManager.prototype.resetErrors = function (queryId) {\n        var queryInfo = this.queries.get(queryId);\n        if (queryInfo) {\n            queryInfo.networkError = undefined;\n            queryInfo.graphQLErrors = [];\n        }\n    };\n    QueryManager.prototype.transform = function (document) {\n        return this.documentTransform.transformDocument(document);\n    };\n    QueryManager.prototype.getDocumentInfo = function (document) {\n        var transformCache = this.transformCache;\n        if (!transformCache.has(document)) {\n            var cacheEntry = {\n                // TODO These three calls (hasClientExports, shouldForceResolvers, and\n                // usesNonreactiveDirective) are performing independent full traversals\n                // of the transformed document. We should consider merging these\n                // traversals into a single pass in the future, though the work is\n                // cached after the first time.\n                hasClientExports: hasClientExports(document),\n                hasForcedResolvers: this.localState.shouldForceResolvers(document),\n                hasNonreactiveDirective: hasDirectives([\"nonreactive\"], document),\n                clientQuery: this.localState.clientQuery(document),\n                serverQuery: removeDirectivesFromDocument([\n                    { name: \"client\", remove: true },\n                    { name: \"connection\" },\n                    { name: \"nonreactive\" },\n                ], document),\n                defaultVars: getDefaultValues(getOperationDefinition(document)),\n                // Transform any mutation or subscription operations to query operations\n                // so we can read/write them from/to the cache.\n                asQuery: __assign(__assign({}, document), { definitions: document.definitions.map(function (def) {\n                        if (def.kind === \"OperationDefinition\" &&\n                            def.operation !== \"query\") {\n                            return __assign(__assign({}, def), { operation: \"query\" });\n                        }\n                        return def;\n                    }) }),\n            };\n            transformCache.set(document, cacheEntry);\n        }\n        return transformCache.get(document);\n    };\n    QueryManager.prototype.getVariables = function (document, variables) {\n        return __assign(__assign({}, this.getDocumentInfo(document).defaultVars), variables);\n    };\n    QueryManager.prototype.watchQuery = function (options) {\n        var query = this.transform(options.query);\n        // assign variable default values if supplied\n        // NOTE: We don't modify options.query here with the transformed query to\n        // ensure observable.options.query is set to the raw untransformed query.\n        options = __assign(__assign({}, options), { variables: this.getVariables(query, options.variables) });\n        if (typeof options.notifyOnNetworkStatusChange === \"undefined\") {\n            options.notifyOnNetworkStatusChange = false;\n        }\n        var queryInfo = new QueryInfo(this);\n        var observable = new ObservableQuery({\n            queryManager: this,\n            queryInfo: queryInfo,\n            options: options,\n        });\n        observable[\"lastQuery\"] = query;\n        this.queries.set(observable.queryId, queryInfo);\n        // We give queryInfo the transformed query to ensure the first cache diff\n        // uses the transformed query instead of the raw query\n        queryInfo.init({\n            document: query,\n            observableQuery: observable,\n            variables: observable.variables,\n        });\n        return observable;\n    };\n    QueryManager.prototype.query = function (options, queryId) {\n        var _this = this;\n        if (queryId === void 0) { queryId = this.generateQueryId(); }\n        invariant(options.query, 29);\n        invariant(options.query.kind === \"Document\", 30);\n        invariant(!options.returnPartialData, 31);\n        invariant(!options.pollInterval, 32);\n        return this.fetchQuery(queryId, __assign(__assign({}, options), { query: this.transform(options.query) })).finally(function () { return _this.stopQuery(queryId); });\n    };\n    QueryManager.prototype.generateQueryId = function () {\n        return String(this.queryIdCounter++);\n    };\n    QueryManager.prototype.generateRequestId = function () {\n        return this.requestIdCounter++;\n    };\n    QueryManager.prototype.generateMutationId = function () {\n        return String(this.mutationIdCounter++);\n    };\n    QueryManager.prototype.stopQueryInStore = function (queryId) {\n        this.stopQueryInStoreNoBroadcast(queryId);\n        this.broadcastQueries();\n    };\n    QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {\n        var queryInfo = this.queries.get(queryId);\n        if (queryInfo)\n            queryInfo.stop();\n    };\n    QueryManager.prototype.clearStore = function (options) {\n        if (options === void 0) { options = {\n            discardWatches: true,\n        }; }\n        // Before we have sent the reset action to the store, we can no longer\n        // rely on the results returned by in-flight requests since these may\n        // depend on values that previously existed in the data portion of the\n        // store. So, we cancel the promises and observers that we have issued\n        // so far and not yet resolved (in the case of queries).\n        this.cancelPendingFetches(newInvariantError(33));\n        this.queries.forEach(function (queryInfo) {\n            if (queryInfo.observableQuery) {\n                // Set loading to true so listeners don't trigger unless they want\n                // results with partial data.\n                queryInfo.networkStatus = NetworkStatus.loading;\n            }\n            else {\n                queryInfo.stop();\n            }\n        });\n        if (this.mutationStore) {\n            this.mutationStore = Object.create(null);\n        }\n        // begin removing data from the store\n        return this.cache.reset(options);\n    };\n    QueryManager.prototype.getObservableQueries = function (include) {\n        var _this = this;\n        if (include === void 0) { include = \"active\"; }\n        var queries = new Map();\n        var queryNamesAndDocs = new Map();\n        var legacyQueryOptions = new Set();\n        if (Array.isArray(include)) {\n            include.forEach(function (desc) {\n                if (typeof desc === \"string\") {\n                    queryNamesAndDocs.set(desc, false);\n                }\n                else if (isDocumentNode(desc)) {\n                    queryNamesAndDocs.set(_this.transform(desc), false);\n                }\n                else if (isNonNullObject(desc) && desc.query) {\n                    legacyQueryOptions.add(desc);\n                }\n            });\n        }\n        this.queries.forEach(function (_a, queryId) {\n            var oq = _a.observableQuery, document = _a.document;\n            if (oq) {\n                if (include === \"all\") {\n                    queries.set(queryId, oq);\n                    return;\n                }\n                var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;\n                if (fetchPolicy === \"standby\" ||\n                    (include === \"active\" && !oq.hasObservers())) {\n                    return;\n                }\n                if (include === \"active\" ||\n                    (queryName && queryNamesAndDocs.has(queryName)) ||\n                    (document && queryNamesAndDocs.has(document))) {\n                    queries.set(queryId, oq);\n                    if (queryName)\n                        queryNamesAndDocs.set(queryName, true);\n                    if (document)\n                        queryNamesAndDocs.set(document, true);\n                }\n            }\n        });\n        if (legacyQueryOptions.size) {\n            legacyQueryOptions.forEach(function (options) {\n                // We will be issuing a fresh network request for this query, so we\n                // pre-allocate a new query ID here, using a special prefix to enable\n                // cleaning up these temporary queries later, after fetching.\n                var queryId = makeUniqueId(\"legacyOneTimeQuery\");\n                var queryInfo = _this.getQuery(queryId).init({\n                    document: options.query,\n                    variables: options.variables,\n                });\n                var oq = new ObservableQuery({\n                    queryManager: _this,\n                    queryInfo: queryInfo,\n                    options: __assign(__assign({}, options), { fetchPolicy: \"network-only\" }),\n                });\n                invariant(oq.queryId === queryId);\n                queryInfo.setObservableQuery(oq);\n                queries.set(queryId, oq);\n            });\n        }\n        if (globalThis.__DEV__ !== false && queryNamesAndDocs.size) {\n            queryNamesAndDocs.forEach(function (included, nameOrDoc) {\n                if (!included) {\n                    globalThis.__DEV__ !== false && invariant.warn(typeof nameOrDoc === \"string\" ? 34 : 35, nameOrDoc);\n                }\n            });\n        }\n        return queries;\n    };\n    QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {\n        var _this = this;\n        if (includeStandby === void 0) { includeStandby = false; }\n        var observableQueryPromises = [];\n        this.getObservableQueries(includeStandby ? \"all\" : \"active\").forEach(function (observableQuery, queryId) {\n            var fetchPolicy = observableQuery.options.fetchPolicy;\n            observableQuery.resetLastResults();\n            if (includeStandby ||\n                (fetchPolicy !== \"standby\" && fetchPolicy !== \"cache-only\")) {\n                observableQueryPromises.push(observableQuery.refetch());\n            }\n            _this.getQuery(queryId).setDiff(null);\n        });\n        this.broadcastQueries();\n        return Promise.all(observableQueryPromises);\n    };\n    QueryManager.prototype.setObservableQuery = function (observableQuery) {\n        this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);\n    };\n    QueryManager.prototype.startGraphQLSubscription = function (_a) {\n        var _this = this;\n        var query = _a.query, fetchPolicy = _a.fetchPolicy, _b = _a.errorPolicy, errorPolicy = _b === void 0 ? \"none\" : _b, variables = _a.variables, _c = _a.context, context = _c === void 0 ? {} : _c, _d = _a.extensions, extensions = _d === void 0 ? {} : _d;\n        query = this.transform(query);\n        variables = this.getVariables(query, variables);\n        var makeObservable = function (variables) {\n            return _this.getObservableFromLink(query, context, variables, extensions).map(function (result) {\n                if (fetchPolicy !== \"no-cache\") {\n                    // the subscription interface should handle not sending us results we no longer subscribe to.\n                    // XXX I don't think we ever send in an object with errors, but we might in the future...\n                    if (shouldWriteResult(result, errorPolicy)) {\n                        _this.cache.write({\n                            query: query,\n                            result: result.data,\n                            dataId: \"ROOT_SUBSCRIPTION\",\n                            variables: variables,\n                        });\n                    }\n                    _this.broadcastQueries();\n                }\n                var hasErrors = graphQLResultHasError(result);\n                var hasProtocolErrors = graphQLResultHasProtocolErrors(result);\n                if (hasErrors || hasProtocolErrors) {\n                    var errors = {};\n                    if (hasErrors) {\n                        errors.graphQLErrors = result.errors;\n                    }\n                    if (hasProtocolErrors) {\n                        errors.protocolErrors = result.extensions[PROTOCOL_ERRORS_SYMBOL];\n                    }\n                    // `errorPolicy` is a mechanism for handling GraphQL errors, according\n                    // to our documentation, so we throw protocol errors regardless of the\n                    // set error policy.\n                    if (errorPolicy === \"none\" || hasProtocolErrors) {\n                        throw new ApolloError(errors);\n                    }\n                }\n                if (errorPolicy === \"ignore\") {\n                    delete result.errors;\n                }\n                return result;\n            });\n        };\n        if (this.getDocumentInfo(query).hasClientExports) {\n            var observablePromise_1 = this.localState\n                .addExportedVariables(query, variables, context)\n                .then(makeObservable);\n            return new Observable(function (observer) {\n                var sub = null;\n                observablePromise_1.then(function (observable) { return (sub = observable.subscribe(observer)); }, observer.error);\n                return function () { return sub && sub.unsubscribe(); };\n            });\n        }\n        return makeObservable(variables);\n    };\n    QueryManager.prototype.stopQuery = function (queryId) {\n        this.stopQueryNoBroadcast(queryId);\n        this.broadcastQueries();\n    };\n    QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {\n        this.stopQueryInStoreNoBroadcast(queryId);\n        this.removeQuery(queryId);\n    };\n    QueryManager.prototype.removeQuery = function (queryId) {\n        // teardown all links\n        // Both `QueryManager.fetchRequest` and `QueryManager.query` create separate promises\n        // that each add their reject functions to fetchCancelFns.\n        // A query created with `QueryManager.query()` could trigger a `QueryManager.fetchRequest`.\n        // The same queryId could have two rejection fns for two promises\n        this.fetchCancelFns.delete(queryId);\n        if (this.queries.has(queryId)) {\n            this.getQuery(queryId).stop();\n            this.queries.delete(queryId);\n        }\n    };\n    QueryManager.prototype.broadcastQueries = function () {\n        if (this.onBroadcast)\n            this.onBroadcast();\n        this.queries.forEach(function (info) { return info.notify(); });\n    };\n    QueryManager.prototype.getLocalState = function () {\n        return this.localState;\n    };\n    QueryManager.prototype.getObservableFromLink = function (query, context, variables, extensions, \n    // Prefer context.queryDeduplication if specified.\n    deduplication) {\n        var _this = this;\n        var _a;\n        if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }\n        var observable;\n        var _b = this.getDocumentInfo(query), serverQuery = _b.serverQuery, clientQuery = _b.clientQuery;\n        if (serverQuery) {\n            var _c = this, inFlightLinkObservables_1 = _c.inFlightLinkObservables, link = _c.link;\n            var operation = {\n                query: serverQuery,\n                variables: variables,\n                operationName: getOperationName(serverQuery) || void 0,\n                context: this.prepareContext(__assign(__assign({}, context), { forceFetch: !deduplication })),\n                extensions: extensions,\n            };\n            context = operation.context;\n            if (deduplication) {\n                var printedServerQuery_1 = print(serverQuery);\n                var varJson_1 = canonicalStringify(variables);\n                var entry = inFlightLinkObservables_1.lookup(printedServerQuery_1, varJson_1);\n                observable = entry.observable;\n                if (!observable) {\n                    var concast = new Concast([\n                        execute(link, operation),\n                    ]);\n                    observable = entry.observable = concast;\n                    concast.beforeNext(function () {\n                        inFlightLinkObservables_1.remove(printedServerQuery_1, varJson_1);\n                    });\n                }\n            }\n            else {\n                observable = new Concast([\n                    execute(link, operation),\n                ]);\n            }\n        }\n        else {\n            observable = new Concast([Observable.of({ data: {} })]);\n            context = this.prepareContext(context);\n        }\n        if (clientQuery) {\n            observable = asyncMap(observable, function (result) {\n                return _this.localState.runResolvers({\n                    document: clientQuery,\n                    remoteResult: result,\n                    context: context,\n                    variables: variables,\n                });\n            });\n        }\n        return observable;\n    };\n    QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {\n        var requestId = (queryInfo.lastRequestId = this.generateRequestId());\n        // Performing transformForLink here gives this.cache a chance to fill in\n        // missing fragment definitions (for example) before sending this document\n        // through the link chain.\n        var linkDocument = this.cache.transformForLink(options.query);\n        return asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {\n            var graphQLErrors = getGraphQLErrorsFromResult(result);\n            var hasErrors = graphQLErrors.length > 0;\n            var errorPolicy = options.errorPolicy;\n            // If we interrupted this request by calling getResultsFromLink again\n            // with the same QueryInfo object, we ignore the old results.\n            if (requestId >= queryInfo.lastRequestId) {\n                if (hasErrors && errorPolicy === \"none\") {\n                    // Throwing here effectively calls observer.error.\n                    throw queryInfo.markError(new ApolloError({\n                        graphQLErrors: graphQLErrors,\n                    }));\n                }\n                // Use linkDocument rather than queryInfo.document so the\n                // operation/fragments used to write the result are the same as the\n                // ones used to obtain it from the link.\n                queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);\n                queryInfo.markReady();\n            }\n            var aqr = {\n                data: result.data,\n                loading: false,\n                networkStatus: NetworkStatus.ready,\n            };\n            // In the case we start multiple network requests simulatenously, we\n            // want to ensure we properly set `data` if we're reporting on an old\n            // result which will not be caught by the conditional above that ends up\n            // throwing the markError result.\n            if (hasErrors && errorPolicy === \"none\") {\n                aqr.data = void 0;\n            }\n            if (hasErrors && errorPolicy !== \"ignore\") {\n                aqr.errors = graphQLErrors;\n                aqr.networkStatus = NetworkStatus.error;\n            }\n            return aqr;\n        }, function (networkError) {\n            var error = isApolloError(networkError) ? networkError : (new ApolloError({ networkError: networkError }));\n            // Avoid storing errors from older interrupted queries.\n            if (requestId >= queryInfo.lastRequestId) {\n                queryInfo.markError(error);\n            }\n            throw error;\n        });\n    };\n    QueryManager.prototype.fetchConcastWithInfo = function (queryId, options, \n    // The initial networkStatus for this fetch, most often\n    // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n    // or setVariables.\n    networkStatus, query) {\n        var _this = this;\n        if (networkStatus === void 0) { networkStatus = NetworkStatus.loading; }\n        if (query === void 0) { query = options.query; }\n        var variables = this.getVariables(query, options.variables);\n        var queryInfo = this.getQuery(queryId);\n        var defaults = this.defaultOptions.watchQuery;\n        var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? (defaults && defaults.fetchPolicy) || \"cache-first\" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? (defaults && defaults.errorPolicy) || \"none\" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;\n        var normalized = Object.assign({}, options, {\n            query: query,\n            variables: variables,\n            fetchPolicy: fetchPolicy,\n            errorPolicy: errorPolicy,\n            returnPartialData: returnPartialData,\n            notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,\n            context: context,\n        });\n        var fromVariables = function (variables) {\n            // Since normalized is always a fresh copy of options, it's safe to\n            // modify its properties here, rather than creating yet another new\n            // WatchQueryOptions object.\n            normalized.variables = variables;\n            var sourcesWithInfo = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);\n            if (\n            // If we're in standby, postpone advancing options.fetchPolicy using\n            // applyNextFetchPolicy.\n            normalized.fetchPolicy !== \"standby\" &&\n                // The \"standby\" policy currently returns [] from fetchQueryByPolicy, so\n                // this is another way to detect when nothing was done/fetched.\n                sourcesWithInfo.sources.length > 0 &&\n                queryInfo.observableQuery) {\n                queryInfo.observableQuery[\"applyNextFetchPolicy\"](\"after-fetch\", options);\n            }\n            return sourcesWithInfo;\n        };\n        // This cancel function needs to be set before the concast is created,\n        // in case concast creation synchronously cancels the request.\n        var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };\n        this.fetchCancelFns.set(queryId, function (reason) {\n            cleanupCancelFn();\n            // This delay ensures the concast variable has been initialized.\n            setTimeout(function () { return concast.cancel(reason); });\n        });\n        var concast, containsDataFromLink;\n        // If the query has @export(as: ...) directives, then we need to\n        // process those directives asynchronously. When there are no\n        // @export directives (the common case), we deliberately avoid\n        // wrapping the result of this.fetchQueryByPolicy in a Promise,\n        // since the timing of result delivery is (unfortunately) important\n        // for backwards compatibility. TODO This code could be simpler if\n        // we deprecated and removed LocalState.\n        if (this.getDocumentInfo(normalized.query).hasClientExports) {\n            concast = new Concast(this.localState\n                .addExportedVariables(normalized.query, normalized.variables, normalized.context)\n                .then(fromVariables)\n                .then(function (sourcesWithInfo) { return sourcesWithInfo.sources; }));\n            // there is just no way we can synchronously get the *right* value here,\n            // so we will assume `true`, which is the behaviour before the bug fix in\n            // #10597. This means that bug is not fixed in that case, and is probably\n            // un-fixable with reasonable effort for the edge case of @export as\n            // directives.\n            containsDataFromLink = true;\n        }\n        else {\n            var sourcesWithInfo = fromVariables(normalized.variables);\n            containsDataFromLink = sourcesWithInfo.fromLink;\n            concast = new Concast(sourcesWithInfo.sources);\n        }\n        concast.promise.then(cleanupCancelFn, cleanupCancelFn);\n        return {\n            concast: concast,\n            fromLink: containsDataFromLink,\n        };\n    };\n    QueryManager.prototype.refetchQueries = function (_a) {\n        var _this = this;\n        var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? makeUniqueId(\"refetchQueries\") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;\n        var includedQueriesById = new Map();\n        if (include) {\n            this.getObservableQueries(include).forEach(function (oq, queryId) {\n                includedQueriesById.set(queryId, {\n                    oq: oq,\n                    lastDiff: _this.getQuery(queryId).getDiff(),\n                });\n            });\n        }\n        var results = new Map();\n        if (updateCache) {\n            this.cache.batch({\n                update: updateCache,\n                // Since you can perform any combination of cache reads and/or writes in\n                // the cache.batch update function, its optimistic option can be either\n                // a boolean or a string, representing three distinct modes of\n                // operation:\n                //\n                // * false: read/write only the root layer\n                // * true: read/write the topmost layer\n                // * string: read/write a fresh optimistic layer with that ID string\n                //\n                // When typeof optimistic === \"string\", a new optimistic layer will be\n                // temporarily created within cache.batch with that string as its ID. If\n                // we then pass that same string as the removeOptimistic option, we can\n                // make cache.batch immediately remove the optimistic layer after\n                // running the updateCache function, triggering only one broadcast.\n                //\n                // However, the refetchQueries method accepts only true or false for its\n                // optimistic option (not string). We interpret true to mean a temporary\n                // optimistic layer should be created, to allow efficiently rolling back\n                // the effect of the updateCache function, which involves passing a\n                // string instead of true as the optimistic option to cache.batch, when\n                // refetchQueries receives optimistic: true.\n                //\n                // In other words, we are deliberately not supporting the use case of\n                // writing to an *existing* optimistic layer (using the refetchQueries\n                // updateCache function), since that would potentially interfere with\n                // other optimistic updates in progress. Instead, you can read/write\n                // only the root layer by passing optimistic: false to refetchQueries,\n                // or you can read/write a brand new optimistic layer that will be\n                // automatically removed by passing optimistic: true.\n                optimistic: (optimistic && removeOptimistic) || false,\n                // The removeOptimistic option can also be provided by itself, even if\n                // optimistic === false, to remove some previously-added optimistic\n                // layer safely and efficiently, like we do in markMutationResult.\n                //\n                // If an explicit removeOptimistic string is provided with optimistic:\n                // true, the removeOptimistic string will determine the ID of the\n                // temporary optimistic layer, in case that ever matters.\n                removeOptimistic: removeOptimistic,\n                onWatchUpdated: function (watch, diff, lastDiff) {\n                    var oq = watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;\n                    if (oq) {\n                        if (onQueryUpdated) {\n                            // Since we're about to handle this query now, remove it from\n                            // includedQueriesById, in case it was added earlier because of\n                            // options.include.\n                            includedQueriesById.delete(oq.queryId);\n                            var result = onQueryUpdated(oq, diff, lastDiff);\n                            if (result === true) {\n                                // The onQueryUpdated function requested the default refetching\n                                // behavior by returning true.\n                                result = oq.refetch();\n                            }\n                            // Record the result in the results Map, as long as onQueryUpdated\n                            // did not return false to skip/ignore this result.\n                            if (result !== false) {\n                                results.set(oq, result);\n                            }\n                            // Allow the default cache broadcast to happen, except when\n                            // onQueryUpdated returns false.\n                            return result;\n                        }\n                        if (onQueryUpdated !== null) {\n                            // If we don't have an onQueryUpdated function, and onQueryUpdated\n                            // was not disabled by passing null, make sure this query is\n                            // \"included\" like any other options.include-specified query.\n                            includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });\n                        }\n                    }\n                },\n            });\n        }\n        if (includedQueriesById.size) {\n            includedQueriesById.forEach(function (_a, queryId) {\n                var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;\n                var result;\n                // If onQueryUpdated is provided, we want to use it for all included\n                // queries, even the QueryOptions ones.\n                if (onQueryUpdated) {\n                    if (!diff) {\n                        var info = oq[\"queryInfo\"];\n                        info.reset(); // Force info.getDiff() to read from cache.\n                        diff = info.getDiff();\n                    }\n                    result = onQueryUpdated(oq, diff, lastDiff);\n                }\n                // Otherwise, we fall back to refetching.\n                if (!onQueryUpdated || result === true) {\n                    result = oq.refetch();\n                }\n                if (result !== false) {\n                    results.set(oq, result);\n                }\n                if (queryId.indexOf(\"legacyOneTimeQuery\") >= 0) {\n                    _this.stopQueryNoBroadcast(queryId);\n                }\n            });\n        }\n        if (removeOptimistic) {\n            // In case no updateCache callback was provided (so cache.batch was not\n            // called above, and thus did not already remove the optimistic layer),\n            // remove it here. Since this is a no-op when the layer has already been\n            // removed, we do it even if we called cache.batch above, since it's\n            // possible this.cache is an instance of some ApolloCache subclass other\n            // than InMemoryCache, and does not fully support the removeOptimistic\n            // option for cache.batch.\n            this.cache.removeOptimistic(removeOptimistic);\n        }\n        return results;\n    };\n    QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a, \n    // The initial networkStatus for this fetch, most often\n    // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n    // or setVariables.\n    networkStatus) {\n        var _this = this;\n        var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;\n        var oldNetworkStatus = queryInfo.networkStatus;\n        queryInfo.init({\n            document: query,\n            variables: variables,\n            networkStatus: networkStatus,\n        });\n        var readCache = function () { return queryInfo.getDiff(); };\n        var resultsFromCache = function (diff, networkStatus) {\n            if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || NetworkStatus.loading; }\n            var data = diff.result;\n            if (globalThis.__DEV__ !== false && !returnPartialData && !equal(data, {})) {\n                logMissingFieldErrors(diff.missing);\n            }\n            var fromData = function (data) {\n                return Observable.of(__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true })));\n            };\n            if (data && _this.getDocumentInfo(query).hasForcedResolvers) {\n                return _this.localState\n                    .runResolvers({\n                    document: query,\n                    remoteResult: { data: data },\n                    context: context,\n                    variables: variables,\n                    onlyRunForcedResolvers: true,\n                })\n                    .then(function (resolved) { return fromData(resolved.data || void 0); });\n            }\n            // Resolves https://github.com/apollographql/apollo-client/issues/10317.\n            // If errorPolicy is 'none' and notifyOnNetworkStatusChange is true,\n            // data was incorrectly returned from the cache on refetch:\n            // if diff.missing exists, we should not return cache data.\n            if (errorPolicy === \"none\" &&\n                networkStatus === NetworkStatus.refetch &&\n                Array.isArray(diff.missing)) {\n                return fromData(void 0);\n            }\n            return fromData(data);\n        };\n        var cacheWriteBehavior = fetchPolicy === \"no-cache\" ? 0 /* CacheWriteBehavior.FORBID */\n            // Watched queries must opt into overwriting existing data on refetch,\n            // by passing refetchWritePolicy: \"overwrite\" in their WatchQueryOptions.\n            : (networkStatus === NetworkStatus.refetch &&\n                refetchWritePolicy !== \"merge\") ?\n                1 /* CacheWriteBehavior.OVERWRITE */\n                : 2 /* CacheWriteBehavior.MERGE */;\n        var resultsFromLink = function () {\n            return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {\n                query: query,\n                variables: variables,\n                context: context,\n                fetchPolicy: fetchPolicy,\n                errorPolicy: errorPolicy,\n            });\n        };\n        var shouldNotify = notifyOnNetworkStatusChange &&\n            typeof oldNetworkStatus === \"number\" &&\n            oldNetworkStatus !== networkStatus &&\n            isNetworkRequestInFlight(networkStatus);\n        switch (fetchPolicy) {\n            default:\n            case \"cache-first\": {\n                var diff = readCache();\n                if (diff.complete) {\n                    return {\n                        fromLink: false,\n                        sources: [resultsFromCache(diff, queryInfo.markReady())],\n                    };\n                }\n                if (returnPartialData || shouldNotify) {\n                    return {\n                        fromLink: true,\n                        sources: [resultsFromCache(diff), resultsFromLink()],\n                    };\n                }\n                return { fromLink: true, sources: [resultsFromLink()] };\n            }\n            case \"cache-and-network\": {\n                var diff = readCache();\n                if (diff.complete || returnPartialData || shouldNotify) {\n                    return {\n                        fromLink: true,\n                        sources: [resultsFromCache(diff), resultsFromLink()],\n                    };\n                }\n                return { fromLink: true, sources: [resultsFromLink()] };\n            }\n            case \"cache-only\":\n                return {\n                    fromLink: false,\n                    sources: [resultsFromCache(readCache(), queryInfo.markReady())],\n                };\n            case \"network-only\":\n                if (shouldNotify) {\n                    return {\n                        fromLink: true,\n                        sources: [resultsFromCache(readCache()), resultsFromLink()],\n                    };\n                }\n                return { fromLink: true, sources: [resultsFromLink()] };\n            case \"no-cache\":\n                if (shouldNotify) {\n                    return {\n                        fromLink: true,\n                        // Note that queryInfo.getDiff() for no-cache queries does not call\n                        // cache.diff, but instead returns a { complete: false } stub result\n                        // when there is no queryInfo.diff already defined.\n                        sources: [resultsFromCache(queryInfo.getDiff()), resultsFromLink()],\n                    };\n                }\n                return { fromLink: true, sources: [resultsFromLink()] };\n            case \"standby\":\n                return { fromLink: false, sources: [] };\n        }\n    };\n    QueryManager.prototype.getQuery = function (queryId) {\n        if (queryId && !this.queries.has(queryId)) {\n            this.queries.set(queryId, new QueryInfo(this, queryId));\n        }\n        return this.queries.get(queryId);\n    };\n    QueryManager.prototype.prepareContext = function (context) {\n        if (context === void 0) { context = {}; }\n        var newContext = this.localState.prepareContext(context);\n        return __assign(__assign(__assign({}, this.defaultContext), newContext), { clientAwareness: this.clientAwareness });\n    };\n    return QueryManager;\n}());\nexport { QueryManager };\n//# sourceMappingURL=QueryManager.js.map","import { __assign, __awaiter, __generator } from \"tslib\";\nimport { invariant } from \"../utilities/globals/index.js\";\nimport { visit, BREAK, isSelectionNode } from \"graphql\";\nimport { argumentsObjectFromField, buildQueryFromSelectionSet, createFragmentMap, getFragmentDefinitions, getMainDefinition, hasDirectives, isField, isInlineFragment, mergeDeep, mergeDeepArray, removeClientSetsFromDocument, resultKeyNameFromField, shouldInclude, } from \"../utilities/index.js\";\nimport { cacheSlot } from \"../cache/index.js\";\nvar LocalState = /** @class */ (function () {\n    function LocalState(_a) {\n        var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;\n        this.selectionsToResolveCache = new WeakMap();\n        this.cache = cache;\n        if (client) {\n            this.client = client;\n        }\n        if (resolvers) {\n            this.addResolvers(resolvers);\n        }\n        if (fragmentMatcher) {\n            this.setFragmentMatcher(fragmentMatcher);\n        }\n    }\n    LocalState.prototype.addResolvers = function (resolvers) {\n        var _this = this;\n        this.resolvers = this.resolvers || {};\n        if (Array.isArray(resolvers)) {\n            resolvers.forEach(function (resolverGroup) {\n                _this.resolvers = mergeDeep(_this.resolvers, resolverGroup);\n            });\n        }\n        else {\n            this.resolvers = mergeDeep(this.resolvers, resolvers);\n        }\n    };\n    LocalState.prototype.setResolvers = function (resolvers) {\n        this.resolvers = {};\n        this.addResolvers(resolvers);\n    };\n    LocalState.prototype.getResolvers = function () {\n        return this.resolvers || {};\n    };\n    // Run local client resolvers against the incoming query and remote data.\n    // Locally resolved field values are merged with the incoming remote data,\n    // and returned. Note that locally resolved fields will overwrite\n    // remote data using the same field name.\n    LocalState.prototype.runResolvers = function (_a) {\n        return __awaiter(this, arguments, void 0, function (_b) {\n            var document = _b.document, remoteResult = _b.remoteResult, context = _b.context, variables = _b.variables, _c = _b.onlyRunForcedResolvers, onlyRunForcedResolvers = _c === void 0 ? false : _c;\n            return __generator(this, function (_d) {\n                if (document) {\n                    return [2 /*return*/, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (__assign(__assign({}, remoteResult), { data: localResult.result })); })];\n                }\n                return [2 /*return*/, remoteResult];\n            });\n        });\n    };\n    LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {\n        this.fragmentMatcher = fragmentMatcher;\n    };\n    LocalState.prototype.getFragmentMatcher = function () {\n        return this.fragmentMatcher;\n    };\n    // Client queries contain everything in the incoming document (if a @client\n    // directive is found).\n    LocalState.prototype.clientQuery = function (document) {\n        if (hasDirectives([\"client\"], document)) {\n            if (this.resolvers) {\n                return document;\n            }\n        }\n        return null;\n    };\n    // Server queries are stripped of all @client based selection sets.\n    LocalState.prototype.serverQuery = function (document) {\n        return removeClientSetsFromDocument(document);\n    };\n    LocalState.prototype.prepareContext = function (context) {\n        var cache = this.cache;\n        return __assign(__assign({}, context), { cache: cache, \n            // Getting an entry's cache key is useful for local state resolvers.\n            getCacheKey: function (obj) {\n                return cache.identify(obj);\n            } });\n    };\n    // To support `@client @export(as: \"someVar\")` syntax, we'll first resolve\n    // @client @export fields locally, then pass the resolved values back to be\n    // used alongside the original operation variables.\n    LocalState.prototype.addExportedVariables = function (document_1) {\n        return __awaiter(this, arguments, void 0, function (document, variables, context) {\n            if (variables === void 0) { variables = {}; }\n            if (context === void 0) { context = {}; }\n            return __generator(this, function (_a) {\n                if (document) {\n                    return [2 /*return*/, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (__assign(__assign({}, variables), data.exportedVariables)); })];\n                }\n                return [2 /*return*/, __assign({}, variables)];\n            });\n        });\n    };\n    LocalState.prototype.shouldForceResolvers = function (document) {\n        var forceResolvers = false;\n        visit(document, {\n            Directive: {\n                enter: function (node) {\n                    if (node.name.value === \"client\" && node.arguments) {\n                        forceResolvers = node.arguments.some(function (arg) {\n                            return arg.name.value === \"always\" &&\n                                arg.value.kind === \"BooleanValue\" &&\n                                arg.value.value === true;\n                        });\n                        if (forceResolvers) {\n                            return BREAK;\n                        }\n                    }\n                },\n            },\n        });\n        return forceResolvers;\n    };\n    // Query the cache and return matching data.\n    LocalState.prototype.buildRootValueFromCache = function (document, variables) {\n        return this.cache.diff({\n            query: buildQueryFromSelectionSet(document),\n            variables: variables,\n            returnPartialData: true,\n            optimistic: false,\n        }).result;\n    };\n    LocalState.prototype.resolveDocument = function (document_1, rootValue_1) {\n        return __awaiter(this, arguments, void 0, function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {\n            var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;\n            if (context === void 0) { context = {}; }\n            if (variables === void 0) { variables = {}; }\n            if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }\n            if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }\n            return __generator(this, function (_b) {\n                mainDefinition = getMainDefinition(document);\n                fragments = getFragmentDefinitions(document);\n                fragmentMap = createFragmentMap(fragments);\n                selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);\n                definitionOperation = mainDefinition.operation;\n                defaultOperationType = definitionOperation ?\n                    definitionOperation.charAt(0).toUpperCase() +\n                        definitionOperation.slice(1)\n                    : \"Query\";\n                _a = this, cache = _a.cache, client = _a.client;\n                execContext = {\n                    fragmentMap: fragmentMap,\n                    context: __assign(__assign({}, context), { cache: cache, client: client }),\n                    variables: variables,\n                    fragmentMatcher: fragmentMatcher,\n                    defaultOperationType: defaultOperationType,\n                    exportedVariables: {},\n                    selectionsToResolve: selectionsToResolve,\n                    onlyRunForcedResolvers: onlyRunForcedResolvers,\n                };\n                isClientFieldDescendant = false;\n                return [2 /*return*/, this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({\n                        result: result,\n                        exportedVariables: execContext.exportedVariables,\n                    }); })];\n            });\n        });\n    };\n    LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {\n        return __awaiter(this, void 0, void 0, function () {\n            var fragmentMap, context, variables, resultsToMerge, execute;\n            var _this = this;\n            return __generator(this, function (_a) {\n                fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;\n                resultsToMerge = [rootValue];\n                execute = function (selection) { return __awaiter(_this, void 0, void 0, function () {\n                    var fragment, typeCondition;\n                    return __generator(this, function (_a) {\n                        if (!isClientFieldDescendant &&\n                            !execContext.selectionsToResolve.has(selection)) {\n                            // Skip selections without @client directives\n                            // (still processing if one of the ancestors or one of the child fields has @client directive)\n                            return [2 /*return*/];\n                        }\n                        if (!shouldInclude(selection, variables)) {\n                            // Skip this entirely.\n                            return [2 /*return*/];\n                        }\n                        if (isField(selection)) {\n                            return [2 /*return*/, this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {\n                                    var _a;\n                                    if (typeof fieldResult !== \"undefined\") {\n                                        resultsToMerge.push((_a = {},\n                                            _a[resultKeyNameFromField(selection)] = fieldResult,\n                                            _a));\n                                    }\n                                })];\n                        }\n                        if (isInlineFragment(selection)) {\n                            fragment = selection;\n                        }\n                        else {\n                            // This is a named fragment.\n                            fragment = fragmentMap[selection.name.value];\n                            invariant(fragment, 18, selection.name.value);\n                        }\n                        if (fragment && fragment.typeCondition) {\n                            typeCondition = fragment.typeCondition.name.value;\n                            if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {\n                                return [2 /*return*/, this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {\n                                        resultsToMerge.push(fragmentResult);\n                                    })];\n                            }\n                        }\n                        return [2 /*return*/];\n                    });\n                }); };\n                return [2 /*return*/, Promise.all(selectionSet.selections.map(execute)).then(function () {\n                        return mergeDeepArray(resultsToMerge);\n                    })];\n            });\n        });\n    };\n    LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {\n        return __awaiter(this, void 0, void 0, function () {\n            var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;\n            var _this = this;\n            return __generator(this, function (_a) {\n                if (!rootValue) {\n                    return [2 /*return*/, null];\n                }\n                variables = execContext.variables;\n                fieldName = field.name.value;\n                aliasedFieldName = resultKeyNameFromField(field);\n                aliasUsed = fieldName !== aliasedFieldName;\n                defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];\n                resultPromise = Promise.resolve(defaultResult);\n                // Usually all local resolvers are run when passing through here, but\n                // if we've specifically identified that we only want to run forced\n                // resolvers (that is, resolvers for fields marked with\n                // `@client(always: true)`), then we'll skip running non-forced resolvers.\n                if (!execContext.onlyRunForcedResolvers ||\n                    this.shouldForceResolvers(field)) {\n                    resolverType = rootValue.__typename || execContext.defaultOperationType;\n                    resolverMap = this.resolvers && this.resolvers[resolverType];\n                    if (resolverMap) {\n                        resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];\n                        if (resolve) {\n                            resultPromise = Promise.resolve(\n                            // In case the resolve function accesses reactive variables,\n                            // set cacheSlot to the current cache instance.\n                            cacheSlot.withValue(this.cache, resolve, [\n                                rootValue,\n                                argumentsObjectFromField(field, variables),\n                                execContext.context,\n                                { field: field, fragmentMap: execContext.fragmentMap },\n                            ]));\n                        }\n                    }\n                }\n                return [2 /*return*/, resultPromise.then(function (result) {\n                        var _a, _b;\n                        if (result === void 0) { result = defaultResult; }\n                        // If an @export directive is associated with the current field, store\n                        // the `as` export variable name and current result for later use.\n                        if (field.directives) {\n                            field.directives.forEach(function (directive) {\n                                if (directive.name.value === \"export\" && directive.arguments) {\n                                    directive.arguments.forEach(function (arg) {\n                                        if (arg.name.value === \"as\" && arg.value.kind === \"StringValue\") {\n                                            execContext.exportedVariables[arg.value.value] = result;\n                                        }\n                                    });\n                                }\n                            });\n                        }\n                        // Handle all scalar types here.\n                        if (!field.selectionSet) {\n                            return result;\n                        }\n                        // From here down, the field has a selection set, which means it's trying\n                        // to query a GraphQLObjectType.\n                        if (result == null) {\n                            // Basically any field in a GraphQL response can be null, or missing\n                            return result;\n                        }\n                        var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === \"client\"; })) !== null && _b !== void 0 ? _b : false;\n                        if (Array.isArray(result)) {\n                            return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);\n                        }\n                        // Returned value is an object, and the query has a sub-selection. Recurse.\n                        if (field.selectionSet) {\n                            return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);\n                        }\n                    })];\n            });\n        });\n    };\n    LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {\n        var _this = this;\n        return Promise.all(result.map(function (item) {\n            if (item === null) {\n                return null;\n            }\n            // This is a nested array, recurse.\n            if (Array.isArray(item)) {\n                return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);\n            }\n            // This is an object, run the selection set on it.\n            if (field.selectionSet) {\n                return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);\n            }\n        }));\n    };\n    // Collect selection nodes on paths from document root down to all @client directives.\n    // This function takes into account transitive fragment spreads.\n    // Complexity equals to a single `visit` over the full document.\n    LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {\n        var isSingleASTNode = function (node) { return !Array.isArray(node); };\n        var selectionsToResolveCache = this.selectionsToResolveCache;\n        function collectByDefinition(definitionNode) {\n            if (!selectionsToResolveCache.has(definitionNode)) {\n                var matches_1 = new Set();\n                selectionsToResolveCache.set(definitionNode, matches_1);\n                visit(definitionNode, {\n                    Directive: function (node, _, __, ___, ancestors) {\n                        if (node.name.value === \"client\") {\n                            ancestors.forEach(function (node) {\n                                if (isSingleASTNode(node) && isSelectionNode(node)) {\n                                    matches_1.add(node);\n                                }\n                            });\n                        }\n                    },\n                    FragmentSpread: function (spread, _, __, ___, ancestors) {\n                        var fragment = fragmentMap[spread.name.value];\n                        invariant(fragment, 19, spread.name.value);\n                        var fragmentSelections = collectByDefinition(fragment);\n                        if (fragmentSelections.size > 0) {\n                            // Fragment for this spread contains @client directive (either directly or transitively)\n                            // Collect selection nodes on paths from the root down to fields with the @client directive\n                            ancestors.forEach(function (node) {\n                                if (isSingleASTNode(node) && isSelectionNode(node)) {\n                                    matches_1.add(node);\n                                }\n                            });\n                            matches_1.add(spread);\n                            fragmentSelections.forEach(function (selection) {\n                                matches_1.add(selection);\n                            });\n                        }\n                    },\n                });\n            }\n            return selectionsToResolveCache.get(definitionNode);\n        }\n        return collectByDefinition(mainDefinition);\n    };\n    return LocalState;\n}());\nexport { LocalState };\n//# sourceMappingURL=LocalState.js.map","import { __assign } from \"tslib\";\nimport { invariant, newInvariantError } from \"../utilities/globals/index.js\";\nimport { ApolloLink, execute } from \"../link/core/index.js\";\nimport { version } from \"../version.js\";\nimport { HttpLink } from \"../link/http/index.js\";\nimport { QueryManager } from \"./QueryManager.js\";\nimport { LocalState } from \"./LocalState.js\";\nvar hasSuggestedDevtools = false;\n// Though mergeOptions now resides in @apollo/client/utilities, it was\n// previously declared and exported from this module, and then reexported from\n// @apollo/client/core. Since we need to preserve that API anyway, the easiest\n// solution is to reexport mergeOptions where it was previously declared (here).\nimport { mergeOptions } from \"../utilities/index.js\";\nimport { getApolloClientMemoryInternals } from \"../utilities/caching/getMemoryInternals.js\";\nexport { mergeOptions };\n/**\n * This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries\n * and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,\n * receive results from the server and cache the results in a store. It also delivers updates\n * to GraphQL queries through `Observable` instances.\n */\nvar ApolloClient = /** @class */ (function () {\n    /**\n     * Constructs an instance of `ApolloClient`.\n     *\n     * @example\n     * ```js\n     * import { ApolloClient, InMemoryCache } from '@apollo/client';\n     *\n     * const cache = new InMemoryCache();\n     *\n     * const client = new ApolloClient({\n     *   // Provide required constructor fields\n     *   cache: cache,\n     *   uri: 'http://localhost:4000/',\n     *\n     *   // Provide some optional constructor fields\n     *   name: 'react-web-client',\n     *   version: '1.3',\n     *   queryDeduplication: false,\n     *   defaultOptions: {\n     *     watchQuery: {\n     *       fetchPolicy: 'cache-and-network',\n     *     },\n     *   },\n     * });\n     * ```\n     */\n    function ApolloClient(options) {\n        var _this = this;\n        this.resetStoreCallbacks = [];\n        this.clearStoreCallbacks = [];\n        if (!options.cache) {\n            throw newInvariantError(15);\n        }\n        var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, documentTransform = options.documentTransform, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, \n        // Expose the client instance as window.__APOLLO_CLIENT__ and call\n        // onBroadcast in queryManager.broadcastQueries to enable browser\n        // devtools, but disable them by default in production.\n        connectToDevTools = options.connectToDevTools, _c = options.queryDeduplication, queryDeduplication = _c === void 0 ? true : _c, defaultOptions = options.defaultOptions, defaultContext = options.defaultContext, _d = options.assumeImmutableResults, assumeImmutableResults = _d === void 0 ? cache.assumeImmutableResults : _d, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version, devtools = options.devtools;\n        var link = options.link;\n        if (!link) {\n            link =\n                uri ? new HttpLink({ uri: uri, credentials: credentials, headers: headers }) : ApolloLink.empty();\n        }\n        this.link = link;\n        this.cache = cache;\n        this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;\n        this.queryDeduplication = queryDeduplication;\n        this.defaultOptions = defaultOptions || Object.create(null);\n        this.typeDefs = typeDefs;\n        this.devtoolsConfig = __assign(__assign({}, devtools), { enabled: (devtools === null || devtools === void 0 ? void 0 : devtools.enabled) || connectToDevTools });\n        if (this.devtoolsConfig.enabled === undefined) {\n            this.devtoolsConfig.enabled = globalThis.__DEV__ !== false;\n        }\n        if (ssrForceFetchDelay) {\n            setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);\n        }\n        this.watchQuery = this.watchQuery.bind(this);\n        this.query = this.query.bind(this);\n        this.mutate = this.mutate.bind(this);\n        this.watchFragment = this.watchFragment.bind(this);\n        this.resetStore = this.resetStore.bind(this);\n        this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);\n        this.version = version;\n        this.localState = new LocalState({\n            cache: cache,\n            client: this,\n            resolvers: resolvers,\n            fragmentMatcher: fragmentMatcher,\n        });\n        this.queryManager = new QueryManager({\n            cache: this.cache,\n            link: this.link,\n            defaultOptions: this.defaultOptions,\n            defaultContext: defaultContext,\n            documentTransform: documentTransform,\n            queryDeduplication: queryDeduplication,\n            ssrMode: ssrMode,\n            clientAwareness: {\n                name: clientAwarenessName,\n                version: clientAwarenessVersion,\n            },\n            localState: this.localState,\n            assumeImmutableResults: assumeImmutableResults,\n            onBroadcast: this.devtoolsConfig.enabled ?\n                function () {\n                    if (_this.devToolsHookCb) {\n                        _this.devToolsHookCb({\n                            action: {},\n                            state: {\n                                queries: _this.queryManager.getQueryStore(),\n                                mutations: _this.queryManager.mutationStore || {},\n                            },\n                            dataWithOptimisticResults: _this.cache.extract(true),\n                        });\n                    }\n                }\n                : void 0,\n        });\n        if (this.devtoolsConfig.enabled)\n            this.connectToDevTools();\n    }\n    ApolloClient.prototype.connectToDevTools = function () {\n        if (typeof window === \"undefined\") {\n            return;\n        }\n        var windowWithDevTools = window;\n        var devtoolsSymbol = Symbol.for(\"apollo.devtools\");\n        (windowWithDevTools[devtoolsSymbol] =\n            windowWithDevTools[devtoolsSymbol] || []).push(this);\n        windowWithDevTools.__APOLLO_CLIENT__ = this;\n        /**\n         * Suggest installing the devtools for developers who don't have them\n         */\n        if (!hasSuggestedDevtools && globalThis.__DEV__ !== false) {\n            hasSuggestedDevtools = true;\n            if (window.document &&\n                window.top === window.self &&\n                /^(https?|file):$/.test(window.location.protocol)) {\n                setTimeout(function () {\n                    if (!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {\n                        var nav = window.navigator;\n                        var ua = nav && nav.userAgent;\n                        var url = void 0;\n                        if (typeof ua === \"string\") {\n                            if (ua.indexOf(\"Chrome/\") > -1) {\n                                url =\n                                    \"https://chrome.google.com/webstore/detail/\" +\n                                        \"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm\";\n                            }\n                            else if (ua.indexOf(\"Firefox/\") > -1) {\n                                url =\n                                    \"https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/\";\n                            }\n                        }\n                        if (url) {\n                            globalThis.__DEV__ !== false && invariant.log(\"Download the Apollo DevTools for a better development \" +\n                                \"experience: %s\", url);\n                        }\n                    }\n                }, 10000);\n            }\n        }\n    };\n    Object.defineProperty(ApolloClient.prototype, \"documentTransform\", {\n        /**\n         * The `DocumentTransform` used to modify GraphQL documents before a request\n         * is made. If a custom `DocumentTransform` is not provided, this will be the\n         * default document transform.\n         */\n        get: function () {\n            return this.queryManager.documentTransform;\n        },\n        enumerable: false,\n        configurable: true\n    });\n    /**\n     * Call this method to terminate any active client processes, making it safe\n     * to dispose of this `ApolloClient` instance.\n     */\n    ApolloClient.prototype.stop = function () {\n        this.queryManager.stop();\n    };\n    /**\n     * This watches the cache store of the query according to the options specified and\n     * returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and\n     * receive updated results through an observer when the cache store changes.\n     *\n     * Note that this method is not an implementation of GraphQL subscriptions. Rather,\n     * it uses Apollo's store in order to reactively deliver updates to your query results.\n     *\n     * For example, suppose you call watchQuery on a GraphQL query that fetches a person's\n     * first and last name and this person has a particular object identifier, provided by\n     * dataIdFromObject. Later, a different query fetches that same person's\n     * first and last name and the first name has now changed. Then, any observers associated\n     * with the results of the first query will be updated with a new result object.\n     *\n     * Note that if the cache does not change, the subscriber will *not* be notified.\n     *\n     * See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for\n     * a description of store reactivity.\n     */\n    ApolloClient.prototype.watchQuery = function (options) {\n        if (this.defaultOptions.watchQuery) {\n            options = mergeOptions(this.defaultOptions.watchQuery, options);\n        }\n        // XXX Overwriting options is probably not the best way to do this long term...\n        if (this.disableNetworkFetches &&\n            (options.fetchPolicy === \"network-only\" ||\n                options.fetchPolicy === \"cache-and-network\")) {\n            options = __assign(__assign({}, options), { fetchPolicy: \"cache-first\" });\n        }\n        return this.queryManager.watchQuery(options);\n    };\n    /**\n     * This resolves a single query according to the options specified and\n     * returns a `Promise` which is either resolved with the resulting data\n     * or rejected with an error.\n     *\n     * @param options - An object of type `QueryOptions` that allows us to\n     * describe how this query should be treated e.g. whether it should hit the\n     * server at all or just resolve from the cache, etc.\n     */\n    ApolloClient.prototype.query = function (options) {\n        if (this.defaultOptions.query) {\n            options = mergeOptions(this.defaultOptions.query, options);\n        }\n        invariant(options.fetchPolicy !== \"cache-and-network\", 16);\n        if (this.disableNetworkFetches && options.fetchPolicy === \"network-only\") {\n            options = __assign(__assign({}, options), { fetchPolicy: \"cache-first\" });\n        }\n        return this.queryManager.query(options);\n    };\n    /**\n     * This resolves a single mutation according to the options specified and returns a\n     * Promise which is either resolved with the resulting data or rejected with an\n     * error. In some cases both `data` and `errors` might be undefined, for example\n     * when `errorPolicy` is set to `'ignore'`.\n     *\n     * It takes options as an object with the following keys and values:\n     */\n    ApolloClient.prototype.mutate = function (options) {\n        if (this.defaultOptions.mutate) {\n            options = mergeOptions(this.defaultOptions.mutate, options);\n        }\n        return this.queryManager.mutate(options);\n    };\n    /**\n     * This subscribes to a graphql subscription according to the options specified and returns an\n     * `Observable` which either emits received data or an error.\n     */\n    ApolloClient.prototype.subscribe = function (options) {\n        return this.queryManager.startGraphQLSubscription(options);\n    };\n    /**\n     * Tries to read some data from the store in the shape of the provided\n     * GraphQL query without making a network request. This method will start at\n     * the root query. To start at a specific id returned by `dataIdFromObject`\n     * use `readFragment`.\n     *\n     * @param optimistic - Set to `true` to allow `readQuery` to return\n     * optimistic results. Is `false` by default.\n     */\n    ApolloClient.prototype.readQuery = function (options, optimistic) {\n        if (optimistic === void 0) { optimistic = false; }\n        return this.cache.readQuery(options, optimistic);\n    };\n    /**\n     * Watches the cache store of the fragment according to the options specified\n     * and returns an `Observable`. We can subscribe to this\n     * `Observable` and receive updated results through an\n     * observer when the cache store changes.\n     *\n     * You must pass in a GraphQL document with a single fragment or a document\n     * with multiple fragments that represent what you are reading. If you pass\n     * in a document with multiple fragments then you must also specify a\n     * `fragmentName`.\n     *\n     * @since 3.10.0\n     * @param options - An object of type `WatchFragmentOptions` that allows\n     * the cache to identify the fragment and optionally specify whether to react\n     * to optimistic updates.\n     */\n    ApolloClient.prototype.watchFragment = function (options) {\n        return this.cache.watchFragment(options);\n    };\n    /**\n     * Tries to read some data from the store in the shape of the provided\n     * GraphQL fragment without making a network request. This method will read a\n     * GraphQL fragment from any arbitrary id that is currently cached, unlike\n     * `readQuery` which will only read from the root query.\n     *\n     * You must pass in a GraphQL document with a single fragment or a document\n     * with multiple fragments that represent what you are reading. If you pass\n     * in a document with multiple fragments then you must also specify a\n     * `fragmentName`.\n     *\n     * @param optimistic - Set to `true` to allow `readFragment` to return\n     * optimistic results. Is `false` by default.\n     */\n    ApolloClient.prototype.readFragment = function (options, optimistic) {\n        if (optimistic === void 0) { optimistic = false; }\n        return this.cache.readFragment(options, optimistic);\n    };\n    /**\n     * Writes some data in the shape of the provided GraphQL query directly to\n     * the store. This method will start at the root query. To start at a\n     * specific id returned by `dataIdFromObject` then use `writeFragment`.\n     */\n    ApolloClient.prototype.writeQuery = function (options) {\n        var ref = this.cache.writeQuery(options);\n        if (options.broadcast !== false) {\n            this.queryManager.broadcastQueries();\n        }\n        return ref;\n    };\n    /**\n     * Writes some data in the shape of the provided GraphQL fragment directly to\n     * the store. This method will write to a GraphQL fragment from any arbitrary\n     * id that is currently cached, unlike `writeQuery` which will only write\n     * from the root query.\n     *\n     * You must pass in a GraphQL document with a single fragment or a document\n     * with multiple fragments that represent what you are writing. If you pass\n     * in a document with multiple fragments then you must also specify a\n     * `fragmentName`.\n     */\n    ApolloClient.prototype.writeFragment = function (options) {\n        var ref = this.cache.writeFragment(options);\n        if (options.broadcast !== false) {\n            this.queryManager.broadcastQueries();\n        }\n        return ref;\n    };\n    ApolloClient.prototype.__actionHookForDevTools = function (cb) {\n        this.devToolsHookCb = cb;\n    };\n    ApolloClient.prototype.__requestRaw = function (payload) {\n        return execute(this.link, payload);\n    };\n    /**\n     * Resets your entire store by clearing out your cache and then re-executing\n     * all of your active queries. This makes it so that you may guarantee that\n     * there is no data left in your store from a time before you called this\n     * method.\n     *\n     * `resetStore()` is useful when your user just logged out. You’ve removed the\n     * user session, and you now want to make sure that any references to data you\n     * might have fetched while the user session was active is gone.\n     *\n     * It is important to remember that `resetStore()` *will* refetch any active\n     * queries. This means that any components that might be mounted will execute\n     * their queries again using your network interface. If you do not want to\n     * re-execute any queries then you should make sure to stop watching any\n     * active queries.\n     */\n    ApolloClient.prototype.resetStore = function () {\n        var _this = this;\n        return Promise.resolve()\n            .then(function () {\n            return _this.queryManager.clearStore({\n                discardWatches: false,\n            });\n        })\n            .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })\n            .then(function () { return _this.reFetchObservableQueries(); });\n    };\n    /**\n     * Remove all data from the store. Unlike `resetStore`, `clearStore` will\n     * not refetch any active queries.\n     */\n    ApolloClient.prototype.clearStore = function () {\n        var _this = this;\n        return Promise.resolve()\n            .then(function () {\n            return _this.queryManager.clearStore({\n                discardWatches: true,\n            });\n        })\n            .then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });\n    };\n    /**\n     * Allows callbacks to be registered that are executed when the store is\n     * reset. `onResetStore` returns an unsubscribe function that can be used\n     * to remove registered callbacks.\n     */\n    ApolloClient.prototype.onResetStore = function (cb) {\n        var _this = this;\n        this.resetStoreCallbacks.push(cb);\n        return function () {\n            _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });\n        };\n    };\n    /**\n     * Allows callbacks to be registered that are executed when the store is\n     * cleared. `onClearStore` returns an unsubscribe function that can be used\n     * to remove registered callbacks.\n     */\n    ApolloClient.prototype.onClearStore = function (cb) {\n        var _this = this;\n        this.clearStoreCallbacks.push(cb);\n        return function () {\n            _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });\n        };\n    };\n    /**\n     * Refetches all of your active queries.\n     *\n     * `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage\n     *\n     * It is important to remember that `reFetchObservableQueries()` *will* refetch any active\n     * queries. This means that any components that might be mounted will execute\n     * their queries again using your network interface. If you do not want to\n     * re-execute any queries then you should make sure to stop watching any\n     * active queries.\n     * Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.\n     */\n    ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {\n        return this.queryManager.reFetchObservableQueries(includeStandby);\n    };\n    /**\n     * Refetches specified active queries. Similar to \"reFetchObservableQueries()\" but with a specific list of queries.\n     *\n     * `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.\n     *\n     * It is important to remember that `refetchQueries()` *will* refetch specified active\n     * queries. This means that any components that might be mounted will execute\n     * their queries again using your network interface. If you do not want to\n     * re-execute any queries then you should make sure to stop watching any\n     * active queries.\n     */\n    ApolloClient.prototype.refetchQueries = function (options) {\n        var map = this.queryManager.refetchQueries(options);\n        var queries = [];\n        var results = [];\n        map.forEach(function (result, obsQuery) {\n            queries.push(obsQuery);\n            results.push(result);\n        });\n        var result = Promise.all(results);\n        // In case you need the raw results immediately, without awaiting\n        // Promise.all(results):\n        result.queries = queries;\n        result.results = results;\n        // If you decide to ignore the result Promise because you're using\n        // result.queries and result.results instead, you shouldn't have to worry\n        // about preventing uncaught rejections for the Promise.all result.\n        result.catch(function (error) {\n            globalThis.__DEV__ !== false && invariant.debug(17, error);\n        });\n        return result;\n    };\n    /**\n     * Get all currently active `ObservableQuery` objects, in a `Map` keyed by\n     * query ID strings.\n     *\n     * An \"active\" query is one that has observers and a `fetchPolicy` other than\n     * \"standby\" or \"cache-only\".\n     *\n     * You can include all `ObservableQuery` objects (including the inactive ones)\n     * by passing \"all\" instead of \"active\", or you can include just a subset of\n     * active queries by passing an array of query names or DocumentNode objects.\n     */\n    ApolloClient.prototype.getObservableQueries = function (include) {\n        if (include === void 0) { include = \"active\"; }\n        return this.queryManager.getObservableQueries(include);\n    };\n    /**\n     * Exposes the cache's complete state, in a serializable format for later restoration.\n     */\n    ApolloClient.prototype.extract = function (optimistic) {\n        return this.cache.extract(optimistic);\n    };\n    /**\n     * Replaces existing state in the cache (if any) with the values expressed by\n     * `serializedState`.\n     *\n     * Called when hydrating a cache (server side rendering, or offline storage),\n     * and also (potentially) during hot reloads.\n     */\n    ApolloClient.prototype.restore = function (serializedState) {\n        return this.cache.restore(serializedState);\n    };\n    /**\n     * Add additional local resolvers.\n     */\n    ApolloClient.prototype.addResolvers = function (resolvers) {\n        this.localState.addResolvers(resolvers);\n    };\n    /**\n     * Set (override existing) local resolvers.\n     */\n    ApolloClient.prototype.setResolvers = function (resolvers) {\n        this.localState.setResolvers(resolvers);\n    };\n    /**\n     * Get all registered local resolvers.\n     */\n    ApolloClient.prototype.getResolvers = function () {\n        return this.localState.getResolvers();\n    };\n    /**\n     * Set a custom local state fragment matcher.\n     */\n    ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {\n        this.localState.setFragmentMatcher(fragmentMatcher);\n    };\n    /**\n     * Define a new ApolloLink (or link chain) that Apollo Client will use.\n     */\n    ApolloClient.prototype.setLink = function (newLink) {\n        this.link = this.queryManager.link = newLink;\n    };\n    Object.defineProperty(ApolloClient.prototype, \"defaultContext\", {\n        get: function () {\n            return this.queryManager.defaultContext;\n        },\n        enumerable: false,\n        configurable: true\n    });\n    return ApolloClient;\n}());\nexport { ApolloClient };\nif (globalThis.__DEV__ !== false) {\n    ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;\n}\n//# sourceMappingURL=ApolloClient.js.map","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n    extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n    return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n    if (typeof b !== \"function\" && b !== null)\r\n        throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n    extendStatics(d, b);\r\n    function __() { this.constructor = d; }\r\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n    __assign = Object.assign || function __assign(t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    }\r\n    return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        t[p] = s[p];\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                t[p[i]] = s[p[i]];\r\n        }\r\n    return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n    return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n    if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n    return new (P || (P = Promise))(function (resolve, reject) {\r\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n    });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n    function verb(n) { return function (v) { return step([n, v]); }; }\r\n    function step(op) {\r\n        if (f) throw new TypeError(\"Generator is already executing.\");\r\n        while (_) try {\r\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n            if (y = 0, t) op = [op[0] & 2, t.value];\r\n            switch (op[0]) {\r\n                case 0: case 1: t = op; break;\r\n                case 4: _.label++; return { value: op[1], done: false };\r\n                case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                default:\r\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                    if (t[2]) _.ops.pop();\r\n                    _.trys.pop(); continue;\r\n            }\r\n            op = body.call(thisArg, _);\r\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n    }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n    var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n    if (m) return m.call(o);\r\n    if (o && typeof o.length === \"number\") return {\r\n        next: function () {\r\n            if (o && i >= o.length) o = void 0;\r\n            return { value: o && o[i++], done: !o };\r\n        }\r\n    };\r\n    throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n    if (!m) return o;\r\n    var i = m.call(o), r, ar = [], e;\r\n    try {\r\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n    }\r\n    catch (error) { e = { error: error }; }\r\n    finally {\r\n        try {\r\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n        }\r\n        finally { if (e) throw e.error; }\r\n    }\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n    for (var ar = [], i = 0; i < arguments.length; i++)\r\n        ar = ar.concat(__read(arguments[i]));\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n    for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n            r[k] = a[j];\r\n    return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n        if (ar || !(i in from)) {\r\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n            ar[i] = from[i];\r\n        }\r\n    }\r\n    return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n    return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n    return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n    function fulfill(value) { resume(\"next\", value); }\r\n    function reject(value) { resume(\"throw\", value); }\r\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n    var i, p;\r\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var m = o[Symbol.asyncIterator], i;\r\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n    if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n    return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n    o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n    if (mod && mod.__esModule) return mod;\r\n    var result = {};\r\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n    __setModuleDefault(result, mod);\r\n    return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n    return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","import { __assign } from \"tslib\";\nimport { parse } from 'graphql';\nvar docCache = new Map();\nvar fragmentSourceMap = new Map();\nvar printFragmentWarnings = true;\nvar experimentalFragmentVariables = false;\nfunction normalize(string) {\n    return string.replace(/[\\s,]+/g, ' ').trim();\n}\nfunction cacheKeyFromLoc(loc) {\n    return normalize(loc.source.body.substring(loc.start, loc.end));\n}\nfunction processFragments(ast) {\n    var seenKeys = new Set();\n    var definitions = [];\n    ast.definitions.forEach(function (fragmentDefinition) {\n        if (fragmentDefinition.kind === 'FragmentDefinition') {\n            var fragmentName = fragmentDefinition.name.value;\n            var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);\n            var sourceKeySet = fragmentSourceMap.get(fragmentName);\n            if (sourceKeySet && !sourceKeySet.has(sourceKey)) {\n                if (printFragmentWarnings) {\n                    console.warn(\"Warning: fragment with name \" + fragmentName + \" already exists.\\n\"\n                        + \"graphql-tag enforces all fragment names across your application to be unique; read more about\\n\"\n                        + \"this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names\");\n                }\n            }\n            else if (!sourceKeySet) {\n                fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);\n            }\n            sourceKeySet.add(sourceKey);\n            if (!seenKeys.has(sourceKey)) {\n                seenKeys.add(sourceKey);\n                definitions.push(fragmentDefinition);\n            }\n        }\n        else {\n            definitions.push(fragmentDefinition);\n        }\n    });\n    return __assign(__assign({}, ast), { definitions: definitions });\n}\nfunction stripLoc(doc) {\n    var workSet = new Set(doc.definitions);\n    workSet.forEach(function (node) {\n        if (node.loc)\n            delete node.loc;\n        Object.keys(node).forEach(function (key) {\n            var value = node[key];\n            if (value && typeof value === 'object') {\n                workSet.add(value);\n            }\n        });\n    });\n    var loc = doc.loc;\n    if (loc) {\n        delete loc.startToken;\n        delete loc.endToken;\n    }\n    return doc;\n}\nfunction parseDocument(source) {\n    var cacheKey = normalize(source);\n    if (!docCache.has(cacheKey)) {\n        var parsed = parse(source, {\n            experimentalFragmentVariables: experimentalFragmentVariables,\n            allowLegacyFragmentVariables: experimentalFragmentVariables\n        });\n        if (!parsed || parsed.kind !== 'Document') {\n            throw new Error('Not a valid GraphQL document.');\n        }\n        docCache.set(cacheKey, stripLoc(processFragments(parsed)));\n    }\n    return docCache.get(cacheKey);\n}\nexport function gql(literals) {\n    var args = [];\n    for (var _i = 1; _i < arguments.length; _i++) {\n        args[_i - 1] = arguments[_i];\n    }\n    if (typeof literals === 'string') {\n        literals = [literals];\n    }\n    var result = literals[0];\n    args.forEach(function (arg, i) {\n        if (arg && arg.kind === 'Document') {\n            result += arg.loc.source.body;\n        }\n        else {\n            result += arg;\n        }\n        result += literals[i + 1];\n    });\n    return parseDocument(result);\n}\nexport function resetCaches() {\n    docCache.clear();\n    fragmentSourceMap.clear();\n}\nexport function disableFragmentWarnings() {\n    printFragmentWarnings = false;\n}\nexport function enableExperimentalFragmentVariables() {\n    experimentalFragmentVariables = true;\n}\nexport function disableExperimentalFragmentVariables() {\n    experimentalFragmentVariables = false;\n}\nvar extras = {\n    gql: gql,\n    resetCaches: resetCaches,\n    disableFragmentWarnings: disableFragmentWarnings,\n    enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,\n    disableExperimentalFragmentVariables: disableExperimentalFragmentVariables\n};\n(function (gql_1) {\n    gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;\n})(gql || (gql = {}));\ngql[\"default\"] = gql;\nexport default gql;\n//# sourceMappingURL=index.js.map","import { __awaiter, __extends, __generator } from \"tslib\";\nimport { ApolloLink } from \"../core/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nimport { buildDelayFunction } from \"./delayFunction.js\";\nimport { buildRetryFunction } from \"./retryFunction.js\";\n/**\n * Tracking and management of operations that may be (or currently are) retried.\n */\nvar RetryableOperation = /** @class */ (function () {\n    function RetryableOperation(observer, operation, forward, delayFor, retryIf) {\n        var _this = this;\n        this.observer = observer;\n        this.operation = operation;\n        this.forward = forward;\n        this.delayFor = delayFor;\n        this.retryIf = retryIf;\n        this.retryCount = 0;\n        this.currentSubscription = null;\n        this.onError = function (error) { return __awaiter(_this, void 0, void 0, function () {\n            var shouldRetry;\n            return __generator(this, function (_a) {\n                switch (_a.label) {\n                    case 0:\n                        this.retryCount += 1;\n                        return [4 /*yield*/, this.retryIf(this.retryCount, this.operation, error)];\n                    case 1:\n                        shouldRetry = _a.sent();\n                        if (shouldRetry) {\n                            this.scheduleRetry(this.delayFor(this.retryCount, this.operation, error));\n                            return [2 /*return*/];\n                        }\n                        this.observer.error(error);\n                        return [2 /*return*/];\n                }\n            });\n        }); };\n        this.try();\n    }\n    /**\n     * Stop retrying for the operation, and cancel any in-progress requests.\n     */\n    RetryableOperation.prototype.cancel = function () {\n        if (this.currentSubscription) {\n            this.currentSubscription.unsubscribe();\n        }\n        clearTimeout(this.timerId);\n        this.timerId = undefined;\n        this.currentSubscription = null;\n    };\n    RetryableOperation.prototype.try = function () {\n        this.currentSubscription = this.forward(this.operation).subscribe({\n            next: this.observer.next.bind(this.observer),\n            error: this.onError,\n            complete: this.observer.complete.bind(this.observer),\n        });\n    };\n    RetryableOperation.prototype.scheduleRetry = function (delay) {\n        var _this = this;\n        if (this.timerId) {\n            throw new Error(\"RetryLink BUG! Encountered overlapping retries\");\n        }\n        this.timerId = setTimeout(function () {\n            _this.timerId = undefined;\n            _this.try();\n        }, delay);\n    };\n    return RetryableOperation;\n}());\nvar RetryLink = /** @class */ (function (_super) {\n    __extends(RetryLink, _super);\n    function RetryLink(options) {\n        var _this = _super.call(this) || this;\n        var _a = options || {}, attempts = _a.attempts, delay = _a.delay;\n        _this.delayFor =\n            typeof delay === \"function\" ? delay : buildDelayFunction(delay);\n        _this.retryIf =\n            typeof attempts === \"function\" ? attempts : buildRetryFunction(attempts);\n        return _this;\n    }\n    RetryLink.prototype.request = function (operation, nextLink) {\n        var _this = this;\n        return new Observable(function (observer) {\n            var retryable = new RetryableOperation(observer, operation, nextLink, _this.delayFor, _this.retryIf);\n            return function () {\n                retryable.cancel();\n            };\n        });\n    };\n    return RetryLink;\n}(ApolloLink));\nexport { RetryLink };\n//# sourceMappingURL=retryLink.js.map","export function buildDelayFunction(delayOptions) {\n    var _a = delayOptions || {}, _b = _a.initial, initial = _b === void 0 ? 300 : _b, _c = _a.jitter, jitter = _c === void 0 ? true : _c, _d = _a.max, max = _d === void 0 ? Infinity : _d;\n    // If we're jittering, baseDelay is half of the maximum delay for that\n    // attempt (and is, on average, the delay we will encounter).\n    // If we're not jittering, adjust baseDelay so that the first attempt\n    // lines up with initialDelay, for everyone's sanity.\n    var baseDelay = jitter ? initial : initial / 2;\n    return function delayFunction(count) {\n        var delay = Math.min(max, baseDelay * Math.pow(2, count));\n        if (jitter) {\n            // We opt for a full jitter approach for a mostly uniform distribution,\n            // but bound it within initialDelay and delay for everyone's sanity.\n            delay = Math.random() * delay;\n        }\n        return delay;\n    };\n}\n//# sourceMappingURL=delayFunction.js.map","export function buildRetryFunction(retryOptions) {\n    var _a = retryOptions || {}, retryIf = _a.retryIf, _b = _a.max, max = _b === void 0 ? 5 : _b;\n    return function retryFunction(count, operation, error) {\n        if (count >= max)\n            return false;\n        return retryIf ? retryIf(error, operation) : !!error;\n    };\n}\n//# sourceMappingURL=retryFunction.js.map","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { AdobeAssetOrderField } from '../../assets/AdobeAssetOrder';\nimport type { Asset, AssetContainer, OrderByField, Query } from '../generated/types';\n\nexport type AssetListConnectionArgs  = {\n    first: number,\n    after?: string,\n    filter?: {\n        dc_format?: Array<string>\n    }\n    orderBy?: {\n        direction?: 'ASCENDING' | 'DESCENDING',\n        field: 'NAME' | 'CREATE_DATE' | 'MODIFY_DATE'\n    }\n}\n\nconst compositeAndFileFields = [\n    'repo_size',\n    'repo_version',\n    {\n        'renditionLink': [ 'href', 'templated' ]\n    },\n    {\n        'blockDownloadLink': [ 'href', 'templated' ]\n    },\n    {\n        'blockUploadLink': [ 'href', 'templated' ]\n    },\n] as const;\n\nconst fileFields = [\n    ...compositeAndFileFields,\n    'tiff_imageLength',\n    'tiff_imageWidth'\n] as const;\n\nconst directoryFields = [\n    {\n        'pageLink': [ 'href', 'templated' ]\n    },\n    {\n        'blockUploadLink': [ 'href', 'templated' ]\n    }\n] as const;\n\nexport const GQLSpecialFolderFields = [\n    'dc_format',\n    'repo_ancestors',\n    'repo_assetClass',\n    'repo_assetType',\n    'repo_assetSubType',\n    'repo_assetId',\n    'repo_createDate',\n    {\n        'repo_createdBy': [ 'id' ]\n    },\n    'repo_modifiedBy',\n    'repo_modifyDate',\n    'repo_name',\n    'repo_path',\n    'repo_state',\n    {\n        'storage_assignee': [ 'id', 'type' ]\n    },\n    'storage_deviceCreateDate',\n    'storage_deviceModifyDate',\n    'storage_region',\n    {\n        'repository': [\n            'repo_repositoryId',\n            {\n                'repo_owner': [ 'id', 'type' ]\n            },\n            'repo_repositoryType'\n        ]\n    },\n    {\n        'primaryLink': [ 'href', 'templated' ]\n    },\n    {\n        operation: 'Directory',\n        fields: directoryFields,\n        fragment: true\n    }\n] as const;\n\nconst baseAssetFields = [\n    {\n        'appMetadata': [ 'am: valueOf(key: \"\")' ]\n    },\n    'dc_format',\n    {\n        'labels': [ 'lastAccessDate', { favorite: [ 'isFavorite' ] } ]\n    },\n    {\n        'effectivePermissions': [ 'default', 'primary', 'applicationMetadata', 'aclPolicy', 'directory', 'annotations' ]\n    },\n    'repo_ancestors',\n    'repo_assetClass',\n    'repo_assetType',\n    'repo_assetSubType',\n    'primary_etag',\n    'repo_assetId',\n    'repo_createDate',\n    {\n        'repo_createdBy': [ 'id' ]\n    },\n    'repo_modifiedBy',\n    'repo_modifyDate',\n    'repo_name',\n    'repo_path',\n    'repo_state',\n    {\n        'storage_assignee': [ 'id', 'type' ]\n    },\n    'storage_deviceCreateDate',\n    'storage_deviceModifyDate',\n    'storage_region',\n    {\n        'repository': [\n            'repo_repositoryId',\n            {\n                'repo_owner': [ 'id', 'type' ]\n            },\n            'repo_repositoryType'\n        ]\n    },\n    {\n        'primaryLink': [ 'href', 'templated' ]\n    },\n] as const;\n\nexport const GQLResolveAssetFields = [\n    ...baseAssetFields,\n    {\n        operation: 'Composite',\n        fields: compositeAndFileFields,\n        fragment: true\n    },\n    {\n        operation: 'File',\n        fields: fileFields,\n        fragment: true\n    },\n    {\n        operation: 'Directory',\n        fields: directoryFields,\n        fragment: true\n    }\n] as const;\n\nexport type IdQuery = {\n    resolveAssetById: Query['resolveAssetById'] & AssetContainer\n}\n\nexport type PathQuery = {\n    resolveAssetByPath: Query['resolveAssetByPath']\n}\nexport type RelativePathQuery = {\n    resolveUserHome: Asset & {\n        assetByRelativePath: Query['resolveAssetByRelativePath']\n    }\n};\n\nexport enum Privelege {\n    READ = 'READ',\n    WRITE = 'WRITE',\n    ACK = 'ACK',\n    DELETE = 'DELETE'\n}\n\nexport type GQLEffectivePermissions = {\n    // \"Represents *\"\n    default: Privelege[];\n\n    // Other rel types\n    primary?: Privelege[];\n    applicationMetadata?: Privelege[];\n    aclPolicy?: Privelege[];\n    directory?: Privelege[];\n    annotations?: Privelege[];\n}\n\nexport type PageInfo = { hasNextPage: boolean, endCursor?: string };\n\nexport const OrderFieldToGQLOrderBy: { [key in AdobeAssetOrderField]: OrderByField } = {\n    'name': 'NAME',\n    'created': 'CREATE_DATE',\n    'modified': 'MODIFY_DATE',\n    // GQL doesn't sort on share date\n    'shared': 'MODIFY_DATE'\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar OperationType;\n(function (OperationType) {\n    OperationType[\"Mutation\"] = \"mutation\";\n    OperationType[\"Query\"] = \"query\";\n    OperationType[\"Subscription\"] = \"subscription\";\n})(OperationType || (OperationType = {}));\nexports.default = OperationType;\n//# sourceMappingURL=OperationType.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isNestedField = void 0;\nfunction isNestedField(object) {\n    return ((typeof object === \"object\" &&\n        object.hasOwnProperty(\"operation\") &&\n        object.hasOwnProperty(\"variables\") &&\n        object.hasOwnProperty(\"fields\")) ||\n        (typeof object === \"object\" &&\n            object.hasOwnProperty(\"operation\") &&\n            object.hasOwnProperty(\"fragment\") &&\n            object.hasOwnProperty(\"fields\")));\n}\nexports.isNestedField = isNestedField;\n//# sourceMappingURL=NestedField.js.map","\"use strict\";\nvar __assign = (this && this.__assign) || function () {\n    __assign = Object.assign || function(t) {\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\n            s = arguments[i];\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n                t[p] = s[p];\n        }\n        return t;\n    };\n    return __assign.apply(this, arguments);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar NestedField_1 = require(\"./NestedField\");\nvar Utils = /** @class */ (function () {\n    function Utils() {\n    }\n    Utils.resolveVariables = function (operations) {\n        var ret = {};\n        for (var _i = 0, operations_1 = operations; _i < operations_1.length; _i++) {\n            var _a = operations_1[_i], variables = _a.variables, fields = _a.fields;\n            ret = __assign(__assign(__assign({}, ret), variables), ((fields && Utils.getNestedVariables(fields)) || {}));\n        }\n        return ret;\n    };\n    // Convert object to name and argument map. eg: (id: $id)\n    Utils.queryDataNameAndArgumentMap = function (variables) {\n        return variables && Object.keys(variables).length\n            ? \"(\".concat(Object.entries(variables).reduce(function (dataString, _a, i) {\n                var key = _a[0], value = _a[1];\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\").concat(value && value.name ? value.name : key, \": $\").concat(key);\n            }, \"\"), \")\")\n            : \"\";\n    };\n    Utils.queryFieldsMap = function (fields) {\n        var _this = this;\n        return fields\n            ? fields\n                .map(function (field) {\n                if ((0, NestedField_1.isNestedField)(field)) {\n                    return Utils.queryNestedFieldMap(field);\n                }\n                else if (typeof field === \"object\") {\n                    var result_1 = \"\";\n                    Object.entries(field).forEach(function (_a, index, array) {\n                        var key = _a[0], values = _a[1];\n                        result_1 += \"\".concat(key, \" \").concat(values.length > 0\n                            ? \"{ \" + _this.queryFieldsMap(values) + \" }\"\n                            : \"\");\n                        // If it's not the last item in array, join with comma\n                        if (index < array.length - 1) {\n                            result_1 += \", \";\n                        }\n                    });\n                    return result_1;\n                }\n                else {\n                    return \"\".concat(field);\n                }\n            })\n                .join(\", \")\n            : \"\";\n    };\n    Utils.operationOrAlias = function (operation) {\n        return typeof operation === \"string\"\n            ? operation\n            : \"\".concat(operation.alias, \": \").concat(operation.name);\n    };\n    Utils.isFragment = function (field) {\n        var _a;\n        return (_a = (field === null || field === void 0 ? void 0 : field.fragment) === true) !== null && _a !== void 0 ? _a : false;\n    };\n    Utils.operationOrFragment = function (field) {\n        return Utils.isFragment(field)\n            ? field.operation\n            : Utils.operationOrAlias(field.operation);\n    };\n    Utils.getFragment = function (field) {\n        return Utils.isFragment(field) ? \"... on \" : \"\";\n    };\n    Utils.queryNestedFieldMap = function (field) {\n        return \"\".concat(Utils.getFragment(field)).concat(Utils.operationOrFragment(field), \" \").concat(this.isFragment(field)\n            ? \"\"\n            : this.queryDataNameAndArgumentMap(field.variables), \" \").concat(field.fields.length > 0\n            ? \"{ \" + this.queryFieldsMap(field.fields) + \" }\"\n            : \"\");\n    };\n    // Variables map. eg: { \"id\": 1, \"name\": \"Jon Doe\" }\n    Utils.queryVariablesMap = function (variables, fields) {\n        var variablesMapped = {};\n        var update = function (vars) {\n            if (vars) {\n                Object.keys(vars).map(function (key) {\n                    variablesMapped[key] =\n                        typeof vars[key] === \"object\" ? vars[key].value : vars[key];\n                });\n            }\n        };\n        update(variables);\n        if (fields && typeof fields === \"object\") {\n            update(Utils.getNestedVariables(fields));\n        }\n        return variablesMapped;\n    };\n    Utils.getNestedVariables = function (fields) {\n        var variables = {};\n        function getDeepestVariables(innerFields) {\n            innerFields === null || innerFields === void 0 ? void 0 : innerFields.forEach(function (field) {\n                if ((0, NestedField_1.isNestedField)(field)) {\n                    variables = __assign(__assign(__assign({}, field.variables), variables), (field.fields && getDeepestVariables(field.fields)));\n                }\n                else {\n                    if (typeof field === \"object\") {\n                        for (var _i = 0, _a = Object.entries(field); _i < _a.length; _i++) {\n                            var _b = _a[_i], value = _b[1];\n                            getDeepestVariables(value);\n                        }\n                    }\n                }\n            });\n            return variables;\n        }\n        getDeepestVariables(fields);\n        return variables;\n    };\n    Utils.queryDataType = function (variable) {\n        var type = \"String\";\n        var value = typeof variable === \"object\" ? variable.value : variable;\n        if ((variable === null || variable === void 0 ? void 0 : variable.type) != null) {\n            type = variable.type;\n        }\n        else {\n            // TODO: Should handle the undefined value (either in array value or single value)\n            var candidateValue = Array.isArray(value) ? value[0] : value;\n            switch (typeof candidateValue) {\n                case \"object\":\n                    type = \"Object\";\n                    break;\n                case \"boolean\":\n                    type = \"Boolean\";\n                    break;\n                case \"number\":\n                    type = candidateValue % 1 === 0 ? \"Int\" : \"Float\";\n                    break;\n            }\n        }\n        // set object based variable properties\n        if (typeof variable === \"object\") {\n            if (variable.list === true) {\n                type = \"[\".concat(type, \"]\");\n            }\n            else if (Array.isArray(variable.list)) {\n                type = \"[\".concat(type).concat(variable.list[0] ? \"!\" : \"\", \"]\");\n            }\n            if (variable.required) {\n                type += \"!\";\n            }\n        }\n        return type;\n    };\n    return Utils;\n}());\nexports.default = Utils;\n//# sourceMappingURL=Utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar OperationType_1 = require(\"../OperationType\");\nvar Utils_1 = require(\"../Utils\");\nvar DefaultAppSyncMutationAdapter = /** @class */ (function () {\n    function DefaultAppSyncMutationAdapter(options) {\n        if (Array.isArray(options)) {\n            this.variables = Utils_1.default.resolveVariables(options);\n        }\n        else {\n            this.variables = options.variables;\n            this.fields = options.fields;\n            this.operation = options.operation;\n        }\n    }\n    DefaultAppSyncMutationAdapter.prototype.mutationBuilder = function () {\n        return this.operationWrapperTemplate(this.variables, this.operationTemplate(this.operation));\n    };\n    DefaultAppSyncMutationAdapter.prototype.mutationsBuilder = function (mutations) {\n        var _this = this;\n        var content = mutations.map(function (opts) {\n            _this.operation = opts.operation;\n            _this.variables = opts.variables;\n            _this.fields = opts.fields;\n            return _this.operationTemplate(opts.operation);\n        });\n        return this.operationWrapperTemplate(Utils_1.default.resolveVariables(mutations), content.join(\"\\n  \"));\n    };\n    // Convert object to name and argument map. eg: (id: $id)\n    DefaultAppSyncMutationAdapter.prototype.queryDataNameAndArgumentMap = function () {\n        return this.variables && Object.keys(this.variables).length\n            ? \"(\".concat(Object.keys(this.variables).reduce(function (dataString, key, i) {\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\").concat(key, \": $\").concat(key);\n            }, \"\"), \")\")\n            : \"\";\n    };\n    DefaultAppSyncMutationAdapter.prototype.queryDataArgumentAndTypeMap = function (variables) {\n        return Object.keys(variables).length\n            ? \"(\".concat(Object.keys(variables).reduce(function (dataString, key, i) {\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\", \"$\").concat(key, \": \").concat(Utils_1.default.queryDataType(variables[key]));\n            }, \"\"), \")\")\n            : \"\";\n    };\n    // start of mutation building\n    DefaultAppSyncMutationAdapter.prototype.operationWrapperTemplate = function (variables, content) {\n        var operation = typeof this.operation === \"string\" ? this.operation : this.operation.name;\n        return {\n            query: \"\".concat(OperationType_1.default.Mutation, \" \").concat(operation.charAt(0).toUpperCase() + operation.slice(1), \" \").concat(this.queryDataArgumentAndTypeMap(variables), \" {\\n  \").concat(content, \"\\n}\"),\n            variables: Utils_1.default.queryVariablesMap(variables),\n        };\n    };\n    DefaultAppSyncMutationAdapter.prototype.operationTemplate = function (operation) {\n        var operationName = typeof operation === \"string\"\n            ? operation\n            : \"\".concat(operation.alias, \": \").concat(operation.name);\n        return \"\".concat(operationName, \" \").concat(this.queryDataNameAndArgumentMap(), \" {\\n    \").concat(this.queryFieldsMap(this.fields), \"\\n  }\");\n    };\n    // Fields selection map. eg: { id, name }\n    DefaultAppSyncMutationAdapter.prototype.queryFieldsMap = function (fields) {\n        var _this = this;\n        return Array.isArray(fields)\n            ? fields\n                .map(function (field) {\n                return typeof field === \"object\"\n                    ? \"\".concat(Object.keys(field)[0], \" { \").concat(_this.queryFieldsMap(Object.values(field)[0]), \" }\")\n                    : \"\".concat(field);\n            })\n                .join(\", \")\n            : \"\";\n    };\n    return DefaultAppSyncMutationAdapter;\n}());\nexports.default = DefaultAppSyncMutationAdapter;\n//# sourceMappingURL=DefaultAppSyncMutationAdapter.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar OperationType_1 = require(\"../OperationType\");\nvar Utils_1 = require(\"../Utils\");\nvar DefaultAppSyncQueryAdapter = /** @class */ (function () {\n    function DefaultAppSyncQueryAdapter(options) {\n        this.queryDataType = function (variable) {\n            var type = \"String\";\n            var value = typeof variable === \"object\" ? variable.value : variable;\n            if (variable.type !== undefined) {\n                type = variable.type;\n            }\n            else {\n                switch (typeof value) {\n                    case \"object\":\n                        type = \"Object\";\n                        break;\n                    case \"boolean\":\n                        type = \"Boolean\";\n                        break;\n                    case \"number\":\n                        type = value % 1 === 0 ? \"Int\" : \"Float\";\n                        break;\n                }\n            }\n            if (typeof variable === \"object\" && variable.required) {\n                type += \"!\";\n            }\n            return type;\n        };\n        if (Array.isArray(options)) {\n            this.variables = Utils_1.default.resolveVariables(options);\n        }\n        else {\n            this.variables = options.variables;\n            this.fields = options.fields || [];\n            this.operation = options.operation;\n        }\n    }\n    // kicks off building for a single query\n    DefaultAppSyncQueryAdapter.prototype.queryBuilder = function () {\n        return this.operationWrapperTemplate(this.operationTemplate());\n    };\n    // if we have an array of options, call this\n    DefaultAppSyncQueryAdapter.prototype.queriesBuilder = function (queries) {\n        var _this = this;\n        var content = function () {\n            var tmpl = [];\n            queries.forEach(function (query) {\n                if (query) {\n                    _this.operation = query.operation;\n                    _this.fields = query.fields;\n                    _this.variables = query.variables;\n                    tmpl.push(_this.operationTemplate());\n                }\n            });\n            return tmpl.join(\" \");\n        };\n        return this.operationWrapperTemplate(content());\n    };\n    // Convert object to name and argument map. eg: (id: $id)\n    DefaultAppSyncQueryAdapter.prototype.queryDataNameAndArgumentMap = function () {\n        return this.variables && Object.keys(this.variables).length\n            ? \"(\".concat(Object.keys(this.variables).reduce(function (dataString, key, i) {\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\").concat(key, \": $\").concat(key);\n            }, \"\"), \")\")\n            : \"\";\n    };\n    // Convert object to argument and type map. eg: ($id: Int)\n    DefaultAppSyncQueryAdapter.prototype.queryDataArgumentAndTypeMap = function () {\n        var _this = this;\n        return this.variables && Object.keys(this.variables).length\n            ? \"(\".concat(Object.keys(this.variables).reduce(function (dataString, key, i) {\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\", \"$\").concat(key, \": \").concat(_this.queryDataType(_this.variables[key]));\n            }, \"\"), \")\")\n            : \"\";\n    };\n    DefaultAppSyncQueryAdapter.prototype.operationWrapperTemplate = function (content) {\n        var operation = typeof this.operation === \"string\" ? this.operation : this.operation.name;\n        return {\n            query: \"\".concat(OperationType_1.default.Query, \" \").concat(operation\n                .charAt(0)\n                .toUpperCase()).concat(operation.slice(1), \" \").concat(this.queryDataArgumentAndTypeMap(), \" { \").concat(content, \" }\"),\n            variables: Utils_1.default.queryVariablesMap(this.variables),\n        };\n    };\n    // query\n    DefaultAppSyncQueryAdapter.prototype.operationTemplate = function () {\n        var operation = typeof this.operation === \"string\"\n            ? this.operation\n            : \"\".concat(this.operation.alias, \": \").concat(this.operation.name);\n        return \"\".concat(operation, \" \").concat(this.queryDataNameAndArgumentMap(), \" { nodes { \").concat(Utils_1.default.queryFieldsMap(this.fields), \" } }\");\n    };\n    return DefaultAppSyncQueryAdapter;\n}());\nexports.default = DefaultAppSyncQueryAdapter;\n//# sourceMappingURL=DefaultAppSyncQueryAdapter.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DefaultAppSyncMutationAdapter_1 = require(\"./DefaultAppSyncMutationAdapter\");\nvar DefaultAppSyncQueryAdapter_1 = require(\"./DefaultAppSyncQueryAdapter\");\nexports.default = { DefaultAppSyncQueryAdapter: DefaultAppSyncQueryAdapter_1.default, DefaultAppSyncMutationAdapter: DefaultAppSyncMutationAdapter_1.default };\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __assign = (this && this.__assign) || function () {\n    __assign = Object.assign || function(t) {\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\n            s = arguments[i];\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n                t[p] = s[p];\n        }\n        return t;\n    };\n    return __assign.apply(this, arguments);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar OperationType_1 = require(\"../OperationType\");\nvar Utils_1 = require(\"../Utils\");\nvar DefaultMutationAdapter = /** @class */ (function () {\n    function DefaultMutationAdapter(options, configuration) {\n        var _this = this;\n        if (Array.isArray(options)) {\n            this.variables = Utils_1.default.resolveVariables(options);\n        }\n        else {\n            this.variables = options.variables;\n            this.fields = options.fields;\n            this.operation = options.operation;\n        }\n        // Default configs\n        this.config = {\n            operationName: \"\",\n        };\n        if (configuration) {\n            Object.entries(configuration).forEach(function (_a) {\n                var key = _a[0], value = _a[1];\n                _this.config[key] = value;\n            });\n        }\n    }\n    DefaultMutationAdapter.prototype.mutationBuilder = function () {\n        return this.operationWrapperTemplate(OperationType_1.default.Mutation, this.variables, this.operationTemplate(this.operation));\n    };\n    DefaultMutationAdapter.prototype.mutationsBuilder = function (mutations) {\n        var _this = this;\n        var content = mutations.map(function (opts) {\n            _this.operation = opts.operation;\n            _this.variables = opts.variables;\n            _this.fields = opts.fields;\n            return _this.operationTemplate(opts.operation);\n        });\n        return this.operationWrapperTemplate(OperationType_1.default.Mutation, Utils_1.default.resolveVariables(mutations), content.join(\"\\n  \"));\n    };\n    DefaultMutationAdapter.prototype.queryDataArgumentAndTypeMap = function (variablesUsed) {\n        if (this.fields && typeof this.fields === \"object\") {\n            variablesUsed = __assign(__assign({}, Utils_1.default.getNestedVariables(this.fields)), variablesUsed);\n        }\n        return variablesUsed && Object.keys(variablesUsed).length > 0\n            ? \"(\".concat(Object.keys(variablesUsed).reduce(function (dataString, key, i) {\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\", \"$\").concat(key, \": \").concat(Utils_1.default.queryDataType(variablesUsed[key]));\n            }, \"\"), \")\")\n            : \"\";\n    };\n    // start of mutation building\n    DefaultMutationAdapter.prototype.operationWrapperTemplate = function (type, variables, content) {\n        var query = \"\".concat(type, \" \").concat(this.queryDataArgumentAndTypeMap(variables), \" {\\n      \").concat(content, \"\\n    }\");\n        if (this.config.operationName) {\n            query = query.replace(\"mutation\", \"mutation \".concat(this.config.operationName));\n        }\n        return {\n            query: query,\n            variables: Utils_1.default.queryVariablesMap(variables, this.fields),\n        };\n    };\n    DefaultMutationAdapter.prototype.operationTemplate = function (operation) {\n        var operationName = typeof operation === \"string\"\n            ? operation\n            : \"\".concat(operation.alias, \": \").concat(operation.name);\n        return \"\".concat(operationName, \" \").concat(Utils_1.default.queryDataNameAndArgumentMap(this.variables), \" \").concat(this.fields && this.fields.length > 0\n            ? \"{\\n    \".concat(Utils_1.default.queryFieldsMap(this.fields), \"\\n  }\")\n            : \"\");\n    };\n    return DefaultMutationAdapter;\n}());\nexports.default = DefaultMutationAdapter;\n//# sourceMappingURL=DefaultMutationAdapter.js.map","\"use strict\";\nvar __assign = (this && this.__assign) || function () {\n    __assign = Object.assign || function(t) {\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\n            s = arguments[i];\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n                t[p] = s[p];\n        }\n        return t;\n    };\n    return __assign.apply(this, arguments);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar OperationType_1 = require(\"../OperationType\");\nvar Utils_1 = require(\"../Utils\");\nvar DefaultQueryAdapter = /** @class */ (function () {\n    function DefaultQueryAdapter(options, configuration) {\n        var _this = this;\n        // Default configs\n        this.config = {\n            operationName: \"\",\n        };\n        if (configuration) {\n            Object.entries(configuration).forEach(function (_a) {\n                var key = _a[0], value = _a[1];\n                _this.config[key] = value;\n            });\n        }\n        if (Array.isArray(options)) {\n            this.variables = Utils_1.default.resolveVariables(options);\n        }\n        else {\n            this.variables = options.variables;\n            this.fields = options.fields || [];\n            this.operation = options.operation;\n        }\n    }\n    // kicks off building for a single query\n    DefaultQueryAdapter.prototype.queryBuilder = function () {\n        return this.operationWrapperTemplate(this.operationTemplate(this.variables));\n    };\n    // if we have an array of options, call this\n    DefaultQueryAdapter.prototype.queriesBuilder = function (queries) {\n        var _this = this;\n        var content = function () {\n            var tmpl = [];\n            queries.forEach(function (query) {\n                if (query) {\n                    _this.operation = query.operation;\n                    _this.fields = query.fields;\n                    tmpl.push(_this.operationTemplate(query.variables));\n                }\n            });\n            return tmpl.join(\" \");\n        };\n        return this.operationWrapperTemplate(content());\n    };\n    // Convert object to argument and type map. eg: ($id: Int)\n    DefaultQueryAdapter.prototype.queryDataArgumentAndTypeMap = function () {\n        var variablesUsed = this.variables;\n        if (this.fields && typeof this.fields === \"object\") {\n            variablesUsed = __assign(__assign({}, Utils_1.default.getNestedVariables(this.fields)), variablesUsed);\n        }\n        return variablesUsed && Object.keys(variablesUsed).length > 0\n            ? \"(\".concat(Object.keys(variablesUsed).reduce(function (dataString, key, i) {\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\", \"$\").concat(key, \": \").concat(Utils_1.default.queryDataType(variablesUsed[key]));\n            }, \"\"), \")\")\n            : \"\";\n    };\n    DefaultQueryAdapter.prototype.operationWrapperTemplate = function (content) {\n        var query = \"\".concat(OperationType_1.default.Query, \" \").concat(this.queryDataArgumentAndTypeMap(), \" { \").concat(content, \" }\");\n        query = query.replace(\"query\", \"query\".concat(this.config.operationName !== \"\" ? \" \" + this.config.operationName : \"\"));\n        return {\n            query: query,\n            variables: Utils_1.default.queryVariablesMap(this.variables, this.fields),\n        };\n    };\n    // query\n    DefaultQueryAdapter.prototype.operationTemplate = function (variables) {\n        var operation = typeof this.operation === \"string\"\n            ? this.operation\n            : \"\".concat(this.operation.alias, \": \").concat(this.operation.name);\n        return \"\".concat(operation, \" \").concat(variables ? Utils_1.default.queryDataNameAndArgumentMap(variables) : \"\", \" \").concat(this.fields && this.fields.length > 0\n            ? \"{ \" + Utils_1.default.queryFieldsMap(this.fields) + \" }\"\n            : \"\");\n    };\n    return DefaultQueryAdapter;\n}());\nexports.default = DefaultQueryAdapter;\n//# sourceMappingURL=DefaultQueryAdapter.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar OperationType_1 = require(\"../OperationType\");\nvar Utils_1 = require(\"../Utils\");\nvar DefaultSubscriptionAdapter = /** @class */ (function () {\n    function DefaultSubscriptionAdapter(options) {\n        if (Array.isArray(options)) {\n            this.variables = Utils_1.default.resolveVariables(options);\n        }\n        else {\n            this.variables = options.variables;\n            this.fields = options.fields;\n            this.operation = options.operation;\n        }\n    }\n    DefaultSubscriptionAdapter.prototype.subscriptionBuilder = function () {\n        return this.operationWrapperTemplate(OperationType_1.default.Subscription, this.variables, this.operationTemplate(this.operation));\n    };\n    DefaultSubscriptionAdapter.prototype.subscriptionsBuilder = function (subscriptions) {\n        var _this = this;\n        var content = subscriptions.map(function (opts) {\n            _this.operation = opts.operation;\n            _this.variables = opts.variables;\n            _this.fields = opts.fields;\n            return _this.operationTemplate(opts.operation);\n        });\n        return this.operationWrapperTemplate(OperationType_1.default.Subscription, Utils_1.default.resolveVariables(subscriptions), content.join(\"\\n  \"));\n    };\n    // Convert object to name and argument map. eg: (id: $id)\n    DefaultSubscriptionAdapter.prototype.queryDataNameAndArgumentMap = function () {\n        return this.variables && Object.keys(this.variables).length\n            ? \"(\".concat(Object.keys(this.variables).reduce(function (dataString, key, i) {\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\").concat(key, \": $\").concat(key);\n            }, \"\"), \")\")\n            : \"\";\n    };\n    DefaultSubscriptionAdapter.prototype.queryDataArgumentAndTypeMap = function (variables) {\n        return Object.keys(variables).length\n            ? \"(\".concat(Object.keys(variables).reduce(function (dataString, key, i) {\n                return \"\".concat(dataString).concat(i !== 0 ? \", \" : \"\", \"$\").concat(key, \": \").concat(Utils_1.default.queryDataType(variables[key]));\n            }, \"\"), \")\")\n            : \"\";\n    };\n    // start of subscription building\n    DefaultSubscriptionAdapter.prototype.operationWrapperTemplate = function (type, variables, content) {\n        return {\n            query: \"\".concat(type, \" \").concat(this.queryDataArgumentAndTypeMap(variables), \" {\\n  \").concat(content, \"\\n}\"),\n            variables: Utils_1.default.queryVariablesMap(variables),\n        };\n    };\n    DefaultSubscriptionAdapter.prototype.operationTemplate = function (operation) {\n        var operationName = typeof this.operation === \"string\"\n            ? this.operation\n            : \"\".concat(this.operation.alias, \": \").concat(this.operation.name);\n        return \"\".concat(operationName, \" \").concat(this.queryDataNameAndArgumentMap(), \" {\\n    \").concat(this.queryFieldsMap(this.fields), \"\\n  }\");\n    };\n    // Fields selection map. eg: { id, name }\n    DefaultSubscriptionAdapter.prototype.queryFieldsMap = function (fields) {\n        var _this = this;\n        return fields\n            ? fields\n                .map(function (field) {\n                return typeof field === \"object\"\n                    ? \"\".concat(Object.keys(field)[0], \" { \").concat(_this.queryFieldsMap(Object.values(field)[0]), \" }\")\n                    : \"\".concat(field);\n            })\n                .join(\", \")\n            : \"\";\n    };\n    return DefaultSubscriptionAdapter;\n}());\nexports.default = DefaultSubscriptionAdapter;\n//# sourceMappingURL=DefaultSubscriptionAdapter.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.adapters = exports.query = exports.mutation = exports.subscription = void 0;\nvar adapters_1 = require(\"./adapters\");\nexports.adapters = adapters_1.default;\nvar DefaultMutationAdapter_1 = require(\"./adapters/DefaultMutationAdapter\");\nvar DefaultQueryAdapter_1 = require(\"./adapters/DefaultQueryAdapter\");\nvar DefaultSubscriptionAdapter_1 = require(\"./adapters/DefaultSubscriptionAdapter\");\nfunction queryOperation(options, adapter, config) {\n    var defaultAdapter;\n    if (Array.isArray(options)) {\n        if (adapter) {\n            var customAdapter = new adapter(options, config);\n            return customAdapter.queriesBuilder(options);\n        }\n        defaultAdapter = new DefaultQueryAdapter_1.default(options, config);\n        return defaultAdapter.queriesBuilder(options);\n    }\n    if (adapter) {\n        var customAdapter = new adapter(options, config);\n        return customAdapter.queryBuilder();\n    }\n    defaultAdapter = new DefaultQueryAdapter_1.default(options, config);\n    return defaultAdapter.queryBuilder();\n}\nexports.query = queryOperation;\nfunction mutationOperation(options, adapter, config) {\n    var customAdapter;\n    var defaultAdapter;\n    if (Array.isArray(options)) {\n        if (adapter) {\n            // @ts-ignore\n            customAdapter = new adapter(options, config);\n            return customAdapter.mutationsBuilder(options);\n        }\n        defaultAdapter = new DefaultMutationAdapter_1.default(options, config);\n        return defaultAdapter.mutationsBuilder(options);\n    }\n    if (adapter) {\n        // @ts-ignore\n        customAdapter = new adapter(options, config);\n        return customAdapter.mutationBuilder();\n    }\n    defaultAdapter = new DefaultMutationAdapter_1.default(options, config);\n    return defaultAdapter.mutationBuilder();\n}\nexports.mutation = mutationOperation;\nfunction subscriptionOperation(options, adapter) {\n    var customAdapter;\n    var defaultAdapter;\n    if (Array.isArray(options)) {\n        if (adapter) {\n            // @ts-ignore\n            customAdapter = new adapter(options);\n            return customAdapter.subscriptionsBuilder(options);\n        }\n        defaultAdapter = new DefaultSubscriptionAdapter_1.default(options);\n        return defaultAdapter.subscriptionsBuilder(options);\n    }\n    if (adapter) {\n        // @ts-ignore\n        customAdapter = new adapter(options);\n        return customAdapter.subscriptionBuilder();\n    }\n    defaultAdapter = new DefaultSubscriptionAdapter_1.default(options);\n    return defaultAdapter.subscriptionBuilder();\n}\nexports.subscription = subscriptionOperation;\n//# sourceMappingURL=index.js.map","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport const repoMetadataFragment = `\n    fragment repoMetadata on Asset {\n        repo_assetId\n        repo_name\n        repo_path\n        repo_createDate\n        repo_createdBy {\n            id\n        }\n        repo_modifyDate\n        repo_modifiedBy\n        primary_etag\n        repo_state\n        dc_format\n        storage_deviceCreateDate\n        storage_deviceModifyDate\n        storage_region\n        storage_assignee {\n            id\n            type\n        }\n        repository {\n            repo_repositoryId\n            repo_repositoryType\n            repo_owner {\n                id\n            }\n        }\n        repo_ancestors\n        repo_assetClass\n        repo_assetType\n        repo_assetSubType\n        primaryLink {\n            href\n            templated\n        }\n        blockUploadLink {\n            href\n            templated\n        }\n        ... on Composite {\n            repo_version\n            repo_size\n            isComposite\n            primaryLink {\n                href\n            }\n            blockDownloadLink {\n                href\n            }\n            renditionLink {\n                href\n            }\n        }\n        ... on File {\n            repo_version\n            repo_size\n            isFile\n            primaryLink {\n                href\n            }\n            blockDownloadLink {\n                href\n            }\n            renditionLink {\n                href\n            }\n            tiff_imageLength\n            tiff_imageWidth\n        }\n    }\n`;\n\nexport const appMetadataFragment = `\n    fragment applicationMetadata on Asset {\n        appMetadata {\n            am: valueOf(key: \"\")\n        }\n    }\n`;\n\nexport const effectivePermissionsFragment = `\n    fragment effectivePermissions on Asset {\n        effectivePermissions {\n            aclPolicy\n            annotations\n            applicationMetadata\n            default\n            directory\n            primary\n        }\n    }\n`;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { AssetLoadHints } from '../../interface/AssetModel';\nimport { OrderFieldToGQLOrderBy } from '../models/AssetSubgraphModel';\nimport { appMetadataFragment, effectivePermissionsFragment, repoMetadataFragment } from './fragments';\n\nfunction getListingQuery(loadHints?: AssetLoadHints) {\n    if (!loadHints?.listingHints) {\n        return '';\n    }\n    let listingFragment = '... on Directory {';\n    listingFragment += `\n        repo_assetId\n    `;\n    for (let i = 0; i < loadHints.listingHints.length; i++) {\n        const order = loadHints.listingHints[i].order;\n        listingFragment += `\n        list${i + 1}: childrenConnection(\n            first: ${loadHints.listingHints[i].loadOptions?.limit ?? 10},\n            orderBy: [\n                {\n                    field: ${OrderFieldToGQLOrderBy[order.field]},\n                    direction: ${order.direction.toUpperCase()}\n                }\n            ],\n            filter: {\n                dc_format: ${loadHints.listingHints[i].filter?.mediaTypes ?? null}\n            }\n        ) {\n            edges {\n                node {\n                    ...repoMetadata\n                    ...applicationMetadata\n                    # TODO: undefined effectivePermissions is equivalent to false for now.\n                    # We will change it to deferred in the future.\n                    ${loadHints.listingHints[i].effectivePermissions ? '...effectivePermissions' : ''}\n                }\n            }\n            pageInfo {\n                endCursor\n                hasNextPage\n            }\n        }\n        `;\n    }\n    listingFragment += '}';\n    return listingFragment;\n}\n\nfunction assetByPathDataQuery(loadHints?: AssetLoadHints) {\n    let query = '';\n    // undefined and false are different for appMetadata.\n    // undefined means load all the appMetadata fields that SAM.js requires eagerly for now (i.e. shell:visibility).\n    // false means load no appMetadata fields in the query\n    if (loadHints?.appMetadata) {\n        query += `\n            ...applicationMetadata\n        `;\n    }\n    if (loadHints?.effectivePermissions) {\n        query += `\n            ...effectivePermissions\n        `;\n    }\n    return query;\n}\n\nfunction needEffectivePermissionsFragment(loadHints?: AssetLoadHints) {\n    return loadHints?.effectivePermissions || loadHints?.listingHints?.some((hint) => hint.effectivePermissions);\n}\n\nfunction needAppMetadataFragment(loadHints?: AssetLoadHints) {\n    return loadHints?.appMetadata || loadHints?.listingHints?.length;\n}\n\nexport function resolveAssetByPathQuery(loadHints?: AssetLoadHints) {\n    const query = repoMetadataFragment\n                    + (needAppMetadataFragment(loadHints) ? appMetadataFragment : '')\n                    + (needEffectivePermissionsFragment(loadHints) ? effectivePermissionsFragment : '');\n    return query + `\n        query getAssetByPath($assetPath: String!, $repositoryId: ID!) {\n            resolveAssetByPath(assetPath: $assetPath, repositoryId: $repositoryId) {\n                ...repoMetadata\n                ${assetByPathDataQuery(loadHints)}\n                ${getListingQuery(loadHints)}\n            }\n        }\n    `;\n}\n\nexport function assetByRelativePathQuery(loadHints?: AssetLoadHints) {\n    const query = repoMetadataFragment\n                    + (needAppMetadataFragment(loadHints) ? appMetadataFragment : '')\n                    + (needEffectivePermissionsFragment(loadHints) ? effectivePermissionsFragment : '');\n    return query + `\n        query getAssetByPath($assetPath: String!) {\n            resolveUserHome {\n                ...repoMetadata\n                ... on Directory {\n                    assetByRelativePath(relativePath: $assetPath) {\n                        ...repoMetadata\n                        ${assetByPathDataQuery(loadHints)}\n                        ${getListingQuery(loadHints)}\n                    }\n                }\n            }\n        }\n    `;\n}\n\nexport function getChildrenQuery() {\n    const query = repoMetadataFragment + appMetadataFragment + effectivePermissionsFragment;\n    return query + `\n        query getChildren($assetId: ID!, $first: Int!, $after: String, $orderBy: [OrderByInput!], $filter: AssetFilter) {\n            resolveAssetById(assetId: $assetId) {\n                ... on Directory {\n                    repo_assetId\n                    repo_ancestors\n                    childrenConnection(first: $first, after: $after, orderBy: $orderBy, filter: $filter) {\n                        edges {\n                            node {\n                                ...repoMetadata\n                                ...applicationMetadata\n                                ...effectivePermissions\n                            }\n                        }\n                        pageInfo {\n                            endCursor\n                            hasNextPage\n                        }\n                    }\n                }\n            }\n        }\n    `;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { gql } from '@apollo/client/core';\n\nexport const UPDATE_LAST_ACCESSED = gql`\n    mutation updateLastAccessed($assetId: ID!, $input: UpdateLabelInput!) {\n        updateLabel(assetId: $assetId, input: $input) {\n            lastAccessDate\n        }\n    }\n`;\n","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n        if (ar || !(i in from)) {\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n            ar[i] = from[i];\n        }\n    }\n    return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar Log = (function () {\n    function Log(options) {\n        var _a = options.debug, debug = _a === void 0 ? false : _a;\n        this.debug = debug;\n        this.lines = [];\n    }\n    Log.prototype.emit = function (level, message) {\n        if (level in console) {\n            var prefix = Log.prefix;\n            console[level].apply(console, __spreadArray([prefix], message, false));\n        }\n    };\n    Log.prototype.tailLogs = function () {\n        var _this = this;\n        this.lines.forEach(function (_a) {\n            var level = _a[0], message = _a[1];\n            return _this.emit(level, message);\n        });\n    };\n    Log.prototype.getLogs = function () {\n        return this.lines;\n    };\n    Log.prototype.write = function (level, message) {\n        var buffer = Log.buffer;\n        this.lines = __spreadArray(__spreadArray([], this.lines.slice(1 - buffer), true), [[level, message]], false);\n        if (this.debug || level !== 'log') {\n            this.emit(level, message);\n        }\n    };\n    Log.prototype.info = function () {\n        var message = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            message[_i] = arguments[_i];\n        }\n        this.write('log', message);\n    };\n    Log.prototype.warn = function () {\n        var message = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            message[_i] = arguments[_i];\n        }\n        this.write('warn', message);\n    };\n    Log.prototype.error = function () {\n        var message = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            message[_i] = arguments[_i];\n        }\n        this.write('error', message);\n    };\n    Log.buffer = 30;\n    Log.prefix = '[apollo-cache-persist]';\n    return Log;\n}());\nexport default Log;\n//# sourceMappingURL=Log.js.map","var Cache = (function () {\n    function Cache(options) {\n        var cache = options.cache, _a = options.serialize, serialize = _a === void 0 ? true : _a;\n        this.cache = cache;\n        this.serialize = serialize;\n    }\n    Cache.prototype.extract = function () {\n        var data = this.cache.extract();\n        if (this.serialize) {\n            data = JSON.stringify(data);\n        }\n        return data;\n    };\n    Cache.prototype.restore = function (data) {\n        if (this.serialize && typeof data === 'string') {\n            data = JSON.parse(data);\n        }\n        if (data != null) {\n            this.cache.restore(data);\n        }\n    };\n    return Cache;\n}());\nexport default Cache;\n//# sourceMappingURL=Cache.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n    return new (P || (P = Promise))(function (resolve, reject) {\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\n    });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n    function verb(n) { return function (v) { return step([n, v]); }; }\n    function step(op) {\n        if (f) throw new TypeError(\"Generator is already executing.\");\n        while (g && (g = 0, op[0] && (_ = 0)), _) try {\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n            if (y = 0, t) op = [op[0] & 2, t.value];\n            switch (op[0]) {\n                case 0: case 1: t = op; break;\n                case 4: _.label++; return { value: op[1], done: false };\n                case 5: _.label++; y = op[1]; op = [0]; continue;\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\n                default:\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                    if (t[2]) _.ops.pop();\n                    _.trys.pop(); continue;\n            }\n            op = body.call(thisArg, _);\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n    }\n};\nvar Storage = (function () {\n    function Storage(options) {\n        var storage = options.storage, _a = options.key, key = _a === void 0 ? 'apollo-cache-persist' : _a;\n        this.storage = storage;\n        this.key = key;\n    }\n    Storage.prototype.read = function () {\n        return __awaiter(this, void 0, void 0, function () {\n            return __generator(this, function (_a) {\n                return [2, this.storage.getItem(this.key)];\n            });\n        });\n    };\n    Storage.prototype.write = function (data) {\n        return __awaiter(this, void 0, void 0, function () {\n            return __generator(this, function (_a) {\n                switch (_a.label) {\n                    case 0: return [4, this.storage.setItem(this.key, data)];\n                    case 1:\n                        _a.sent();\n                        return [2];\n                }\n            });\n        });\n    };\n    Storage.prototype.purge = function () {\n        return __awaiter(this, void 0, void 0, function () {\n            return __generator(this, function (_a) {\n                switch (_a.label) {\n                    case 0: return [4, this.storage.removeItem(this.key)];\n                    case 1:\n                        _a.sent();\n                        return [2];\n                }\n            });\n        });\n    };\n    Storage.prototype.getSize = function () {\n        return __awaiter(this, void 0, void 0, function () {\n            var data;\n            return __generator(this, function (_a) {\n                switch (_a.label) {\n                    case 0: return [4, this.storage.getItem(this.key)];\n                    case 1:\n                        data = _a.sent();\n                        if (data == null) {\n                            return [2, 0];\n                        }\n                        else {\n                            return [2, typeof data === 'string' ? data.length : null];\n                        }\n                        return [2];\n                }\n            });\n        });\n    };\n    return Storage;\n}());\nexport default Storage;\n//# sourceMappingURL=Storage.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n    return new (P || (P = Promise))(function (resolve, reject) {\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\n    });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n    function verb(n) { return function (v) { return step([n, v]); }; }\n    function step(op) {\n        if (f) throw new TypeError(\"Generator is already executing.\");\n        while (g && (g = 0, op[0] && (_ = 0)), _) try {\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n            if (y = 0, t) op = [op[0] & 2, t.value];\n            switch (op[0]) {\n                case 0: case 1: t = op; break;\n                case 4: _.label++; return { value: op[1], done: false };\n                case 5: _.label++; y = op[1]; op = [0]; continue;\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\n                default:\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                    if (t[2]) _.ops.pop();\n                    _.trys.pop(); continue;\n            }\n            op = body.call(thisArg, _);\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n    }\n};\nvar Persistor = (function () {\n    function Persistor(_a, options) {\n        var log = _a.log, cache = _a.cache, storage = _a.storage;\n        var _b = options.maxSize, maxSize = _b === void 0 ? 1024 * 1024 : _b, persistenceMapper = options.persistenceMapper;\n        this.log = log;\n        this.cache = cache;\n        this.storage = storage;\n        this.paused = false;\n        if (persistenceMapper) {\n            this.persistenceMapper = persistenceMapper;\n        }\n        if (maxSize) {\n            this.maxSize = maxSize;\n        }\n    }\n    Persistor.prototype.persist = function () {\n        return __awaiter(this, void 0, void 0, function () {\n            var data, error_1;\n            return __generator(this, function (_a) {\n                switch (_a.label) {\n                    case 0:\n                        _a.trys.push([0, 6, , 7]);\n                        data = this.cache.extract();\n                        if (!(!this.paused && this.persistenceMapper)) return [3, 2];\n                        return [4, this.persistenceMapper(data)];\n                    case 1:\n                        data = _a.sent();\n                        _a.label = 2;\n                    case 2:\n                        if (!(this.maxSize != null &&\n                            typeof data === 'string' &&\n                            data.length > this.maxSize &&\n                            !this.paused)) return [3, 4];\n                        return [4, this.purge()];\n                    case 3:\n                        _a.sent();\n                        this.paused = true;\n                        return [2];\n                    case 4:\n                        if (this.paused) {\n                            return [2];\n                        }\n                        return [4, this.storage.write(data)];\n                    case 5:\n                        _a.sent();\n                        this.log.info(typeof data === 'string'\n                            ? \"Persisted cache of size \".concat(data.length, \" characters\")\n                            : 'Persisted cache');\n                        return [3, 7];\n                    case 6:\n                        error_1 = _a.sent();\n                        this.log.error('Error persisting cache', error_1);\n                        throw error_1;\n                    case 7: return [2];\n                }\n            });\n        });\n    };\n    Persistor.prototype.restore = function () {\n        return __awaiter(this, void 0, void 0, function () {\n            var data, error_2;\n            return __generator(this, function (_a) {\n                switch (_a.label) {\n                    case 0:\n                        _a.trys.push([0, 5, , 6]);\n                        return [4, this.storage.read()];\n                    case 1:\n                        data = _a.sent();\n                        if (!(data != null)) return [3, 3];\n                        return [4, this.cache.restore(data)];\n                    case 2:\n                        _a.sent();\n                        this.log.info(typeof data === 'string'\n                            ? \"Restored cache of size \".concat(data.length, \" characters\")\n                            : 'Restored cache');\n                        return [3, 4];\n                    case 3:\n                        this.log.info('No stored cache to restore');\n                        _a.label = 4;\n                    case 4: return [3, 6];\n                    case 5:\n                        error_2 = _a.sent();\n                        this.log.error('Error restoring cache', error_2);\n                        throw error_2;\n                    case 6: return [2];\n                }\n            });\n        });\n    };\n    Persistor.prototype.purge = function () {\n        return __awaiter(this, void 0, void 0, function () {\n            var error_3;\n            return __generator(this, function (_a) {\n                switch (_a.label) {\n                    case 0:\n                        _a.trys.push([0, 2, , 3]);\n                        return [4, this.storage.purge()];\n                    case 1:\n                        _a.sent();\n                        this.log.info('Purged cache storage');\n                        return [3, 3];\n                    case 2:\n                        error_3 = _a.sent();\n                        this.log.error('Error purging cache storage', error_3);\n                        throw error_3;\n                    case 3: return [2];\n                }\n            });\n        });\n    };\n    return Persistor;\n}());\nexport default Persistor;\n//# sourceMappingURL=Persistor.js.map","export default (function (_a) {\n    var cache = _a.cache;\n    return function (persist) {\n        var write = cache.write;\n        var evict = cache.evict;\n        var modify = cache.modify;\n        var gc = cache.gc;\n        cache.write = function () {\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            var result = write.apply(cache, args);\n            persist();\n            return result;\n        };\n        cache.evict = function () {\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            var result = evict.apply(cache, args);\n            persist();\n            return result;\n        };\n        cache.modify = function () {\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            var result = modify.apply(cache, args);\n            persist();\n            return result;\n        };\n        cache.gc = function () {\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            var result = gc.apply(cache, args);\n            persist();\n            return result;\n        };\n        return function () {\n            cache.write = write;\n            cache.evict = evict;\n            cache.modify = modify;\n            cache.gc = gc;\n        };\n    };\n});\n//# sourceMappingURL=onCacheWrite.js.map","import onCacheWrite from './onCacheWrite';\nimport onAppBackground from './onAppBackground';\nvar Trigger = (function () {\n    function Trigger(_a, options) {\n        var log = _a.log, persistor = _a.persistor;\n        var _this = this;\n        this.fire = function () {\n            if (!_this.debounce) {\n                _this.persist();\n                return;\n            }\n            if (_this.timeout != null) {\n                clearTimeout(_this.timeout);\n            }\n            _this.timeout = setTimeout(_this.persist, _this.debounce);\n        };\n        this.persist = function () {\n            if (_this.paused) {\n                return;\n            }\n            _this.persistor.persist();\n        };\n        var defaultDebounce = Trigger.defaultDebounce;\n        var cache = options.cache, debounce = options.debounce, _b = options.trigger, trigger = _b === void 0 ? 'write' : _b;\n        if (!trigger) {\n            return;\n        }\n        this.debounce = debounce != null ? debounce : defaultDebounce;\n        this.persistor = persistor;\n        this.paused = false;\n        switch (trigger) {\n            case 'write':\n                this.uninstall = onCacheWrite({ cache: cache })(this.fire);\n                break;\n            case 'background':\n                if (debounce) {\n                    log.warn('Debounce is not recommended with `background` trigger');\n                }\n                this.debounce = debounce;\n                this.uninstall = onAppBackground({ cache: cache, log: log })(this.fire);\n                break;\n            default:\n                if (typeof trigger === 'function') {\n                    this.uninstall = trigger(this.fire);\n                }\n                else {\n                    throw Error(\"Unrecognized trigger option: \".concat(trigger));\n                }\n        }\n    }\n    Trigger.prototype.pause = function () {\n        this.paused = true;\n    };\n    Trigger.prototype.resume = function () {\n        this.paused = false;\n    };\n    Trigger.prototype.remove = function () {\n        if (this.uninstall) {\n            this.uninstall();\n            this.uninstall = null;\n            this.paused = true;\n        }\n    };\n    Trigger.defaultDebounce = 1000;\n    return Trigger;\n}());\nexport default Trigger;\n//# sourceMappingURL=Trigger.js.map","import onCacheWrite from './onCacheWrite';\nexport default (function (_a) {\n    var log = _a.log, cache = _a.cache;\n    return function (persist) {\n        log.warn('Trigger option `background` not available on web; using `write` trigger');\n        return onCacheWrite({ cache: cache })(persist);\n    };\n});\n//# sourceMappingURL=onAppBackground.js.map","import Log from './Log';\nimport Cache from './Cache';\nimport Storage from './Storage';\nimport Persistor from './Persistor';\nimport Trigger from './Trigger';\nvar CachePersistor = (function () {\n    function CachePersistor(options) {\n        if (!options.cache) {\n            throw new Error('In order to persist your Apollo Cache, you need to pass in a cache. ' +\n                'Please see https://www.apollographql.com/docs/react/basics/caching.html for our default InMemoryCache.');\n        }\n        if (!options.storage) {\n            throw new Error('In order to persist your Apollo Cache, you need to pass in an underlying storage provider. ' +\n                'Please see https://github.com/apollographql/apollo-cache-persist#storage-providers');\n        }\n        var log = new Log(options);\n        var cache = new Cache(options);\n        var storage = new Storage(options);\n        var persistor = new Persistor({ log: log, cache: cache, storage: storage }, options);\n        var trigger = new Trigger({ log: log, persistor: persistor }, options);\n        this.log = log;\n        this.cache = cache;\n        this.storage = storage;\n        this.persistor = persistor;\n        this.trigger = trigger;\n    }\n    CachePersistor.prototype.persist = function () {\n        return this.persistor.persist();\n    };\n    CachePersistor.prototype.restore = function () {\n        return this.persistor.restore();\n    };\n    CachePersistor.prototype.purge = function () {\n        return this.persistor.purge();\n    };\n    CachePersistor.prototype.pause = function () {\n        this.trigger.pause();\n    };\n    CachePersistor.prototype.resume = function () {\n        this.trigger.resume();\n    };\n    CachePersistor.prototype.remove = function () {\n        this.trigger.remove();\n    };\n    CachePersistor.prototype.getLogs = function (print) {\n        if (print === void 0) { print = false; }\n        if (print) {\n            this.log.tailLogs();\n        }\n        else {\n            return this.log.getLogs();\n        }\n    };\n    CachePersistor.prototype.getSize = function () {\n        return this.storage.getSize();\n    };\n    return CachePersistor;\n}());\nexport default CachePersistor;\n//# sourceMappingURL=CachePersistor.js.map","var __extends = (this && this.__extends) || (function () {\n    var extendStatics = function (d, b) {\n        extendStatics = Object.setPrototypeOf ||\n            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n        return extendStatics(d, b);\n    };\n    return function (d, b) {\n        if (typeof b !== \"function\" && b !== null)\n            throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n        extendStatics(d, b);\n        function __() { this.constructor = d; }\n        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n    };\n})();\nimport CachePersistor from './CachePersistor';\nimport Persistor from './Persistor';\nimport Storage from './Storage';\nexport var persistCacheSync = function (options) {\n    var cachePersistor = new SynchronousCachePersistor(options);\n    cachePersistor.restoreSync();\n};\nvar SynchronousCachePersistor = (function (_super) {\n    __extends(SynchronousCachePersistor, _super);\n    function SynchronousCachePersistor(options) {\n        var _this = _super.call(this, options) || this;\n        _this.storage = new SynchronousStorage(options);\n        _this.persistor = new SynchronousPersistor({ log: _this.log, cache: _this.cache, storage: _this.storage }, options);\n        return _this;\n    }\n    SynchronousCachePersistor.prototype.restoreSync = function () {\n        this.persistor.restoreSync();\n    };\n    return SynchronousCachePersistor;\n}(CachePersistor));\nexport { SynchronousCachePersistor };\nvar SynchronousPersistor = (function (_super) {\n    __extends(SynchronousPersistor, _super);\n    function SynchronousPersistor(_a, options) {\n        var log = _a.log, cache = _a.cache, storage = _a.storage;\n        return _super.call(this, { log: log, cache: cache, storage: storage }, options) || this;\n    }\n    SynchronousPersistor.prototype.restoreSync = function () {\n        this.cache.restore(this.storage.readSync());\n    };\n    return SynchronousPersistor;\n}(Persistor));\nexport { SynchronousPersistor };\nvar SynchronousStorage = (function (_super) {\n    __extends(SynchronousStorage, _super);\n    function SynchronousStorage(options) {\n        return _super.call(this, options) || this;\n    }\n    SynchronousStorage.prototype.readSync = function () {\n        return this.storage.getItem(this.key);\n    };\n    return SynchronousStorage;\n}(Storage));\nexport { SynchronousStorage };\n//# sourceMappingURL=persistCacheSync.js.map","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { TypePolicies } from '@apollo/client';\n\nconst typePolicies: TypePolicies = {\n    Asset: {\n        keyFields: [ 'repo_assetId' ],\n    },\n    Repository: {\n        keyFields: [ 'repo_repositoryId' ],\n    },\n    Link: {\n        keyFields: [ 'href' ],\n    },\n    AssetList: {\n        keyFields: [ 'assetListId' ]\n    }\n};\nexport default typePolicies;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ApolloError, ApolloQueryResult, ObservableQuery, Observer } from '@apollo/client';\nimport SAMError from '../core/SAMError';\nimport { isDeepEqual } from '../core/ObjectUtils';\nimport type Resource from '../assets/Resource';\nimport { synchronized } from '../core/decorators';\nimport { ManagedPromise } from '../utils/ManagedPromise';\nimport type { ISAMCorePrivate } from '../indexPrivate';\n\n\n/**\n * Watches an Apollo watchQuery and manages its lifecycle, including subscription,\n * error handling, and callbacks for deferred data. Designed to avoid memory leaks\n * by unsubscribing when the query becomes idle. Provides a promise for the first result,\n * and a callback when subsequent results are returned (to handle deferred data).\n *\n * @template T The type of the resource data.\n * @implements Observer<ApolloQueryResult<T>>\n */\nexport class ResourceQueryWatcher<T> implements Observer<ApolloQueryResult<T>> {\n\n    queryIdleTimeout: ReturnType<typeof setTimeout> | undefined;\n    subscription: ReturnType<ObservableQuery<any>['subscribe']> | undefined;\n    previousResult: ApolloQueryResult<T> | undefined;\n    firstResultPromise = new ManagedPromise<T>();\n\n    constructor(\n        private readonly _core: ISAMCorePrivate,\n        private readonly resource: Resource<T>,\n        private readonly processIncrementalData?: (result: any) => void\n    ) {\n    }\n\n    /**\n     * Apollo doesn't currently provide a status update that lets us know that deferred data\n     * has completely arrived, so that we can unsubscribe.\n     *\n     * To work around this, and in the spirit of similar fetch() timeouts,\n     * we fire an idle timer to unsubscribe the query from further updates\n     * when it has been idle for 30 seconds or so. Our current GQL deferred usage\n     * is constrained to fetching extra fields like appMetadata, and if those don't\n     * arrive within that timeframe, they likely won't.\n     */\n    onQueryIdle = () => {\n        this.queryIdleTimeout = undefined;\n        // If the query is idle, unsubscribe to avoid memory leaks.\n        if (!this.subscription?.closed) {\n            this.subscription?.unsubscribe();\n        }\n    };\n\n    start(subscription: ReturnType<ObservableQuery<any>['subscribe']>) {\n        this.subscription = subscription;\n    }\n\n    @synchronized\n    async next(result: ApolloQueryResult<T>) {\n        if (this.queryIdleTimeout) {\n            clearTimeout(this.queryIdleTimeout);\n            this.queryIdleTimeout = undefined;\n        }\n        const watchQueryTTL: number = this._core._environment.getValue('GRAPHQL_WATCH_QUERY_TTL');\n\n        this.queryIdleTimeout = setTimeout(this.onQueryIdle, watchQueryTTL);\n        let parsedResult;\n        try {\n            parsedResult = await this.resource?._parse(result) as T;\n        } catch (error) {\n            this.resource?._setError(error);\n            if (!this.previousResult) {\n                this.firstResultPromise.reject(error);\n            }\n            if (!this.subscription?.closed) {\n                this.subscription?.unsubscribe();\n            }\n            return;\n        }\n        await this.resource?._setData(parsedResult, {\n            // We only want to set `loading` if we know we're definitely going to get more data.\n            // This is used to prevent lists from being ReadyFullyLoaded until all data is received.\n            // We only know that's true if `queryResult.loading` is true.\n            loading: result.loading,\n            // If the result has changed from the previous result, we mark it as changed.\n            // ItemLoaderState will recompute its lists if it gets notified that a non-loading\n            // result has arrived that didn't match the previous result.\n            changed: !isDeepEqual(this.previousResult?.data, result.data, true)\n        });\n\n        if (!this.previousResult) {\n            this.firstResultPromise.resolve(parsedResult);\n        } else {\n            this.processIncrementalData?.(parsedResult);\n        }\n        this.previousResult = result;\n    }\n\n    error(apolloError: ApolloError) {\n        const error = SAMError.createWithApolloError(apolloError);\n        this.resource?._setError(error);\n        if (!this.previousResult) {\n            this.firstResultPromise.reject(error);\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { ApolloQueryResult, NormalizedCacheObject, OperationVariables, QueryOptions, WatchQueryFetchPolicy, WatchQueryOptions } from '@apollo/client/core';\nimport {\n    ApolloClient,\n    ApolloError,\n    ApolloLink,\n    HttpLink,\n    InMemoryCache,\n    from,\n    gql,\n} from '@apollo/client/core';\nimport { RetryLink } from '@apollo/client/link/retry';\nimport type { ServerError } from '@apollo/client/link/utils';\nimport type { ISAMObject } from '../indexPrivate';\nimport type {\n    AssetListConnectionArgs,\n    IdQuery,\n    PathQuery,\n    RelativePathQuery,\n} from './models/AssetSubgraphModel';\nimport {\n    GQLResolveAssetFields,\n} from './models/AssetSubgraphModel';\nimport { SAMError, SAMErrorCode } from '../core/SAMError';\nimport { query } from 'gql-query-builder'; import type Fields from 'gql-query-builder/build/Fields';\nimport clamp from '../utils/clamp';\nimport { memoize, synchronized } from '../core/decorators/';\nimport type { AssetFilter, OrderByInput, Query, SharedWithYouListAssetListConnectionArgs, SharedWithYouQuery } from './generated/types';\nimport type { AssetLoadHints } from '@sam-js-src/interface/AssetModel';\nimport { assetByRelativePathQuery, getChildrenQuery, resolveAssetByPathQuery } from './queries/getAsset';\nimport type { AssetContainerChildrenConnectionArgs } from './generated/types';\nimport type { PlsRecentsQuery, PlsRecentsQueryVariables } from './generated/types';\nimport { UPDATE_LAST_ACCESSED } from './mutations/LastAccessed';\nimport type { UpdateLabelMutation, UpdateLabelMutationVariables } from './generated/types';\nimport { persistCache } from 'apollo3-cache-persist';\nimport generatedPossibleTypes from './generated/possibleTypes.json';\nimport Resource, { isGraphQLResult, isResponse } from '../assets/Resource';\nimport typePolicies from './models/typePolicies';\nimport type GraphQLAssetResource from './GraphQLAssetResource';\nimport { ResourceQueryWatcher } from './ResourceQueryWatcher';\nimport type { GenerationHistoryAssetsQuery } from './GQLManager';\n\nconst { possibleTypes } = generatedPossibleTypes;\n\ntype FavoritesQuery = Pick<Query, 'favorites'>;\n\nfunction isServerError(error: Error): error is ServerError {\n    return error && 'statusCode' in error && typeof error.statusCode === 'number';\n}\n\nexport default class GQLInterface implements ISAMObject {\n\n    /**\n     * _addTypeName is for internal use only. Just for testing purposes.\n     */\n    constructor(\n        readonly _core: ISAMCorePrivate,\n    ) { }\n\n    error(msg: string): void {\n        this._core._environment.error(msg);\n    }\n\n    warn(msg: string): void {\n        this._core._environment.warn(msg);\n    }\n\n    get cacheEnabled(): boolean {\n        return this._core._environment.getValue('FEATURE_FLAGS')?.['use-graphql-cache'] ?? false;\n    }\n\n    @memoize\n    private async _client(_addTypeName: boolean = true): Promise<ApolloClient<NormalizedCacheObject>> {\n        const useEdge = this._core._environment.getValue('HIGH_PRIORITY_RAPI_REQUESTS');\n        const httpLink = new HttpLink({\n            uri: useEdge ? `https://${this._core._environment.endpoints.ACPC_SUPERGRAPH_EDGE_HOST}` : `https://${this._core._environment.endpoints.ACPC_SUPERGRAPH_HOST}`,\n            ...(this._core._environment._hooks?.fetch ? { fetch: this._core._environment._hooks.fetch } : {})\n        });\n\n        // Refresh the access token before setting the context in case it's not valid\n        await this._core._environment._refreshAccessToken();\n        const authMiddleware = new ApolloLink((operation, forward) => {\n            const token = this._core._environment.getValue('ACCESS_TOKEN');\n            operation.setContext({\n                headers: {\n                    authorization: `Bearer ${token}`,\n                    'x-api-key': this._core._environment.getValue('CLIENT_ID'),\n                },\n            });\n            return forward(operation);\n        });\n\n        // On a 401 error, attempt to refresh the access token and retry the operation.\n        const retryLink = new RetryLink({\n            delay: (count, _operation, error) => {\n                // On the first retry it's likely we haven't secured a user token yet, set delay to 0\n                // Additionally, since Auth is handled in Environment.ts we will only hit this retry once\n                if (count === 1) {\n                    return 0;\n                }\n\n                const min = this._core._environment.getValue('MIN_RETRY_INTERVAL');\n                const max = this._core._environment.getValue('MAX_RETRY_INTERVAL');\n                const delay = clamp(Math.pow(2, count) * 1000, min, max);\n                this._core._environment.log(`GQL: Retryable error ${error.statusCode} retrying in ${delay}ms, ${count} retries so far`);\n\n                return delay;\n            },\n            attempts: async (count, _operation, error) => {\n                const maxRetries = this._core._environment._maxNumberOfRetries;\n                const hasExceededMaxRetries = count > maxRetries;\n                const isUnauthorizedError = isServerError(error) && error.statusCode === 401;\n                if (isUnauthorizedError) {\n                    this._core._environment._isTokenInvalid = true;\n                }\n                if (hasExceededMaxRetries) {\n                    this._core._environment.log(\n                        `GQL: Retryable error ${error.statusCode} attempt ${count} exceeded ${maxRetries} retries`);\n                }\n                if (hasExceededMaxRetries || !isUnauthorizedError) {\n                    return false;\n                }\n                // refresh the access token as it is invalid.\n                // This will trigger a new token to be fetched and the context to be updated.\n                await this._core._environment._refreshAccessToken();\n                return true;\n            },\n        });\n\n        const cache = new InMemoryCache({\n            addTypename: _addTypeName,\n            possibleTypes,\n            typePolicies,\n        });\n\n        // If the cache is enabled, persist the cache to SAM's persistent storage\n        // under the default \"apollo-cache-persist\" key.\n        if (this.cacheEnabled) {\n            const samCache = this._core._environment.cache;\n            await persistCache({\n                cache,\n                debug: false,\n                storage: {\n                    getItem: (key) => samCache.getItem(key),\n                    setItem: (key, value) => samCache.setItem(key, value),\n                    removeItem: (key) => samCache.deleteItem(key),\n                },\n            });\n        }\n\n        return new ApolloClient({\n            // retryLink needs to be passed in before the authMiddleware link so that\n            // the authMiddleware link will re-run on retry and update the\n            // operation context with the new access token.\n            link: from([ retryLink, authMiddleware, httpLink ]),\n            cache,\n            defaultOptions: {\n                query: {\n                    // \"query\" is not reactive, so when the cache is enabled, we want to\n                    // store results in the in-memory cache, but always fetch from the network.\n                    // If the cache isn't enabled, don't store the response in the cache at all.\n                    fetchPolicy: this.cacheEnabled ? 'network-only' : 'no-cache',\n                    // TODO: Need to understand various error policies that Apollo client offers and see which suits our needs\n                    errorPolicy: 'all',\n                },\n                watchQuery: {\n                    // \"watchQuery\" _is_ reactive, so when the cache is enabled, we want to receive cached data first, then network data.\n                    // If the cache isn't enabled, don't store the response in the cache at all (though we only use watchQuery when cache is enabled).\n                    // When cache is enabled, use the cache for the initial data and then fetch from the network.\n                    fetchPolicy: this.cacheEnabled ? 'cache-and-network' : 'no-cache',\n                    errorPolicy: 'all',\n                },\n            },\n        });\n    }\n\n    /**\n     * Initializes the Apollo client.\n     * @param _addTypeName - Whether to add the typename to the query.\n     */\n    @synchronized\n    async initialize(\n        _addTypeName: boolean = true\n    ): Promise<void> {\n        await this._client(_addTypeName);\n    }\n\n    /**\n     * Executes a GraphQL query or watchQuery, depending on whether the query needs incremental data or not,\n     * and whether the cache is enabled.\n     * The `flags` provided to `parseQueryResult` will indicate whether the result is still loading or if the data\n     * has changed since the previous response (e.g. indicating we should update lists in response to the new data).\n     *\n     * If GraphQL caching is not enabled, the query is only executed once with a `fetchPolicy` of `network-only`.\n     *\n     * @param queryOptions - The query options to use for the query.\n     * @param resource - The resource to update with the query result.\n     * @param processIncrementalData - A function to process incremental data updates from the query.\n     *\n     * @return The FIRST result of the query (typically from cache, but can be from the service). The resource will receive updates.\n     */\n    private async query<TData, TVariables extends OperationVariables = OperationVariables>(\n        queryOptions: QueryOptions<TVariables, TData> | WatchQueryOptions<TVariables, TData>,\n        resource?: Resource<TData>,\n        processIncrementalData?: (incrementalData: TData) => void,\n    ): Promise<TData> {\n        resource = resource ?? new Resource(this._core);\n\n        const client = await this._client();\n        // If the cache isn't enabled and we don't need to process incremental data, we can just use a\n        // regular Apollo \"query\", which returns results once. Otherwise we'll use a watchQuery.\n        if (!this.cacheEnabled && queryOptions.fetchPolicy !== 'cache-and-network' && !processIncrementalData) {\n            let result: ApolloQueryResult<TData>;\n            try {\n                result = await client.query<TData, TVariables>({\n                    ...queryOptions,\n                    // With the cache disabled, always skip the cache unless the requestor says otherwise.\n                    fetchPolicy: queryOptions.fetchPolicy ?? 'no-cache',\n                });\n            } catch (error) {\n                throw SAMError.createWithApolloError(error as ApolloError);\n            }\n            const data = await resource._parse(result);\n            await resource._setData(data);\n            return data;\n        } else {\n            // For skipCache, go to the network; we'll store the response in the cache for later.\n            // For skipRevalidation, use the cache without going to the network (unless there is no cache).\n            // Otherwise, we'll use cache-and-network to get the cached data first, then the network data, using `watchQuery`.\n            const defaultFetchPolicy: WatchQueryFetchPolicy\n                = resource.skipCache ? 'network-only'\n                    : resource.skipRevalidation ? 'cache-first'\n                        : this.cacheEnabled ? 'cache-and-network' : 'no-cache';\n\n            // If the cache is enabled, watchQuery() allows us to update the resource when we have new data.\n            const observableQuery = client.watchQuery({\n                ...queryOptions,\n                fetchPolicy: queryOptions.fetchPolicy ?? defaultFetchPolicy,\n            });\n            const queryWatcher = new ResourceQueryWatcher<TData>(this._core, resource, processIncrementalData);\n            observableQuery.subscribe(queryWatcher);\n            return queryWatcher.firstResultPromise.promise;\n        }\n    }\n\n    /**\n      * Retrive a page of favorite assets for the user.\n      */\n    async getFavorites(\n        gqlArgs: AssetListConnectionArgs,\n        resource?: Resource<FavoritesQuery>,\n        processIncrementalData?: (incrementalData: FavoritesQuery) => void,\n    ) {\n        let q: ReturnType<typeof query>;\n\n        try {\n            // gql-query-builder consumes errors, build query strings in a try-catch\n            // TODO: propose just using graphql-tag\n            q = query(\n                {\n                    operation: 'favorites',\n                    fields: [\n                        'assetListId',\n                        {\n                            operation: 'assetListConnection',\n                            variables: {\n                                first: { value: gqlArgs.first, required: true },\n                                after: gqlArgs.after,\n                                filter: { value: gqlArgs.filter, type: 'AssetListFilter', required: false },\n                                orderBy: { value: gqlArgs.orderBy, type: 'FavoriteOrderByInput', required: false }\n                            },\n                            fields: [\n                                {\n                                    pageInfo: [ 'hasNextPage', 'endCursor' ],\n                                },\n                                {\n                                    edges: [\n                                        'cursor',\n                                        {\n                                            node: [ { operation: 'Asset', fragment: true, fields: GQLResolveAssetFields } ]\n                                        },\n                                    ],\n                                },\n                            ],\n                        },\n                    ],\n                },\n                null,\n                {\n                    operationName: 'favorites',\n                }\n            );\n        } catch (err) {\n            this.error('error building query string');\n            throw SAMError.create(\n                SAMErrorCode.INTERNAL_ERROR,\n                'Error building query string for getFavorites',\n                { underlyingError: err }\n            );\n        }\n\n        return this.query<FavoritesQuery>({\n            query: gql(q.query),\n            variables: q.variables,\n        }, resource, processIncrementalData);\n    }\n\n    /**\n     * Marks or unmarks an asset as favorited.\n     */\n    async setFavorite(assetId: string, isFavorite: boolean) {\n        const client = await this._client();\n        try {\n            await client.mutate({\n                mutation: gql`\n                    mutation updateLabel($assetId: ID!, $input: UpdateLabelInput!) {\n                        updateLabel(assetId: $assetId, input: $input) {\n                            favorite {\n                                isFavorite\n                            }\n                        }\n                    }\n                `,\n                variables: {\n                    assetId,\n                    input: {\n                        favorite: {\n                            isFavorite\n                        }\n                    },\n                }\n            });\n        } catch (error) {\n            if (error instanceof ApolloError) {\n                throw SAMError.createWithApolloError(error);\n            }\n\n            // Only `ApolloErrors` should be thrown, but this is here just in case.\n            throw SAMError.create(\n                SAMErrorCode.UNKNOWN,\n                'No data or error returned from the query getAssetById'\n            );\n        }\n    }\n\n    /**\n     * Retrieves an asset by its ID\n     * Additional loading parameters can be introduced in the future updates.\n     * In the future, we might use codegen to generate types from the schema.\n     */\n    async getAssetById(assetId: string, resource: GraphQLAssetResource<IdQuery>): Promise<void> {\n        const resolveAssetById = query(\n            {\n                operation: 'resolveAssetById',\n                variables: {\n                    assetId: {\n                        value: assetId,\n                        name: 'assetId',\n                        required: true,\n                        type: 'ID',\n                    },\n                },\n                fields: GQLResolveAssetFields as unknown as Fields,\n            },\n            null,\n            {\n                operationName: 'getAssetById',\n            }\n        );\n\n        await this.query<IdQuery>({\n            query: gql(resolveAssetById.query),\n            variables: resolveAssetById.variables,\n        }, resource);\n    }\n\n    async getAssetByPath(\n        assetPath: string,\n        repositoryId: string,\n        loadHints: AssetLoadHints | undefined,\n        resource: Resource<PathQuery>\n    ): Promise<void> {\n        const resolveAssetByPath = {\n            query: resolveAssetByPathQuery(loadHints),\n            variables: {\n                assetPath,\n                repositoryId,\n            }\n        };\n\n        await this.query<PathQuery>({\n            query: gql(resolveAssetByPath.query),\n            variables: resolveAssetByPath.variables,\n        }, resource);\n    }\n\n    async getAssetByRelativePath(\n        assetPath: string,\n        loadHints: AssetLoadHints | undefined,\n        resource: Resource<RelativePathQuery>\n    ): Promise<RelativePathQuery> {\n        // if repositoryId is not provided, fetch the asset by relative path from the user's home repository\n        // this query will return the home folder data and the asset data\n        const resolveAssetByPath = {\n            query: assetByRelativePathQuery(loadHints),\n            variables: {\n                assetPath,\n            }\n        };\n\n        return this.query<RelativePathQuery>({\n            query: gql(resolveAssetByPath.query),\n            variables: resolveAssetByPath.variables,\n        }, resource);\n    }\n\n    async getSharedWithYou(\n        options: SharedWithYouListAssetListConnectionArgs,\n        resource?: Resource<SharedWithYouQuery>,\n        processIncrementalData?: (incrementalData: SharedWithYouQuery) => void\n    ): Promise<SharedWithYouQuery> {\n        const { first, after, filter, orderBy } = options;\n        const sharedWithYouQuery = await import('./queries/SWYAdobeAsset');\n\n        return this.query<SharedWithYouQuery>({\n            query: sharedWithYouQuery.SHARED_WITH_YOU_ASSETS,\n            variables: { first, after, filter, orderBy },\n        }, resource, processIncrementalData);\n    }\n\n    async getChildren(assetId: string, args: AssetContainerChildrenConnectionArgs, resource: Resource<IdQuery>): Promise<IdQuery> {\n        const getChildren = {\n            query: getChildrenQuery(),\n            variables: {\n                assetId,\n                first: args.first,\n                after: args.after,\n                orderBy: args.orderBy,\n                filter: args.filter\n            }\n        };\n\n        return this.query<IdQuery>({\n            query: gql(getChildren.query),\n            variables: getChildren.variables,\n        }, resource);\n    }\n\n    async getGenerationHistoryAssets(options: { first: number, after?: string, orderBy?: OrderByInput[], filter?: AssetFilter }, resource?: Resource<GenerationHistoryAssetsQuery>) {\n        const { generationHistoryAssets } = await import('./queries/generationHistoryAssets');\n\n        // Before we execute the query, we need to override the resource's parser to handle the case where the fireflyGenerationsDirectory (a sub-field in the response) is null\n        // In this case data.errors will be populated with a NOT_FOUND error, but we still want to return an empty array\n        resource && (resource.parser = (response: Response | ApolloQueryResult<GenerationHistoryAssetsQuery>) => {\n            if (isResponse(response)) {\n                return response.json();\n            } else if (isGraphQLResult(response)) {\n                if (!response.data) {\n                    if (!response.errors?.[0]) {\n                        throw SAMError.create(\n                            SAMErrorCode.UNKNOWN,\n                            'No data or error returned from the query generationHistoryAssets'\n                        );\n                    }\n                    throw SAMError.createWithGraphQLError(response.errors?.[0]);\n                }\n\n                // if there are errors not related to the firefly-generations directory, we should throw an error\n                const error = response.errors?.find(err => !err.path?.includes('fireflyGenerationsDirectory'));\n\n                if (error) {\n                    throw SAMError.createWithGraphQLError(error);\n                }\n\n                // if there is no firefly-generations directory it likely means that the user has not yet generated any assets\n                // in this case, we should return an empty array\n                if (response.data.homeFolder.fireflyGenerationsDirectory === null) {\n                    return { homeFolder: { fireflyGenerationsDirectory: { generationAssetsConnection: { assets: [], pageInfo: { hasNextPage: false, endCursor: null } } } } };\n                }\n\n                return response.data;\n            }\n\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Resource.parse() received an unexpected response type: ' + response);\n        });\n\n        const results = await this.query<GenerationHistoryAssetsQuery>({\n            query: generationHistoryAssets,\n            variables: {\n                'relativePath': '/appassets/firefly-generations',\n                'first': options.first,\n                'after': options.after,\n                'filter': options.filter,\n                'orderBy': options.orderBy\n            }\n        }, resource);\n\n        return results.homeFolder.fireflyGenerationsDirectory!.generationAssetsConnection;\n    }\n\n    /**\n     * Retrieves a list of recently accessed assets based on the last access date.\n     * Uses GraphQL subscription to handle @defer fields properly.\n     * @param options - Arguments for pagination, filtering and sorting\n     * @returns A promise that resolves to the initial recent assets data\n     * @throws {SAMError} If there's an error with the GraphQL subscription\n     */\n    async recents(\n        options: PlsRecentsQueryVariables,\n        resource: Resource<PlsRecentsQuery> = new Resource<PlsRecentsQuery>(this._core),\n        processIncrementalData?: (incrementalData: PlsRecentsQuery) => void\n    ): Promise<PlsRecentsQuery> {\n        const { first, after, filter } = options;\n        const recentsQuery = await import('./queries/Recents');\n\n        return this.query<PlsRecentsQuery>({\n            query: recentsQuery.recents,\n            variables: { first, after, filter },\n        }, resource, processIncrementalData);\n    }\n\n    async updateLastAccessed(data: UpdateLabelMutationVariables): Promise<void> {\n        const client = await this._client();\n        const result = await client.mutate<UpdateLabelMutation>({\n            mutation: UPDATE_LAST_ACCESSED,\n            variables: data\n        }).catch((error: ApolloError) => {\n            throw SAMError.createWithApolloError(error);\n        });\n        if (!result.data?.updateLabel) {\n            if (!result.errors?.[0]) {\n                throw SAMError.create(\n                    SAMErrorCode.UNKNOWN,\n                    'No data or error returned from the query updateLastAccessed'\n                );\n            }\n            throw SAMError.createWithGraphQLError(result.errors?.[0]);\n        }\n\n    }\n}\n\n\n\n","import CachePersistor from './CachePersistor';\nexport default (function (options) {\n    var persistor = new CachePersistor(options);\n    return persistor.restore();\n});\n//# sourceMappingURL=persistCache.js.map","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport AdobeAsset from '../assets/AdobeAsset';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { GenerationHistoryAssetData } from '../interface/GenerationHistoryAssetModel';\nimport { GENERATION_HISTORY_MEDIA_TYPES } from '../interface/GenerationHistoryAssetModel';\nimport PropertyUpdater from '../core/PropertyUpdater';\n\ntype GenerationModelDisplayName = 'Imagen' | 'Veo' | 'GPT' | 'Clio' | 'Firefly' | 'Flux' | 'Pika' | 'Ideogram' | 'Runway' | 'Luma' | 'Topaz' | 'ElevenLabs' | 'Moonvalley';\n\n// maps internal generation model names to a display name to be used in 3rd party APIs\nconst GET_GENERATION_MODEL_DISPLAY_NAME: Record<string, GenerationModelDisplayName> = {\n    'imagen': 'Imagen',\n    'veo': 'Veo',\n    'gpt-4o-image': 'GPT',\n    'clio': 'Firefly',\n    'clio_v4': 'Firefly',\n    'clineto': 'Firefly',\n    'flux': 'Flux',\n    'fluxPro': 'Flux',\n    'fluxUltra': 'Flux',\n    'fluxBagel': 'Flux',\n    'fluxKontextPro': 'Flux',\n    'pika': 'Pika',\n    'ideogram': 'Ideogram',\n    'runway-gen4-image': 'Runway',\n    'runway': 'Runway',\n    'luma': 'Luma',\n    'topaz': 'Topaz',\n    'elevenlabs': 'ElevenLabs',\n    'moonvalley': 'Moonvalley',\n} as const;\n\nexport const getGenerationModelDisplayName = (model: string): GenerationModelDisplayName | string => {\n    return GET_GENERATION_MODEL_DISPLAY_NAME[model] ?? model;\n};\n\nexport const GenerationHistoryAssetUpdater = new ItemUpdater<AdobeAsset, Partial<GenerationHistoryAssetData>>({\n    localItemType: AdobeAsset,\n    remoteIdProperty: 'asset_id',\n    propertyUpdater: new PropertyUpdater({\n        '_appMetadata._data': {\n            name: 'applicationMetadata',\n            format: 'object_subset',\n            set: (parsedSource: any, dest: any) => {\n                const asset = dest as AdobeAsset;\n                // Melville will always return the complete set of application metadata, so it should use _setData instead of _mergeData\n                asset.appMetadata._setData(parsedSource);\n            }\n        },\n        _isFavorite: { name: 'isFavorite', format: 'boolean' },\n        _assetClass: { get: () => 'composite' },\n        _generationModelDisplayName: 'generationModelDisplayName',\n        _name: 'repo:name',\n        _size: { name: 'repo:size', format: 'number' },\n        _type: { name: 'type', format: 'string', choices: GENERATION_HISTORY_MEDIA_TYPES },\n        __links: { name: '_links', format: 'object' },\n        _created: { name: 'createdDate', format: 'date' },\n        _modified: { name: 'modifiedDate', format: 'date' },\n        _etag: 'composite_manifest_etag',\n        _path: 'asset_name_path',\n        _repositoryID: 'repo:repositoryId',\n        _createdBy: 'repo:createdBy',\n        _modifiedBy: 'repo:modifiedBy',\n    }),\n});\n","import { getGenerationModelDisplayName } from '@sam-js-src/generation-history/GenerationHistoryAsset';\nimport type { AdobeAssetUpdaterMetadata } from '../assets/AdobeAsset';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { parseEffectivePermissions, type Permission } from '../interface/AssetModel';\nimport { RelType, type IServiceLink } from '../interface/LinkUtils';\nimport type { AssetLinks, IEffectivePermissions, PermissionType } from '../interface/RepositoryModel';\nimport type { GQLEffectivePermissions } from './models/PLSModels';\n\nexport function parseGQLEffectivePermissions(permissions: GQLEffectivePermissions): Permission {\n    const toLowerCase = (resource: string[] | undefined) => resource?.map(p => p.toLowerCase() as PermissionType);\n\n    const rapiPermissions: IEffectivePermissions = {};\n    rapiPermissions['*'] = toLowerCase(permissions.default);\n    rapiPermissions[RelType.PRIMARY] = toLowerCase(permissions.primary);\n    rapiPermissions[RelType.AC_POLICY] = toLowerCase(permissions.aclPolicy);\n    rapiPermissions[RelType.DIRECTORY] = toLowerCase(permissions.directory);\n    rapiPermissions[RelType.APP_METADATA] = toLowerCase(permissions.applicationMetadata);\n    rapiPermissions[RelType.ANNOTATIONS] = toLowerCase(permissions.annotations);\n    return parseEffectivePermissions(rapiPermissions);\n}\n\n/**\n * Removes undefined properties from an object recursively\n */\nfunction filterUndefinedProperties<T extends Record<string, any>>(obj: T): Partial<T> {\n    const result: Partial<T> = {};\n\n    for (const [ key, value ] of Object.entries(obj)) {\n        if (value !== undefined) {\n            if (value && typeof value === 'object' && !Array.isArray(value)) {\n                const filtered = filterUndefinedProperties(value);\n                if (Object.keys(filtered).length > 0) {\n                    result[key as keyof T] = filtered as T[keyof T];\n                }\n            } else {\n                result[key as keyof T] = value;\n            }\n        }\n    }\n\n    return result;\n}\n\n/**\n * Converts GraphQL query response  to Adobe asset data format.\n * In the future, we will add additional transformations to this data.\n * We might use codegen to generate types from the schema.\n */\nexport default function convertGQLAssetToAdobeAssetData(data: any): AdobeAssetUpdaterMetadata {\n    if (!data) {\n        throw SAMError.create(SAMErrorCode.UNKNOWN, 'Asset data missing from GraphQL response');\n    }\n    const repoRepresentations = Object.fromEntries(\n        Object.entries(data.repo_representations ?? {}).filter(([ , value ]) => value === true)\n    );\n    const effectivePermissions = data.effectivePermissions && parseGQLEffectivePermissions(data.effectivePermissions);\n\n    const assetData = {\n        'dc:format': data.dc_format,\n        'repo:ancestors': data.repo_ancestors,\n        'repo:assetClass': data.repo_assetClass?.toLowerCase(),\n        'repo:assetType': data.repo_assetType,\n        'repo:assetSubType': data.repo_assetSubType,\n        'repo:representations': repoRepresentations,\n        'repo:assetId': data.repo_assetId,\n        'repo:etag': data.primary_etag,\n        'repo:createDate': data.repo_createDate,\n        'repo:createdBy': data.repo_createdBy?.id,\n        'repo:modifyDate': data.repo_modifyDate,\n        'repo:name': data.repo_name,\n        'repo:path': data.repo_path,\n        'repo:modifiedBy': data.repo_modifiedBy,\n        'repo:repositoryId': data.repository?.repo_repositoryId,\n        'repo:state': data.repo_state,\n        'repo:size': data.repo_size,\n        'repo:version': data.repo_version,\n        'storage:assignee': data.storage_assignee,\n        'storage:region': data.storage_region,\n        'storage:deviceCreateDate': data.storage_deviceCreateDate,\n        'storage:deviceModifyDate': data.storage_deviceModifyDate,\n        'tiff:imageLength': data.tiff_imageLength,\n        'tiff:imageWidth': data.tiff_imageWidth,\n        generationModelDisplayName: data.appMetadata?.am?.firefly && getGenerationModelDisplayName(data.appMetadata.am.firefly.generationModel?.name),\n        effectivePermission: effectivePermissions,\n        perUserMetadata: {\n            'shell:lastAccessDate': data.labels?.['lastAccessDate'],\n        },\n        _embedded: {\n            [RelType.APP_METADATA]: data.appMetadata?.am || {}\n        },\n        _links: {\n            [RelType.PRIMARY]: data.primaryLink as IServiceLink,\n            [RelType.BLOCK_INITIALIZE]: data.blockUploadLink as AssetLinks[RelType.BLOCK_INITIALIZE],\n            [RelType.DOWNLOAD]: data.blockDownloadLink as IServiceLink,\n            [RelType.RENDITION]: data.renditionLink as IServiceLink,\n            [RelType.PAGE]: data.pageLink as IServiceLink,\n        } as AssetLinks,\n        isFavorite: data.labels?.favorite?.isFavorite,\n        sharedViaInvite: !!data.sharingInfo?.sharedWithYou\n        // @TODO_GQL things we need to consider more about\n    };\n\n    return filterUndefinedProperties(assetData);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/* eslint-disable no-dupe-class-members */\nimport type AppMetadataResource from '../assets/AppMetadataResource';\nimport type EffectivePermissionsResource from '../assets/EffectivePermissionsResource';\nimport type PerUserMetadataResource from '../assets/PerUserMetadataResource';\nimport type RepoMetadataResource from '../assets/RepoMetadataResource';\nimport { RelType } from '../interface/LinkUtils';\nimport type { RepositoryMetadata } from '../interface/RepositoryModel';\nimport Resource from '../assets/Resource';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type { Asset, Maybe } from './generated/types';\nimport convertGQLAssetToAdobeAssetData from './convertGQLAssetToAdobeAssetData';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\n\nexport interface IAssetResources {\n    repoMetadataResource?: RepoMetadataResource;\n    appMetadataResource?: AppMetadataResource;\n    effectivePermissionsResource?: EffectivePermissionsResource;\n    perUserMetadataResource?: PerUserMetadataResource;\n}\n\n/**\n * A resource that can store and represent a single GraphQL result,\n * where the result may have Asset metadata within the query.\n * Methods on this Resource allow consumers to extract an AdobeAsset\n * from the result, with the appropriate data piped into the asset.\n */\nexport default class GraphQLAssetResource<TQuery> extends Resource {\n    resultHandlers: Array<(result: TQuery) => void> = [];\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n    ) {\n        super(_core, {\n            onChange: async (result) => {\n                if (!result) {\n                    return;\n                }\n                for (const onResult of this.resultHandlers) {\n                    onResult(result);\n                }\n            },\n        });\n    }\n\n    /**\n     * Adds a result handler callback that will be invoked when query results are available.\n     * If data is already present, the handler will be called immediately with the current data.\n     *\n     * @param onResult - Callback function that receives the query result data\n     */\n    addResultHandler(onResult: (result: TQuery) => void) {\n        this.resultHandlers.push(onResult);\n        if (this.data) {\n            onResult(this.data);\n        }\n    }\n\n    /**\n     * Adds an asset from a GraphQL query result by applying a transformation function.\n     *\n     * @param assetFromResult - A function that extracts asset information from the GraphQL query result\n     * @param asset - Optional existing AdobeAsset to update with the extracted data\n     * @returns A Promise that resolves to an AdobeAsset with the applied data\n     * @throws {SAMError} When the asset extraction fails or when applying data to the asset fails\n     */\n    addAssetFromResult(assetFromResult: (result: TQuery) => Maybe<Asset> | undefined, asset?: AdobeAsset): Promise<AdobeAsset> {\n        return new Promise((resolve, reject) => {\n            this.addResultHandler((result: TQuery) => {\n                const maybeAssetInfo = assetFromResult(result);\n                if (maybeAssetInfo) {\n                    this._applyDataToAsset(maybeAssetInfo, asset)\n                        .then(resolve)\n                        .catch(error => {\n                            reject(SAMError.create(SAMErrorCode.UNKNOWN, 'Error applying asset', error));\n                        });\n                } else {\n                    reject(SAMError.create(SAMErrorCode.UNKNOWN, 'Asset not found on GraphQL query'));\n                }\n            });\n        });\n    }\n\n    /**\n     * Adds asset resources from a GraphQL query result by applying a transformation function\n     * and updating the provided subresources (such as repoMetadata, appMetadata, etc).\n     *\n     * @param assetFromResult - A function that extracts an Asset from the query result\n     * @param subresources - The asset resources object to be updated with data from the extracted asset\n     *\n     * @throws {SAMError} With code UNKNOWN if there's an error applying asset resources or if no asset is found in the query result\n     */\n    addAssetResourcesFromResult(assetFromResult: (result: TQuery) => Maybe<Asset> | undefined, subresources: IAssetResources): Promise<void> {\n        return new Promise((resolve, reject) => {\n            this.addResultHandler(async (result: TQuery) => {\n                const maybeAssetInfo = assetFromResult(result);\n                if (maybeAssetInfo) {\n                    try {\n                        resolve(await this._applyDataToAssetResources(maybeAssetInfo, subresources));\n                    } catch (error) {\n                        reject(SAMError.create(SAMErrorCode.UNKNOWN, 'Error applying asset resources'));\n                    }\n                } else {\n                    reject(SAMError.create(SAMErrorCode.UNKNOWN, 'Asset not found on GraphQL query'));\n                }\n            });\n        });\n    }\n\n    private async _applyDataToAssetResources(data: Asset, subresources: IAssetResources): Promise<void> {\n        const {\n            effectivePermission,\n            perUserMetadata,\n            _embedded,\n            ...adobeAssetData\n        } = convertGQLAssetToAdobeAssetData(data) ?? {};\n        const appMetadata = _embedded?.[RelType.APP_METADATA] ?? {};\n        await Promise.all([\n            subresources?.repoMetadataResource?._setData(adobeAssetData as RepositoryMetadata),\n            subresources?.effectivePermissionsResource?._setData(effectivePermission!),\n            subresources?.appMetadataResource?._setData(appMetadata),\n            subresources?.perUserMetadataResource?._setData(perUserMetadata!),\n        ]);\n    }\n\n    private async _applyDataToAsset(data: Asset, asset?: AdobeAsset): Promise<AdobeAsset> {\n        const {\n            effectivePermission,\n            perUserMetadata,\n            _embedded,\n            ...adobeAssetData\n        } = convertGQLAssetToAdobeAssetData(data) ?? {};\n        const appMetadata = _embedded?.[RelType.APP_METADATA] ?? {};\n\n        if (asset) {\n            asset._handleResourceUpdates({\n                effectivePermission,\n                perUserMetadata,\n                repoMetadata: adobeAssetData as RepositoryMetadata,\n                appMetadata\n            });\n            return asset;\n        } else {\n            const pool = this._core._getAssetPool();\n            const session = pool.createMutationSession();\n            const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ adobeAssetData ]);\n            const asset = this._core._adobeAssetFactory.assetFromRepoMetadata({\n                session,\n                updaters,\n                repoMetadata: adobeAssetData as RepositoryMetadata,\n                permissions: effectivePermission,\n                appMetadata,\n                perUserMetadata,\n            });\n            session.commit();\n            return asset;\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { AssetListingHints, AssetLoadHints } from '../interface/AssetModel';\nimport type { AdobeAssetUpdaterMetadata } from '../assets/AdobeAsset';\nimport GQLInterface from './GQLInterface';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport type {\n    IdQuery,\n    PathQuery,\n    RelativePathQuery } from './models/AssetSubgraphModel';\nimport {\n    OrderFieldToGQLOrderBy,\n    type AssetListConnectionArgs,\n} from './models/AssetSubgraphModel';\nimport { synchronized } from '../core/decorators';\nimport type AdobeAssetOrder from '../assets/AdobeAssetOrder';\nimport AdobeAssetFilter from '../assets/AdobeAssetFilter';\nimport type { ILoadOptions } from '../core/ItemList';\nimport type { PLSListResponse } from './models/PLSModels';\nimport type {\n    Asset,\n    AssetChildConnection,\n    AssetChildEdge,\n    AssetFilter,\n    OrderByInput,\n    PageInfo,\n    PlsRecentsQuery,\n    PlsRecentsQueryVariables,\n    Query,\n    SharedWithYouListAssetListConnectionArgs,\n    SharedWithYouQuery\n} from './generated/types';\nimport { firstInSet, isDeepEqual } from '../core/ObjectUtils';\nimport convertGQLAssetToAdobeAssetData from './convertGQLAssetToAdobeAssetData';\nimport Resource from '../assets/Resource';\nimport GraphQLAssetResource, { type IAssetResources } from './GraphQLAssetResource';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type AdobeAsset from '../assets/AdobeAsset';\n\nexport type ListData = {\n    children: AdobeAssetUpdaterMetadata[],\n    pageInfo: PageInfo,\n    ancestors: string[] | undefined,\n    resource?: Resource<ListData>\n}\n\nexport type GetAssetByPathResult = {\n    homeFolder?: AdobeAsset | null;\n    asset: AdobeAsset | null;\n}\n\ntype FavoritesQuery = Pick<Query, 'favorites'>;\n// Manually defining the type for the generationHistoryAssets query as it is not generated by the codegen and contains field aliases\n// Codegen allows for generating types using the string passed to the gql tag, but this needs to be configured\nexport type GenerationHistoryAssetsQuery = {\n    homeFolder: {\n        id: string;\n        fireflyGenerationsDirectory?: {\n            id: string;\n            generationAssetsConnection: {\n                pageInfo: {\n                    hasNextPage: boolean;\n                    endCursor: string | null;\n                };\n                assets: AssetChildEdge[];\n            }\n        }\n    }\n}\n\nexport default class GQLManager implements ISAMObject {\n    private _gqlInterface: GQLInterface = new GQLInterface(this._core);\n\n    private _listData: Map<string, ListData> = new Map();\n\n    constructor(\n        readonly _core: ISAMCorePrivate\n    ) {}\n\n    async initialize() {\n        await this._gqlInterface.initialize();\n    }\n\n    // if loadHints.listingHints is provided, then we need to store the children data in the manager\n    private _handleListingHints(asset: AdobeAsset, listingHints: AssetLoadHints['listingHints'], assetByPath: Asset) {\n        for (let i = 0; listingHints && i < listingHints?.length; i++) {\n            const listItem = (assetByPath as any)[`list${i + 1}`] as AssetChildConnection;\n            const hash = this.generateDirectoryLoaderHash({\n                assetId: asset.id,\n                filter: listingHints[i].filter,\n                order: listingHints[i].order,\n                loadOptions: listingHints[i].loadOptions\n            });\n\n            const existingData = this._listData.get(hash);\n            const newData: ListData = {\n                children: listItem.edges.map((child) => convertGQLAssetToAdobeAssetData(child.node)),\n                pageInfo: listItem.pageInfo,\n                ancestors: asset.ancestorIDs,\n                resource: existingData?.resource\n            };\n            this._listData.set(hash, newData);\n            // If this listing has already been requested (we have its ItemLoaderState resource),\n            // changed data here will trigger the list to recompute itself with the new data,\n            newData.resource?._setData(newData, {\n                changed: !isDeepEqual(existingData, newData, true)\n            });\n        }\n    }\n    /**\n     * Get an asset by path.\n     * @param assetPath - The path of the asset to get.\n     * @param repositoryId - The repository ID of the asset to get(optional). If not provided, the asset will be fetched relative to the user's home repository.\n     * @returns The asset data and the home folder data(if repositoryId is not provided).\n     */\n    @synchronized\n    async getAssetByPath(assetPath: string, repositoryId?: string, loadHints?: AssetLoadHints): Promise<GetAssetByPathResult> {\n        let homeFolder: AdobeAsset | undefined;\n        let asset: AdobeAsset;\n\n        if (!repositoryId) {\n            const resource = new GraphQLAssetResource<RelativePathQuery>(this._core);\n            await this._gqlInterface.getAssetByRelativePath(assetPath, loadHints, resource);\n            homeFolder = await resource.addAssetFromResult(result => result.resolveUserHome);\n            asset = await resource.addAssetFromResult(result => result.resolveUserHome.assetByRelativePath);\n            resource.addResultHandler((result) => {\n                this._handleListingHints(asset, loadHints?.listingHints, result.resolveUserHome.assetByRelativePath!);\n            });\n        } else {\n            const resource = new GraphQLAssetResource<PathQuery>(this._core);\n            await this._gqlInterface.getAssetByPath(assetPath, repositoryId, loadHints, resource);\n            asset = await resource.addAssetFromResult(result => result.resolveAssetByPath);\n            resource.addResultHandler((result) => {\n                this._handleListingHints(asset, loadHints?.listingHints, result.resolveAssetByPath!);\n            });\n        }\n        return {\n            homeFolder,\n            asset\n        };\n    }\n\n    @synchronized\n    async getAssetById(assetId: string) {\n        const resource = new GraphQLAssetResource<IdQuery>(this._core);\n        await this._gqlInterface.getAssetById(assetId, resource);\n        return resource.addAssetFromResult(result => result.resolveAssetById);\n    }\n\n    async getGenerationHistoryAssets(options: { first: number, after?: string, orderBy?: OrderByInput[], filter?: AssetFilter }, resource?: Resource<GenerationHistoryAssetsQuery>,)  {\n        const { assets, pageInfo } = await this._gqlInterface.getGenerationHistoryAssets(options, resource);\n\n        return {\n            items: assets.map((asset: any) => convertGQLAssetToAdobeAssetData(asset.node)),\n            pageInfo\n        };\n    }\n\n    @synchronized\n    async getAssetResourcesById(assetId: string, assetResources?: IAssetResources) {\n        const resource = new GraphQLAssetResource<IdQuery>(this._core);\n        await this._gqlInterface.getAssetById(assetId, resource);\n        if (assetResources) {\n            await resource.addAssetResourcesFromResult(result => result.resolveAssetById, assetResources);\n        }\n    }\n\n    @synchronized\n    async getFavorites(\n        args: AssetListConnectionArgs,\n        resource?: Resource<FavoritesQuery>,\n        processIncrementalData?: (incrementalData: FavoritesQuery) => void\n    ): Promise<PLSListResponse> {\n        const {\n            favorites: {\n                assetListId,\n                assetListConnection: { pageInfo, edges },\n            },\n        } = await this._gqlInterface.getFavorites(args, resource, processIncrementalData);\n\n        const favorites = edges.map((edge: any) => convertGQLAssetToAdobeAssetData(edge.node));\n        return { items: favorites, pageInfo, assetListId };\n    }\n\n    async getSharedWithYou(\n        options: SharedWithYouListAssetListConnectionArgs,\n        resource?: Resource<SharedWithYouQuery>,\n        processIncrementalData?: (incrementalData: SharedWithYouQuery) => void\n    ): Promise<PLSListResponse> {\n        const {\n            sharedWithYou: {\n                assetListId,\n                assetListConnection: { pageInfo, edges },\n            },\n        } = await this._gqlInterface.getSharedWithYou(options, resource, processIncrementalData);\n\n        const sharedWithYouAssets = edges.map((edge: any) => convertGQLAssetToAdobeAssetData(edge.node));\n        return { items: sharedWithYouAssets, pageInfo, assetListId };\n    }\n\n    async recents(\n        options: PlsRecentsQueryVariables,\n        resource?: Resource<PlsRecentsQuery>,\n        processIncrementalData?: (incrementalData: PlsRecentsQuery) => void\n    ): Promise<PLSListResponse> {\n        const {\n            recents: {\n                assetListId,\n                assetListConnection: { pageInfo, edges },\n            },\n        } = await this._gqlInterface.recents(options, resource, processIncrementalData);\n\n        const recents = edges.map((edge: any) => convertGQLAssetToAdobeAssetData(edge.node));\n        return { items: recents, pageInfo, assetListId };\n    }\n\n    async setFavorite(assetId: string, isFavorite: boolean): Promise<void> {\n        await this._gqlInterface.setFavorite(assetId, isFavorite);\n    }\n\n    private generateDirectoryLoaderHash({\n        assetId,\n        order,\n        filter = new AdobeAssetFilter(),\n        loadOptions\n    }: {\n        assetId: string,\n        order: AdobeAssetOrder,\n        filter?: AdobeAssetFilter,\n        loadOptions?: ILoadOptions\n    }) {\n        let hash = assetId + ':' + order.hash + ':' + filter.hash;\n        if (loadOptions?.limit) {\n            hash += 'limit:' + loadOptions.limit;\n        }\n        return hash;\n    }\n\n    async getChildren(\n        assetId: string,\n        options: AssetListingHints & { after?: string },\n        resource: Resource = new Resource<unknown>(this._core)\n    ): Promise<ListData> {\n        const { filter, order, loadOptions } = options;\n        const hash = this.generateDirectoryLoaderHash({\n            assetId,\n            filter,\n            order,\n            loadOptions\n        });\n\n        const listData = this._listData.get(hash);\n        if (listData) {\n            if (listData.resource) {\n                // If we already have a resource for this list, we've already used the list data\n                // to fill out a directory page, so we should discard the cached list data and request anew.\n                this._listData.delete(hash);\n            } else {\n                // Otherwise, we can return the list data.\n                // We'll store the resource so that if the data changes (e.g. from an outdated cache),\n                // we can tell the list to recompute.\n                listData.resource = resource;\n                return listData;\n            }\n        }\n\n        const gqlFilter: AssetFilter = {\n            dc_format: filter?.mediaTypes?.size ? [ ...filter.mediaTypes ] : undefined\n        };\n        if (filter?.excludeAssetTypes?.size) {\n            // Always do server-side exclude filtering for at least one excluded assetType, the rest can\n            // be handled client-side.\n            gqlFilter.assetType = { neq: firstInSet(filter.excludeAssetTypes) };\n        } else if (filter?.assetTypes?.size === 1) {\n            // Only do server-side filtering if there is exactly one assetType, otherwise rely on\n            // client-side filtering.\n            gqlFilter.assetType = { eq: firstInSet(filter.assetTypes) };\n        }\n        if (filter?.assetSubTypes?.size === 1) {\n            gqlFilter.assetSubType = { eq: firstInSet(filter.assetSubTypes) };\n        }\n\n        const data = await this._gqlInterface.getChildren(assetId, {\n            first: options.loadOptions?.limit ?? 20,\n            orderBy: [\n                {\n                    field: OrderFieldToGQLOrderBy[options.order.field],\n                    direction: options.order.direction.toUpperCase() as 'ASCENDING' | 'DESCENDING'\n                }\n            ],\n            filter: Object.values(gqlFilter).some(val => val) ? gqlFilter : undefined,\n            after: options.after\n        }, resource);\n\n        if (!data.resolveAssetById?.childrenConnection) {\n            throw SAMError.create(SAMErrorCode.UNKNOWN, 'childrenConnection not present');\n        }\n        const { edges, pageInfo } = data.resolveAssetById.childrenConnection;\n\n        return {\n            children: edges.map((edge: any) => convertGQLAssetToAdobeAssetData(edge.node)),\n            pageInfo,\n            ancestors: data.resolveAssetById.repo_ancestors,\n            resource\n        };\n    }\n\n    async updateLastAccessed(assetId: string, lastAccessDate: string | null): Promise<void> {\n        await this._gqlInterface.updateLastAccessed({\n            assetId,\n            input: {\n                lastAccessDate\n            }\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IServiceLink, LinkRequirements } from './LinkUtils';\nimport { RelType } from './LinkUtils';\n\nexport type IProjectSpaceSelector =\n    | 'BOOKMARKED'\n    | 'CHILDREN'\n    | 'CONTRIBUTOR_COUNT'\n    | 'FULL'\n    | 'MINIMUM'\n    | 'REPOSITORY_NAME'\n    | 'ROLE';\n\nexport interface IProjectsTeamLinks {\n    [RelType.PRIMARY]: IServiceLink,\n    [RelType.WORKSPACES_CREATE]: IServiceLink,\n    [RelType.WORKSPACES_PAGE]: IServiceLink,\n    [RelType.TEAMS_DISCARD]: IServiceLink,\n    [RelType.TEAMS_RESTORE]: IServiceLink,\n    [RelType.TEAMS_RENAME]: IServiceLink,\n    [RelType.TEAMS_PROPERTIES]: IServiceLink,\n    [RelType.TEAMS_PRIMARY]: IServiceLink\n}\n\nexport interface IProjectsOrgRepository {\n    repositoryId: string;\n}\n\nexport interface IProjectsTeam {\n    repositoryId: string;\n    repositoryName: string;\n    repositoryOwner: {\n        id: string,\n        type: string,\n        email?: string\n    };\n    collaboratorRole: string;\n    _links: IProjectsTeamLinks;\n    id: string;\n    name: string;\n    state: string;\n    createDate: string;\n    createdBy: string;\n    description?: string;\n    role: string;\n}\n\nexport type IProjectsTeamState =\n    | 'active'\n    | 'discarded';\n\nexport type IProjectsTeamsOrderBy =\n    | 'name'\n    | 'createDate';\n\nexport interface IProjectsTeamsLinks {\n    [RelType.TEAMS_CREATE]: IServiceLink,\n    [RelType.GENERIC_PAGE]: IServiceLink\n}\n\nexport interface IProjectsSpaceLinks {\n    [RelType.PRIMARY]: IServiceLink,\n    [RelType.DISCARD]: IServiceLink,\n    [RelType.RESTORE]: IServiceLink,\n    [RelType.WORKSPACES_PRIMARY]: IServiceLink\n}\n\n// Child name 'libraries'\nexport interface IProjectSpaceLibrariesChildLinks {\n    [RelType.PROJECTS_LIBRARIES_PAGE]: IServiceLink,\n    [RelType.PROJECTS_LIBRARIES_CREATE]: IServiceLink,\n    [RelType.PROJECTS_LIBRARIES_BATCH]: IServiceLink,\n}\n\n// Child name 'outputs'\nexport interface IProjectSpaceOutputsChildLinks {\n    [RelType.PRIMARY]: IServiceLink,\n    [RelType.PAGE]: IServiceLink,\n}\n\n// Child name 'working_files'\nexport interface IProjectSpaceWorkingFilesChildLinks {\n    [RelType.PRIMARY]: IServiceLink,\n    [RelType.PAGE]: IServiceLink,\n    [RelType.CREATE]: IServiceLink\n}\n\nexport type IProjectsSpaceChildLinks  = IProjectSpaceLibrariesChildLinks | IProjectSpaceOutputsChildLinks | IProjectSpaceWorkingFilesChildLinks;\n\nexport interface IProjectsSpacesLinks {\n    [RelType.GENERIC_PAGE]: IServiceLink;\n}\n\nexport interface IWorkspacesIndexLinks {\n    [RelType.WORKSPACES_CONTEXT]: IServiceLink,\n    [RelType.TEAMS_PAGE]: IServiceLink,\n    [RelType.WORKSPACES_PRIMARY]: IServiceLink,\n    [RelType.WORKSPACES_PAGE]: IServiceLink,\n    [RelType.REPOSITORIES_PAGE]: IServiceLink,\n    [RelType.TEAMS_CREATE]: IServiceLink,\n    [RelType.TEAM_PROVISION]: IServiceLink,\n    [RelType.WORKSPACES_BOOKMARKS_BATCH]: IServiceLink\n}\n\nexport const WORKSPACE_INDEX_LINKS: LinkRequirements = {\n    [RelType.WORKSPACES_CONTEXT]: [],\n    [RelType.TEAMS_PAGE]: [ 'start', 'limit' ],\n    [RelType.WORKSPACES_PRIMARY]: [ 'id', 'selector' ],\n    [RelType.WORKSPACES_PAGE]: [ 'orderBy', 'start', 'limit', 'teamId', 'bookmarkFilter', 'teamAccess' ],\n    [RelType.REPOSITORIES_PAGE]: [],\n    [RelType.TEAMS_CREATE]: [],\n    [RelType.TEAM_PROVISION]: [],\n    [RelType.WORKSPACES_BOOKMARKS_BATCH]: []\n};\n\nexport interface IProjectsPageSpec {\n    start: number;\n    limit: number;\n    totalLimit: number;\n}\n\nexport interface IProjectsOrgRepositoriesResponse {\n    repositories: IProjectsOrgRepository[];\n}\n\nexport interface IProjectsTeamsResponse {\n    teams: IProjectsTeam[],\n    pageSpec: IProjectsPageSpec,\n    _links: IProjectsTeamsLinks\n}\n\nexport type IProjectSpaceAccess =\n    | 'private'\n    | 'team';\n\nexport type IProjectsSpaceChildName =\n    | 'canvases'\n    | 'libraries'\n    | 'outputs'\n    | 'resources'\n    | 'working_files';\n\nexport type IProjectsSpaceState =\n    | 'active'\n    | 'archived'\n    | 'in_progress';\n\n\nexport interface IProjectsSpaceChild {\n    id: string;\n    name: IProjectsSpaceChildName;\n    _links: IProjectsSpaceChildLinks;\n}\n\nexport interface IProjectsSpace {\n    etag: string;\n    access: IProjectSpaceAccess;\n    description: string;\n    children: IProjectsSpaceChild[];\n    state: IProjectsSpaceState;\n    thumbnail: string;\n\n    directoryType: string;\n    pathName: string;\n\n    createdDate: string;\n    modifiedDate: string;\n\n    isProject: boolean;\n\n    role: string;\n    contributorCount: number;\n    version: number;\n    repositoryId: string;\n    repositoryName: string;\n    teamId: string;\n    teamName: string;\n    bookmarked: boolean;\n    color: string;\n\n    _links: IProjectsSpaceLinks;\n    id: string;\n    name: string;\n}\n\nexport interface IProjectsSpacesResponse {\n    projects: IProjectsSpace[];\n    pageSpec: IProjectsPageSpec,\n    _links: IProjectsSpacesLinks\n}\n\nexport interface IProjectsTeamPropertiesResponse {\n    description?: string;\n}\n\nexport type IProjectsSpaceOrderBy =\n    | 'name'\n    | 'createdDate';\n\nexport interface IProjectsSpaceResponse extends IProjectsSpace {\n}\n\nexport interface IWorkspacesIndexResponse {\n    _links: IWorkspacesIndexLinks\n}\n\nexport interface IProjectsTeamCreateQuery extends IProjectsTeamCreateData {\n    repositoryId: string;\n}\n\nexport interface IProjectsTeamCreateData {\n    name: string;\n}\n\nexport interface IProjectsTeamCreateResponse extends IProjectsTeam {\n}\n\nexport interface IProjectsTeamProvisionResponse extends IProjectsTeam {\n}\n\nexport type IProjectsBookmarkOpType = 'ADD' | 'REMOVE';\nexport interface IProjectsBookmarkOpsData {\n    op: IProjectsBookmarkOpType;\n    items: {\n        projectUrn: string;\n        userId: string;\n    }[];\n}\nexport interface IProjectsBookmarkBatchResponse {\n    responses: {\n        status: number;\n        request: {\n            projectUrn: string;\n        };\n    }[];\n}\n\nexport type IProjectCreateDataAccess =\n    | 'private'\n    | 'team';\n\nexport interface IProjectsCreateData {\n    name: string;\n    description: string;\n    color: string;\n    access: IProjectCreateDataAccess;\n}\n\nexport interface IProjectsCreateQuery extends IProjectsCreateData {\n    parentId: string;\n}\n\nexport interface IProjectsSpaceContextQuery {\n    'repo:assetId': string;\n}\n\nexport type IProjectsSpaceContextRequest = IProjectsSpaceContextQuery[];\n\nexport interface IProjectsSpaceContextResponseItem {\n    body: IProjectsSpace,\n    request: IProjectsSpaceContextQuery,\n    status: number;\n}\n\nexport interface IProjectsSpaceContextResponse {\n    _links: {},\n    responses: IProjectsSpaceContextResponseItem[]\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type jsonpatch from 'json-patch';\n\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport InterfaceBase from './InterfaceBase';\nimport type {\n    IProjectsTeamsResponse,\n    IProjectsSpacesResponse,\n    IProjectsSpaceOrderBy,\n    IProjectsSpaceResponse,\n    IProjectsSpaceLinks,\n    IProjectsTeamCreateResponse,\n    IWorkspacesIndexLinks,\n    IProjectsTeamsOrderBy,\n    IWorkspacesIndexResponse,\n    IProjectsTeamProvisionResponse,\n    IProjectsBookmarkOpsData,\n    IProjectsSpaceContextRequest,\n    IProjectsSpaceContextResponse,\n    IProjectsBookmarkBatchResponse,\n    IProjectsOrgRepositoriesResponse,\n    IProjectSpaceSelector,\n    IProjectsTeamLinks,\n    IProjectsCreateQuery,\n    IProjectsTeamCreateQuery,\n    IProjectsTeamState,\n    IProjectsTeamPropertiesResponse\n} from './WorkspacesModel';\nimport {\n    WORKSPACE_INDEX_LINKS\n} from './WorkspacesModel';\nimport type {\n    HeaderMap } from './LinkUtils';\nimport {\n    getURLFromLinks,\n    JSON_MIME_TYPE,\n    JSON_PATCH_MIME_TYPE,\n    RelType,\n    validateLinks\n} from './LinkUtils';\nimport { cache, key } from '../core/decorators';\n\n// Team provisioning can return both 200 and 201 depending on if\n// the user already had the team created or not. We check for this ahead of time,\n// but there is a chance the user has a pending or simultaneous call to provision\n// the team from a different tab or application. In SAM we don't actually\n// care about 200 or 201, but we want to make sure they are both valid codes.\nconst TEAM_PROVISION_SUCCESS_CODES = [ 200, 201 ];\n\nexport const SPACE_FULL_SELECTOR: IProjectSpaceSelector[] = [ 'FULL' ];\n\ntype IPageOptions = {\n    start: number;\n    limit: number;\n}\n\nexport interface TeamsListingOptions extends IListingOptions<IProjectsTeamsOrderBy> {\n    state?: IProjectsTeamState;\n    nameContains?: string;\n}\n\ninterface IListingOptions<IOrderField> extends IPageOptions {\n    orderDirection: IOrderDirection;\n    orderBy: IOrderField;\n}\n\nexport interface SpacesListingOptions extends IListingOptions<IProjectsSpaceOrderBy> {\n    bookmarked: boolean;\n    teamID?: string;\n    teamAccess?: boolean;\n}\n\nconst DefaultTeamListingOptions: TeamsListingOptions = {\n    start: 0,\n    limit: 0,\n    orderDirection: 'ascending',\n    orderBy: 'name'\n};\n\nconst DefaultSpacesListingOptions: SpacesListingOptions = {\n    orderDirection: 'ascending',\n    orderBy: 'name',\n    bookmarked: false,\n    teamID: undefined,\n    start: 0,\n    limit: 0\n};\n\nfunction getDefaultOptions<OptionTypes>(Defaults: OptionTypes, options?: Partial<OptionTypes>): OptionTypes {\n    return Object.assign({}, Defaults, options);\n}\n\nfunction getDirectionValue<IOrderField>(userOptions: IListingOptions<IOrderField>) {\n    const directionFlag = userOptions.orderDirection === 'ascending' ? '+' : '-';\n    return directionFlag + userOptions.orderBy;\n}\n\nfunction createPageTemplate(options: IPageOptions) {\n    const templateValues: any = {};\n    if (options.start) {\n        templateValues.start = options.start;\n    }\n    if (options.limit) {\n        templateValues.limit = options.limit;\n    }\n    return templateValues;\n}\n\nexport function getTeamListingPath(links: IWorkspacesIndexLinks, options?: Partial<TeamsListingOptions>): string {\n    const userOptions = getDefaultOptions(DefaultTeamListingOptions, options);\n    const templateValues = createPageTemplate(userOptions);\n    templateValues.orderBy = getDirectionValue(userOptions);\n    templateValues.nameContains = userOptions.nameContains;\n    templateValues.state = userOptions.state;\n    return getURLFromLinks(links, RelType.TEAMS_PAGE, templateValues);\n}\n\nexport function getSpacesListingPath(links: IWorkspacesIndexLinks, options?: Partial<SpacesListingOptions>): string {\n    const userOptions = getDefaultOptions(DefaultSpacesListingOptions, options);\n    const templateValues: any = createPageTemplate(userOptions);\n    templateValues.orderBy = getDirectionValue(userOptions);\n    // The service sets bookmarkFilter to \"true\" by default, so pass \"false\" if bookmarked is false or undefined.\n    if (!userOptions.bookmarked) {\n        templateValues.bookmarkFilter = false;\n    }\n    // The only value that is implemented by the server is teamAccess=undefined or teamAccess=false.\n    // teamAccess=undefined -> all spaces are returned\n    // teamAccess=false -> returns only the spaces that are from teams the user is not part of.\n    if (userOptions.teamAccess === false) {\n        templateValues.teamAccess = false;\n    }\n    const { teamID } = userOptions;\n    if (teamID) {\n        templateValues.teamId = teamID;\n    }\n    return getURLFromLinks(links, RelType.WORKSPACES_PAGE, templateValues);\n}\n\nfunction validateRequiredProjectLinks(links: any) {\n    return validateLinks(links, WORKSPACE_INDEX_LINKS);\n}\n\nexport default class WorkspacesInterface extends InterfaceBase {\n\n    private _getHeaders(contentType?: string): HeaderMap {\n        const headers: HeaderMap = {\n            'x-service-features': 'CanvasMigration',\n            // NOTE: [SAM-1222] disabling cache because /projects/{spaceId} sets an etag header that\n            //      does not change when the user's bookmark preference changes, causing browsers to\n            //      automatically add the etag header on requests and get the cached value of the\n            //      bookmark field rather than the actual value.\n            'Cache-Control': 'no-cache'\n        };\n        if (contentType) {\n            headers['Content-Type'] = contentType;\n        }\n        return headers;\n    }\n\n    @cache(validateRequiredProjectLinks)\n    private async _discoverLinks(@key rootHref: string): Promise<IWorkspacesIndexLinks> {\n        const response: IWorkspacesIndexResponse = await this._getResponse(rootHref, this._getHeaders());\n        return response._links;\n    }\n\n    private _getEndpointHref(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.PROJECTS_HOST}${endpoint}`;\n    }\n\n    async discoverLinks(): Promise<IWorkspacesIndexLinks> {\n        return this._discoverLinks(this._getEndpointHref(`/api/v2/index`));\n    }\n\n    async getTeams(options?: Partial<TeamsListingOptions>): Promise<IProjectsTeamsResponse> {\n        const links = await this.discoverLinks();\n        const url = getTeamListingPath(links, options);\n        return await this._getResponse(url, this._getHeaders());\n    }\n\n    /**\n     * Get repositories where user can create CC Team\n     */\n    async getOrgRepositories(): Promise<IProjectsOrgRepositoriesResponse> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(links, RelType.REPOSITORIES_PAGE, {});\n        return await this._getResponse(url, this._getHeaders());\n    }\n\n    /**\n     * Create a team under /content/assets folder.\n     */\n    async createTeam(data: IProjectsTeamCreateQuery): Promise<IProjectsTeamCreateResponse> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(links, RelType.TEAMS_CREATE, {});\n        const response = await this._doPost(\n            url,\n            this._getHeaders(JSON_MIME_TYPE),\n            JSON.stringify(data));\n        return response.json();\n    }\n\n    /**\n     * Permanently Delete a Team\n     */\n    async permanentlyDeleteTeam(links: IProjectsTeamLinks): Promise<void> {\n        const url = getURLFromLinks(links, RelType.TEAMS_PRIMARY);\n        await this._doDelete(url, this._getHeaders(), [ 204 ]);\n    }\n\n    /**\n     * Archive/Discard Team\n     */\n    async archiveTeam(links: IProjectsTeamLinks): Promise<void> {\n        const url = getURLFromLinks(links, RelType.TEAMS_DISCARD);\n        await this._doPost(url, this._getHeaders(), undefined, [ 204 ]);\n    }\n\n    /**\n     * Restore Team.\n     */\n    async restoreTeam(teamLinks: IProjectsTeamLinks): Promise<void> {\n        const url = getURLFromLinks(teamLinks, RelType.TEAMS_RESTORE);\n        await this._doPost(url, this._getHeaders(), undefined, [ 204 ]);\n    }\n\n    /**\n     * Rename Team.\n     */\n    async renameTeam(teamLinks: IProjectsTeamLinks, name: string): Promise<void> {\n        const url = getURLFromLinks(teamLinks, RelType.TEAMS_RENAME);\n        await this._doPost(url, this._getHeaders(JSON_MIME_TYPE), JSON.stringify({ name }), [ 204 ]);\n    }\n\n    /**\n     * Patch a Team\n     */\n    async patchTeam(teamLinks: IProjectsTeamLinks, data: jsonpatch.OpPatch[]) {\n        const url = getURLFromLinks(teamLinks, RelType.TEAMS_PROPERTIES);\n        await this._doPatch(url, { ...this._getHeaders(JSON_PATCH_MIME_TYPE), 'If-Match': '*' }, JSON.stringify(data), [ 204 ]);\n    }\n\n    /**\n     * Fetches Properties for a team.\n     */\n    async getTeamProperties(teamLinks: IProjectsTeamLinks): Promise<IProjectsTeamPropertiesResponse> {\n        const url = getURLFromLinks(teamLinks, RelType.TEAMS_PROPERTIES);\n        return await this._getResponse(url, this._getHeaders());\n    }\n\n    /**\n     * Provisions a Team folder within User storage for a Type 1 user only. The provisioned team name is in format:\n     * \"Team {{USER_FIRST_NAME}}\" depending on the localization of the requesting user.\n     */\n    async provisionTeam(): Promise<IProjectsTeamProvisionResponse> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(links, RelType.TEAM_PROVISION, {});\n        const response = await this._doPost(url, this._getHeaders(), undefined, TEAM_PROVISION_SUCCESS_CODES);\n        return response.json();\n    }\n\n    async getSpaces(options?: Partial<SpacesListingOptions>): Promise<IProjectsSpacesResponse> {\n        const links = await this.discoverLinks();\n        const url = getSpacesListingPath(links, options);\n        return await this._getResponse(url, this._getHeaders());\n    }\n\n    async getSpace(id: string, selector: IProjectSpaceSelector[] = SPACE_FULL_SELECTOR): Promise<IProjectsSpaceResponse> {\n        const links = await this.discoverLinks();\n        const spaceLink = getURLFromLinks(links, RelType.WORKSPACES_PRIMARY, { id, selector });\n        return await this._getResponse(spaceLink, this._getHeaders());\n    }\n\n    async reloadSpace(spaceLinks: IProjectsSpaceLinks, selector: IProjectSpaceSelector[] = SPACE_FULL_SELECTOR): Promise<IProjectsSpaceResponse> {\n        const spaceLink = getURLFromLinks(spaceLinks, RelType.WORKSPACES_PRIMARY, { selector });\n        return await this._getResponse(spaceLink, this._getHeaders());\n    }\n\n    async bookmarkOp(data: IProjectsBookmarkOpsData): Promise<IProjectsBookmarkBatchResponse> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(links, RelType.WORKSPACES_BOOKMARKS_BATCH);\n        const response = await this._doPost(url, this._getHeaders(JSON_MIME_TYPE), JSON.stringify(data), [ 200 ]);\n        return response.json();\n    }\n\n    async createSpace(teamLinks: IProjectsTeamLinks, data: IProjectsCreateQuery): Promise<IProjectsSpaceResponse> {\n        const url = getURLFromLinks(teamLinks, RelType.WORKSPACES_CREATE);\n        const response = await this._doPost(url, this._getHeaders(JSON_MIME_TYPE), JSON.stringify(data));\n        return response.json();\n    }\n\n    async patchSpace(spaceLinks: IProjectsSpaceLinks, data: jsonpatch.OpPatch[]): Promise<void> {\n        const url = getURLFromLinks(spaceLinks, RelType.WORKSPACES_PRIMARY);\n        await this._doPatch(url, this._getHeaders(JSON_PATCH_MIME_TYPE), JSON.stringify(data), [ 200, 204 ]);\n    }\n\n    async getEnclosingSpaces(data: IProjectsSpaceContextRequest): Promise<IProjectsSpaceContextResponse> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(links, RelType.WORKSPACES_CONTEXT);\n        const response = await this._doPost(url, this._getHeaders(JSON_MIME_TYPE), JSON.stringify(data), [ 200 ]);\n        return response.json();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type WorkspaceInterface from '../interface/WorkspacesInterface';\nimport type { TeamRole } from './Space';\nimport type Space from './Space';\nimport { SpaceUpdater } from './Space';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport { OrderFieldToIProjectsSpaceOrderBy } from './SpaceOrder';\nimport type SpaceFilter from './SpaceFilter';\nimport type { SpaceConfig } from './SpaceSource';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { clearLastReloadError } from '../core/InternalProperties';\n\nexport type GetTeamRoleFn = (teamId: string) => TeamRole;\nexport type TeamRoleGetterFactory = () => Promise<GetTeamRoleFn>;\n\nexport default class SpaceLoader implements IItemLoader<SpaceConfig> {\n\n    constructor(\n        private _spacePool: ItemPool<Space>,\n        private _workspaceInterface: WorkspaceInterface,\n        private _teamRoleGetterFactory: TeamRoleGetterFactory) {\n    }\n\n    supportsFilter(filter?: SpaceFilter): boolean {\n        // - only state === 'active' is supported.\n        // - cannot handle teamRole === 'MEMBER' yet.\n        if (!filter) {\n            // If we don't provide a filter at all, then we cannot use the loader\n            return false;\n        }\n        const { teamRole, state } = filter;\n        return teamRole !== 'MEMBER' && state === 'active';\n    }\n\n    async loadPage(options: IItemLoaderOptions<SpaceConfig>): Promise<ILoadedPage<SpaceConfig>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<SpaceConfig>, start?: number): Promise<ILoadedPage<SpaceConfig>> {\n        const { order, filter } = options;\n        const { limit } = options.loadOptions ?? {};\n        const teamRole = (filter as SpaceFilter)?.teamRole;\n        if (teamRole === 'MEMBER') {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Filtering only for spaces with reamRole MEMBER is not supported.');\n        }\n\n        // We will ignore the update if we had local changes sooner than this timestamp.\n        const latency = this._spacePool._core._environment.getValue('PROJECTS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n\n        const resultPromise = this._workspaceInterface.getSpaces({\n            orderBy: OrderFieldToIProjectsSpaceOrderBy[order.field],\n            orderDirection: order.direction,\n            teamID: (filter as SpaceFilter)?.teamID,\n            bookmarked: (filter as SpaceFilter)?.bookmarked,\n            teamAccess: teamRole === 'NONE' ? false : undefined,\n            start,\n            limit\n        });\n\n        // If the teamRole was used in the request, then we trust the server resolved the correct value for the filter.\n        // If we don't have teamRole in the filter, then we will lookup in the client side list of teams. If the teams are not\n        // loaded yet, we will just fallback to 'NONE' until the teams are eventually loaded.\n        // The team pool delegate in the space context will update the team role once the teams are known.\n        const teamRoleFn = teamRole ? (() => teamRole) : await this._teamRoleGetterFactory();\n\n        // Wait for the results after we start loading the role factory above. That will make the requests run in parallel when needed.\n        const result = await resultPromise;\n\n        const session = this._spacePool.createLoaderUpdateSession(mostRecentValidMutation);\n\n        // Inject the teamRole in all the items that we load.\n        const items = SpaceUpdater.updateRemoteItems(session, result.projects.map((item) => {\n            return {\n                ...item,\n                teamRole: teamRoleFn(item.teamId),\n\n                // The `/projects` listing endpoint doesn't add the state property,\n                // but it only returns active spaces anyways. We can inject\n                // the property automatically to make sure any restored space,\n                // gets back into the correct lists.\n                state: 'active'\n            };\n        }));\n\n        // Make sure we ignore any reload errors now that we have refreshed the listing of the space.\n        for (const item of items) {\n            item[clearLastReloadError]();\n        }\n\n        session.commit();\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<SpaceConfig> | undefined;\n\n        // Note that it is important to skip the entire page size,\n        // even if we didn't get any items back.\n        // The service is based on USS which might filter out items\n        // on the fly when they are retrieved instead of ahead of time\n        // when the total limit is computed. As a result, some pages might\n        // even come in empty.\n        const nextStart = result.pageSpec.start + result.pageSpec.limit;\n        if (nextStart < result.pageSpec.totalLimit) {\n            loadNextPage = (options: IItemLoaderOptions<SpaceConfig>) =>\n                this._loadPage(options, nextStart);\n        }\n\n        return {\n            items,\n            total: result.pageSpec.totalLimit,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ProjectInterface from '../interface/WorkspacesInterface';\nimport type Team from './Team';\nimport { TeamUpdater } from './Team';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type { TeamConfig } from './TeamSource';\nimport { OrderFieldToIProjectsTeamsOrderBy } from './TeamOrder';\nimport type TeamFilter from './TeamFilter';\n\nexport default class TeamLoader implements IItemLoader<TeamConfig> {\n\n    constructor(\n        private _teamPool: ItemPool<Team>,\n        private _projectInterface: ProjectInterface) {\n    }\n\n    async loadPage(options: IItemLoaderOptions<TeamConfig>): Promise<ILoadedPage<TeamConfig>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<TeamConfig>, start?: number): Promise<ILoadedPage<TeamConfig>> {\n        const { order, filter } = options;\n        const { limit } = options.loadOptions ?? {};\n\n        // We will ignore the update if we had local changes sooner than this timestamp.\n        const latency = this._teamPool._core._environment.getValue('PROJECTS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n\n        const result = await this._projectInterface.getTeams({\n            orderBy: OrderFieldToIProjectsTeamsOrderBy[order.field],\n            orderDirection: order.direction,\n            start,\n            limit,\n            nameContains: (filter as TeamFilter)?.nameContains,\n            state: (filter as TeamFilter)?.state\n        });\n\n        const session = this._teamPool.createLoaderUpdateSession(mostRecentValidMutation);\n        const items = TeamUpdater.updateRemoteItems(session, result.teams);\n        session.commit();\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<TeamConfig> | undefined;\n\n        // Note that it is important to skip the entire page size,\n        // even if we didn't get any items back.\n        // The service is based on USS which might filter out items\n        // on the fly when they are retrieved instead of ahead of time\n        // when the total limit is computed. As a result, some pages might\n        // even come in empty.\n        const nextStart = result.pageSpec.start + result.pageSpec.limit;\n        if (nextStart < result.pageSpec.totalLimit) {\n            loadNextPage = (options: IItemLoaderOptions<TeamConfig>) =>\n                this._loadPage(options, nextStart);\n        }\n\n        return {\n            items,\n            total: result.pageSpec.totalLimit,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IItemLoader, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type ProjectInterface from '../interface/WorkspacesInterface';\nimport type OrgRepository from './OrgRepository';\nimport { OrgRepositoryUpdater } from './OrgRepository';\nimport type { OrgRepositoryConfig } from './OrgRepositorySource';\n\nexport default class OrgRepositoryLoader implements IItemLoader<OrgRepositoryConfig> {\n\n    constructor(\n        private _orgRepositoryPool: ItemPool<OrgRepository>,\n        private _projectInterface: ProjectInterface) {\n    }\n\n    async loadPage(): Promise<ILoadedPage<OrgRepositoryConfig>> {\n        const result = await this._projectInterface.getOrgRepositories();\n        const session = this._orgRepositoryPool.createLoaderUpdateSession(Date.now());\n\n        const items = OrgRepositoryUpdater.updateRemoteItems(session, result.repositories);\n        session.commit();\n\n        return { items };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type jsonpatch from 'json-patch';\n\nimport { memoize } from '../core/decorators';\nimport type { IItemPoolDelegate, ItemsChangedEvent } from '../core/ItemPool';\nimport ItemPool, { ITEMS_CHANGED } from '../core/ItemPool';\nimport type { ItemId } from '../core/ItemBase';\nimport ItemSource from '../core/ItemSource';\nimport ProjectInterface, { SPACE_FULL_SELECTOR } from '../interface/WorkspacesInterface';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport type Space from './Space';\nimport { SpaceUpdater } from './Space';\nimport type { TeamRoleGetterFactory } from './SpaceLoader';\nimport SpaceLoader from './SpaceLoader';\nimport type Team from './Team';\nimport { TeamUpdater } from './Team';\nimport TeamLoader from './TeamLoader';\nimport type { TeamConfig, TeamSource } from './TeamSource';\nimport type OrgRepository from './OrgRepository';\nimport OrgRepositoryLoader from './OrgRepositoryLoader';\nimport type { OrgRepositorySource } from './OrgRepositorySource';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport TeamOrder from './TeamOrder';\nimport type { IItemList } from '../core/ItemList';\nimport type {\n    IProjectsBookmarkOpType,\n    IProjectsCreateData,\n    IWorkspacesIndexLinks,\n    IProjectsSpace,\n    IProjectsBookmarkBatchResponse,\n    IProjectsTeamCreateData,\n    IProjectsTeam\n} from '../interface/WorkspacesModel';\nimport type {\n    NameConflictMap,\n    AssetRenameMap } from '../assets/AssetUtils';\nimport {\n    batchFormatFileName,\n    validatePlatformRepoName,\n    updateCachedDescendents,\n    renameFileInPath,\n    getBatchRenamedAssetName\n} from '../assets/AssetUtils';\nimport type { SpaceSource } from './SpaceSource';\nimport ItemBase from '../core/ItemBase';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport { reloadSpace } from '../core/InternalProperties';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport type { IBatchOperationResult, IOperation, IOperationQuery, RepositoryMetadata } from '../interface/RepositoryModel';\nimport RepositoryInterface from '../interface/RepositoryInterface';\nimport { waitForListLoad } from '../utils/waitForListLoad';\nimport { retryFailedOpsDueToConflict } from '../assets/ConflictRetryHelper';\nimport TeamFilter from './TeamFilter';\nimport SpaceFilter from './SpaceFilter';\nimport EverythingFilter from '../core/EverythingFilter';\nimport type ItemList from '../core/ItemList';\n\n// We want to refresh teams only if we didn't get the list in the past 5 minutes.\n// This avoids loading teams again during auto-provisioning in case the client\n// already fetched the teams.\nconst TEAM_REFRESH_TIMEOUT = 5 * 60 * 1000;\n\nfunction createTeamRoleGetter(teams: IItemList<TeamConfig> | ItemList<TeamConfig>) {\n    const map = new Set<string>(teams.items.map((team) => team.id));\n    return (teamID: string) => map.has(teamID) ? 'MEMBER' : 'NONE';\n}\n\nfunction getLinks<LinkTypes>(item: { _links: LinkTypes }) {\n    const links: LinkTypes = item._links;\n    if (!links) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Object has not been loaded correctly, missing \"_links\" property.');\n    }\n    return links!;\n}\n\nexport interface ISpaceUpdate {\n    name?: string;\n    description?: string;\n    color?: string;\n}\n\nexport interface ITeamUpdate {\n    description?: string;\n    name?: string;\n}\n\nexport type IBatchOperationSpaceResult = IBatchOperationResult<Space>;\n\nexport default class SpaceContext implements ISAMObject {\n\n    private _orgRepositoryPool = new ItemPool<OrgRepository>(this._core, 'orgRepository');\n    private _teamPool = new ItemPool<Team>(this._core, 'team');\n    private _spacePool = new ItemPool<Space>(this._core, 'space');\n\n    private _projectInterface = new ProjectInterface(this._core);\n    private _rapi = new RepositoryInterface(this._core);\n    private _hostAssetContext = this._core.hostAssetContext;\n\n    constructor(readonly _core: ISAMCorePrivate) {\n        // Make sure we have a delegate to update all the teamRoles of the spaces once a new team is added.\n        this._teamPool.addDelegate(this._teamPoolDelegate, 'context');\n    }\n\n    get projectInterface(): ProjectInterface {\n        return this._projectInterface;\n    }\n\n    get orgRepositoryPool(): ItemPool<OrgRepository> {\n        return this._orgRepositoryPool;\n    }\n\n    get teamPool(): ItemPool<Team> {\n        return this._teamPool;\n    }\n\n    get spacePool(): ItemPool<Space> {\n        return this._spacePool;\n    }\n\n    /**\n     * Returns a cached list of links for the project service index route.\n     */\n    async discoverLinks(): Promise<IWorkspacesIndexLinks> {\n        return await this._projectInterface.discoverLinks();\n    }\n\n    @memoize\n    getOrgRepositories(): OrgRepositorySource {\n        const loader = new OrgRepositoryLoader(this._orgRepositoryPool, this._projectInterface);\n        return new ItemSource(this._orgRepositoryPool, [ loader ]);\n    }\n\n    @memoize\n    getTeams(): TeamSource {\n        const loader = new TeamLoader(this._teamPool, this._projectInterface);\n        return new ItemSource(this._teamPool, [ loader ], new TeamFilter());\n    }\n\n    @memoize\n    getSpaces(): SpaceSource {\n        // Make sure that the space loader checks for team membership during load.\n        const loader = new SpaceLoader(this._spacePool, this._projectInterface, this._teamRoleGetterFactory);\n        return new ItemSource(this._spacePool, [ loader ], new SpaceFilter());\n    }\n\n    private _teamRoleGetterFactory: TeamRoleGetterFactory = async () => {\n        const teams = await this._fetchTeams();\n        return createTeamRoleGetter(teams);\n    };\n\n    private _teamPoolDelegate: IItemPoolDelegate<Team> = {\n        onItemsUpdated: () => {\n            // Iterate on all the known spaces and update their teamRole based on what we know from the list of Teams.\n            // Note that this might update spaces that have been discarded, but that's alright as they might be restored\n            // at some point in the future. Since `this.getSpaces().getList()` will trigger fetching the Teams, it is\n            // expected that the Team list will typically already be loaded, so it should not use `getTeams().getList()`\n            // since that will cause it to fetch the Teams list again. Fetching teams as a side-effect of unit tests that\n            // manipulate Teams using the teamPool will unexpectedly cause the teams list to load without any Nock mock\n            // to provide it.\n            // NOTE: _getExistingList requires an explicit filter, but this Teams list should not be filtered, so it\n            // must pass in an EverythingFilter, which is not allowed as an explicit filter in the public interface,\n            // so casting to `any` because it should not put EverythingFilter in the public API.\n            const teams = this.getTeams()._getExistingList(TeamOrder.default, new EverythingFilter<Team>() as any);\n            // Teams List won't exist if manipulating the teamPool without loading the teams first.\n            // Teams List will be empty when the TeamLoader converts the service response to Team models via\n            // TeamUpdater.updateRemoteItems(), because it triggers ItemPool.onItemsUpdated() before it has actually\n            // put the items in the List.\n            if (!teams || !teams.items.length) {\n                this._core._environment.debug('[SpaceContext._teamPoolDelegate] skipping update of Space.teamRole -- no teams');\n                return;\n            }\n            const spacePool = this._spacePool;\n            const getTeamRole = createTeamRoleGetter(teams);\n            const spaceSession = spacePool.createUpdateSession('Updating teamRole across all spaces');\n            this._spacePool.forEach((space: Space) => {\n                const newTeamRole = getTeamRole(space.teamID);\n                if (space.teamRole !== newTeamRole) {\n                    SpaceUpdater.updateLocalItem(spaceSession, space, { teamRole: newTeamRole });\n                }\n            });\n            spaceSession.commit();\n        }\n    };\n\n    private async _fetchTeams(): Promise<IItemList<TeamConfig>> {\n        // Get the list with refreshTimeOut so that it will not immediately refresh if the list already exists\n        const teams = this.getTeams().getList(TeamOrder.default, undefined, { refreshTimeout: TEAM_REFRESH_TIMEOUT });\n        await waitForListLoad(teams);\n        return teams;\n    }\n\n    async provisionType1Team(): Promise<Team | undefined> {\n        // Auto-provision a team for CCI user if the user is not currently sponsoring a team.\n        if (this._core._environment.getValue('ACCOUNT_TYPE') !== 'type1') {\n            return undefined;\n        }\n\n        const teams = await this._fetchTeams();\n\n        const userId = this._core._environment.getValue('USER_ID');\n        let team = teams.items.find((team: Team) => team.repositoryOwnerID === userId && team.repositoryOwnerType === 'user');\n        if (!team) {\n            // This should automatically add the team to the lists.\n            const response = await this._projectInterface.provisionTeam();\n\n            // The team might be just created, if we are refreshing the list of teams\n            // it might not exist yet, so we have to keep it alive until USS is eventually consistent.\n            const session = this._teamPool.createMutationSession();\n            team = TeamUpdater.updateRemoteItem(session, response);\n            session.commit();\n        }\n\n        return team;\n    }\n\n    async createTeam(orgRepository: OrgRepository, data: IProjectsTeamCreateData): Promise<Team> {\n        const response = await this._projectInterface.createTeam({\n            ...data,\n            repositoryId: orgRepository.repositoryID\n        });\n        const session = this._teamPool.createMutationSession();\n        const team = TeamUpdater.updateRemoteItem(session, response);\n        session.commit();\n        return team;\n    }\n\n    private async _renameAsset(id: string, newName: string): Promise<AdobeAsset> {\n        if (!validatePlatformRepoName(newName)) {\n            // Validate the name here to avoid resolving the asset if the name is invalid.\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for the rename operation.');\n        }\n\n        // FIXME: `item._links[RelType.PRIMARY]` already has the resolved link for the asset.\n        // We could reuse the link to avoid a separate resolve by id call.\n        const asset = await this._hostAssetContext.getAssetWithCloudID(id);\n        await asset.rename(newName);\n\n        // Return the new name of the asset, just in case the server decided to change it.\n        return asset;\n    }\n\n    private async _renameTeam(team: Team, update: ITeamUpdate) {\n        const name = update.name;\n        if (!name) {\n            return;\n        }\n\n        if (!validatePlatformRepoName(name)) {\n            // Validate the name here to avoid resolving the asset if the name is invalid.\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for the rename operation.');\n        }\n\n        const links = getLinks(team);\n        await this._projectInterface.renameTeam(links, name);\n\n        // Since the client could have both an instance to a Team\n        // and the underlying AdobeAsset we should check that if the\n        // AdobeAsset exists in the AssetContext ItemPool and if it does\n        // update it and it's descendents as well.\n        const adobeAssetPool = this._core._getAssetPool();\n        const localAdobeAsset = adobeAssetPool.getLocalItemById(team.id);\n        const assetContext = await this._core.getAssetContext();\n        if (localAdobeAsset) {\n            const newPath = renameFileInPath(name, localAdobeAsset);\n            const adobeAssetSession = adobeAssetPool.createUpdateSession();\n\n            updateCachedDescendents({\n                assetPool: adobeAssetPool,\n                asset: localAdobeAsset,\n                session: adobeAssetSession,\n                operation: { type: 'rename', newPath },\n                assetContext\n            });\n\n            this._hostAssetContext._adobeAssetUpdater.updateLocalItem(\n                adobeAssetSession,\n                localAdobeAsset,\n                {\n                    'repo:path': newPath,\n                    'repo:name': name\n                }\n            );\n            adobeAssetSession.commit();\n        }\n\n        const updateSession = this.teamPool.createMutationSession();\n        TeamUpdater.updateLocalItem(updateSession, team, { name });\n        updateSession.commit();\n    }\n\n    async renameTeam(team: Team, newName: string): Promise<void> {\n        await this.updateTeam(team, { name: newName });\n    }\n\n    async restoreTeam(team: Team): Promise<void> {\n        await ItemBase.runExclusiveTask('restore', [ team ], async () => {\n            try {\n                const links = getLinks(team);\n                const updateSession = this.teamPool.createUpdateSession();\n                await this._projectInterface.restoreTeam(links);\n                TeamUpdater.updateLocalItem(updateSession, team, { state: 'active' });\n                updateSession.commit();\n            } catch (e) {\n                // We want to avoid updating the pool if\n                // there are errors like CONFLICT that could occur.\n                throw SAMError.create(SAMErrorCode.UNKNOWN,\n                    'An error occured restoring team',\n                    { underlyingError: e }\n                );\n            }\n        });\n    }\n\n    async archiveTeam(team: Team): Promise<void> {\n        await ItemBase.runExclusiveTask('archive', [ team ], async () => {\n            // TODO: should this be createMutationSession?\n            const updateSession = this.teamPool.createUpdateSession();\n            try {\n                const links = getLinks(team);\n                await this._projectInterface.archiveTeam(links);\n            } catch (error) {\n                const e = error as SAMError;\n                // @TODO https://jira.corp.adobe.com/browse/SAM-2064\n                // Temporary fallback, remove once M2 APIs are in prod\n                if (e.code === SAMErrorCode.BAD_REQUEST) {\n                    const asset = await this._hostAssetContext.getAssetWithCloudID(team.id);\n                    await asset.discard();\n                } else {\n                    throw e;\n                }\n            }\n            TeamUpdater.updateLocalItem(updateSession, team, { state: 'discarded' });\n            updateSession.commit();\n        });\n    }\n\n    /**\n     * The Projects services accepts only\n     * a string value with the length\n     * less than or equal to 1000.\n     */\n    private _validateDescription(value: string) {\n        return value.length <= 1000;\n    }\n\n    private _validateColor(value: string) {\n        return /^#[A-Fa-f0-9]{6}$/.test(value);\n    }\n\n    private _getPatchOP(\n        value: string,\n        path: string,\n        existingValue?: string,\n        validator?: (value: string) => boolean\n    ): jsonpatch.OpPatch {\n\n        if (validator && !validator(value)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Property ${path} has invalid value`);\n        }\n\n        // If there was a description and now there\n        // is none, we should \"remove\".\n        if (value.length === 0\n            && existingValue && existingValue.length > 0) {\n            return {\n                op: 'remove',\n                path\n            };\n        }\n\n        return {\n            op: existingValue ? 'replace' : 'add',\n            value,\n            path\n        };\n    }\n\n    private async _patchTeam(team: Team, update: ITeamUpdate): Promise<void> {\n        const  { description } = update;\n        const bodyData: jsonpatch.OpPatch[] = [];\n        const localUpdate: Partial<IProjectsTeam> = {};\n\n        if (description !== undefined) {\n            bodyData.push(this._getPatchOP(\n                description,\n                '/description',\n                team.description,\n                this._validateDescription\n            ));\n            localUpdate.description = description;\n        }\n\n        if (!bodyData.length) {\n            return;\n        }\n\n        const links = getLinks(team);\n        await this._projectInterface.patchTeam(links, bodyData);\n\n        const updateSession = this.teamPool.createMutationSession();\n        TeamUpdater.updateLocalItem(updateSession, team, localUpdate);\n        updateSession.commit();\n    }\n\n    async updateTeam(team: Team, update: ITeamUpdate): Promise<void> {\n        await ItemBase.runExclusiveTask('update', [ team ], async () => {\n            const results = await Promise.allSettled([\n                this._patchTeam(team, update),\n                this._renameTeam(team, update)\n            ]);\n\n            // Checks for rejection and calls the handler\n            // to delete the item because it has not been\n            // found.\n            this._checkForRejection(results, () => {\n                const session = this.teamPool.createUpdateSession();\n                session.queueDiscardedItem(team);\n                session.commit();\n            });\n        });\n    }\n\n    async loadTeamProperties(team: Team): Promise<void> {\n        const links = getLinks(team);\n        const properties = await this._projectInterface.getTeamProperties(links);\n        if (!properties || Object.keys(properties).length === 0) {\n            return;\n        }\n\n        const updateSession = this.teamPool.createMutationSession();\n        TeamUpdater.updateLocalItem(updateSession, team, { ...properties });\n        updateSession.commit();\n    }\n\n    async permanentlyDeleteTeam(team: Team): Promise<void> {\n        if (team.state === 'active') {\n            throw SAMError.create(\n                SAMErrorCode.UNSUPPORTED,\n                'Teams that are not \\'discarded\\' cannot be permanently deleted.'\n            );\n        }\n\n        const onItemsChanged = (event: ItemsChangedEvent<Team>) => {\n            if (event.discardedItems) {\n                const permDeleteTeamIDs: ItemId[] = event.discardedItems\n                    .filter(item => item.id === team.id)\n                    .map(item => item.id);\n                if (permDeleteTeamIDs.length) {\n                    this._teamPool.removeLocalItems(permDeleteTeamIDs);\n                }\n            }\n        };\n\n        this._teamPool.on(ITEMS_CHANGED, onItemsChanged);\n        try {\n            await ItemBase.runExclusiveTask('delete', [ team ], async () => {\n                const links = getLinks(team);\n                await this._projectInterface.permanentlyDeleteTeam(links);\n                const updateSession = this.teamPool.createUpdateSession();\n                updateSession.queueDiscardedItem(team);\n                updateSession.commit();\n            });\n        } finally {\n            this.teamPool.off(ITEMS_CHANGED, onItemsChanged);\n        }\n    }\n\n    // Reload space is an implementation detail of the space context,\n    // external projects should use space.load() instead.\n    async [reloadSpace](space: Space): Promise<void> {\n        const latency = this._core._environment.getValue('PROJECTS_ITEM_UPDATE_LATENCY');\n        await space.waitForMutationPropagationIfNeeded(latency);\n\n        const links = getLinks(space);\n        const result = await this._projectInterface.reloadSpace(links, SPACE_FULL_SELECTOR);\n        const session = this._spacePool.createUpdateSession();\n        SpaceUpdater.updateLocalItem(session, space, result);\n        session.commit();\n    }\n\n    /**\n     * Internal helper method for moving spaces.\n     * @param spaces spaces to be moved\n     * @param team destination team where spaces are intended to be moved\n     * @param assetRenameMap allows renaming of assets in the batch operation\n     * @param retryOnConflict whether to retry the move op for failed spaces in case of conflict\n     * @param assetConflictMap map to save the newName and count used for all assets in batch\n     * @returns the result for batch operation after retrying for failed assets if asked.\n     */\n    private async _moveSpaces(\n        spaces: Space[],\n        team: Team,\n        assetRenameMap: AssetRenameMap<Space> = new Map(),\n        retryOnConflict: boolean = true,\n        assetConflictMap?: NameConflictMap\n    ): Promise<IBatchOperationSpaceResult> {\n        let resultOps: IBatchOperationSpaceResult = { failedResults: [], newModels: [] };\n\n        await ItemBase.runExclusiveTask('move', spaces, async () => {\n            const targetAsset = await this._hostAssetContext.getAssetWithCloudID(team.id);\n            if (assetConflictMap === undefined) {\n                assetConflictMap = new Map() as NameConflictMap;\n            }\n            const spacesById = new Map<string, Space>();\n            const ops = spaces.map((space) => {\n                spacesById.set(space.id, space);\n                let newPath = `${targetAsset.repoPath}/${getBatchRenamedAssetName(space, assetRenameMap)}`;\n\n                newPath = batchFormatFileName(this._core, space.id, newPath, false, assetConflictMap!);\n                return {\n                    op: 'move',\n                    id: space.id,\n                    source: {\n                        'repo:assetId': space.id,\n                        'repo:repositoryId': space.repositoryID\n                    },\n                    target: {\n                        'repo:path': newPath,\n                        'repo:repositoryId': targetAsset.repositoryID\n                    }\n                } as IOperation;\n            });\n\n            resultOps = await this._runOperations(ops, spacesById, {\n                teamId: team.id,\n                teamName: team.name\n            });\n        });\n        if (retryOnConflict) {\n            return await retryFailedOpsDueToConflict(resultOps, team, assetRenameMap, assetConflictMap!, this._moveSpaces.bind(this));\n        }\n        return resultOps;\n    }\n\n    /**\n     * Public method to move spaces to a team\n     * @param spaces spaces to be moved\n     * @param team destination team where spaces are intended to be moved\n     * @returns the result for batch operation after retrying for failed assets.\n     */\n    async moveSpaces(spaces: Space[], team: Team): Promise<IBatchOperationSpaceResult> {\n        return this._moveSpaces(spaces, team);\n    }\n\n    async archiveSpaces(spaces: Space[]): Promise<IBatchOperationSpaceResult> {\n        return await ItemBase.runExclusiveTask('archive', spaces, async () => {\n            const spacesById = new Map<string, Space>();\n            const ops = spaces.map((space) => {\n                spacesById.set(space.id, space);\n                return {\n                    op: 'discard',\n                    id: space.id,\n                    target: {\n                        'repo:assetId': space.id,\n                        'repo:repositoryId': space.repositoryID\n                    },\n                } as IOperation;\n            });\n\n            return await this._runOperations(ops, spacesById);\n        });\n    }\n\n    async restoreSpaces(spaces: Space[], restoreNameMap?: Map<Space, string>): Promise<IBatchOperationSpaceResult> {\n        return await ItemBase.runExclusiveTask('restore', spaces, async () => {\n            const spacesById = new Map<string, Space>();\n            const ops = spaces.map((space) => {\n                spacesById.set(space.id, space);\n                return {\n                    op: 'restore',\n                    id: space.id,\n                    target: {\n                        'repo:assetId': space.id,\n                        'repo:repositoryId': space.repositoryID\n                    },\n                    name: restoreNameMap?.get(space)\n                } as IOperation;\n            });\n            return await this._runOperations(ops, spacesById);\n        });\n    }\n\n    async _runOperations(\n        ops: IOperationQuery, spacesById: Map<string, Space>, additionalSpaceUpdates: Partial<IProjectsSpace> = {}\n    ): Promise<IBatchOperationSpaceResult> {\n        const assetContext = await this._core.getAssetContext();\n        return await this._rapi.runOperationsForContext<Space>(\n            ops,\n            spacesById,\n            this._spacePool,\n            (session: IUpdateSession<Space>, space: Space, remoteItem?: RepositoryMetadata) => {\n                if (!remoteItem) {\n                    throw SAMError.create(SAMErrorCode.UNKNOWN, 'Missing metadata from asset bulk operation.');\n                }\n                // We want to update the repo:path of all the descendants of the space only in case of move/rename.\n                const remoteRepoPath = remoteItem['repo:path'];\n                if (space.pathName !== remoteRepoPath) {\n                    const adobeAssetPool = this._core._getAssetPool();\n                    const localAdobeAsset = adobeAssetPool.getLocalItemById(space.id);\n                    const assetSession = adobeAssetPool.createUpdateSession();\n\n                    if (localAdobeAsset) {\n                        updateCachedDescendents({\n                            assetPool: adobeAssetPool,\n                            asset: localAdobeAsset,\n                            session: assetSession,\n                            operation: { type: 'rename', newPath: remoteRepoPath },\n                            assetContext\n                        });\n                        assetContext._adobeAssetUpdater.updateLocalItem(\n                            assetSession,\n                            localAdobeAsset,\n                            {\n                                'repo:path': remoteRepoPath\n                            }\n                        );\n                        assetSession.commit();\n                    }\n                }\n\n                SpaceUpdater.updateLocalItem(session, space, {\n                    state: remoteItem['repo:state'] === 'ACTIVE' ? 'active' : 'archived',\n                    name: remoteItem['repo:name'],\n                    pathName: remoteItem['repo:path'],\n                    ...additionalSpaceUpdates\n                });\n                return undefined;\n            },\n            [\n                {\n                    // Refresh this space to make sure we have the latest version of it.\n                    // Note that we cannot use 404 - NOT_FOUND as a sign that the space has been\n                    // permanently deleted as we get that same error code when the space\n                    // is still active, just that the user is not allowed to archive/restore it.\n                    // It is better to just reload the space to validate we still have access to\n                    match: (error: SAMError) => error.code === SAMErrorCode.ACCESS_DENIED || error.code === SAMErrorCode.NOT_FOUND,\n                    action: async (space: Space) => {\n                        return await space.load().catch((error: Error) => {\n                            return { model: space, error: error as SAMError };\n                        });\n                    }\n                }\n            ]\n        );\n    }\n\n    async createSpaceBookmarks(spaces: Space[]): Promise<void>  {\n        return this._bookmarkSpaces('ADD', spaces);\n    }\n\n    async removeSpaceBookmarks(spaces: Space[]): Promise<void>  {\n        return this._bookmarkSpaces('REMOVE', spaces);\n    }\n\n    private async _bookmarkSpaces(op: IProjectsBookmarkOpType, spaces: Space[]): Promise<void> {\n        await ItemBase.runExclusiveTask('bookmark', spaces, async () => {\n            const userId = this._core._environment.getValue('USER_ID');\n\n            // Attempt to make the change ahead of time.\n            const change: Partial<IProjectsSpace>  = {\n                bookmarked: op === 'ADD'\n            };\n            const localSession = this.spacePool.createUpdateSession();\n\n            const spaceById = new Map<string, { space: Space, wasBookmarked: boolean, status?: number }>();\n            const items = spaces.map((space) => {\n                spaceById.set(space.id, { space, wasBookmarked: space.isBookmarked });\n                SpaceUpdater.updateLocalItem(localSession, space, change);\n                return {\n                    projectUrn: space.id,\n                    userId\n                };\n            });\n            localSession.commit();\n\n            let response: IProjectsBookmarkBatchResponse | undefined;\n\n            try {\n                response = await this._projectInterface.bookmarkOp({ op, items });\n            } finally {\n                if (response) {\n                    for (const item of response.responses) {\n                        const info = spaceById.get(item.request?.projectUrn);\n                        if (info) {\n                            info.status = item.status;\n                        }\n                    }\n                }\n\n                // Revert all incomplete changes.\n                const restoreSession = this.spacePool.createUpdateSession();\n                const mutationSession = this.spacePool.createMutationSession();\n\n                for (const { space, wasBookmarked, status } of spaceById.values()) {\n                    if (status === 201) {\n                        // Reapply the change, in case there was a different fetch in-between.\n                        // This should also force the mutation timestamp to update on the space.\n                        SpaceUpdater.updateLocalItem(mutationSession, space, change);\n                    } else {\n                        // Revert the local change.\n                        SpaceUpdater.updateLocalItem(restoreSession, space, {\n                            bookmarked: wasBookmarked\n                        });\n\n                        // Check if the item was removed on a different device\n                        // and remove it from internal lists too.\n                        if (status === 404) {\n                            restoreSession.queueDiscardedItem(space);\n                        }\n                    }\n                }\n                restoreSession.commit();\n                mutationSession.commit();\n            }\n        });\n    }\n\n    private _checkForRejection(\n        results: PromiseSettledResult<void>[],\n        onRemoveItem: () => void\n    ) {\n        for (const result of results) {\n            if (result.status === 'rejected') {\n                const error = result.reason;\n                // Remove the item entirely\n                if (error instanceof SAMError && error.code === SAMErrorCode.NOT_FOUND) {\n                    onRemoveItem();\n                }\n                throw error;\n            }\n        }\n    }\n\n    async updateSpace(space: Space, update: ISpaceUpdate): Promise<void> {\n        // Make both rename and patch go through the same exclusive task,\n        // to allow them to execute in parallel.\n        await ItemBase.runExclusiveTask('update', [ space ], async () => {\n            const results = await Promise.allSettled([\n                this._renameSpace(space, update),\n                this._patchSpace(space, update)\n            ]);\n\n            this._checkForRejection(results, () => {\n                const session = this.spacePool.createUpdateSession();\n                session.queueDiscardedItem(space);\n                session.commit();\n            });\n        });\n    }\n\n    private async _renameSpace(space: Space, update: ISpaceUpdate): Promise<void> {\n        const  { name } = update;\n        if (name === undefined) {\n            return;\n        }\n\n        const asset = await this._renameAsset(space.id, name);\n        const updateSession = this.spacePool.createMutationSession();\n        SpaceUpdater.updateLocalItem(updateSession, space, {\n            name: asset.name,\n            pathName: asset.repoPath\n        });\n        updateSession.commit();\n    }\n\n    private async _patchSpace(space: Space, update: ISpaceUpdate): Promise<void> {\n        const  { description, color } = update;\n        const bodyData: jsonpatch.OpPatch[] = [];\n        const localUpdate: Partial<IProjectsSpace> = {};\n\n        if (description !== undefined) {\n            bodyData.push(this._getPatchOP(\n                description,\n                `/description`,\n                space.description,\n                this._validateDescription\n            ));\n            localUpdate.description = description;\n        }\n\n        if (color !== undefined) {\n            bodyData.push(this._getPatchOP(\n                color,\n                `/color`,\n                space.color,\n                this._validateColor\n            ));\n            localUpdate.color = color;\n        }\n\n        if (!bodyData.length) {\n            return;\n        }\n\n        const links = getLinks(space);\n\n        // Ideally, the patch would return the updated state, but that's not the case here.\n        await this._projectInterface.patchSpace(links, bodyData);\n\n        // We will have to assume that a successful change means the changed values are the latest ones.\n        const updateSession = this.spacePool.createMutationSession();\n        SpaceUpdater.updateLocalItem(updateSession, space, localUpdate);\n        updateSession.commit();\n    }\n\n    async createSpace(team: Team, data: IProjectsCreateData): Promise<Space> {\n        const links = getLinks(team);\n\n        this._validateColor(data.color);\n        this._validateDescription(data.description);\n        validatePlatformRepoName(data.name);\n\n        const response = await this._projectInterface.createSpace(links, {\n            ...data,\n            parentId: team.id\n        });\n        // A space might not show up until a few seconds later, so we must keep it alive during this time.\n        const updateSession = this.spacePool.createMutationSession();\n        const space = SpaceUpdater.updateRemoteItem(updateSession, {\n            ...response,\n\n            // Make sure the service injects the teamId.\n            teamId: team.id\n        });\n        updateSession.commit();\n        return space;\n    }\n\n    async getEnclosingSpace(assetId: string): Promise<Space | undefined> {\n        const spaceMap = await this.getEnclosingSpaces([ assetId ]);\n        return spaceMap.get(assetId);\n    }\n\n    async getEnclosingSpaces(assetIds: string[]): Promise<Map<string, Space>> {\n        // The :context API uses the USS to lookup the enclosing space, so it suffers by the\n        // same amount of latency as the listing APIs. We will ignore the info we get from this\n        // API if the asset was mutated more recently than the maximum expected latency for USS.\n        const latency = this._core._environment.getValue('PROJECTS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;  // We will ignore the update if we had local changes sooner than this timestamp.\n\n        const result = await this._projectInterface.getEnclosingSpaces(assetIds.map((id) => ({ 'repo:assetId': id })));\n        const map = new Map<string, Space>();\n        const updateSession = this.spacePool.createUpdateSession('get enclosing spaces', mostRecentValidMutation);\n        for (const item of result.responses) {\n            if (item.status !== 200) {\n                continue;\n            }\n            const id = item.request['repo:assetId'];\n            const space = SpaceUpdater.updateRemoteItem(updateSession, item.body);\n            map.set(id, space);\n        }\n        updateSession.commit();\n        return map;\n    }\n\n    async lookupSpaceById(id: string): Promise<Space> {\n        let space = this._spacePool.getLocalItemById(id);\n        if (!space) {\n            // Note that we don't have a local space, so we don't have to worry about eventual consistency on this item.\n            const response = await this._projectInterface.getSpace(id, SPACE_FULL_SELECTOR);\n            const session = this._spacePool.createUpdateSession();\n            space = SpaceUpdater.updateRemoteItem(session, response);\n            session.commit();\n        }\n        return space;\n    }\n\n    /**\n     * This API is temporary and it is specifically for Projects UI to use with SS workflows.\n     * It will eventually be deprecated in favor of using notifications\n     * @param teamId\n     */\n    onUserLeftTeam(teamId: string): void {\n        const team = this._teamPool.getLocalItemById(teamId);\n        if (team) {\n            const session = this._teamPool.createUpdateSession();\n            session.queueDiscardedItem(team);\n            session.commit();\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n\nimport type { IServiceLink, RelType } from './LinkUtils';\n\nexport interface IGradientColorRGB {\n    r: number;\n    g: number;\n    b: number;\n}\n\nexport interface IGradientColorStopValue {\n    mode: string;\n    value: IGradientColorRGB;\n}\n\n/**\n * Color Stop\n * Each color stop has at minimum a color and offset.\n * Every color must include an sRGB representation.\n */\nexport interface IGradientColorStop {\n    color: IGradientColorStopValue[];\n    /**\n     * Percentage offset for the color stop along the gradient path\n     */\n    offset: number;\n}\n\nexport interface IGradientResponseLinks {\n    [RelType.PROJECTS_GRADIENTS_COLLECTION]: IServiceLink\n}\n\nexport interface IGradientItemResponse {\n    'project:gradientId': string;\n    /**\n     * IComputedGradientData extends IGradientData and\n     * adds a couple of properties for use within SAM.js.\n     */\n    'project:gradientData': IComputedGradientData;\n    'project:gradientName': string;\n    'project:gradientTextColor': IGradientTextColor;\n}\n\nexport interface IGradientTextColor {\n    alpha: number;\n    mode: 'RGB' | string;\n    value: IGradientColorRGB;\n    type: 'process' | string;\n}\n\n// The computed item response interface allows us to create an unique\n// id for the gradient based on language and it's actual id\n// this way we can store the unique gradients.\nexport interface IGradientComputedItemResponse extends IGradientItemResponse {\n    computedID: string;\n}\n\nexport function computeGradientID(rawGradientId: string, languageCode: string): string {\n    return `${rawGradientId}-${languageCode}`;\n}\n\nexport interface IGradientOpacity {\n    /**\n     * Percentage offset for the opacity stop along the gradient path\n     */\n    offset: number;\n    /**\n     * Location of midpoint between the previous stop and this stop,\n     * as a percentage of the distance between by the interpolation algorithm).\n     * The midpoint is ignored for the first stop, since it has no previous stop.\n     */\n    opacity: number;\n}\n\n/**\n * Gradient Data Derived from\n * https://git.corp.adobe.com/caf/xcm/blob/1efcec108c1dcc7bfbfe7bc7eb313dcfdcc94138/schemas/cc/library/data/gradient/gradient.schema.json\n */\n\nexport interface IGradientData {\n    /**\n     * The type of gradient (linear or radial)\n     */\n    type: 'linear' | 'radial';\n    /**\n     * Rotation of the gradient (applies to both linear and radial gradients)\n     * - this is measured anti clockwise from the positive x-axis\n     */\n    angle?: number;\n    /**\n     * Each color stop has at minimum a color and offset.\n     * Every color must include an sRGB representation.\n     */\n    stops: IGradientColorStop[];\n    /**\n     * This is separate from the color stops, since some applications like\n     * Photoshop support separate color and opacity stops\n     */\n    opacities?: IGradientOpacity[];\n}\n\nexport interface IComputedGradientData extends IGradientData {\n    isDefault?: boolean;\n    languageCode?: string;\n}\n\nexport interface IGradientsResponse {\n    default: string;\n    children: IGradientItemResponse[];\n    _links: IGradientResponseLinks;\n}\n\n/**\n * Takes the response from the service and computes the result\n * to add additional properties.\n *\n * @param rawGradientData Data directly from the service.\n * @param defaultGradientId The default gradient from the service.\n * @param languageCode The language code.\n * @returns\n */\nexport function computeGradients(\n    rawGradientData: IGradientItemResponse[],\n    defaultGradientId: string,\n    languageCode: string\n): IGradientComputedItemResponse[] {\n    return rawGradientData.map((gradient: IGradientItemResponse) => {\n        return {\n            ...gradient,\n            computedID: computeGradientID(gradient['project:gradientId'], languageCode),\n            'project:gradientData': {\n                ...gradient['project:gradientData'],\n                isDefault: defaultGradientId === gradient['project:gradientId'],\n                languageCode\n            }\n        };\n    });\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as AdobeAsset } from './AdobeAsset';\nimport type { IImplicitDirectoryListingFilterOptions } from './ImplicitDirectoryListingFilter';\nimport ImplicitDirectoryListingFilter from './ImplicitDirectoryListingFilter';\nimport type { IAdobeAssetFilterOptions } from './AdobeAssetFilter';\nimport AdobeAssetFilter from './AdobeAssetFilter';\nimport type { IImplicitAdobeAssetFilterBaseOptions } from './ImplicitAdobeAssetFilterBase';\n\n\nexport type IImplicitDirectoryListingAssetFilterOptions = IAdobeAssetFilterOptions & IImplicitDirectoryListingFilterOptions & IImplicitAdobeAssetFilterBaseOptions;\n\nexport default class ImplicitDirectoryListingAssetFilter implements IImplicitFilter<AdobeAsset> {\n    private readonly _implicitDirectoryListingFilter?: ImplicitDirectoryListingFilter;\n    private readonly _adobeAssetFilter?: AdobeAssetFilter;\n\n    constructor(options: IImplicitDirectoryListingAssetFilterOptions) {\n        const { asset, mediaTypes, excludeMediaTypes, ...baseOpts } = options;\n        // ImplicitDirectoryListingFilter handles the ImplicitAdobeAssetFilterBase cases\n        this._implicitDirectoryListingFilter = new ImplicitDirectoryListingFilter({ asset, ...baseOpts });\n        if (mediaTypes || excludeMediaTypes) {\n            this._adobeAssetFilter = new AdobeAssetFilter({\n                mediaTypes,\n                excludeMediaTypes\n            });\n        }\n    }\n\n    matches(item: AdobeAsset): boolean {\n        if (this._adobeAssetFilter && !this._adobeAssetFilter.matches(item)) {\n            return false;\n        }\n\n        if (this._implicitDirectoryListingFilter && !this._implicitDirectoryListingFilter.matches(item)) {\n            return false;\n        }\n\n        // it matched both filters above\n        return true;\n    }\n\n    get mediaTypes(): Set<string> | undefined {\n        return this._adobeAssetFilter?.mediaTypes;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { AssetClass, AssetLinks, Owner, RepositoryMetadata } from '../interface/RepositoryModel';\nimport { AssetStateChoices } from '../interface/RepositoryModel';\nimport { memoize, observable } from '../core/decorators';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport type {\n    IProject,\n    IProjectLinks,\n    IProjectPatchData,\n    IProjectsCreatorData } from '../interface/ProjectsModel';\nimport {\n    _projectLinkKeys,\n    parseProjectEffectivePermissions,\n    ProjectDirectorySubtype,\n    projectDirectorySubTypes,\n    ProjectLeaveReason,\n    ProjectViews,\n} from '../interface/ProjectsModel';\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater, { NotFound } from '../core/PropertyUpdater';\nimport type { AdobeAssetUpdaterMetadata } from '../assets/AdobeAsset';\nimport AdobeAsset, { StorageAssigneeFormat } from '../assets/AdobeAsset';\nimport { renameFileInPath, validatePlatformRepoName, updateCachedDescendents } from '../assets/AssetUtils';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport ProjectsInterface from '../interface/ProjectsInterface';\nimport { RelType } from '../interface/LinkUtils';\nimport { Permission, PERMISSION_ALL } from '../interface/AssetModel';\nimport type { Gradient } from './Gradient';\nimport { computeGradientID } from '../interface/GradientModel';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport { SharedCollaboratorChangedEvent } from '../indexPrivate';\nimport type { AdobeAssetSource } from '../assets/AdobeAssetSource';\nimport AdobeAssetDirectoryLoader from '../assets/AdobeAssetDirectoryLoader';\nimport ItemSource from '../core/ItemSource';\nimport { libraryMediaTypeString } from '../assets/AdobeAssetFactory';\nimport ImplicitDirectoryListingAssetFilter from '../assets/ImplicitDirectoryListingAssetFilter';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport { lazyLoaded, LazyLoadManager, LoadStatus } from '../core/decorators/LazyLoadManager';\nimport { CHANGE, SharedChangeEvent } from '../core/ChangeEvent';\nimport type { CreateLibraryOptions, CreateProjectLibraryData } from '../interface/LibraryModel';\nimport type Library from '../libraries/Library';\nimport type { IPerUserMetadata } from '../interface/AssetModel';\nimport type { IAccessRequestNotification, IAccessRequestPermissions, IAccessRequestResult } from '../interface/InvitationModel';\nexport interface IProjectProperties {\n    gradientID: string;\n    /**\n     * @experimental API May change.\n     */\n    description: string;\n}\n/**\n * The views that a project can actually have\n * which currently excludes ProjectViews.All and ProjectViews.Admin\n */\ntype ProjectItemView = SAM.ProjectViews.SWY | SAM.ProjectViews.Yours | undefined;\n\nexport default class Project extends AdobeAsset implements SAM.Project {\n    public isProject: boolean = true;\n\n    private _description: string = '';\n    private _projectLinks?: IProjectLinks;\n\n    // We have separate permissions for a Project and AdobeAsset.\n    // AdobeAsset permissions for a project are the permissions on the folder (i.e. representing the project)\n    // ESM users might not have permission on the parent folder for Projects, so the permissions cannot be derived\n    // from the parent folder like normal folders.\n    private _projectPermissions: Permission = PERMISSION_ALL;\n\n    /**\n     * This is the raw id that exists on the project app metadata\n     * but we internally compute this value and join the language\n     * code so we can store them in the ItemPool uniquely\n     * so if you need the computed gradientID, use the public\n     * Project.gradientID() and not the private _gradientID;\n     */\n    private _gradientID?: string;\n    private _creator?: IProjectsCreatorData;\n    private _gradient: Gradient | undefined;\n    private _projectInterface = new ProjectsInterface(this._core);\n    private _repositoryOwner: Owner = { id: '', type: 'user' };\n    private _directorySubtype: ProjectDirectorySubtype = ProjectDirectorySubtype.CC_PROJECTS;\n    protected _assetClass: AssetClass = 'directory';\n\n    /**\n     * [SHARED-3832] Some Projects are available to the whole org but should not show up in the current user's listings\n     * unless it is a recent Project. However, detecting this case is tricky in getProjectbyID, so it should assume the\n     * Project is not allowed on lists until it is proven that it should be allowed.\n     *\n     * @package -- for use in SAM.js only\n     */\n    public _allowInLists = false;\n    /**\n     * @package -- only for use in SAM.js\n     * TODO: once we have support for lastAccessDate from projects service, we can set remove this.\n     */\n    public _isRecent = false;\n\n    /**\n     * List of inaccessible library references for this project.\n     * These are library references that the user does not have access to.\n     */\n    private _inaccessibleLibraryReferences: string[] | undefined;\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        id: string,\n        metadata?: {\n            projectLinks?: IProjectLinks,\n            links?: AssetLinks,\n            etag?: string\n        }\n    ) {\n        super(_core, id, metadata);\n        this._projectLinks = metadata?.projectLinks;\n\n        // Overridden property.\n        // True to start with. If we have the metadata, we will update this.\n        this._needsRepoMetadata = true;\n\n        LazyLoadManager.manageLazyLoading(this, [ {\n            event: SharedChangeEvent,\n            fetchData: this._getGradient\n        } ]);\n    }\n\n\n    @observable\n    get gradientID(): string {\n        return this._gradientID ?? '';\n    }\n\n    /**\n     * Lazy loads and returns the Gradient belonging to this\n     * Project.\n     */\n    @lazyLoaded(SharedChangeEvent, '_gradient')\n    get gradient(): Gradient | undefined {\n        return this._gradient;\n    }\n\n    private async _getGradient() {\n        this._gradient = await this._core.projectContext.getGradient(this.gradientID);\n    }\n\n    /**\n     * @TODO@PROJECT\n     * @experimental API may change.\n     */\n    @observable\n    get description(): string {\n        oneTimeWarning('Description Not yet Supported', 'Currently the description field is not supported by the service.');\n        return this._description;\n    }\n\n    /**\n     * This property represents the \"sub-type\" of the project directory. There have been several\n     * new types introduced to support CSC Projects.\n     *\n     * ACPC Project is the general term used to describe the \"project\" construct\n     * in AUP, the CSC Project (Content Supply Chain) Project\n     *\n     * WFProject: Work Front Project\n     * CCProject: Creative Cloud Project\n     *\n     */\n    get directorySubtype(): ProjectDirectorySubtype {\n        return this._directorySubtype;\n    }\n\n    /**\n     * @experimental API May change.\n     * Returns the number of library references in this project that the current user does not have access to.\n     *\n     * @warning This property is not guaranteed to be loaded. It is only populated when this project's library references are loaded via a LibrarySource.\n     *\n     * @returns {number|undefined} Count of inaccessible library reference IDs or undefined if not loaded\n     */\n    @observable\n    get inaccessibleLibraryReferencesCount(): number | undefined {\n        return this._inaccessibleLibraryReferences ? this._inaccessibleLibraryReferences.length : undefined;\n    }\n\n    /**\n     * @param repoMetadata {RepositoryMetadata} If passed in, it will be used instead of loading from the service\n     * @param appMetadata {any} If passed in, it will be used instead of loading from the service\n     *\n     * @package -- only for use in SAM.js\n     */\n    async _load({\n        repoMetadata,\n        appMetadata,\n        effectivePermission,\n        projectMetadata,\n        perUserMetadata\n    }: {\n        repoMetadata?: RepositoryMetadata;\n        appMetadata?: any;\n        effectivePermission?: Permission;\n        projectMetadata?: IProject;\n        perUserMetadata?: IPerUserMetadata;\n    } = {}): Promise<void> {\n        // First load the AdobeAsset so that once we get the project metadata we override any relevant\n        // properties with the project metadata. One example of such field is createdBy. Etag is another one.\n        // We need to take care of permissions. We will get the permissions from the project service\n        // and we should handle them here as they are extended from RAPI effective permissions.\n        // https://jira.corp.adobe.com/browse/SAM-3086\n        // Also we need update the load method so that it does not load the permissions for a project\n        // We can probably govern that with the help of an argument to the load method.\n        await super._load({ repoMetadata, appMetadata, effectivePermission, perUserMetadata });\n\n        // If we have the project metadata, then we will use that to update the project\n        if (!projectMetadata) {\n            // load the project metadata using the project service\n            projectMetadata = await this._projectInterface.getProject(this.id);\n        }\n        const session = this._core.projectContext._assetPool.createMutationSession<Project>();\n        this._core.projectContext._projectUpdater.updateRemoteItem(session, projectMetadata!);\n        session.commit();\n    }\n\n    // @TODO@PROJECT We should implement something similar to _ensureLink here.\n    get projectLinks(): IProjectLinks | undefined {\n        return this._projectLinks;\n    }\n\n    get creator(): IProjectsCreatorData | undefined {\n        return this._creator;\n    }\n\n    /**\n     * The view that this project belongs to.\n     */\n    @observable\n    get view(): ProjectItemView {\n        // repositoryOwner is not loaded yet\n        if (!this._repositoryOwner.id) {\n            return undefined;\n        }\n        const currentUserId = this._core._environment.getUserId();\n        const { defaultOrganizationId, organizations } = this._core.hostAssetContext;\n        const allOwners: string[] = [\n            currentUserId,\n            ...(organizations?.map(org => org.id) || [])\n        ];\n        if (this._repositoryOwner.id === currentUserId || this._repositoryOwner.id === defaultOrganizationId) {\n            return ProjectViews.Yours;\n        }\n        if (!allOwners.includes(this._repositoryOwner.id)) {\n            return ProjectViews.SWY;\n        }\n        return undefined;\n    }\n\n    async move(destFolder: AdobeAsset): Promise<void> {\n        oneTimeWarning('[MOVE_UNSUPPORTED]', `Move on a project is not supported ${destFolder}`);\n        return;\n    }\n\n    /**\n     * A move method designed only for CSC Projects to encapsulate some of the buisiness logic\n     * reqiured to move a CSC Project to a new location.\n     *\n     * @service -- This method requires an allow listed Service Principal\n     *\n     */\n    async moveCSCProject(targetProjectId: string): Promise<void> {\n        const projectContext = await this._core.getProjectContext();\n        await projectContext.moveCSCProject(this.id, targetProjectId);\n    }\n\n    async rename(newName: string): Promise<void> {\n        if (!this._projectLinks?.[RelType.PROJECTS_RENAME]) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Rename link is missing for this project.');\n        }\n        if (!validatePlatformRepoName(newName)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for asset rename operation.');\n        }\n        await this._projectInterface.renameProject(newName, this._projectLinks);\n        const projectPool = this._core.projectContext._assetPool;\n        const assetContext = await this._core.getAssetContext();\n        // Update the repo:name and repo:path after a rename\n        const session = projectPool.createUpdateSession<Project>();\n        const newPath = renameFileInPath(newName, this);\n        updateCachedDescendents({\n            assetPool: this._core._getAssetPool(),\n            asset: this,\n            session,\n            operation: { type: 'rename', newPath },\n            assetContext\n        });\n        this._core.projectContext._projectUpdater.updateLocalItem(session, this, { 'repo:name': newName, 'repo:path': newPath });\n        session.commit();\n    }\n\n    /**\n     * Discards a project through the Projects service instead of RAPI.\n     *\n     */\n    async discard(): Promise<void> {\n        if (this.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Asset is already discarded');\n        }\n\n        await this._ensureLink(RelType.DISCARD);\n\n        await this._projectInterface.discardProject(this.id, this._projectLinks as IProjectLinks);\n        const projectPool = this._core._getAssetPool();\n        const assetContext = await this._core.getAssetContext();\n        const session = projectPool.createUpdateSession<Project>();\n\n        updateCachedDescendents({\n            assetPool: projectPool,\n            asset: this,\n            session,\n            operation: { type: 'discard' },\n            assetContext\n        });\n        this._core.projectContext._projectUpdater.updateLocalItem(session, this, { 'repo:state': 'DISCARDED' });\n        session.commit();\n    }\n\n    /**\n     * Restores a project through the Projects service instead of RAPI.\n     *\n     */\n    async restore(): Promise<void> {\n        if (!this.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Cannot restore an asset that is not discarded');\n        }\n\n        await this._ensureLink(RelType.RESTORE);\n        await this._projectInterface.restoreProject(this.id, this._projectLinks as IProjectLinks);\n        const projectPool = this._core._getAssetPool();\n        const assetContext = await this._core.getAssetContext();\n        const session = projectPool.createUpdateSession<Project>();\n        updateCachedDescendents({\n            assetPool: projectPool,\n            asset: this,\n            session,\n            operation: { type: 'restore' },\n            assetContext\n        });\n        this._core.projectContext._projectUpdater.updateLocalItem(session, this, { 'repo:state': 'ACTIVE' });\n        session.commit();\n    }\n\n    /**\n     * @package\n     **/\n    async _updateProjectLinksFromService() {\n        // load the project links using the project service\n        const returnProject = await this._projectInterface.getProject(this.id);\n        const { _links } = returnProject;\n\n        const projectPool = this._core.projectContext._assetPool;\n        const session = projectPool.createUpdateSession<Project>();\n        this._core.projectContext._projectUpdater.updateLocalItem(session, this, { _links });\n        session.commit();\n    }\n\n    /**\n     * @package\n     **/\n    _isProjectLinkType(relType: RelType): relType is keyof IProjectLinks {\n        return _projectLinkKeys().includes(relType);\n    }\n\n    async _ensureLink(relType: keyof (AssetLinks & IProjectLinks)): Promise<void> {\n        // if the link is in _projectLinks, copy the _projectLink into _links\n        // relType is an AssetsLink index, it might be a link that isn't in IProjectLinks\n        if (this._isProjectLinkType(relType)) {\n            if (!this._projectLinks?.[relType as keyof IProjectLinks]) {\n                await this._updateProjectLinksFromService();\n            }\n            const links: AssetLinks = { ...this.__links, [relType]: this._projectLinks![relType] } as AssetLinks;\n\n            //using the AssetUpdater instead of ProjectUpdater because ProjectUpdater has no way to update _links\n            const session = this._core.hostAssetContext._assetPool.createUpdateSession();\n            this._core.hostAssetContext._adobeAssetUpdater.updateLocalItem(\n                session,\n                this,\n                { '_links': links }\n            );\n            session.commit();\n            return;\n        }\n\n        //call out to fetch the missing link\n        this._core._environment.debug(`ProjectLinkMissing ${relType} Link ${relType} missing on project, called out fetch it`);\n        await super._ensureLink(relType);\n    }\n\n    /**\n     * Validates whether this project can be renamed to the provided name\n     * SAM will take in the name from the client and substitute this in the repo:path\n     * of the project to get an absolute path. Project service would need the absolute\n     * path to disambiguate between projects for accounts that contain projects in both\n     * shared storage (/content/assets) and user storage (/projects). Right now both these\n     * belong to the same repository and once we have the unified storage model they will\n     * have separate repository ids and we will be able to identify them using repository id.\n     * @param name name of the project to be validated for rename.\n     */\n    async validateProjectNameForRename(name: string): Promise<boolean> {\n        if (name.toLowerCase() === this.name.toLowerCase()) {\n            return true;\n        }\n\n        return await this._core.projectContext.validateProjectNameForCreate(name, this);\n    }\n\n    /**\n     * @experimental API May change.\n     * @deprecated - to be removed in a future major version on or after 2024-10-01. SAM-3333\n     */\n    async updateProperties(/* properties: IProjectProperties */) {}\n\n    /**\n     * Returns an enumeration with a more precise reason for why the user\n     * can or cannot leave the Project. It may also return PENDING if we are still\n     * loading collaborator information.\n     *\n     * @returns {ProjectLeaveReason} An enumeration of reasons why the user can or cannot leave.\n     */\n    @lazyLoaded(SharedCollaboratorChangedEvent, '_collaboratorsArray')\n    leaveStatus(): ProjectLeaveReason {\n        // Note: queues collaborators if not fetched already\n        const collaborators = this.collaboratorArray;\n\n        if (!this._isCollaboratorDataLoaded) {\n            return ProjectLeaveReason.PENDING;\n        }\n\n        // If there are no collaborators returned, they can't leave anyway\n        if (collaborators.length === 0) {\n            return ProjectLeaveReason.CANNOT_LEAVE_NO_COLLABORATORS;\n        }\n\n        const currentUserCollaborator = collaborators.find((c) => c.isCurrentUser);\n\n        // If the user doesn't exist in the collaborators list\n        // this user has inherited access to this project and thus they can't\n        // leave and we should return the address book group member error response.\n        if (!currentUserCollaborator) {\n            return ProjectLeaveReason.CANNOT_LEAVE_ADDRESS_BOOK_GROUP_MEMBER;\n        }\n\n        if (currentUserCollaborator.role === 'owner') {\n            return ProjectLeaveReason.CANNOT_LEAVE_IS_OWNER;\n        }\n\n        // Admins of the org have access to all Projects. But sometimes, they can be directly invited by other members\n        // to the Project, which in this case, they are allowed to leave the Project as direct collaborator.\n        // This only removes their entry in the `directCollaborators` list, but won't change the permission as admin\n        // still have access to all content. Without direct invite permission, on leave, we show toast message such\n        // that admin can't leave Project.\n        if (!currentUserCollaborator.isDirect && currentUserCollaborator.isAdmin) {\n            return ProjectLeaveReason.CANNOT_LEAVE_IS_ADMIN_OF_PROJECT;\n        }\n\n        // At this point if they are the only collaborator then\n        // they can't leave, this case happens when a CCI user creates\n        // a Project and they are the only collaborator direct or not.\n        if (collaborators.length === 1) {\n            return ProjectLeaveReason.CANNOT_LEAVE_LAST_COLLABORATOR;\n        }\n\n        // User cannot leave if they are no more collaborators who can share.\n        const anotherDirectCollabWithSharePermissions = collaborators.find((c) => c.canShare && c.isDirect && c !== currentUserCollaborator);\n        // We also need to distinguish between whether it is a USM project or shared-storage project.\n        // In shared-storage projects, the user can't leave if they are the last direct collaborator with share permissions.\n        // In user storage projects, the user can leave as long as she is not the owner of the project.\n        if (!anotherDirectCollabWithSharePermissions && this.storageAssignee.type !== 'user') {\n            return ProjectLeaveReason.CANNOT_LEAVE_LAST_DIRECT_COLLAB_WITH_SHARE_PERMISSION;\n        }\n\n        // If the user is not a direct collaborator and is also\n        // not and admin, they can't leave due to inheriting\n        // access to this project and not getting directly invited.\n        if (!currentUserCollaborator.isDirect) {\n            return ProjectLeaveReason.CANNOT_LEAVE_ADDRESS_BOOK_GROUP_MEMBER;\n        }\n\n        return ProjectLeaveReason.CAN_LEAVE;\n    }\n\n    /**\n     * Returns a boolean based on the userCanLeaveReason() response above.\n     *\n     * @deprecated -- Use {@link Project.leaveStatus instead} -- will be removed on or after 2024-10-01\n     *\n     * @returns Undefined while fetching collaborator data.\n     */\n    userCanLeaveProject(): boolean | undefined {\n        oneTimeWarning('userCanLeaveProject Deprecated', 'Use Project.leaveStatus instead.'\n            + ' This will be removed on or after 2024-10-01.');\n        const reason: ProjectLeaveReason = this.leaveStatus();\n        switch (reason) {\n        case ProjectLeaveReason.PENDING:\n            return;\n        case ProjectLeaveReason.CAN_LEAVE:\n            return true;\n        case ProjectLeaveReason.CANNOT_LEAVE_NO_COLLABORATORS:\n        case ProjectLeaveReason.CANNOT_LEAVE_ADDRESS_BOOK_GROUP_MEMBER:\n        case ProjectLeaveReason.CANNOT_LEAVE_LAST_COLLABORATOR:\n        case ProjectLeaveReason.CANNOT_LEAVE_LAST_DIRECT_COLLAB_WITH_SHARE_PERMISSION:\n        case ProjectLeaveReason.CANNOT_LEAVE_IS_ADMIN_OF_PROJECT:\n        case ProjectLeaveReason.CANNOT_LEAVE_IS_OWNER:\n            return false;\n        }\n    }\n\n    @observable\n    hasPermission(...permissions: Permission[]): boolean {\n        return permissions.every((permission) =>\n            (this._projectPermissions & permission) === permission);\n    }\n\n    /**\n     * Updates project data like gradientID\n     *\n     * @param data Data to be updated on a project.\n     */\n    async updateProject(data: IProjectPatchData) {\n        await this._core.projectContext.updateProject(this.id, data);\n    }\n\n    /**\n     * @package For SAM.js internal use only\n     * checks and sets the permission to restore the project\n     */\n    _applyRestorePermission(updateSession: IUpdateSession<Project>): void {\n        // We don't get the project permissions from USS right now so we try to infer the restore permissions\n        // A user has restore permissions if she can create a project in the repository.\n        const canRestore = this._core.projectContext._getCachedRestoreCapability(this.repositoryID);\n\n        const restorePermissionChanged = canRestore !== this.hasPermission(Permission.Restore);\n        this._projectPermissions = canRestore\n            ? (this._projectPermissions | Permission.Restore)\n            : (this._projectPermissions & ~Permission.Restore);\n\n        if (restorePermissionChanged) {\n            // Manually queue a changed item event since using the updater will not allow\n            // the change to be detected since we are modifying the bits and then asking\n            // the updater to compare the new value with the original value which is the same.\n            updateSession.queueChangedItem(this, [ SharedChangeEvent ]);\n        }\n    }\n\n    /**\n    * @package -- only for use in SAM.js\n    */\n    // TODO: SAM-3499 will allow us to make this more efficient.\n    async _reloadPermissions(): Promise<void> {\n        await this._load();\n        super._reloadPermissions();\n    }\n\n    @memoize\n    get librariesSource(): AdobeAssetSource {\n        const directoryLoader = new AdobeAssetDirectoryLoader(this._core.hostAssetContext._assetPool, this, this._core, true, true);\n        const implicitFilter = new ImplicitDirectoryListingAssetFilter({\n            asset: this,\n            mediaTypes: [ libraryMediaTypeString ],\n            // Any Asset in a Project can also be SWY\n            _isSharedWithYou: true\n        });\n        return new ItemSource(this._core.hostAssetContext._assetPool, [ directoryLoader ], implicitFilter);\n    }\n\n    @observable\n    get repositoryOwner(): Owner {\n        return this._repositoryOwner;\n    }\n\n    /**\n     * Creates a Library in this Project.\n     *\n     * @example\n     * const roles: LibraryRole[] = [{\n     *      type: 'brand',\n     *      usage: 'usage_brand',\n     *      priority: 'priority_brand'\n     * }];\n     * const library = project.createLibrary({ name: 'test', restrictEdit: true, roles });\n     *\n     */\n    async createLibrary(data: CreateProjectLibraryData): Promise<Library> {\n        const libraryContext = await this._core.getLibraryContext();\n        const options: CreateLibraryOptions = {\n            name: data.name,\n            parent_assetId: this.id,\n            roles: data.roles\n        };\n\n        options.access = data.restrictEdit ? 'team_view' : 'team_edit';\n\n        return libraryContext._createLibrary(options);\n    }\n\n    async updateLastAccessed(clear?: boolean): Promise<void> {\n        await super.updateLastAccessed(clear);\n        const session = this._core.projectContext._assetPool.createUpdateSession<Project>();\n        // [SHARED-3832] all Recent projects show in Recent list, but might not show in any other list, so only\n        // set isRecent here.\n        this._core.projectContext._projectUpdater.updateLocalItem(session, this, { isRecent: Boolean(this.lastAccessed) });\n        session.commit();\n    }\n\n    /**\n     * @experimental API May change.\n     *\n     * Creates a reference to a library for this project\n     * Only libraries can be referenced. Reference creation is restricted to\n     * assets with mime type 'application/vnd.adobe.library+dcx'.\n     *\n     * Users must have write permission to the project to create a reference.\n     * Users must have at least read permission on the library to be referenced.\n     *\n     * @param {string} assetId - the id of the library to reference\n     *\n     * @example <caption>Create a library reference</caption>\n     * const library: Library;\n     * await project.createLibraryReference(library.id);\n     *\n     */\n    async createLibraryReference(assetId: string): Promise<void> {\n        // call the service\n        await this._ensureLink(RelType.PROJECTS_REFERENCE_CREATE);\n        const { 'project:referenceId': libraryId } = await this._projectInterface.createLibraryReference(assetId, this._projectLinks as IProjectLinks);\n\n        // update the local library item with the referenced by project\n        const libraryContext = await this._core.getLibraryContext();\n        const library = await libraryContext.getLibraryByAssetId(libraryId);\n        const session = libraryContext._assetPool.createUpdateSession<Library>('create reference library');\n        libraryContext._libraryUpdater.updateLocalItem(session, library,\n            {\n                referenced_by_project: { projectId: this.id, reference: true }\n            });\n        session.commit();\n    }\n\n    /**\n     * @experimental API May change.\n     *\n     * Deletes a reference to a library for this project\n     *\n     * Users must have write permission to the project to delete a reference.\n     * Users must have at least read permission on the library to delete the reference.\n     *\n     * @param {string} assetId - the id of the library to delete the reference for\n     *\n     * @example <caption>Delete a library reference</caption>\n     * const library: Library;\n     * await project.deleteLibraryReference(library.id);\n     *\n     */\n    async deleteLibraryReference(assetId: string): Promise<void> {\n        // call the service\n        await this._ensureLink(RelType.PROJECTS_REFERENCE_PRIMARY);\n        await this._projectInterface.deleteLibraryReference(assetId, this._projectLinks as IProjectLinks);\n\n        // update the local library item to remove the referenced by project\n        // since this is a removal of the reference, we only need to update the library if its already in the asset pool\n        const assetPool = this._core.hostAssetContext._assetPool;\n        const localLibrary = assetPool.getLocalItemById<Library>(assetId);\n        if (localLibrary) {\n            const libraryContext = await this._core.getLibraryContext();\n            const session = libraryContext._assetPool.createUpdateSession<Library>('delete reference library');\n            libraryContext._libraryUpdater.updateLocalItem(session, localLibrary,\n                {\n                    referenced_by_project: { projectId: this.id, reference: false }\n                });\n            session.commit();\n        }\n    }\n\n    /**\n     * @experimental API May change.\n     * Requests access to inaccessible library references for this project.\n     * @param notification - The configuration that will be used to notify owners of the library references.\n     * @returns The result of the access request.\n     */\n    async requestAccessToLibraryReferences(notification: IAccessRequestNotification): Promise<IAccessRequestResult> {\n        if (this._inaccessibleLibraryReferences === undefined) {\n            oneTimeWarning('[INACCESSIBLE_REFERENCES_NOT_LOADED]', 'Inaccessible library references not loaded. No access requests will be made.');\n            return {\n                successfulRequests: [],\n                failedRequests: []\n            };\n        }\n\n        if (this._inaccessibleLibraryReferences.length === 0) {\n            // No inaccessible references - return successful empty result\n            return {\n                successfulRequests: [],\n                failedRequests: []\n            };\n        }\n\n        // By default request access to library references is a viewer\n        const permission: IAccessRequestPermissions = {\n            canComment: true,\n            canShare: true,\n            role: 'viewer'\n        };\n\n        const collaborationContext = await this._core.getCollaborationContext();\n        return await collaborationContext._requestAccess(\n            this._inaccessibleLibraryReferences,\n            notification,\n            permission\n        );\n    }\n}\n\nfunction getPermission(source: Partial<IProject>): Permission | typeof NotFound {\n    // From Project listing\n    if (source._embedded?.[RelType.AC_EFFECTIVE]) {\n        return parseProjectEffectivePermissions(source._embedded[RelType.AC_EFFECTIVE]!);\n    }\n    // If the permissions are not present in the metadata then maintain the current value\n    return NotFound;\n}\n\nexport type ProjectUpdaterMetadata = AdobeAssetUpdaterMetadata & {\n    projectPermissions?: Permission;\n    isRecent?: boolean;\n    allowInLists?: boolean;\n    inaccessibleReferences?: string[];\n}\n\nexport const ProjectUpdater = new ItemUpdater<Project, Partial<IProject | ProjectUpdaterMetadata>>({\n    localItemType: Project,\n    remoteIdProperty: 'repo:assetId',\n    propertyUpdater: new PropertyUpdater({\n        '_repositoryID': 'repo:repositoryId',\n        '_path': 'repo:path',\n        '_etag': 'repo:etag',\n        '_created': { name: 'repo:createDate', format: 'date' },\n        '_description': 'description',\n        '_name': 'repo:name',\n        '_assetState': { name: 'repo:state', choices: AssetStateChoices },\n        '_storageAssignee': { name: 'storage:assignee', format: StorageAssigneeFormat },\n        '_projectLinks': { name: '_links', format: 'object' },\n        '_creator': { name: `_embedded[${RelType.PROJECTS_CREATOR}]`, format: 'object' },\n        '_createdBy': `_embedded[${RelType.PROJECTS_CREATOR}].id`,\n        /**\n         * @note Adding single quotes to ['project:rendition'] causes the property\n         * name to be computed as ''project:rendition'' with two single quotes.\n         * This obviously will cause the property updater to not find the requested property and\n         * not update it so the property naming convention is [project:rendition]\n         * without single quotes around the name.\n         */\n        '_gradientID': {\n            name: `_embedded[${RelType.APP_METADATA}][project:rendition].gradientId`,\n            set: (gradientID: string, dest: ISAMObject) => {\n                const project = dest as Project;\n\n                if (!gradientID) {\n                    project['_gradientID'] = '';\n                    return;\n                }\n                const computedGradientID = computeGradientID(gradientID, project._core._environment.getValue('LOCALE')!);\n                if (project['_gradientID'] !== computedGradientID) {\n                    project['_gradientID'] = computedGradientID;\n                    LazyLoadManager.setLoadStatus(project, CHANGE, LoadStatus.NotLoaded);\n                }\n            }\n        },\n        '_projectPermissions': { get: getPermission, format: 'number' },\n        '_repositoryOwner': { name: `_embedded[${RelType.REPOSITORY}][repo:owner]`, format: StorageAssigneeFormat },\n        '_isRecent': { name: 'isRecent', format: 'boolean' },\n        '_allowInLists': { name: 'allowInLists', format: 'boolean' },\n        '_directorySubtype': { name: 'project:directorySubtype', choices: projectDirectorySubTypes },\n        '_inaccessibleLibraryReferences': { name: 'inaccessibleReferences', isArray: true, format: 'string' }\n    })\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type ProjectInterface from '../interface/ProjectsInterface';\nimport type { ProjectUpdaterMetadata } from './Project';\nimport type Project from './Project';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport { OrderFieldToIProjectsOrderBy } from './ProjectOrder';\nimport type ProjectFilter from './ProjectFilter';\nimport type { ProjectConfig } from './ProjectSource';\nimport type { IServiceLink } from '../interface/LinkUtils';\nimport type {\n    IProject,\n    IProjectsResponse,\n    IRecentProjectsResponse } from '../interface/ProjectsModel';\nimport {\n    PROJECT_VIEW_TO_SERVICE_MAP,\n    ProjectViews,\n} from '../interface/ProjectsModel';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type ItemUpdater from '../core/ItemUpdater';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { ORGANIZATIONS_CHANGED } from './OrganizationsChangedEvent';\nimport { LazyLoadManager } from '../core/decorators/LazyLoadManager';\n\n\nexport default class ProjectsListLoader implements IItemLoader<ProjectConfig> {\n\n    constructor(\n        private _projectPool: ItemPool<Project | AdobeAsset>,\n        private _projectInterface: ProjectInterface,\n        private _projectUpdater: ItemUpdater<Project, Partial<IProject | ProjectUpdaterMetadata>>,\n        private _core: ISAMCorePrivate\n    ) {\n    }\n\n    supportsFilter(filter?: ProjectFilter): boolean {\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<ProjectConfig>): Promise<ILoadedPage<ProjectConfig>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<ProjectConfig>, pageLink?: IServiceLink): Promise<ILoadedPage<ProjectConfig>> {\n        const { order, filter } = options;\n        const { limit } = options.loadOptions ?? {};\n\n        // We will ignore the update if we had local changes sooner than this timestamp.\n        // This default latency is set to 3 seconds right now. We should revisit this value.\n        const latency = this._projectPool._core._environment.getValue('PROJECTS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n\n        let result: IProjectsResponse | IRecentProjectsResponse;\n        if (pageLink) {\n            // We are loading the next page with the link provided.\n            result = await this._projectInterface.getProjectsWithLink(pageLink);\n        } else if (filter?.view === ProjectViews.Recent) {\n            const recentOptions = limit ? { first: limit } : {};\n            result = await this._projectInterface.getRecentProjects(recentOptions, options.resource);\n        } else {\n            // If ProjectFilter is not provided by the client, then it will be an EverythingFilter,\n            // so each ProjectFilter property needs to be checked for existence.\n\n            // Note: If `view` parameter is unspecified, the server uses All as the default\n            const view = !filter.view ? {} : { view: PROJECT_VIEW_TO_SERVICE_MAP[filter.view] };\n            const repositoryId = filter.repositoryID ? { repositoryId: filter.repositoryID } : {};\n            const nameContains = filter.nameContains ? { nameContains: filter.nameContains } : {};\n            const isDiscarded = filter.isDiscarded ? { isDiscarded: true } : {};\n            const directorySubtypes = filter.directorySubtypes ? { directorySubtypes: filter.directorySubtypes } : {};\n            const ownerIds: string[] = [];\n\n            // Yours view needs the org list to determine what filter parameters to send. SWY needs\n            // the org list to do client-side filtering.\n            if (filter.view === ProjectViews.Yours || filter.view === ProjectViews.SWY) {\n                await LazyLoadManager.fetchIfNeeded(this._core.hostAssetContext, ORGANIZATIONS_CHANGED);\n            }\n\n            if (filter.view === ProjectViews.Yours) {\n                const homeOrgId = this._core.hostAssetContext.defaultOrganizationId || '';\n                ownerIds.push(this._core._environment.getUserId());\n                if (homeOrgId) {\n                    ownerIds.push(homeOrgId);\n                }\n            } else if (filter.view === ProjectViews.Organization || filter.view === ProjectViews.Admin) {\n                if (filter.organizationID) {\n                    ownerIds.push(filter.organizationID);\n                }\n            }\n\n            result = await this._projectInterface.getProjects({\n                orderBy: OrderFieldToIProjectsOrderBy[order.field],\n                orderDirection: order.direction,\n                limit,\n                ...view,\n                ...repositoryId,\n                ...nameContains,\n                ...isDiscarded,\n                ...(ownerIds.length ? { ownerId: ownerIds.join(',') } : {}),\n                ...directorySubtypes\n            }, options.resource);\n        }\n\n        const session = this._projectPool.createLoaderUpdateSession<Project>(mostRecentValidMutation);\n        const projects: Partial<IProject | ProjectUpdaterMetadata>[] = result.children.map((project: IProject) =>\n            filter.view === ProjectViews.Recent\n                // [SAMJS-311] isRecent can only be set from Recent view; some Projects are only visible on Recent view\n                ? { ...project, isRecent: true }\n                : { ...project, allowInLists: true });\n        const items = this._projectUpdater.updateRemoteItems(session, projects);\n        session.commit();\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<ProjectConfig> | undefined;\n        const nextPageLink = result._links?.next;\n        if (nextPageLink) {\n            loadNextPage = (options: IItemLoaderOptions<ProjectConfig>) =>\n                this._loadPage(options, nextPageLink);\n        }\n\n        return {\n            items,\n            total: result._page?.total,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n}\n","/*************************************************************************\n*   ADOBE CONFIDENTIAL\n*\n*   Copyright 2024 Adobe\n*   All Rights Reserved.\n*\n*   NOTICE:  All information contained herein is, and remains\n*   the property of Adobe and its suppliers, if any. The intellectual\n*   and technical concepts contained herein are proprietary to Adobe\n*   and its suppliers and are protected by all applicable intellectual\n*   property laws, including trade secret and copyright laws.\n*   Dissemination of this information or reproduction of this material\n*   is strictly forbidden unless prior written permission is obtained\n*   from Adobe.\n**************************************************************************/\nimport type {\n    IImplicitFilter\n} from '../core/ItemFilter';\nimport type Project from './Project';\nimport { SAM } from '@ccx-public/component-types';\n\nexport default class ImplicitProjectFilter implements IImplicitFilter<Project> {\n    view: SAM.ProjectViews = SAM.ProjectViews.All;\n\n    matches(item: Project): boolean {\n        // [SHARED-3832] Projects should not show in lists until they're proven to be part of a list\n        // [SAMJS-311] All Projects flagged as _isRecent should show up in _isRecent view\n        return item.isProject && (item._allowInLists || item._isRecent);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { IContextAPIResponse } from '../interface/ProjectsInterface';\nimport ProjectsInterface from '../interface/ProjectsInterface';\nimport ItemPool from '../core/ItemPool';\nimport type {\n    ISAMCorePrivate,\n    ISAMObject\n} from '../indexPrivate';\nimport type { ProjectUpdaterMetadata } from './Project';\nimport type Project from './Project';\nimport { ProjectUpdater } from './Project';\nimport {\n    consolidated,\n    key,\n    memoize,\n    synchronized\n} from '../core/decorators';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport {\n    renameFileInPath,\n    updateCachedDescendents,\n    validatePlatformRepoName\n} from '../assets/AssetUtils';\nimport SAMError, {\n    isSAMError,\n    SAMErrorCode,\n    SAMErrorSubCode\n} from '../core/SAMError';\nimport type { ProjectSource } from './ProjectSource';\nimport ProjectsListLoader from './ProjectsListLoader';\nimport ItemSource from '../core/ItemSource';\nimport ProjectFilter from './ProjectFilter';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type {\n    Gradient } from './Gradient';\nimport {\n    GradientUpdater\n} from './Gradient';\nimport { computeGradients } from '../interface/GradientModel';\nimport { RelType } from '../interface/LinkUtils';\nimport type { ConfigurationPayload } from '../core/Environment';\nimport type IEvent from '../core/IEvent';\nimport { CONFIG_CHANGE } from '../core/SAMCoreEvents';\nimport type {\n    IProject,\n    IProjectPatchData } from '../interface/ProjectsModel';\nimport {\n    ProjectDirectorySubtype } from '../interface/ProjectsModel';\nimport {\n    CanCreateProjectReason,\n    ProjectCapabilities\n} from '../interface/ProjectsModel';\nimport type { AdobeAssetGlobalSearchSource } from '../assets/AdobeAssetSource';\nimport AdobeAssetGlobalSearchFilter from '../assets/AdobeAssetGlobalSearchFilter';\nimport GlobalSearchLoader from '../assets/GlobalSearchLoader';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport {\n    default as ProjectOrder,\n    type ProjectOrderField\n} from './ProjectOrder';\nimport ImplicitProjectFilter from './ImplicitProjectFilter';\nimport USSInterface from '../interface/USSInterface';\nimport { Permission } from '../interface/AssetModel';\nimport { SearchProps } from '../interface/USSModel';\nimport RepoMetadataResource from '../assets/RepoMetadataResource';\n\nexport interface IProjectCreate {\n    name: string;\n    gradientID: string;\n}\n\n/**\n * Provides all Project related functionality like getting\n * lists of projects among other features.\n *\n * @experimental This API is in an experimental phase so expect that\n * API\"s will not be final and there will be breaking changes\n * without bumping the major version until this comment is removed.\n */\nexport default class ProjectContext implements ISAMObject, SAM.ProjectContext {\n    private _projectInterface = new ProjectsInterface(this._core);\n    private _gradientPool = new ItemPool<Gradient>(this._core, 'gradient');\n    private _defaultGradient?: Gradient;\n    private _canRestoreProjectCache: Map<string, boolean> = new Map();\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        /**\n         * @package -- For use in SAM.js only\n         */\n        readonly _assetPool: ItemPool<Project | AdobeAsset>\n    ) {\n        // If the language configuration changes lets\n        // just start refetching the gradients automatically.\n        this._core.on(CONFIG_CHANGE,\n            (\n                event: IEvent,\n                sender: any,\n                payload: ConfigurationPayload\n            ) => {\n                if (payload.configurationKeyName === 'LOCALE') {\n                    this._getGradients();\n                }\n            }\n        );\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     * Updaters shouldn't be accessed directly.\n     */\n    readonly _projectUpdater =  ProjectUpdater;\n\n    /**\n     * @package -- only for use in SAM.js\n     * @deprecated Will be removed on or after 10-01-2024.\n     */\n    get assetPool(): ItemPool<Project | AdobeAsset> {\n        oneTimeWarning('ProjectContext._assetPool', 'This property is deprecated and will be removed on or after'\n            + ' 10-01-2024. For internal use by SAM.js only.');\n        return this._assetPool;\n    }\n\n    /**\n     * @experimental API May change.\n     *\n     * @example\n     * const projectContext = samCore.projectContext;\n     * const projectsSource = projectsContext.projects;\n     * const yourProjects = projectsSource.getList();\n     *\n     * @TODO SAM-2834\n     */\n    @memoize\n    projects(): ProjectSource {\n        // Trigger lazy-loading of the organizations if they haven't been loaded yet.\n        this._core.hostAssetContext.organizations;\n\n        const loader = new ProjectsListLoader(\n            this._assetPool,\n            this._projectInterface,\n            this._projectUpdater,\n            this._core\n        );\n        return new ItemSource(this._assetPool as ItemPool<Project>, [ loader ], new ImplicitProjectFilter());\n    }\n\n    /**\n     * @experimental API May change.\n     */\n    @keepAlive\n    async createProject(data: IProjectCreate) {\n        const { name, gradientID } = data;\n        if (!validatePlatformRepoName(name)) {\n            // Validate the name here to avoid resolving the asset if the name is invalid.\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for the rename operation.');\n        }\n\n        // Get the gradient and use the original gradient ID\n        // provided by the services when creating a project.\n        // The id for gradients is computed to include the language\n        // code as well.\n        const originalGradient = await this.getGradient(gradientID);\n        const response = await this._projectInterface.createProject({\n            [RelType.APP_METADATA]: {\n                'project:rendition': {\n                    'gradientId': originalGradient.gradientID\n                }\n            },\n            'repo:name': name\n        });\n        const session = this._assetPool.createMutationSession<Project>();\n        const project = this._projectUpdater.updateRemoteItem(session, { ...response, allowInLists: true } as Partial<IProject | ProjectUpdaterMetadata>);\n        session.commit();\n        return project;\n    }\n\n    /**\n     * Resolves a given name to a Project, if one exists.\n     * @param name name of the project to be resolved.\n     * @returns a promise that resolves to the Project with the given name.\n     */\n    async resolveProjectByName(name: string): Promise<Project> {\n        const projectMetadata: IProject = await this._projectInterface.resolveProjectByName(name);\n        const id: string = projectMetadata['repo:assetId'];\n        this._core.collaborationContext.confirmAccess(id);\n        const session = this._assetPool.createMutationSession<Project>();\n        const project = this._projectUpdater.updateRemoteItem(session, projectMetadata);\n        session.commit();\n        return project;\n    }\n\n    /**\n     * Validates whether the user can create a new project with the provided name.\n     * Project service is able to determine where to create the project for a user hence\n     * the name is sufficient for this validation.\n     * @param name name of the project to be validated for creation.\n     */\n    @consolidated\n    async validateProjectNameForCreate(@key name: string, project?: Project, repositoryID?: string): Promise<boolean> {\n        if (!validatePlatformRepoName(name)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid project name.');\n        }\n\n        let updatedName = name;\n        if (project) {\n            updatedName = renameFileInPath(name, project);\n        }\n\n        try {\n            await this._projectInterface.validateProjectName(updatedName, repositoryID);\n        } catch (e) {\n            const samError = e as SAMError;\n            if (samError.code === SAMErrorCode.NOT_FOUND) {\n                return true;\n            } else if (samError.code === SAMErrorCode.CONFLICT) {\n                return false;\n            }\n\n            // At this point the error is something else entirely and\n            // not related to the the availability of the name. Could\n            // be a networking error or something similar.\n            throw e;\n        }\n        return false;\n    }\n\n    /**\n     * Gets a project with the given ID.\n     *\n     * @note This method will automatically determine if it should call\n     * to confirm access with the invitations service.\n     *\n     * @param id ID of the project\n     * @param confirmAccess Whether to confirm access with the invitations service. NOTE - only\n     * to be used by services.\n     * @returns a promise that resolves to the Project with the given ID\n     */\n    @keepAlive\n    @synchronized\n    async getProjectbyID(@key id: string, confirmAccess: boolean = true): Promise<Project> {\n        let project = this._assetPool.getLocalItemById<Project>(id);\n        if (project) {\n            // Asynchronously confirm access since the user got here\n            // from a list or confirmed it before since it's in the cache so\n            // the call may not need to happen or may not affect the user.\n            if (confirmAccess) {\n                this._core.collaborationContext.confirmAccess(id);\n            }\n            return project;\n        }\n\n        if (confirmAccess) {\n            await this._core.collaborationContext.confirmAccess(id);\n        }\n        const projectMetadata = await this._projectInterface.getProject(id);\n        const session = this._assetPool.createMutationSession<Project>();\n        project = this._projectUpdater.updateRemoteItem(session, projectMetadata);\n        // [SHARED-3832] Read-only Org-owned Projects should not show on lists unless the user was invited\n        // directly or invited via a group other than \"Org Everybody\". This is done in SAM.js rather than by Projects\n        // Service so that the check can be done async so it does not block getting the Project for 1Up, badging.\n        if (!project.hasPermission(Permission.Write) && project.repositoryOwner.type === 'org') {\n            // Note: check is done async\n            this._checkForInvite(project);\n        } else {\n            // otherwise, assume Project can be found on lists\n            this._projectUpdater.updateLocalItem(session, project, { allowInLists: true });\n        }\n        session.commit();\n        return project;\n    }\n\n    /**\n     * [SHARED-3832] Checks if the Project is visible to the user due to invitation, whether by group or direct invite.\n     * Uses USS rather than Invitation service because it is difficult to check if the user has access due to group\n     * invite.\n     *\n     * @param {Project} project\n     * @returns {Promise<void>}\n     * @private\n     */\n    private async _checkForInvite(project: Project): Promise<void> {\n        const ussInterface = new USSInterface(this._core);\n        const response = await ussInterface.getQueryResponse({\n            limit: 1,\n            asset_id: project.id,\n            [SearchProps.SHARED_VIA_INVITE]: true\n        });\n        // If there are any items, the user was invited to the Project\n        if (response.result_sets[0].items.length) {\n            const session = this._assetPool.createUpdateSession<Project>();\n            this._projectUpdater.updateLocalItem(session, project, { allowInLists: true });\n            session.commit();\n        }\n    }\n\n    private async _getGradients(): Promise<Gradient[]> {\n        const locale = this._core._environment.getValue('LOCALE')!;\n        const gradientData = await this._projectInterface.getGradients(locale);\n        const defaultGradientId = gradientData.default;\n        const session = this._gradientPool.createUpdateSession();\n        const computedGradients = computeGradients(gradientData.children, defaultGradientId, locale);\n        const gradients: Gradient[] = GradientUpdater.updateRemoteItems(session, computedGradients);\n        session.commit();\n        return gradients;\n    }\n\n    /**\n     * Returns the list of available gradients.\n     */\n    async getGradients(): Promise<Gradient[]> {\n        return await this._getGradients();\n    }\n\n    /**\n     * Gets a single gradient by ID if that gradient does not\n     * locally we fetch all the gradients and if it still does not\n     * exist then we return the default gradient provided.\n     *\n     * @param id\n     * @returns\n     */\n    async getGradient(id: string): Promise<Gradient> {\n        const gradient = this._gradientPool.getLocalItemById(id);\n        const locale = this._core._environment.getValue('LOCALE');\n        if (gradient && gradient.languageCode === locale) {\n            return gradient;\n        }\n\n        await this._getGradients();\n        const newGradient = this._gradientPool.getLocalItemById(id);\n\n        if (!newGradient) {\n            if (this._defaultGradient && this._defaultGradient.languageCode === locale) {\n                return this._defaultGradient;\n            }\n\n            this._gradientPool.forEach((gradient: Gradient) => {\n                if (gradient.isDefault) {\n                    this._defaultGradient = gradient;\n                }\n            });\n\n            if (this._defaultGradient) {\n                return this._defaultGradient;\n            }\n\n            // There should always be a default gradient but in the case\n            // where maybe it doesn't exist we should still throw an error\n            throw SAMError.create(SAMErrorCode.UNKNOWN, `Gradient ID does not exist ${id}`);\n        }\n\n        return newGradient;\n    }\n\n    async updateProject(id: string, data: IProjectPatchData) {\n        let newData = {};\n        if (data.gradientID)  {\n            const gradient = await this.getGradient(data.gradientID);\n            const project = await this.getProjectbyID(id);\n            const links = project.projectLinks!;\n            newData = { ...newData, ...{ gradientID: gradient.gradientID } };\n            await this._projectInterface.patchProject(links, newData);\n\n            const session = this._assetPool.createMutationSession<Project>();\n            this._projectUpdater.updateRemoteItem(session, {\n                'repo:assetId': project.id,\n                _embedded: {\n                    [RelType.APP_METADATA]: {\n                        'project:rendition': {\n                            /**\n                             * @note when updating the local model with\n                             * \"remote\" data, we should use the raw gradientID\n                             * instead of the computed one.\n                             */\n                            gradientId: gradient.gradientID\n                        }\n                    }\n                }\n            });\n            session.commit();\n        }\n    }\n\n    /**\n     * Used to hide and show the create button for users who may or may not\n     * have the required privileges to do so.\n     * @note Does not throw errors, use canCreateProjectReason to determine the specific\n     * reason behind why a user can or cannot create a project.\n     *\n     * @param repositoryID Optional repositoryID for admins for who have access to multiple repos.\n     * @returns {boolean}\n     */\n    async canCreateProjects(repositoryID?: string): Promise<boolean> {\n        try {\n            await this._projectInterface.getCapability(ProjectCapabilities.CREATE, repositoryID);\n            return true;\n        } catch (e) {\n            // If it's not a sam error then something else happened\n            // and we should throw that error.\n            if (!isSAMError(e)) {\n                throw e;\n            }\n\n            return false;\n        }\n    }\n\n    /**\n     * @package for internal SAM.js use only.\n     * @param repositoryID the repository id of the project\n     * Restoring capability is same as the capability to create a project.\n     */\n    async _canRestoreProject(repositoryID: string): Promise<boolean> {\n        if (this._canRestoreProjectCache.has(repositoryID)) {\n            return this._canRestoreProjectCache.get(repositoryID)!;\n        }\n        const canRestore = await this.canCreateProjects(repositoryID);\n        this._canRestoreProjectCache.set(repositoryID, canRestore);\n        return canRestore;\n    }\n\n    /**\n     * @package for internal SAM.js use only.\n     * @param repositoryID the repository id of the project\n     */\n    _getCachedRestoreCapability(repositoryID: string): boolean {\n        return this._canRestoreProjectCache.get(repositoryID) || false;\n    }\n\n    /**\n     * @package for internal SAM.js use only.\n     * @returns a promise that resolves to the index of the project.\n     */\n    @synchronized\n    async _prefetchIndex() {\n        await this._projectInterface._discoverProjectLinks();\n    }\n\n    /**\n     * Used to determine the specific reasoning behind why a user can't\n     * create projects. Returns unknown if the error is unrelated to\n     * one of the \"known\" reasons.\n     *\n     * @param repositoryID\n     * @returns\n     */\n    async canCreateProjectReason(repositoryID?: string): Promise<CanCreateProjectReason> {\n        try {\n            await this._projectInterface.getCapability(ProjectCapabilities.CREATE, repositoryID);\n            return CanCreateProjectReason.ALLOWED;\n        } catch (error) {\n            if (!isSAMError(error)) {\n                return CanCreateProjectReason.UNKNOWN;\n            }\n            switch (error.subCode) {\n            case SAMErrorSubCode.PROJECTS_ADMIN_ONLY:\n                return CanCreateProjectReason.ADMIN_DISABLED;\n            case SAMErrorSubCode.PROJECTS_NO_HOME_REPOSITORY:\n                return CanCreateProjectReason.NO_HOME_REPOSITORY;\n            case SAMErrorSubCode.PROJECTS_INVALID_REPOSITORY:\n                return CanCreateProjectReason.INVALID_REPOSITORY;\n            default:\n                return CanCreateProjectReason.UNKNOWN;\n            }\n        }\n    }\n\n    /**\n     * Provides a AdobeAssetGlobalSearchFilter that goes directly to USS for search results\n     *\n     * @note all project related properties will be lazily fetched in this case.\n     *\n     * @TODO https://jira.corp.adobe.com/browse/SHARED-3489\n     * @param {string} query Query string for search.\n     * @returns {AdobeAssetGlobalSearchFilter}\n     */\n    getProjectsSearchSource(query: string): AdobeAssetGlobalSearchSource {\n        const implicitFilter = new AdobeAssetGlobalSearchFilter({\n            _query: query,\n            _projectsOnly: true\n        });\n        const globalSearchLoader = new GlobalSearchLoader(\n            this._core.hostAssetContext._assetPool,\n            this._core,\n            this._core.hostAssetContext._globalSearchInterfaceV3,\n            implicitFilter\n        );\n        return new ItemSource(this._assetPool, [ globalSearchLoader ], implicitFilter);\n    }\n\n    /**\n     * It has been reported that sometimes a Project asset is missing the parent project id in the inherited property\n     * of the app metadata [SAM-3590]. This method is used to call the Context API [CCXB-20015] which was implemented\n     * to address the issue in the following ways:\n     * 1. Returns the parent project id so SAM.js can fix the inherited property of the local child asset.\n     * 2. Fixes the inheritable property of the parent project if it is missing data.\n     * 3. Fixes the inherited property of the child asset if it is missing data.\n     * @param assetId\n     * @param repoId\n     * @package -- only for use in SAM.js\n     */\n    async _callContextAPI(assetId: string, repoId: string): Promise<IContextAPIResponse> {\n        const discoveryLinks = await this._projectInterface._discoverProjectLinks();\n        const href = discoveryLinks[RelType.PROJECTS_CONTEXT].href;\n        return await this._projectInterface._issueContextAPIRequest(assetId, repoId, href);\n    }\n\n    /**\n     * @experimental\n     */\n    getProjectOrder(direction: IOrderDirection = 'ascending', field: ProjectOrderField = 'name'): ProjectOrder {\n        return new ProjectOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getProjectFilter(options?: SAM.IProjectFilterOptions): ProjectFilter {\n        return new ProjectFilter(options);\n    }\n\n    /**\n     * @experimental\n     *\n     * @internal This method requires Service Token Authentication\n     * the associated IMS client ID must be allowlisted (Only the Workfront client ID\n     * will be allowlisted for this API).\n     * @param {string} name - The name of the project.\n     * @param {CSCProjectDirectorySubtype} - The CSC Project SubType.\n     * @param {string} path The path to be created relative to the Workfront top-level. Similar to RAPI create,\n     * This does not represent the entire path, but only the directories that should be created\n     * under the top-level \"/workfront\" directory returned by Index Workfront API.\n     * This should include the Project name as the final segment of the path. If both\n     * this parameter and the \"repo:assetId\" are provided or the provided \"repo:path\"\n     * contains an existing Project, then an error will be returned (see Response).\n     *\n     * @param {string} orgId - The Organization ID that the Project will be created within.\n     * @param {string} userId - The IMS User ID that the CSC Project creation is on behalf of. The \"repo:createdBy\"\n     * will be set to this value when creating the CSC Project directory. The user will\n     * also be given Editor permission to the CSC Project.\n     *\n     * @param {Record<string, any>} [appMetadata] - The app metadata to be set on the CSC Project.\n     */\n    async createCSCProjectByPath(\n        name: string,\n        subType: ProjectDirectorySubtype,\n        path: string,\n        orgId: string,\n        userId?: string,\n        appMetadata?: Record<string, any>\n    ): Promise<Project> {\n        return this._createCSCProject({ name, subType, path, orgId, userId, appMetadata });\n    }\n\n    /**\n     * @experimental\n     *\n     * @internal This method requires Service Token Authentication\n     * the associated IMS client ID must be allowlisted (Only the Workfront client ID\n     * will be allowlisted for this API).\n     *\n     * @throws {SAMError.BAD_REQUEST} if the parent is not a WF_PORTFOLIO or WF_PROGRAM.\n     *\n     * @param {string} name - The name of the project.\n     * @param {CSCProjectDirectorySubtype} - The CSC Project SubType.\n     * @param {string} orgId - The Organization ID that the Project will be created within.\n     * @param {string} parentAssetId  - The asset ID of the Project that the new Project should be created within.\n     * The Project will be validated to ensure that it is of subType \"wfPortolio\" or \"wfProgram\".\n     * If this parameter is not provided, then the Project will be created starting from the top-level.\n     * If both this parameter and the \"repo:path\" are provided, then an error will be returned (see Response).\n     *\n     * @param {string|undefined} [userId] - The IMS User ID that the CSC Project creation is on behalf of. The \"repo:createdBy\"\n     * will be set to this value when creating the CSC Project directory. The user will\n     * also be given Editor permission to the CSC Project.\n     *\n     * @param {Record<string, any>} [appMetadata] - The app metadata to be set on the CSC Project.\n     */\n    async createCSCProjectInParent(\n        name: string,\n        subType: ProjectDirectorySubtype,\n        parentAssetId: string,\n        orgId: string,\n        userId?: string,\n        appMetadata?: Record<string, any>\n    ): Promise<Project> {\n        return this._createCSCProject({ name, subType, parentAssetId, orgId, userId, appMetadata });\n    }\n\n    /**\n     * A move method designed only for CSC Projects to encapsulate some of the business logic\n     * required to move a CSC Project to a new location.\n     *\n     * @service -- This method requires an allow listed Service Principal\n     */\n    async moveCSCProject(sourceProjectId: string, targetProjectId: string): Promise<void> {\n        const project = await this.getProjectbyID(sourceProjectId, false);\n\n        if (project.directorySubtype === ProjectDirectorySubtype.CC_PROJECTS) {\n            throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Move is only supported for CSC Projects');\n        }\n\n        const sourceProjectLinks = project.projectLinks!;\n\n        // Pass the target project ID and the source project links.\n        await this._projectInterface.moveCSCProject(targetProjectId, sourceProjectLinks);\n        const assetContext = await this._core.getAssetContext();\n        // Projects service does not return the new project metadata, so we need to fetch it again eventually.\n        const newTargetMetadata = await this._projectInterface.getProject(sourceProjectId);\n        const session = this._assetPool.createMutationSession<Project>();\n\n        // Update any cached descendants of the source project.\n        updateCachedDescendents({\n            assetPool: this._assetPool,\n            asset: project,\n            session,\n            operation: { type: 'move', newPath: newTargetMetadata['repo:path'] },\n            assetContext\n        });\n\n        this._projectUpdater.updateRemoteItem(session, newTargetMetadata);\n        session.commit();\n    }\n\n    /**\n     *\n     * The private implementation for the above public CSC Create* methods.\n     *\n     * @note Only accepts either a path or a parentAssetId, both will result in an error\n     * from the services.\n     */\n    private async _createCSCProject(opts: {\n        name: string;\n        subType: ProjectDirectorySubtype;\n        parentAssetId?: string;\n        path?: string;\n        orgId: string;\n        userId?: string;\n        appMetadata?: Record<string, any>;\n    }) {\n        const { name, subType, parentAssetId, path, orgId, userId, appMetadata } = opts;\n\n        if (!validatePlatformRepoName(name)) {\n            // Validate the name here to avoid resolving the asset if the name is invalid.\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided');\n        }\n        const baseCSCCreateOptions = {\n            name,\n            projectDirectorySubType: subType,\n            ...(appMetadata ? {\n                appMetadata: { ...appMetadata }\n            } : {})\n        };\n\n        let createData;\n        if (parentAssetId) {\n            createData = {\n                ...baseCSCCreateOptions,\n                parentAssetId\n            };\n        } else {\n            createData = {\n                ...baseCSCCreateOptions,\n                path: path!\n            };\n        }\n\n        const cscProjectMetadata = await this._projectInterface.createCSCProject(\n            createData,\n            orgId,\n            userId\n        );\n\n        const session = this._assetPool.createMutationSession<Project>();\n        const cscProject = this._projectUpdater.updateRemoteItem(\n            session,\n            {\n                ...cscProjectMetadata,\n                allowInLists: true\n            } as Partial<IProject | ProjectUpdaterMetadata>\n        );\n        session.commit();\n\n        // Ensure links and repository metadata is presents since Projects API doesn't provide any links or metadata\n        // we can't call _Load() because it calls into permissions, PUPA which the service token may not have\n        // access to for the time being.\n        const resource = new RepoMetadataResource(this._core, cscProject);\n        await resource.load();\n        await cscProject._handleResourceUpdates({\n            repoMetadata: resource.data,\n        });\n\n        return cscProject;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '../SAMError';\nimport type { IHasKeyMap } from './key';\nimport { KeysProperty } from './key';\n\n/**\n * The @consolidated decorator is for async methods where multiple calls in parallel can be combined into one\n * call. E.g., if caller1 is waiting for a response and caller2 makes a call, caller2 will receive the same\n * response as caller1.\n *\n * Often used in lazy-load cases where the data needs to be fetched only once initially, and only once when\n * it needs refreshing.\n **\n * A parameter can be marked as @key, allowing multiple concurrent calls so long as the keys are different.\n */\nexport default (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n    const promisesMapProperty = Symbol(`@consolidated ${propertyKey}`);\n    const method = descriptor.value;\n    if (!method) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, '@consolidated decorator can only be applied to a method');\n    }\n    descriptor.value = async function (this: IHasKeyMap & { [promisesMapProperty]: Map<string, ReturnType<typeof method>> }, ...args: any[]) {\n        const keyIndex = this[KeysProperty]?.get(propertyKey);\n        const key: string = keyIndex === undefined ? 'default' : args[keyIndex];\n\n        const map = this[promisesMapProperty] || (this[promisesMapProperty] = new Map);\n        const promise = map.get(key);\n        // Another call is pending, so piggy-back on it\n        if (promise) {\n            return promise;\n        } else {\n            // Track this call so other callers can piggy-back on it\n            const promise = method.apply(this, args);\n            map.set(key, promise);\n            promise.finally(() => {\n                map.delete(key);\n            });\n            return promise;\n        }\n    };\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ValidationMap } from '../utils/classroomUtils';\nimport { getMemberComputedKey, validateTypes } from '../utils/classroomUtils';\nimport type { IClassroomMember, IRemoteClassroomMembers } from './ClassroomMemberModel';\nimport { ClassroomMemberRole } from './ClassroomMemberModel';\nimport type { IClassroomCreateData, IClassroomUpdateData, IRemoteBlockOrRemoveResponse, IRemoteClassroom, IRemoteMembership, ICoTeacherEligibilityEntry, ICheckCoTeacherEligibilityOptions } from './ClassroomModel';\nimport { SubjectTypes } from './ClassroomModel';\nimport InterfaceBase from './InterfaceBase';\nimport type { HeaderMap } from './LinkUtils';\nimport { JSON_MIME_TYPE } from './LinkUtils';\n\nconst API_ROOT = '/api/v1';\nconst headers: HeaderMap = { 'Content-Type': JSON_MIME_TYPE };\n\ninterface IRefreshCodeResponse {\n    classroomId: string;\n    classcode: string;\n}\n\nexport function validateClassroomData(data: IClassroomCreateData): string[] {\n    const errors: string[] = [];\n\n    // Handle basic validation\n    const classroomDataToValidate: ValidationMap<IClassroomCreateData>[] = [\n        { key: 'subject', type: 'enum', isRequired: false, ref: SubjectTypes },\n        { key: 'grades', type: 'string[]', isRequired: false },\n        { key: 'period', type: 'string', isRequired: false },\n        { key: 'teachers', type: 'string[]', isRequired: false },\n    ];\n\n    errors.push(...validateTypes(classroomDataToValidate, data));\n\n    // Handle validation of virtual and non-virtual classrooms\n    const hasName = typeof data.name === 'string' && data.name !== null;\n    const hasId = typeof data.id === 'string' && data.id !== null;\n\n    // One of these must be defined\n    // Both _can_ be defined, but id will take precedence and name will be ignored\n    if (!hasName && !hasId) {\n        errors.push('name or id is missing');\n    }\n\n    return errors;\n}\n\nexport default class ClassroomsInterface extends InterfaceBase {\n    /** Overrides the default behavior for a 202 response */\n    protected async _monitorResponse(response: Response): Promise<Response> {\n        return response;\n    }\n\n    private _getUrl(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.CLASSROOMS_HOST}${endpoint}`;\n    }\n\n    /**\n     * @description Creates a new Classroom\n     *\n     * @param data needed to create a Classroom like name and subject\n     * @returns promise resolving to the newly created Classroom\n    */\n    async createClassroom(data: IClassroomCreateData): Promise<IRemoteClassroom> {\n        const response = await this._doPost(this._getUrl(`${API_ROOT}/classrooms`), headers, JSON.stringify({\n            className: data.name,\n            subject: data.subject,\n            grades: data.grades,\n            period: data.period,\n            teachers: data.teachers?.map(email => encodeURIComponent(email)) || []\n        }), [ 201 ]);\n        const jsonResponse = await response.json();\n\n        return jsonResponse;\n    }\n\n    /**\n     * Creates a new Classroom from a virtual class\n     * @param id that maps to the virtual classroom being migrated to a real class\n     * @returns promise resolving to the newly created Classroom\n    */\n    async createClassroomFromVirtual(virtualClassroomId: string): Promise<IRemoteClassroom> {\n        const response = await this._doPost(this._getUrl(`${API_ROOT}/classrooms/virtual/${virtualClassroomId}/create`), { 'Content-Type': JSON_MIME_TYPE }, undefined, [ 201 ]);\n        const jsonResponse = await response.json();\n\n        return jsonResponse;\n    }\n\n    /**\n     * Creates a new Classroom with updated metadata from a virtual class\n     * @param id that maps to the virtual classroom being migrated to a real class\n     * @param data that the real classroom will be created with\n     * @returns promise resolving to the newly created Classroom\n    */\n    async updateClassroomFromVirtual(virtualClassroomId: string, data: IClassroomCreateData): Promise<IRemoteClassroom> {\n        const response = await this._doPost(this._getUrl(`${API_ROOT}/classrooms/virtual/${virtualClassroomId}/update`), { 'Content-Type': JSON_MIME_TYPE }, JSON.stringify({\n            className: data.name,\n            subject: data.subject,\n            grades: data.grades,\n            period: data.period,\n            teachers: data.teachers?.map(email => encodeURIComponent(email)) || []\n        }), [ 201 ]);\n        const jsonResponse = await response.json();\n\n        return jsonResponse;\n    }\n\n    /**\n     * @description Deletes a single classroom\n     *\n     * @param id Either the classId or the classCode.  The endpoint queries both.\n    */\n    async deleteClassroom(id: string): Promise<void> {\n        await this._doDelete(this._getUrl(`${API_ROOT}/classrooms/${id}`), headers, [ 202 ]);\n    }\n\n    /**\n     * @description Deletes a single virtual classroom\n     *\n     * @param id the classId\n    */\n    async deleteVirtualClassroom(id: string): Promise<void> {\n        await this._doPost(this._getUrl(`${API_ROOT}/classrooms/virtual/${id}/delete`), headers, undefined, [ 202 ]);\n    }\n\n    /**\n     * @description Gets a single classroom by class ID\n     *\n     * @param id Either the classId or the classCode.  The endpoint queries both.\n     * @returns A promise that resolves to a classroom\n     */\n    async getClassroom(id: string): Promise<IRemoteClassroom> {\n        const response = this._getResponse(this._getUrl(`${API_ROOT}/classrooms/${id}`));\n        return response.then((classroom: any) => {\n            // Handle the null value of importedFrom in ACPCEDU-1892\n            classroom.importedFrom ??= {};\n            return classroom;\n        });\n    }\n\n    /**\n     * @description Gets a list of all available classrooms\n     *\n     * @returns A promise that resolves to a list of classrooms\n     */\n    async getClassrooms(): Promise<IRemoteClassroom[]> {\n        const response = this._getResponse(this._getUrl(`${API_ROOT}/classrooms`));\n\n        // Handle the null value of importedFrom in ACPCEDU-1892\n        return response.then((classrooms) => {\n            return (classrooms as any[]).map((classroom) => {\n                classroom.importedFrom ??= {};\n                return classroom;\n            });\n        });\n    }\n\n    /**\n     * @description Refreshes the classroom code for a given classroom\n     *\n     * @param id The classroom ID associated with a single classroom\n     * @returns A promise that resolves to a classroom\n     */\n    async refreshClassroomCode(id: string): Promise<IRefreshCodeResponse> {\n        return this._doPut(this._getUrl(`${API_ROOT}/classrooms/${id}/code/refresh`), undefined, undefined, [ 200 ]).then((response) => response.json());\n    }\n\n    /**\n     * Updates a classroom with new data\n     * @param id The classroom ID\n     * @param data The new data that the classroom will be updated with\n     * @returns A promise that resolves to the classroom with updated fields\n     */\n    async updateClassroom(id: string, data: IClassroomUpdateData): Promise<Partial<IRemoteClassroom>> {\n        const response = await this._doPatch(this._getUrl(`${API_ROOT}/classrooms/${id}`), { 'Content-Type': JSON_MIME_TYPE }, JSON.stringify({\n            className: data.name,\n            subject: data.subject,\n            grades: data.grades,\n            period: data.period,\n            teachers: data.teachers?.map(email => encodeURIComponent(email)) || [],\n        }));\n        return response.json();\n    }\n\n    /**\n     * Gets the teachers of a classroom\n     * @param id The classroom ID\n     * @returns Teachers of a given classroom\n     */\n    async getClassroomTeachers(id: string): Promise<IClassroomMember[]> {\n        return this.getClassroomMembers(id, ClassroomMemberRole.TEACHER);\n    }\n\n    /**\n     * Gets the students of a classroom\n     * @param id The classroom ID\n     * @returns Students of a given classroom, wrapped in a classroom object for the list loader\n     */\n    async getClassroomStudents(id: string): Promise<IClassroomMember[]> {\n        return await this.getClassroomMembers(id, ClassroomMemberRole.STUDENT);\n    }\n\n    /**\n     * Gets the members of a classroom\n     * @param id The classroom ID\n     * @param filter The filter to apply to the members, either 'students' or 'teachers'. If not provided, all members are returned.\n     * @returns Members of a given classroom\n     */\n    async getClassroomMembers(id: string, filter: ClassroomMemberRole): Promise<IClassroomMember[]> {\n        const urlFilter = filter === ClassroomMemberRole.NONE ?  '' : `/${filter}s`;\n        const url = `${API_ROOT}/classrooms/${id}/members${urlFilter}`;\n        const classroomResponse: IRemoteClassroomMembers = await this._getResponse(this._getUrl(url));\n\n        // Response doesn't include classroomId on each member, so need to add it here\n        classroomResponse.members.forEach((member) => {\n            member.classroomId = id;\n            member.computedKey = getMemberComputedKey(id, member.userId);\n        });\n\n        return classroomResponse.members;\n    }\n\n    /**\n     * Gets the membership status of a user in a classroom\n     * @param id The classroom ID\n     *\n     * @returns Membership status of the user in the classroom\n     */\n    async getMembership(id: string): Promise<IRemoteMembership> {\n        return this._getResponse(this._getUrl(`${API_ROOT}/classrooms/${id}/members/status`));\n    }\n\n    /**\n     * Blocks a student from a classroom\n     *\n     * @param classroomId Class ID of the classroom to block the student from\n     * @param studentId Student ID to block\n     *\n     * @returns A promise that resolves to the response from the server\n     */\n    async blockStudent(classroomId: string, studentId: string): Promise<IRemoteBlockOrRemoveResponse> {\n        const response = await this._doPost(this._getUrl(`${API_ROOT}/classrooms/${classroomId}/members/students/block`), headers, JSON.stringify({\n            studentId\n        }), [ 200 ]);\n        return await response.json();\n    }\n\n    /**\n     * Unblocks a student from a classroom\n     *\n     * @param classroomId Class ID of the classroom to unblock the student from\n     * @param studentId Student ID to unblock\n     *\n     * @returns A promise that resolves to the response from the server\n     */\n    async unblockStudent(classroomId: string, studentId: string): Promise<IRemoteBlockOrRemoveResponse> {\n        const response = await this._doPost(this._getUrl(`${API_ROOT}/classrooms/${classroomId}/members/students/unblock`), headers, JSON.stringify({\n            studentId\n        }), [ 200 ]);\n        return await response.json();\n    }\n\n    /**\n     * Removes a student from a classroom\n     *\n     * @param classroomId Class ID of the classroom to remove the student from\n     * @param studentId Student ID to remove\n     *\n     * @returns A promise that resolves to the response from the server\n     */\n    async removeStudent(classroomId: string, studentId: string): Promise<IRemoteBlockOrRemoveResponse> {\n        const response = await this._doDelete(this._getUrl(`${API_ROOT}/classrooms/${classroomId}/members/students?studentId=${studentId}`), headers, [ 202 ]);\n        return await response.json();\n    }\n\n    /**\n     * Removes a teacher from a classroom\n     *\n     * @param classroomId Class ID of the classroom to remove the teacher from\n     * @param userId Teacher's user ID to remove\n     *\n     * @returns A promise that resolves to the response from the server\n     */\n    async removeTeacher(classroomId: string, userId: string): Promise<IRemoteBlockOrRemoveResponse> {\n        const response = await this._doDelete(this._getUrl(`${API_ROOT}/classrooms/${classroomId}/members/teachers?userId=${userId}`), headers, [ 202 ]);\n        return await response.json();\n    }\n\n    /**\n     * Checks eligibility of users to be added as co-teachers to a classroom\n     *\n     * @param options The options for checking co-teacher eligibility\n     * @returns A promise that resolves to the eligibility response from the server\n     */\n    async checkCoTeacherEligibility(options: ICheckCoTeacherEligibilityOptions): Promise<Array<ICoTeacherEligibilityEntry>> {\n        const response = await this._doPost(\n            this._getUrl(`${API_ROOT}/classrooms/users/eligibility`),\n            headers,\n            JSON.stringify({\n                classroomId: options.classroomId,\n                role: 'teacher',\n                emails: options.emails,\n            }),\n            [ 200 ]\n        );\n        return await response.json();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ClassroomsInterface from '../interface/ClassroomsInterface';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type ClassroomMember from './ClassroomMember';\nimport { ClassroomMemberUpdater } from './ClassroomMember';\nimport type { ClassroomMemberConfig } from './ClassroomMemberSource';\nimport type ClassroomMemberFilter from '../classrooms/ClassroomMemberFilter';\n\nexport default class ClassroomMemberListLoader implements IItemLoader<ClassroomMemberConfig> {\n    constructor(private _ClassroomMemberPool: ItemPool<ClassroomMember>, private _classroomsInterface: ClassroomsInterface) {}\n\n    async loadPage(options: IItemLoaderOptions<ClassroomMemberConfig>): Promise<ILoadedPage<ClassroomMemberConfig>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<ClassroomMemberConfig>): Promise<ILoadedPage<ClassroomMemberConfig>> {\n        const { filter } = options;\n        const classroomMemberFilter = filter as ClassroomMemberFilter;\n\n        const result = await this._classroomsInterface.getClassroomMembers(classroomMemberFilter.classroomId, classroomMemberFilter.role);\n        const session = this._ClassroomMemberPool.createLoaderUpdateSession<ClassroomMember>(Date.now());\n        const items = ClassroomMemberUpdater.updateRemoteItems(session, result);\n        session.commit();\n\n        return {\n            items,\n            total: items.length,\n            loadNextPage: undefined,\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport { observable } from '../core/decorators';\nimport ItemBase from '../core/ItemBase';\nimport type { IRemoteClassroom, IClassroomUpdateData, IImportSource, IRemoteImportSource, ICoTeacherEligibilityEntry, ICheckCoTeacherEligibilityOptions } from '../interface/ClassroomModel';\nimport { SubjectTypes, ClassroomStatus, ClassroomType } from '../interface/ClassroomModel';\nimport ClassroomsInterface from '../interface/ClassroomsInterface';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport ItemUpdater from '../core/ItemUpdater';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport type { ClassroomMemberSource } from '../classroom-member/ClassroomMemberSource';\nimport ItemSource from '../core/ItemSource';\nimport ClassroomMemberListLoader from '../classroom-member/ClassroomMemberListLoader';\nimport ClassroomMemberFilter from './ClassroomMemberFilter';\nimport { ClassroomMemberRole } from '../interface/ClassroomMemberModel';\n\nexport const SubjectChoices: SubjectTypes[] = Object.values(SubjectTypes);\n\n/**\n * Class representing the notion of a \"classroom\".  This is currently a read-only object\n * but this may be extended to support CRUD operations in the future.\n * @extends ItemBase\n *\n * @example\n * // Instatiate list and load contents\n * const classroomsList = core.classroomContext.getClassrooms().getList(...options);\n * await waitForListLoad(classroomsList);\n *\n * // Get a specific classroom\n * const load = useMemo(() => core.classroomContext.getClassroomById(id), [classroomContext, id]);\n * const { value: classroom, error, loading } = useLoading<Classroom | undefined>(undefined, load);\n */\nexport default class Classroom extends ItemBase implements SAM.Classroom {\n    private _code: string = '';\n    private _created?: string;\n    private _createdBy: string = '';\n    private _importSource: IImportSource = {};\n    private _isDeleted: boolean = false;\n    private _isVirtual: boolean = false;\n    private _grades: string[] = [];\n    private _members: ClassroomMemberSource;\n    private _memberRole: ClassroomMemberRole = ClassroomMemberRole.NONE;\n    private _name: string = '';\n    private _period: string = '';\n    private _status: ClassroomStatus = ClassroomStatus.ACTIVE;\n    private _subject: SubjectTypes = SubjectTypes.noSubject;\n    private _type?: ClassroomType;\n    private _classroomsInterface = new ClassroomsInterface(this._core);\n    private _userCount?: number; // User count is not captured for virtual classrooms\n    private _assetId: string = '';\n\n    constructor(readonly _core: ISAMCorePrivate, id: string) {\n        super(_core, id);\n        const loader = new ClassroomMemberListLoader(this._core.classroomContext._classroomMemberPool, this._classroomsInterface);\n        this._members = new ItemSource(this._core.classroomContext._classroomMemberPool, [ loader ], new ClassroomMemberFilter({ classroomId: this.id }));\n    }\n\n    /**\n     * For SAM.js internal use only\n     * Due to the classroom ID changing when the classroom is migrated\n     * from a virtual to a real class, clients will NOT have access to\n     * the new instance of the classroom through their existing reference\n     * to the original virtual instance of the class.\n     *\n     * To support classroom workflow reattempts directly following the migration\n     * of the virtual class when the client is still referencing the class\n     * ID when it was virtual, the virtual instance of the class ID will persist\n     * on this session's migrated instance of the class.\n     */\n    _virtualId?: string;\n\n    @observable\n    get code(): string {\n        return this._code;\n    }\n\n    @observable\n    get created(): Date | undefined {\n        if (!this._created) {\n            return undefined;\n        }\n\n        return new Date(this._created);\n    }\n\n    @observable\n    get createdBy(): string {\n        return this._createdBy;\n    }\n\n    @observable\n    get importSource(): IImportSource {\n        return this._importSource;\n    }\n\n    @observable\n    get isDeleted(): boolean {\n        return this._isDeleted;\n    }\n\n    @observable\n    get isVirtual(): boolean {\n        return this._isVirtual;\n    }\n\n    @observable\n    get grades(): string[] {\n        return this._grades;\n    }\n\n    /**\n     * When getting the resulting list from the ClassroomMemberSource, include a role on the filter to get only students or teachers back\n     *\n     * @example <caption>Get all students</caption>\n     * const studentList = classroom.members.getList(ClassroomMemberOrder.default, new ClassroomMemberFilter({ classroomId: classroom.id, role: ClassroomMemberRole.STUDENT }));\n     * waitForListLoad(studentList);\n     * const students: ClassroomMember[] = studentList.items;\n     *\n     * @example <caption>Get all members</caption>\n     * const allMembersList = classroom.members.getList(ClassroomMemberOrder.default, new ClassroomMemberFilter({ classroomId: classroom.id}));\n     * waitForListLoad(allMembersList);\n     * const allMembers: ClassroomMember[] = allMembersList.items;\n     */\n    @observable\n    get members(): ClassroomMemberSource {\n        return this._members;\n    }\n\n    @observable\n    get memberRole(): ClassroomMemberRole {\n        return this._memberRole;\n    }\n\n    @observable\n    get name(): string {\n        return this._name;\n    }\n\n    @observable\n    get period(): string {\n        return this._period;\n    }\n\n    @observable\n    get status(): ClassroomStatus {\n        return this._status;\n    }\n\n    @observable\n    get subject(): SubjectTypes {\n        return this._subject;\n    }\n\n    @observable\n    get type(): ClassroomType | undefined {\n        return this._type;\n    }\n\n    @observable\n    get userCount(): number | undefined {\n        // For now, userCount is calculated as studentCount + 1.\n        // In the future, this could give an inaccurate count if we allow multiple teachers to one classroom\n        // Follow up on this field in [ACPCEDU-2333]\n        return this._userCount;\n    }\n\n    /**\n     * This is the asset ID of the classroom folder.\n     * The classroom ID is the classroom org ID\n     */\n    @observable\n    get assetId(): string {\n        return this._assetId;\n    }\n\n    /**\n     * Deletes this classroom, along with all assignments and other child object\n     *\n     * @example <caption>Delete a classroom</caption>\n     * await classroom.delete();\n     */\n    async delete(): Promise<void> {\n        await this._classroomsInterface.deleteClassroom(this.id);\n    }\n\n    /**\n     * Refreshes the classroom code\n     *\n     * @example <caption>Refresh the classroom code</caption>\n     * await classroom.refreshCode();\n     */\n    async refreshCode(): Promise<void> {\n        this._classroomsInterface.refreshClassroomCode(this.id);\n    }\n\n    /**\n     * Updates a classroom's data\n     *\n     * @example <caption>Update a Classrooms name</caption>\n     * await classroom.update({ name: 'New Name' });\n     */\n    async update(data: IClassroomUpdateData): Promise<void> {\n        return this._core.classroomContext.updateClassroom(this.id, data);\n    }\n\n    /**\n     * Checks if the co-teacher is eligible to be added to the classroom\n     *\n     * @example <caption>Check if the co-teacher is eligible to be added to the classroom</caption>\n     * await classroom.checkCoTeacherEligibility({ emails: ['test@test.com'] });\n     */\n    async checkCoTeacherEligibility(options: ICheckCoTeacherEligibilityOptions): Promise<Array<ICoTeacherEligibilityEntry>> {\n        return this._classroomsInterface.checkCoTeacherEligibility({ ...options, classroomId: this.id });\n    }\n}\n\nfunction getAlternateClassroomId(remoteItem: Partial<IRemoteClassroom>): string | undefined {\n    return remoteItem.virtualId;\n}\n\nexport const ClassroomUpdater = new ItemUpdater<Classroom, Partial<IRemoteClassroom>>({\n    localItemType: Classroom,\n    remoteIdProperty: 'classId',\n    getAlternateId: getAlternateClassroomId,\n    propertyUpdater: new PropertyUpdater({\n        _assetId: { name: 'assetId', format: 'string' },\n        _code: { name: 'classCode', format: 'string' },\n        _created: { name: 'createdOn', format: 'string' },\n        _createdBy: { name: 'createdBy', format: 'string' },\n        _importSource: {\n            name: 'importedFrom',\n            format: 'object',\n            set: (remoteImportSource: IRemoteImportSource, dest: ISAMObject) => {\n                const classroom = dest as Classroom;\n\n                classroom['_importSource'] = {\n                    id: remoteImportSource.sourceId,\n                    type: remoteImportSource.source,\n                    synced: remoteImportSource.lastUpdatedAt ? new Date(remoteImportSource.lastUpdatedAt) : undefined,\n                };\n            },\n        },\n        _isDeleted: { name: 'deleted', format: 'boolean' },\n        _isVirtual: { name: 'isVirtualClassroom', format: 'boolean' },\n        _grades: { isArray: true, name: 'grades' },\n        _memberRole: { name: 'memberRole', format: 'string' },\n        _name: { name: 'className', format: 'string' },\n        _period: { name: 'period', format: 'string' },\n        _status: { name: 'status', format: 'string', choices: Object.values(ClassroomStatus) },\n        _subject: { name: 'subject', format: 'string', choices: SubjectChoices },\n        _type: { name: 'type', format: 'string', choices: Object.values(ClassroomType) },\n        _userCount: { name: 'userCount', format: 'number' },\n        _virtualId: { name: 'virtualId', format: 'string' },\n    }),\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ClassroomsInterface from '../interface/ClassroomsInterface';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type Classroom from './Classroom';\nimport { ClassroomUpdater } from './Classroom';\nimport type { ClassroomConfig } from './ClassroomSource';\n\nexport default class ClassroomListLoader implements IItemLoader<ClassroomConfig> {\n    constructor(private _classroomPool: ItemPool<Classroom>, private _classroomsInterface: ClassroomsInterface) {}\n\n    async loadPage(options: IItemLoaderOptions<ClassroomConfig>): Promise<ILoadedPage<ClassroomConfig>> {\n        return await this._loadPage(options);\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    private async _loadPage(options: IItemLoaderOptions<ClassroomConfig>, start?: number): Promise<ILoadedPage<ClassroomConfig>> {\n        const result = await this._classroomsInterface.getClassrooms();\n        const session = this._classroomPool.createLoaderUpdateSession(Date.now());\n        const items = ClassroomUpdater.updateRemoteItems(session, result);\n        session.commit();\n\n        return {\n            items,\n            total: items.length,\n            loadNextPage: undefined,\n        };\n    }\n}\n","/*************************************************************************\n   *\n   * ADOBE CONFIDENTIAL\n   * ___________________\n   *\n   *  Copyright 2024 Adobe Systems Incorporated\n   *  All Rights Reserved.\n   *\n   * NOTICE:  All information contained herein is, and remains\n   * the property of Adobe Systems Incorporated and its suppliers,\n   * if any.  The intellectual and technical concepts contained\n   * herein are proprietary to Adobe Systems Incorporated and its\n   * suppliers and are protected by trade secret or copyright law.\n   * Dissemination of this information or reproduction of this material\n   * is strictly forbidden unless prior written permission is obtained\n   * from Adobe Systems Incorporated.\n   **************************************************************************/\n\nimport type {\n    IRemoteAssignment,\n    IAssignmentCreateData,\n    IAssignmentsLinks,\n    IAssignmentsOrderBy,\n    IAssignmentsResponse,\n    AssignmentLinks,\n    IAssignmentsIndexLinks,\n    IAssignmentsIndexResponse,\n    AssignmentSubmissionOwnershipEnums } from './AssignmentModel';\nimport {\n    ASSIGNMENTS_INDEX_LINKS,\n    AssignmentStatus\n} from './AssignmentModel';\nimport type {\n    HeaderMap } from './LinkUtils';\nimport {\n    getURLFromLinks,\n    RelType,\n    JSON_MIME_TYPE,\n    validateLinks\n} from './LinkUtils';\nimport InterfaceBase from './InterfaceBase';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport { cache, key } from '../core/decorators';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type { Tutorial } from './TutorialModel';\nimport type { ValidationMap } from '../utils/classroomUtils';\nimport { getSAMVersionRequestHeader, validateType, validateTypes } from '../utils/classroomUtils';\nimport setURLSearchParams from '../utils/searchParams';\n\ntype IPageOptions = {\n    start: number;\n    limit: number;\n};\n\ninterface IListingOptions<IOrderField> extends IPageOptions {\n    orderDirection: IOrderDirection;\n    orderBy: IOrderField;\n}\n\nconst headers = getSAMVersionRequestHeader();\n\nexport interface AssignmentsListingOptions // will be used in getAssignments\n    extends IListingOptions<IAssignmentsOrderBy> {\n    classroomId?: string;\n    campaignId?: string;\n    submissions?: string;\n}\n\nconst DefaultAssignmentsListingOptions: AssignmentsListingOptions = {\n    orderDirection: 'ascending',\n    orderBy: 'repo:name',\n    start: 0,\n    limit: 0\n};\n\nfunction createPageTemplate(options: IPageOptions) {\n    const templateValues: Parameters<typeof getURLFromLinks>[2] = {};\n    if (options.start) {\n        templateValues.start = options.start.toString();\n    }\n    if (options.limit) {\n        templateValues.limit = options.limit.toString();\n    }\n    return templateValues;\n}\n\nfunction getDirectionValue<IOrderField>(userOptions: IListingOptions<IOrderField>) {\n    const directionFlag = userOptions.orderDirection === 'ascending' ? '+' : '-';\n    return directionFlag + userOptions.orderBy;\n}\n\n/**\n * @description Gets the path for the assignments listing\n * @param links The links object containing valid actions this user has on the assignment\n * @param options The options for the assignments listing\n * @throws {SAMError} if both classroomId and campaignId are provided or neither are provided\n * @returns The path for the assignments listing\n */\nexport function getAssignmentsListingPath(links: IAssignmentsLinks, options?: Partial<AssignmentsListingOptions>): string {\n    const userOptions = Object.assign({}, DefaultAssignmentsListingOptions, options);\n    const templateValues = createPageTemplate(userOptions);\n    templateValues.orderBy = getDirectionValue(userOptions);\n    const { classroomId, campaignId, submissions } = userOptions;\n\n    if (classroomId) {\n        templateValues.classroomId = classroomId;\n    } else if (campaignId) {\n        templateValues.campaignId = campaignId;\n    }\n    if (submissions) {\n        templateValues.submissions = submissions;\n    }\n    return getURLFromLinks(links, RelType.ASSIGNMENTS_COLLECTION, templateValues);\n}\n\nfunction validateRequiredAssignmentLinks(links: any) {\n    return validateLinks(links, ASSIGNMENTS_INDEX_LINKS);\n}\n\n/**\n * Validates that a Tutorial object has all of the required properties and they are the correct types\n * @returns An array of error messages if there are any validation errors\n */\nfunction validateTutorialData(data: Tutorial): string[] {\n    return validateTypes([\n        { key: 'surfaces', type: 'object', isRequired: true },\n        { key: 'aem_id', type: 'string', isRequired: true },\n        { key: 'metadata', type: 'object', isRequired: false },\n    ], data);\n}\n\n/**\n * Validates that the object which will create an Assignment has all of the required properties and they are the correct types\n * @returns An array of error messages if there are any validation errors\n */\nexport function validateAssignmentData(data: IAssignmentCreateData): string[] {\n    const errors: string[] = [];\n\n    // Handle basic type validation\n    const assignmentDataToValidate: ValidationMap<IAssignmentCreateData>[] = [\n        { key: 'classroomId', type: 'string', isRequired: true },\n        { key: 'createdBy', type: 'string', isRequired: false },\n        { key: 'dueDate', type: 'date', isRequired: false },\n        { key: 'externalTemplateIds', type: 'string[]', isRequired: false },\n        { key: 'instructions', type: 'string', isRequired: false },\n        { key: 'name', type: 'string', isRequired: true },\n        { key: 'status', type: 'enum', isRequired: false, ref: AssignmentStatus },\n        { key: 'tasks', type: 'string[]', isRequired: false },\n        { key: 'templateIds', type: 'string[]', isRequired: false },\n    ];\n\n    errors.push(...validateTypes(assignmentDataToValidate, data));\n\n    // Handle references since it can be multiple types\n    data.references?.forEach((reference, idx) => {\n        if (typeof reference === 'object') {\n            if (!validateType(reference.content, 'string', true) && !validateType(reference.content, 'blob', true)) {\n                errors.push(`references[${idx}].content is not a string, Blob, or is missing`);\n            }\n\n            if (!validateType(reference.name, 'string', true)) {\n                errors.push(`references[${idx}].name is not a string or is missing`);\n            }\n        } else if (typeof reference !== 'string') {\n            errors.push(`references[${idx}] is not an string or ExternalAsset`);\n        }\n    });\n\n    // Handle tutorials\n    if (data.externalTutorials) {\n        if (!Array.isArray(data.externalTutorials)) {\n            errors.push('externalTutorials is not an array');\n        } else {\n            data.externalTutorials.forEach((tutorial, idx) => {\n                validateTutorialData(tutorial).forEach((error) => {\n                    errors.push(`externalTutorials[${idx}]: ${error}`);\n                });\n            });\n        }\n    }\n\n    // Handle assignment material validation\n    const hasTasks = (data.tasks?.length ?? 0) > 0;\n    const hasTemplates = (data.templateIds?.length ?? 0) > 0;\n    const hasTutorials = (data.externalTutorials?.length ?? 0) > 0;\n    const hasExternalTemplates = (data.externalTemplateIds?.length ?? 0) > 0;\n    const isDraft = data.status === AssignmentStatus.DRAFT;\n    const hasStartingPoint = hasTasks || hasTemplates || hasTutorials || hasExternalTemplates;\n\n    if (!isDraft && !hasStartingPoint) {\n        errors.push('Assigned Assignment must have tasks, templates, externalTemplateIds, or tutorials');\n    }\n\n    return errors;\n}\n\nexport default class AssignmentsInterface extends InterfaceBase {\n    @cache(validateRequiredAssignmentLinks)\n    private async _discoverLinks(@key rootHref: string): Promise<IAssignmentsIndexLinks> {\n        const response: IAssignmentsIndexResponse = await this._getResponse(rootHref, { headers });\n        return response._links;\n    }\n\n    private _getEndpointHref(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.ASSIGNMENTS_HOST}${endpoint}`;\n    }\n\n    async discoverLinks(): Promise<IAssignmentsIndexLinks> {\n        return this._discoverLinks(this._getEndpointHref(`/api/v1/index`));\n    }\n\n    /**\n     * @description Fetches the list of Assignments based on the options provided\n     * @param options : options to sort and filter the Assignments listing\n     * @throws {SAMError} if both classroomId and campaignId are provided or neither are provided\n     * @returns resolves to list of Assignments along with the page information and links to the next page\n    */\n    async getAssignments(options: Partial<AssignmentsListingOptions>): Promise<IAssignmentsResponse> {\n        // options.classroomId is optional as the type is reused elsewhere, but really it's needed here to get assignments\n        if (!options.classroomId && !options.campaignId) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'classroomId or campaignId is required to fetch assignments');\n        }\n        if (options.classroomId && options.campaignId) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Cannot fetch assignments by both classroomId and campaignId');\n        }\n        const links = await this.discoverLinks();\n        const url = getAssignmentsListingPath(links, options);\n        return this._getResponse(url, { headers });\n    }\n\n    /**\n     * Get an Assignment by id or code\n     * @param identifierType What type of identifier we will fetch by\n     * @param identifier The assignment ID or code depending on value of identifierType\n     * @param submissions Use this if you want to include or exclude submissions from the assignment\n     * @param additionalHeaders Additional headers to include in the request\n     * @returns The fetched assignment\n     */\n    private async getAssignmentBy(identifierType: 'id' | 'code', identifier: string, submissions?: AssignmentSubmissionOwnershipEnums, additionalHeaders?: HeaderMap): Promise<IRemoteAssignment> {\n        const links = await this.discoverLinks();\n        const params: Parameters<typeof getURLFromLinks>[2] = identifierType === 'id'\n            ? { assignmentId: identifier }\n            : { assignmentCode: identifier };\n        const relType = identifierType === 'id' ? RelType.ASSIGNMENTS_PRIMARY : RelType.ASSIGNMENTS_CODE;\n\n        if (submissions) {\n            params.submissions = submissions;\n        }\n        const url = getURLFromLinks(links, relType, params);\n        return this._getResponse(url, { headers: { ...headers, ...additionalHeaders } });\n    }\n\n    /**\n     * @description Gets the metadata for a single assignment\n     * @param id asset id that uniquely identifies the assignment\n     * @param submissions Use this if you want to include or exclude submissions from the assignment\n     * @param additionalHeaders Additional headers to include in the request\n     * @returns resolves to assignment metadata for the given id\n    */\n    async getAssignment(id: string, submissions?: AssignmentSubmissionOwnershipEnums, additionalHeaders?: HeaderMap): Promise<IRemoteAssignment> {\n        return this.getAssignmentBy('id', id, submissions, additionalHeaders);\n    }\n\n    /**\n     * @description Gets the metadata for a single assignment by code\n     * @param code code that identifies assignment\n     * @param submissions Use this if you want to include or exclude submissions from the assignment\n     * @param additionalHeaders Additional headers to include in the request\n     * @returns resolves to assignment metadata for the given code\n    */\n    async getAssignmentByCode(code: string, submissions?: AssignmentSubmissionOwnershipEnums, additionalHeaders?: HeaderMap): Promise<IRemoteAssignment> {\n        return this.getAssignmentBy('code', code, submissions, additionalHeaders);\n    }\n\n    /**\n     * Creates a new Assignment\n     * @param data needed to create a Assignment like name and instructions\n     * @returns the newly created Assignment\n    */\n    async createAssignment(data: IAssignmentCreateData): Promise<IRemoteAssignment> {\n        // [ACPCEDU-444]: When specified, status always takes precedence; if tasks present then assignment is ASSIGNED, otherwise it is DRAFT.\n        const hasTasks = (data.tasks?.length ?? 0) > 0;\n        const status = data.status || (hasTasks ? AssignmentStatus.ASSIGNED : AssignmentStatus.DRAFT);\n\n        const links = await this.discoverLinks();\n        const url = new URL(getURLFromLinks(links, RelType.ASSIGNMENTS_CREATE));\n        setURLSearchParams(url, {\n            classroomId: data.classroomId,\n            assign: (status === AssignmentStatus.ASSIGNED).toString(),\n        });\n\n        const extTemplateIds = data.externalTemplateIds || [];\n        const extTutorials = data.externalTutorials?.map(t => JSON.stringify(t)) || [];\n\n        const options = {\n            'assignment:canClassroomReadSubmissions': data.canClassroomReadSubmissions,\n            'assignment:dueDate': data.dueDate?.toISOString(),\n            'assignment:instructions': data.instructions,\n            'repo:name': data.name,\n            'assignment:status': status,\n            'assignment:tasks': data.tasks || [],\n            'assignment:createdBy': data.createdBy,\n            'assignment:externalTemplateIds': [ ...extTemplateIds, ...extTutorials ],\n            'assignment:campaignId': data.campaignId\n        };\n\n        const response = await this._doPost(url.toString(), { ...headers, 'Content-Type': JSON_MIME_TYPE }, JSON.stringify(options), [ 201 ]);\n        // TODO: https://jira.corp.adobe.com/browse/ACPCEDU-403 Add error handling\n        const jsonResponse = await response.json();\n\n        return jsonResponse;\n    }\n\n    /**\n     * Updates an assignment's data\n     * @param id The id of the Assignment to update\n     * @param data The data to update the Assignment with. Currently only the instructions, dueDate, tasks, and templateIds can be modified.\n     */\n    async patchAssignment(id: string, ops: {\n        op: string;\n        path: string;\n        value: unknown;\n    }[]): Promise<IRemoteAssignment> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(links, RelType.ASSIGNMENTS_PRIMARY, { assignmentId: id });\n        const response = await this._doPatch(url, { ...headers, 'Content-Type': JSON_MIME_TYPE }, JSON.stringify(ops), [ 200, 204 ]);\n        const jsonResponse = await response.json();\n        return jsonResponse;\n    }\n\n    /**\n     * Discards an assignment -- from the DISCARDED state, an assignment can be permanently deleted or restored\n     * @param id The id of the Assignment to discard\n     * @param links The links object containing valid actions this user has on the assignment\n     */\n    async discardAssignment(id: string, links: AssignmentLinks): Promise<void> {\n        if (!links?.[RelType.DISCARD]) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Discard link is missing for this assignment ${id}`);\n        }\n        const url = getURLFromLinks(links, RelType.DISCARD, { assignmentId: id });\n\n        await this._doPost(url, headers, undefined, [ 204 ]);\n    }\n\n    /**\n     * Restores a discarded assignment\n     * @param id The id of the Assignment to restore\n     * @param links The links object containing valid actions this user has on the assignment\n     */\n    async restoreAssignment(id: string, links: AssignmentLinks): Promise<void> {\n        if (!links?.[RelType.RESTORE]) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Restore link is missing for this assignment ${id}`);\n        }\n        const url = getURLFromLinks(links, RelType.RESTORE, { assignmentId: id });\n\n        await this._doPost(url, headers, undefined, [ 204 ]);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport StudentAssignmentsInterface from '../interface/StudentAssignmentsInterface';\nimport AppMetadataResource from '../assets/AppMetadataResource';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type StudentAssignment from './StudentAssignment';\nimport { StudentAssignmentUpdater } from './StudentAssignment';\nimport { RequestHeaders } from '../utils/classroomUtils';\n\nexport default class StudentAssignmentAppMetadataResource extends AppMetadataResource {\n    private _studentAssignmentsInterface;\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _parent: StudentAssignment,\n    ) {\n        super(_core, _parent);\n\n        this._studentAssignmentsInterface = new StudentAssignmentsInterface(this._core);\n    }\n\n    protected async _loadData() {\n        // Get the core links from RAPI\n        const rapiLinks = await this._core.hostAssetContext._rapi.getAssetLinks(this._parent.id);\n\n        // Application specific links are within the Hume response, we will merge these with the core links\n        const studentAssignmentMetadata = await this._studentAssignmentsInterface.getStudentAssignment(this._parent.id, undefined, { [RequestHeaders.PREFER_RAPI]: 'true' });\n        const { _links: humeLinks, ...rest } = studentAssignmentMetadata;\n        await this._setData({\n            ...rest,\n            _links: {\n                ...rapiLinks,\n                ...humeLinks,\n            }\n        });\n\n        // Updates the StudentAssignment to include the latest app metadata\n        const session = this._core._getAssetPool().createMutationSession<StudentAssignment>();\n        StudentAssignmentUpdater.updateLocalItem(session, this._parent, this.data);\n        session.commit();\n    }\n}\n","import type {\n    IItemLoader,\n    IItemLoaderOptions,\n    ILoadedPage,\n} from '../core/ItemLoader';\nimport type { IServiceLink } from '../interface/LinkUtils';\nimport type StudentAssignment from './StudentAssignment';\nimport type { StudentAssignmentFileConfig } from './StudentAssignmentFileSource';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type StudentAssignmentsInterface from '../interface/StudentAssignmentsInterface';\nimport type StudentAssignmentFile from './StudentAssignmentFile';\n\nexport default class StudentAssignmentFilesListLoader\nimplements IItemLoader<StudentAssignmentFileConfig> {\n    private _core: ISAMCorePrivate;\n    private _studentAssignmentsInterface: StudentAssignmentsInterface;\n\n    constructor({ core, studentAssignmentsInterface }: {core: ISAMCorePrivate, studentAssignmentsInterface: StudentAssignmentsInterface}) {\n        this._core = core;\n        this._studentAssignmentsInterface = studentAssignmentsInterface;\n    }\n\n    async loadPage(\n        options: IItemLoaderOptions<StudentAssignmentFileConfig>\n    ): Promise<ILoadedPage<StudentAssignmentFileConfig>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(\n        options: IItemLoaderOptions<StudentAssignmentFileConfig>,\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars -- TODO: https://jira.corp.adobe.com/browse/ACPCEDU-405 add support for paging or remove this\n        pageLink?: IServiceLink\n    ): Promise<ILoadedPage<StudentAssignmentFileConfig>> {\n        const mostRecentValidMutation = Date.now();\n        const { studentAssignmentId } = options.implicitFilter;\n        const cachedStudentAssignment = this._core._getAssetPool().getLocalItemById<StudentAssignment>(studentAssignmentId);\n        let studentAssignmentFiles = cachedStudentAssignment?.studentAssignmentFiles ?? [];\n\n        if (cachedStudentAssignment && cachedStudentAssignment._hasLoadedChildren) {\n            /**\n             * If we already have loaded both the StudentAssignment and its files,\n             * then we can just link them since they are all already in the pool.\n             *\n             * Includes any relevant SAFs that have been cached as AdobeAssets\n             * which occurs if the file was cached prior to being moved into\n             * a StudentAssignment.\n             * [ACPCEDU-3290] will introduce a longer-term approach for handling this behavior\n             * to support other/future cases where the asset type changes over time\n             */\n            studentAssignmentFiles = this._core._getAssetPool().toArray().filter(\n                (item) => item.studentAssignmentId === studentAssignmentId\n            ) as StudentAssignmentFile[];\n        } else if (studentAssignmentFiles.length === 0) {\n            // If the StudentAssignment was not yet loaded, or if it was loaded without\n            // the files, then we need to fetch the files from the server.\n            const studentAssignmentMetadata = await this._studentAssignmentsInterface.getStudentAssignment(studentAssignmentId, { loadDocuments: true });\n            const assignmentId = studentAssignmentMetadata['classroom:context']['classroom:assignmentContext']['classroom:assignmentAssetId'];\n            const classroomId = studentAssignmentMetadata['classroom:context']['classroom:classroomContext']['classroom:classroomAssetId'];\n            const session = this._core._getAssetPool().createMutationSession<StudentAssignmentFile>();\n            studentAssignmentFiles = this._core.classroomContext._updateStudentAssignmentFilesCache({ remoteStudentAssignmentFiles: studentAssignmentMetadata.children, session, assignmentId, classroomId, studentAssignmentId });\n            if (cachedStudentAssignment) {\n                cachedStudentAssignment._hasLoadedChildren = true;\n            }\n        }\n\n        return {\n            items: studentAssignmentFiles,\n            total: studentAssignmentFiles.length,\n            mostRecentValidMutation,\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { AssignmentAdobeAssetMetadata } from '../interface/AssignmentModel';\nimport type { Assignee, StudentAssignmentLinks, IRemoteAssignee, IRemoteStudentAssignment } from '../interface/StudentAssignmentModel';\nimport { StudentAssignmentStatus } from '../interface/StudentAssignmentModel';\nimport type { IRemoteStudentAssignmentFile, IStudentAssignmentFilesOptions } from '../interface/StudentAssignmentFileModel';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport type { AssetClass, AssetLinks, RepositoryMetadata } from '../interface/RepositoryModel';\nimport { observable } from '../core/decorators';\nimport AdobeAsset from '../assets/AdobeAsset';\nimport type StudentAssignmentFile from './StudentAssignmentFile';\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport type { IPerUserMetadata } from '../interface/AssetModel';\nimport { Permission } from '../interface/AssetModel';\nimport type { StudentAssignmentFileSource } from './StudentAssignmentFileSource';\nimport StudentAssignmentAppMetadataResource from './StudentAssignmentAppMetadataResource';\nimport StudentAssignmentsInterface from '../interface/StudentAssignmentsInterface';\nimport ItemSource from '../core/ItemSource';\nimport type ItemPool from '../core/ItemPool';\nimport StudentAssignmentFilesListLoader from './StudentAssignmentFilesListLoader';\nimport StudentAssignmentFileFilter from './StudentAssignmentFileFilter';\nimport { RequestHeaders } from '../utils/classroomUtils';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\n\nexport type StudentAssignmentParams = {\n    assignmentId: string;\n    links: StudentAssignmentLinks;\n    status: StudentAssignmentStatus;\n    student: Assignee;\n    studentDirectoryId?: string;\n    submission?: AssignmentAdobeAssetMetadata;\n    submissionDate?: Date;\n}\n\nexport default class StudentAssignment extends AdobeAsset implements SAM.StudentAssignment {\n    protected _assetClass: AssetClass = 'directory'; // this makes assignment a folder\n    private _assignmentId: string = '';\n    private _assignmentCode: string = '';\n    private _parentClassroomId: string = '';\n    private _inheritedClassroomId: string = '';\n    // Have the associated SA Files been loaded into the pool?\n    // Note: the odd \"...Prop\" naming is to avoid a conflict with the getter/setter\n    private _hasLoadedChildrenProp: boolean = false;\n    private _status: StudentAssignmentStatus = StudentAssignmentStatus.NOT_STARTED;\n    private _student: Assignee = { id: '', displayName: '', email: '' };\n    private _studentAssignmentsInterface = new StudentAssignmentsInterface(this._core);\n    private _studentDirectoryId?: string;\n    private _submission?: AssignmentAdobeAssetMetadata;\n    private _submissionDate?: Date;\n    private _studentAssignmentAppMetadata: StudentAssignmentAppMetadataResource;\n\n    private _studentAssignmentFilesSource?: StudentAssignmentFileSource;\n    // This field is intended to preserve child assets provided by the remote item that may not be available through the StudentAssignmentFileSource yet/that\n    // a weak ref to the list does not exist yet until getList is called\n    private _studentAssignmentFiles: StudentAssignmentFile[] = [];\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        id: string,\n        metadata?: {\n            links?: AssetLinks;\n        }\n    ) {\n        super(_core, id, metadata);\n        this._studentAssignmentAppMetadata = new StudentAssignmentAppMetadataResource(_core, this);\n\n        // Overridden property.\n        // True to start with. If we have the metadata, we will update this.\n        // Keep in mind that the submission service does not include all Adobe\n        // Asset metadata in its responses, hence why this is needed.\n        this._needsRepoMetadata = true;\n    }\n\n    /**\n     * A flag that indicates whether the StudentAssignment is virtual or not.\n     * SAs are not actual assets until the status changes from NOT_STARTED,\n     * at that time the SA folder asset is created.\n     *\n     * Overrides the AdobeAsset isVirtual.\n     */\n    @observable\n    get isVirtual(): boolean {\n        return this.status === StudentAssignmentStatus.NOT_STARTED;\n    }\n\n    @observable\n    get appMetadata(): StudentAssignmentAppMetadataResource {\n        return this._studentAssignmentAppMetadata;\n    }\n\n    /**\n     * Were child assets fetched in parallel to this StudentAssignment.  This differentiates\n     * when files were NOT fetched vs files were fetched but the files are not yet associated\n     * with the StudentAssignment (i.e. the files are not present in this._studentAssignmentFiles)\n     * @package Only for use in SAM.js.\n     */\n    get _hasLoadedChildren(): boolean {\n        return this._hasLoadedChildrenProp;\n    }\n\n    /**\n     * @package Only for use in SAM.js.\n     */\n    set _hasLoadedChildren(value: boolean) {\n        this._hasLoadedChildrenProp = value;\n    }\n\n    /**\n     * @package Only for use in SAM.js. Please use .files() instead.\n     */\n    get studentAssignmentFiles(): StudentAssignmentFile[] {\n        return this._studentAssignmentFiles;\n    }\n\n    @observable\n    get assignmentId(): string {\n        return this._assignmentId;\n    }\n\n    @observable\n    get assignmentCode(): string {\n        return this._assignmentCode;\n    }\n\n    /**\n     * Overrides the default implementation in AdobeAsset\n     */\n    @observable\n    get parentClassroomId(): string {\n        // We expect to always have classroom:context on hand\n        // In the unexpected case that we don't, we can fall back to cc:inherited or the super call that will check appMetadata\n        return this._parentClassroomId || this._inheritedClassroomId || super.parentClassroomId || '';\n    }\n\n    /**\n     * Overrides the default implementation in AdobeAsset\n     */\n    @observable\n    get parentAssignmentId(): string {\n        return this.assignmentId;\n    }\n\n    @observable\n    get status(): StudentAssignmentStatus {\n        return this._status;\n    }\n\n    @observable\n    get student(): Assignee {\n        return this._student;\n    }\n\n    @observable\n    get studentDirectoryId(): string | undefined {\n        return this._studentDirectoryId;\n    }\n\n    @observable\n    get submission(): AssignmentAdobeAssetMetadata | undefined {\n        return this._submission;\n    }\n\n    @observable\n    get submissionDate(): Date | undefined {\n        return this._submissionDate;\n    }\n\n    get isStudentAssignment(): boolean | undefined {\n        return true;\n    }\n\n    /**\n     * Returns the files in the student's assignment directory. Optional parameter to specify the order of the files.\n     * @throws {Error} if the student directory asset is not a folder\n     * @deprecated Use `.files` instead. Will be removed in ACPCEDU-3305.\n     */\n    @observable\n    async getFiles(options: IStudentAssignmentFilesOptions = {}): Promise<StudentAssignmentFile[]> {\n        if (!this._studentDirectoryId) {\n            return [];\n        }\n\n        return this._core.classroomContext.getStudentAssignmentFiles({\n            studentDirectoryId: this.studentDirectoryId!, order: options.order\n        });\n    }\n\n    /**\n     * Returns undefined if the StudentAssignment is NOT_STARTED, otherwise\n     * returns the StudentAssignmentsSource which contains a list of StudentAssignmentFile[].\n     *\n     * @example <caption>Get all StudentAssignmentFiles for this StudentAssignment</caption>\n     * const safList = studentAssignment.files?.getList(StudentAssignmentFileOrder.default);\n     * await waitForListLoad(safList);\n     * const safs: StudentAssignmentFile[] = safList?.items || [];\n     */\n    get files(): StudentAssignmentFileSource | undefined {\n        if (!this._studentDirectoryId) {\n            // The StudentAssignment is NOT_STARTED so there are no files to fetch\n            return undefined;\n        }\n\n        if (!this._studentAssignmentFilesSource) {\n            this._studentAssignmentFilesSource = new ItemSource(\n                this._core._getAssetPool() as ItemPool<StudentAssignmentFile>,\n                [ new StudentAssignmentFilesListLoader({ core: this._core, studentAssignmentsInterface: this._studentAssignmentsInterface }) ],\n                new StudentAssignmentFileFilter(this._studentDirectoryId)\n            );\n        }\n\n        return this._studentAssignmentFilesSource;\n    }\n\n    /**\n     * @deprecated This getter is deprecated and clients should use the links() function instead moving forward.\n     * This method will be removed on or after 2025-7-1 in ACPCEDU-3393\n     */\n    @observable\n    get studentAssignmentLinks(): StudentAssignmentLinks {\n        return this.links;\n    }\n\n    @observable\n    get links(): StudentAssignmentLinks {\n        // Make a copy to avoid the client accidentally manipulating the links\n        return Object.assign({}, this.__links as StudentAssignmentLinks);\n    }\n\n    /**\n     * Other students will have read access to this directory if the class gallery is enabled.\n     * To reduce visibility to in-progress work, we do not want to load new work files from ONS notifications.\n     * @package -- internal use only\n     */\n    get _canLoadNewChildrenFromONSNotification(): boolean {\n        return this.hasPermission(Permission.Write);\n    }\n\n    /**\n     * Checks if this StudentAssignment is able to be started\n     *\n     * @example <caption>Check if the StudentAssignment can be started</caption>\n     * if (studentAssignment.canStart()) {\n     *  // Do something\n     * }\n     */\n    canStart(): boolean {\n        return this._status === StudentAssignmentStatus.NOT_STARTED;\n    }\n\n    /**\n     * Checks if this StudentAssignment can be returned by the teachers\n     *\n     * @example <caption>Check if the StudentAssignment can be returned</caption>\n     * if (studentAssignment.canReturn()) {\n     *  // Do something\n     * }\n     */\n    canReturn(): boolean {\n        return this._status === StudentAssignmentStatus.SUBMITTED;\n    }\n\n    // this _load will be extended in https://jira.corp.adobe.com/browse/ACPCEDU-2125 to account for cases where we don't need to fetch Assignment just to get StudentAssignment\n    // Until then, we can assume StudentAssignments are coming from GET assignments\n    /**\n   * @param repoMetadata {RepositoryMetadata} If passed in, it will be used instead of loading from the service\n   * @param appMetadata {any} If passed in, it will be used instead of loading from the service\n   *\n   * @package -- only for use in SAM.js\n   */\n    async _load({\n        repoMetadata,\n        appMetadata,\n        effectivePermission,\n        perUserMetadata,\n        doFetchStudentAssignmentMetadata = true,\n    }: {\n        repoMetadata?: RepositoryMetadata;\n        appMetadata?: any;\n        effectivePermission?: Permission;\n        perUserMetadata?: IPerUserMetadata;\n        doFetchStudentAssignmentMetadata?: boolean;\n    } = {}): Promise<void> {\n        // Similar to what Project already has, first load the AdobeAsset so that once we get the student assignment metadata we override any relevant\n        // properties with the student assignment metadata\n        await super._load({ repoMetadata, appMetadata, effectivePermission, perUserMetadata });\n\n        if (doFetchStudentAssignmentMetadata) {\n            const studentAssignmentMetadata = await this._studentAssignmentsInterface.getStudentAssignment(this.id, undefined, { [RequestHeaders.PREFER_RAPI]: 'true' });\n            const session = this._core._getAssetPool().createMutationSession<StudentAssignment>();\n            StudentAssignmentUpdater.updateRemoteItem(\n                session,\n                studentAssignmentMetadata\n            );\n            session.commit();\n        }\n    }\n\n    /**\n     * Marks this student assignment as returned.\n     *\n     * @example <caption>Return a StudentAssignment</caption>\n     * await studentAssignment.return();\n     */\n    async return(): Promise<StudentAssignment> {\n        return this._core.classroomContext._returnAssignment({\n            links: this.links,\n            studentAssignmentId: this.studentDirectoryId!,\n            submissionId: this.submission?.['repo:assetId'] as string,\n        });\n    }\n\n    /**\n     * Marks this student assignment as started.\n     *\n     * @example <caption>Start a StudentAssignment</caption>\n     * await studentAssignment.start();\n     */\n    async start(): Promise<StudentAssignment> {\n        return this._core.classroomContext._startAssignment({\n            assignmentId: this.assignmentId,\n            links: this.links,\n        });\n    }\n\n    /**\n     * Marks this student assignment as submitted. Note that this should only be called by the student for\n     * submitting their own assignment.\n     * @param submissionId - The asset ID of the student's work to become the submission for this assignment.\n     *\n     * @example <caption>Submit a StudentAssignment</caption>\n     * await studentAssignment.submit('submission-id');\n     */\n    async submit(submissionId: string): Promise<StudentAssignment> {\n        await this._core.classroomContext.submitAssignment({\n            assignmentId: this.assignmentId,\n            links: this.links,\n            status: this.status,\n            studentAssignmentId: this.studentDirectoryId,\n            submissionId,\n        });\n        return this;\n    }\n\n    /**\n     * Returns true as the StudentAssignment is a child of Classroom\n     * Overrides the default implementation in AdobeAsset\n     */\n    @observable\n    get isChildOfClassroom(): boolean {\n        return true;\n    }\n\n    /**\n     * Returns true as the StudentAssignment is a child of Assignment\n     * Overrides the default implementation in AdobeAsset\n     */\n    @observable\n    get isChildOfAssignment(): boolean {\n        return true;\n    }\n\n    /**\n     * Returns false as the StudentAssignment is not a child of AssignmentMaterials\n     * Overrides the default implementation in AdobeAsset\n     */\n    @observable\n    get isChildOfAssignmentMaterials(): boolean {\n        return false;\n    }\n\n    /**\n     * Returns false as the StudentAssignment is not a child of StudentAssignment\n     * Overrides the default implementation in AdobeAsset\n     */\n    @observable\n    get isChildOfStudentAssignment(): boolean {\n        return false;\n    }\n}\n\nexport function getAlternateStudentAssignmentId(remoteItem: Partial<IRemoteStudentAssignment>): string {\n    // We expect to always have classroom:context on hand\n    // In the unexpected case that we don't, we can fall back to cc:inherited or throw an error.\n    let id;\n    if (remoteItem['classroom:context'] !== undefined) {\n        id = remoteItem['classroom:context']['classroom:assignmentContext']['classroom:assignmentAssetId'];\n    } else if (remoteItem['cc:inherited'] !== undefined && remoteItem['cc:inherited']['cc:assignment'] !== undefined) {\n        id = remoteItem['cc:inherited']['cc:assignment']['repo:assetId'];\n    } else {\n        throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, `Remote item does not have classroom:context or cc:inherited defined`);\n    }\n\n    return `${remoteItem['assignment:assignee']?.id}-${id}`;\n}\n\nexport const StudentAssignmentUpdater = new ItemUpdater<StudentAssignment, Partial<IRemoteStudentAssignment>>({\n    remoteIdProperty: 'repo:assetId',\n    getAlternateId: getAlternateStudentAssignmentId,\n    localItemType: StudentAssignment,\n    propertyUpdater: new PropertyUpdater({\n        _assignmentId: { name: 'classroom:context[classroom:assignmentContext][classroom:assignmentAssetId]', format: 'string' },\n        _assignmentCode: { name: 'computedAssignmentCode', format: 'string' },\n        _parentClassroomId: { name: 'classroom:context[classroom:classroomContext][classroom:classroomAssetId]', format: 'string' },\n        _inheritedClassroomId: { name: 'cc:inherited[cc:classroom][repo:assetId]', format: 'string' },\n        _studentAssignmentFiles: {\n            isArray: true,\n            name: 'children',\n            format: 'object',\n            set: (remoteStudentAssignmentFiles: IRemoteStudentAssignmentFile[], dest: ISAMObject) => {\n                const studentAssignment = dest as StudentAssignment;\n                studentAssignment.studentAssignmentFiles.length = 0;\n                const session = studentAssignment._core._getAssetPool().createMutationSession<StudentAssignmentFile>();\n                const files = studentAssignment._core.classroomContext._updateStudentAssignmentFilesCache({ remoteStudentAssignmentFiles, session, assignmentId: studentAssignment.assignmentId, classroomId: studentAssignment.parentClassroomId, studentAssignmentId: studentAssignment.id });\n                studentAssignment.studentAssignmentFiles.push(...files);\n            }\n        },\n        __links: { name: '_links', format: 'object' },\n        _status: { name: 'assignment:submissionStatus', format: 'string' },\n        // if using 'object' in the format, the setter will be called  when the response omits displayName ( because undefined is different than the name it already has ).\n        // This leads to the result of having the updater dispatches the change event whenever the setter is called.\n        // Using 'object_subset' so the parse/isEqual's will only compare the members in the response with their corresponding values in the local object,\n        // so it only calls the setter when something specified in the response differences from the existing value.\n        _student: { name: 'assignment:assignee', format: 'object_subset', set: (remoteAssignee: IRemoteAssignee, dest: ISAMObject) => {\n            const studentAssignment = dest as StudentAssignment;\n            // Hume will not provide displayName or email in start/submit/return API responses.\n            // If we only pass through the object from Hume, missing/undefined required fields of display name and email will override the existing non-empty ones.\n            studentAssignment['_student'] = { ...studentAssignment['_student'], ...remoteAssignee };\n        } },\n        _studentDirectoryId: { name: 'repo:assetId', format: 'string' },\n        _submission: { name: 'assignment:submission', format: 'object' },\n        _submissionDate: { name: 'assignment:submissionDate', format: 'date' },\n    }),\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport AppMetadataResource from '../assets/AppMetadataResource';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type Assignment from './Assignment';\nimport { AssignmentUpdater } from './Assignment';\n\nexport default class AssignmentAppMetadataResource extends AppMetadataResource {\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        readonly _parent: Assignment,\n    ) {\n        super(_core, _parent);\n    }\n\n    protected async _loadData() {\n        // Directly fetches app metadata from R-API since there is a chance app metadata\n        // has been fetched external to Hume, such as the case the Assignment was fetched\n        // with AssetContext.getAssetWithCloudID.\n        await super._loadData();\n        // Updates the Assignment to include the latest app metadata\n        const session = this._core._getAssetPool().createMutationSession<Assignment>();\n        AssignmentUpdater.updateLocalItem(session, this._parent, this.data);\n        session.commit();\n    }\n}\n","import type { RequiredStudentAssignmentFilterOptions } from '../interface/StudentAssignmentModel';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type StudentAssignment from './StudentAssignment';\n\nexport default class ImplicitStudentAssignmentFilter implements IImplicitFilter<StudentAssignment> {\n    public readonly assignmentCode: string;\n    public readonly assignmentId: string;\n    /**\n     * @package -- only for use in SAM.js\n     */\n    public _monitoredFolder?: AdobeAsset;\n\n    constructor(options: RequiredStudentAssignmentFilterOptions) {\n        const { assignmentCode, assignmentId } = options || {};\n        // default values for assignment code and id are empty strings, match for ensuring comparisons work correctly\n        this.assignmentCode = assignmentCode || '';\n        this.assignmentId = assignmentId || '';\n    }\n    matches(item: AdobeAsset | StudentAssignment): boolean {\n        if (!this.assignmentId && !this.assignmentCode) {\n            throw new Error('Getting StudentAssignments across Assignments is not supported at this time');\n        }\n\n        if (!item.isStudentAssignment) {\n            return false;\n        }\n\n        const studentAssignmentItem = item as StudentAssignment;\n\n        // either this.assignmentId or this.assignmentCode should be non-empty\n        if (this.assignmentId && (this.assignmentId !== studentAssignmentItem.assignmentId)) {\n            return false;\n        }\n\n        if (this.assignmentCode && (this.assignmentCode !== studentAssignmentItem.assignmentCode)) {\n            return false;\n        }\n\n        return true;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { AdobeAssetUpdaterMetadata } from '../assets/AdobeAsset';\nimport AdobeAsset from '../assets/AdobeAsset';\nimport { memoize, observable, retry } from '../core/decorators';\nimport type {\n    AssetClass,\n    AssetLinks,\n    RepositoryMetadata } from '../interface/RepositoryModel';\nimport {\n    AssetStateChoices\n} from '../interface/RepositoryModel';\nimport type { Permission } from '../interface/AssetModel';\nimport type {\n    AssignmentLinks,\n    IAssignmentPatchData,\n    IRemoteAssignment } from '../interface/AssignmentModel';\nimport {\n    AssignmentStatus\n} from '../interface/AssignmentModel';\nimport ItemUpdater from '../core/ItemUpdater';\nimport PropertyUpdater from '../core/PropertyUpdater';\nimport AssignmentsInterface from '../interface/AssignmentsInterface';\nimport type { IRemoteStudentAssignment } from '../interface/StudentAssignmentModel';\nimport type StudentAssignment from './StudentAssignment';\nimport { StudentAssignmentUpdater } from './StudentAssignment';\nimport StudentAssignmentOrder from './StudentAssignmentOrder';\nimport type { Tutorial } from '../interface/TutorialModel';\nimport AssignmentAppMetadataResource from './AssignmentAppMetadataResource';\nimport type { StudentAssignmentSource } from './StudentAssignmentSource';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport ImplicitStudentAssignmentFilter from './ImplicitStudentAssignmentFilter';\nimport { RequestHeaders } from '../utils/classroomUtils';\nimport { RelType } from '../interface/LinkUtils';\n\nexport const AssignmentStatusChoices: AssignmentStatus[] = Object.values(AssignmentStatus);\n\nexport default class Assignment extends AdobeAsset implements SAM.Assignment {\n    protected _assetClass: AssetClass = 'directory'; // this makes assignment a folder\n    private _assignmentInterface = new AssignmentsInterface(this._core);\n    private _canClassroomReadSubmissions: boolean = false;\n    private _classroomId: string = '';\n    private _code: string = '';\n    private _dueDate?: Date; // due date is optional here otherwise the default value would be the current date\n    private _externalTemplateIds: string[] = [];\n    /**\n     * This is the raw data from remote, we need to parse it to get the actual external tutorials.\n     * Storing the raw data allows the property updater to know if the data has changed.\n     * Both externalTemplateIds and externalTutorials are derived from this data.\n     */\n    private _externalTemplateIdsRemote: string[] = [];\n    private _instructions: string = '';\n    private _isAutoCreated: boolean = false;\n    private _status!: AssignmentStatus;\n    private _studentAssignments: StudentAssignment[] = [];\n    private _tasks?: string[];\n    private _templateIds?: string[];\n    private _referenceIds?: string[];\n    private _externalTutorials: Partial<Tutorial>[] = [];\n    private _isExternalTutorialsDirty: boolean = false;\n    private _assignmentAppMetadata: AssignmentAppMetadataResource;\n    private _parentClassroomId: string = '';\n    private _materialsAssetId: string = '';\n    private _studentsAssetId: string = '';\n    private _parentAssignmentsFolderAssetId: string = '';\n    private _campaignId?: string;\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        id: string,\n        metadata?: {\n            links?: AssetLinks;\n        }\n    ) {\n        super(_core, id, metadata);\n        this._assignmentAppMetadata = new AssignmentAppMetadataResource(_core, this);\n\n        // Overridden property.\n        // True to start with. If we have the metadata, we will update this.\n        // Keep in mind that the assignment service does not include all Adobe\n        // Asset metadata in its responses, hence why this is needed.\n        this._needsRepoMetadata = true;\n    }\n\n    @observable\n    get appMetadata(): AssignmentAppMetadataResource {\n        return this._assignmentAppMetadata;\n    }\n\n    @observable\n    get canClassroomReadSubmissions(): boolean {\n        return this._canClassroomReadSubmissions;\n    }\n\n    @observable\n    get campaignId(): string | undefined {\n        return this._campaignId;\n    }\n\n    @observable\n    get classroomId(): string {\n        return this._classroomId;\n    }\n\n    /**\n     * Overrides default AdobeAsset check\n     * */\n    @observable\n    get isChildOfAssignment(): boolean {\n        return false;\n    }\n\n    /**\n     * Overrides default AdobeAsset check\n     * */\n    @observable\n    get isChildOfAssignmentMaterials(): boolean {\n        return false;\n    }\n\n    /**\n     * Overrides default AdobeAsset check\n     * */\n    @observable\n    get isChildOfClassroom(): boolean {\n        return true;\n    }\n\n    /**\n     * Overrides default AdobeAsset check\n     * */\n    @observable\n    get isChildOfStudentAssignment(): boolean {\n        return false;\n    }\n\n    /**\n     * Gets all student assignments for this assignment\n     * @package Only for use in SAM.js. Please use `getStudentAssignments()` instead.\n     */\n    @observable\n    get studentAssignments(): StudentAssignment[] {\n        return this._studentAssignments;\n    }\n\n    /**\n     * Builds a StudentAssignmentFilter that is scoped to this Assignment ID\n     * @package -- for use in SAM.js only\n     */\n    _getStudentAssignmentsFilter(): ImplicitStudentAssignmentFilter {\n        return new ImplicitStudentAssignmentFilter({\n            assignmentId: this.id,\n        });\n    }\n\n    /**\n     * Fetches the list of StudentAssignments for this Assignment\n     * @example <caption>Get all student assignments for this assignment</caption>\n     * const studentAssignments = assignment.getStudentAssignments().getList(StudentAssignmentOrder.default);\n     *\n     * @example <caption>Get all student assignments for this assignment that are in progress</caption>\n     * const filter = assignment.getStudentAssignmentsFilter({ status: [StudentAssignmentStatus.IN_PROGRESS] });\n     * const studentAssignments = assignment.getStudentAssignments().getList(StudentAssignmentOrder.default, filter);\n     */\n    @memoize\n    getStudentAssignments(): StudentAssignmentSource {\n        return this._core.classroomContext._getStudentAssignmentsSource(this._getStudentAssignmentsFilter());\n    }\n\n    @observable\n    get code(): string {\n        return this._code;\n    }\n\n    @observable\n    get isAssignment(): boolean {\n        return true;\n    }\n\n    @observable\n    get instructions(): string {\n        return this._instructions;\n    }\n\n    @observable\n    get isAutoCreated(): boolean {\n        return this._isAutoCreated;\n    }\n\n    @observable\n    get dueDate(): Date | undefined {\n        return this._dueDate;\n    }\n\n    @observable\n    get status(): AssignmentStatus {\n        return this._status;\n    }\n\n    @observable\n    get tasks(): string[] {\n        return this._tasks ?? [];\n    }\n\n    @observable\n    get templateIds(): string[] {\n        return this._templateIds ?? [];\n    }\n\n    @observable\n    get parentClassroomId(): string {\n        return this._parentClassroomId;\n    }\n\n    @observable\n    get materialsAssetId(): string {\n        return this._materialsAssetId;\n    }\n\n    @observable\n    get studentsAssetId(): string {\n        return this._studentsAssetId;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    get _parentAssignmentsAssetId(): string {\n        return this._parentAssignmentsFolderAssetId;\n    }\n\n    @observable\n    get externalTemplateIds(): string[] {\n        if (this._isExternalTutorialsDirty) {\n            this._externalTemplateIds = this._externalTemplateIdsRemote.filter((templateIdOrTutorial) => {\n                try {\n                    JSON.parse(templateIdOrTutorial);\n                    // If it is an object then it is not a template ID, filter it out\n                    return false;\n                } catch {\n                    return true;\n                }\n            });\n        }\n\n        return this._externalTemplateIds;\n    }\n\n    @observable\n    get externalTutorials(): Partial<Tutorial>[] {\n        if (this._isExternalTutorialsDirty) {\n            this._externalTutorials = this._externalTemplateIdsRemote.reduce((acc, templateIdOrTutorial) => {\n                try {\n                    acc.push(JSON.parse(templateIdOrTutorial));\n                } catch {\n                    // Not a tutorial, ignore\n                }\n\n                return acc;\n            }, [] as  Partial<Tutorial>[]);\n        }\n\n        return this._externalTutorials;\n    }\n\n    @observable\n    get referenceIds(): string[] {\n        return this._referenceIds ?? [];\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     * Will override any cached assignment with the latest data from the assignment service and R-API\n     */\n    @retry\n    _loadWithRetry(): Promise<void> {\n        return this._load();\n    }\n\n    /**\n   * @param repoMetadata {RepositoryMetadata} If passed in, it will be used instead of loading from the service\n   * @param appMetadata {any} If passed in, it will be used instead of loading from the service\n   *\n   * @package -- only for use in SAM.js\n   */\n    async _load({\n        repoMetadata,\n        appMetadata,\n        effectivePermission,\n    }: {\n        repoMetadata?: RepositoryMetadata;\n        appMetadata?: any;\n        effectivePermission?: Permission;\n    } = {}): Promise<void> {\n        // Similar to what Project already has, first load the AdobeAsset so that once we get the assignment metadata we override any relevant\n        // properties with the assignment metadata\n        await super._load({ repoMetadata, appMetadata, effectivePermission });\n\n        // The Assignment asset must have the assignment links from Hume to be considered complete\n        // Only checking for a single link. If we have this one we can assume we have others\n        const didLinksComeFromHume = this.links[RelType.ASSIGNMENTS_PRIMARY] !== undefined;\n\n        // A majority of the Assignment model has already been set at this point using an AdobeAsset\n        // However the AdobeAsset does not include the expected children array so\n        // we need to call Hume to fetch this info to preserve existing behavior.\n        // Once all clients have moved onto lazy loading studentAssignments this can be removed.\n        const isPartialAssignment = this.studentAssignments.length === 0;\n        // The assignment model is constructed of a mix of repo and app metadata, if either are missing, refetch the assignment\n        const isStaleAssignment = !repoMetadata || !appMetadata;\n        if (isStaleAssignment || isPartialAssignment || !didLinksComeFromHume) {\n            // load the assignment metadata using the assignment service\n            const assignmentMetadata = await this._assignmentInterface.getAssignment(\n                this.id, undefined, { [RequestHeaders.PREFER_RAPI]: 'true' }\n            );\n            const session = this._core._getAssetPool().createMutationSession<Assignment>();\n            AssignmentUpdater.updateRemoteItem(session, assignmentMetadata!);\n            session.commit();\n        }\n    }\n\n    /**\n     * Updates the metadata for an assignment. If template IDs are provided then they\n     * will be cloned to the assignment's working folder with new asset IDs\n     */\n    async updateAssignment(data: IAssignmentPatchData): Promise<void> {\n        return this._core.classroomContext.updateAssignment(this.id, data);\n    }\n\n    /**\n     * Clones the incoming assets to the assignment's working folder with new asset IDs\n     * @param templateAssetIds - An array of asset IDs which will be used to copy the asset from the teacher to the assignment\n     */\n    async setTemplates(templateAssetIds: string[]): Promise<void> {\n        return this._core.classroomContext.updateAssignment(this.id, { templateIds: templateAssetIds });\n    }\n\n    /**\n     * Discards an assignment -- from discarded state, assignment can either be restored or permanently deleted.\n     */\n    async discard(): Promise<void> {\n        if (this.isDiscarded) {\n            return;\n        }\n\n        await this._assignmentInterface.discardAssignment(this.id, this.links);\n        const assignmentPool = this._core._getAssetPool();\n        const session = assignmentPool.createUpdateSession<Assignment>();\n        AssignmentUpdater.updateLocalItem(session, this, { 'repo:state': AssetStateChoices[1] });\n        session.commit();\n    }\n\n    /**\n     * Restores an assignment from the discarded state\n     */\n    async restore(): Promise<void> {\n        if (!this.isDiscarded) {\n            return;\n        }\n\n        await this._assignmentInterface.restoreAssignment(this.id, this.links);\n        const assignmentPool = this._core._getAssetPool();\n        const session = assignmentPool.createUpdateSession<Assignment>();\n        AssignmentUpdater.updateLocalItem(session, this, { 'repo:state': AssetStateChoices[0] });\n        session.commit();\n    }\n\n    @observable\n    get links(): AssignmentLinks {\n        // Make a copy to avoid the client accidentally manipulating the links\n        return Object.assign({}, this.__links as AssignmentLinks);\n    }\n}\n\nexport const AssignmentUpdater = new ItemUpdater<Assignment, Partial<IRemoteAssignment | AdobeAssetUpdaterMetadata>>({\n    localItemType: Assignment,\n    remoteIdProperty: 'repo:assetId',\n    propertyUpdater: new PropertyUpdater({\n        _campaignId: { name: 'assignment:campaignId', format: 'string' },\n        _canClassroomReadSubmissions: { name: 'assignment:canClassroomReadSubmissions', format: 'boolean' },\n        _name: { name: 'repo:name', format: 'string' },\n        _created: { name: 'repo:createDate', format: 'date' },\n        _parentClassroomAssetId: { name: 'classroom:context[classroom:classroomContext][classroom:classroomAssetId]', format: 'string' },\n        _parentAssignmentsFolderAssetId: { name: 'classroom:context[classroom:assignmentsContext][classroom:assignmentsAssetId]', format: 'string' },\n        _materialsAssetId: { name: 'classroom:context[assignment:materialsContext][assignment:materialsAssetId]', format: 'string' },\n        _studentsAssetId: { name: 'classroom:context[assignment:studentsContext][assignment:studentsAssetId]', format: 'string' },\n        _repositoryID: { name: 'repo:repositoryId', format: 'string' },\n        __links: { name: '_links', format: 'object' },\n        // things TBD from Assignment service are below\n        _studentAssignments: {\n            isArray: true,\n            name: 'children',\n            format: 'object',\n            set: (studentAssignments: IRemoteStudentAssignment[], dest: ISAMObject) => {\n                const assignment = dest as Assignment;\n\n                // Clearing the collection in case this updater is called twice, to avoid duplicate student assignments.\n                assignment.studentAssignments.length = 0;\n\n                const session = assignment._core._getAssetPool().createMutationSession<StudentAssignment>();\n\n                // Add computed values for each student assignment\n                const studentAssignmentsWithComputedValues = studentAssignments.map(sa => ({\n                    ...sa,\n                    'computedAssignmentCode': assignment.code,\n                    'classroom:context': {\n                        'classroom:assignmentContext': {\n                            'classroom:assignmentAssetId': assignment.id\n                        },\n                        'classroom:classroomContext': {\n                            'classroom:classroomAssetId': assignment.parentClassroomId\n                        },\n                        'classroom:assignmentsContext': {\n                            'classroom:assignmentsAssetId': assignment._parentAssignmentsAssetId\n                        },\n                        'assignment:materialsContext': {\n                            'assignment:materialsAssetId': assignment.materialsAssetId\n                        },\n                        'assignment:studentsContext': {\n                            'assignment:studentsAssetId': assignment.studentsAssetId\n                        }\n                    }\n                }));\n\n                const cachedStudentAssignments = StudentAssignmentUpdater.updateRemoteItems(\n                    session,\n                    studentAssignmentsWithComputedValues\n                );\n                session.commit();\n\n                // cannot do assignment.studentAssignments = cachedStudentAssignments instead because it mentioned assignment.studentAssignments is read-only\n                assignment.studentAssignments.push(...cachedStudentAssignments);\n\n                const order = StudentAssignmentOrder.default;\n                order.sortItems(assignment.studentAssignments);\n            }\n        },\n        _tasks: { isArray: true, name: 'assignment:tasks' },\n        _code: { name: 'assignment:code', format: 'string' },\n        _classroomId: { name: 'assignment:classroomId', format: 'string' },\n        _createdBy: { name: 'repo:createdBy', format: 'string' },\n        _status: { name: 'assignment:status', format: 'string', choices: AssignmentStatusChoices },\n        _dueDate: { name: 'assignment:dueDate', format: 'date' },\n        _instructions: { name: 'assignment:instructions', format: 'string' },\n        _templateIds: { name: 'assignment:templateIds', isArray: true },\n        _externalTemplateIdsRemote: {\n            name: 'assignment:externalTemplateIds',\n            isArray: true,\n            set: (externalTemplateIdsAndTutorials: string[], dest: ISAMObject) => {\n                const assignment = dest as Assignment;\n                assignment['_externalTemplateIdsRemote'] = externalTemplateIdsAndTutorials;\n                assignment['_isExternalTutorialsDirty'] = true;\n            }\n        },\n        _referenceIds: { name: 'assignment:referenceIds', isArray: true },\n        _path: { name: 'repo:path', format: 'string' },\n        _modifiedBy: { name: 'repo:modifiedBy', format: 'string' },\n        _assetState: { name: 'repo:state', choices: AssetStateChoices },\n        _isAutoCreated: { get: (source) => source['assignment:createdBy'] === 'adobe', format: 'boolean' },\n    }),\n});\n","import type AssignmentInterface from '../interface/AssignmentsInterface';\nimport type Assignment from './Assignment';\nimport { AssignmentUpdater } from './Assignment';\nimport type {\n    IItemLoader,\n    IItemLoaderOptions,\n    ILoadedPage,\n} from '../core/ItemLoader';\nimport type { AssignmentConfig } from './AssignmentSource';\nimport type { IServiceLink } from '../interface/LinkUtils';\nimport type { IAssignmentsResponse, IRemoteAssignment } from '../interface/AssignmentModel';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type AssignmentFilter from './AssignmentFilter';\nimport type AdobeAsset from '../assets/AdobeAsset';\n\nexport default class AssignmentsListLoader\nimplements IItemLoader<AssignmentConfig> {\n    constructor(\n        private _assignmentInterface: AssignmentInterface,\n        private _core: ISAMCorePrivate,\n    ) {}\n\n    async loadPage(\n        options: IItemLoaderOptions<AssignmentConfig>\n    ): Promise<ILoadedPage<AssignmentConfig>> {\n        return await this._loadPage(options);\n    }\n\n    /**\n     * Observe Assignments folder to get enable automatic ONS updates for assignments page.\n     * @param assignment - assignment, which contains parent folder ID\n     * @returns promise that resolves to students adobe asset instance\n     */\n    private async observeAssignmentsFolder(assignment: IRemoteAssignment): Promise<AdobeAsset> {\n        // Despite classroom:assignmentsContext being an optional field, it is guaranteed to be present for Assignments\n        const assignmentsFolderId = assignment!['classroom:context']['classroom:assignmentsContext']!['classroom:assignmentsAssetId'];\n        // This ticket [ACPCEDU-2563] will try to optimize this.\n        return this._core.hostAssetContext.getAssetWithCloudID(assignmentsFolderId!);\n    }\n\n    private async _loadPage(\n        options: IItemLoaderOptions<AssignmentConfig>,\n        // TODO: https://jira.corp.adobe.com/browse/ACPCEDU-405 add support for paging or remove this\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        pageLink?: IServiceLink\n    ): Promise<ILoadedPage<AssignmentConfig>> {\n        const filter = options.filter as AssignmentFilter;\n        const { classroomId, campaignId, submissions } = filter;\n        const result: IAssignmentsResponse = await this._assignmentInterface.getAssignments({\n            ...options,\n            classroomId,\n            campaignId,\n            submissions: await this._core.classroomContext.validateStudentAssignmentsFilter(submissions, classroomId),\n        });\n        const mostRecentValidMutation = Date.now(); // can add latency similar to what Project has\n\n        // TBD: we probably want a \"mutation\" session here instead of \"update\" session\n        // Details can be found in https://git.corp.adobe.com/torq/acpl-model/pull/3902#discussion_r7024503\n        const session = this._core._getAssetPool().createLoaderUpdateSession<Assignment>(\n            mostRecentValidMutation\n        );\n        const items = AssignmentUpdater.updateRemoteItems(session, result.children);\n        session.commit();\n\n        // All assignments will have the same parent folder ID, so we can observe the parent folder using just the first assignment\n        if (result.children.length > 0) {\n            this.observeAssignmentsFolder(result.children[0]).then((folder) => {\n                // pin this to memory so Garbage Collector does not remove it as long as the list is still kept in memory\n                filter._monitoredFolder = folder;\n            });\n        }\n\n        return {\n            items,\n            total: result.children.length,\n            mostRecentValidMutation,\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type StudentAssignmentsInterface from '../interface/StudentAssignmentsInterface';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type StudentAssignment from './StudentAssignment';\nimport { StudentAssignmentUpdater } from './StudentAssignment';\nimport type { StudentAssignmentConfig } from './StudentAssignmentSource';\nimport type { IRemoteStudentAssignment, IStudentAssignmentResponse } from '../interface/StudentAssignmentModel';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type { ISAMCorePrivate } from '../indexPrivate';\n\nexport default class StudentAssignmentListLoader implements IItemLoader<StudentAssignmentConfig> {\n    constructor(private _StudentAssignmentsInterface: StudentAssignmentsInterface, private _core: ISAMCorePrivate) {}\n\n    async loadPage(options: IItemLoaderOptions<StudentAssignmentConfig>): Promise<ILoadedPage<StudentAssignmentConfig>> {\n        return await this._loadPage(options);\n    }\n\n    /**\n     * Fetch and observe the students folder to track when its children NOT_STARTED Student assignments are changed to IN_PROGRESS ones.\n     * @param studentsMetadata - metadata of the students folder\n     * @returns promise that resolves to students adobe asset instance\n     */\n    private async observeStudentsFolder({ remoteStudentAssignments }: { remoteStudentAssignments: IRemoteStudentAssignment[] }): Promise<AdobeAsset> {\n        // Every remote student assignment has the same students asset id\n        const firstRemoteStudentAssignment = remoteStudentAssignments[0];\n        const studentsAssetId = firstRemoteStudentAssignment['classroom:context']['assignment:studentsContext']['assignment:studentsAssetId'];\n        // Maintain a full-weight adobe asset representation of the students folder as of now since other client can request one of its attributes.\n        // This ticket [ACPCEDU-2563] will try to optimize this.\n        return this._core.hostAssetContext.getAssetWithCloudID(studentsAssetId);\n    }\n\n    /** @note api does not support pagination */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    private async _loadPage(options: IItemLoaderOptions<StudentAssignmentConfig>, start?: number): Promise<ILoadedPage<StudentAssignmentConfig>> {\n        const { filter: explicitFilter, implicitFilter } = options;\n        /**\n         * Filter scenarios:\n         *\n         * From Assignment.getStudentAssignments() or ClassroomContext.getStudentAssignments():\n         * implicitFilter = ImplicitStudentAssignmentFilter({assignmentId OR assignmentCode})\n         * explicitFilter = StudentAssignmentFilter | EverythingFilter\n         */\n\n        const { loadDocuments } = explicitFilter;\n        const { assignmentId, assignmentCode } = implicitFilter;\n\n        let studentAssignments: StudentAssignment[] = [];\n\n        const result: IStudentAssignmentResponse = await this._StudentAssignmentsInterface.getStudentAssignments({\n            assignmentCode, assignmentId, loadDocuments });\n        const remoteStudentAssignments: IRemoteStudentAssignment[] = result.children;\n\n        const session = this._core._getAssetPool().createUpdateSession<StudentAssignment>();\n\n        // Add computedAssignmentCode to each remote student assignment if present\n        const studentAssignmentsWithCode = assignmentCode ? remoteStudentAssignments.map(sa => (\n            {\n                ...sa,\n                'computedAssignmentCode': assignmentCode,\n            }\n        )) : remoteStudentAssignments;\n\n        studentAssignments = StudentAssignmentUpdater.updateRemoteItems(session, studentAssignmentsWithCode);\n        session.commit();\n\n        if (loadDocuments) {\n            for (const studentAssignment of studentAssignments) {\n                // Since we are preloading the files before there is a StudentAssignment object to associate them with,\n                // the SA and it's files may need to be linked up later by the file loader.\n                studentAssignment._hasLoadedChildren = true;\n            }\n        }\n\n        // No need to await, let this happen in parallel because we don't really care if it ends up failing\n        // this is a nice-to-have for an ideal real-time experience for user, but is not needed by\n        // the user at this moment so do not impact the performance of the current workflow\n        // If there's no student assignments, which means we don't have students assigned to this assignment, we don't need to observe the students folder\n        if (remoteStudentAssignments.length > 0) {\n            this.observeStudentsFolder({ remoteStudentAssignments }).then((folder) => {\n                // pin this to memory so Garbage Collector does not remove it as long as the list is still kept in memory\n                implicitFilter._monitoredFolder = folder;\n            });\n        }\n\n        return {\n            items: studentAssignments,\n            total: studentAssignments.length,\n            loadNextPage: undefined,\n        };\n    }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Updates to this file should also be replicated to @opentelemetry/core too.\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * - <object> (When all else fails)\n */\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexport var _globalThis = typeof globalThis === 'object'\n    ? globalThis\n    : typeof self === 'object'\n        ? self\n        : typeof window === 'object'\n            ? window\n            : typeof global === 'object'\n                ? global\n                : {};\n//# sourceMappingURL=globalThis.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// this is autogenerated file, see scripts/version-update.js\nexport var VERSION = '1.7.0';\n//# sourceMappingURL=version.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { VERSION } from '../version';\nvar re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n *    - 1.x package cannot use global 2.x package\n *    - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n *    - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n *    - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(ownVersion) {\n    var acceptedVersions = new Set([ownVersion]);\n    var rejectedVersions = new Set();\n    var myVersionMatch = ownVersion.match(re);\n    if (!myVersionMatch) {\n        // we cannot guarantee compatibility so we always return noop\n        return function () { return false; };\n    }\n    var ownVersionParsed = {\n        major: +myVersionMatch[1],\n        minor: +myVersionMatch[2],\n        patch: +myVersionMatch[3],\n        prerelease: myVersionMatch[4],\n    };\n    // if ownVersion has a prerelease tag, versions must match exactly\n    if (ownVersionParsed.prerelease != null) {\n        return function isExactmatch(globalVersion) {\n            return globalVersion === ownVersion;\n        };\n    }\n    function _reject(v) {\n        rejectedVersions.add(v);\n        return false;\n    }\n    function _accept(v) {\n        acceptedVersions.add(v);\n        return true;\n    }\n    return function isCompatible(globalVersion) {\n        if (acceptedVersions.has(globalVersion)) {\n            return true;\n        }\n        if (rejectedVersions.has(globalVersion)) {\n            return false;\n        }\n        var globalVersionMatch = globalVersion.match(re);\n        if (!globalVersionMatch) {\n            // cannot parse other version\n            // we cannot guarantee compatibility so we always noop\n            return _reject(globalVersion);\n        }\n        var globalVersionParsed = {\n            major: +globalVersionMatch[1],\n            minor: +globalVersionMatch[2],\n            patch: +globalVersionMatch[3],\n            prerelease: globalVersionMatch[4],\n        };\n        // if globalVersion has a prerelease tag, versions must match exactly\n        if (globalVersionParsed.prerelease != null) {\n            return _reject(globalVersion);\n        }\n        // major versions must match\n        if (ownVersionParsed.major !== globalVersionParsed.major) {\n            return _reject(globalVersion);\n        }\n        if (ownVersionParsed.major === 0) {\n            if (ownVersionParsed.minor === globalVersionParsed.minor &&\n                ownVersionParsed.patch <= globalVersionParsed.patch) {\n                return _accept(globalVersion);\n            }\n            return _reject(globalVersion);\n        }\n        if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n            return _accept(globalVersion);\n        }\n        return _reject(globalVersion);\n    };\n}\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n *    - 1.x package cannot use global 2.x package\n *    - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n *    - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n *    - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport var isCompatible = _makeCompatibilityCheck(VERSION);\n//# sourceMappingURL=semver.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { _globalThis } from '../platform';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\nvar major = VERSION.split('.')[0];\nvar GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\"opentelemetry.js.api.\" + major);\nvar _global = _globalThis;\nexport function registerGlobal(type, instance, diag, allowOverride) {\n    var _a;\n    if (allowOverride === void 0) { allowOverride = false; }\n    var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {\n        version: VERSION,\n    });\n    if (!allowOverride && api[type]) {\n        // already registered an API of this type\n        var err = new Error(\"@opentelemetry/api: Attempted duplicate registration of API: \" + type);\n        diag.error(err.stack || err.message);\n        return false;\n    }\n    if (api.version !== VERSION) {\n        // All registered APIs must be of the same version exactly\n        var err = new Error(\"@opentelemetry/api: Registration of version v\" + api.version + \" for \" + type + \" does not match previously registered API v\" + VERSION);\n        diag.error(err.stack || err.message);\n        return false;\n    }\n    api[type] = instance;\n    diag.debug(\"@opentelemetry/api: Registered a global for \" + type + \" v\" + VERSION + \".\");\n    return true;\n}\nexport function getGlobal(type) {\n    var _a, _b;\n    var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;\n    if (!globalVersion || !isCompatible(globalVersion)) {\n        return;\n    }\n    return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];\n}\nexport function unregisterGlobal(type, diag) {\n    diag.debug(\"@opentelemetry/api: Unregistering a global for \" + type + \" v\" + VERSION + \".\");\n    var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n    if (api) {\n        delete api[type];\n    }\n}\n//# sourceMappingURL=global-utils.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n    if (!m) return o;\n    var i = m.call(o), r, ar = [], e;\n    try {\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n    }\n    catch (error) { e = { error: error }; }\n    finally {\n        try {\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\n        }\n        finally { if (e) throw e.error; }\n    }\n    return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n        if (ar || !(i in from)) {\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n            ar[i] = from[i];\n        }\n    }\n    return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { getGlobal } from '../internal/global-utils';\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nvar DiagComponentLogger = /** @class */ (function () {\n    function DiagComponentLogger(props) {\n        this._namespace = props.namespace || 'DiagComponentLogger';\n    }\n    DiagComponentLogger.prototype.debug = function () {\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        return logProxy('debug', this._namespace, args);\n    };\n    DiagComponentLogger.prototype.error = function () {\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        return logProxy('error', this._namespace, args);\n    };\n    DiagComponentLogger.prototype.info = function () {\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        return logProxy('info', this._namespace, args);\n    };\n    DiagComponentLogger.prototype.warn = function () {\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        return logProxy('warn', this._namespace, args);\n    };\n    DiagComponentLogger.prototype.verbose = function () {\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        return logProxy('verbose', this._namespace, args);\n    };\n    return DiagComponentLogger;\n}());\nexport { DiagComponentLogger };\nfunction logProxy(funcName, namespace, args) {\n    var logger = getGlobal('diag');\n    // shortcut if logger not set\n    if (!logger) {\n        return;\n    }\n    args.unshift(namespace);\n    return logger[funcName].apply(logger, __spreadArray([], __read(args), false));\n}\n//# sourceMappingURL=ComponentLogger.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport var DiagLogLevel;\n(function (DiagLogLevel) {\n    /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n    DiagLogLevel[DiagLogLevel[\"NONE\"] = 0] = \"NONE\";\n    /** Identifies an error scenario */\n    DiagLogLevel[DiagLogLevel[\"ERROR\"] = 30] = \"ERROR\";\n    /** Identifies a warning scenario */\n    DiagLogLevel[DiagLogLevel[\"WARN\"] = 50] = \"WARN\";\n    /** General informational log message */\n    DiagLogLevel[DiagLogLevel[\"INFO\"] = 60] = \"INFO\";\n    /** General debug log message */\n    DiagLogLevel[DiagLogLevel[\"DEBUG\"] = 70] = \"DEBUG\";\n    /**\n     * Detailed trace level logging should only be used for development, should only be set\n     * in a development environment.\n     */\n    DiagLogLevel[DiagLogLevel[\"VERBOSE\"] = 80] = \"VERBOSE\";\n    /** Used to set the logging level to include all logging */\n    DiagLogLevel[DiagLogLevel[\"ALL\"] = 9999] = \"ALL\";\n})(DiagLogLevel || (DiagLogLevel = {}));\n//# sourceMappingURL=types.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n    if (!m) return o;\n    var i = m.call(o), r, ar = [], e;\n    try {\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n    }\n    catch (error) { e = { error: error }; }\n    finally {\n        try {\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\n        }\n        finally { if (e) throw e.error; }\n    }\n    return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n        if (ar || !(i in from)) {\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n            ar[i] = from[i];\n        }\n    }\n    return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport { DiagLogLevel, } from '../diag/types';\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nvar API_NAME = 'diag';\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nvar DiagAPI = /** @class */ (function () {\n    /**\n     * Private internal constructor\n     * @private\n     */\n    function DiagAPI() {\n        function _logProxy(funcName) {\n            return function () {\n                var args = [];\n                for (var _i = 0; _i < arguments.length; _i++) {\n                    args[_i] = arguments[_i];\n                }\n                var logger = getGlobal('diag');\n                // shortcut if logger not set\n                if (!logger)\n                    return;\n                return logger[funcName].apply(logger, __spreadArray([], __read(args), false));\n            };\n        }\n        // Using self local variable for minification purposes as 'this' cannot be minified\n        var self = this;\n        // DiagAPI specific functions\n        var setLogger = function (logger, optionsOrLogLevel) {\n            var _a, _b, _c;\n            if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }; }\n            if (logger === self) {\n                // There isn't much we can do here.\n                // Logging to the console might break the user application.\n                // Try to log to self. If a logger was previously registered it will receive the log.\n                var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation');\n                self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);\n                return false;\n            }\n            if (typeof optionsOrLogLevel === 'number') {\n                optionsOrLogLevel = {\n                    logLevel: optionsOrLogLevel,\n                };\n            }\n            var oldLogger = getGlobal('diag');\n            var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);\n            // There already is an logger registered. We'll let it know before overwriting it.\n            if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n                var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : '<failed to generate stacktrace>';\n                oldLogger.warn(\"Current logger will be overwritten from \" + stack);\n                newLogger.warn(\"Current logger will overwrite one already registered from \" + stack);\n            }\n            return registerGlobal('diag', newLogger, self, true);\n        };\n        self.setLogger = setLogger;\n        self.disable = function () {\n            unregisterGlobal(API_NAME, self);\n        };\n        self.createComponentLogger = function (options) {\n            return new DiagComponentLogger(options);\n        };\n        self.verbose = _logProxy('verbose');\n        self.debug = _logProxy('debug');\n        self.info = _logProxy('info');\n        self.warn = _logProxy('warn');\n        self.error = _logProxy('error');\n    }\n    /** Get the singleton instance of the DiagAPI API */\n    DiagAPI.instance = function () {\n        if (!this._instance) {\n            this._instance = new DiagAPI();\n        }\n        return this._instance;\n    };\n    return DiagAPI;\n}());\nexport { DiagAPI };\n//# sourceMappingURL=diag.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DiagLogLevel } from '../types';\nexport function createLogLevelDiagLogger(maxLevel, logger) {\n    if (maxLevel < DiagLogLevel.NONE) {\n        maxLevel = DiagLogLevel.NONE;\n    }\n    else if (maxLevel > DiagLogLevel.ALL) {\n        maxLevel = DiagLogLevel.ALL;\n    }\n    // In case the logger is null or undefined\n    logger = logger || {};\n    function _filterFunc(funcName, theLevel) {\n        var theFunc = logger[funcName];\n        if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n            return theFunc.bind(logger);\n        }\n        return function () { };\n    }\n    return {\n        error: _filterFunc('error', DiagLogLevel.ERROR),\n        warn: _filterFunc('warn', DiagLogLevel.WARN),\n        info: _filterFunc('info', DiagLogLevel.INFO),\n        debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n        verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n    };\n}\n//# sourceMappingURL=logLevelLogger.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n    if (!m) return o;\n    var i = m.call(o), r, ar = [], e;\n    try {\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n    }\n    catch (error) { e = { error: error }; }\n    finally {\n        try {\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\n        }\n        finally { if (e) throw e.error; }\n    }\n    return ar;\n};\nvar __values = (this && this.__values) || function(o) {\n    var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n    if (m) return m.call(o);\n    if (o && typeof o.length === \"number\") return {\n        next: function () {\n            if (o && i >= o.length) o = void 0;\n            return { value: o && o[i++], done: !o };\n        }\n    };\n    throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nvar BaggageImpl = /** @class */ (function () {\n    function BaggageImpl(entries) {\n        this._entries = entries ? new Map(entries) : new Map();\n    }\n    BaggageImpl.prototype.getEntry = function (key) {\n        var entry = this._entries.get(key);\n        if (!entry) {\n            return undefined;\n        }\n        return Object.assign({}, entry);\n    };\n    BaggageImpl.prototype.getAllEntries = function () {\n        return Array.from(this._entries.entries()).map(function (_a) {\n            var _b = __read(_a, 2), k = _b[0], v = _b[1];\n            return [k, v];\n        });\n    };\n    BaggageImpl.prototype.setEntry = function (key, entry) {\n        var newBaggage = new BaggageImpl(this._entries);\n        newBaggage._entries.set(key, entry);\n        return newBaggage;\n    };\n    BaggageImpl.prototype.removeEntry = function (key) {\n        var newBaggage = new BaggageImpl(this._entries);\n        newBaggage._entries.delete(key);\n        return newBaggage;\n    };\n    BaggageImpl.prototype.removeEntries = function () {\n        var e_1, _a;\n        var keys = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            keys[_i] = arguments[_i];\n        }\n        var newBaggage = new BaggageImpl(this._entries);\n        try {\n            for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {\n                var key = keys_1_1.value;\n                newBaggage._entries.delete(key);\n            }\n        }\n        catch (e_1_1) { e_1 = { error: e_1_1 }; }\n        finally {\n            try {\n                if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);\n            }\n            finally { if (e_1) throw e_1.error; }\n        }\n        return newBaggage;\n    };\n    BaggageImpl.prototype.clear = function () {\n        return new BaggageImpl();\n    };\n    return BaggageImpl;\n}());\nexport { BaggageImpl };\n//# sourceMappingURL=baggage-impl.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DiagAPI } from '../api/diag';\nimport { BaggageImpl } from './internal/baggage-impl';\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\nvar diag = DiagAPI.instance();\n/**\n * Create a new Baggage with optional entries\n *\n * @param entries An array of baggage entries the new baggage should contain\n */\nexport function createBaggage(entries) {\n    if (entries === void 0) { entries = {}; }\n    return new BaggageImpl(new Map(Object.entries(entries)));\n}\n/**\n * Create a serializable BaggageEntryMetadata object from a string.\n *\n * @param str string metadata. Format is currently not defined by the spec and has no special meaning.\n *\n */\nexport function baggageEntryMetadataFromString(str) {\n    if (typeof str !== 'string') {\n        diag.error(\"Cannot create baggage metadata from unknown type: \" + typeof str);\n        str = '';\n    }\n    return {\n        __TYPE__: baggageEntryMetadataSymbol,\n        toString: function () {\n            return str;\n        },\n    };\n}\n//# sourceMappingURL=utils.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description) {\n    // The specification states that for the same input, multiple calls should\n    // return different keys. Due to the nature of the JS dependency management\n    // system, this creates problems where multiple versions of some package\n    // could hold different keys for the same property.\n    //\n    // Therefore, we use Symbol.for which returns the same key for the same input.\n    return Symbol.for(description);\n}\nvar BaseContext = /** @class */ (function () {\n    /**\n     * Construct a new context which inherits values from an optional parent context.\n     *\n     * @param parentContext a context from which to inherit values\n     */\n    function BaseContext(parentContext) {\n        // for minification\n        var self = this;\n        self._currentContext = parentContext ? new Map(parentContext) : new Map();\n        self.getValue = function (key) { return self._currentContext.get(key); };\n        self.setValue = function (key, value) {\n            var context = new BaseContext(self._currentContext);\n            context._currentContext.set(key, value);\n            return context;\n        };\n        self.deleteValue = function (key) {\n            var context = new BaseContext(self._currentContext);\n            context._currentContext.delete(key);\n            return context;\n        };\n    }\n    return BaseContext;\n}());\n/** The root context is used as the default parent context when there is no active context */\nexport var ROOT_CONTEXT = new BaseContext();\n//# sourceMappingURL=context.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport var TraceFlags;\n(function (TraceFlags) {\n    /** Represents no flag set. */\n    TraceFlags[TraceFlags[\"NONE\"] = 0] = \"NONE\";\n    /** Bit to represent whether trace is sampled in trace flags. */\n    TraceFlags[TraceFlags[\"SAMPLED\"] = 1] = \"SAMPLED\";\n})(TraceFlags || (TraceFlags = {}));\n//# sourceMappingURL=trace_flags.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n    var extendStatics = function (d, b) {\n        extendStatics = Object.setPrototypeOf ||\n            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n        return extendStatics(d, b);\n    };\n    return function (d, b) {\n        if (typeof b !== \"function\" && b !== null)\n            throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n        extendStatics(d, b);\n        function __() { this.constructor = d; }\n        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n    };\n})();\n/**\n * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses\n * constant NoopMetrics for all of its methods.\n */\nvar NoopMeter = /** @class */ (function () {\n    function NoopMeter() {\n    }\n    /**\n     * @see {@link Meter.createHistogram}\n     */\n    NoopMeter.prototype.createHistogram = function (_name, _options) {\n        return NOOP_HISTOGRAM_METRIC;\n    };\n    /**\n     * @see {@link Meter.createCounter}\n     */\n    NoopMeter.prototype.createCounter = function (_name, _options) {\n        return NOOP_COUNTER_METRIC;\n    };\n    /**\n     * @see {@link Meter.createUpDownCounter}\n     */\n    NoopMeter.prototype.createUpDownCounter = function (_name, _options) {\n        return NOOP_UP_DOWN_COUNTER_METRIC;\n    };\n    /**\n     * @see {@link Meter.createObservableGauge}\n     */\n    NoopMeter.prototype.createObservableGauge = function (_name, _options) {\n        return NOOP_OBSERVABLE_GAUGE_METRIC;\n    };\n    /**\n     * @see {@link Meter.createObservableCounter}\n     */\n    NoopMeter.prototype.createObservableCounter = function (_name, _options) {\n        return NOOP_OBSERVABLE_COUNTER_METRIC;\n    };\n    /**\n     * @see {@link Meter.createObservableUpDownCounter}\n     */\n    NoopMeter.prototype.createObservableUpDownCounter = function (_name, _options) {\n        return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;\n    };\n    /**\n     * @see {@link Meter.addBatchObservableCallback}\n     */\n    NoopMeter.prototype.addBatchObservableCallback = function (_callback, _observables) { };\n    /**\n     * @see {@link Meter.removeBatchObservableCallback}\n     */\n    NoopMeter.prototype.removeBatchObservableCallback = function (_callback) { };\n    return NoopMeter;\n}());\nexport { NoopMeter };\nvar NoopMetric = /** @class */ (function () {\n    function NoopMetric() {\n    }\n    return NoopMetric;\n}());\nexport { NoopMetric };\nvar NoopCounterMetric = /** @class */ (function (_super) {\n    __extends(NoopCounterMetric, _super);\n    function NoopCounterMetric() {\n        return _super !== null && _super.apply(this, arguments) || this;\n    }\n    NoopCounterMetric.prototype.add = function (_value, _attributes) { };\n    return NoopCounterMetric;\n}(NoopMetric));\nexport { NoopCounterMetric };\nvar NoopUpDownCounterMetric = /** @class */ (function (_super) {\n    __extends(NoopUpDownCounterMetric, _super);\n    function NoopUpDownCounterMetric() {\n        return _super !== null && _super.apply(this, arguments) || this;\n    }\n    NoopUpDownCounterMetric.prototype.add = function (_value, _attributes) { };\n    return NoopUpDownCounterMetric;\n}(NoopMetric));\nexport { NoopUpDownCounterMetric };\nvar NoopHistogramMetric = /** @class */ (function (_super) {\n    __extends(NoopHistogramMetric, _super);\n    function NoopHistogramMetric() {\n        return _super !== null && _super.apply(this, arguments) || this;\n    }\n    NoopHistogramMetric.prototype.record = function (_value, _attributes) { };\n    return NoopHistogramMetric;\n}(NoopMetric));\nexport { NoopHistogramMetric };\nvar NoopObservableMetric = /** @class */ (function () {\n    function NoopObservableMetric() {\n    }\n    NoopObservableMetric.prototype.addCallback = function (_callback) { };\n    NoopObservableMetric.prototype.removeCallback = function (_callback) { };\n    return NoopObservableMetric;\n}());\nexport { NoopObservableMetric };\nvar NoopObservableCounterMetric = /** @class */ (function (_super) {\n    __extends(NoopObservableCounterMetric, _super);\n    function NoopObservableCounterMetric() {\n        return _super !== null && _super.apply(this, arguments) || this;\n    }\n    return NoopObservableCounterMetric;\n}(NoopObservableMetric));\nexport { NoopObservableCounterMetric };\nvar NoopObservableGaugeMetric = /** @class */ (function (_super) {\n    __extends(NoopObservableGaugeMetric, _super);\n    function NoopObservableGaugeMetric() {\n        return _super !== null && _super.apply(this, arguments) || this;\n    }\n    return NoopObservableGaugeMetric;\n}(NoopObservableMetric));\nexport { NoopObservableGaugeMetric };\nvar NoopObservableUpDownCounterMetric = /** @class */ (function (_super) {\n    __extends(NoopObservableUpDownCounterMetric, _super);\n    function NoopObservableUpDownCounterMetric() {\n        return _super !== null && _super.apply(this, arguments) || this;\n    }\n    return NoopObservableUpDownCounterMetric;\n}(NoopObservableMetric));\nexport { NoopObservableUpDownCounterMetric };\nexport var NOOP_METER = new NoopMeter();\n// Synchronous instruments\nexport var NOOP_COUNTER_METRIC = new NoopCounterMetric();\nexport var NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();\nexport var NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();\n// Asynchronous instruments\nexport var NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();\nexport var NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();\nexport var NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();\n/**\n * Create a no-op Meter\n */\nexport function createNoopMeter() {\n    return NOOP_METER;\n}\n//# sourceMappingURL=NoopMeter.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport var defaultTextMapGetter = {\n    get: function (carrier, key) {\n        if (carrier == null) {\n            return undefined;\n        }\n        return carrier[key];\n    },\n    keys: function (carrier) {\n        if (carrier == null) {\n            return [];\n        }\n        return Object.keys(carrier);\n    },\n};\nexport var defaultTextMapSetter = {\n    set: function (carrier, key, value) {\n        if (carrier == null) {\n            return;\n        }\n        carrier[key] = value;\n    },\n};\n//# sourceMappingURL=TextMapPropagator.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n    if (!m) return o;\n    var i = m.call(o), r, ar = [], e;\n    try {\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n    }\n    catch (error) { e = { error: error }; }\n    finally {\n        try {\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\n        }\n        finally { if (e) throw e.error; }\n    }\n    return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n        if (ar || !(i in from)) {\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n            ar[i] = from[i];\n        }\n    }\n    return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { ROOT_CONTEXT } from './context';\nvar NoopContextManager = /** @class */ (function () {\n    function NoopContextManager() {\n    }\n    NoopContextManager.prototype.active = function () {\n        return ROOT_CONTEXT;\n    };\n    NoopContextManager.prototype.with = function (_context, fn, thisArg) {\n        var args = [];\n        for (var _i = 3; _i < arguments.length; _i++) {\n            args[_i - 3] = arguments[_i];\n        }\n        return fn.call.apply(fn, __spreadArray([thisArg], __read(args), false));\n    };\n    NoopContextManager.prototype.bind = function (_context, target) {\n        return target;\n    };\n    NoopContextManager.prototype.enable = function () {\n        return this;\n    };\n    NoopContextManager.prototype.disable = function () {\n        return this;\n    };\n    return NoopContextManager;\n}());\nexport { NoopContextManager };\n//# sourceMappingURL=NoopContextManager.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n    if (!m) return o;\n    var i = m.call(o), r, ar = [], e;\n    try {\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n    }\n    catch (error) { e = { error: error }; }\n    finally {\n        try {\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\n        }\n        finally { if (e) throw e.error; }\n    }\n    return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n        if (ar || !(i in from)) {\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n            ar[i] = from[i];\n        }\n    }\n    return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nimport { DiagAPI } from './diag';\nvar API_NAME = 'context';\nvar NOOP_CONTEXT_MANAGER = new NoopContextManager();\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nvar ContextAPI = /** @class */ (function () {\n    /** Empty private constructor prevents end users from constructing a new instance of the API */\n    function ContextAPI() {\n    }\n    /** Get the singleton instance of the Context API */\n    ContextAPI.getInstance = function () {\n        if (!this._instance) {\n            this._instance = new ContextAPI();\n        }\n        return this._instance;\n    };\n    /**\n     * Set the current context manager.\n     *\n     * @returns true if the context manager was successfully registered, else false\n     */\n    ContextAPI.prototype.setGlobalContextManager = function (contextManager) {\n        return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n    };\n    /**\n     * Get the currently active context\n     */\n    ContextAPI.prototype.active = function () {\n        return this._getContextManager().active();\n    };\n    /**\n     * Execute a function with an active context\n     *\n     * @param context context to be active during function execution\n     * @param fn function to execute in a context\n     * @param thisArg optional receiver to be used for calling fn\n     * @param args optional arguments forwarded to fn\n     */\n    ContextAPI.prototype.with = function (context, fn, thisArg) {\n        var _a;\n        var args = [];\n        for (var _i = 3; _i < arguments.length; _i++) {\n            args[_i - 3] = arguments[_i];\n        }\n        return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], __read(args), false));\n    };\n    /**\n     * Bind a context to a target function or event emitter\n     *\n     * @param context context to bind to the event emitter or function. Defaults to the currently active context\n     * @param target function or event emitter to bind\n     */\n    ContextAPI.prototype.bind = function (context, target) {\n        return this._getContextManager().bind(context, target);\n    };\n    ContextAPI.prototype._getContextManager = function () {\n        return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n    };\n    /** Disable and remove the global context manager */\n    ContextAPI.prototype.disable = function () {\n        this._getContextManager().disable();\n        unregisterGlobal(API_NAME, DiagAPI.instance());\n    };\n    return ContextAPI;\n}());\nexport { ContextAPI };\n//# sourceMappingURL=context.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { TraceFlags } from './trace_flags';\nexport var INVALID_SPANID = '0000000000000000';\nexport var INVALID_TRACEID = '00000000000000000000000000000000';\nexport var INVALID_SPAN_CONTEXT = {\n    traceId: INVALID_TRACEID,\n    spanId: INVALID_SPANID,\n    traceFlags: TraceFlags.NONE,\n};\n//# sourceMappingURL=invalid-span-constants.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nvar NonRecordingSpan = /** @class */ (function () {\n    function NonRecordingSpan(_spanContext) {\n        if (_spanContext === void 0) { _spanContext = INVALID_SPAN_CONTEXT; }\n        this._spanContext = _spanContext;\n    }\n    // Returns a SpanContext.\n    NonRecordingSpan.prototype.spanContext = function () {\n        return this._spanContext;\n    };\n    // By default does nothing\n    NonRecordingSpan.prototype.setAttribute = function (_key, _value) {\n        return this;\n    };\n    // By default does nothing\n    NonRecordingSpan.prototype.setAttributes = function (_attributes) {\n        return this;\n    };\n    // By default does nothing\n    NonRecordingSpan.prototype.addEvent = function (_name, _attributes) {\n        return this;\n    };\n    // By default does nothing\n    NonRecordingSpan.prototype.setStatus = function (_status) {\n        return this;\n    };\n    // By default does nothing\n    NonRecordingSpan.prototype.updateName = function (_name) {\n        return this;\n    };\n    // By default does nothing\n    NonRecordingSpan.prototype.end = function (_endTime) { };\n    // isRecording always returns false for NonRecordingSpan.\n    NonRecordingSpan.prototype.isRecording = function () {\n        return false;\n    };\n    // By default does nothing\n    NonRecordingSpan.prototype.recordException = function (_exception, _time) { };\n    return NonRecordingSpan;\n}());\nexport { NonRecordingSpan };\n//# sourceMappingURL=NonRecordingSpan.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { createContextKey } from '../context/context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n/**\n * span key\n */\nvar SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context) {\n    return context.getValue(SPAN_KEY) || undefined;\n}\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan() {\n    return getSpan(ContextAPI.getInstance().active());\n}\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context, span) {\n    return context.setValue(SPAN_KEY, span);\n}\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context) {\n    return context.deleteValue(SPAN_KEY);\n}\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(context, spanContext) {\n    return setSpan(context, new NonRecordingSpan(spanContext));\n}\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context) {\n    var _a;\n    return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();\n}\n//# sourceMappingURL=context-utils.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nvar VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nvar VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\nexport function isValidTraceId(traceId) {\n    return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\nexport function isValidSpanId(spanId) {\n    return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext) {\n    return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId));\n}\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext) {\n    return new NonRecordingSpan(spanContext);\n}\n//# sourceMappingURL=spancontext-utils.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ContextAPI } from '../api/context';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { isSpanContextValid } from './spancontext-utils';\nvar contextApi = ContextAPI.getInstance();\n/**\n * No-op implementations of {@link Tracer}.\n */\nvar NoopTracer = /** @class */ (function () {\n    function NoopTracer() {\n    }\n    // startSpan starts a noop span.\n    NoopTracer.prototype.startSpan = function (name, options, context) {\n        if (context === void 0) { context = contextApi.active(); }\n        var root = Boolean(options === null || options === void 0 ? void 0 : options.root);\n        if (root) {\n            return new NonRecordingSpan();\n        }\n        var parentFromContext = context && getSpanContext(context);\n        if (isSpanContext(parentFromContext) &&\n            isSpanContextValid(parentFromContext)) {\n            return new NonRecordingSpan(parentFromContext);\n        }\n        else {\n            return new NonRecordingSpan();\n        }\n    };\n    NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) {\n        var opts;\n        var ctx;\n        var fn;\n        if (arguments.length < 2) {\n            return;\n        }\n        else if (arguments.length === 2) {\n            fn = arg2;\n        }\n        else if (arguments.length === 3) {\n            opts = arg2;\n            fn = arg3;\n        }\n        else {\n            opts = arg2;\n            ctx = arg3;\n            fn = arg4;\n        }\n        var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();\n        var span = this.startSpan(name, opts, parentContext);\n        var contextWithSpanSet = setSpan(parentContext, span);\n        return contextApi.with(contextWithSpanSet, fn, undefined, span);\n    };\n    return NoopTracer;\n}());\nexport { NoopTracer };\nfunction isSpanContext(spanContext) {\n    return (typeof spanContext === 'object' &&\n        typeof spanContext['spanId'] === 'string' &&\n        typeof spanContext['traceId'] === 'string' &&\n        typeof spanContext['traceFlags'] === 'number');\n}\n//# sourceMappingURL=NoopTracer.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NoopTracer } from './NoopTracer';\nvar NOOP_TRACER = new NoopTracer();\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nvar ProxyTracer = /** @class */ (function () {\n    function ProxyTracer(_provider, name, version, options) {\n        this._provider = _provider;\n        this.name = name;\n        this.version = version;\n        this.options = options;\n    }\n    ProxyTracer.prototype.startSpan = function (name, options, context) {\n        return this._getTracer().startSpan(name, options, context);\n    };\n    ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) {\n        var tracer = this._getTracer();\n        return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n    };\n    /**\n     * Try to get a tracer from the proxy tracer provider.\n     * If the proxy tracer provider has no delegate, return a noop tracer.\n     */\n    ProxyTracer.prototype._getTracer = function () {\n        if (this._delegate) {\n            return this._delegate;\n        }\n        var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);\n        if (!tracer) {\n            return NOOP_TRACER;\n        }\n        this._delegate = tracer;\n        return this._delegate;\n    };\n    return ProxyTracer;\n}());\nexport { ProxyTracer };\n//# sourceMappingURL=ProxyTracer.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nvar NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n *   When a delegate is set, traces are provided from the delegate.\n *   When a delegate is set after tracers have already been provided,\n *   all tracers already provided will use the provided delegate implementation.\n */\nvar ProxyTracerProvider = /** @class */ (function () {\n    function ProxyTracerProvider() {\n    }\n    /**\n     * Get a {@link ProxyTracer}\n     */\n    ProxyTracerProvider.prototype.getTracer = function (name, version, options) {\n        var _a;\n        return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options));\n    };\n    ProxyTracerProvider.prototype.getDelegate = function () {\n        var _a;\n        return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;\n    };\n    /**\n     * Set the delegate tracer provider\n     */\n    ProxyTracerProvider.prototype.setDelegate = function (delegate) {\n        this._delegate = delegate;\n    };\n    ProxyTracerProvider.prototype.getDelegateTracer = function (name, version, options) {\n        var _a;\n        return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);\n    };\n    return ProxyTracerProvider;\n}());\nexport { ProxyTracerProvider };\n//# sourceMappingURL=ProxyTracerProvider.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NoopTracer } from './NoopTracer';\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nvar NoopTracerProvider = /** @class */ (function () {\n    function NoopTracerProvider() {\n    }\n    NoopTracerProvider.prototype.getTracer = function (_name, _version, _options) {\n        return new NoopTracer();\n    };\n    return NoopTracerProvider;\n}());\nexport { NoopTracerProvider };\n//# sourceMappingURL=NoopTracerProvider.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport var context = ContextAPI.getInstance();\n//# sourceMappingURL=context-api.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { DiagAPI } from './api/diag';\n/**\n * Entrypoint for Diag API.\n * Defines Diagnostic handler used for internal diagnostic logging operations.\n * The default provides a Noop DiagLogger implementation which may be changed via the\n * diag.setLogger(logger: DiagLogger) function.\n */\nexport var diag = DiagAPI.instance();\n//# sourceMappingURL=diag-api.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NOOP_METER } from './NoopMeter';\n/**\n * An implementation of the {@link MeterProvider} which returns an impotent Meter\n * for all calls to `getMeter`\n */\nvar NoopMeterProvider = /** @class */ (function () {\n    function NoopMeterProvider() {\n    }\n    NoopMeterProvider.prototype.getMeter = function (_name, _version, _options) {\n        return NOOP_METER;\n    };\n    return NoopMeterProvider;\n}());\nexport { NoopMeterProvider };\nexport var NOOP_METER_PROVIDER = new NoopMeterProvider();\n//# sourceMappingURL=NoopMeterProvider.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider';\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nimport { DiagAPI } from './diag';\nvar API_NAME = 'metrics';\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Metrics API\n */\nvar MetricsAPI = /** @class */ (function () {\n    /** Empty private constructor prevents end users from constructing a new instance of the API */\n    function MetricsAPI() {\n    }\n    /** Get the singleton instance of the Metrics API */\n    MetricsAPI.getInstance = function () {\n        if (!this._instance) {\n            this._instance = new MetricsAPI();\n        }\n        return this._instance;\n    };\n    /**\n     * Set the current global meter provider.\n     * Returns true if the meter provider was successfully registered, else false.\n     */\n    MetricsAPI.prototype.setGlobalMeterProvider = function (provider) {\n        return registerGlobal(API_NAME, provider, DiagAPI.instance());\n    };\n    /**\n     * Returns the global meter provider.\n     */\n    MetricsAPI.prototype.getMeterProvider = function () {\n        return getGlobal(API_NAME) || NOOP_METER_PROVIDER;\n    };\n    /**\n     * Returns a meter from the global meter provider.\n     */\n    MetricsAPI.prototype.getMeter = function (name, version, options) {\n        return this.getMeterProvider().getMeter(name, version, options);\n    };\n    /** Remove the global meter provider */\n    MetricsAPI.prototype.disable = function () {\n        unregisterGlobal(API_NAME, DiagAPI.instance());\n    };\n    return MetricsAPI;\n}());\nexport { MetricsAPI };\n//# sourceMappingURL=metrics.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { MetricsAPI } from './api/metrics';\n/** Entrypoint for metrics API */\nexport var metrics = MetricsAPI.getInstance();\n//# sourceMappingURL=metrics-api.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * No-op implementations of {@link TextMapPropagator}.\n */\nvar NoopTextMapPropagator = /** @class */ (function () {\n    function NoopTextMapPropagator() {\n    }\n    /** Noop inject function does nothing */\n    NoopTextMapPropagator.prototype.inject = function (_context, _carrier) { };\n    /** Noop extract function does nothing and returns the input context */\n    NoopTextMapPropagator.prototype.extract = function (context, _carrier) {\n        return context;\n    };\n    NoopTextMapPropagator.prototype.fields = function () {\n        return [];\n    };\n    return NoopTextMapPropagator;\n}());\nexport { NoopTextMapPropagator };\n//# sourceMappingURL=NoopTextMapPropagator.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ContextAPI } from '../api/context';\nimport { createContextKey } from '../context/context';\n/**\n * Baggage key\n */\nvar BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key');\n/**\n * Retrieve the current baggage from the given context\n *\n * @param {Context} Context that manage all context values\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getBaggage(context) {\n    return context.getValue(BAGGAGE_KEY) || undefined;\n}\n/**\n * Retrieve the current baggage from the active/current context\n *\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getActiveBaggage() {\n    return getBaggage(ContextAPI.getInstance().active());\n}\n/**\n * Store a baggage in the given context\n *\n * @param {Context} Context that manage all context values\n * @param {Baggage} baggage that will be set in the actual context\n */\nexport function setBaggage(context, baggage) {\n    return context.setValue(BAGGAGE_KEY, baggage);\n}\n/**\n * Delete the baggage stored in the given context\n *\n * @param {Context} Context that manage all context values\n */\nexport function deleteBaggage(context) {\n    return context.deleteValue(BAGGAGE_KEY);\n}\n//# sourceMappingURL=context-helpers.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nimport { NoopTextMapPropagator } from '../propagation/NoopTextMapPropagator';\nimport { defaultTextMapGetter, defaultTextMapSetter, } from '../propagation/TextMapPropagator';\nimport { getBaggage, getActiveBaggage, setBaggage, deleteBaggage, } from '../baggage/context-helpers';\nimport { createBaggage } from '../baggage/utils';\nimport { DiagAPI } from './diag';\nvar API_NAME = 'propagation';\nvar NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Propagation API\n */\nvar PropagationAPI = /** @class */ (function () {\n    /** Empty private constructor prevents end users from constructing a new instance of the API */\n    function PropagationAPI() {\n        this.createBaggage = createBaggage;\n        this.getBaggage = getBaggage;\n        this.getActiveBaggage = getActiveBaggage;\n        this.setBaggage = setBaggage;\n        this.deleteBaggage = deleteBaggage;\n    }\n    /** Get the singleton instance of the Propagator API */\n    PropagationAPI.getInstance = function () {\n        if (!this._instance) {\n            this._instance = new PropagationAPI();\n        }\n        return this._instance;\n    };\n    /**\n     * Set the current propagator.\n     *\n     * @returns true if the propagator was successfully registered, else false\n     */\n    PropagationAPI.prototype.setGlobalPropagator = function (propagator) {\n        return registerGlobal(API_NAME, propagator, DiagAPI.instance());\n    };\n    /**\n     * Inject context into a carrier to be propagated inter-process\n     *\n     * @param context Context carrying tracing data to inject\n     * @param carrier carrier to inject context into\n     * @param setter Function used to set values on the carrier\n     */\n    PropagationAPI.prototype.inject = function (context, carrier, setter) {\n        if (setter === void 0) { setter = defaultTextMapSetter; }\n        return this._getGlobalPropagator().inject(context, carrier, setter);\n    };\n    /**\n     * Extract context from a carrier\n     *\n     * @param context Context which the newly created context will inherit from\n     * @param carrier Carrier to extract context from\n     * @param getter Function used to extract keys from a carrier\n     */\n    PropagationAPI.prototype.extract = function (context, carrier, getter) {\n        if (getter === void 0) { getter = defaultTextMapGetter; }\n        return this._getGlobalPropagator().extract(context, carrier, getter);\n    };\n    /**\n     * Return a list of all fields which may be used by the propagator.\n     */\n    PropagationAPI.prototype.fields = function () {\n        return this._getGlobalPropagator().fields();\n    };\n    /** Remove the global propagator */\n    PropagationAPI.prototype.disable = function () {\n        unregisterGlobal(API_NAME, DiagAPI.instance());\n    };\n    PropagationAPI.prototype._getGlobalPropagator = function () {\n        return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;\n    };\n    return PropagationAPI;\n}());\nexport { PropagationAPI };\n//# sourceMappingURL=propagation.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { PropagationAPI } from './api/propagation';\n/** Entrypoint for propagation API */\nexport var propagation = PropagationAPI.getInstance();\n//# sourceMappingURL=propagation-api.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport { isSpanContextValid, wrapSpanContext, } from '../trace/spancontext-utils';\nimport { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext, } from '../trace/context-utils';\nimport { DiagAPI } from './diag';\nvar API_NAME = 'trace';\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nvar TraceAPI = /** @class */ (function () {\n    /** Empty private constructor prevents end users from constructing a new instance of the API */\n    function TraceAPI() {\n        this._proxyTracerProvider = new ProxyTracerProvider();\n        this.wrapSpanContext = wrapSpanContext;\n        this.isSpanContextValid = isSpanContextValid;\n        this.deleteSpan = deleteSpan;\n        this.getSpan = getSpan;\n        this.getActiveSpan = getActiveSpan;\n        this.getSpanContext = getSpanContext;\n        this.setSpan = setSpan;\n        this.setSpanContext = setSpanContext;\n    }\n    /** Get the singleton instance of the Trace API */\n    TraceAPI.getInstance = function () {\n        if (!this._instance) {\n            this._instance = new TraceAPI();\n        }\n        return this._instance;\n    };\n    /**\n     * Set the current global tracer.\n     *\n     * @returns true if the tracer provider was successfully registered, else false\n     */\n    TraceAPI.prototype.setGlobalTracerProvider = function (provider) {\n        var success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());\n        if (success) {\n            this._proxyTracerProvider.setDelegate(provider);\n        }\n        return success;\n    };\n    /**\n     * Returns the global tracer provider.\n     */\n    TraceAPI.prototype.getTracerProvider = function () {\n        return getGlobal(API_NAME) || this._proxyTracerProvider;\n    };\n    /**\n     * Returns a tracer from the global tracer provider.\n     */\n    TraceAPI.prototype.getTracer = function (name, version) {\n        return this.getTracerProvider().getTracer(name, version);\n    };\n    /** Remove the global tracer provider */\n    TraceAPI.prototype.disable = function () {\n        unregisterGlobal(API_NAME, DiagAPI.instance());\n        this._proxyTracerProvider = new ProxyTracerProvider();\n    };\n    return TraceAPI;\n}());\nexport { TraceAPI };\n//# sourceMappingURL=trace.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { baggageEntryMetadataFromString } from './baggage/utils';\n// Context APIs\nexport { createContextKey, ROOT_CONTEXT } from './context/context';\n// Diag APIs\nexport { DiagConsoleLogger } from './diag/consoleLogger';\nexport { DiagLogLevel, } from './diag/types';\n// Metrics APIs\nexport { createNoopMeter } from './metrics/NoopMeter';\nexport { ValueType, } from './metrics/Metric';\n// Propagation APIs\nexport { defaultTextMapGetter, defaultTextMapSetter, } from './propagation/TextMapPropagator';\nexport { ProxyTracer } from './trace/ProxyTracer';\nexport { ProxyTracerProvider } from './trace/ProxyTracerProvider';\nexport { SamplingDecision } from './trace/SamplingResult';\nexport { SpanKind } from './trace/span_kind';\nexport { SpanStatusCode } from './trace/status';\nexport { TraceFlags } from './trace/trace_flags';\nexport { createTraceState } from './trace/internal/utils';\nexport { isSpanContextValid, isValidTraceId, isValidSpanId, } from './trace/spancontext-utils';\nexport { INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT, } from './trace/invalid-span-constants';\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { context } from './context-api';\nimport { diag } from './diag-api';\nimport { metrics } from './metrics-api';\nimport { propagation } from './propagation-api';\nimport { trace } from './trace-api';\n// Named export.\nexport { context, diag, metrics, propagation, trace };\n// Default export.\nexport default {\n    context: context,\n    diag: diag,\n    metrics: metrics,\n    propagation: propagation,\n    trace: trace,\n};\n//# sourceMappingURL=index.js.map","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport var trace = TraceAPI.getInstance();\n//# sourceMappingURL=trace-api.js.map","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport opentelemetry from '@opentelemetry/api';\nimport oneTimeWarning from '../../utils/oneTimeWarning';\n\n/**\n * Decorator for capturing the class name that is included in the span name\n * We are unable to directly fetch the class name from the target due to minification of code\n * @param className - The name of the class.\n * @returns The decorated constructor.\n */\nexport function traceableAs(className: string) {\n    return function (constructor: any) {\n        constructor.traceableAs = () => { return className; };\n    };\n}\n\n/**\n * Decorator for instrumenting a method for emitting tracing spans and events.\n * @param target - The class or prototype of the class.\n * @param propertyKey - The name of the method.\n * @param descriptor - The property descriptor for the method.\n * @returns The decorated method.\n * @remarks ensure that OTel SDK version is compatible with OTel API that SAM.js depends on.\n */\nexport function trace(target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n    let targetConstructor: any = undefined;\n    if (typeof target === 'function' && target.prototype?.constructor) {\n        // target is a class\n        targetConstructor = target.prototype.constructor;\n\n    } else if (typeof target === 'object' && target.constructor) {\n        // target is a class instance\n        targetConstructor = target.constructor;\n    }\n\n    const method = descriptor.value;\n    descriptor.value = function (...args: any[]) {\n        let spanName: string = propertyKey;\n        if (targetConstructor) {\n            let className: string;\n            if (typeof targetConstructor.traceableAs === 'function') {\n                // If the class has a static method traceableAs, use it\n                className = targetConstructor.traceableAs();\n            } else {\n                // Otherwise, fall back to the class name, which might be mangled by minifiers\n                oneTimeWarning(\n                    'Class name not provided',\n                    `Use the traceableAs decorator on the class of ${spanName} to ensure the class name does not get minified`\n                );\n                className = targetConstructor.name;\n            }\n            spanName = className + '.' + spanName;\n        }\n\n        const tracer = opentelemetry.trace.getTracer('sam-js');\n        const span = tracer.startSpan(spanName);\n        const ctx = opentelemetry.trace.setSpan(opentelemetry.context.active(), span);\n        try {\n            const result = opentelemetry.context.with(ctx, method, this, ...args);\n            // Checking whether result is a JS Promise\n            if (!!result && typeof result.then === 'function') {\n                return result.catch((e: any) => {\n                    if (e instanceof Error) {\n                        span.recordException(e);\n                    }\n                    throw e;\n                }).finally(() => {\n                    span.end();\n                });\n            } else {\n                span.end();\n                return result;\n            }\n        } catch (e) {\n            if (e instanceof Error) {\n                span.recordException(e);\n            }\n            span.end();\n            throw e;\n        }\n    };\n    return descriptor;\n}\n\n/**\n * Sets an attribute on the active tracing span.\n * @param key - Tracing span attribute key.\n * @param value - Tracing span attribute value.\n */\nexport function setTracingSpanAttribute(key: string, value?: string) {\n    opentelemetry.trace.getActiveSpan()?.setAttribute(key, value || '');\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport { weakCache, key, memoize, synchronized } from '../core/decorators';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport ItemPool from '../core/ItemPool';\nimport ItemSource from '../core/ItemSource';\nimport type { IBatchOperationResult } from '../interface/RepositoryModel';\nimport type Classroom from './Classroom';\nimport { ClassroomUpdater } from './Classroom';\nimport ClassroomListListLoader from './ClassroomListLoader';\nimport ClassroomsInterface, { validateClassroomData } from '../interface/ClassroomsInterface';\nimport type { ClassroomSource } from './ClassroomSource';\nimport Assignment, { AssignmentUpdater } from '../assignments/Assignment';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport AssignmentsListLoader from '../assignments/AssignmentListLoader';\nimport AssignmentsInterface, { validateAssignmentData } from '../interface/AssignmentsInterface';\nimport type { AssignmentSource } from '../assignments/AssignmentSource';\nimport type { StudentAssignmentSource } from '../assignments/StudentAssignmentSource';\nimport type { IClassroomCreateData, IClassroomUpdateData, IRemoteClassroom, IRemoteBlockOrRemoveResponse, IRemoteMembership, ICoTeacherEligibilityEntry, ICheckCoTeacherEligibilityOptions, CreateClassroomBoardOptions, GetAssignmentBoardsOptions, GetClassroomBoardsOptions, ValidateClassroomBoardNameForCreateOptions, ValidateClassroomBoardNameForUpdateOptions } from '../interface/ClassroomModel';\nimport type { ExternalAsset, IAssignmentCreateData, IAssignmentPatchData, IAssignmentRemotePatchData, IAssignmentUpdateData } from '../interface/AssignmentModel';\nimport { AssignmentStatus, AssignmentSubmissionOwnershipEnums, assignmentRemoteFieldMapping } from '../interface/AssignmentModel';\nimport { validatePlatformRepoName } from '../assets/AssetUtils';\nimport type { GetStudentAssignmentOptions, IRemoteStudentAssignment, IStudentAssignmentReturnData, IStudentAssignmentStartData, IStudentAssignmentSubmitClassroomContextData, RequiredStudentAssignmentFilterOptions, StudentAssignmentOptionalParams } from '../interface/StudentAssignmentModel';\nimport { StudentAssignmentStatus } from '../interface/StudentAssignmentModel';\nimport SAMError from '../core/SAMError';\nimport { SAMErrorCode } from '../core/SAMError';\nimport StudentAssignmentsInterface from '../interface/StudentAssignmentsInterface';\nimport type StudentAssignmentFile from '../assignments/StudentAssignmentFile';\nimport { StudentAssignmentFileUpdater } from '../assignments/StudentAssignmentFile';\nimport type { IGetStudentAssignmentFiles, IRemoteStudentAssignmentFile, IRemoteStudentAssignmentFileMetadataWithComputedValues, IStudentAssignmentFileRemotePatchData } from '../interface/StudentAssignmentFileModel';\nimport hasProperty from '../utils/hasProperty';\nimport type jsonpatch from 'json-patch';\nimport { waitForListLoad } from '../utils/waitForListLoad';\nimport type ClassroomMember from '../classroom-member/ClassroomMember';\nimport type { ClassroomMemberSource } from '../classroom-member/ClassroomMemberSource';\nimport ClassroomMemberListLoader from '../classroom-member/ClassroomMemberListLoader';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport type StudentAssignment from '../assignments/StudentAssignment';\nimport { StudentAssignmentUpdater } from '../assignments/StudentAssignment';\nimport AdobeAssetOrder from '../assets/AdobeAssetOrder';\nimport { getMemberComputedKey, validateString } from '../utils/classroomUtils';\nimport StudentAssignmentFilesListFilter from '../assignments/StudentAssignmentFilesListFilter';\nimport { ClassroomMemberRole } from '../interface/ClassroomMemberModel';\nimport StudentAssignmentListLoader from '../assignments/StudentAssignmentListLoader';\nimport type { IUpdateSession } from '../core/UpdateSession';\nimport { default as ClassroomOrder, type ClassroomOrderField } from './ClassroomOrder';\nimport { default as AssignmentOrder, type AssignmentOrderField } from '../assignments/AssignmentOrder';\nimport { default as AssignmentFilter, type IAssignmentFilterOptions } from '../assignments/AssignmentFilter';\nimport { default as StudentAssignmentOrder, type StudentAssignmentOrderField } from '../assignments/StudentAssignmentOrder';\nimport { default as StudentAssignmentFileOrder, type StudentAssignmentFileOrderField } from '../assignments/StudentAssignmentFileOrder';\nimport { default as StudentAssignmentFileFilter, type StudentAssignmentFileFilterOptions } from '../assignments/StudentAssignmentFileFilter';\nimport { default as ClassroomMemberOrder, type ClassroomMemberOrderField } from '../classroom-member/ClassroomMemberOrder';\nimport { default as ClassroomMemberFilter, type IClassroomMemberFilterOptions } from './ClassroomMemberFilter';\nimport StudentAssignmentFilter from '../assignments/StudentAssignmentFilter';\nimport ImplicitStudentAssignmentFilter from '../assignments/ImplicitStudentAssignmentFilter';\nimport { trace, traceableAs } from '../core/decorators/trace';\nimport { Permission } from '../interface/AssetModel';\nimport type Board from '../boards/Board';\nimport type BoardContext from '../boards/BoardContext';\nimport type { BoardSource } from '../boards/BoardSource';\nimport { BoardType } from '../interface/BoardModel';\nexport type IBatchOperationClassroomResult = IBatchOperationResult<Classroom>;\nimport { default as BoardOrder } from '../boards/BoardOrder';\n\ninterface UpdateAssignmentMaterialsResult {\n    shouldUpdateTemplates: boolean;\n    shouldUpdateReferences: boolean;\n    updatedTemplateIds: string[];\n    updatedReferenceIds: string[];\n    assetsToDiscard: string[];\n}\n\ntype GetRealClassroomGivenClassroomIdOrCodeResult = {\n    classroom: Classroom,\n    isVirtualClassroomJustMigrated?: boolean\n};\n\ntype GetRealClassroomGivenClassroomIdOrCodeOptions = {\n    classroomId?: string,\n    classroomCode?: string,\n};\n\n@traceableAs('ClassroomContext')\nexport default class ClassroomContext implements ISAMObject, SAM.ClassroomContext {\n    private _assignmentInterface = new AssignmentsInterface(this._core);\n    private _classroomsInterface = new ClassroomsInterface(this._core);\n    private _studentAssignmentsInterface = new StudentAssignmentsInterface(this._core);\n    private _boardContext!: BoardContext;\n\n    constructor(readonly _core: ISAMCorePrivate, private _assetPool: ItemPool<Assignment | AdobeAsset | StudentAssignment | StudentAssignmentFile>) {\n        this._core.getBoardContext().then((boardContext) => {\n            this._boardContext = boardContext;\n        });\n    }\n\n    readonly _studentAssignmentFileUpdater = StudentAssignmentFileUpdater;\n    readonly _studentAssignmentUpdater = StudentAssignmentUpdater;\n    readonly _assignmentUpdater = AssignmentUpdater;\n\n    /**\n     * Ensures that the board context has been fetched before using it\n     * @throws {Error} if the board context is not initialized\n     */\n    private _ensureBoardContext(): BoardContext {\n        if (!this._boardContext) {\n            throw new Error('Board context not initialized');\n        }\n        return this._boardContext;\n    }\n\n    /**\n     * @package -- for SAM.js internal use only\n     */\n    public _classroomPool = new ItemPool<Classroom>(this._core, 'classroom');\n\n    /**\n     * @package -- for SAM.js internal use only\n     */\n    public _classroomMemberPool = new ItemPool<ClassroomMember>(this._core, 'classroomMember');\n\n    /**\n     * @description Gets a classroom with the given class ID.\n     *\n     * @param id The classroom ID (ex: '123@AdobeOrg')\n     *\n     * @example <caption>Fetch a classroom by ID</caption>\n     * const classroom: Classroom = await classroomContext.getClassroomById('123@AdobeOrg');\n     */\n    @keepAlive\n    @synchronized\n    async getClassroomById(@key id: string): Promise<Classroom> {\n        validateString(id, 'id');\n\n        const classroomInterface = this._classroomsInterface;\n        const pool = this._classroomPool;\n        let classroom = pool.getLocalItemById(id);\n        if (!classroom) {\n            // Note that we don't have a local classroom, so we don't have to worry about eventual consistency on this item.\n            const response = await classroomInterface.getClassroom(id);\n            const session = pool.createUpdateSession();\n            classroom = ClassroomUpdater.updateRemoteItem(session, this._processRemoteClassroomItem(id, response));\n            session.commit();\n        }\n        return classroom;\n    }\n\n    /**\n     * @description Gets a classroom with the given class code. Typically, using getClassroomById is preferred.\n     *\n     * @param classCode The classroom code (ex: 'ABCDEF')\n     *\n     * @example <caption>Fetch a classroom by ID</caption>\n     * const classroom: Classroom = await classroomContext.getClassroomByCode('ABCDEF');\n     */\n    @keepAlive\n    @synchronized\n    async getClassroomByCode(@key classCode: string): Promise<Classroom> {\n        validateString(classCode, 'classCode');\n\n        // Check if the classroom is cached already\n        // Since getLocalItemById only supports the primary ID,\n        // not the code, iterate through the cached list\n        const classroom = this._classroomPool.toArray().find((classroom) => classroom.code === classCode);\n        if (classroom) {\n            return classroom;\n        }\n        // The interface passes to ID or CODE through the same endpoint and param.\n        return this.getClassroomById(classCode);\n    }\n\n    /**\n     * @description Gets the list of Classrooms that this user has access to\n     *\n     * @example <caption>Get all Classrooms as an array</caption>\n     * const classroomsList: IItemList<ClassroomConfig> = classroomContext.getClassrooms().getList(ClassroomOrder.default);\n     * await waitForListLoad(classroomsList);\n     * const classroomItems: Classroom[] = classroomsList.items;\n     */\n    @memoize\n    getClassrooms(): ClassroomSource {\n        return new ItemSource(this._classroomPool, [ new ClassroomListListLoader(this._classroomPool, this._classroomsInterface) ]);\n    }\n\n    /**\n     * Gets a classroom by its asset ID.\n     *\n     * @param assetId The asset ID of the classroom\n     *\n     * @example <caption>Get a classroom by its asset ID</caption>\n     * const classroom = await classroomContext.getClassroomByAssetId('urn:aaid:sc:VA6C2:123456');\n     */\n    @keepAlive\n    @synchronized\n    async getClassroomByAssetId(@key assetId: string): Promise<Classroom | undefined> {\n        const classroomSource = this.getClassrooms();\n        const classroomList = classroomSource.getList(ClassroomOrder.default, undefined, { loadAllPages: true });\n        await waitForListLoad(classroomList);\n        const classroom = classroomList.items.find((classroom) => classroom.assetId === assetId);\n        return classroom;\n    }\n\n    /**\n     * Gets a classroom by a board ID.\n     *\n     * @param boardId The board ID to get the classroom for\n     *\n     * @example <caption>Get a classroom by its board ID</caption>\n     * const classroom = await classroomContext.getClassroomByBoardId('urn:aaid:sc:VA6C2:e886d4ef-20e5-4567-a09a-7d3a5bde838f');\n     */\n    @keepAlive\n    @synchronized\n    async getClassroomByBoardId(@key boardId: string): Promise<Classroom | undefined> {\n        const board = await this._ensureBoardContext()._getBoard(boardId);\n        return this.getClassroomByAssetId(board._idOfBaseAsset!);\n    }\n\n    /**\n     * Gets a list of Classroom Members. Use a ClassroomMemberFilter on the resulting getList call to filter down to a specific classroom / role.\n     *\n     * @example <caption>Get all Members of all Classrooms</caption>\n     * const memberList: IItemList<ClassroomMemberConfig> = classroomContext.getClassroomMembers().getList(ClassroomMemberOrder.default);\n     * await waitForListLoad(memberList);\n     * const members: ClassroomMember[] = memberList.items;\n     *\n     * @example <caption>Get all Students in a single Classroom</caption>\n     * const memberList: IItemList<ClassroomMemberConfig> = classroomContext.getClassroomMembers().getList(ClassroomMemberOrder.default, new ClassroomMemberFilter({ role: ClassroomMemberRole.STUDENT, classroomId: '123@AdobeOrg' }));\n     * await waitForListLoad(memberList);\n     * const members: ClassroomMember[] = memberList.items;\n     */\n    @memoize\n    getClassroomMembers(): ClassroomMemberSource {\n        return new ItemSource(this._classroomMemberPool, [ new ClassroomMemberListLoader(this._classroomMemberPool, this._classroomsInterface) ]);\n    }\n\n    /**\n     * Get a list of Assignments\n     *\n     * @example <caption>Get all Assignments</caption>\n     * const assignmentsList = classroomContext.getAssignments().getList(AssignmentOrder.default);\n     * await waitForListLoad(assignmentsList);\n     * const assignments: Assignment[] = assignmentsList.items;\n     *\n     * @example <caption>Get all Assignments from a single Classrooms</caption>\n     * const assignmentsList = classroomContext.getAssignments().getList(AssignmentOrder.default, new AssignmentFilter({ classroomId: '123@AdobeOrg' }));\n     * await waitForListLoad(assignmentsList);\n     * const assignments: Assignment[] = assignmentsList.items;\n     *\n     * @example <caption>Get all Assignments from a single Classrooms that the current user created</caption>\n     * const assignmentsList = classroomContext.getAssignments().getList(AssignmentOrder.default, new AssignmentFilter({\n     *  classroomId: '123@AdobeOrg',\n     *  submissions: AssignmentSubmissionOwnershipEnums.SELF\n     * }));\n     * await waitForListLoad(assignmentsList);\n     * const assignments: Assignment[] = assignmentsList.items;\n     */\n    @memoize\n    getAssignments(): AssignmentSource {\n        const loader = new AssignmentsListLoader(\n            this._assignmentInterface,\n            this._core\n        );\n        return new ItemSource(this._assetPool as ItemPool<Assignment>, [ loader ]);\n    }\n\n    /**\n     * Gets the ItemSource for all StudentAssignments in the pool\n     * @package -- for SAM.js internal use only\n     */\n    _getStudentAssignmentsSource(implicitFilter: ImplicitStudentAssignmentFilter): StudentAssignmentSource {\n        const loader = new StudentAssignmentListLoader(\n            this._studentAssignmentsInterface,\n            this._core,\n        );\n        return new ItemSource(this._assetPool as ItemPool<StudentAssignment>, [ loader ], implicitFilter);\n    }\n\n    /**\n     * @description Gets all of the Student Assignments. Can be used to fetch the StudentAssignments for a single Assignment through ID or Code.\n     *\n     * @param [options] Contains the assignmentId or assignmentCode to filter the StudentAssignments by.\n     *\n     * @example <caption>Fetch all Student Assignments for a given Assignment with an ID</caption>\n     * const studentAssignmentsList = classroomContext.getStudentAssignments().getList(StudentAssignmentOrder.default, new StudentAssignmentFilter({ assignmentId: 'urn:aaid:sc:VA6C2:123456' }));\n     * await waitForListLoad(studentAssignmentsList);\n     * const studentAssignments: StudentAssignment[] = studentAssignmentsList.items;\n     *\n     * @example <caption>Fetch all Student Assignments for a given Assignment with a Code</caption>\n     * const classroomContext = samCore.classroomContext;\n     * const assignmentsSource = classroomContext.getStudentAssignments();\n     * const studentAssignments = await assignmentsSource.getList(StudentAssignmentOrder.default, new StudentAssignmentFilter({ assignmentCode: 'WXYZ' }));\n     */\n    @keepAlive\n    @weakCache\n    getStudentAssignments(@key options: RequiredStudentAssignmentFilterOptions): StudentAssignmentSource {\n        return this._getStudentAssignmentsSource(new ImplicitStudentAssignmentFilter(options));\n    }\n\n    private cleanAssignmentName(name: string): string {\n        return name.trimEnd();\n    }\n\n    /**\n     * Creates a new Classroom\n     * @param data creation data (e.g. name, grade etc)\n     * @throws {SAMError} If the data is invalid or the classroom cannot be created\n     *\n     * @example <caption>Create a new Classroom</caption>\n     * const classroom: Classroom = await classroomContext.createClassroom({\n     *  name: 'My Classroom',\n     *  grades: ['K', '1'],\n     *  subject: 'math',\n     * });\n     */\n    @trace\n    @keepAlive\n    @synchronized\n    async createClassroom(data: IClassroomCreateData): Promise<Classroom> {\n        const classroomValidationErrors = validateClassroomData(data);\n        if (classroomValidationErrors.length > 0) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, JSON.stringify(classroomValidationErrors));\n        }\n\n        let response;\n        // Class is being created from a virtual classroom\n        if (data.id) {\n            response = await this._classroomsInterface.createClassroomFromVirtual(data.id);\n            // Preserve the old original identifier for the class to re-index the existing item under its preferred id\n            response.virtualId = data.id;\n        } else {\n            const className = data.name?.trim() || '';\n\n            if (!validatePlatformRepoName(className)) {\n                // Validate the name here to avoid resolving the asset if the name is invalid.\n                throw SAMError.create(\n                    SAMErrorCode.BAD_REQUEST,\n                    'Invalid class name provided for the creation operation.'\n                );\n            }\n\n            response = await this._classroomsInterface.createClassroom({\n                ...data,\n                name: className\n            });\n        }\n\n        // Cache new classroom\n        const session = this._classroomPool.createMutationSession<Classroom>();\n        const classroom = ClassroomUpdater.updateRemoteItem(session, response);\n        session.commit();\n        return classroom;\n    }\n\n    /**\n     * Creates a new Assignment\n     * @param data creation data (e.g. title, instructions, etc)\n     * @throws {SAMError} If the data is invalid or the assignment cannot be created\n     *\n     * @example <caption>Create a new Assignment</caption>\n     * const assignment: Assignment = await classroomContext.createAssignment({\n     *  name: 'My Assignment',\n     *  classroomId: '123@AdobeOrg',\n     *  instructions: 'Do this and that',\n     *  tasks: ['poster']\n     * });\n     */\n    @trace\n    @keepAlive\n    @synchronized\n    async createAssignment(data: IAssignmentCreateData): Promise<Assignment> {\n        const assignmentValidateErrors = validateAssignmentData(data);\n        if (assignmentValidateErrors.length > 0) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, JSON.stringify(assignmentValidateErrors));\n        }\n\n        const trimmedName = this.cleanAssignmentName(data.name);\n\n        if (!validatePlatformRepoName(trimmedName)) {\n            // Validate the name here to avoid resolving the asset if the name is invalid.\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Invalid name provided for the creation operation.'\n            );\n        }\n\n        // TODO[ACPCEDU-4151]: refactor this to use the new this._getRealClassroomGivenClassroomIdOrCode() method\n        let classroomId = data.classroomId;\n        // See if the class ID given maps to a virtual class that has already been migrated recently\n        // if not fetch the classroom and see if it is virtual which requires migrating the class to\n        // a real class before an assignment can be created for it\n        const recentMigratedClassroom = this._classroomPool.toArray().find((classroom) => classroom._virtualId === data.classroomId);\n        if (recentMigratedClassroom) {\n            classroomId = recentMigratedClassroom.id;\n        } else {\n            // Class that maps to given ID has not been migrated recently so fetch and see if it maps to a virtual class\n            const classroom = await this.getClassroomById(data.classroomId);\n            if (classroom.isVirtual) {\n                const migratedClassroom = await this.createClassroom({ id: classroom.id });\n                classroomId = migratedClassroom.id;\n\n                // Check if the virtual class is still being referenced if so throw an error\n                // The newly created real class is what is expected to be returned\n                if (classroomId === data.classroomId) {\n                    throw SAMError.create(\n                        SAMErrorCode.BAD_REQUEST,\n                        'Cannot create an assignment with a virtual classroom.'\n                    );\n                }\n            }\n        }\n\n        // We will not create the assignment with the incoming template IDs\n        // Instead updateAssignment() will clone them and save new asset IDs to this assignment\n        const { templateIds, references, ...createData } = data;\n        createData.name = trimmedName;\n\n        const incomingTemplateIds = templateIds ?? [];\n        const incomingReferences = references ?? [];\n        const hasMaterials = incomingTemplateIds.length + incomingReferences.length > 0;\n\n        const status = createData.status || AssignmentStatus.DRAFT;\n\n        let assignment = this._findAssignment(classroomId, trimmedName);\n        const alreadyCreated = !!assignment;\n\n        if (!assignment) {\n            // If the assignment has materials, it should be created as a draft\n            // and only be assigned when the materials are copied\n            if (!hasProperty(createData, 'status') || hasMaterials) {\n                createData.status = AssignmentStatus.DRAFT;\n            }\n\n            const response = await this._assignmentInterface.createAssignment({ ...createData, classroomId });\n\n            const session = this._assetPool.createMutationSession<Assignment>();\n            assignment = AssignmentUpdater.updateRemoteItem(session, response);\n            // Commit the session to ensure the assignment is available in the pool even if the updateAssignment() call fails.\n            session.commit();\n        }\n\n        const materialsUpdateData: Pick<IAssignmentUpdateData, 'references' | 'templateIds'> = {};\n        if (incomingTemplateIds.length > 0) {\n            materialsUpdateData.templateIds = incomingTemplateIds;\n        }\n        if (incomingReferences.length > 0) {\n            materialsUpdateData.references = incomingReferences;\n        }\n\n        // Only update with materials or if the assignment had already been created. Other data is able to\n        // be assigned on creation but it may now be updated.\n        if (hasMaterials || alreadyCreated) {\n            try {\n                await this.updateAssignment(assignment.id, {\n                    ...materialsUpdateData,\n                    ...(alreadyCreated ? { ...createData, name: undefined } : {}),\n                    status\n                });\n            } catch (error) {\n                throw SAMError.wrapErrorIfNeeded(SAMErrorCode.INTERNAL_ERROR, 'Error updating assignment materials', error);\n            }\n        }\n\n        return assignment!;\n    }\n\n    /**\n     * Finds an assignment in the asset pool\n     * @param classroomId The classroom ID of the assignment\n     * @param assignmentName The name of the assignment\n     * @returns The assignment if found, otherwise undefined\n     * @package Only for use in SAM.js\n     */\n    private _findAssignment(classroomId: string, assignmentName: string): Assignment | undefined {\n        return this._assetPool.toArray().find((item) =>\n            item instanceof Assignment\n                && item.classroomId === classroomId\n                && item.name === assignmentName) as Assignment;\n    }\n\n    /**\n     * Gets a Assignment with the given ID.\n     *\n     * @note in the near future, we can call to check the access to this assignment given by an ID.\n     *\n     * @param id ID of the Assignment\n     * @param data The data necessary to fetch correct assignments\n     *\n     * @example <caption>Fetch an Assignment by ID, fetching only the current user's StudentAssignments</caption>\n     * const assignment: Assignment = await classroomContext.getAssignmentByID('urn:aaid:sc:VA6C2:123456', AssignmentSubmissionOwnershipEnums.SELF);\n     *\n     * @example <caption>Fetch an Assignment by ID, fetching all child StudentAssignments for all users. The classroomID must be passed in for this case. This will only work when called from a teacher's session.</caption>\n     * const assignment: Assignment = await classroomContext.getAssignmentByID('urn:aaid:sc:VA6C2:123456', AssignmentSubmissionOwnershipEnums.ANY, '123@AdobeOrg');\n     */\n    @keepAlive\n    @synchronized\n    async getAssignmentByID(@key id: string, submissions?: AssignmentSubmissionOwnershipEnums, classroomId?: string): Promise<Assignment> {\n        validateString(id, 'id');\n        if (classroomId) {\n            validateString(classroomId, 'classroomId');\n        }\n\n        let assignment = this._assetPool.getLocalItemById<Assignment>(id);\n        if (assignment) {\n            return assignment;\n        }\n        const submissionsType = await this.validateStudentAssignmentsFilter(submissions, classroomId);\n        const assignmentMetadata = await this._assignmentInterface.getAssignment(\n            id,\n            submissionsType\n        );\n        const session = this._assetPool.createMutationSession<Assignment>();\n        assignment = AssignmentUpdater.updateRemoteItem(\n            session,\n            assignmentMetadata\n        );\n        session.commit();\n        return assignment;\n    }\n\n    /**\n     * This function gets an assignment by its code.\n     *\n     * @param code Code used to fetch assignment\n     *\n     * @example <caption>Fetch an Assignment by ID, fetching only the current user's StudentAssignments</caption>\n     * const assignment: Assignment = await classroomContext.getAssignmentByCode('ABCDEF', AssignmentSubmissionOwnershipEnums.SELF);\n     *\n     * @example <caption>Fetch an Assignment by ID, fetching all child StudentAssignments for all users. The classroomID must be passed in for this case. This will only work when called from a teacher's session.</caption>\n     * const assignment: Assignment = await classroomContext.getAssignmentByCode('ABCDEF', AssignmentSubmissionOwnershipEnums.ANY, '123@AdobeOrg');\n     */\n    @keepAlive\n    @synchronized\n    async getAssignmentByCode(@key code: string, submissions?: AssignmentSubmissionOwnershipEnums, classroomId?: string): Promise<Assignment> {\n        validateString(code, 'code');\n        if (classroomId) {\n            validateString(classroomId, 'classroomId');\n        }\n\n        // Check if the assignment is cached already\n        // Since getLocalItemById only supports the primary ID,\n        // not the code, iterate through the cached list\n        let assignment = this._assetPool.toArray<Assignment>().find((assignment) => assignment.code === code);\n        if (assignment) {\n            return assignment;\n        }\n        const submissionsType = await this.validateStudentAssignmentsFilter(submissions, classroomId);\n        const assignmentMetadata = await this._assignmentInterface.getAssignmentByCode(code, submissionsType);\n        const session = this._assetPool.createMutationSession<Assignment>();\n        assignment = AssignmentUpdater.updateRemoteItem(\n            session,\n            assignmentMetadata\n        );\n        session.commit();\n        return assignment;\n    }\n\n    /**\n     * @description Gets a student assignment with the given student assignment ID.\n     * This function is not expected to call with the ID of not-started student assignment since it has no real asset ID.\n     * If loadDocuments is enabled, the student assignment files will only be fetched IF the student assignment is NOT cached.\n     * Otherwise the files will be lazy loaded when the client calls studentAssignment.files.getList(...)\n     *\n     * @param id of the student assignment that is being fetched\n     *\n     * @example <caption>Get a StudentAssignment by ID</caption>\n     * const studentAssignment: StudentAssignment = await classroomContext.getStudentAssignmentById('urn:aaid:sc:VA6C2:123456:789');\n     *\n     * @example <caption>Get a StudentAssignment with the student assignment files loaded</caption>\n     * const studentAssignment: StudentAssignment = await classroomContext.getStudentAssignmentById('urn:aaid:sc:VA6C2:123456:789', {loadDocuments: true});\n     */\n    @keepAlive\n    @synchronized\n    public async getStudentAssignmentById(@key studentAssignmentId: string, options?: GetStudentAssignmentOptions): Promise<StudentAssignment> {\n        const cachedStudentAssignment = this._assetPool.getLocalItemById<StudentAssignment>(studentAssignmentId);\n        if (cachedStudentAssignment) {\n            return cachedStudentAssignment;\n        }\n        const studentAssignmentMetadata = await this._studentAssignmentsInterface.getStudentAssignment(studentAssignmentId, options);\n        const session = this._assetPool.createMutationSession<StudentAssignment>();\n        const studentAssignment = StudentAssignmentUpdater.updateRemoteItem(\n            session,\n            studentAssignmentMetadata\n        );\n        studentAssignment._hasLoadedChildren = options?.loadDocuments ?? false;\n        session.commit();\n        return studentAssignment;\n    }\n\n    /**\n     * Discards the given assignment\n     * This assignment will be eligible to be restored or permanentlyDeleted from this state\n     * @param assignment Assignment to be discarded\n     * @package Only for use in SAM.js\n     */\n    @synchronized\n    async _discardAssignment(assignment: Assignment) {\n        await assignment.discard();\n    }\n\n    /**\n     * Restores the given assignment\n     * @param assignment Assignment to be restored\n     * @package Only for use in SAM.js\n     */\n    @synchronized\n    async _restoreAssignment(assignment: Assignment)  {\n        await assignment.restore();\n    }\n\n    /**\n     * Update the computedStudentAssignmentId of the remote student assignment files\n     * @param remoteStudentAssignmentFiles The remote student assignment files to update the computedStudentAssignmentId with\n     * @param studentAssignmentId The student assignment ID to update the remote student assignment files with\n     * @package Only for use in SAM.js\n     */\n    _computeRemoteStudentAssignmentFiles({\n        assignmentId,\n        classroomId,\n        remoteStudentAssignmentFiles,\n        studentAssignmentId\n    }: {\n        assignmentId: string,\n        classroomId?: string,\n        remoteStudentAssignmentFiles: IRemoteStudentAssignmentFile[],\n        studentAssignmentId: string\n    }): IRemoteStudentAssignmentFileMetadataWithComputedValues[] {\n        const remoteStudentAssignmentFilesWithComputedValues = [ ...remoteStudentAssignmentFiles ] as IRemoteStudentAssignmentFileMetadataWithComputedValues[];\n        // attach the parent ID (Student assignment ID) to each file\n        return remoteStudentAssignmentFilesWithComputedValues.map((remoteStudentAssignmentFileWithComputedValues) => {\n            remoteStudentAssignmentFileWithComputedValues.computedStudentAssignmentId = studentAssignmentId;\n            remoteStudentAssignmentFileWithComputedValues.computedAssignmentId = assignmentId;\n            if (classroomId) {\n                if (!classroomId.startsWith('urn')) {\n                    // If this is hit, it is likely that the classroom primary ID,\n                    // its org ID, is being passed in which is NOT the asset ID\n                    throw SAMError.create(SAMErrorCode.BAD_REQUEST, `The classroomId provided, ${classroomId}, is NOT an asset ID`);\n                }\n                remoteStudentAssignmentFileWithComputedValues.computedClassroomAssetId = classroomId;\n            }\n            return remoteStudentAssignmentFileWithComputedValues;\n        });\n    }\n\n    /**\n     * Update the student assignment files cache given the remote student assignment files\n     * @param remoteStudentAssignmentFiles The remote student assignment files to update the cache with\n     * @param studentAssignment The student assignment to update the cache with\n     * @package Only for use in SAM.js\n     */\n    _updateStudentAssignmentFilesCache({\n        assignmentId,\n        classroomId,\n        remoteStudentAssignmentFiles,\n        session,\n        studentAssignmentId\n    }: {\n        assignmentId: string,\n        classroomId?: string,\n        remoteStudentAssignmentFiles: IRemoteStudentAssignmentFile[],\n        session: IUpdateSession<StudentAssignmentFile>,\n        studentAssignmentId: string}): StudentAssignmentFile[] {\n        const remoteStudentAssignmentFilesWithComputedValues = this._computeRemoteStudentAssignmentFiles({ remoteStudentAssignmentFiles, assignmentId, classroomId, studentAssignmentId });\n        const files = StudentAssignmentFileUpdater.updateRemoteItems(\n            session,\n            remoteStudentAssignmentFilesWithComputedValues\n        );\n        session.commit();\n        return files;\n    }\n\n    /**\n     * Returns a StudentAssignment.\n     * @param data The data necessary to return the assignment.\n     * @package Only for use in SAM.js\n     */\n    @synchronized\n    async _returnAssignment(data: IStudentAssignmentReturnData): Promise<StudentAssignment> {\n        const remoteStudentAssignment = await this._studentAssignmentsInterface.return(data);\n        // no need to provide assignmentID since the student work directory ID / repo ID is already provided\n        const session = this._assetPool.createMutationSession<StudentAssignment>();\n        const studentAssignment = StudentAssignmentUpdater.updateRemoteItem(\n            session,\n            remoteStudentAssignment\n        );\n        session.commit();\n        return studentAssignment;\n    }\n\n    /**\n     * Starts a StudentAssignment.\n     * @param data The data necessary to start the assignment.\n     * @package Only for use in SAM.js\n     */\n    @synchronized\n    async _startAssignment(data: IStudentAssignmentStartData): Promise<StudentAssignment> {\n        const remoteStudentAssignment = await this._studentAssignmentsInterface.start(data);\n        const session = this._assetPool.createMutationSession<StudentAssignment>();\n        const studentAssignment = StudentAssignmentUpdater.updateRemoteItem(\n            session,\n            remoteStudentAssignment\n        );\n        session.commit();\n        return studentAssignment;\n    }\n\n    /**\n     * Submits a StudentAssignment.\n     * @param data The data necessary to submit the assignment.\n     * @throws {SAMError} if the studentAssignmentId or assignmentId is not provided, or if the current user does not have write permission to the submission file when the file needs to be moved.\n     * @deprecated Use `StudentAssignment.submit` instead\n     * This property will be removed on or after 2025-7-1 in ACPCEDU-3393\n     *\n     * @example <caption>Submit an assignment by StudentAssignment ID</caption>\n     * const studentAssignment: StudentAssignment = await classroomContext.submitAssignment({ studentAssignmentId: 'urn:aaid:sc:VA6C2:123456:789', submissionId: 'urn:aaid:sc:VA6C2:123456:789:submission' });\n     */\n    @trace\n    @synchronized\n    public async submitAssignment(data: IStudentAssignmentSubmitClassroomContextData): Promise<IRemoteStudentAssignment> {\n        const { assignmentId, status, studentAssignmentId, submissionId } = data;\n\n        const validAssignmentId = validateString(assignmentId, 'assignmentId', false);\n        // studentAssignmentId may be undefined (when NOT_STARTED) but otherwise must be valid.\n        const validStudentAssignmentId\n            = (validAssignmentId && studentAssignmentId === undefined)\n            || validateString(studentAssignmentId, 'studentAssignmentId', false);\n\n        if (!validAssignmentId && !validStudentAssignmentId) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Either studentAssignmentId or assignmentId is required to submit an assignment');\n        }\n\n        if (!validAssignmentId && status === StudentAssignmentStatus.NOT_STARTED) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'assignmentId is required when the assignment has not been started');\n        }\n\n        // Check the provided studentAssignmentId rather than the validStudentAssignmentId because while\n        // validStudentAssignmentId can be true even when missing due to assignemtId being provided, it will\n        // be an error condition if status is also not provided.\n        if ((!studentAssignmentId && status && status !== StudentAssignmentStatus.NOT_STARTED)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'studentAssignmentId is required once the assignment has been started');\n        }\n\n        let studentAssignment: StudentAssignment;\n\n        if (!status || status !== StudentAssignmentStatus.NOT_STARTED) {\n            if (!studentAssignmentId) {\n                // [ACPCEDU-4043]: Example of a place to add a try/catch block to handle errors when fetching the assignment.\n                const assignment = await this.getAssignmentByID(assignmentId!, AssignmentSubmissionOwnershipEnums.SELF);\n\n                // It is ok to assume the first studentAssignment is available since the student is the one\n                // submitting the assignment and SELF ownership was requested.\n                studentAssignment = assignment.studentAssignments[0];\n\n                // The original implementation was unable to start an assignment. In order to be consistent with the original\n                // if not given a studentAssignmentId and it is determined that the assignment is not started, throw an error.\n                // In the original the error would have been BAD_REQUEST: \"Missing link for relationship type: <url>/rel/submit\"\n                // but the message is now more descriptive.\n                if (studentAssignment.status === StudentAssignmentStatus.NOT_STARTED) {\n                    throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'studentAssignmentId is required once the assignment has been started');\n                }\n            } else {\n                studentAssignment = await this.getStudentAssignmentById(studentAssignmentId!);\n            }\n        } else {\n            studentAssignment = await this._startAssignment({\n                assignmentId: assignmentId!,\n                links: data.links,\n            });\n        }\n\n        const submittedAsset: AdobeAsset = await this._core.hostAssetContext.getAssetWithCloudID(submissionId);\n\n        // If the submittedAsset is not already in the studentAssignment directory, it is a floating file and needs moved.\n        // [ACPCEDU-4042]: Performance optimization to skip fetching children if we know the assignment was just started.\n        if (await this._isFloating(studentAssignment, submittedAsset)) {\n            // Intention is to move the file, check write permission.\n            // Three cases to throw errors here\n            // 1. Student does not have move and / or write permission on the submitted asset, so it will fail the subsequent move call if we don't throw an error opportunistically\n            // 2. Catches a potential error when getting the parent asset, if the user does not have permission to get that asset.\n            // 3. Source parent asset does not have write permission\n\n            if (!submittedAsset.hasPermission(Permission.Move) || !submittedAsset.hasPermission(Permission.Write)) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Current user does not have permission to move and / or submit this asset: ${submittedAsset.id}`);\n            }\n\n            let parentAsset, parentRepoPath;\n            try {\n                parentRepoPath = submittedAsset.repoPath.substring(0, submittedAsset.repoPath.lastIndexOf('/'));\n                // If this call results in an error, we want to throw a more specific error message\n                parentAsset = await this._core.hostAssetContext.getAssetWithRepoPath(parentRepoPath, submittedAsset.repositoryID);\n            } catch (error) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Unable to fetch the parent asset of the file being submitted using the path ${parentRepoPath}: ${error}`);\n            }\n\n            if (!parentAsset.hasPermission(Permission.Write)) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Current user is trying to submit an assignment from a folder that they do not have write permission on -- directory ID: ${parentAsset.id}`);\n            }\n\n            // Match date formatting when submitting an assignment\n            const formattedDate = this._getFormattedCreatedDateHelper({ includeFormattedDate: false, date: new Date() });\n            const assignment = await this.getAssignmentByID(assignmentId!);\n            const updatedName = `${studentAssignment.student.displayName} ${assignment.name} ${formattedDate}.${submittedAsset.extension}`;\n\n            // Naming collision will not be a problem, move will rename the file to a unique name if needed\n            await submittedAsset.move(studentAssignment, updatedName);\n        }\n\n        const { studentDirectoryId } = studentAssignment;\n        const remoteStudentAssignment = await this._studentAssignmentsInterface.submit({\n            links: studentAssignment.links,\n            studentAssignmentId: studentDirectoryId!,\n            submissionId,\n        });\n\n        const session = this._assetPool.createMutationSession<StudentAssignment>();\n        StudentAssignmentUpdater.updateRemoteItem(\n            session,\n            remoteStudentAssignment\n        );\n        session.commit();\n\n        return remoteStudentAssignment;\n    }\n\n    /**\n     * Function to determine if a submitted file is floating; that is a file that is not currently within the student's assignment directory.\n     * @param studentAssignment The StudentAssignment object being submitted.\n     * @param submissionId The ID of the asset being submitted for the assignment.\n     */\n    private async _isFloating(studentAssignment: StudentAssignment, submittedAsset: AdobeAsset): Promise<boolean> {\n        // If the submitted asset's parent matches the student assignment, the file is not floating.\n        if (submittedAsset.isChildOfStudentAssignment) {\n            if (submittedAsset.parentStudentAssignmentId !== studentAssignment.id) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Submitted asset is already in a different assignment directory and has been submitted to another assignment -- directory ID: ${submittedAsset.parentStudentAssignmentId}, attempted to turn in to: ${studentAssignment.id}`);\n            }\n            return false;\n        }\n\n        // Fallback to looking in the student assignment's directory for the asset that was submitted; when it is not in the list\n        // then the file is floating.\n        try {\n            const list = studentAssignment.children?.getList(AdobeAssetOrder.default);\n            if (list) {\n                await waitForListLoad(list);\n                return !list.items.some(asset => asset.id === submittedAsset.id);\n            }\n        } catch (error) {\n            // We would not expect an error from the list load call here so this is a temporary precaution to help with debugging.\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Error waiting for list load in floating file check: ${error}`);\n        }\n\n        return true; // This is a floating file because parent ID doesn't match and there are no files in the assignment directory.\n    }\n\n    /**\n     * Function to update a StudentAssignmentFile\n     * @throws {SAMError} if the deprecated interface is used alongside preferred interface\n     *\n     * @param studentAssignmentFile StudentAssignmentFile that will be updated. Either the object or the ID can be passed.\n     * @param data Data to update the file with. Note that sourceAsset/sourceAssets OR sourceTasks are allowed, but not both in one update call.\n     *\n     * @example <caption>Link asset to an existing StudentAssignmentFile</caption>\n     * const updatedStudentAssignmentFile: StudentAssignmentFile = await classroomContext.updateStudentAssignmentFile(studentAssignmentFile, { sourceAsset: {'repo:assetId': 'urn:mock-id'} });\n     *\n     * @example <caption>Add new tasks to an existing StudentAssignmentFile by ID</caption>\n     * const updatedStudentAssignmentFile: StudentAssignmentFile = await classroomContext.updateStudentAssignmentFile('saf-ID', { sourceTasks: ['poster'] });\n     */\n    async updateStudentAssignmentFile(studentAssignmentFile: StudentAssignmentFile | string, data: IStudentAssignmentFileRemotePatchData): Promise<StudentAssignmentFile | AdobeAsset> {\n        // Ensure clients are not using a mix of the deprecated interface (as of ACPCEDU-2214) and the preferred interface\n        // Remove support of deprecated interface in this function and relevant unit tests once all clients have migrated to the preferred interface\n        const isUsingPreferredInterface = data.sourceAsset || data.sourceTasks || data.sourceTutorials;\n        const isUsingDeprecatedInterface = data.sourceAssets || data['assignment:sourceAssets'] || data['assignment:sourceTasks'] || data['assignment:sourceTutorials'];\n        if (isUsingPreferredInterface && isUsingDeprecatedInterface) {\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, 'Do not use the deprecated interface.');\n        }\n\n        const sourceAssets = data.sourceAssets ?? data['assignment:sourceAssets'] ?? [];\n        const sourceTasks = data.sourceTasks ?? data['assignment:sourceTasks'] ?? [];\n        const sourceTutorials = data.sourceTutorials ?? data['assignment:sourceTutorials'] ?? [];\n\n        const patchData: jsonpatch.OpPatch[] = [\n            {\n                op: 'add',\n                path: '/assignment:sourceAssets',\n                value: sourceAssets\n            },\n            {\n                op: 'add',\n                path: '/assignment:sourceTasks',\n                value: sourceTasks\n            },\n            {\n                op: 'add',\n                path: '/assignment:sourceTutorials',\n                value: sourceTutorials\n            },\n        ];\n\n        if (data.sourceAsset) {\n            patchData.push({\n                op: 'add',\n                path: '/assignment:sourceAsset',\n                value: data.sourceAsset\n            });\n        }\n\n        const assetToPatch = typeof studentAssignmentFile === 'string'\n            ? await this._core.hostAssetContext.getAssetWithCloudID(studentAssignmentFile)\n            : studentAssignmentFile;\n\n        await assetToPatch.patchAppMetadata(patchData);\n\n        return assetToPatch;\n    }\n\n    /**\n     * Determine if the given name is valid for creating an assignment\n     * @throws {SAMError} if the name is invalid\n     *\n     * @example <caption>Validate an assignment name before creating an assignment for a Classroom</caption>\n     * try {\n     *  await classroomContext.validateAssignmentNameForCreate('My Assignment', '123@AdobeOrg');\n     * } catch (error) {}\n     */\n    async validateAssignmentNameForCreate(name: string, classroomId?: string): Promise<void> {\n        await this._validateAssignmentName(name, classroomId);\n    }\n\n    /**\n     * Verifies the usage of submissions (representing Student Assignments) and\n     * returns the Student Assignments submission type (either client specified or a default calculated based on membership role)\n     * @param data The data necessary to check validity of submissions\n     * @throws {SAMError} if the submissions type is invalid\n     * @package Only for use in SAM.js\n     */\n    async validateStudentAssignmentsFilter(submissions?: AssignmentSubmissionOwnershipEnums, classroomId?: string): Promise<AssignmentSubmissionOwnershipEnums | undefined> {\n        if (submissions && submissions === AssignmentSubmissionOwnershipEnums.ANY) {\n            if (!classroomId) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Cannot fetch specified assignment submission type without classroomId');\n            }\n            const membershipStatus = await this.getClassroomMembership(classroomId);\n            // If a submission type is specified as ANY and the membership role is 'Student'\n            // throw an error (a student cannot request any assignment submissions other than their own)\n            if (membershipStatus.role === ClassroomMemberRole.STUDENT) {\n                throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Student role cannot request assignment submission type \"ANY\"');\n            }\n        }\n        return submissions;\n    }\n\n    /**\n     * Determine if the given name is valid when updating an assignment\n     * @throws {SAMError} if the name is invalid\n     *\n     * @example <caption>Validate an assignment name before updating an assignment for a Classroom</caption>\n     * try {\n     *  await classroomContext.validateAssignmentNameForCreate('My Assignment', '123@AdobeOrg', 'assignment-id');\n     * } catch (error) {}\n\n     */\n    async validateAssignmentNameForUpdate(name: string, classroomId: string, assignmentId: string): Promise<void> {\n        await this._validateAssignmentName(name, classroomId, assignmentId);\n    }\n\n    /**\n     * Determine if the given name is valid\n     *  - Name cannot contain only whitespace\n     *  - Name must adhere to asset naming rules\n     *  - Name cannot end in a period\n     *  - The name must be unique within the classroom\n     * @throws {SAMError} if the name is invalid or not unique\n     */\n    @synchronized\n    private async _validateAssignmentName(name: string, classroomId?: string, assignmentId?: string): Promise<void> {\n        const trimmedName = name.trim();\n        // Name cannot have leading or trailing whitespace\n        if (trimmedName.length === 0) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The assignment name cannot be blank.');\n        }\n        // Name must adhere to asset naming rules\n        if (!validatePlatformRepoName(trimmedName)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The assignment name is an invalid platform repo name.');\n        }\n        // Name cannot end in a period\n        if (trimmedName.endsWith('.')) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'The assignment name cannot end with a period.');\n        }\n\n        // Name must be unique within the classroom\n        if (!classroomId) {\n            // Assignment does not map to a specific class yet so the name is valid for this case\n            return;\n        }\n        const classroom = await this.getClassroomById(classroomId);\n        if (classroom.isVirtual) {\n            // No assignments exist in a virtual classroom\n            return;\n        }\n        const assignments = this.getAssignments();\n        const assignmentList = assignments.getList(\n            await this.getAssignmentOrder(),\n            await this.getAssignmentFilter({ classroomId }),\n            {}\n        );\n        await waitForListLoad(assignmentList);\n        const locale = this._core._environment.getValue('LOCALE');\n        const matchingAssignment = assignmentList.items.find(assignment => assignment.name.toLocaleLowerCase(locale) === trimmedName.toLocaleLowerCase(locale));\n        if (matchingAssignment) {\n            if (!assignmentId || matchingAssignment.id !== assignmentId) {\n                throw SAMError.create(SAMErrorCode.CONFLICT, 'The assignment name must be unique within the classroom.');\n            }\n        }\n    }\n\n    /**\n     * Updates an Assignment's name\n     * @throws {SAMError} If the assignment could not be renamed\n     * @param assignmentId The assignment ID\n     * @param newName The new name\n     */\n    @synchronized\n    private async _renameAssignment(assignmentId: string, newName: string): Promise<void> {\n        const assignment = await this.getAssignmentByID(assignmentId);\n\n        try {\n            // repositoryID must be present for the rename operation to work\n            if (!assignment.repositoryID) {\n                await assignment._load();\n            }\n\n            return assignment.rename(newName);\n        } catch (error) {\n            if (error instanceof SAMError) {\n                throw error;\n            }\n\n            throw SAMError.create(SAMErrorCode.INTERNAL_ERROR, `Could not rename asset \"${assignmentId}\"`);\n        }\n    }\n\n    /**\n     * Updates an Assignment's data and copies any given asset to the materials folder of the assignment\n     * @param id The assignmentId of the Assignment to update\n     * @param data The data to update the Assignment with\n     *\n     * @example <caption>Update an Assignment with new materials</caption>\n     * await classroomContext.updateAssignment('assignmentID', { name: 'New Name', templateIds: ['templateID'], references: ['referenceID'] });\n     */\n    @synchronized\n    async updateAssignment(assignmentId: string, data: Partial<IAssignmentUpdateData>): Promise<void> {\n        validateString(assignmentId, 'assignmentId');\n\n        // Extract references and templateIds because they should not be updated\n        // unless _getUpdatedAssignmentMaterials determines that they should be\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const { references, status, templateIds, ...otherAssignmentData } = data;\n        const materialUpdates = await this._getUpdatedAssignmentMaterials(assignmentId, data);\n\n        const patchData: IAssignmentPatchData = otherAssignmentData;\n\n        if (materialUpdates.shouldUpdateTemplates) {\n            patchData.templateIds = materialUpdates.updatedTemplateIds;\n        }\n\n        if (materialUpdates.shouldUpdateReferences) {\n            patchData.referenceIds = materialUpdates.updatedReferenceIds;\n        }\n        const promises = [];\n        const shouldRename = Boolean(data.name);\n\n        // The update operation can happen in parallel with the rename operation\n        if (shouldRename) {\n            patchData.name = this.cleanAssignmentName(data.name!);\n            promises.push(this._renameAssignment(assignmentId, patchData.name));\n        }\n        if (status === AssignmentStatus.ASSIGNED) {\n            patchData.status = status;\n        }\n\n        promises.push(this._updateAssignmentMetadata(assignmentId, patchData));\n\n        await Promise.all(promises);\n\n        // Cleaning up after setting the new templates in case the copy OR update fails\n        // Note: If the discard operation fails on any asset then it will be orphaned forever\n        // TODO: Determine how we can do a proper cleanup of any orphaned assets, not just on update\n        this._discardAssets(materialUpdates.assetsToDiscard);\n    }\n\n    /**\n     * Updates an Assignment's data\n     * @param assignmentId The assignmentId of the Assignment to update\n     * @param data The data to update the Assignment with\n    */\n    @synchronized\n    private async _updateAssignmentMetadata(assignmentId: string, data: IAssignmentPatchData): Promise<void> {\n        if (Object.keys(data).length === 0) {\n            // Nothing to update\n            return;\n        }\n\n        const mappedData = Object.entries(assignmentRemoteFieldMapping).reduce((acc, [ localKey, remoteKey ]) => {\n            const hasKey = hasProperty(data, localKey);\n            if (hasKey) {\n                const value = data[localKey as keyof IAssignmentPatchData];\n                if (value instanceof Date) {\n                    // @ts-expect-error\n                    acc[remoteKey] = value.toISOString();\n                } else if (localKey === 'dueDate' && !value) {\n                    // @ts-expect-error\n                    acc[remoteKey] = ''; // Set to an empty string in the case we want to remove the dueDate\n                } else {\n                    // @ts-expect-error\n                    acc[remoteKey] = value;\n                }\n            }\n\n            return acc;\n        }, { 'repo:assetId': assignmentId } as IAssignmentRemotePatchData);\n\n        const ops = this._getUpdateAssignmentOps(mappedData);\n        if (ops.length !== 0) {\n            const response = await this._assignmentInterface.patchAssignment(assignmentId, ops);\n            const session = this._assetPool.createMutationSession<Assignment>();\n            AssignmentUpdater.updateRemoteItem(\n                session,\n                response\n            );\n\n            session.commit();\n        }\n    }\n\n    /**\n     * Gets the asset representing the materials folder of an assignment\n     * @throws {SAMError} If the materials folder cannot be found\n     * @param assignmentId\n     */\n    private async _getAssignmentMaterialsFolderAsset(assignmentId: string): Promise<AdobeAsset> {\n        const assignment = await this.getAssignmentByID(assignmentId);\n\n        const materialsFolderPath = `${assignment.repoPath}/materials`;\n        const materialsFolderAsset = await this._core.hostAssetContext.getAssetWithRepoPath(materialsFolderPath, assignment.repositoryID);\n        if (!materialsFolderAsset) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Could not find materials folder with path of \"${materialsFolderPath}\"`);\n        }\n\n        return materialsFolderAsset;\n    }\n\n    /**\n     * Gets a list of assets by ID\n     * @throws {SAMError} If any asset cannot be found\n     */\n    private async _getAssets(assetIds: string[]): Promise<AdobeAsset[]> {\n        return (await Promise.allSettled(assetIds.map(assetId => this._core.hostAssetContext.getAssetWithCloudID(assetId)))).map((result, index) => {\n            if (result.status === 'fulfilled') {\n                return result.value;\n            }\n\n            throw SAMError.wrapErrorIfNeeded(SAMErrorCode.INTERNAL_ERROR, `Failed to get asset with ID of \"${assetIds[index]}\"`, result.reason);\n        });\n    }\n\n    /** Discards a list of assets by ID */\n    private async _discardAssets(assetIds: string[]): Promise<void> {\n        if (assetIds.length === 0) {\n            return;\n        }\n\n        const assets = await this._getAssets(assetIds);\n\n        await Promise.allSettled(assets.map((asset) => asset.discard()));\n    }\n\n    /** Returns a list of ops used to update an assignment */\n    private _getUpdateAssignmentOps(mappedData: IAssignmentRemotePatchData) {\n        const ops = Object.entries(mappedData)\n            .filter(([ key ]) => key.startsWith('assignment:')) // We can only update the assignment metadata, not the asset metadata\n            .map(([ key, value ]) => ({ op: 'replace', path: `/${key}`, value }));\n        return ops;\n    }\n\n    /**\n     * Copies the given assets to the materials folder of the assignment\n     * @param assignmentId The assignment ID to copy to\n     * @param assetIds The assets to copy\n     * @returns The asset IDs of the copied assets\n     * @throws {SAMError} If any asset cannot be copied\n     */\n    private async _copyAssetsToMaterialsFolder(assignmentId: string, assetIds: string[]): Promise<string[]> {\n        if (assetIds.length === 0) {\n            return [];\n        }\n\n        const assignment = await this.getAssignmentByID(assignmentId);\n        const assetsToCopy = await this._getAssets(assetIds);\n\n        // Copying the assets one at a time (but in parallel) because the batch copy cannot copy assets from different directories\n        const copyPromises = assetsToCopy.map((asset, idx) => {\n            const extension = asset.extension ? `.${asset.extension}` : '';\n            return asset._copyWithDestMetadata(assignment.repositoryID, `${assignment.repoPath}/materials`, `${assignment.name} ${this._getFormattedCreatedDateHelper({ includeFormattedDate: true, date: new Date() })} ${idx}${extension}`);\n        });\n\n        const clonedAssets = (await Promise.allSettled(copyPromises))\n            .map((result, index) => {\n                if (result.status === 'fulfilled') {\n                    return result.value;\n                }\n\n                throw SAMError.wrapErrorIfNeeded(SAMErrorCode.INTERNAL_ERROR, `Failed to copy asset with ID of \"${assetIds[index]}\"`, result.reason);\n            });\n\n        return clonedAssets.map(asset => asset.id);\n    }\n\n    /**\n     * Helper function to format the created date for the asset name\n     * @package -- for SAM.js internal use only\n     */\n    public _getFormattedCreatedDateHelper({ includeFormattedDate, date }: {includeFormattedDate: boolean, date: Date}): string {\n        const locale = this._core._environment.getValue('LOCALE');\n        const dateTimeFormat: Intl.DateTimeFormatOptions = includeFormattedDate ? {\n            year: 'numeric',\n            month: 'numeric',\n            day: 'numeric',\n            hour: 'numeric',\n            minute: 'numeric',\n            second: 'numeric',\n            fractionalSecondDigits: 3,\n            hourCycle: 'h24'\n        } : {\n            hour: 'numeric',\n            minute: 'numeric',\n            second: 'numeric',\n        };\n        // Need to replace to convert from colons to periods, example: 14:28:00 to 14.28.00\n        return new Intl.DateTimeFormat(locale, dateTimeFormat).format(date).replace(/[/:]/g, '.');\n    }\n\n    /** Determines which files need to be kept, cloned, and discarded when updating an assignment with new resources. */\n    private async _determineAssetDifferences(assignmentId: string, field: 'templateIds' | 'referenceIds', incomingAssetIds: string[] | undefined) {\n        const assignment = await this.getAssignmentByID(assignmentId);\n\n        if (!incomingAssetIds) {\n            return {\n                assetsToCopy: [],\n                assetsToKeep: [],\n                assetsToDiscard: assignment[field],\n            };\n        }\n\n        const assetsToDiscard = assignment[field].filter(templateId => !incomingAssetIds.includes(templateId));\n        const assetsToCopy = incomingAssetIds.filter(templateId => !assignment[field].includes(templateId));\n        const assetsToKeep = assignment[field].filter(templateId => incomingAssetIds.includes(templateId));\n\n        return {\n            assetsToCopy,\n            assetsToKeep,\n            assetsToDiscard,\n        };\n    }\n\n    /**\n     * Based on incoming update data this will determine which assets need to be kept, cloned, and discarded.\n     * Assets to be kept are returned as-is.\n     * Assets to be cloned are copied to the materials folder of the assignment, and returned along with the kept asset IDs.\n     * Assets to be discarded are returned and are expected to be discarded after calling this function.\n     */\n    private async _getUpdatedAssignmentMaterials(assignmentId: string, data: Partial<IAssignmentUpdateData>): Promise<UpdateAssignmentMaterialsResult> {\n        const shouldUpdateTemplates = hasProperty(data, 'templateIds');\n        const shouldUpdateReferences = hasProperty(data, 'references');\n\n        const result: UpdateAssignmentMaterialsResult = {\n            assetsToDiscard: [],\n            shouldUpdateReferences,\n            shouldUpdateTemplates,\n            updatedReferenceIds: [],\n            updatedTemplateIds: [],\n        };\n\n        const assetsToCopy: string[] = [];\n        let splitIdx = 0;\n\n        const materialsPromises: (() => Promise<any>)[] = [];\n\n        if (shouldUpdateTemplates) {\n            const templateDifferences = await this._determineAssetDifferences(assignmentId, 'templateIds', data.templateIds);\n            result.assetsToDiscard.push(...templateDifferences.assetsToDiscard);\n            assetsToCopy.push(...templateDifferences.assetsToCopy);\n            result.updatedTemplateIds.push(...templateDifferences.assetsToKeep);\n            splitIdx = assetsToCopy.length;\n        }\n\n        if (shouldUpdateReferences) {\n            // Split the incoming references into IDs and ExternalAssets\n            const { referenceIds, referencesToImport } = data.references?.reduce((acc, cur) => {\n                if (typeof cur === 'string') {\n                    acc.referenceIds.push(cur);\n                } else {\n                    acc.referencesToImport.push(cur);\n                }\n\n                return acc;\n            }, {\n                referenceIds: [],\n                referencesToImport: [],\n            } as { referenceIds: string[], referencesToImport: ExternalAsset[] }) ?? { referenceIds: [], referencesToImport: [] };\n\n            const referenceDifferences = await this._determineAssetDifferences(assignmentId, 'referenceIds', referenceIds);\n            result.assetsToDiscard.push(...referenceDifferences.assetsToDiscard);\n            assetsToCopy.push(...referenceDifferences.assetsToCopy);\n            result.updatedReferenceIds.push(...referenceDifferences.assetsToKeep);\n\n            // If there are any ExternalAssets to import then we need to import them into the materials folder\n            // and store the new asset IDs in the references field\n            if (referencesToImport.length > 0) {\n                materialsPromises.push(async () => {\n                    const importedReferenceAssetIds: string[] = [];\n                    const importResults = await this.importNewReferencesForAssignment(assignmentId, referencesToImport);\n                    importResults.forEach((result) => {\n                        if (result.status === 'fulfilled') {\n                            importedReferenceAssetIds.push(result.value.id);\n                        } else {\n                            throw SAMError.create(\n                                SAMErrorCode.BAD_REQUEST,\n                                'Error importing reference asset',\n                                { underlyingError: result.reason });\n                        }\n                    });\n\n                    result.updatedReferenceIds.push(...importedReferenceAssetIds);\n                });\n            }\n        }\n\n        let clonedAssetIds: string[] = [];\n\n        // Copy all assets at once to avoid multiple API calls\n        materialsPromises.push(async () => {\n            clonedAssetIds = await this._copyAssetsToMaterialsFolder(assignmentId, assetsToCopy);\n        });\n\n        // Upload references and copy templates concurrently\n        await Promise.all(materialsPromises.map((fn) => fn()));\n\n        // Split the result into templates and references\n        const [ clonedTemplates, clonedReferences ] = [ clonedAssetIds.slice(0, splitIdx), clonedAssetIds.slice(splitIdx) ];\n\n        result.updatedTemplateIds.push(...clonedTemplates);\n        result.updatedReferenceIds.push(...clonedReferences);\n\n        return result;\n    }\n\n    /**\n     * Imports each ExternalAsset as a file into the assignment's materials folder\n     * @returns The AdobeAsset objects of the imported files\n     */\n    private async importNewReferencesForAssignment(assignmentId: string, references: ExternalAsset[]): Promise<PromiseSettledResult<AdobeAsset>[]> {\n        const materialsFolder = await this._getAssignmentMaterialsFolderAsset(assignmentId);\n        return Promise.allSettled(references.map(async (reference) => {\n            return materialsFolder.importFile(reference.content, reference.name, reference.mediaType, true, 0, false);\n        }));\n    }\n\n    /**\n     * Function to get a list of StudentAssignmentFiles for a given StudentDirectoryId\n     *\n     * @param {} param Contains parameters for StudentDirectoryId and order for the list\n     * @throws {Error} if the student directory asset is not a folder\n     * @deprecated Use `StudentAssignment.files` instead. Will be removed in ACPCEDU-3305.\n     */\n    async getStudentAssignmentFiles({ studentDirectoryId, order }: IGetStudentAssignmentFiles): Promise<StudentAssignmentFile[]> {\n        validateString(studentDirectoryId, 'studentDirectoryId');\n\n        const folderAsset = await this._core.hostAssetContext.getAssetWithCloudID(studentDirectoryId);\n        const list = folderAsset.children!.getList(order || AdobeAssetOrder.default, new StudentAssignmentFilesListFilter(), { loadAllPages: true });\n        // Waiting for the list because clients expect all files to be returned from this method without having to wait themselves\n        await waitForListLoad(list);\n        return list.items as StudentAssignmentFile[];\n    }\n\n    /**\n     * Refreshes the classroom codes for the given classroom IDs\n     *\n     * @param classIds list of classroomIds to refresh\n     *\n     * @example <caption>Refresh classroom codes for a list of classroom IDs</caption>\n     * await classroomContext.refreshClassroomCodes(['123@AdobeID']);\n     */\n    @synchronized\n    async refreshClassroomCodes(classIds: string[]): Promise<void> {\n        validateString(classIds, 'classIds');\n\n        // Attempt to refresh all codes\n        const results = await Promise.allSettled(classIds.map(id => this._classroomsInterface.refreshClassroomCode(id)));\n\n        // Filter out failing requests\n        // @ts-expect-error -- TS can't infer the type of results after filtering. Will be fixed in TS 5.5\n        const classroomsToUpdate = results.filter(result => result.status === 'fulfilled').map(result => result.value);\n\n        // Fetch each classroom so that we have an IRemoteClassroom, update its code to the new one\n        const updatedClassrooms = await Promise.allSettled(classroomsToUpdate.map(async ({ classroomId, classcode }) => {\n            const classroom = await this._classroomsInterface.getClassroom(classroomId);\n            classroom.classCode = classcode;\n            return classroom;\n        }));\n\n        // Filter out any lookups that failed\n        // @ts-expect-error -- TS can't infer the type of results after filtering. Will be fixed in TS 5.5\n        const successfullyUpdatedClassrooms = updatedClassrooms.filter(result => result.status === 'fulfilled').map(result => result.value);\n\n        const session = this._classroomPool.createMutationSession<Classroom>();\n        ClassroomUpdater.updateRemoteItems(session, successfullyUpdatedClassrooms);\n        session.commit();\n    }\n\n    /**\n     * @description Deletes classrooms with the given class IDs.\n     *\n     * @param ids either an array or single string that maps to classIds or classCodes\n     *\n     * @example <caption>Delete a classroom by ID</caption>\n     * await classroomContext.deleteClassrooms('123@AdobeID');\n     */\n    async deleteClassrooms(ids: string | string[]): Promise<void> {\n        validateString(ids, 'ids');\n\n        if (Array.isArray(ids)) {\n            await Promise.all(ids.map(id => this.deleteClassrooms(id)));\n        } else {\n            const classroom = await this.getClassroomById(ids);\n            if (classroom.isVirtual) {\n                await this._classroomsInterface.deleteVirtualClassroom(ids);\n            } else {\n                await this._classroomsInterface.deleteClassroom(ids);\n            }\n            const session = this._classroomPool.createUpdateSession<Classroom>();\n            session.queueDiscardedItem(classroom);\n            session.commit();\n            // The session doesn't actually remove the item from the pool\n            this._classroomPool.removeLocalItems([ classroom.id! ]);\n        }\n    }\n\n    /**\n     * Updates a classroom with new data\n     *\n     * @example <caption>Update a classroom by ID</caption>\n     * await classroomContext.updateClassroom('123@AdobeID', { name: 'New Name' });\n     */\n    @trace\n    async updateClassroom(classroomId: string, data: IClassroomUpdateData): Promise<void> {\n        validateString(classroomId, 'classroomId');\n\n        let updatedClassroomData;\n        const classroom = await this.getClassroomById(classroomId);\n        // Classroom name is required for the update operation\n        // If it is not passed in then we can get it from the pool\n        data.name ??= classroom.name;\n        if (classroom.isVirtual) {\n            updatedClassroomData = await this._classroomsInterface.updateClassroomFromVirtual(classroom.id, data);\n            // Preserve the old original identifier for the class to re-index the existing item under its preferred id\n            updatedClassroomData.virtualId = classroom.id;\n        } else {\n            updatedClassroomData = await this._classroomsInterface.updateClassroom(classroomId, data);\n        }\n\n        const session = this._classroomPool.createMutationSession<Classroom>();\n        ClassroomUpdater.updateRemoteItem(session, this._processRemoteClassroomItem(classroomId, updatedClassroomData));\n        session.commit();\n    }\n\n    private _processRemoteClassroomItem(classroomId: string, remoteClassroom: Partial<IRemoteClassroom>): Partial<IRemoteClassroom> {\n        const cachedClassroom = this._classroomPool.getLocalItemById(classroomId);\n        // Preserve the classroom's old virtual ID if it is set in this session\n        if (cachedClassroom?._virtualId) {\n            remoteClassroom.virtualId = cachedClassroom._virtualId;\n        }\n        return remoteClassroom;\n    }\n\n    /**\n     * Returns the current user's (determined by bearer token of the request) membership status for a classroom\n     *\n     * @param classroomId ID of the classroom to check status of user for\n     *\n     * @example <caption>Get the current user's membership status for a classroom</caption>\n     * const membershipStatus: IRemoteMembership = await this.getClassroomMembership('123@AdobeOrg');\n     */\n    async getClassroomMembership(classroomId: string): Promise<IRemoteMembership> {\n        validateString(classroomId, 'classroomId');\n\n        return this._classroomsInterface.getMembership(classroomId);\n    }\n\n    /**\n     * Blocks a student from a classroom\n     *\n     * @param classroomId Classroom ID to block student from\n     * @param studentId Student ID to block\n     *\n     * @example <caption>Block a student from a classroom</caption>\n     * await classroomContext.blockStudentFromClassroom('123@AdobeOrg', 'user@adobe.com');\n     */\n    async blockStudentFromClassroom(classroomId: string, studentId: string): Promise<IRemoteBlockOrRemoveResponse> {\n        validateString(classroomId, 'classroomId');\n        validateString(studentId, 'studentId');\n\n        return this._classroomsInterface.blockStudent(classroomId, studentId);\n    }\n\n    /**\n     * Unblocks a student from a classroom\n     *\n     * @param classroomId Classroom ID to unblock student from\n     * @param studentId Student ID to unblock\n     *\n     * @example <caption>Block a student from a classroom</caption>\n     * await classroomContext.unblockStudentFromClassroom('123@AdobeOrg', 'user@adobe.com');\n     */\n    async unblockStudentFromClassroom(classroomId: string, studentId: string): Promise<IRemoteBlockOrRemoveResponse> {\n        validateString(classroomId, 'classroomId');\n        validateString(studentId, 'studentId');\n\n        return this._classroomsInterface.unblockStudent(classroomId, studentId);\n    }\n\n    /**\n     * Removes a student from a classroom\n     *\n     * @param classroomId Classroom ID to remove student from\n     * @param studentId Student ID to remove\n     *\n     * @example <caption>Remove a student from a classroom</caption>\n     * await classroomContext.removeStudentFromClassroom('123@AdobeOrg', 'user@adobeId');\n     */\n    async removeStudentFromClassroom(classroomId: string, studentId: string): Promise<IRemoteBlockOrRemoveResponse> {\n        validateString(classroomId, 'classroomId');\n        validateString(studentId, 'studentId');\n\n        const removeResponse = await this._classroomsInterface.removeStudent(classroomId, studentId);\n\n        this.removeUserFromPool(classroomId, studentId);\n\n        return removeResponse;\n    }\n\n    /**\n     * Removes a teacher from a classroom\n     *\n     * @param classroomId Classroom ID to remove teacher from\n     * @param teacherId Teacher's user ID to remove\n     *\n     * @example <caption>Remove a teacher from a classroom</caption>\n     * await classroomContext.removeTeacherFromClassroom('123@AdobeOrg', 'user@adobeId');\n     */\n    async removeTeacherFromClassroom(classroomId: string, teacherId: string): Promise<IRemoteBlockOrRemoveResponse> {\n        validateString(classroomId, 'classroomId');\n        validateString(teacherId, 'teacherId');\n\n        const removeResponse = await this._classroomsInterface.removeTeacher(classroomId, teacherId);\n        this.removeUserFromPool(classroomId, teacherId);\n\n        return removeResponse;\n    }\n\n    /**\n     * Removes a user from the local pool\n     * So long as the users were fetched initially from the Classroom.members.getList() method and added to the classroomMemberPool, they'll be present to remove.\n     *\n     * @param classroomId The classroom ID to remove the user from\n     * @param userId The user ID to remove\n     */\n    private removeUserFromPool(classroomId: string, userId: string): void {\n        const member = this._classroomMemberPool.getLocalItemById(getMemberComputedKey(classroomId, userId));\n        if (member) {\n            const session = this._classroomMemberPool.createUpdateSession<ClassroomMember>();\n            session.queueDiscardedItem(member);\n            session.commit();\n            this._classroomMemberPool.removeLocalItems([ getMemberComputedKey(classroomId, userId) ]);\n        }\n    }\n\n    /**\n     * Creates a ClassroomOrder object\n     * @experimental\n     *\n     * @example <caption>Create a ClassroomOrder</caption>\n     * const order: ClassroomOrder = await classroomContext.getClassroomOrder('descending', 'created');\n     */\n    getClassroomOrder(direction: IOrderDirection = 'ascending', field: ClassroomOrderField = 'name'): ClassroomOrder {\n        return new ClassroomOrder(direction, field);\n    }\n\n    /**\n     * Creates a AssignmentOrder object\n     * @experimental\n     *\n     * @example <caption>Create a AssignmentOrder</caption>\n     * const order: AssignmentOrder = await classroomContext.getAssignmentOrder('descending', 'status');\n     */\n    getAssignmentOrder(direction: IOrderDirection = 'ascending', field: AssignmentOrderField = 'name'): AssignmentOrder {\n        return new AssignmentOrder(direction, field);\n    }\n\n    /**\n     * Creates a AssignmentFilter object\n     * @experimental\n     *\n     * @example <caption>Create a AssignmentFilter</caption>\n     * const filter: AssignmentFilter = await classroomContext.getAssignmentFilter({ classroomId: '123@AdobeOrg' });\n     */\n    getAssignmentFilter(options: Partial<IAssignmentFilterOptions> = {}): AssignmentFilter {\n        return new AssignmentFilter(options);\n    }\n\n    /**\n     * Creates a StudentAssignmentOrder object\n     * @experimental\n     *\n     * @example <caption>Create a StudentAssignmentOrder</caption>\n     * const order: StudentAssignmentOrder = await classroomContext.getStudentAssignmentOrder('descending', 'studentDisplayName');\n     */\n    getStudentAssignmentOrder(direction: IOrderDirection = 'ascending', field: StudentAssignmentOrderField = 'studentDisplayName'): StudentAssignmentOrder {\n        return new StudentAssignmentOrder(direction, field);\n    }\n\n    /**\n     * Creates a StudentAssignmentFilter object\n     * @experimental\n     *\n     * @example <caption>Create a StudentAssignmentFilter</caption>\n     * const filter: StudentAssignmentFilter = await classroomContext.getStudentAssignmentFilter({ assignmentId: 'assignmentID', status: [StudentAssignmentStatus.NOT_STARTED] });\n     */\n    getStudentAssignmentFilter(options: StudentAssignmentOptionalParams): StudentAssignmentFilter {\n        return new StudentAssignmentFilter(options);\n    }\n\n    /**\n     * Creates a StudentAssignmentFileOrder object\n     * @experimental\n     *\n     * @example <caption>Create a StudentAssignmentFileOrder</caption>\n     * const order: StudentAssignmentFileOrder = await classroomContext.getStudentAssignmentFileOrder('descending', 'modified');\n     */\n    getStudentAssignmentFileOrder(direction: IOrderDirection = 'ascending', field: StudentAssignmentFileOrderField = 'name'): StudentAssignmentFileOrder {\n        return new StudentAssignmentFileOrder(direction, field);\n    }\n\n    /**\n     * Creates a StudentAssignmentFileFilter object\n     * @experimental\n     *\n     * @param studentAssignmentId The ID of the StudentAssignment that the files returned are associated with\n     * @param options Deprecated, further filtering of files is not supported at this time\n     *\n     * @example <caption>Create a StudentAssignmentFileFilter</caption>\n     * const filter: StudentAssignmentFileFilter = await classroomContext.getStudentAssignmentFileFilter('student-assignment-id');\n     */\n    getStudentAssignmentFileFilter(studentAssignmentId: string, options?: StudentAssignmentFileFilterOptions): StudentAssignmentFileFilter {\n        return new StudentAssignmentFileFilter(studentAssignmentId, options);\n    }\n\n    /**\n     * Creates a ClassroomMemberOrder object\n     * @experimental\n     *\n     * @example <caption>Create a ClassroomMemberOrder</caption>\n     * const order: ClassroomMemberOrder = await classroomContext.getClassroomMemberOrder('descending', 'name');\n     */\n    getClassroomMemberOrder(direction: IOrderDirection = 'ascending', field: ClassroomMemberOrderField = 'name'): ClassroomMemberOrder {\n        return new ClassroomMemberOrder(direction, field);\n    }\n\n    /**\n     * Creates a ClassroomMemberFilter object\n     * @experimental\n     *\n     * @example <caption>Create a ClassroomMemberFilter</caption>\n     * const filter: ClassroomMemberFilter = await classroomContext.getClassroomMemberFilter({classroomId: '123@AdobeOrg'});\n     */\n    getClassroomMemberFilter(options: Partial<IClassroomMemberFilterOptions>): ClassroomMemberFilter {\n        return new ClassroomMemberFilter(options);\n    }\n\n    /**\n     * Checks eligibility of users to be added as co-teachers to a classroom\n     *\n     * @example <caption>Check co-teacher eligibility</caption>\n     * const eligibility = await classroomContext.checkCoTeacherEligibility({ emails: ['user@adobe.com'], classroomId: '123@AdobeOrg' });\n     */\n    async checkCoTeacherEligibility(options: ICheckCoTeacherEligibilityOptions): Promise<Array<ICoTeacherEligibilityEntry>> {\n        return this._classroomsInterface.checkCoTeacherEligibility(options);\n    }\n\n    /**\n     * Gets a classroom by ID or code\n     * @throws {SAMError} if neither classroomCode nor classroomId is provided\n     */\n    private async _getClassroomByIdOrCode(options: GetClassroomBoardsOptions): Promise<Classroom> {\n        const { classroomCode, classroomId } = options;\n        if (classroomId) {\n            return this.getClassroomById(classroomId);\n        } else if (classroomCode) {\n            return this.getClassroomByCode(classroomCode);\n        } else {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Either classroomCode or classroomId must be provided');\n        }\n    }\n\n    /**\n     * Gets an assignment ID via assignment code or assignment ID\n     * @throws {SAMError} if neither assignmentCode nor assignmentId is provided\n     */\n    private async _getAssignmentId(options: GetAssignmentBoardsOptions): Promise<string> {\n        const { assignmentCode, assignmentId } = options;\n        if (assignmentId) {\n            return assignmentId;\n        } else if (assignmentCode) {\n            const assignment = await this.getAssignmentByCode(assignmentCode);\n            return assignment.id;\n        } else {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Either assignmentCode or assignmentId must be provided');\n        }\n    }\n\n    /**\n     * Gets the boards for a classroom given a classroom ID or classroom code\n     * @experimental\n     *\n     * @example <caption>Get all Boards</caption>\n     * const classroomBoardsList = (await classroomContext.getClassroomBoards({classroomId: '123@AdobeOrg'})).getList(BoardOrder.default);\n     * await waitForListLoad(classroomBoardsList);\n     * const classroomBoards: Board[] = classroomBoardsList.items;\n     */\n    @keepAlive\n    @weakCache\n    async getClassroomBoards(@key options: GetClassroomBoardsOptions): Promise<BoardSource> {\n        const classroom = await this._getClassroomByIdOrCode(options);\n        return this._ensureBoardContext().getBoards({ baseAssetId: classroom.assetId });\n    }\n\n    /**\n     * Gets the boards for an assignment given an assignment ID or assignment code\n     * @experimental\n     *\n     * @example <caption>Get the boards for an assignment</caption>\n     * const assignmentBoardsList = (await classroomContext.getAssignmentBoards({assignmentId: 'assignmentID'})).getList(BoardOrder.default);\n     * await waitForListLoad(assignmentBoardsList);\n     * const assignmentBoards: Board[] = assignmentBoardsList.items;\n     */\n    @keepAlive\n    @weakCache\n    async getAssignmentBoards(@key options: GetAssignmentBoardsOptions): Promise<BoardSource> {\n        const assignmentId = await this._getAssignmentId(options);\n        return this._ensureBoardContext().getBoards({ baseAssetId: assignmentId });\n    }\n\n    /**\n     * Gets the only assignment board for an assignment.\n     * It throws an error if the list has more than 1 item.\n     * It returns undefined where there is no boards in the list.\n     * @experimental\n     *\n     * @example <caption>Get the only board for an assignment</caption>\n     * const assignmentBoard: Board = await classroomContext.getAssignmentBoard({assignmentId: 'assignmentID'});\n     * const assignmentBoard: Board = await classroomContext.getAssignmentBoard({assignmentCode: 'ABCD12'});\n     */\n    @keepAlive\n    @synchronized\n    async getAssignmentBoard(@key options: GetAssignmentBoardsOptions): Promise<Board | undefined> {\n        const boardSource = await this.getAssignmentBoards(options);\n        const boardList = boardSource.getList(BoardOrder.default, undefined, { loadAllPages: true });\n        await waitForListLoad(boardList);\n        if (boardList.items.length > 1) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Expected 1 board, got ${boardList.items.length}`);\n        }\n        return boardList.items[0];\n    }\n\n    /**\n     * Gets a real classroom given a classroom ID or classroom code.\n     * If the classroom is found in the pool then its ID and asset ID are returned\n     * If the classroom is not found in the pool then it is fetched and if it is virtual\n     * then a new real classroom is created and the ID and asset ID of the newly created classroom are returned\n     * @returns {Promise<GetRealClassroomGivenClassroomIdOrCodeResult>} A non-virtual classroom\n     */\n    async _getRealClassroomGivenClassroomIdOrCode({ classroomId, classroomCode }: GetRealClassroomGivenClassroomIdOrCodeOptions): Promise<GetRealClassroomGivenClassroomIdOrCodeResult> {\n        const currentClassroomId = classroomId || '';\n\n        // See if the class ID given maps to a virtual class that has already been migrated recently\n        // if not fetch the classroom and see if it is virtual which requires migrating the class to\n        // a real class before an assignment can be created for it\n        const recentMigratedClassroom = this._classroomPool.toArray().find((classroom) => classroom._virtualId === currentClassroomId);\n        if (recentMigratedClassroom) {\n            return { classroom: recentMigratedClassroom };\n        } else {\n            // Class that maps to given ID has not been migrated recently so fetch and see if it maps to a virtual class\n            const classroomIdentifier: GetClassroomBoardsOptions = classroomId\n                ? { classroomId }\n                : { classroomCode: classroomCode! };\n            const classroom = await this._getClassroomByIdOrCode(classroomIdentifier);\n            if (classroom.isVirtual) {\n                const migratedClassroom = await this.createClassroom({ id: classroom.id });\n                // Check if the virtual class is still being referenced if so throw an error\n                // The newly created real class is what is expected to be returned\n                if (currentClassroomId === migratedClassroom.id) {\n                    throw SAMError.create(\n                        SAMErrorCode.BAD_REQUEST,\n                        'Cannot create an asset with a virtual classroom.'\n                    );\n                }\n                return { classroom: migratedClassroom, isVirtualClassroomJustMigrated: true };\n            }\n            return { classroom };\n        }\n    }\n\n    /**\n     * Creates a board for a classroom\n     * @experimental\n     *\n     * @example <caption>Create a board for a classroom</caption>\n     * const board: Board = await classroomContext.createClassroomBoard({ name: 'My Classroom Board', classroomId: '123@AdobeOrg' });\n     */\n    @trace\n    async createClassroomBoard(options: CreateClassroomBoardOptions): Promise<Board> {\n        const { classroomId, classroomCode, ...rest } = options;\n        const { classroom, isVirtualClassroomJustMigrated } = await this._getRealClassroomGivenClassroomIdOrCode({ classroomId, classroomCode });\n        const { id: currentClassroomId, assetId: currentClassroomAssetId } = classroom;\n\n        // Name validation is already done within BoardContext.createBoard\n        return this._ensureBoardContext().createBoard({\n            ...rest,\n            baseAssetId: currentClassroomAssetId,\n            type: BoardType.CLASSROOM,\n            additionalData: {\n                classroomId: currentClassroomId,\n            },\n            // If the classroom is just migrated, we don't need to check for duplicate names\n            shouldCheckForDuplicateName: !isVirtualClassroomJustMigrated\n        });\n    }\n\n    /**\n     * Validates a classroom board name for creation\n     * @experimental\n     *\n     * @example <caption>Validate a classroom board name for creation</caption>\n     * await classroomContext.validateClassroomBoardNameForCreate({ name: 'My Classroom Board', classroomId: '123@AdobeOrg' });\n     * await classroomContext.validateClassroomBoardNameForCreate({ name: 'My Classroom Board', classroomCode: 'HL4ABC' });\n     */\n    async validateClassroomBoardNameForCreate(options: ValidateClassroomBoardNameForCreateOptions): Promise<void> {\n        let baseAssetId: string | undefined;\n        let classroom: Classroom | undefined;\n        const { classroomCode, classroomId } = options;\n        // In this case, when classroom ID/code is not given, we won't provide baseAssetId which won't make the API call to fetch all boards in _validateBoardName function.\n        //  This will not provide assetList to validateAssetName function. This ultimately makes validateAssetName to check for the name format and not whether the name is duplicate.\n        if (classroomCode || classroomId) {\n            const classroomIdentifier: GetClassroomBoardsOptions = classroomId\n                ? { classroomId }\n                : { classroomCode: classroomCode! };\n            classroom = await this._getClassroomByIdOrCode(classroomIdentifier);\n            baseAssetId = classroom.assetId;\n        }\n        return this._ensureBoardContext().validateBoardNameForCreate({ name: options.name, baseAssetId });\n    }\n\n    /**\n     * Validates a classroom board name for update\n     * @experimental\n     *\n     * @example <caption>Validate a classroom board name for update</caption>\n     * await classroomContext.validateClassroomBoardNameForUpdate({ name: 'My Classroom Board', boardId: 'boardID', classroomId: '123@AdobeOrg' });\n     * await classroomContext.validateClassroomBoardNameForUpdate({ name: 'My Classroom Board', boardId: 'boardID', classroomCode: 'HL4ABC' });\n     */\n    async validateClassroomBoardNameForUpdate(options: ValidateClassroomBoardNameForUpdateOptions): Promise<void> {\n        const { name, boardId } = options;\n        const classroom = await this._getClassroomByIdOrCode(options);\n        return this._ensureBoardContext().validateBoardNameForUpdate({ name, baseAssetId: classroom.assetId, boardId });\n    }\n}\n","/*************************************************************************\n   *\n   * ADOBE CONFIDENTIAL\n   * ___________________\n   *\n   *  Copyright 2025 Adobe Systems Incorporated\n   *  All Rights Reserved.\n   *\n   * NOTICE:  All information contained herein is, and remains\n   * the property of Adobe Systems Incorporated and its suppliers,\n   * if any.  The intellectual and technical concepts contained\n   * herein are proprietary to Adobe Systems Incorporated and its\n   * suppliers and are protected by trade secret or copyright law.\n   * Dissemination of this information or reproduction of this material\n   * is strictly forbidden unless prior written permission is obtained\n   * from Adobe Systems Incorporated.\n   **************************************************************************/\n\n/**\n * This is a temporary file while the Hume service implements the Boards API.\n * It contains mock response objects that we expect Hume to provide us in the future.\n * This will be removed in ACPCEDU-3734\n */\n\nconst GetBoardByIdResponse = {\n    'repo:name': 'Sample board name',\n    'dc:description': 'Board description',\n    'board#type': 'classroom',\n    'board:context': {\n        'baseAssetId': 'urn:aaid:sc:VA6C2:af99f449-ea01-3e3e-aba5-fe57fd38364b',\n        'boardsAssetId': 'urn:aaid:sc:VA6C2:af99f449-ea01-3e3e-aba5-fe57fd38364c'\n    },\n    'repo:assetId': 'urn:aaid:sc:VA6C2:61b71cdc-4d42-5ac2-8d19-dede02efdxyz',\n    'repo:createDate': '2024-10-01T21:59:01.415Z',\n    'repo:modifyDate': '2024-10-01T21:59:06.565Z',\n    'repo:createdBy': '1916195E667CADAB0A12345D@AdobeID',\n    'repo:modifiedBy': '1916195E667CADAB0A12345D@AdobeID',\n    'posts': [\n        {\n            'id': 'af46a980-9cc5-4baf-935c-123fcb6ee615',\n            'description': 'Text 1',\n            'type': 'application/vnd.adobe.post.text+dcx',\n            'postedBy': {\n                'userId': 'BF44198F668D1EAE0A494021@af361967668d0331494131.e',\n                'email': 'assignmentstudent1@itaw16.onmicrosoft.com',\n                'firstName': 'John',\n                'lastName': 'Doe',\n                'displayName': 'John. Doe',\n                'images': {\n                    '50': 'https://example_50_pixel.com',\n                    '100': 'https://example_100_pixel.com'\n                }\n            },\n            'created': '2020-03-17T21:23:25.693Z',\n            'modified': '2020-03-17T22:23:25.693Z',\n\n            'board#createdData': {\n                'userId': '0D522D2B5D7687E40A494215@AdobeID'\n            },\n            'board#modifiedData': {\n                'userId': '0D522D2B5D7687E40A494215@AdobeID'\n            }\n        },\n        {\n            'id': 'af46a980-9cc5-4baf-935c-501fcb6ee616',\n            'name': 'My poster',\n            'description': 'My poster description',\n            'type': 'application/vnd.adobe.post.assetlink+dcx',\n            'link': {\n                'repo:assetId': 'urn:aaid:sc:VA6C2:61b71cdc-4d42-5ac2-8d19-dede02efdbbb',\n                'repo:etag': '\"167dd86b8f8d4ac88f40722210655c51\"'\n            },\n            'postedBy': {\n                'userId': 'BF44198F668D1EAE0A494021@af361967668d0331494131.e',\n                'email': 'assignmentstudent1@itaw16.onmicrosoft.com',\n                'firstName': 'John',\n                'lastName': 'Doe',\n                'displayName': 'John. Doe',\n                'images': {\n                    '50': 'https://example_50_pixel.com',\n                    '100': 'https://example_100_pixel.com'\n                }\n            },\n            'created': '2020-03-17T21:23:25.693Z',\n            'modified': '2020-03-17T22:23:25.693Z',\n            'board#createdData': {\n                'userId': '0D522D2B5D7687E40A494215@AdobeID'\n            },\n            'board#modifiedData': {\n                'userId': '0D522D2B5D7687E40A494215@AdobeID'\n            }\n        }\n    ]\n};\n\nexport { GetBoardByIdResponse };\n","/*************************************************************************\n   *\n   * ADOBE CONFIDENTIAL\n   * ___________________\n   *\n   *  Copyright 2025 Adobe Systems Incorporated\n   *  All Rights Reserved.\n   *\n   * NOTICE:  All information contained herein is, and remains\n   * the property of Adobe Systems Incorporated and its suppliers,\n   * if any.  The intellectual and technical concepts contained\n   * herein are proprietary to Adobe Systems Incorporated and its\n   * suppliers and are protected by trade secret or copyright law.\n   * Dissemination of this information or reproduction of this material\n   * is strictly forbidden unless prior written permission is obtained\n   * from Adobe Systems Incorporated.\n   **************************************************************************/\n\nimport type { BoardsIndexLinks, BoardsIndexResponse, CreateBoardOptions, RemoteBoard, UpdateBoardOptions, AddBoardPostOptions, CreateBoardPayload, GetBoardsResponse, GetBoardsOptions, RemoteTextPost, RemoteAssetLinkPost, BoardLinks, AddPostValuePayload, PublishBoardInterfaceOptions, PublishOptions } from './BoardModel';\n\nimport { BOARDS_REQUIRED_INDEX_LINKS, PostType, PostTypeMap } from './BoardModel';\nimport { cache, key } from '../core/decorators';\nimport InterfaceBase from './InterfaceBase';\nimport { getURLFromLinks, JSON_MIME_TYPE, RelType, validateLinks } from './LinkUtils';\nimport type jsonpatch from 'json-patch';\nimport { getSAMVersionRequestHeader } from '../utils/classroomUtils';\nimport { GetBoardByIdResponse } from './MockBoardResponses';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\n\n\nconst headers = getSAMVersionRequestHeader();\n\nfunction validateRequiredBoardLinks(links: any) {\n    return validateLinks(links, BOARDS_REQUIRED_INDEX_LINKS);\n}\n\nexport default class BoardsInterface extends InterfaceBase {\n    @cache(validateRequiredBoardLinks)\n    private async _discoverLinks(@key rootHref: string): Promise<BoardsIndexLinks> {\n        const response: BoardsIndexResponse = await this._getResponse(rootHref, { headers });\n        return response._links;\n    }\n\n    private _getEndpointHref(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.ASSIGNMENTS_HOST}${endpoint}`;\n    }\n\n    /**\n     * Discovers and retrieves the available board-related API links and endpoints\n     */\n    async discoverLinks(): Promise<BoardsIndexLinks> {\n        return this._discoverLinks(this._getEndpointHref(`/api/v1/boards/index`));\n    }\n\n    /**\n     * Creates a new board\n     */\n    async createBoard(data: CreateBoardOptions): Promise<RemoteBoard> {\n        const links = await this.discoverLinks();\n        const { name, description, type, additionalData, posts } = data;\n        const dataToPost: CreateBoardPayload = {\n            'repo:name': name,\n            'dc:description': description,\n            'board#type': type,\n            'additionalMetadata': additionalData,\n        };\n\n        if (posts) {\n            dataToPost.posts = await Promise.all(posts.map(post => this.mapPostCreationData(post)));\n        }\n\n        const url = getURLFromLinks(links, RelType.BOARDS_CREATE, {\n            baseAssetId: data.baseAssetId,\n            useBaseAssetDirectory: data.shouldCreateDirectlyInBaseAsset || false\n        });\n        const response = await this._doPost(url, {\n            ...headers,\n            'Content-Type': JSON_MIME_TYPE,\n        },\n        JSON.stringify(dataToPost),\n        [ 201 ]\n        );\n        return response.json();\n    }\n\n    /**\n     * Retrieves a specific board by its ID\n     */\n    async getBoard(boardId: string): Promise<RemoteBoard> {\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(links, RelType.BOARDS_PRIMARY, {  boardId  });\n        const response = await this._doGet(url, { headers });\n        return response.json();\n    }\n\n    /**\n     * Retrieves all boards associated with a specific linked asset\n     */\n    async getBoards(options: GetBoardsOptions): Promise<RemoteBoard[]> {\n        const { baseAssetId } = options;\n        const links = await this.discoverLinks();\n        const url = getURLFromLinks(links, RelType.BOARDS_COLLECTION, {\n            baseAssetId,\n            useBaseAssetDirectory: options.shouldGetDirectlyInBaseAsset || false\n        });\n        const response = await this._doGet(url, { headers });\n        const data: GetBoardsResponse = await response.json();\n        return data.children;\n    }\n\n    /** Transforms the data given to {@link updateBoard} for posts into the data expected by the API */\n    private async mapPostCreationData(post: AddBoardPostOptions): Promise<AddPostValuePayload> {\n        const { name, description, type, userId } = post;\n\n        const remotePost: AddPostValuePayload = {\n            name,\n            'board#postDescription': description,\n            type: PostTypeMap.toB(type),\n        };\n\n        if (userId) {\n            remotePost.userId = userId;\n        }\n\n        if (type === PostType.Text) {\n            (remotePost as RemoteTextPost)['board#postText'] = post.text;\n        }\n\n        if (type === PostType.AssetLink) {\n            // At this point assetId will be defined because it was provided or the user uploaded an asset\n            const asset = await this._core.hostAssetContext.getAssetWithCloudID(post.assetId!);\n            (remotePost as RemoteAssetLinkPost).link = {\n                'repo:assetId': post.assetId!,\n                'dc:format': asset.mediaType,\n            };\n        }\n\n        return remotePost;\n    }\n\n    /**\n     * Updates an existing board's properties, including description and posts\n     */\n    async updateBoard(data: UpdateBoardOptions): Promise<RemoteBoard | undefined> {\n        const links = await this.discoverLinks();\n        const { displayName: newName, description: boardDescription, postsToAdd = [], postsToRemove, postsToUpdate, boardId } = data;\n        const patchData: jsonpatch.OpPatch[] = [];\n\n        if (newName !== undefined) {\n            patchData.push({\n                op: 'replace',\n                path: '/repo:name',\n                value: newName\n            });\n        }\n\n        if (boardDescription !== undefined) {\n            patchData.push({\n                op: 'replace',\n                path: '/dc:description',\n                value: boardDescription\n            });\n        }\n\n        for (const post of postsToAdd) {\n            patchData.push({\n                op: 'add',\n                path: '/board#post',\n                value: await this.mapPostCreationData(post),\n            });\n        }\n\n        postsToRemove?.forEach((postId) => {\n            patchData.push({\n                op: 'remove',\n                path: `/board#post/${postId}`\n            });\n        });\n\n        // User is only allowed to update post description\n        postsToUpdate?.forEach((post) => {\n            patchData.push({\n                op: 'replace',\n                path: `/board#post/${post.id}/board#postDescription`,\n                value: post.description\n            });\n        });\n\n        const url = getURLFromLinks(links, RelType.BOARDS_PRIMARY, {  boardId  });\n\n        if (patchData.length > 0) {\n            const response = await this._doPatch(url, {\n                ...headers,\n                'Content-Type': JSON_MIME_TYPE,\n            }, JSON.stringify(patchData));\n            return response.json();\n        }\n    }\n\n    /**\n     * Updates the users who can modify a board\n     */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Remove with ACPCEDU-3734\n    async updateUsers(boardId: string): Promise<RemoteBoard> {\n        await this.discoverLinks();\n        return Promise.resolve(GetBoardByIdResponse) as unknown as Promise<RemoteBoard>;\n        // TODO: Handle this once we know the post body format ACPCEDU-3734\n        // const patchData: jsonpatch.OpPatch[] = [];\n        // const response = await this._doPatch(\n        //     this._getEndpointHref(`/api/v1/boards/${boardId}/users`),\n        //     {},\n        //     JSON.stringify(patchData)\n        // );\n        // return response.json();\n    }\n\n    /**\n     * Discard a specific board\n     */\n    async discardBoard(boardId: string, links: BoardLinks): Promise<void> {\n        if (!links?.[RelType.BOARDS_DISCARD]) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Discard link is missing for this board ${boardId}`);\n        }\n        const url = getURLFromLinks(links, RelType.BOARDS_DISCARD, { boardId });\n        await this._doPost(url, headers, undefined, [ 204 ]);\n    }\n\n    /**\n     * Publishes a board, making it available for viewing\n     */\n    async publishBoard(options: PublishBoardInterfaceOptions): Promise<RemoteBoard> {\n        const { boardId, links, boardTitle, boardSubTitle, showPosterName } = options;\n        if (!links?.[RelType.BOARDS_PUBLISH]) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Publish link is missing for this board ${boardId}`);\n        }\n        const url = getURLFromLinks(links, RelType.BOARDS_PUBLISH, { boardId });\n        const requestBody: PublishOptions = { boardTitle, boardSubTitle, showPosterName };\n        const response = await this._doPost(\n            url,\n            {\n                ...headers,\n                'Content-Type': JSON_MIME_TYPE,\n            },\n            JSON.stringify(requestBody),\n            [ 201 ]\n        );\n        return response.json();\n    }\n\n    /**\n     * Unpublishes a specific board\n     */\n    async unpublishBoard({ boardId, links }: { boardId: string, links: BoardLinks }): Promise<void> {\n        if (!links?.[RelType.BOARDS_UNPUBLISH]) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, `Unpublish link is missing for this board ${boardId}`);\n        }\n        const url = getURLFromLinks(links, RelType.BOARDS_UNPUBLISH, { boardId });\n        await this._doPost(url, headers, undefined, [ 204 ]);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage } from '../core/ItemLoader';\nimport type { BoardConfig } from './BoardSource';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { default as Board } from './Board';\n\nimport BoardsInterface from '../interface/BoardsInterface';\nimport { BoardUpdater } from './Board';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type { RemoteBoard } from '../interface/BoardModel';\n\nexport default class BoardListLoader implements IItemLoader<BoardConfig> {\n    private _boardsInterface: BoardsInterface;\n    private _core: ISAMCorePrivate;\n\n    constructor(core: ISAMCorePrivate) {\n        this._core = core;\n        this._boardsInterface = new BoardsInterface(core);\n    }\n\n    private async observeBoardsFolder(remoteBoards: RemoteBoard[]): Promise<AdobeAsset> {\n        // We fetched boards by the parent asset ID so each board will have the same boardsAssetId, just observe one of them\n        const boardsAssetId = remoteBoards[0]['board:context']['boardsAssetId'];\n        return this._core.hostAssetContext.getAssetWithCloudID(boardsAssetId);\n    }\n\n    async loadPage(options: IItemLoaderOptions<BoardConfig>): Promise<ILoadedPage<BoardConfig>> {\n        return this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<BoardConfig>): Promise<ILoadedPage<BoardConfig>> {\n        const { filter, implicitFilter } = options;\n        const baseAssetId = implicitFilter.baseAssetId || filter.baseAssetId;\n        const shouldGetDirectlyInBaseAsset = implicitFilter.shouldGetDirectlyInBaseAsset || filter.shouldGetDirectlyInBaseAsset || false;\n        const remoteBoards = await this._boardsInterface.getBoards({ baseAssetId, shouldGetDirectlyInBaseAsset });\n        const session = this._core._getAssetPool().createLoaderUpdateSession<Board>(Date.now());\n        const boards = BoardUpdater.updateRemoteItems(session, remoteBoards);\n        session.commit();\n\n        if (remoteBoards.length > 0) {\n            this.observeBoardsFolder(remoteBoards).then((folder) => {\n                // pin this to memory so Garbage Collector does not remove it as long as the list is still kept in memory\n                implicitFilter._monitoredFolder = folder;\n            });\n        }\n\n        return {\n            items: boards,\n            total: boards.length,\n            mostRecentValidMutation: Date.now(),\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type {\n    AddPostOptions,\n    BoardOrderOptions,\n    CreateBoardOptions,\n    GetBoardsOptions,\n    GetPostByBoardAndPostIdOptions,\n    PublishBoardOptions,\n    RemoteBoard,\n    RemovePostOptions,\n    UpdateBoardOptions,\n    UpdateBoardPostOptions,\n    UploadFileOptions,\n    ValidateBoardNameForCreateOptions,\n    ValidateBoardNameForUpdateOptions,\n    ValidateBoardNameOptions,\n    AddBoardPostOptions,\n    PostOrderOptions\n} from '../interface/BoardModel';\nimport { default as BoardOrder } from './BoardOrder';\nimport type { BoardSource } from './BoardSource';\nimport type ItemPool from '../core/ItemPool';\n\nimport Board from './Board';\nimport { PostType, BoardType, MAX_POST_FILE_NAME_LENGTH } from '../interface/BoardModel';\nimport { default as BoardFilter, type BoardFilterOptions } from './BoardFilter';\nimport { BoardUpdater } from './Board';\nimport BoardsInterface from '../interface/BoardsInterface';\nimport SAMError, { isSAMError, SAMErrorCode } from '../core/SAMError';\nimport BoardListLoader from './BoardListLoader';\nimport ItemSource from '../core/ItemSource';\nimport { key, weakCache } from '../core/decorators';\nimport { trace, traceableAs } from '../core/decorators/trace';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport { CLOUD_CONTENT_ROOT_FOLDER, Permission } from '@sam-js-src/interface/AssetModel';\nimport { synchronized } from '../core/decorators';\nimport { waitForListLoad } from '../utils/waitForListLoad';\nimport { cleanAssetName, validateAssetName } from '../assets/AssetUtils';\n// TODO[ACPCEDU-3818]: move this validateString to a more generic utils folder\nimport { validateString } from '../utils/classroomUtils';\nimport type Post from './Post';\nimport { AssetListStatus } from '@sam-js-src/core/ItemLoaderState';\nimport PostOrder from './PostOrder';\n\n\n@traceableAs('BoardContext')\nexport default class BoardContext implements ISAMObject, SAM.BoardContext {\n    private _boardsInterface = new BoardsInterface(this._core);\n\n    constructor(readonly _core: ISAMCorePrivate, private _assetPool: ItemPool<AdobeAsset | Board>) {}\n\n    readonly _boardUpdater = BoardUpdater;\n\n    /**\n     * Updates a board asset within the asset pool given the remote board data and the local board instance, returning the mapped local Board instance\n     * @param board The board to update\n     * @param updatedRemoteSourceBoard The remote board data to update the local board with\n     * @param hasLoadedPosts Whether the board has loaded its posts. If true, the board will be marked as having loaded its posts.\n     * @returns The updated local board\n     */\n    private updateBoardInPool({ board, remoteBoard, hasLoadedPosts }: { board?: Board, remoteBoard: Partial<RemoteBoard>, hasLoadedPosts?: boolean }): Board {\n        const session = this._core._getAssetPool().createMutationSession<Board>();\n        let updatedBoard: Board;\n        if (board) {\n            BoardUpdater.updateLocalItem(session, board, remoteBoard);\n            updatedBoard = board;\n        } else {\n            updatedBoard = BoardUpdater.updateRemoteItem(session, remoteBoard);\n        }\n        session.commit();\n        // only update the _hasLoadedPosts if hasLoadedPosts is provided\n        if (hasLoadedPosts !== undefined) {\n            updatedBoard._hasLoadedPosts = hasLoadedPosts;\n        }\n        return updatedBoard;\n    }\n\n    /**\n     * Retrieves a board asset from the asset pool, or fetches it from the server if it doesn't exist locally or does not have posts loaded\n     * @throws {SAMError} if the board is discarded\n     * @example <caption>Get a board by ID</caption>\n     * const board = await boardContext.getBoardById('board-id');\n     */\n    @keepAlive\n    @synchronized\n    async getBoardById(@key boardId: string): Promise<Board> {\n        const existingBoard = this._core._getAssetPool().getLocalItemById<Board>(boardId);\n        const currentBoard = (existingBoard?._hasLoadedPosts) ? existingBoard : await this._fetchBoardById(boardId);\n\n        // Discarded boards are not allowed to be returned\n        if (currentBoard?.isDiscarded) {\n            throw SAMError.create(SAMErrorCode.NOT_FOUND, `Board ${boardId} is discarded`);\n        }\n        return currentBoard;\n    }\n\n    /**\n     * Retrieves a board asset from the asset pool, or fetches it from the server if it doesn't exist locally.\n     * The retrieved board may not have posts loaded.\n     * @throws {SAMError} if the board ID is not provided or is invalid\n     * @package -- for SAM.js internal use only\n     */\n    @keepAlive\n    @synchronized\n    async _getBoard(@key boardId: string): Promise<Board> {\n        const existingBoard = this._core._getAssetPool().getLocalItemById<Board>(boardId);\n        if (existingBoard) {\n            return existingBoard;\n        }\n        return this._fetchBoardById(boardId);\n    }\n\n    /**\n     * Fetches a board asset from the server, regardless of whether it's cached in the pool or not\n     * Removes the board from the pool if the board is not found or the user does not have access to it based on the service call error\n     * @throws {SAMError} if the board ID is not provided or is invalid\n     * @package -- for SAM.js internal use only\n     */\n    @keepAlive\n    @synchronized\n    async _fetchBoardById(@key boardId: string, promiseToResolve?: Promise<void>): Promise<Board> {\n        if (!validateString([ boardId ], 'Board ID', false)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Board ID is required');\n        }\n        let remoteBoard: RemoteBoard | undefined;\n        let errorFromBoardFetch: unknown;\n        try {\n            remoteBoard = await this._boardsInterface.getBoard(boardId);\n        } catch (error) {\n            errorFromBoardFetch = error;\n        }\n\n        await promiseToResolve;\n\n        if (remoteBoard) {\n            // Mark the board as having loaded its posts as posts are always\n            // provided in the GET boards/<id> response.\n            // Note though that posts are NOT included in GET boards response\n            return this.updateBoardInPool({ remoteBoard, hasLoadedPosts: true });\n        }\n\n        // If the board is not found or the user does not have access to it, we need to remove the board from the pool\n        if (isSAMError(errorFromBoardFetch)) {\n            if (errorFromBoardFetch.code === SAMErrorCode.NOT_FOUND || errorFromBoardFetch.code === SAMErrorCode.ACCESS_DENIED) {\n                // retrieve the board from the pool\n                const cachedBoard = this._core._getAssetPool().getLocalItemById<Board>(boardId);\n                if (cachedBoard) {\n                    // If the board is found in the pool, we need to remove the board from the pool\n                    // since the user is not allowed to access the board\n                    this._discardBoardFromPool(cachedBoard);\n                }\n            }\n        }\n        throw errorFromBoardFetch;\n    }\n\n    /**\n     * Determine if the given name is valid for creating a board\n     * @throws {SAMError} if the name is invalid\n     *\n     * @example <caption>Validate a board name before creating a board</caption>\n     * try {\n     *  await boardContext.validateBoardNameForCreate({ name: 'My Board', baseAssetId: '123@AdobeOrg' });\n     * } catch (error) {}\n     */\n    async validateBoardNameForCreate({ name, baseAssetId, shouldValidateDirectlyInBaseAsset = false }: ValidateBoardNameForCreateOptions): Promise<void> {\n        await this._validateBoardName({ name, baseAssetId, shouldValidateDirectlyInBaseAsset });\n    }\n\n    /**\n     * Determine if the given name is valid when updating a board\n     * @throws {SAMError} if the name is invalid\n     *\n     * @example <caption>Validate a board name before updating a board</caption>\n     * try {\n     *  await boardContext.validateBoardNameForUpdate({ name: 'My Board', baseAssetId: '123@AdobeOrg', boardId: 'board-id' });\n     * } catch (error) {}\n     */\n    async validateBoardNameForUpdate({ name, baseAssetId, boardId, shouldValidateDirectlyInBaseAsset = false }: ValidateBoardNameForUpdateOptions): Promise<void> {\n        try {\n            // TODO[ACPCEDU-3818]: throw SAMError instead of Error\n            validateString([ baseAssetId, boardId ], 'BaseAssetId and boardId');\n        } catch (error) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Base asset ID and board ID are required for name validation'\n            );\n        }\n\n        await this._validateBoardName({ name, baseAssetId, boardId, shouldValidateDirectlyInBaseAsset });\n    }\n\n    /**\n     * Validates a board name\n     * @param name The name to validate\n     * @param baseAssetId The base asset ID. If provided, the board name will be validated against the boards under the base asset.\n     * @param boardId The board ID. If provided, the board name will be validated against the board itself.\n     * @param shouldValidateDirectlyInBaseAsset Whether to validate directly in the base asset. If true, the board name will be validated against the boards under the base asset.\n     */\n    private async _validateBoardName({ name, baseAssetId, boardId, shouldValidateDirectlyInBaseAsset = false }: ValidateBoardNameOptions): Promise<void> {\n        let assetList: Board[] = [];\n        // If baseAssetId is provided, we need to get the list of boards under the base asset\n        if (baseAssetId) {\n            const filter = this.getBoardFilter({ baseAssetId });\n            const order = this.getBoardOrder();\n            const boardList = this.getBoards({ baseAssetId, shouldGetDirectlyInBaseAsset: shouldValidateDirectlyInBaseAsset }).getList(order, filter, { loadAllPages: true });\n            await waitForListLoad(boardList);\n            // throw SAMError if the list fails to load\n            if (boardList.status === AssetListStatus.HadLoaderErrors) {\n                throw SAMError.create(SAMErrorCode.NETWORK_ERROR, 'Failed to load boards');\n            }\n            assetList = boardList.items;\n        }\n\n        const locale = this._core._environment.getValue('LOCALE');\n        return validateAssetName({\n            name,\n            assetId: boardId,\n            assetList,\n            locale,\n            // in case the asset is not a board, we should return false and not throw an error if the asset does not have a displayName\n            getOtherAssetName: (asset: AdobeAsset) => asset instanceof Board ? asset.displayName : asset.name\n        });\n    }\n\n    /**\n     * Creates a new board asset\n     * @throws {SAMError} if:\n     * - the board name is invalid\n     * - base asset ID or type is missing\n     * - type is CLASSROOM and classroomId is missing in additionalData\n     * @example <caption>Create a new board</caption>\n     * const board = await boardContext.createBoard({\n     *     name: 'My Board',\n     *     baseAssetId: 'base-asset-id',\n     *     type: BoardType.CLASSROOM,\n     *     additionalData: { classroomId: 'classroom-id' }\n     * });\n     */\n    @trace\n    async createBoard(data: CreateBoardOptions): Promise<Board> {\n        const { name, baseAssetId, shouldCheckForDuplicateName = true, type, additionalData, posts = [] } = data;\n        if (!baseAssetId || !type) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Base asset ID and type are required for board creation'\n            );\n        }\n\n        if (type === BoardType.CLASSROOM && !additionalData?.classroomId) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Classroom ID is required for classroom boards'\n            );\n        }\n        // If shouldCheckForDuplicateName is false, we don't need to validate the board name by not passing in baseAssetId\n        await this._validateBoardName({ name, baseAssetId: shouldCheckForDuplicateName ? baseAssetId : undefined });\n\n        if (posts.length > 0) {\n            data.posts = await Promise.all(posts.map(post => this.processNewPost(post)));\n        }\n\n        const remoteBoard = await this._boardsInterface.createBoard(data);\n        // Mark the board as having loaded its posts as posts can be added as params to createBoard\n        return this.updateBoardInPool({ remoteBoard, hasLoadedPosts: true });\n    }\n\n    /**\n     * Retrieves the uploads folder for the current user.\n     * If the uploads folder does not exist, it will be created.\n     * @throws {SAMError} if the uploads folder cannot be retrieved or created\n     */\n    private async _getUserHomeUploadsFolder(): Promise<AdobeAsset> {\n        const uploadsPath = `${CLOUD_CONTENT_ROOT_FOLDER}/Uploads`;\n\n        try {\n            return await this._core.hostAssetContext.getAssetWithRepoPath(uploadsPath);\n        } catch (error) {\n            if (isSAMError(error) && error.code === SAMErrorCode.NOT_FOUND) {\n                const rootFolder = await this._core.hostAssetContext.getRootFolder();\n                return rootFolder.createFolder(uploadsPath.split('/').pop()!);\n            }\n            throw SAMError.wrapErrorIfNeeded(SAMErrorCode.INTERNAL_ERROR, 'Failed to get uploads folder', error);\n        }\n    }\n\n    /**\n     * Uploads a file. If no parentAssetId is provided, the file will be uploaded to the user's Uploads folder.\n     * @throws {SAMError} if the file cannot be uploaded or the parent asset cannot be found\n     */\n    private async _uploadFileForAssetLinkPost(post: UploadFileOptions): Promise<AdobeAsset> {\n        let destinationFolder: AdobeAsset;\n        if (post.parentAssetId) {\n            destinationFolder = await this._core.hostAssetContext.getAssetWithCloudID(post.parentAssetId);\n        } else {\n            destinationFolder = await this._getUserHomeUploadsFolder();\n        }\n        return destinationFolder.importFile(post.blob, post.fileName, post.mediaType, true, 0, false);\n    }\n\n    /**\n     * Updates a board and update the local board in the asset pool\n     * @param updateData The update data\n     */\n    private async _updateBoardAfterPatchingBoard(updateData: UpdateBoardOptions): Promise<void> {\n        const remoteBoard = await this._boardsInterface.updateBoard(updateData);\n        if (remoteBoard) {\n            // Mark the board as having loaded its posts as posts will be returned in the updateBoard response if there are any\n            this.updateBoardInPool({ remoteBoard, hasLoadedPosts: true });\n        }\n    }\n\n    /**\n     * Validates incoming new post data and handles uploading of files if needed.\n     * @returns a modified post data object\n     * @throws {SAMError} for AssetLink posts:\n     *   - If the blob is provided without fileName\n     *   - If the blob's filename is invalid\n     *   - If the blob is provided and the parent folder cannot be found or created\n     *   - If neither an assetId nor a blob is provided\n     * @throws {SAMError} for Text posts:\n     *   - If the text is not provided\n     */\n    private async processNewPost(postData: AddBoardPostOptions): Promise<AddBoardPostOptions> {\n        if (postData.type === PostType.AssetLink) {\n            if (postData.assetId && postData.blob) {\n                throw SAMError.create(\n                    SAMErrorCode.BAD_REQUEST,\n                    'Asset ID and blob cannot be provided together for asset link posts'\n                );\n            } else if (!postData.assetId && postData.blob) {\n                if (!postData.fileName) {\n                    throw SAMError.create(\n                        SAMErrorCode.BAD_REQUEST,\n                        'File name is required for asset link posts with a blob'\n                    );\n                }\n\n                const cleanedFileName = cleanAssetName({ name: postData.fileName, maxLength: MAX_POST_FILE_NAME_LENGTH, shouldValidate: true });\n                const uploadOptions: UploadFileOptions = {\n                    blob: postData.blob,\n                    fileName: cleanedFileName,\n                    mediaType: postData.mediaType,\n                    parentAssetId: postData.parentAssetId\n                };\n\n                const uploadedAsset = await this._uploadFileForAssetLinkPost(uploadOptions);\n                postData.assetId = uploadedAsset.id;\n                postData.fileName = uploadedAsset.name;\n            } else if (!postData.assetId) {\n                throw SAMError.create(\n                    SAMErrorCode.BAD_REQUEST,\n                    'Asset ID or blob is required for asset link posts'\n                );\n            }\n        } else if (postData.type === PostType.Text) {\n            if (!postData.text) {\n                throw SAMError.create(\n                    SAMErrorCode.BAD_REQUEST,\n                    'Text is required for text posts'\n                );\n            }\n        }\n\n        return postData;\n    }\n\n    /**\n     * Adds a new post to a board.\n     * - If the type is AssetLink:\n     *   - If assetId is provided then the board will create a reference to that asset. The blob is ignored in this case\n     *   - If a blob is provided then the file will be uploaded and a new asset will be created from it which the board will reference\n     * - If the type is Text then the board will create a new text post with the provided text\n     * @throws {SAMError} for AssetLink posts:\n     *   - If the blob is provided without fileName\n     *   - If the blob's filename is invalid\n     *   - If the blob is provided and the parent folder cannot be found or created\n     *   - If neither an assetId nor a blob is provided\n     * @throws {SAMError} for Text posts:\n     *   - If the text is not provided\n     * @example <caption>Add a post to the board</caption>\n     * await boardContext.addPost({ boardId: 'board-id', type: 'text', text: 'Hello, world!' });\n     * await boardContext.addPost({ boardId: 'board-id', type: 'assetLink', assetId: 'asset-id' });\n     * await boardContext.addPost({ boardId: 'board-id', type: 'assetLink', blob: new Blob([ 'Hello, world!' ]), fileName: 'hello.txt' });\n     */\n    @trace\n    async addPost({ boardId, ...post }: AddPostOptions): Promise<void> {\n        const processedPost = await this.processNewPost(post);\n\n        const updateData: UpdateBoardOptions = {\n            boardId,\n            postsToAdd: [ processedPost ]\n        };\n        await this._updateBoardAfterPatchingBoard(updateData);\n    }\n\n    /**\n     * Removes a post from a board asset\n     * @example <caption>Remove a post from the board</caption>\n     * await boardContext.removePost({ boardId: 'board-id', postId: 'post-id' });\n     */\n    async removePost({ boardId, postId }: RemovePostOptions): Promise<void> {\n        const updateData: UpdateBoardOptions = {\n            boardId,\n            postsToRemove: [ postId ]\n        };\n        await this._updateBoardAfterPatchingBoard(updateData);\n    }\n\n    /**\n     * Updates a post on a board asset\n     */\n    @trace\n    async updatePost({ boardId, ...data }: UpdateBoardPostOptions): Promise<void> {\n        const updateData: UpdateBoardOptions = {\n            boardId,\n            postsToUpdate: [ data ]\n        };\n        await this._updateBoardAfterPatchingBoard(updateData);\n    }\n\n    /**\n     * Retrieves all boards under a parent asset\n     */\n    @keepAlive\n    @weakCache\n    getBoards(@key { baseAssetId, shouldGetDirectlyInBaseAsset }: GetBoardsOptions): BoardSource {\n        if (!baseAssetId) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Base asset ID is required for fetching boards'\n            );\n        }\n        const loader = new BoardListLoader(this._core);\n        const implicitFilter = new BoardFilter({\n            baseAssetId,\n            shouldGetDirectlyInBaseAsset: shouldGetDirectlyInBaseAsset || false\n        });\n        return new ItemSource(this._assetPool as ItemPool<Board>, [ loader ], implicitFilter);\n    }\n\n    private _cleanBoardName(name: string): string {\n        return name.trimEnd();\n    }\n\n    /**\n     * Validates and cleans a board name before renaming a board\n     * @throws {SAMError} If the board name is invalid\n     * @param boardId The board ID\n     * @param newName The new name\n     * @param baseAssetId The base asset ID\n     * @returns The cleaned board name\n     */\n    @synchronized\n    private async _validateAndCleanBoardNameBeforeRenamingBoard({ boardId, newName, baseAssetId }: {boardId: string, newName: string, baseAssetId: string}): Promise<string> {\n        await this._validateBoardName({ name: newName, baseAssetId, boardId });\n        return `${this._cleanBoardName(newName)}${Board.boardNameSuffix}`;\n    }\n\n    /**\n     * Updates the description along with other manifest metadata of a board asset. To add/remove post, use addPost or removePost instead\n     */\n    @trace\n    async updateBoard({ boardId, description, displayName }: UpdateBoardOptions): Promise<void> {\n        let board: Board | undefined;\n        let cleanedBoardName: string | undefined;\n\n        const shouldUpdateBoardName = displayName !== undefined;\n        const isNewBoardDescriptionProvided = description !== undefined;\n        const shouldGetBoardForUpdate = isNewBoardDescriptionProvided || shouldUpdateBoardName;\n\n        if (shouldGetBoardForUpdate) {\n            board = await this._getBoard(boardId);\n        }\n\n        if (shouldUpdateBoardName) {\n            cleanedBoardName = await this._validateAndCleanBoardNameBeforeRenamingBoard({ boardId, newName: displayName, baseAssetId: board?._idOfBaseAsset as string });\n        }\n\n        const shouldUpdateBoardDescription = isNewBoardDescriptionProvided && description !== board?.description;\n        const shouldUpdateBoard = shouldUpdateBoardDescription || shouldUpdateBoardName;\n\n        if (shouldUpdateBoard) {\n            const updateData: UpdateBoardOptions = {\n                boardId,\n                description,\n                displayName: cleanedBoardName\n            };\n            await this._updateBoardAfterPatchingBoard(updateData);\n        }\n    }\n\n    private _discardBoardFromPool(board: Board): void {\n        const session = this._core._getAssetPool().createUpdateSession<Board>();\n        BoardUpdater.updateLocalItem(session, board, { effectivePermission: Permission.None });\n        session.queueDiscardedItem(board);\n        session.commit();\n        this._core._getAssetPool().removeLocalItems([ board.id ]);\n    }\n\n    /**\n     * Deletes a board asset permanently\n     */\n    async discardBoard(boardId: string): Promise<void> {\n        const board = await this._getBoard(boardId);\n        await this._boardsInterface.discardBoard(boardId, board.links);\n        return this._discardBoardFromPool(board);\n    }\n\n\n    /**\n     * Publishes a board asset\n     * This also optimistically updates the local source board to keep it in sync.  If the remote update fails, this can lead to a temporary inconsistency.\n     * @returns the public/published board\n     * @experimental Boards functionality is still in progress, this method is subject to change ACPCEDU-3888\n     * @throws {SAMError} if the board is read-only or user does not have permission to publish it\n     * @example <caption>Publish the board with a custom title and subtitle</caption>\n     * const publishedBoard = await boardContext.publishBoard({ boardId: 'urn-board-id', boardTitle: 'Published Biology Board', boardSubTitle: 'By Biology - Period 2', showPosterName: true });\n     */\n    @trace\n    async publishBoard(options: PublishBoardOptions): Promise<Board> {\n        const { boardId, boardSubTitle, boardTitle, showPosterName } = options;\n        const sourceBoard = await this._getBoard(boardId);\n        if (!sourceBoard.canPublish) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'The board is read-only and cannot be published'\n            );\n        }\n\n        const publishedRemoteBoard = await this._boardsInterface.publishBoard({\n            boardId,\n            links: sourceBoard.links,\n            boardTitle,\n            boardSubTitle,\n            showPosterName\n        });\n\n        // Update the source board with the published board info\n        const updatedLocalSourceBoard: Partial<RemoteBoard> = {\n            'board:publishedBoard': {\n                'repo:assetId': publishedRemoteBoard['repo:assetId'],\n                'board:showPosterName': showPosterName\n            },\n        };\n        // Update source board\n        this.updateBoardInPool({ board: sourceBoard, remoteBoard: updatedLocalSourceBoard });\n        // Update child published board. Remote data from Board service always contains posts if there are any for published board at all\n        return this.updateBoardInPool({ remoteBoard: publishedRemoteBoard, hasLoadedPosts: true });\n    }\n\n    /**\n     * Unpublishes a board asset\n     * This also optimistically updates the local source board to keep it in sync.  If the remote update fails, this can lead to a temporary inconsistency.\n     * @experimental Boards functionality is still in progress, this method is subject to change ACPCEDU-1013\n     * @throws {SAMError} if the board is not published or user does not have permission to unpublish it\n     * @example <caption>Unpublish the board</caption>\n     * await boardContext.unpublishBoard('board-id');\n    */\n    @trace\n    async unpublishBoard(boardId: string): Promise<void> {\n        const sourceBoard = await this._getBoard(boardId);\n        if (!sourceBoard.canUnpublish) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'The board is not published so cannot be unpublished'\n            );\n        }\n\n        await this._boardsInterface.unpublishBoard({ boardId, links: sourceBoard.links });\n        // discarding the published board if it exists in the asset pool\n        const publishedBoardId = sourceBoard.publishedBoardInfo?.boardId as string;\n        const publishedBoard = this._assetPool.getLocalItemById<Board>(publishedBoardId);\n        if (publishedBoard) {\n            this._discardBoardFromPool(publishedBoard);\n        }\n        // Update the source board's published board info to undefined\n        this.updateBoardInPool({ board: sourceBoard, remoteBoard: {\n            'board:publishedBoard': undefined\n        } });\n    }\n\n    /**\n     * Creates a BoardOrder object\n     *\n     * @example <caption>Create a BoardOrder</caption>\n     * const order = boardContext.getBoardOrder({ direction: 'descending', field: 'created' });\n     */\n    getBoardOrder(options?: Partial<BoardOrderOptions>): BoardOrder {\n        const defaultOptions: BoardOrderOptions = {\n            direction: 'ascending',\n            field: 'name'\n        };\n        const mergedOptions = Object.assign({}, defaultOptions, options);\n        return new BoardOrder(mergedOptions.direction, mergedOptions.field);\n    }\n\n    /**\n     * Creates a BoardFilter object\n     *\n     * @example <caption>Create a BoardFilter</caption>\n     * const filter = boardContext.getBoardFilter({ baseAssetId: 'base-asset-id });\n     */\n    getBoardFilter(options: Partial<BoardFilterOptions>): BoardFilter {\n        return new BoardFilter(options);\n    }\n\n    /**\n     * Creates a PostOrder object\n     *\n     * @example <caption>Create a PostOrder</caption>\n     * const order = boardContext.getPostOrder({ direction: 'descending' });\n     */\n    getPostOrder(options: Partial<PostOrderOptions> = {}): PostOrder {\n        const defaultOptions: PostOrderOptions = {\n            direction: PostOrder.default.direction,\n            field: PostOrder.default.field\n        };\n        const mergedOptions = Object.assign({}, defaultOptions, options);\n        return new PostOrder(mergedOptions.direction, mergedOptions.field);\n    }\n\n    /**\n     * Retrieves a post by board ID and post ID\n     * @throws {SAMError} if the post is not found\n     * @example <caption>Get a post by board ID and post ID</caption>\n     * const post: Post = await boardContext.getPostByBoardAndPostId({ boardId: 'board-id', postId: 'post-id' });\n     */\n    async getPostByBoardAndPostId({ boardId, postId }: GetPostByBoardAndPostIdOptions): Promise<Post> {\n        const board = await this.getBoardById(boardId);\n        const post = board._postPool.getLocalItemById(postId);\n        if (!post) {\n            throw SAMError.create(SAMErrorCode.NOT_FOUND, `Post with ID ${postId} not found`);\n        }\n        return post;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\n\nimport type { default as Library } from './Library';\n\nimport ImplicitAdobeAssetFilterBase from '../assets/ImplicitAdobeAssetFilterBase';\nimport { LibraryOwnerFilter, LibraryRolesFilter } from '../interface/LibraryModel';\n\nimport { itemMatchesOwnerFilter, itemMatchesRolesFilter } from './LibraryFilterUtils';\nimport type { LibraryFilterOptions } from './LibraryFilter';\n\ntype ImplicitLibraryFilterOptions = Pick<LibraryFilterOptions, 'owner' | 'roles'>;\n\n/**\n * Internal filter that is for ensuring only libraries that are not hidden, discarded, etc. are shown in Library lists.\n * The Implicit Filter determines the nature of the LibrarySource.\n */\nexport default class ImplicitLibraryFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<Library> {\n    static TrainingSets = new ImplicitLibraryFilter({\n        owner: [ LibraryOwnerFilter.All ], roles: [ LibraryRolesFilter.TrainingSet ]\n    });\n\n    readonly _owner?: Set<LibraryOwnerFilter>;\n    readonly _roles?: Set<LibraryRolesFilter>;\n\n    constructor(readonly filterOptions?: ImplicitLibraryFilterOptions) {\n        super({ _isSharedWithYou: true });\n\n        if (filterOptions?.owner && filterOptions.owner.length > 0) {\n            this._owner = new Set([ ...filterOptions.owner ]);\n        }\n        if (filterOptions?.roles && filterOptions.roles.length > 0) {\n            this._roles = new Set([ ...filterOptions.roles ]);\n        }\n    }\n\n    // used by ItemList and ItemLoaderState and is called when asset change notifications come in to check if the asset is still eligible to be on a particular list\n    matches(item: Library): boolean {\n        if (!item.isLibrary) {\n            return false;\n        }\n        if (this._owner && !itemMatchesOwnerFilter(item, this._owner)) {\n            return false;\n        }\n        if (this._roles && !itemMatchesRolesFilter(item, this._roles)) {\n            return false;\n        }\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type LibraryInterface from '../interface/LibraryInterface';\nimport type { LibraryListParameters, LibraryData, LibrariesResponse, MelvilleLink, OwnerParameters, RolesParameters } from '../interface/LibraryModel';\nimport { LibraryProjectFilterEnum } from '../interface/LibraryModel';\nimport type Library from './Library';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type LibraryOrder from './LibraryOrder';\nimport { OrderFieldToLibraryOrderBy } from './LibraryOrder';\nimport LibraryFilter from './LibraryFilter';\n\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type ItemUpdater from '../core/ItemUpdater';\nimport type ImplicitLibraryFilter from './ImplicitLibraryFilter';\nimport type { IItemSourceConfig } from '../core/ItemList';\nimport { LazyLoadManager } from '../core/decorators/LazyLoadManager';\nimport { STORAGE_ASSIGNEE_CHANGED } from '../assets/AssetEvents';\nimport type Project from '../projects/Project';\nimport type { ISAMCorePrivate } from '../indexPrivate';\n\n// Load Libraries from Melville\nexport default class LibraryListLoader<Config extends IItemSourceConfig> implements IItemLoader<Config> {\n\n    constructor(\n        private _libraryPool: ItemPool<Library | AdobeAsset>,\n        private _libraryInterface: LibraryInterface,\n        private _libraryUpdater: ItemUpdater<Library, Partial<LibraryData>>,\n        private _core: ISAMCorePrivate\n    ) {}\n\n    // only supports LibraryFilter\n    supportsFilter(filter: LibraryFilter): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<Config>): Promise<ILoadedPage<Config>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<Config>, pageLink?: MelvilleLink): Promise<ILoadedPage<Config>> {\n        let result: LibrariesResponse;\n        const filter = options.filter as LibraryFilter;\n\n        if (pageLink) {\n            if (options.loadOptions?.limit) {\n                pageLink.href = pageLink.href.replace(/limit=[0-9]*/, `limit=${options.loadOptions.limit}`);\n            }\n            result = await this._libraryInterface.getLibrariesWithLink(pageLink);\n        } else {\n            const {  limit } = options.loadOptions ?? {};\n            const implicitFilter = options.implicitFilter as ImplicitLibraryFilter;\n            const order = options.order as LibraryOrder;\n\n            // Give preference to the implicit filter. Use default if filter is EverythingFilter.\n            const ownerFilter = implicitFilter._owner || filter._owner || LibraryFilter.DEFAULT._owner;\n            const rolesFilter = implicitFilter._roles || filter._roles;\n\n            // Move filters into query parameters, making sure to sort the arrays so that the eventual query string is deterministic.\n            const queryParams: LibraryListParameters = {};\n            if (ownerFilter && !filter._reference) {\n                // Only set owner parameter if filter._reference doesn't exist\n                queryParams.owner = [ ...ownerFilter ].sort().join(',') as OwnerParameters;\n            }\n            if (filter._reference) {\n                queryParams.references = filter._reference;\n            }\n            if (rolesFilter) {\n                queryParams.roles = [ ...rolesFilter ].sort().join(',') as RolesParameters;\n            }\n            if (filter._project) {\n                queryParams.team = filter._project;\n            }\n            if (filter._publishMetadata) {\n                queryParams.itemFilter = filter._publishMetadata;\n            }\n            queryParams.orderBy = order.direction === 'ascending' ? OrderFieldToLibraryOrderBy[order.field] : `-${OrderFieldToLibraryOrderBy[order.field]}`;\n            if (limit) {\n                queryParams.limit = limit;\n                if (!queryParams.start) {\n                    queryParams.start = 0;\n                }\n            }\n            // The selector specifies what data will be returned on each library.\n            // Details includes extra information about each library, including the library's custom thumbnail.\n            queryParams.selector = 'rendition_grid,collaboration,details';\n\n            result = await this._libraryInterface.getLibraries(queryParams);\n        }\n\n        // update the libraries data with referenced by project data\n        if (filter._project) {\n            this._decorateLibraryDataWithReferencedByProject(result.libraries, filter._project);\n        }\n\n\n        // Libraries listings from Melville are considered \"USS\" sources (with the current exception of a public libraries-only listing), and may have stale data.\n        // To prevent it from potentially overwriting fresh RAPI data within the USS latency window, we will use\n        // 'createLoaderUpdateSession' instead of 'createLoaderMutationSession' and this update will be ignored if there were local changes later than this timestamp.\n        const latency = this._libraryPool._core._environment.getValue('USS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n        const session = this._libraryPool.createLoaderUpdateSession<Library>(mostRecentValidMutation);\n        const items = this._libraryUpdater.updateRemoteItems(session, result.libraries); // get or create Library instances\n        items.forEach(library => library._setLibraryLoadState('LOADED'));\n        // Mark storage_assignee as loaded, so that we do not trigger a lazy load of the value.\n        items.forEach(library => LazyLoadManager.updatedByItemUpdater(library, STORAGE_ASSIGNEE_CHANGED));\n        session.commit(); // put items in the pool\n\n        // Update project with inaccessible references if available\n        if (filter._project) {\n            this._updateProjectInaccessibleReferences(filter._project, result.inaccessibleReferences);\n        }\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<Config> | undefined;\n        const nextPageLink = result._links?.next;\n        if (nextPageLink) {\n            loadNextPage = (options: IItemLoaderOptions<Config>) =>\n                this._loadPage(options, nextPageLink);\n        }\n\n        return {\n            items,\n            total: result.total_count, // total number of libraries in the account (not the page)\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n\n    /**\n     * When requesting libraries with the references filter for a specific project,\n     * Melville returns a list of libraries and includes a 'reference' boolean field to indicate\n     * if the library is referenced by the project vs. when the library is in the project itself.\n     *\n     * request: team=project-123&references=only\n     * response: from Melville:\n     *\n     * {\n     *  \"libraries\": [\n     *      {\n     *          \"library_urn\": \"library-in-project-123\", // library is in the project\n     *      },\n     *      {\n     *          \"library_urn\": \"library-referenced-by-project-123\", // library is referenced by the project\n     *          \"reference\": true\n     *      }\n     *  ]\n     * }\n     *\n     * This method supplements the Melville data by adding a 'referenced_by_project' field to the library data that includes the projectId\n     * used to request the data. This allows us to use the item updater to update the libraries and track which libraries are referenced by a project.\n     *\n     * @param libraries - The Melville libraries data.\n     * @param projectId - The project ID that was used to request the referenced libraries.\n     */\n    private _decorateLibraryDataWithReferencedByProject(libraries: LibraryData[], projectId: string) {\n        if (projectId === LibraryProjectFilterEnum.All || projectId === LibraryProjectFilterEnum.None) {\n            return;\n        }\n        libraries.forEach(library => {\n            const { reference } = library;\n            if (reference && projectId) {\n                library.referenced_by_project = { projectId, reference };\n            }\n        });\n    }\n\n    /**\n     * Updates the project with inaccessible references from the Melville response.\n     * inaccessibleReferences are only returned by Melville when requesting libraries\n     * with a reference filter for a specific project.\n     *\n     * @param inaccessibleReferences - Any inaccessible references from Melville\n     * @param projectId - The project ID that was used to request the referenced libraries\n     */\n    private _updateProjectInaccessibleReferences(projectId: string, inaccessibleReferences?: string[]) {\n        if (!inaccessibleReferences) {\n            return;\n        }\n\n        const projectContext = this._core._getProjectContext();\n        // Only update Projects if ProjectContext is already loaded\n        if (!projectContext) { return; }\n        const project = projectContext._assetPool.getLocalItemById<Project>(projectId);\n\n        // if project is not already found in the pool, skip updating inaccessible references\n        if (!project) {\n            return;\n        }\n\n        // Update the project with inaccessible references\n        const session = projectContext._assetPool.createUpdateSession<Project>('update project inaccessible references');\n        projectContext._projectUpdater.updateLocalItem(session, project, { inaccessibleReferences });\n        session.commit();\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type LibraryInterface from '../interface/LibraryInterface';\nimport type Library from './Library';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport type ItemPool from '../core/ItemPool';\nimport type ImplicitLibrarySearchFilter from './ImplicitLibrarySearchFilter';\nimport type { LibraryData, LibrariesResponse, MelvilleLink } from '../interface/LibraryModel';\nimport type { LibrarySearchConfig } from './LibrarySearchSource';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type ItemUpdater from '../core/ItemUpdater';\nimport { LazyLoadManager } from '../core/decorators/LazyLoadManager';\nimport { STORAGE_ASSIGNEE_CHANGED } from '../assets/AssetEvents';\nimport type { IExplicitFilter } from '../core/ItemFilter';\n\nexport default class LibrarySearchLoader implements IItemLoader<LibrarySearchConfig> {\n\n    constructor(\n        private _libraryPool: ItemPool<Library | AdobeAsset>,\n        private _libraryInterface: LibraryInterface,\n        private _libraryUpdater: ItemUpdater<Library, Partial<LibraryData>>\n    ) {\n    }\n\n    supportsFilter(filter?: IExplicitFilter<Library>): boolean {\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<LibrarySearchConfig>): Promise<ILoadedPage<LibrarySearchConfig>> {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<LibrarySearchConfig>, pageLink?: MelvilleLink): Promise<ILoadedPage<LibrarySearchConfig>> {\n        const { implicitFilter } = options;\n        const { _query } = implicitFilter as ImplicitLibrarySearchFilter;\n\n        // We will ignore the update if we had local changes sooner than this timestamp.\n        // This default latency is set to 3 seconds right now. We should revisit this value.\n        const latency = this._libraryPool._core._environment.getValue('PROJECTS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n\n        let result: LibrariesResponse;\n        if (pageLink) {\n            if (options.loadOptions?.limit) {\n                // replace the limit value in the URL with the provided limit value from the options.\n                pageLink.href = pageLink.href.replace(/limit=[0-9]*/, `limit=${options.loadOptions.limit}`);\n            }\n            result = await this._libraryInterface.searchLibrariesWithLink(_query, pageLink);\n        } else {\n            result = await this._libraryInterface.searchLibraries(_query);\n        }\n\n        const session = this._libraryPool.createLoaderUpdateSession<Library>(mostRecentValidMutation);\n        const items = this._libraryUpdater.updateRemoteItems(session, result.libraries ?? []);\n        for (const item of items) {\n            LazyLoadManager.updatedByItemUpdater(item, STORAGE_ASSIGNEE_CHANGED);\n        }\n        session.commit();\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<LibrarySearchConfig> | undefined;\n        const nextPageLink = result._links?.next;\n        if (nextPageLink) {\n            loadNextPage = (options: IItemLoaderOptions<LibrarySearchConfig>) =>\n                this._loadPage(options, nextPageLink);\n        }\n        implicitFilter!._matchingIDsFromSearch = new Set([\n            // copy existing, if needed\n            ...(implicitFilter!._matchingIDsFromSearch || []),\n            ...(items.map(item => item.id)) ]);\n\n        return {\n            items,\n            total: result.total_count,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { IImplicitFilter } from '../core/ItemFilter';\nimport type { default as Library } from './Library';\nimport ImplicitAdobeAssetFilterBase from '../assets/ImplicitAdobeAssetFilterBase';\n\ninterface ILibraryFilterOptions {\n    query: string;\n}\n\nexport default class LibrarySearchFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<Library> {\n    readonly _query: string = '';\n    /**\n     * @package -- only for use by ILibraryFilterOptions/Loader\n     */\n    _matchingIDsFromSearch: Set<string> | undefined;\n\n    constructor(options: Partial<ILibraryFilterOptions>) {\n        super();\n        this._query = options.query?.trim() ?? '';\n    }\n\n    get query(): string {\n        return this._query;\n    }\n\n    matches(item: Library): boolean {\n\n        if (!item.isLibrary) {\n            return false;\n        }\n\n        // Check if the item's id is in the current filter's id list\n        if (this._matchingIDsFromSearch && !this._matchingIDsFromSearch.has(item.id)) {\n            return false;\n        }\n\n        // If the query exists but there's no id list, we probably haven't finished loading yet\n        if ((this._query) && !this._matchingIDsFromSearch) {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport { SAMErrorCode } from '../core/SAMError';\nimport type AssetContext from '../assets/AssetContext';\nimport type LibraryInterface from '../interface/LibraryInterface';\nimport type Cache from '../core/Cache';\nimport { NotFound } from '../core/Cache';\nimport { EventEmitter } from 'events';\n\n/**\n * Represents a location in the user storage which are required to exist for the LibraryContext to function properly.\n * It provides functions to ensure the existence of the location and to watch for changes in the location.\n */\nexport abstract class SubscriptionLocation extends EventEmitter {\n    protected _cacheKey: string;\n    protected _path: string;\n    protected _asset: AdobeAsset | undefined = undefined;\n\n    constructor(cacheKey: string, path: string) {\n        super();\n        this._cacheKey = cacheKey;\n        this._path = path;\n    }\n\n    get cacheKey(): string { return this._cacheKey; }\n    get path(): string { return this._path; }\n    get asset(): AdobeAsset | undefined { return this._asset; }\n\n    async ensureExistence(context: AssetContext, libraryInterface: LibraryInterface): Promise<AdobeAsset> {\n        const environment = context._core._environment;\n        const cache = environment.cache;\n        const cacheKey = this._cacheKey;\n        const assetId = await cache.getItem(cacheKey);\n        try {\n            const asset = assetId !== NotFound ? await context.getAssetWithCloudID(assetId) : await context.getAssetWithRepoPath(this._path);\n            cache.setItem(cacheKey, asset.cloudID);\n            return this._setAsset(asset, cache);\n        } catch (e: any) {\n            if (e.code === SAMErrorCode.NOT_FOUND) {\n                environment.debug(`${this._path} not found, creating it now`);\n                const asset = await this._create(context, libraryInterface);\n                return this._setAsset(asset, cache);\n            }\n            throw e;\n        }\n    }\n\n    protected _callback = () => {\n        this.emit('change');\n    };\n\n    private async _setAsset(asset: AdobeAsset, cache: Cache): Promise<AdobeAsset> {\n        this._asset = asset;\n        await cache.setItem(this._cacheKey, asset.cloudID);\n        this._setUpWatcher();\n        return asset;\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    protected abstract _create(context: AssetContext, libraryInterface: LibraryInterface): Promise<AdobeAsset>;\n    protected abstract _setUpWatcher(): void;\n}\n\nexport class SyncGroupLocation extends SubscriptionLocation {\n    constructor() {\n        super('SYNC_GROUP_ID', '/assets/adobe-libraries');\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    protected async _create(context: AssetContext, libraryInterface: LibraryInterface): Promise<AdobeAsset> {\n        return await (await context.getHomeFolder()).createFolder(this.path);\n    }\n\n    protected _setUpWatcher(): void {\n        this._asset?.on('change', this._callback);\n    }\n}\n\nclass BookmarkLocation extends SubscriptionLocation {\n    constructor(cacheKey: string, path: string) {\n        super(cacheKey, path);\n    }\n\n    protected async _create(context: AssetContext, libraryInterface: LibraryInterface): Promise<AdobeAsset> {\n        // call to Melville's GET /bookmarks endpoint ensures that the bookmarks are created\n        await libraryInterface.getBookmarks();\n        return context.getAssetWithRepoPath(this.path);\n    }\n\n    protected _setUpWatcher(): void {\n        this._asset?.on('change', this._callback);\n        this._asset?.appMetadata.on('change', this._callback);\n    }\n}\n\nexport class CollabBookmarkLocation extends BookmarkLocation {\n    constructor() {\n        super('COLLAB_BOOKMARKS_ID', '/sync/adobe-libraries/collab-bookmarks.json');\n    }\n}\n\nexport class PublicBookmarkLocation extends BookmarkLocation {\n    constructor() {\n        super('PUBLIC_BOOKMARKS_ID', '/sync/adobe-libraries/bookmarks.json');\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type ItemPool from '../core/ItemPool';\nimport type Library from './Library';\nimport { LibraryUpdater } from './Library';\nimport LibraryInterface  from '../interface/LibraryInterface';\nimport type { CreateLibraryOptions, CreatePersonalLibraryData, LibrarySelectors } from '../interface/LibraryModel';\nimport { LibraryOwnerFilter } from '../interface/LibraryModel';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport { validatePlatformRepoName } from '../assets/AssetUtils';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport type { LibraryConfig, LibrarySource } from './LibrarySource';\nimport { memoize } from '../core/decorators';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport ItemSource from '../core/ItemSource';\nimport ImplicitLibraryFilter from './ImplicitLibraryFilter';\nimport LibraryListLoader from './LibraryListLoader';\nimport { SAMError, SAMErrorCode } from '../core/SAMError';\nimport type { LibrarySearchSource } from './LibrarySearchSource';\nimport LibrarySearchLoader from './LibrarySearchLoader';\nimport ImplicitLibrarySearchFilter from './ImplicitLibrarySearchFilter';\nimport type { SubscriptionLocation } from './SubscriptionLocation';\nimport { SyncGroupLocation, PublicBookmarkLocation, CollabBookmarkLocation } from './SubscriptionLocation';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport { default as LibraryFilter, type  LibraryFilterOptions } from './LibraryFilter';\nimport { default as LibraryOrder, type  LibraryOrderField } from './LibraryOrder';\nimport { Env } from '../core/Environment';\nimport type ICCLibraries from '../library-contents/index';\n\n/**\n * Provides all Library related functionality like getting\n * lists of libraries among other features.\n *\n * @experimental This API is in an experimental phase so expect that\n * APIs will not be final and there will be breaking changes\n * without bumping the major version until this comment is removed.\n */\nexport default class LibraryContext implements ISAMObject, SAM.LibraryContext {\n    private _ccLibraries: ICCLibraries | undefined;\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        private __assetPool: ItemPool<Library | AdobeAsset>\n    ) { }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    readonly _libraryUpdater = LibraryUpdater;\n    /**\n     * @package -- only for use in SAM.js\n     */\n    readonly _libraryInterface: LibraryInterface = new LibraryInterface(this._core);\n    /**\n     * @package -- only for use in SAM.js\n     */\n    public _syncGroupLocation: SubscriptionLocation = new SyncGroupLocation();\n    /**\n     * @package -- only for use in SAM.js\n     */\n    public _publicBookmarkLocation: SubscriptionLocation = new PublicBookmarkLocation();\n    /**\n     * @package -- only for use in SAM.js\n     */\n    public _collabBookmarkLocation: SubscriptionLocation = new CollabBookmarkLocation();\n    /**\n     * @package -- for use in SAM.js only\n     */\n    get _assetPool(): ItemPool<Library | AdobeAsset> {\n        return this.__assetPool;\n    }\n\n    /**\n     * Returns the LibrarySource which will return a list of the user's libraries.\n     * To request a different set of libraries, create a new LibraryFilter and pass it to the getList method.\n     * @example\n     * const libraryContext = await core.getLibraryContext();\n     * const order = new LibraryOrder('ascending', 'modified');\n     * const filter = LibraryFilter.AllLibraries; // If no filter is provided, will default to all of the user's libraries.\n     * const libraryList = libraryContext.librariesSource.getList(order, filter, loadOptions);\n     * libraryList.on(STATE_CHANGED, () => {\n     *     if (libraryList.status !== AssetListStatus.Loading) { const libraries = libraryList.items; }\n     * });\n     * Note: loadOptions.limit will be ignored on public libraries, which are not currently paginated.\n     */\n    @memoize\n    get librariesSource(): LibrarySource {\n        const loader = new LibraryListLoader<LibraryConfig>(\n            this._assetPool,\n            this._libraryInterface,\n            this._libraryUpdater,\n            this._core\n        );\n        this._ensureSubscriptionLocationExistence()      // start listening for changes to subscription locations\n            .then(() => {\n                this._publicBookmarkLocation.on('change', this._onPublicBookmarksChanged.bind(this));\n                this._collabBookmarkLocation.on('change', this._onCollabBookmarksChanged.bind(this));\n            })\n            .catch(error => {\n                this._core._environment.error(`Error ensuring subscription location existence: ${error}`);\n            });\n\n        return new ItemSource<LibraryConfig>(this._assetPool as ItemPool<Library>, [ loader ], new ImplicitLibraryFilter());\n    }\n\n    private _onPublicBookmarksChanged() {\n        for (const list of this.librariesSource._getLists()) {\n            if (list.filter._owner?.has(LibraryOwnerFilter.Public)) {\n                list.refresh();\n            }\n        }\n    }\n\n    private _onCollabBookmarksChanged() {\n        for (const list of this.librariesSource._getLists()) {\n            // Note: If LibraryOwnerFilter.Other is ever enabled, it should be included in this check.\n            if (list.filter._owner?.has(LibraryOwnerFilter.Incoming)) {\n                list.refresh();\n            }\n        }\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    async _createLibrary(options: CreateLibraryOptions): Promise<Library> {\n        if (!validatePlatformRepoName(options.name)) {\n            // Validate the name here to avoid resolving the asset if the name is invalid.\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid name provided for the createLibrary operation.');\n        }\n\n        const libraryData = await this._libraryInterface.createLibrary(options);\n        const session = this._assetPool.createMutationSession<Library>();\n        const library = this._libraryUpdater.updateRemoteItem(session, libraryData);\n        library._setLibraryLoadState('LOADED');\n        session.commit();\n        return library;\n    }\n\n    /**\n     * Provides the source to search for Libraries by a full or partial name.\n     *\n     * @param {string} query The full or partial Library name to search for.\n     * @returns {LibrarySearchSource} The source on which getList() is called to get the list of libraries that match the query.\n     * @example\n     * const libraryContext = await core.getLibraryContext();\n     * const librarySource = libraryContext.getLibrarySearchSource('full-or-partial-library-name');\n     * const libraryList = librarySource.getList(LibraryOrder.default);\n     */\n    getLibrarySearchSource(query: string): LibrarySearchSource {\n        const implicitFilter = new ImplicitLibrarySearchFilter({ query });\n        const loader = new LibrarySearchLoader(\n            this._assetPool,\n            this._libraryInterface,\n            this._libraryUpdater\n        );\n        return new ItemSource(this._assetPool as ItemPool<Library>, [ loader ], implicitFilter);\n    }\n\n    /**\n     * Creates a personal library.\n     *\n     * @example\n     * const libraryContext = await core.getLibraryContext();\n     * const roles: LibraryRole[] = [{\n     *      type: 'brand',\n     *      usage: 'usage_brand',\n     *      priority: 'priority_brand'\n     * }];\n     * const library = libraryContext.createLibrary({ name: 'test', roles });\n     *\n     */\n    @keepAlive\n    async createPersonalLibrary(data: CreatePersonalLibraryData): Promise<Library> {\n        const options = { syncCreate: true, name: data.name, roles: data.roles };\n\n        return this._createLibrary(options);\n    }\n\n    private async _getLibraryLocally(assetId: string): Promise<Library | undefined> {\n        // Locate the library in the local pool\n        const library = this._assetPool.getLocalItemById(assetId) as Library | undefined;\n        if (!library) {\n            // Library not found locally.\n            return undefined;\n        }\n\n        // This will go to Melville only if the library is not fully loaded.\n        await library._waitForLibraryLoad();\n        return library;\n    }\n\n    /**\n     * @package -- for use in SAM.js only\n     */\n    async _getLibraryRemotely(assetId: string, options?: { selectors?: LibrarySelectors[] }): Promise<Library | undefined> {\n        // Load the library from Melville. There will be a network call here.\n        const libraryData = await this._libraryInterface.getLibraryData(assetId, options);\n        if (!libraryData) {\n            return undefined;\n        }\n\n        const session = this._assetPool.createMutationSession<Library>();\n        const updatedLibrary = this._libraryUpdater.updateRemoteItem(session, libraryData);\n        session.commit();\n\n        return updatedLibrary;\n    }\n\n    private _isValidURN(id: string): boolean {\n        const urnRegex = /^urn:[a-zA-Z0-9][a-zA-Z0-9-]{0,31}:[a-zA-Z0-9()+,\\-.:=@;$_!*'%/?#]+$/;\n        return urnRegex.test(id);\n    }\n\n    // assetId can be LibraryAssetId or, currently, PublicLibraryId.\n    // TODO: Once [CCXB-21655] is complete, this will support assetIDs for public libraries.\n    // At that point, we can remove tryRemoteOnly.\n    // TODO: This should actually be named getLibraryByID() per https://wiki.corp.adobe.com/display/ACPCSDK/SAM+and+CC+Libraries+Strategic+Direction\n    @keepAlive\n    async getLibraryByAssetId(assetId: string): Promise<Library> {\n        const tryLocalThenRemote = async (id: string) => {\n            let library = await this._getLibraryLocally(id);\n            if (!library) {\n                library = await this._getLibraryRemotely(id);\n            }\n            return library;\n        };\n\n        const tryRemoteOnly = async (id: string) => {\n            return await this._getLibraryRemotely(id);\n        };\n\n        // For private libraries, we first try to get the library locally and then remotely using the asset id.\n        // For public libraries, we only try to get the libraries remotely using the public library id.\n        const library = this._isValidURN(assetId)\n            ? await tryLocalThenRemote(assetId)\n            : await tryRemoteOnly(assetId);\n\n        if (!library) {\n            throw SAMError.create(SAMErrorCode.NOT_FOUND, `Library not found for the given ID: ${assetId}`);\n        }\n\n        return library;\n    }\n\n    /**\n     * should be called once the client is interested in libraries listing\n     * @package -- for use in SAM.js only\n     * @returns Promise<void> - resolves when the special library locations are ensured to exist\n     */\n    async _ensureSubscriptionLocationExistence(): Promise<void> {\n        const assetContext = await this._core.getAssetContext();\n        return Promise.allSettled([\n            this._syncGroupLocation.ensureExistence(assetContext, this._libraryInterface),\n            this._publicBookmarkLocation.ensureExistence(assetContext, this._libraryInterface),\n            this._collabBookmarkLocation.ensureExistence(assetContext, this._libraryInterface)\n        ]).then(results => {\n            results.forEach(result => {\n                if (result.status === 'rejected') {\n                    throw result.reason;\n                }\n            });\n            return;\n        });\n    }\n\n    /**\n     * @experimental\n     */\n    getLibraryOrder(direction: IOrderDirection = 'descending', field: LibraryOrderField = 'modified'): LibraryOrder {\n        return new LibraryOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getLibraryFilter(options?: Partial<LibraryFilterOptions | undefined>): LibraryFilter {\n        return new LibraryFilter(options);\n    }\n\n    /**\n     * Called to obtain the CCLibraries instance.\n     * @package -- for use in SAM.js only\n     * @returns Promise<CCLibraries> - resolves with the CCLibraries instance.\n     */\n    async _getLibrariesModule(): Promise<ICCLibraries> {\n        if (!this._ccLibraries) {\n            // TODO: Switch to using a common component config per [ACPCSDK-3]\n            try {\n                const { default: CCLibraries, CloudDriver } = await import('../library-contents/index');\n                const token = this._core._environment.getValue('ACCESS_TOKEN');\n                const env = (this._core._environment.getValue('ENVIRONMENT') === Env.Production) ? 'production' : 'staging';\n                const cloudDriver = new CloudDriver(this._core, async () => ({  env, token, options: {} }));\n                await cloudDriver.init();\n                const initializationOptions = { disableLocalFallthrough: true, skipConnectingOnInit: false, disablePreemptiveLibraryLoad: true };\n                this._ccLibraries = new CCLibraries(this._core, this._assetPool, cloudDriver, initializationOptions);\n            } catch (error) {\n                this._core._environment.error(`Error loading CCLibraries module: ${error}`);\n                throw error;\n            }\n        }\n        return this._ccLibraries;\n    }\n\n    /**\n     * Called to obtain the CCLibraries instance.\n     * @package -- for use in SAM.js only\n     * Use from within the CCLibraries Module code, where we know the instance is already available.\n     */\n    _getLibrariesModule_NoLoad(): ICCLibraries | undefined {\n        return this._ccLibraries;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type CustomModelInterface from '../interface/CustomModelInterface';\nimport type ItemPool from '../core/ItemPool';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { AdobeAsset, IItemSourceConfig } from 'src';\nimport type {\n    IItemLoader,\n    IItemLoaderOptions,\n    ILoadNextPage,\n    ILoadedPage,\n} from '../core/ItemLoader';\nimport type CustomModel from '../custom-models/CustomModel';\nimport { CustomModelUpdaterMelville } from '../custom-models/CustomModel';\nimport CustomModelOrder from './CustomModelOrder';\nimport { OrderFieldToCustomModelOrderBy } from './CustomModelOrder';\nimport type { MelvilleLink } from '../interface/LibraryModel';\nimport type {\n    CustomModelsResponseMelville,\n    MelvilleCustomModelListParameters,\n} from '../interface/CustomModelModel';\nimport type CustomModelFilter from '@sam-js-src/custom-models/CustomModelFilter';\n\nexport default class CustomModelLoader<Config extends IItemSourceConfig>\nimplements IItemLoader<Config> {\n    constructor(\n        private _assetPool: ItemPool<CustomModel | AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private _customModelInterface: CustomModelInterface\n    ) {}\n\n    async loadPage(options: IItemLoaderOptions<Config>) {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(\n        options: IItemLoaderOptions<Config>,\n        pageLink?: MelvilleLink\n    ): Promise<ILoadedPage<Config>> {\n        let result: CustomModelsResponseMelville;\n\n        const { order, limit, filter } = options;\n        const queryParams: MelvilleCustomModelListParameters = {};\n        const effectiveOrder = order || CustomModelOrder.default;\n        const field = (effectiveOrder as CustomModelOrder).field;\n        queryParams.orderBy = effectiveOrder.direction === 'ascending'\n            ? OrderFieldToCustomModelOrderBy[field]\n            : `-${OrderFieldToCustomModelOrderBy[field]}`;\n\n        if (limit) {\n            queryParams.limit = limit;\n            if (!queryParams.start) {\n                queryParams.start = 0;\n            }\n        }\n\n        const listingOptions = (filter as CustomModelFilter)?.listingOptions;\n\n        const body: Record<string, any> = listingOptions ? { ...listingOptions } : {};\n        // Map external field names to internal API names\n        if (body.createDateMin) {\n            body.createdDateMin = body.createDateMin.getTime();\n            delete body.createDateMin;\n        }\n        if (body.createDateMax) {\n            body.createdDateMax = body.createDateMax.getTime();\n            delete body.createDateMax;\n        }\n        if (body.modifyDateMin) {\n            body.modifiedDateMin = body.modifyDateMin.getTime();\n            delete body.modifyDateMin;\n        }\n        if (body.modifyDateMax) {\n            body.modifiedDateMax = body.modifyDateMax.getTime();\n            delete body.modifyDateMax;\n        }\n\n        if (pageLink) {\n            result = await this._customModelInterface.searchCustomModelsUsingPageLink(body, pageLink);\n        } else {\n            result = await this._customModelInterface.searchCustomModels(queryParams, body);\n        }\n\n        const latency = this._core._environment.getValue('USS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n        const session = this._assetPool.createLoaderUpdateSession<CustomModel>(mostRecentValidMutation);\n        const items = CustomModelUpdaterMelville.updateRemoteItems(session, result.custom_models);\n        session.commit();\n\n        let loadNextPage: ILoadNextPage<Config> | undefined;\n        const nextPageLink = result._links?.next;\n        if (nextPageLink) {\n            loadNextPage = (nextOptions: IItemLoaderOptions<Config>) =>\n                this._loadPage(nextOptions, nextPageLink);\n        }\n\n        return {\n            items,\n            total: result.total_count,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport type DateRange = {\n    min?: string,\n    max?: string\n};\n\nexport const makeDateRange = (max?: Date, min?: Date): DateRange | undefined => {\n    return ((max || min) ? { min: getDateString(min), max: getDateString(max) } as DateRange : undefined);\n};\n\nexport const getDateString = (date?: Date): string | undefined => {\n    return (date ? date.toISOString() : date);\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { IGetUSSResults } from '../assets/USSLoaderHelper';\nimport USSLoaderHelper from '../assets/USSLoaderHelper';\nimport type {\n    IItemLoader,\n    IItemLoaderOptions,\n    ILoadedPage,\n} from '../core/ItemLoader';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type CustomModelFilter from './CustomModelFilter';\nimport type { CustomModelSearchConfig } from './CustomModelSource';\nimport type { USSResponse } from '../interface/USSModel';\nimport { SearchProps } from '../interface/USSModel';\nimport type USSInterface from '../interface/USSInterface';\nimport type { ISearchQueryCustomModel } from '../interface/CustomModelModel';\nimport { CUSTOM_MODEL_MEDIA_TYPE } from '../interface/CustomModelModel';\nimport { customModelOrderToUSSOrder } from './CustomModelOrder';\nimport type CustomModelContext from './CustomModelContext';\nimport { makeDateRange } from '../utils/dateUtils';\n\nexport default class CustomModelSearchLoader implements IItemLoader<CustomModelSearchConfig> {\n    private _ussLoaderHelper: USSLoaderHelper<CustomModelSearchConfig>;\n    private _ussInterface: USSInterface;\n\n    constructor(\n        private _core: ISAMCorePrivate,\n        public _customModelContext: CustomModelContext\n    ) {\n        this._ussInterface = this._core.hostAssetContext._ussInterface;\n        this._ussLoaderHelper = new USSLoaderHelper(this._core.hostAssetContext._assetPool, _core, this);\n    }\n\n    supportsFilter(filter?: CustomModelFilter): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    loadPage(options: IItemLoaderOptions<CustomModelSearchConfig>): Promise<ILoadedPage<CustomModelSearchConfig>> {\n        return this._ussLoaderHelper.loadPage(options);\n    }\n\n    /**\n     * @package -- for use by USSLoaderHelper\n     */\n    async _getUSSResults(options: IGetUSSResults<CustomModelSearchConfig>\n    ): Promise<USSResponse> {\n        const {\n            implicitFilter: { query },\n            filter: { listingOptions },\n            order: customModelOrder\n        } = options;\n\n        const createDateRange = makeDateRange(listingOptions?.createDateMax, listingOptions?.createDateMin);\n        const modifyDateRange = makeDateRange(listingOptions?.modifyDateMax, listingOptions?.modifyDateMin);\n\n        const ussQuery: ISearchQueryCustomModel = {\n            hints: [ { acp_platform_v2: true, creative_cloud_rendition_v2: true } ],\n            asset_name: query,\n            limit: options.loadOptions?.limit ?? 100,\n            start_index: options?.start ?? 0,\n            [SearchProps.TYPE]: [ CUSTOM_MODEL_MEDIA_TYPE ],\n            creative_cloud_asset_type: 'dcx',\n            ...customModelOrderToUSSOrder(customModelOrder),\n            fetch_fields: {\n                includes: [\n                    '_embedded',\n                    'stock_content',\n                    'link_additional_metadata',\n                    'app_metadata',\n                    'firefly#cme$$baseModelName',\n                    'firefly#cme$$baseModelVersion',\n                    'firefly#cme$$conceptId',\n                    'firefly#cme$$trainingMode',\n                    'firefly#cme$$superclass',\n                    'firefly#cme$$version',\n                    'firefly#ffmodel'\n                ]\n            },\n            'app_metadata$$cme:publishedState': listingOptions?.publishedState,\n            sync_created_date: createDateRange ? { range: createDateRange } : undefined,\n            sync_updated_date: modifyDateRange ? { range: modifyDateRange } : undefined\n        };\n\n        return this._ussInterface.getQueryResponse(ussQuery);\n    }\n\n    /**\n     * @package -- only for use by USSLoaderHelper\n     */\n    _postProcessPage(\n        { implicitFilter }: IItemLoaderOptions<CustomModelSearchConfig>,\n        page: ILoadedPage<CustomModelSearchConfig>\n    ): void {\n        const { items } = page;\n\n        implicitFilter._matchingIDsFromSearch = new Set([\n            // copy existing, if needed\n            ...(implicitFilter._matchingIDsFromSearch || []),\n            ...(items.map(item => item.id)) ]);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type {\n    IImplicitAdobeAssetFilterBaseOptions\n} from '../assets/ImplicitAdobeAssetFilterBase';\nimport type CustomModel from './CustomModel';\nimport ImplicitCustomModelFilter from './ImplicitCustomModelFilter';\n\nexport interface ICustomModelSearchListingOptions {\n    query: string\n}\n\nexport default class CustomModelSearchFilter extends ImplicitCustomModelFilter {\n    readonly _query: string;\n    _matchingIDsFromSearch: Set<string> | undefined;\n\n    constructor(options: ICustomModelSearchListingOptions & Partial<IImplicitAdobeAssetFilterBaseOptions>) {\n        const { query, ...superOptions } = options;\n        super(superOptions);\n\n        this._query = query.trim();\n    }\n\n    get query(): string {\n        return this._query;\n    }\n\n    matches(item: CustomModel): boolean {\n        // Check if the item's id is in the current filter's id list\n        if (this._matchingIDsFromSearch && !this._matchingIDsFromSearch.has(item.id)) {\n            return false;\n        }\n\n        // If the query exists but there's no id list, we probably haven't finished loading yet\n        if ((this._query) && !this._matchingIDsFromSearch) {\n            return false;\n        }\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport ItemUpdater from '../../core/ItemUpdater';\nimport AdobeAsset from '../../assets/AdobeAsset';\nimport type { CustomModelData } from './LegacyCustomModelModel';\nimport { CustomModelPublishedState } from './LegacyCustomModelModel';\nimport PropertyUpdater from '../../core/PropertyUpdater';\nimport { observable } from '../../core/decorators';\n\nexport default class LegacyCustomModel extends AdobeAsset implements SAM.LegacyCustomModel {\n    public isCustomModel: boolean = true;\n\n    private _inferenceReady: boolean = false;\n    private _publishedState: CustomModelPublishedState = CustomModelPublishedState.UNPUBLISHED;\n    private _samplePrompt: string = '';\n    private _renditionUrl?: string;\n    private _displayName: string = '';\n    private _baseModelName: string = '';\n    private _baseModelVersion: string = '';\n    private _conceptId: string = '';\n    private _trainingMode: string = '';\n\n    @observable\n    get inferenceReady() {\n        return this._inferenceReady;\n    }\n\n    @observable\n    get publishedState() {\n        return this._publishedState;\n    }\n\n    @observable\n    get samplePrompt() {\n        return this._samplePrompt;\n    }\n\n    @observable\n    get renditionUrl() {\n        return this._renditionUrl;\n    }\n\n    @observable\n    get displayName() {\n        return this._displayName;\n    }\n\n    @observable\n    get baseModelName() {\n        return this._baseModelName;\n    }\n    @observable\n    get baseModelVersion() {\n        return this._baseModelVersion;\n    }\n    @observable\n    get conceptId() {\n        return this._conceptId;\n    }\n    @observable\n    get trainingMode() {\n        return this._trainingMode;\n    }\n}\n\nexport const LegacyCustomModelUpdater = new ItemUpdater<LegacyCustomModel, CustomModelData>(\n    {\n        localItemType: LegacyCustomModel,\n        remoteIdProperty: 'assetId',\n        propertyUpdater: new PropertyUpdater({\n            '_inferenceReady': { name: 'inferenceReady', format: 'boolean' },\n            // TODO: create a type with array of choices?\n            '_publishedState': 'publishedState',\n            '_samplePrompt': 'samplePrompt',\n            '_renditionUrl': 'renditionUrl',\n            '_displayName': 'displayName',\n            '_baseModelName': 'baseModelName',\n            '_baseModelVersion': 'baseModelVersion',\n            '_conceptId': 'conceptId',\n            '_trainingMode': 'trainingMode',\n            // on AdobeAsset\n            '_links': { name: '_links', format: 'object' },\n            '_name': 'assetName',\n            '_path': 'path',\n            '_created': { name: 'createDate', format: 'date' },\n            '_modified': { name: 'modifyDate', format: 'date'  },\n            '_createdBy': 'createdBy',\n            '_version': 'version',\n            '_etag': 'etag',\n            '_storageRegion': 'region',\n            '_size': { name: 'size', format: 'number' },\n        }),\n    }\n);\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type LegacyCustomModelInterface from './LegacyCustomModelInterface';\nimport type ItemPool from '../../core/ItemPool';\nimport type { ISAMCorePrivate } from '../../indexPrivate';\nimport type { AdobeAsset } from 'src';\nimport type {\n    LegacyCustomModelConfig,\n} from './LegacyCustomModelSource';\nimport type {\n    IItemLoader,\n    IItemLoaderOptions,\n    ILoadNextPage,\n    ILoadedPage,\n} from '../../core/ItemLoader';\nimport type LegacyCustomModel from './LegacyCustomModel';\nimport { LegacyCustomModelUpdater } from './LegacyCustomModel';\nimport { LegacyOrderFieldToCustomModelOrderBy } from './LegacyCustomModelOrder';\nimport type LegacyCustomModelFilter from './LegacyCustomModelFilter';\n\nexport default class CustomModelLoader\nimplements IItemLoader<LegacyCustomModelConfig> {\n    constructor(\n        private _assetPool: ItemPool<LegacyCustomModel | AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private _customModelInterface: LegacyCustomModelInterface\n    ) {}\n\n    async loadPage(options: IItemLoaderOptions<LegacyCustomModelConfig>) {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(\n        options: IItemLoaderOptions<LegacyCustomModelConfig>,\n        startIndex?: number\n    ): Promise<ILoadedPage<LegacyCustomModelConfig>> {\n        const { order, filter } = options;\n        const { limit } = options.loadOptions ?? {};\n        const customModelFilter = filter as LegacyCustomModelFilter;\n        const listingOptions = customModelFilter.listingOptions;\n\n        const listOptions = {\n            orderBy: LegacyOrderFieldToCustomModelOrderBy[order.field],\n            limit,\n            ...listingOptions,\n        };\n        const result = await this._customModelInterface.getCustomModels(\n            startIndex ? { ...listOptions, startIndex } : listOptions\n        );\n        const session = this._assetPool.createLoaderUpdateSession<LegacyCustomModel>(\n            Date.now() - this._core._environment.getValue('USS_LIST_UPDATE_LATENCY')\n        );\n        const items = LegacyCustomModelUpdater.updateRemoteItems(session, result.items);\n        session.commit();\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<LegacyCustomModelConfig> | undefined;\n        const nextPageLink = result.nextPage?.startIndex;\n        if (nextPageLink) {\n            loadNextPage = (options: IItemLoaderOptions<LegacyCustomModelConfig>) =>\n                this._loadPage(options, nextPageLink);\n        }\n\n        return {\n            items,\n            loadNextPage,\n            total: result.total\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type {\n    CustomModelPublishedState,\n    LegacyCreateTrainingSetOptions,\n    LegacyCustomModelCreateOptions,\n    CustomModelOrderBy,\n    CustomModelsMelvilleResponse,\n    CustomModelsResponse\n} from './LegacyCustomModelModel';\nimport InterfaceBase from '../../interface/InterfaceBase';\nimport { fillURLTemplate } from '../../interface/LinkUtils';\nimport packageJSON from '../../../package.json';\nimport type { CreateLibraryOptions } from '../../interface/LibraryModel';\nimport SAMError, { SAMErrorCode } from '../../core/SAMError';\nimport type Library from '../../libraries/Library';\nimport type { IFetchOptions } from '../../core/Environment';\n\nexport const REGION_MAP: Record<string, string> = {\n    VA6C2: 'va6',\n    VA6: 'va6',\n    VA7: 'va6',\n    JPN3: 'jpn3',\n    IRL1: 'irl1',\n};\n\n// define type based off of keys of REGION_MAP\ntype RegionKey = keyof typeof REGION_MAP;\n\n/**\n * Returns the storage region for a given region key. The storage region is stored in the home folder and is stored as\n * an uppercase string. The mapping takes this uppercase string and returns the corresponding storage region that is used\n * to build the url to the endpoint.\n * @param region    The region key as stored in the home folder\n */\nexport function storageRegionForUrl(region: RegionKey): string {\n    return REGION_MAP[region];\n}\n\ninterface IListingOptions<IOrderField> {\n    orderBy: IOrderField;\n    limit: number;\n}\n\nexport interface CustomModelListingOptions\n    extends IListingOptions<CustomModelOrderBy> {\n    startIndex?: number;\n    createdBy?: string;\n    name?: string;\n    publishedState?: CustomModelPublishedState;\n    createDateMin?: Date;\n    createDateMax?: Date;\n    modifyDateMin?: Date;\n    modifyDateMax?: Date;\n}\n\nexport default class CustomModelInterface extends InterfaceBase {\n    private _getMelvilleUrl(endpoint: string): string {\n        return `https://${this._core._environment.endpoints.MELVILLE_HOST}${endpoint}`;\n    }\n\n    //\n    protected async _getFetchOptionOverrides(originalHref: string, originalOptions: IFetchOptions): Promise<{\n        href: string;\n        options: IFetchOptions\n    }> {\n        const { href, options } = await super._getFetchOptionOverrides(originalHref, originalOptions);\n        return {\n            href,\n            options: {\n                ...options,\n                headers: {\n                    ...options.headers,\n                    'X-Product-Location': `SAM.js/${packageJSON.version}`\n                }\n            }\n        };\n    }\n\n    private async _getUrl(endpoint: string): Promise<string> {\n        const homeFolder = await this._core.hostAssetContext.getHomeFolder();\n        const region = REGION_MAP[homeFolder.storageRegion];\n        const acpHost = this._core._environment.endpoints.ACP_CS_HOST;\n        const subdomain = acpHost.split('.')[0];\n        const regionalizedSubdomain = `${subdomain}-${region}`;\n\n        // Replaces non-regionalized subdomain with its' regionalized version, using the region of the homeFolder eg.\n        //\n        //   when storage region = 'JPN3':\n        //     platform-cs-stage.adobe.io =>\n        //     platform-cs-stage-${REGION_MAP[JPN3]}.adobe.com =>\n        //     platform-cs-stage-jpn3.adobe.com\n        //\n        //   when storage region = 'IRL1':\n        //     platform-cs-stage.adobe.io =>\n        //     platform-cs-stage-${REGION_MAP[IRL1]}.adobe.com =>\n        //     platform-cs-stage-irl1.adobe.com\n        return `https://${acpHost.replace(\n            subdomain,\n            regionalizedSubdomain\n        )}/fps/${endpoint}`;\n    }\n\n    /**\n   * Fetches the list of custom models based on the options provided\n   * @param options : options to sort and filter the projects listing\n   * @returns the list of custom models along with the page information and links to the next page\n   */\n    async getCustomModels(\n        options?: Partial<CustomModelListingOptions>\n    ): Promise<CustomModelsResponse> {\n        const queryParams = options\n            ? JSON.parse(\n                JSON.stringify(options)\n            )\n            : {};\n\n        const url = fillURLTemplate(\n            await this._getUrl('customModels'),\n            queryParams\n        );\n\n        return this._getResponse(url);\n    }\n\n    /**\n     * Create a training set to be used with a custom model. The training set is considered a child of the parent asset\n     * specified by the parentAssetId.\n     */\n    async createTrainingSet(options: LegacyCreateTrainingSetOptions): Promise<Library> {\n        if (!options.name) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid argument: missing required name');\n        }\n\n        if (!options.projectId) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid argument: missing required projectId. The parent must be a project');\n        }\n\n        if (!options['firefly#ffmodel'].schemaVersion) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Invalid argument: missing required schemaVersion.');\n        }\n\n        const creationOptions: CreateLibraryOptions = {\n            name: options.name,\n            parent_assetId: options.projectId,\n            roles: [ {\n                type: 'cm_training_set'\n            } ],\n\n            // this key is not currently used by melville but will soon be enabled\n            // sending it does not affect the request\n            'firefly#ffmodel': options['firefly#ffmodel'],\n\n            // TODO: remove this when melville switches to 'firefly#ffmodel'\n            'firefly#cme': {\n                ...options['firefly#ffmodel'],\n                version: options['firefly#ffmodel'].schemaVersion\n            }\n        };\n\n        const libraryContext = await this._core.getLibraryContext();\n        return libraryContext._createLibrary(creationOptions);\n    }\n\n    async getTrainingSetById(assetId: string): Promise<Library | undefined> {\n        const libraryContext = await this._core.getLibraryContext();\n        return libraryContext._getLibraryRemotely(assetId);\n    }\n\n    async createCustomModel(options: LegacyCustomModelCreateOptions): Promise<CustomModelsMelvilleResponse> {\n        const endpoint: string = `/api/v1/custom-models`;\n\n        const response = await this._doPost(\n            this._getMelvilleUrl(endpoint),\n            { 'Content-Type': 'application/json' },\n            JSON.stringify(options),\n            [ 201, 200 ]);\n\n        const idString = response.headers.get('asset-id');\n        if (!idString) {\n            throw SAMError.create(SAMErrorCode.NOT_FOUND, 'Asset id for newly created custom model not returned by melville');\n        }\n\n        return { id: idString };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type AdobeAsset from '../../assets/AdobeAsset';\nimport type {\n    IItemLoader,\n    IItemLoaderOptions,\n    ILoadNextPage,\n    ILoadedPage,\n} from '../../core/ItemLoader';\nimport type ItemPool from '../../core/ItemPool';\nimport type { ISAMCorePrivate } from '../../indexPrivate';\nimport type LegacyCustomModelInterface from './LegacyCustomModelInterface';\nimport type LegacyCustomModel from './LegacyCustomModel';\nimport { LegacyCustomModelUpdater } from './LegacyCustomModel';\nimport type LegacyCustomModelFilter from './LegacyCustomModelFilter';\nimport { LegacyOrderFieldToCustomModelOrderBy } from './LegacyCustomModelOrder';\nimport type { LegacyCustomModelSearchConfig } from './LegacyCustomModelSource';\n\nexport default class CustomModelSearchLoader implements IItemLoader<LegacyCustomModelSearchConfig> {\n    constructor(\n        private _assetPool: ItemPool<LegacyCustomModel | AdobeAsset>,\n        private _core: ISAMCorePrivate,\n        private _customModelInterface: LegacyCustomModelInterface\n    ) {}\n\n    supportsFilter(filter?: LegacyCustomModelFilter): boolean {\n        // If we don't provide a filter at all, then we cannot use the loader\n        return filter !== undefined;\n    }\n\n    async loadPage(options: IItemLoaderOptions<LegacyCustomModelSearchConfig>) {\n        return this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<LegacyCustomModelSearchConfig>, startIndex?: number): Promise<ILoadedPage<LegacyCustomModelSearchConfig>> {\n        const { order, implicitFilter, filter } = options;\n        const { limit } = options.loadOptions ?? {};\n        const customModelSearchFilter = implicitFilter;\n        const customModelFilter = filter as LegacyCustomModelFilter;\n        const listingOptions = ('listingOptions' in customModelFilter && customModelFilter['listingOptions']) || [];\n\n        const listOptions = {\n            orderBy: LegacyOrderFieldToCustomModelOrderBy[order.field],\n            limit,\n            ...listingOptions,\n            name: customModelSearchFilter.query\n        };\n        const result = await this._customModelInterface.getCustomModels(\n            startIndex ? { ...listOptions, startIndex } : listOptions\n        );\n        const session = this._assetPool.createLoaderUpdateSession<LegacyCustomModel>(\n            Date.now() - this._core._environment.getValue('USS_LIST_UPDATE_LATENCY')\n        );\n        const items = LegacyCustomModelUpdater.updateRemoteItems(session, result.items);\n        session.commit();\n\n        // Check if we have another page to load.\n        let loadNextPage: ILoadNextPage<LegacyCustomModelSearchConfig> | undefined;\n        const nextPageLink = result.nextPage?.startIndex;\n        if (nextPageLink) {\n            loadNextPage = (options: IItemLoaderOptions<LegacyCustomModelSearchConfig>) =>\n                this._loadPage(options, nextPageLink);\n        }\n\n        implicitFilter!._matchingIDsFromSearch = new Set([\n            // copy existing, if needed\n            ...(implicitFilter!._matchingIDsFromSearch || []),\n            ...(items.map(item => item.id)) ]);\n\n        return {\n            items,\n            loadNextPage,\n            total: result.total\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type LegacyCustomModel from './LegacyCustomModel';\nimport type {\n    IImplicitAdobeAssetFilterBaseOptions\n} from '../../assets/ImplicitAdobeAssetFilterBase';\nimport ImplicitAdobeAssetFilterBase from '../../assets/ImplicitAdobeAssetFilterBase';\nimport type { IImplicitFilter } from '../../core/ItemFilter';\n\nexport default class ImplicitCustomModelFilter extends ImplicitAdobeAssetFilterBase implements IImplicitFilter<LegacyCustomModel> {\n    constructor(options?: Partial<IImplicitAdobeAssetFilterBaseOptions>) {\n        super(options);\n    }\n\n    matches(item: LegacyCustomModel) {\n        if (!item.isCustomModel) {\n            return false;\n        }\n\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type {\n    IImplicitAdobeAssetFilterBaseOptions\n} from '../../assets/ImplicitAdobeAssetFilterBase';\nimport type LegacyCustomModel from './LegacyCustomModel';\nimport LegacyImplicitCustomModelFilter from './LegacyImplicitCustomModelFilter';\n\nexport interface ICustomModelSearchListingOptions {\n    query: string\n}\n\nexport default class CustomModelSearchFilter extends LegacyImplicitCustomModelFilter {\n    readonly _query: string;\n    _matchingIDsFromSearch: Set<string> | undefined;\n\n    constructor(options: ICustomModelSearchListingOptions & Partial<IImplicitAdobeAssetFilterBaseOptions>) {\n        const { query, ...superOptions } = options;\n        super(superOptions);\n\n        this._query = query.trim();\n    }\n\n    get query(): string {\n        return this._query;\n    }\n\n    matches(item: LegacyCustomModel): boolean {\n        // Check if the item's id is in the current filter's id list\n        if (this._matchingIDsFromSearch && !this._matchingIDsFromSearch.has(item.id)) {\n            return false;\n        }\n\n        // If the query exists but there's no id list, we probably haven't finished loading yet\n        if ((this._query) && !this._matchingIDsFromSearch) {\n            return false;\n        }\n        return super.matches(item);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type {\n    LegacyCustomModelConfig, LegacyCustomModelSearchConfig, LegacyCustomModelSearchSource,\n    LegacyCustomModelSource,\n} from './LegacyCustomModelSource';\nimport { memoize } from '../../core/decorators';\nimport type AdobeAsset from '../../assets/AdobeAsset';\nimport type ItemPool from '../../core/ItemPool';\nimport type { ISAMCorePrivate, ISAMObject } from '../../indexPrivate';\nimport ItemSource from '../../core/ItemSource';\nimport LegacyCustomModelLoader from './LegacyCustomModelLoader';\nimport LegacyCustomModelInterface from './LegacyCustomModelInterface';\nimport type LegacyCustomModel from './LegacyCustomModel';\nimport { LegacyCustomModelUpdater } from './LegacyCustomModel';\nimport LegacyCustomModelSearchLoader from './LegacyCustomModelSearchLoader';\nimport LegacyCustomModelSearchFilter from './LegacyCustomModelSearchFilter';\nimport LegacyImplicitCustomModelFilter from './LegacyImplicitCustomModelFilter';\nimport type Library from '../../libraries/Library';\nimport { LibraryUpdater } from '../../libraries/Library';\nimport type { LibraryConfig, LibrarySource } from '../../libraries/LibrarySource';\nimport LibraryInterface from '../../interface/LibraryInterface';\nimport LibraryListLoader from '../../libraries/LibraryListLoader';\nimport ImplicitLibraryFilter from '../../libraries/ImplicitLibraryFilter';\nimport type { LegacyCustomModelCreateOptions, CustomModelsMelvilleResponse, LegacyCreateTrainingSetOptions } from './LegacyCustomModelModel';\nimport type { IOrderDirection } from '../../core/ItemOrder';\nimport { default as LegacyCustomModelOrder,  type CustomModelOrderField } from './LegacyCustomModelOrder';\nimport { default as LegacyCustomModelFilter, type ICustomModelListingOptions } from './LegacyCustomModelFilter';\n\n\n/**\n * Provides Custom Model functionality such as listing.\n *\n * @experimental This API is in an experimental phase so expect that\n * API's will not be final and there will be breaking changes\n * without bumping the major version until this comment is removed.\n */\nexport default class LegacyCustomModelContext implements ISAMObject, SAM.LegacyCustomModelContext {\n    readonly _customModelInterface = new LegacyCustomModelInterface(this._core);\n\n    constructor(\n        /**\n         * @package -- for use in SAM.js only\n         */\n        readonly _core: ISAMCorePrivate,\n        /**\n         * @package -- for use in SAM.js only\n         */\n        readonly _assetPool: ItemPool<LegacyCustomModel | AdobeAsset>\n    ) {}\n\n    /**\n     * @experimental\n     */\n    getCustomModelOrder(direction: IOrderDirection = 'descending', field: CustomModelOrderField = 'modified'): LegacyCustomModelOrder {\n        return new LegacyCustomModelOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getCustomModelFilter(options?: Partial<ICustomModelListingOptions | undefined>): LegacyCustomModelFilter {\n        return new LegacyCustomModelFilter(options);\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     * Updaters shouldn't be accessed directly.\n     */\n    readonly _customModelUpdater =  LegacyCustomModelUpdater;\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    private readonly _libraryInterface: LibraryInterface = new LibraryInterface(this._core);\n\n    /**\n   * @example\n   * const customModelContext = samCore.customModelContext;\n   * const customModelSource = customModelContext.customModelSearchSource;\n   *\n   * Search custom models a user has access to by name. The set of assets returned in a list is static once the\n   * search is executed - ie newly created items which fit a list will not be added, edits to items which qualify\n   * them to be part of a list will not have any effect. However, discard/delete/permission loss will still be\n   * reflected.\n   */\n    customModelSearchSource(query: string): LegacyCustomModelSearchSource {\n        // declare an implicitFilter\n        const implicitFilter = new LegacyCustomModelSearchFilter({ query });\n\n        // declare a CustomModelSearchLoader\n        return new ItemSource<LegacyCustomModelSearchConfig>(\n            this._assetPool as ItemPool<LegacyCustomModel>,\n            [\n                new LegacyCustomModelSearchLoader(\n                    this._assetPool,\n                    this._core,\n                    this._customModelInterface\n                ),\n            ],\n            implicitFilter\n        );\n    }\n\n    /**\n   * @example\n   * const customModelContext = samCore.customModelContext;\n   * const customModelSource = customModelContext.customModelSource;\n   *\n   * Gets all custom models a user has access to\n   */\n    @memoize\n    get customModelSource(): LegacyCustomModelSource {\n        return new ItemSource<LegacyCustomModelConfig>(\n            this._assetPool as ItemPool<LegacyCustomModel>,\n            [\n                new LegacyCustomModelLoader(\n                    this._assetPool,\n                    this._core,\n                    this._customModelInterface\n                ),\n            ],\n            new LegacyImplicitCustomModelFilter()\n        );\n    }\n\n    async createTrainingSet(options: LegacyCreateTrainingSetOptions): Promise<Library> {\n        return this._customModelInterface.createTrainingSet(options);\n    }\n\n    /**\n     * Returns the `TrainingSetSource` which will return a list of training set libraries the user has access to.\n     * @example\n     * const context = await core.getCustomModelContext();\n     * const order = new LibraryOrder('ascending', 'modified');\n     * const filter = TrainingSetFilter.DEFAULT;\n     * const list = await context.trainingSetsSource().getList(order, filter, loadOptions);\n     * list.on(STATE_CHANGED, () => {\n     *     if (list.status !== AssetListStatus.Loading) { const trainingSets = list.items; }\n     * });\n     */\n    @memoize\n    async trainingSetsSource(): Promise<LibrarySource> {\n        const libraryContext = await this._core.getLibraryContext();\n        const loader = new LibraryListLoader<LibraryConfig>(\n            libraryContext._assetPool,\n            this._libraryInterface,\n            LibraryUpdater,\n            this._core\n        );\n        return new ItemSource<LibraryConfig>(libraryContext._assetPool as ItemPool<Library>, [ loader ], ImplicitLibraryFilter.TrainingSets);\n    }\n\n    /* We need to always fetch remotely because local training sets might have been populated by a melville listing,\n     * and those training sets don't have custom model data.\n     */\n    async getTrainingSetById(assetId: string): Promise<Library | undefined> {\n        return this._customModelInterface.getTrainingSetById(assetId);\n    }\n\n    async createCustomModel(options: LegacyCustomModelCreateOptions): Promise<CustomModelsMelvilleResponse> {\n        return this._customModelInterface.createCustomModel(options);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { LibraryFilterOptions } from '../libraries/LibraryFilter';\nimport LibraryFilter from '../libraries/LibraryFilter';\nimport type { IExplicitFilter } from '../core/ItemFilter';\nimport type Library from '../libraries/Library';\nimport { LibraryOwnerFilter, LibraryRolesFilter } from '../interface/LibraryModel';\n\nexport default class TrainingSetFilter extends LibraryFilter implements IExplicitFilter<Library> {\n    static DEFAULT = new TrainingSetFilter();\n\n    constructor(options?: Pick<LibraryFilterOptions, 'project'>) {\n        super({ ...options, owner: [ LibraryOwnerFilter.All ], roles: [ LibraryRolesFilter.TrainingSet ] });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type Library from '../libraries/Library';\nimport { isLibrary } from '../libraries/Library';\nimport type CustomModel from './CustomModel';\nimport { isCustomModel } from './CustomModel';\nimport type { IImplicitFilter, IItemFilter } from '../core/ItemFilter';\nimport CustomModelFilter from './CustomModelFilter';\nimport TrainingSetFilter from './TrainingSetFilter';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type LibraryFilter from '../libraries/LibraryFilter';\n\nexport interface ICustomModelDashboardFilterOptions {\n    customModelFilter?: IItemFilter<CustomModel>\n    trainingSetFilter?: IItemFilter<Library>\n}\n\nexport default class ImplicitCustomModelDashboardFilter implements IImplicitFilter<CustomModel | Library> {\n    private _customModelFilter?: IImplicitFilter<CustomModel>;\n    private _trainingSetFilter?: IImplicitFilter<Library>;\n\n    constructor(options: ICustomModelDashboardFilterOptions = {}) {\n        this._customModelFilter = options.customModelFilter || new CustomModelFilter();\n        this._trainingSetFilter = options.trainingSetFilter || new TrainingSetFilter();\n    }\n\n    get _owner() {\n        return this._trainingSetFilter ? (this._trainingSetFilter as LibraryFilter)._owner : undefined;\n    }\n\n    get _roles() {\n        return this._trainingSetFilter ? (this._trainingSetFilter as LibraryFilter)._roles : undefined;\n    }\n\n    matches(item: AdobeAsset): boolean {\n        if (isCustomModel(item)) {\n            return !!this._customModelFilter && this._customModelFilter.matches(item);\n        }\n\n        if (isLibrary(item)) {\n            return !!this._trainingSetFilter && this._trainingSetFilter.matches(item);\n        }\n\n        return false;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type {\n    CustomModelConfig,\n    CustomModelDashboardConfig,\n    CustomModelDashboardSource,\n    CustomModelSearchConfig,\n    CustomModelSearchSource,\n    CustomModelSource,\n} from './CustomModelSource';\nimport { memoize } from '../core/decorators';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type ItemPool from '../core/ItemPool';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport ItemSource from '../core/ItemSource';\nimport CustomModelLoader from '../custom-models/CustomModelLoader';\nimport type CustomModel from './CustomModel';\nimport { CustomModelUpdaterMelville } from './CustomModel';\nimport CustomModelSearchLoader from './CustomModelSearchLoader';\nimport CustomModelInterface from '../interface/CustomModelInterface';\nimport CustomModelSearchFilter from './CustomModelSearchFilter';\nimport ImplicitCustomModelFilter from './ImplicitCustomModelFilter';\nimport type Library from '../libraries/Library';\nimport { LibraryUpdater } from '../libraries/Library';\nimport type { LibraryConfig, LibrarySource } from '../libraries/LibrarySource';\nimport LibraryInterface from '../interface/LibraryInterface';\nimport LibraryListLoader from '../libraries/LibraryListLoader';\nimport ImplicitLibraryFilter from '../libraries/ImplicitLibraryFilter';\nimport type {\n    CreateTrainingSetOptions,\n    CustomModelCreateOptions,\n    CustomModelTrainingConfiguration,\n    CustomModelUpdateInfoMelville,\n} from '../interface/CustomModelModel';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport LegacyCustomModelContext from './legacy-cme/LegacyCustomModelContext';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport type { ICustomModelListingOptions } from './CustomModelFilter';\nimport CustomModelFilter from './CustomModelFilter';\nimport { default as CustomModelOrder, type CustomModelOrderField } from './CustomModelOrder';\nimport ImplicitCustomModelDashboardFilter from './ImplicitCustomModelDashboardFilter';\nimport { type  LibraryFilterOptions } from '../libraries/LibraryFilter';\nimport { default as TrainingSetFilter } from './TrainingSetFilter';\nimport { default as LibraryOrder, type  LibraryOrderField } from '../libraries/LibraryOrder';\n\n/**\n * Provides Custom Model functionality such as listing.\n *\n * @experimental This API is in an experimental phase so expect that\n * API's will not be final and there will be breaking changes\n * without bumping the major version until this comment is removed.\n */\nexport default class CustomModelContext implements ISAMObject, SAM.CustomModelContext  {\n    readonly _customModelInterface = new CustomModelInterface(this._core);\n\n    constructor(\n        /** @package -- for use in SAM.js only\n         */\n        readonly _core: ISAMCorePrivate,\n        /** @package -- for use in SAM.js only\n         */\n        readonly _assetPool: ItemPool<CustomModel | AdobeAsset>) {\n    }\n\n    /** @package -- only for use in SAM.js Updaters shouldn't be accessed directly.\n     */\n    readonly _customModelUpdaterMelville =  CustomModelUpdaterMelville;\n\n    /** @package -- only for use in SAM.js\n     */\n    private _LegacyCustomModelContext: LegacyCustomModelContext | undefined;\n\n    /** @deprecated -- prefer use of CustomModelContext\n     */\n    get legacyCustomModelContext() {\n        if (!this._LegacyCustomModelContext) {\n            this._LegacyCustomModelContext = new LegacyCustomModelContext(this._core, this._assetPool);\n        }\n\n        return this._LegacyCustomModelContext;\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    private readonly _libraryInterface: LibraryInterface = new LibraryInterface(this._core);\n\n    /**\n   * The accuracy of a search source is ephemeral in that after the search is executed, the collection of returned assets\n   * returned can no longer be assumed to be the complete set of assets that meet the search criteria. ie as new assets\n   * are added/removed which should alter assets in the source, the source will not be live updated and will need to be\n   * recreated (refetched) from USS to get the latest set of qualifying assets.\n   */\n    customModelSearchSource(query: string): CustomModelSearchSource {\n        const implicitFilter = new CustomModelSearchFilter({ query });\n\n        return new ItemSource<CustomModelSearchConfig>(\n            this._assetPool as ItemPool<CustomModel>,\n            [ new CustomModelSearchLoader(this._core, this) ],\n            implicitFilter\n        );\n    }\n\n\n    /*This source contains:\n     *  - All training sets a user has access to\n     *  - All custom models for which the user is a generator\n     * The only way to detect if the user is a generator is to filter out the custom models where the user DOES have access to the training set.\n     * However, since that takes a very long time in cases where there are many training sets, we're going to instead use the heuristic\n     * that a generator typically has read, but not write or comment permissions.\n     * This is subject to change in the future, and hopefully we come up with a better solution for determining which custom models to include in this view.\n     */\n    customModelDashboardSource(): CustomModelDashboardSource {\n        //don't use the same source as the full training set list, to leave open the possibility of a filter on the training sets\n        const implicitFilter = new ImplicitCustomModelDashboardFilter({\n            //filter out custom models where we have access to the training set id\n            customModelFilter: new ImplicitCustomModelFilter({ generatorOnly: true }),\n            trainingSetFilter: ImplicitLibraryFilter.TrainingSets }\n        );\n        return new ItemSource<CustomModelDashboardConfig>(\n            this._assetPool as ItemPool<CustomModel | Library>,\n            [\n                new CustomModelLoader<CustomModelDashboardConfig>(\n                    this._assetPool,\n                    this._core,\n                    this._customModelInterface\n                ),\n                new LibraryListLoader<CustomModelDashboardConfig>(\n                    this._assetPool as ItemPool<AdobeAsset | Library>,\n                    this._libraryInterface,\n                    LibraryUpdater,\n                    this._core\n                )\n            ],\n            implicitFilter\n        );\n    }\n\n    /**\n   * @example\n   * const customModelContext = samCore.customModelContext;\n   * const customModelSource = customModelContext.customModelSource;\n   *\n   * Gets all custom models a user has access to\n   */\n    @memoize\n    get customModelSource(): CustomModelSource {\n        return new ItemSource<CustomModelConfig>(\n            this._assetPool as ItemPool<CustomModel>,\n            [\n                new CustomModelLoader<CustomModelConfig>(\n                    this._assetPool,\n                    this._core,\n                    this._customModelInterface\n                ),\n            ],\n            new ImplicitCustomModelFilter()\n        );\n    }\n\n\n\n    @keepAlive\n    async createTrainingSet(options: CreateTrainingSetOptions): Promise<Library> {\n        return this._customModelInterface.createTrainingSet(options);\n    }\n\n    /**\n     * Returns the `TrainingSetSource` which will return a list of training set libraries the user has access to.\n     * @example\n     * const context = await core.getCustomModelContext();\n     * const order = new LibraryOrder('ascending', 'modified');\n     * const filter = TrainingSetFilter.DEFAULT;\n     * const list = await context.trainingSetsSource().getList(order, filter, loadOptions);\n     * list.on(STATE_CHANGED, () => {\n     *     if (list.status !== AssetListStatus.Loading) { const trainingSets = list.items; }\n     * });\n     */\n    @memoize\n    async trainingSetsSource(): Promise<LibrarySource> {\n        const libraryContext = await this._core.getLibraryContext();\n        const loader = new LibraryListLoader<LibraryConfig>(\n            libraryContext._assetPool,\n            this._libraryInterface,\n            LibraryUpdater,\n            this._core\n        );\n        return new ItemSource<LibraryConfig>(libraryContext._assetPool as ItemPool<Library>, [ loader ], ImplicitLibraryFilter.TrainingSets);\n    }\n\n    /* We need to always fetch remotely because local training sets might have been populated by a melville listing,\n     * and those training sets don't have custom model data.\n     */\n    @keepAlive\n    async getTrainingSetById(assetId: string): Promise<Library | undefined> {\n        return this._customModelInterface.getTrainingSetById(assetId);\n    }\n\n    /**\n     * Update a training set's metadata\n     * @param assetId Training set asset ID\n     * @param metadata metadata object to update the training set with\n     * @param overwrite boolean indicating whether to overwrite existing metadata or merge it with the new metadata.\n     * To delete a metadata field, set overwrite to true and exclude the field from the metadata object.\n     */\n    async updateTrainingSet(assetId: string, metadata: Partial<CustomModelTrainingConfiguration>, overwrite: boolean = false): Promise<void> {\n        // If overwrite is true and the metadata payload doesn't have all required fields, throw an error\n        if (overwrite && (!metadata.schemaVersion || !metadata.trainingMode)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Schema version and training mode are required fields on the training set metadata. To overwrite all metadata, these must be included in the payload.');\n        }\n\n        const trainingSet = await this.getTrainingSetById(assetId);\n\n        if (!trainingSet) {\n            throw SAMError.create(SAMErrorCode.NOT_FOUND, 'Training set not found');\n        }\n\n        let payload;\n        // If overwrite is false, merge existing metadata with passed in metadata to make sure we don't overwrite old metadata fields\n        if (!overwrite) {\n            payload = {\n                ['firefly#cme']: {\n                    ...trainingSet.customModelInfo,\n                    ...metadata\n                }\n            };\n        } else {\n            payload = {\n                ['firefly#cme']: {\n                    ...metadata\n                }\n            };\n        }\n\n        await this._libraryInterface.updateMetadata(trainingSet.id, payload);\n        // TODO: If Melville changes the PUT libraries metadata endpoint to return the updated item, we need to remove refetching the item\n        // JIRA: https://jira.corp.adobe.com/browse/GLOW-467\n        // `getTrainingSetById` will fetch from remote and update the local item\n        await this.getTrainingSetById(trainingSet.id);\n    }\n\n    @keepAlive\n    async createCustomModel(options: CustomModelCreateOptions): Promise<CustomModel> {\n        const customModelData = await this._customModelInterface.createCustomModel(options);\n\n        const session = this._assetPool.createMutationSession<CustomModel>();\n        const customModel = this._customModelUpdaterMelville.updateRemoteItem(session, customModelData);\n        session.commit();\n\n        return customModel;\n    }\n\n    /**\n     * Fetch the custom model from the server, update the remote/local cache, and return it.\n     * @param customModelId The ID of the custom model to fetch\n     * @returns The updated custom model\n     */\n    private async _fetchAndUpdateCustomModelById(customModelId: string): Promise<CustomModel> {\n        const customModelData = await this._customModelInterface.getCustomModelById(customModelId);\n        const session = this._assetPool.createMutationSession<CustomModel>();\n        const customModel = this._customModelUpdaterMelville.updateRemoteItem(session, customModelData);\n        session.commit();\n\n        return customModel;\n    }\n\n    /**\n     * Fetches one custom model by its ID.\n     * Will first check the local asset pool for the custom model and return it if found.\n     * If not found, will fetch the custom model from the server and return it.\n     * @param customModelId\n     * @returns\n     */\n    @keepAlive\n    async getCustomModelById(customModelId: string): Promise<CustomModel> {\n        // Check if we have the custom model in the local item pool\n        const customModel = this._assetPool.getLocalItemById<CustomModel>(customModelId);\n        if (customModel) {\n            if (!customModel.isCustomModel) {\n                throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Attempting to fetch asset type that is not a custom model');\n            }\n            return customModel;\n        }\n\n        // If not, fetch it from the server\n        return this._fetchAndUpdateCustomModelById(customModelId);\n    }\n\n    /**\n     * Given an id and CustomModelUpdateInfoMelville, update the custom model with the new data.\n     * @param customModelId string\n     * @param options CustomModelUpdateInfoMelville\n     */\n    async updateCustomModel(customModelId: string, options: CustomModelUpdateInfoMelville): Promise<void> {\n        // Update the custom model in Melville\n        await this._customModelInterface.updateCustomModel(customModelId, options);\n        // Update the local custom model with the new data\n        await this._fetchAndUpdateCustomModelById(customModelId);\n    }\n\n    /**\n     * @experimental\n     */\n    getCustomModelOrder(direction: IOrderDirection = 'descending', field: CustomModelOrderField = 'modified'): CustomModelOrder {\n        return new CustomModelOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getCustomModelFilter(options?: Partial<ICustomModelListingOptions | undefined>): CustomModelFilter {\n        return new CustomModelFilter(options);\n    }\n\n    /**\n     * @experimental\n     */\n    getTrainingSetOrder(direction: IOrderDirection = 'descending', field: LibraryOrderField = 'modified'): LibraryOrder {\n        return new LibraryOrder(direction, field);\n    }\n\n    /**\n     * @experimental\n     */\n    getTrainingSetFilter(options?: Pick<LibraryFilterOptions, 'project'>): TrainingSetFilter {\n        return new TrainingSetFilter(options);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { FIREFLY_GENERATIONS_DIRECTORY } from '../interface/GenerationHistoryAssetModel';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport ImplicitAdobeAssetFilterBase from '../assets/ImplicitAdobeAssetFilterBase';\nimport type { IItemFilter } from '../core/ItemFilter';\nimport { isGenerationHistoryAsset } from './utils';\n\nexport default class ImplicitGenerationHistoryAssetFilter extends ImplicitAdobeAssetFilterBase implements IItemFilter<AdobeAsset> {\n    matches(item: AdobeAsset) {\n        return isGenerationHistoryAsset(item) && item.repoPath?.startsWith('/' + FIREFLY_GENERATIONS_DIRECTORY + '/');\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { AdobeAsset, GenerationHistoryAssetFilter } from 'src';\nimport type { IItemLoader, IItemLoaderOptions, ILoadedPage, ILoadNextPage } from '../core/ItemLoader';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type GenerationHistoryInterface from '../interface/GenerationHistoryInterface';\nimport type { MelvilleLink } from '../interface/LibraryModel';\n\nimport type {\n    MelvilleGenerationHistoryAssetsParams,\n    MelvilleGenerationHistoryAssetsResponse\n} from '../interface/GenerationHistoryAssetModel';\nimport {\n    FIREFLY_GENERATIONS_DIRECTORY,\n    HISTORY_ASSET_TYPE_TO_MEDIA_TYPE\n} from '../interface/GenerationHistoryAssetModel';\n\nimport { GenerationHistoryAssetUpdater } from './GenerationHistoryAsset';\nimport FavoriteAdobeAssetOrder from '../assets/FavoriteAdobeAssetOrder';\nimport AdobeAssetFilter from '../assets/AdobeAssetFilter';\nimport { AdobeAssetUpdater } from '../assets/AdobeAsset';\nimport type { GenerationHistoryAssetConfig } from '../generation-history/GenerationHistoryAssetSource';\n\nconst $GH_DIR_REF = Symbol('GenerationHistoryDirectoryRef');\nconst $GH_FAVORITES_LIST_REF = Symbol('GenerationHistoryFavoritesListRef');\n\nexport default class GenerationHistoryAssetLoader implements IItemLoader<GenerationHistoryAssetConfig> {\n    constructor(\n        private _core: ISAMCorePrivate,\n        private _generationHistoryInterface: GenerationHistoryInterface\n    ) {}\n\n    async loadPage(options: IItemLoaderOptions<GenerationHistoryAssetConfig>) {\n        return await this._loadPage(options);\n    }\n\n    /**\n   * Loads assets from the supergraph. This is used to load assets from the supergraph which utilizes a directory listing and is more performant than Melville which relies on USS.\n   * However we will still need to go Melville to get a listing of assets by generationGroupId.\n   * @param options - The options for the loader.\n   * @param pageLink - The page link to load.\n   * @returns The assets.\n   */\n    private async _loadAssetsFromSupergraph(\n        options: IItemLoaderOptions<GenerationHistoryAssetConfig>,\n        after?: string\n    ): Promise<ILoadedPage<GenerationHistoryAssetConfig>> {\n        const gqlManager = await this._core._getGQLManager();\n\n        const { loadOptions: { limit: first = 50 } = {}, order, filter } = options;\n\n        const { historyAssetTypes } = filter as GenerationHistoryAssetFilter ?? {};\n\n        //@ts-expect-error\n        options.filter[$GH_FAVORITES_LIST_REF] = this._core.hostAssetContext.favoriteAssetsSource.getList(FavoriteAdobeAssetOrder.default, new AdobeAssetFilter({ mediaTypes: historyAssetTypes.map(type => HISTORY_ASSET_TYPE_TO_MEDIA_TYPE[type]) }), { loadAllPages: true });\n\n        const result = await gqlManager.getGenerationHistoryAssets({\n            first,\n            after,\n            orderBy: [\n                {\n                    direction: order.direction === 'ascending' ? 'ASCENDING' : 'DESCENDING',\n                    field: 'CREATE_DATE'\n                }\n            ],\n            filter: {\n                dc_format: historyAssetTypes.map(type => HISTORY_ASSET_TYPE_TO_MEDIA_TYPE[type])\n            }\n        }, options.resource);\n\n        const mostRecentValidMutation = Date.now() - this._core._environment.getValue('GQL_LIST_UPDATE_LATENCY');\n\n        const session = this._core\n            ._getAssetPool()\n            .createLoaderUpdateSession<AdobeAsset>(mostRecentValidMutation);\n\n        const items = AdobeAssetUpdater.updateRemoteItems(\n            session,\n            result.items\n        );\n\n        session.commit();\n\n        let loadNextPage: ILoadNextPage<GenerationHistoryAssetConfig> | undefined;\n\n        if (result.pageInfo.hasNextPage) {\n            loadNextPage = (options: IItemLoaderOptions<GenerationHistoryAssetConfig>) =>\n                this._loadAssetsFromSupergraph(options, result.pageInfo.endCursor ?? undefined);\n        }\n\n        return {\n            items,\n            loadNextPage\n        };\n    }\n\n    private async _loadPage(\n        options: IItemLoaderOptions<GenerationHistoryAssetConfig>,\n        pageLink?: MelvilleLink\n    ): Promise<ILoadedPage<GenerationHistoryAssetConfig>> {\n        let result: MelvilleGenerationHistoryAssetsResponse;\n\n\n        if (!(options.filter as GenerationHistoryAssetFilter).generationGroupId) {\n            return await this._loadAssetsFromSupergraph(options);\n        }\n\n        if (pageLink) {\n            // We are loading the next page with the link provided.\n            result = await this._generationHistoryInterface.getGenerationHistoryAssetsUsingPageLink(pageLink, options.resource);\n        } else {\n            const { order } = options;\n            const { limit } = options.loadOptions ?? {};\n\n            const { generationGroupId, historyAssetTypes } = options.filter as GenerationHistoryAssetFilter ?? {};\n            const queryParams: MelvilleGenerationHistoryAssetsParams = {};\n            queryParams.orderBy = order.direction === 'ascending' ? 'created_date' : '-created_date';\n            generationGroupId && (queryParams.generationGroupId = generationGroupId);\n            historyAssetTypes.length && (queryParams.generationType = historyAssetTypes.join(','));\n\n            if (limit) {\n                queryParams.limit = limit;\n                if (!queryParams.start) {\n                    queryParams.start = 0;\n                }\n            }\n\n            const assetsPromise = this._generationHistoryInterface.getGenerationHistoryAssets(queryParams, options.resource);\n\n            // Keep reference to a fully loaded favorites list (filtered on the GHA mimetype)\n            // Attaching the list to an instance of the filter allows those assets to be GC'd when GHAs from this loader\n            // are no longer being referenced.\n            // Fetching favorites allows us to instantiate assets in the item pool which include whether or not that\n            // asset is a favorite (we need this as favorites data is not returned from Melville)\n            // TODO: Once we can get the data from Melville, remove this list. Fetching two lists here\n            // could cause bad performance. See https://jira.corp.adobe.com/browse/GLOW-890\n            //@ts-expect-error\n            options.filter[$GH_FAVORITES_LIST_REF] = this._core.hostAssetContext.favoriteAssetsSource.getList(FavoriteAdobeAssetOrder.default, new AdobeAssetFilter({ mediaTypes: historyAssetTypes.map(type => HISTORY_ASSET_TYPE_TO_MEDIA_TYPE[type]) }), { loadAllPages: true });\n\n            // wait for the favorite assset query to resolve as well as generation history assets before returning\n            // results in GHA list\n            const [ assetsResponse ] = await Promise.all([\n                assetsPromise,\n\n                // Note: most GHAs will likely exist in the ghaFolder. Keeping a ref to it let SAMs optimize ONS monitoring to\n                // just the folder for most GHAs, and enables ONS notifications for new GHAs generated. Attaching to the\n                // explicit filter ensures the ghaFolder gets GC'd with the list, then SAM can stop monitoring it via ONS.\n                // @ts-expect-error\n                this.getDefaultGHAFolder().then(folder => options.filter[$GH_DIR_REF] = folder)\n            ]);\n\n            result = assetsResponse;\n        }\n\n        const latency = this._core._environment.getValue('USS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n        const session = this._core._getAssetPool().createLoaderUpdateSession<AdobeAsset>(mostRecentValidMutation);\n        const items = GenerationHistoryAssetUpdater.updateRemoteItems(session, result.listings);\n        session.commit();\n\n        let loadNextPage: ILoadNextPage<GenerationHistoryAssetConfig> | undefined;\n        const nextPageLink = result._links?.next;\n\n        if (nextPageLink) {\n            loadNextPage = (options: IItemLoaderOptions<GenerationHistoryAssetConfig>) =>\n                this._loadPage(options, nextPageLink);\n        }\n\n        return {\n            items,\n            total: result.total_count,\n            loadNextPage,\n            mostRecentValidMutation\n        };\n    }\n\n    async getDefaultGHAFolder() {\n        const generationHistoryContext = await this._core.getGenerationHistoryContext();\n        const { _fireflyGenerationsDirectoryID: _fireflyGenrationsDirectoryID } = generationHistoryContext;\n\n        // attempt to resolve FIREFLY_GENERATIONS_DIRECTORY, create if needed\n        const generationsDirectory = _fireflyGenrationsDirectoryID\n            ? await this._core.hostAssetContext.getAssetWithCloudID(_fireflyGenrationsDirectoryID)\n            : await this._core.hostAssetContext.getAssetWithRepoPath(`/${FIREFLY_GENERATIONS_DIRECTORY}`)\n                .then(directory => directory)\n                .catch(async (err: any) => {\n                    if (err.code === SAMErrorCode.NOT_FOUND) {\n                        const homeFolder = await this._core.hostAssetContext.getHomeFolder();\n                        const assetInterface = await homeFolder._getAssetInterface();\n                        const assetData = await assetInterface.createFolder(FIREFLY_GENERATIONS_DIRECTORY);\n                        const createdDirectory = this._core.hostAssetContext._createAssetFromMetadata(assetData!);\n                        return createdDirectory;\n                    }\n\n                    throw SAMError.create(\n                        SAMErrorCode.UNKNOWN,\n                        'SAM was unable to resolve or create the firefly-generations directory'\n                    );\n                });\n\n        generationHistoryContext._fireflyGenerationsDirectoryID = generationsDirectory.cloudID;\n\n        return generationsDirectory;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { GenerationHistoryAssetFilter, IItemSourceConfig } from 'src';\nimport type {\n    IItemLoaderOptions,\n    IItemLoader,\n    ILoadedPage,\n} from '../core/ItemLoader';\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport { getGenerationGroupId } from './utils';\n\n/**\n * Loads siblings of the same generationGroupId that are already in the assetPool, so they appear in\n * the UI right away even if SAM has to go to the server to check if there are more.\n */\nexport default class GenerationSiblingLoader<Config extends IItemSourceConfig> implements IItemLoader<Config> {\n    constructor(\n        private _core: ISAMCorePrivate\n    ) {}\n\n    async loadPage(options: IItemLoaderOptions<Config>) {\n        return await this._loadPage(options);\n    }\n\n    private async _loadPage(options: IItemLoaderOptions<Config>): Promise<ILoadedPage<Config>> {\n        const { generationGroupId } = options.filter as GenerationHistoryAssetFilter ?? {};\n\n        if (!generationGroupId) {\n            return { items: [] };\n        }\n\n        return { items: this._core._getAssetPool().toArray().filter(item => getGenerationGroupId(item) === generationGroupId) };\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { SAM } from '@ccx-public/component-types';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type ItemPool from '../core/ItemPool';\nimport ItemSource from '../core/ItemSource';\nimport type { ISAMCorePrivate, ISAMObject } from '../indexPrivate';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { memoize } from '../core/decorators';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport GenerationHistoryInterface from '../interface/GenerationHistoryInterface';\nimport { GenerationHistoryAssetUpdater } from './GenerationHistoryAsset';\nimport { isGenerationHistoryAsset } from './utils';\nimport ImplicitGenerationHistoryAssetFilter from './ImplicitGenerationHistoryAssetFilter';\nimport GenerationHistoryAssetLoader from './GenerationHistoryAssetLoader';\nimport type { GenerationHistoryAssetConfig } from './GenerationHistoryAssetSource';\nimport GenerationHistorySiblingLoader from './GenerationHistorySiblingLoader';\nimport type {\n    IGenerationHistoryFilterParams\n} from './GenerationHistoryAssetFilter';\nimport {\n    default as GenerationHistoryAssetFilter,\n    type IGenerationHistoryAssetListingOptions\n} from './GenerationHistoryAssetFilter';\nimport type { IOrderDirection } from '../core/ItemOrder';\nimport { default as GenerationHistoryAssetOrder, type GenerationHistoryAssetOrderField } from './GenerationHistoryAssetOrder';\nimport * as generationHistoryUtils from './utils';\nimport type { PredefinedPrincipal, UpdateAccessRequest } from '@sam-js-src/sharing/SharingContext';\nimport { MEDIA_TO_HISTORY_ASSET_TYPE, HISTORY_ASSET_TYPE_TO_MEDIA_TYPE, GENERATION_HISTORY_MEDIA_TYPES } from '../interface/GenerationHistoryAssetModel';\n\nconst ERROR_MESSAGE_SHARING_RESTRICTION = 'security/sharingRestriction';\ntype PublicLinkResponse = {\n    link: string;\n    permission: PredefinedPrincipal;\n};\n\nconst _throwIfFailedCollaborators = (updateAccessResult: SAM.UpdateAccessResult) => {\n    const failedCollaborators = updateAccessResult.filter(\n        r => r.action === 'add' && r.error\n    );\n    if (failedCollaborators.length > 0) {\n        throw failedCollaborators[0].error;\n    }\n};\n\n/**\n * Provides Generation History functionality such as listing.\n *\n * @experimental This API is in an experimental phase so expect that\n * API's will not be final and there will be breaking changes\n * without bumping the major version until this comment is removed.\n */\nexport default class GenerationHistoryContext implements ISAMObject, SAM.GenerationHistoryContext {\n    readonly _generationHistoryInterface = new GenerationHistoryInterface(this._core);\n    readonly _generationHistoryAssetUpdater = GenerationHistoryAssetUpdater;\n    /** @package -- for use in SAM.js only */\n    _fireflyGenerationsDirectoryID?: string;\n\n    constructor(\n        /** @package -- for use in SAM.js only\n         */\n        readonly _core: ISAMCorePrivate,\n        /** @package -- for use in SAM.js only\n         */\n        readonly _assetPool: ItemPool<AdobeAsset>\n    ) {}\n\n    @memoize\n    get generationHistorySource() {\n        return new ItemSource<GenerationHistoryAssetConfig>(\n            this._assetPool as ItemPool<AdobeAsset>,\n            [\n                new GenerationHistoryAssetLoader(this._core, this._generationHistoryInterface),\n                new GenerationHistorySiblingLoader(this._core)\n            ],\n            new ImplicitGenerationHistoryAssetFilter());\n    }\n\n    @keepAlive\n    async getGenerationHistoryAssetById(assetId: string): Promise<AdobeAsset> {\n        const localAsset = this._assetPool.getLocalItemById<AdobeAsset>(assetId);\n        if (localAsset) {\n            if (!isGenerationHistoryAsset(localAsset)) {\n                throw SAMError.create(SAMErrorCode.INVALID_OPERATION, 'Attempting to fetch asset type that is not a generation history asset');\n            }\n            return localAsset;\n        }\n\n        // supplement get by ID with a call to graphql so we can acquire favorites data\n        // TODO: would be better here if GQLManager exposed a method which takes a raw query string allowing us to just request:\n        // gql`labels { favorite { isFavorite }}``\n        const { isFavorite } = await (await this._core._getGQLManager()).getAssetById(assetId);\n        const remoteHistoryAssetData = await this._generationHistoryInterface.getGenerationHistoryAssetById(assetId);\n        const session = this._assetPool.createMutationSession<AdobeAsset>();\n        const historyAsset = this._generationHistoryAssetUpdater.updateRemoteItem(session, { ...remoteHistoryAssetData, isFavorite });\n        session.commit();\n\n        return historyAsset;\n    }\n\n    get generationHistoryUtils() {\n        return { ...generationHistoryUtils, MEDIA_TO_HISTORY_ASSET_TYPE, HISTORY_ASSET_TYPE_TO_MEDIA_TYPE, GENERATION_HISTORY_MEDIA_TYPES };\n    }\n\n    /**\n     * @experimental\n     */\n    getGenerationHistoryAssetFilter(options: Partial<IGenerationHistoryAssetListingOptions>) {\n        const params: Partial<IGenerationHistoryFilterParams> = options;\n        params.featureFlags = {\n            generationHistoryVectors: this._core._environment.getValue('FEATURE_FLAGS')?.['generation-history-vectors'] ?? false,\n            generationHistoryAudio: this._core._environment.getValue('FEATURE_FLAGS')?.['generation-history-audio'] ?? false\n        };\n        return new GenerationHistoryAssetFilter(params);\n    }\n\n    /**\n     * @experimental\n     */\n    getGenerationHistoryAssetOrder(direction: IOrderDirection = 'descending', field: GenerationHistoryAssetOrderField = 'created') {\n        return new GenerationHistoryAssetOrder(direction, field);\n    }\n\n\n    /**\n     * @param assetId The asset ID of the asset to get the public link for.\n     * @returns A promise that resolves to an object containing the public link for the asset and the permission the asset was set to.\n     * @experimental This API is still in development.\n     */\n    async getPublicLink(assetId: string): Promise<PublicLinkResponse> {\n        const updateRequest: UpdateAccessRequest = {\n            mode: 'all',\n            role: 'viewer',\n            canShare: false,\n            canComment: true\n        };\n        let targetPermission = 'all' as PredefinedPrincipal;\n        const sharingContext = await this._core.getSharingContext();\n        await sharingContext.updateAccess(assetId, updateRequest).then(_throwIfFailedCollaborators).catch(e => {\n            // If asset sharing failed due to sharing restrictions by the org (403.1), swallow the error and attempt to share to orgEverybody\n            if (e.code === SAMErrorCode.ACCESS_DENIED && e.description === ERROR_MESSAGE_SHARING_RESTRICTION) {\n                targetPermission = 'orgEverybody';\n                return sharingContext.updateAccess(assetId, { ...updateRequest, mode: 'orgEverybody' }).then(_throwIfFailedCollaborators);\n            } else {\n                throw e;\n            }\n        });\n\n        // TODO: [GLOW-1331] Replace with the public link obtained from aupSdk.assetUtilityContext\n        const exposedLink = `https://firefly-stage.corp.adobe.com/open/${assetId}`;\n        return {\n            link: exposedLink,\n            permission: targetPermission\n        };\n    }\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport setURLSearchParams from '@sam-js-src/utils/searchParams';\nimport InterfaceBase from './InterfaceBase';\n\ninterface IWorkfrontLinkResponse {\n    UID: string;\n    workfrontObjectGuid: string;\n    workfrontType: string;\n    workfrontURL: string;\n}\n\nexport default class WorkfrontInterface extends InterfaceBase {\n    /**\n     * @TODO [SAMJS-729] replace with prod/stage urls once available.\n     */\n    public _getWorkfrontLinkURL() {\n        return `https://${this._core._environment.endpoints.WORKFRONT_HOST}/esm-connector/api/v1/search`;\n    }\n\n    async getWorkfrontLink(assetId: string, ordId: string): Promise<IWorkfrontLinkResponse> {\n        const url = new URL(`${this._getWorkfrontLinkURL()}?`);\n        setURLSearchParams(url, { 'UID': assetId });\n        const response = await this._doGet(url.toString(),  {\n            headers: {\n                'x-gw-ims-org-id': ordId\n            }\n        });\n        return response.json();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport type { IRepository } from '../interface/RepositoryModel';\nimport { RelType } from '../interface/LinkUtils';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport WorkfrontInterface from '../interface/WorkfrontInterface';\nimport ProjectsInterface from '../interface/ProjectsInterface';\nimport type { IOrganizationsResponse } from '../interface/OrganizationsModel';\nimport Resource from '../assets/Resource';\nimport { AccessControlModifier, AccessControlPrivileges, type AccessControlInheritance, type Principal } from '../access-control/AccessControlModel';\nimport { isDeepEqual } from '../core/ObjectUtils';\nimport SAMError, { SAMErrorCode } from '@sam-js-src/core/SAMError';\nimport type { AssetRGNRelType } from '../interface/AssetInterface';\n\nexport default class WorkfrontContext implements ISAMObject {\n    private _workfrontInterface: WorkfrontInterface;\n    constructor(\n        readonly _core: ISAMCorePrivate\n    ) {\n        this._workfrontInterface = new WorkfrontInterface(this._core);\n    }\n\n    /**\n     * Get an AdobeAsset from a given asset path and repository ID. This method is optimized\n     * to use to only get and build an asset based on repo-metadata without having to call\n     * all the other services to get additional data up-front (PUPA). To get the full asset you can\n     * still call either AssetContext.getAssetWithRepoPath or AssetContext.getAssetWithCloudID().\n     *\n     * @param assetPath The path to get the asset for.\n     * @param repositoryId The repository ID to get the asset for.\n     * @returns The AdobeAsset for the given asset path and repository ID.\n     */\n    public async getAssetWithRepoPath(assetPath: string, repositoryId: string): Promise<AdobeAsset> {\n        const assetContext = await this._core.getAssetContext();\n        const { data } = await assetContext._getRepoDataByPath(assetPath, repositoryId);\n        const session = assetContext._assetPool.createMutationSession();\n        const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ data ]);\n        const newAsset = this._core._adobeAssetFactory.assetFromRepoMetadata({\n            session,\n            repoMetadata: data,\n            updaters\n        });\n        session.commit();\n        return newAsset;\n    }\n\n    /**\n     * Get the repository information from the RAPI index-workfront endpoint.\n     * This is required to decouple workfront from SMU migration scenarios.\n     *\n     * @service Requires service principal token for authentication.\n     * @param orgId The organization ID to get the repository for.\n     * @returns The repository for the Workfront context.\n     */\n    async getRepository(orgId: string): Promise<IRepository> {\n        const assetContext = await this._core.getAssetContext();\n        const repositoryInterface = assetContext._rapi;\n        const workfrontRepositoryIndex = await repositoryInterface.getWorkfrontIndex(orgId);\n        const repositoryData = workfrontRepositoryIndex.newWorkfrontParentDir._embedded[RelType.REPO_METADATA];\n        return {\n            id: repositoryData['repo:repositoryId'],\n            path: repositoryData['repo:path'],\n            name: repositoryData['repo:name'],\n            links: repositoryData._links\n        };\n    }\n\n    /**\n     * Creates an AdobeAsset instance from a cloud ID. Note that this method always returns an AdobeAsset,\n     * even for specialized asset types like Projects or Libraries. Do not use this method if you need\n     * specialized asset behavior - for example, if you need Project-specific functionality, use the\n     * ProjectContext instead. This is intended to be a lightweight way to get an asset when only minimal\n     * metadata is needed.\n     *\n     * @param assetId The cloud ID of the asset\n     * @returns An AdobeAsset instance\n     */\n    async getAssetWithCloudID(assetId: string): Promise<AdobeAsset> {\n        const assetContext = await this._core.getAssetContext();\n        const repoMetadataResource = await assetContext._getAssetRepoDataWithCloudID(assetId);\n        const repoMetadata = repoMetadataResource.data;\n\n        const session = this._core._getAssetPool().createUpdateSession('getAssetWithCloudID');\n        const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ repoMetadata ]);\n        const asset = this._core._adobeAssetFactory.assetFromRepoMetadata({ session, repoMetadata, updaters });\n        session.commit();\n        return asset;\n    }\n\n    /**\n     * Get the Workfront link for a given asset ID and organization ID.\n     *\n     * @param assetId The cloud ID of the asset\n     * @param orgId Optional. The organization ID to get the Workfront link.\n     * @returns The Workfront link for the given asset ID and organization ID\n     */\n    async getWorkfrontLink(assetId: string, orgId?: string): Promise<string> {\n        let org;\n        if (orgId) {\n            org = orgId;\n        } else {\n            const organizationsResource = new Resource<IOrganizationsResponse>(this._core);\n            const projectInterface = new ProjectsInterface(this._core);\n            await projectInterface.getOrganizations(organizationsResource);\n            org = organizationsResource.data?.default;\n        }\n\n        const workfrontLink = await this._workfrontInterface.getWorkfrontLink(assetId, org);\n        return workfrontLink.workfrontURL;\n    }\n\n    /**\n     * @deprecated This method is no longer supported.\n     * Use {@link WorkfrontContext.setDeny} instead.\n     */\n    async setDenyWithDeepOverride(assetId: string): Promise<void> {\n        return Promise.reject(`Method is unimplemented, assetId: ${assetId}`);\n    }\n\n    private _getPrivileges(): AccessControlPrivileges[] {\n        return [\n            AccessControlPrivileges.ACK,\n            AccessControlPrivileges.READ,\n            AccessControlPrivileges.WRITE,\n            AccessControlPrivileges.DELETE\n        ];\n    }\n\n    /**\n     * Add the ACE using the requested inheritance and principal provided\n     * and the pre-configured deny rules.\n     *\n     * @param assetId The cloud ID of the asset\n     * @return void Promise\n     */\n    async setDeny(assetId: string, inheritance: AccessControlInheritance, principal: Principal): Promise<void> {\n        const accessControlContext = await this._core.getAccessControlContext();\n        const acl = await accessControlContext.getACL(assetId);\n        await acl.addACES([\n            {\n                inheritance,\n                principal,\n                privileges: this._getPrivileges(),\n                modifier: AccessControlModifier.DENY,\n                relations: []\n            }\n        ]);\n    }\n\n    /**\n     * Remove the ACE matching the requested inheritance and principal provided\n     * and the pre-configured deny rules.\n     *\n     * @param assetId The cloud ID of the asset\n     * @param inheritance The inheritance value used to set the ACE originally.\n     * @param principal The principal used to set the ACE originally.\n     * @return void Promise\n     */\n    async removeDeny(assetId: string, inheritance: AccessControlInheritance, principal: Principal): Promise<void> {\n        const accessControlContext = await this._core.getAccessControlContext();\n        const acl = await accessControlContext.getACL(assetId);\n        const findAce = acl.aces.find(\n            (ace) => {\n                const matchesAce =  ace.inheritance === inheritance\n                    && isDeepEqual(ace.principal, principal)\n                    && ace.isDeny\n                    && ace.privileges.every((privilege) => this._getPrivileges().includes(privilege))\n                    && ace.relations.length === 0;\n                return matchesAce;\n            }\n        );\n\n        if (findAce) {\n            await acl.removeACES([ findAce ]);\n            return;\n        }\n\n        // The requested inhertiance and princpal did not match any known ACEs.\n        throw SAMError.create(SAMErrorCode.NOT_FOUND, 'ACE matching the requested inheritance and principal was not found');\n    }\n\n    /**\n     * @deprecated use {@link WorkfrontContext.removeDeny} instead.\n     *\n     */\n    async removeDenyWithDeepOverride(assetId: string): Promise<void> {\n        return Promise.reject(`Method is unimplemented, assetId: ${assetId}`);\n    }\n\n    private async _getResourceGenerationNumber(assetId: string, relType: AssetRGNRelType): Promise<number> {\n        const assetContext = await this._core.getAssetContext();\n        const assetPool = assetContext._assetPool;\n        let asset = assetPool.getLocalItemById(assetId);\n        if (!asset) {\n            asset = await assetContext.getAssetWithCloudID(assetId, false);\n        }\n        await asset._ensureLink(relType);\n        const assetInterface = await asset._getAssetInterface();\n\n        const rgn = await assetInterface.getResourceGenerationNumber(relType);\n        if (!rgn) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Resource Generation Number not found, only available in Node environments');\n        }\n\n        const convertedRGN = Number(rgn);\n        if (isNaN(convertedRGN)) {\n            throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Resource Generation Number is not a number');\n        }\n\n        return convertedRGN;\n    }\n\n    /**\n     * Resource Generation Numbers\n     *\n     *\n     * Each Associated Resource has a Resource Generation Number,\n     * which is incremented whenever the Resource itself changes. While strictly increasing,\n     * it is not guaranteed to be gapless. Clients can use the Resource Generation Number to\n     * determine if the Resource, retrieved either through the API or an Asset Event, is more\n     * recent than a local copy of that resource. If retrieved through the API,\n     * the Resource-Generation header is used. If retrieved through an Asset Event,\n     * the event:resourceGeneration property is used.\n     */\n\n    /**\n     * Get the Resource Generation Number for the primary resource.\n     * The Resources-Generation header is not set in the CORS access-control-expose-header provided\n     * by the services behind RAPI. This means Browser based clients will not be able to get the\n     * Resource Generation Number for the primary resource.\n     *\n     * We also don't want to cache the Resource Generation Number for the primary resource\n     * as it may change rapidly over time.\n     */\n    async getPrimaryRGN(assetId: string): Promise<number> {\n        return this._getResourceGenerationNumber(assetId, RelType.PRIMARY);\n    }\n\n    /**\n     * Get the Resource Generation Number for the repository metadata.\n     * The Resources-Generation header is not set in the CORS access-control-expose-header provided\n     * by the services behind RAPI. This means Browser based clients will not be able to get the\n     * Resource Generation Number for the repository metadata.\n     *\n     * We also don't want to cache the Resource Generation Number for the repository metadata\n     * as it may change rapidly over time.\n     *\n     */\n    async getRepoMetadataRGN(assetId: string): Promise<number> {\n        return this._getResourceGenerationNumber(assetId, RelType.REPO_METADATA);\n    }\n\n    /**\n     * Get the Resource Generation Number for the application metadata.\n     * The Resources-Generation header is not set in the CORS access-control-expose-header provided\n     * by the services behind RAPI. This means Browser based clients will not be able to get the\n     * Resource Generation Number for the application metadata.\n     *\n     * We also don't want to cache the Resource Generation Number for the repository metadata\n     * as it may change rapidly over time.\n     *\n     */\n    async getAppMetadataRGN(assetId: string): Promise<number> {\n        return this._getResourceGenerationNumber(assetId, RelType.APP_METADATA);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ISAMCorePrivate } from '../indexPrivate';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport { key, synchronized } from '../core/decorators';\nimport { keepAlive } from '../core/decorators/KeepAliveManager';\nimport type { MinimalAssetLinks } from '../interface/RepositoryModel';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport RepoMetadataResource from '../assets/RepoMetadataResource';\nimport { LazyLoadManager } from '../core/decorators/LazyLoadManager';\nimport { STORAGE_ASSIGNEE_CHANGED } from '../assets/AssetEvents';\n\nexport type MinimalAssetLoadOptions = {\n    isCuratedCollectionAsset?: boolean\n}\n\nexport const DefaultMinimalAssetLoadOptions = {\n    isCuratedCollectionAsset: false\n};\n\ntype MinimalAssetProperties = {\n    isCuratedCollectionAsset: boolean\n}\n\nexport default class KnowledgeWorkspaceContext implements ISAMObject {\n    constructor(\n        readonly _core: ISAMCorePrivate\n    ) {}\n\n    // Tracks assets that have been requested via the KnowledgeWorkspaceContext. This may\n    // affect how SAM.js internally handles these assets re: ONS monitoring or other optimizations.\n    private _minimalAssets: WeakMap<AdobeAsset, MinimalAssetProperties> = new WeakMap<AdobeAsset, MinimalAssetProperties>;\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _isCuratedCollectionAsset(asset: AdobeAsset): boolean {\n        const assetProps = this._minimalAssets.get(asset);\n        return assetProps ? assetProps.isCuratedCollectionAsset : false;\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _isMinimalAsset(asset: AdobeAsset): boolean {\n        return this._minimalAssets.has(asset);\n    }\n\n    /**\n     * Gets the Asset with the given assetId, loading the minimal amount of data needed to create an AdobeAsset instance.\n     *\n     * @remarks\n     *\n     * A minimal `AdobeAsset` instance is only populated with the repo:metadata of the asset.\n     * No application metadata, effective permissions, or other properties are requested.\n     *\n     * If asset exists in the local cache, that existing instance will be returned.\n     *\n     * If asset does not exist in the local cache, a new minimal `AdobeAsset` instance will be created using the\n     * `RelType.REPO_METADATA` link to fetch the repo:metadata for the asset.\n     *\n     * The provided `assetLinks` are only used for the initial fetching of the repo:metadata. The links in the\n     * repo:metadata response will be used for future requests.\n     *\n     * Some AdobeAsset subtypes, such as Projects, Classrooms, etc., currently require application metadata to\n     * determine the correct subtype instance to create. Only use this method if you know that the requested\n     * asset is not one of these types. In the future, repo:metadata will contain the asset subtype, and\n     * we can remove this restriction.\n     *\n     * @param assetId {string} assetId of the desired asset.\n     * @param assetLinks {AssetLinks} set of asset links. `RelType.REPO_METADATA` link must be present to retrieve a minimal asset.\n     * @param loadOptions {MinimalAssetLoadOptions} options for loading the asset. These will not apply if asset is already present in ItemPool.\n     * @return AdobeAsset\n     */\n    @keepAlive\n    @synchronized\n    async getMinimalAssetWithAssetId(@key assetId: string, assetLinks: MinimalAssetLinks, loadOptions?: Partial<MinimalAssetLoadOptions>): Promise<AdobeAsset> {\n        return this._getMinimalAssetById(assetId, assetLinks, loadOptions);\n    }\n\n    @synchronized\n    private async _getMinimalAssetById(@key assetId: string, assetLinks: MinimalAssetLinks, loadOptions?: Partial<MinimalAssetLoadOptions>, repoMetadataResource?: RepoMetadataResource,): Promise<AdobeAsset> {\n        const assetContext = await this._core.getAssetContext();\n        const repositoryInterface = assetContext._rapi;\n        const asset = assetContext._assetPool.getLocalItemById(assetId);\n        if (asset) {\n            // If no repo:metadata resource provided and ONS is disabled, force refresh repo:metadata, because the data may be stale\n            const forceRefresh = this._core._environment.getValue('DISABLE_ONS');\n            if (!repoMetadataResource && forceRefresh) {\n                repoMetadataResource = new RepoMetadataResource(this._core);\n                await repositoryInterface.getRepoMetadataById(assetId, repoMetadataResource, assetLinks);\n            }\n\n            if (repoMetadataResource) {\n                const session = assetContext._assetPool.createMutationSession();\n                assetContext._adobeAssetUpdater.updateRemoteItem(session, repoMetadataResource.data);\n                session.commit();\n            }\n\n            return asset;\n        }\n\n        if (!repoMetadataResource) {\n            repoMetadataResource = new RepoMetadataResource(this._core);\n            await repositoryInterface.getRepoMetadataById(assetId, repoMetadataResource, assetLinks);\n        }\n\n        // Preserve any asset links provided by client when constructing the asset's repo:metadata.\n        const repoMetadata = repoMetadataResource.data;\n        repoMetadata._links = { ...repoMetadata._links, ...assetLinks };\n\n        const session = assetContext._assetPool.createMutationSession();\n        const updaters = await this._core._adobeAssetFactory.getRepoMetadataUpdaters([ repoMetadata ]);\n        const newAsset = this._core._adobeAssetFactory.assetFromRepoMetadata({\n            session,\n            repoMetadata,\n            updaters\n        });\n\n        const loadConfig = { ...DefaultMinimalAssetLoadOptions, ...loadOptions };\n        this._minimalAssets.set(newAsset, { isCuratedCollectionAsset: loadConfig.isCuratedCollectionAsset });\n\n        // Mark storage:assignee as loaded, if it is set from repo:metadata\n        if (repoMetadata && repoMetadata['storage:assignee'] && newAsset._storageAssignee_NoLazyLoad.id === repoMetadata['storage:assignee'].id) {\n            LazyLoadManager.updatedByItemUpdater(newAsset, STORAGE_ASSIGNEE_CHANGED);\n        }\n\n        session.commit();\n\n        newAsset._setResources({\n            repoMetadataResource,\n            effectivePermissionsResource: undefined,\n            appMetadataResource: undefined,\n            perUserMetadataResource: undefined\n        });\n\n        return newAsset;\n    }\n\n    /**\n     * Gets an Asset with the given assetPath and repositoryId, loading the minimal amount of data needed to create an AdobeAsset instance.\n     *\n     * @remarks\n     *\n     * A minimal `AdobeAsset` instance is only populated with the repo:metadata of the asset.\n     * No application metadata, effective permissions, or other properties are requested.\n     *\n     * The provided path should be the full path to the asset. It cannot be a relative path, such as\n     * a path relative to the user's /cloud-content folder.\n     *\n     * If the asset exists in the local cache, that existing instance will be returned. If the asset does not exist\n     * in the local cache, a new minimal `AdobeAsset` instance will be created using the `RelType.REPO_METADATA`\n     * link to fetch the repo:metadata for the asset.\n     *\n     * For performance reasons, if you have the assetId of the asset, you should use `getMinimalAssetWithAssetId()` instead. Because\n     * our item pool maps assets by assetId, if you request an asset by path, we will need to fetch the repo:metadata to get\n     * the assetId of the asset to see if it is in the local cache.\n     *\n     * The provided `assetLinks` are only used for the initial fetching of the repo:metadata. The links in the\n     * repo:metadata response will be used for future requests.\n     *\n     * Some AdobeAsset subtypes, such as Projects, Classrooms, etc., currently require application metadata to\n     * determine the correct subtype instance to create. Only use this method if you know that the requested\n     * asset is not one of these types. In the future, repo:metadata will contain the asset subtype, and\n     * we can remove this restriction.\n     *\n     * @param assetPath {string} full path for the asset\n     * @param repositoryId {string} repositoryID of the asset\n     * @param assetLinks {AssetLinks} set of asset links. `RelType.REPO_METADATA` link must be present to retrieve a minimal asset.\n     * @param loadOptions {MinimalAssetLoadOptions} options for loading the asset. These will not apply if asset is already present in ItemPool.\n     * @return AdobeAsset\n     */\n    @keepAlive\n    @synchronized\n    async getMinimalAssetWithRepoPath(assetPath: string, repositoryId: string, assetLinks: MinimalAssetLinks, loadOptions?: Partial<MinimalAssetLoadOptions>): Promise<AdobeAsset> {\n        return this._getMinimalAssetWithRepoPathImpl(assetPath, repositoryId, assetLinks, loadOptions);\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    @synchronized\n    private async _getMinimalAssetWithRepoPathImpl(assetPath: string, repositoryId: string, assetLinks: MinimalAssetLinks, loadOptions?: Partial<MinimalAssetLoadOptions>): Promise<AdobeAsset> {\n        const assetContext = await this._core.getAssetContext();\n        const repositoryInterface = assetContext._rapi;\n        let asset: AdobeAsset | undefined = undefined;\n        const repoMetadataResource = new RepoMetadataResource(this._core);\n        const repositoryMetadata = await repositoryInterface.getRepoMetadataByPath(\n            repositoryId!,\n            assetPath,\n            repoMetadataResource,\n            assetLinks\n        );\n        asset = await this._getMinimalAssetById(repositoryMetadata['repo:assetId'], assetLinks, loadOptions, repoMetadataResource);\n        return asset;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport type AdobeACE from './AdobeACE';\nimport type { AdobeACEMetadata } from './AccessControlModel';\nimport SAMError, { isSAMError, SAMErrorCode } from '../core/SAMError';\nimport type AssetInterface from '../interface/AssetInterface';\n\nexport default class AdobeACL implements ISAMObject {\n    constructor(\n        public _core: ISAMCorePrivate,\n        private _assetId: string,\n        private _etag: string,\n        private _aces: AdobeACE[] = [],\n        private _assetInterface: AssetInterface\n    ) {}\n\n    /**\n     * Returns a copy of the ACEs as an array\n     */\n    public get aces(): AdobeACE[] {\n        // Copy the ACEs to avoid mutating the original array\n        return [ ...this._aces ];\n    }\n\n    public set aces(value: AdobeACE[]) {\n        // Copy the ACEs from the original data to ensure it doesn't get mutated\n        this._aces = [ ...value ];\n    }\n\n    public get assetId(): string {\n        return this._assetId;\n    }\n\n    public get etag(): string {\n        return this._etag;\n    }\n\n    public set etag(value: string) {\n        this._etag = value;\n    }\n\n    public get isEmpty(): boolean {\n        return this._aces.length === 0;\n    }\n\n    private async _forceRefreshACL(): Promise<void> {\n        const accessControlContext = await this._core.getAccessControlContext();\n        await accessControlContext.getACL(this.assetId, true /* forceRefresh */);\n    }\n\n    private async _handleConflict(e: any) {\n        if (isSAMError(e)) {\n            if (e.code === SAMErrorCode.CONFLICT) {\n                // If the ETag does not match the server's ETag, it will throw\n                // a CONFLICT error. In this case, we should optimistically refresh\n                // the ACL from the server and try again.\n                await this._forceRefreshACL();\n            }\n        }\n        throw e;\n    }\n\n    /**\n     * Determines if there are any ACES with changes locally that have not been\n     * pushed to the server.\n     *\n     * @returns - an array of ACEs that have been modified locally\n     */\n    public hasDirtyACES(): boolean {\n        return this._aces.some(ace => ace._isDirty);\n    }\n\n    /**\n     * Removes the provided ACEs from the ACL.\n     *\n     * @param aces - The ACEs to remove from the ACL.\n     * @returns - The updated ACL.\n     */\n    public async removeACES(aces: AdobeACE[]): Promise<AdobeACE[]> {\n        // if there are any dirty ACEs, throw an error since\n        // this will clear the local changes and get new ACEs from the server\n        // so we want to give the client a chance to update the local ACEs.\n        if (this.hasDirtyACES()) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Cant delete ACEs with pending changes, these will be overwritten'\n            );\n        }\n\n        // Copy the ACEs to avoid mutating the original array\n        const copiedAces = [ ...aces ];\n        copiedAces.sort((ace1, ace2) => ace1.id < ace2.id ? 0 : -1);\n\n        try {\n            await this._assetInterface.deleteAccessControlEntries(aces, this._etag);\n        } catch (e) {\n            await this._handleConflict(e);\n        }\n\n        // If we made it this far, the ACEs were deleted successfully so let's\n        // fetch the new ACEs from the server and update the local ACEs.\n        await this._forceRefreshACL();\n        return this._aces;\n    }\n\n    /**\n     * Adds the provided ACEs to the ACL.\n     *\n     * @param aces - The ACEs to add to the ACL.\n     * @returns - The updated ACL.\n     */\n    public async addACES(aces: AdobeACEMetadata[]): Promise<AdobeACE[]> {\n        // if there are any dirty ACEs, throw an error since\n        // this will clear the local changes and get new ACEs from the server\n        // so we want to give the client a chance to update the local ACEs.\n        if (this.hasDirtyACES()) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Cant add ACES with pending changes, these will be overwritten'\n            );\n        }\n\n        await this._assetInterface.addAccessControlEntries(aces, this._etag);\n\n        // If we made it this far, the ACEs were added successfully so let's\n        // fetch the new ACEs from the server and update the local ACEs.\n        await this._forceRefreshACL();\n        return this._aces;\n    }\n\n    /**\n     * Commits and updates the local ACEs in this ACL with the servers ACL\n     *\n     * @throws {SAMErrorCode.CONFLICT} if the ETag does not match the server's ETag\n     *\n     */\n    public async updateACES() {\n        if (!this.hasDirtyACES()) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'No changes to commit'\n            );\n        }\n\n        const dirtyACES = this._aces.filter(ace => ace._isDirty);\n        try {\n            await this._assetInterface.updateAccessControlList(dirtyACES, this._etag);\n        } catch (e) {\n            await this._handleConflict(e);\n        }\n\n        // If we made it this far, the ACEs were updated successfully so let's\n        // fetch the new ACEs from the server and update the local ACEs.\n        await this._forceRefreshACL();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { RelType } from '../interface/LinkUtils';\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport type {\n    AccessControlPrivileges,\n    IAccessControlPrincipal } from './AccessControlModel';\nimport {\n    AccessControlInheritance,\n    AccessControlModifier,\n    RelTypePlatform\n} from './AccessControlModel';\nimport SAMError, { SAMErrorCode } from '@sam-js-src/core/SAMError';\n\nexport default class AdobeACE implements ISAMObject {\n    private __isDirty: boolean = false;\n    private __isDeleted: boolean = false;\n    constructor(\n        public readonly _core: ISAMCorePrivate,\n        /**\n         * Corresponds to the index of the ACE in the ACL response array.\n         */\n        public readonly id: number,\n        private _privileges: AccessControlPrivileges[],\n        private _modifier: AccessControlModifier,\n        private _inheritance: AccessControlInheritance,\n        private _relations: RelType[],\n        private _principal: IAccessControlPrincipal | string // @TODO this should be specific values for \"special\" principals instead of strings.\n    ) {}\n\n    private _checkIfDeleted(): void {\n        if (this.__isDeleted) {\n            throw SAMError.create(\n                SAMErrorCode.BAD_REQUEST,\n                'Cannot update a deleted ACE'\n            );\n        }\n    }\n\n    /**\n     * Whether this ACE has been modified since it was last committed to the server.\n     * @package - This property is intended for internal use only.\n     */\n    public get _isDirty(): boolean {\n        return this.__isDirty;\n    }\n\n    /**\n     * @package - This property is intended for internal use only.\n     */\n    public set _isDirty(value: boolean) {\n        this.__isDirty = value;\n    }\n\n    /**\n     * @package - This property is intended for internal use only.\n     */\n    public set _isDeleted(value: boolean) {\n        this.__isDeleted = value;\n    }\n\n    /**\n     * @package - This property is intended for internal use only.\n     */\n    public get _isDeleted(): boolean {\n        return this.__isDeleted;\n    }\n\n    public get principal(): IAccessControlPrincipal | string {\n        return this._principal;\n    }\n\n    public set principal(value: IAccessControlPrincipal | string) {\n        this._checkIfDeleted();\n        this._principal = value;\n        this._isDirty = true;\n    }\n\n    public get privileges(): AccessControlPrivileges[] {\n        return this._privileges;\n    }\n\n    public set privileges(value: AccessControlPrivileges[]) {\n        this._checkIfDeleted();\n        this._privileges = value;\n        this._isDirty = true;\n    }\n\n    public get modifier(): AccessControlModifier {\n        return this._modifier;\n    }\n\n    public set modifier(value: AccessControlModifier) {\n        this._checkIfDeleted();\n        this._modifier = value;\n        this._isDirty = true;\n    }\n\n    public get inheritance(): AccessControlInheritance {\n        return this._inheritance;\n    }\n\n    public set inheritance(value: AccessControlInheritance) {\n        this._checkIfDeleted();\n        this._inheritance = value;\n        this._isDirty = true;\n    }\n\n    public get relations(): RelType[] {\n        return this._relations;\n    }\n\n    public set relations(value: RelType[]) {\n        this._checkIfDeleted();\n        this._relations = value;\n        this._isDirty = true;\n    }\n\n    public get isDeny(): boolean {\n        return this._modifier === AccessControlModifier.DENY;\n    }\n\n    public get isGrant(): boolean {\n        return this._modifier === AccessControlModifier.GRANT;\n    }\n\n    public get isDeepInheritance(): boolean {\n        return this._inheritance === AccessControlInheritance.DEEP;\n    }\n\n    public get isSelfInheritance(): boolean {\n        return this._inheritance === AccessControlInheritance.SELF;\n    }\n\n    public get isDeepOverrideInheritance(): boolean {\n        return this._inheritance === AccessControlInheritance.DEEP_OVERRIDE;\n    }\n\n    public get isUserPrincipal(): boolean {\n        if (typeof this._principal === 'string') {\n            return false;\n        }\n        return this._principal['@type'] === RelTypePlatform.PRINCIPAL_TYPE_IMS_USER;\n    }\n\n    public get isGroupPrincipal(): boolean {\n        if (typeof this._principal === 'string') {\n            return false;\n        }\n        return this._principal['@type'] === RelTypePlatform.PRINCIPAL_TYPE_IMS_GROUP;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type { ISAMObject } from '../core/ISAMObject';\nimport AdobeACL from './AdobeACL';\nimport AdobeACE from './AdobeACE';\nimport type { IAccessControlEntryResponse } from './AccessControlModel';\nimport AssetInterface from '../interface/AssetInterface';\nimport { key, cache } from '../core/decorators';\nexport default class AccessControlContext implements ISAMObject {\n    private _aclCache: Map<string, WeakRef<AdobeACL>> = new Map();\n    constructor(\n        public _core: ISAMCorePrivate\n    ) {}\n\n    private _getCachedACL(assetId: string): AdobeACL | undefined {\n        const localACL = this._aclCache.get(assetId);\n        if (localACL) {\n            const aclDeref = localACL.deref();\n            if (aclDeref) {\n                return aclDeref;\n            }\n        }\n        return undefined;\n    }\n\n    /**\n     * Get the asset interface for the asset using memoize to increase session performance.\n     * If the AssetId is found locally in the asset pool we can just get\n     * the asset interface from that, otherwise let's construct just the asset\n     * interface we need to get the access control list. This way we won't have to\n     * use the full getAssetWithCloudID method (which fetches a lot of data). And we\n     * can avoid only creating an AdobeAsset when we only have RepoMetadata.\n     *\n     * @param assetId - The ID of the asset to get the asset interface for.\n     * @returns The asset interface for the asset.\n     */\n    @cache\n    private async _getAssetInterface(@key assetId: string): Promise<AssetInterface> {\n        // Get the asset interface for the asset\n        const localAsset = this._core._getAssetPool().getLocalItemById(assetId);\n        let assetInterface;\n        if (localAsset) {\n            assetInterface = await localAsset._getAssetInterface();\n        } else {\n            const assetContext = await this._core.getAssetContext();\n            // Fetch a minimalist version of AdobeAsset if it doesn't exist already to\n            // avoid fetching more data than we need.\n            const assetRepoData = await assetContext._getAssetRepoDataWithCloudID(assetId);\n            assetInterface = new AssetInterface(\n                assetContext._rapi,\n                assetId,\n                assetRepoData.data._links,\n                assetRepoData.data['repo:etag']\n            );\n        }\n        return assetInterface;\n    }\n\n    /**\n     * Get the access control list for an asset.\n     *\n     * @note An empty array returned means  ACEs have been set on the asset or this client-id user doesn't\n     * have access to see the ACL.\n     *\n     * @param assetId - The ID of the asset to get the access control list.\n     * @param forceRefresh - If true, the ACL and it's ACEs will be refreshed from the server and not pulled from the cache.\n     * useful when the service returns a 200 response because the ACL was updated but the cache was not updated.\n     *\n     * @note with forceRefresh = true, local changes to ACE's will be overwritten without error.\n     */\n    async getACL(assetId: string, forceRefresh: boolean = false): Promise<AdobeACL> {\n        const localACL = this._getCachedACL(assetId);\n        if (localACL && !forceRefresh) {\n            return localACL;\n        }\n\n        const assetInterface = await this._getAssetInterface(assetId);\n        const aclResponse = await assetInterface.getAccessControlList();\n\n        const mapACES = (ace: IAccessControlEntryResponse, index: number) => {\n            return new AdobeACE(\n                this._core,\n                index,\n                ace['repo:privileges'],\n                ace['repo:modifier'],\n                ace['repo:inheritance'],\n                ace['repo:relations'],\n                ace['repo:principal']\n            );\n        };\n\n        // Clear the entire list of ACEs on the ACL if we are forcing a refresh\n        // and after all the calls to the services have settled successfully this way we don't\n        // prematurely remove local ACEs before we get new ones from the server.\n        // We also set the _isDeleted property to true for each ACE so that clients\n        // will get an error when they try to make any changes to a deleted ACE.\n        if (localACL && forceRefresh) {\n            localACL.aces.forEach((ace: AdobeACE) => {\n                ace._isDeleted = true;\n            });\n            localACL.aces = [];\n        }\n\n        if (localACL) {\n            localACL.aces = aclResponse['repo:acl'].map(mapACES);\n            localACL.etag = aclResponse['etag'];\n            return localACL;\n        }\n\n        // ACL doesn't exist in the cache, create a new one.\n        // and return it to the caller.\n        const acl = new AdobeACL(\n            this._core,\n            assetId,\n            aclResponse['etag'],\n            aclResponse['repo:acl'].map(mapACES),\n            assetInterface\n        );\n\n        this._aclCache.set(\n            assetId,\n            new WeakRef(acl)\n        );\n        return acl;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport type ItemPool from '../core/ItemPool';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport { COLLABORATOR_CHANGED } from '@sam-js-src/collaboration/CollaboratorEvents';\nimport type { IInvitationPatch } from '../interface/InvitationModel';\nimport type Collaborator from '@sam-js-src/collaboration/Collaborator';\nimport type { SAM } from '@ccx-public/component-types';\nimport { LazyLoadManager } from '@sam-js-src/core/decorators/LazyLoadManager';\n\ntype AccessOptions = {\n    role: 'viewer' | 'editor';\n    canShare: boolean;\n    canComment: boolean;\n    canDiscover?: boolean; // TODO: Collaborator.canDiscover is not supported in CollaborationContext yet.\n    password?: string;\n}\n\nexport type PredefinedPrincipal = 'all' | 'authenticated' | 'allWithPassword' | 'orgEverybody';\n\n// AccessOptions is not required for private mode.\nexport type UpdateAccessRequest =\n  | { mode: 'private' }\n  | ({ mode: PredefinedPrincipal } & AccessOptions);\n\nconst isTargetMatchPredefinedPrincipal = (target: UpdateAccessRequest, existingPredefinedPrincipal: SAM.Collaborator) => {\n    if (target.mode === 'private') {\n        return !existingPredefinedPrincipal; // private mode matches with empty predefinedPrincipal\n    }\n    if (target.mode === existingPredefinedPrincipal.id) {\n        // TODO: Remove the casting to Collaborator when canComment or commentPermissions is available in SAM.Collaborator\n        return target.role === existingPredefinedPrincipal.role && target.canShare === existingPredefinedPrincipal.canShare && target.canComment === (existingPredefinedPrincipal as Collaborator).commentPermissions.includes('write');\n    }\n    return false;\n};\n\nconst isPredefinedPrincipal = (collaborator: Collaborator): boolean => {\n    return [ 'all', 'authenticated', 'allWithPassword', 'orgEverybody' ].includes(collaborator.id);\n};\n\n/**\n * This class is used to house the api for sharing an asset through ShareSheet.\n * https://wiki.corp.adobe.com/display/ACPCSDK/Share+Sheet+Invitation+SDK+Integration+into+SAM.js#ShareSheetInvitationSDKIntegrationintoSAM.js-SharingContext\n *\n/**\n * @package -- These APIs are currently meant to be used by ShareSheet only or by internal classes within SAM.js.\n */\n\nexport default class SharingContext implements SAM.SharingContext {\n    constructor(\n        public _core: ISAMCorePrivate,\n        readonly _assetPool: ItemPool<AdobeAsset>\n    ) {}\n\n    private async _getAdobeAsset(assetId: string): Promise<AdobeAsset> {\n        const localAsset = this._assetPool.getLocalItemById<AdobeAsset>(assetId) ?? await (await this._core.getAssetContext()).getAssetWithCloudID(assetId);\n        // wait for collaborators to load if needed\n        await LazyLoadManager.fetchIfNeeded(localAsset, COLLABORATOR_CHANGED);\n        return localAsset;\n    }\n\n    private async _getPrincipalCollaborators(assetId: string): Promise<SAM.Collaborator[]> {\n        const collaborators = await (await this._getAdobeAsset(assetId)).collaboratorArray;\n        return collaborators.filter(isPredefinedPrincipal);\n    }\n\n    /**\n     * @package -- Only to be used within SAM.js and ShareSheet.\n     * Assumes that an asset can only have one predefinedPrincipal, which is what ShareSheet currently supports.\n     * This method will replace the existing predefinedPrincipal with the one passed in the request param.\n     * This method can also be used to update an existing predefinedPrincipal with new roles or permissions.\n     * TODO: Handle password protected links Epic: SHARED-996\n     * TODO: Handle org/authenticated editors Epic: SHARED-996\n     */\n    async updateAccess(assetId: string, request: UpdateAccessRequest): Promise<SAM.UpdateAccessResult> {\n        const existingPredefinedPrincipals = await this._getPrincipalCollaborators(assetId);\n        const patchEntries = [];\n        const postEntries = []; // There should only be one post entry, but we'll use an array for consistency.\n\n        if (request.mode === 'private') {\n            // if target is to make it private, remove all predefined principals\n            existingPredefinedPrincipals?.forEach(p => patchEntries.push({ id: p.id, action: 'remove' }));\n        } else {\n            const { mode, ...accessOptions } = request;\n            // Remove all existing predefinedPrincipals that are not the target.\n            const patchesToRemoveExistingPPs = existingPredefinedPrincipals.filter((collaborator) => mode !== collaborator.id).map(p => ({ id: p.id, action: 'remove' }));\n            // If target predefinedPrincipal already exists, update it\n            const ppToUpdate = existingPredefinedPrincipals.find((collaborator) => mode === collaborator.id);\n\n            // If there is a predefinedPrincipal to update add it to the list of patchEntries.\n            if (ppToUpdate && !isTargetMatchPredefinedPrincipal(request, ppToUpdate)) {\n                patchEntries.push({\n                    id: ppToUpdate.id,\n                    action: 'update',\n                    ...accessOptions\n                });\n            }\n            if (!ppToUpdate) {\n                // If the target predefinedPrincipal does not exist, we need to add it via POST\n                postEntries.push({\n                    recipient: mode,\n                    ...accessOptions\n                });\n            }\n            // If there are predefinedPrincipals to remove, add them to the patchEntries.\n            if (patchesToRemoveExistingPPs.length > 0) {\n                patchEntries.push(...patchesToRemoveExistingPPs);\n            }\n        }\n\n        const returnPromise = Promise.all([\n            patchEntries.length > 0 ? this._core.collaborationContext._modifyCollaborators(assetId, patchEntries as IInvitationPatch[]) : Promise.resolve(undefined),\n            postEntries.length > 0 ? this._core.collaborationContext._addCollaborators(assetId, postEntries) : Promise.resolve(undefined)\n        ]).then(([ patchResult, postResult ]) => {\n            const patchResultMap = patchResult?.collaborators?.map(r => ({\n                action: 'update' as const, // Cannot differentiate between update and remove\n                id: r.id,\n                statusCode: r.statusCode,\n                statusText: r.statusText,\n                errorSubcode: r.errorSubcode\n            })) || [];\n            // No need to map `patchResult.invitations` because that is for pending invitations which will never happen for predefinedPrincipals.\n\n            let postResultMap = postResult?.addedCollaborators?.map(r => ({\n                action: 'add' as const,\n                id: r,\n            })) || [];\n\n            if (postResult?.failedCollaborators) {\n                postResultMap = postResultMap.concat(\n                    postResult.failedCollaborators.map(r => ({\n                        action: 'add' as const,\n                        id: r.recipient,\n                        error: r.error\n                    }))\n                );\n            }\n\n            return [ ...patchResultMap, ...postResultMap ];\n        });\n\n        return returnPromise;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport path from 'path-browserify';\nimport type AssetLinkList from './AssetLinkList';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport SAMError, { SAMErrorCode } from '../core/SAMError';\nimport { observable, retry, synchronized } from '../core/decorators';\nimport { Permission } from '../interface/AssetModel';\nimport { SAMObjectEventEmitter } from '../core/SAMObjectEventEmitter';\n\nexport type LinkReference = {\n    ['repo:assetId']: string,\n    ['repo:repositoryId']?: string,\n    ['repo:name']?: string,\n    ['repo:etag']?: string,\n    ['repo:version']?: string,\n    ['dc:format']?: string,\n    ['stRef:relativePath']?: string,\n    ['stRef:fromPart']?: string,\n    ['stRef:documentID']?: string,\n    ['stRef:instanceID']?: string,\n    ['stRef:fromPartInstanceID']?: string,\n    ['stRef:fromPartName']?: string,\n    ['stRef:fromPartDerivedFrom']?: LinkReference,\n    ['stRef:manager']?: 'Adobe Cloud'\n};\n\n// Properties of a link reference that correspond to mutable asset metadata properties (e.g. name, path etc).\n// These are properties that can change on the asset, but don't correspond to a content change\n// (i.e. the link state would be MetadataOutOfDate rather than OutOfDate)\nconst assetMetadataProperties: (keyof LinkReference)[] = [\n    'repo:repositoryId',\n    'repo:name',\n    'repo:etag',\n    'stRef:relativePath',\n    'stRef:documentID'\n];\n\nexport type LinkStatus =\n    | 'UpToDate'\n    | 'MetadataOutOfDate'\n    | 'OutOfDate'\n    | 'Restricted'\n    | 'Discarded'\n    | 'Broken';\n\nfunction isBrokenAsset(asset: AdobeAsset) {\n    // Need to know if permission exactly matches Ack or None, rather than contains, so can't use\n    // hasPermission() here.\n    const permission = asset['_permissions'];\n    return permission === Permission.Ack\n        || permission === Permission.None;\n}\n\n// Illustrator (prior to MAX 2021) does not update the instance ID on save, so we need to fall back to the etag in this case\n// See https://jira.corp.adobe.com/browse/AI-4251857\nconst typesWithUnreliableInstanceID = [\n    'application/illustrator'\n];\n\nexport default class AssetLink extends SAMObjectEventEmitter {\n\n    private _resolvedAssets?: AdobeAsset[];\n    private _resolutionErrors: SAMError[] = [];\n\n    constructor(\n        private _assetLinkList: AssetLinkList,\n        private _data: LinkReference\n    ) {\n        super(_assetLinkList._core);\n    }\n\n    _onChange = () => {\n        // Check if any of the resolved assets broke, and transfer their errors to the link\n        // so we get the right link state (broken or restricted)\n        const brokenAssets = this._resolvedAssets?.filter(isBrokenAsset);\n        if (brokenAssets?.length) {\n            this._resolutionErrors = brokenAssets.map(asset =>\n                SAMError.create(\n                    asset['_permissions'] === Permission.Ack ? SAMErrorCode.ACCESS_DENIED : SAMErrorCode.NOT_FOUND,\n                    'lost access'\n                ));\n            this._resolvedAssets = this._resolvedAssets?.filter(asset => !brokenAssets.includes(asset));\n        }\n        this.emit('change');\n        this._assetLinkList._onChange();\n    };\n\n    @synchronized\n    async _setLinkData(linkData: LinkReference, asset?: AdobeAsset) {\n        this._data = linkData;\n        if (asset) {\n            this._resolvedAssets = [ asset ];\n        }\n        this._onChange();\n        if (!this.adobeAsset || this.assetID !== this.adobeAsset.cloudID) {\n            await this._resolveWithRetry();\n        }\n        // TODO: Check if relative path changed\n        return this;\n    }\n\n    async _setLinkedAsset(asset: AdobeAsset) {\n        const data = this._getLinkDataForAsset(asset);\n        return this._setLinkData(data, asset);\n    }\n\n    _getLinkDataForAsset(asset: AdobeAsset): LinkReference {\n        const linkData: LinkReference = {\n            'repo:assetId': asset.cloudID,\n            'repo:repositoryId': asset.repositoryID,\n            'repo:etag': asset.etag,\n            'dc:format': asset.mediaType,\n            'repo:name': asset.name,\n            'stRef:documentID': asset.embeddedMetadata.data?.['xmpMM:DocumentID'],\n            'stRef:instanceID': asset.embeddedMetadata.data?.['xmpMM:InstanceID'],\n            'stRef:manager': 'Adobe Cloud'\n        };\n\n        // Add relative path if it exists\n        const parent = this._assetLinkList.containerAsset;\n        if (parent && parent.repositoryID === asset.repositoryID) {\n            linkData['stRef:relativePath'] = path.relative(path.dirname(parent.repoPath), asset.repoPath);\n        }\n\n        return linkData;\n    }\n\n    // Ensures that link reference strings are always serialized with the keys in the same order\n    _serializeLinkData(linkData: LinkReference): string {\n        return JSON.stringify(linkData, Object.keys(linkData).sort());\n    }\n\n    @retry\n    _resolveWithRetry(): Promise<void> {\n        return this._resolve();\n    }\n\n    async _resolve(): Promise<void> {\n        const resolvedAssets: AdobeAsset[] = [];\n        const resolutionErrors: SAMError[] = [];\n\n        const handleError = (e: SAMError) => {\n            if ([ SAMErrorCode.NOT_FOUND, SAMErrorCode.ACCESS_DENIED ].includes(e.code)) {\n                resolutionErrors.push(e);\n            } else {\n                throw e;\n            }\n        };\n\n        try {\n            const asset = await this._context.getAssetWithCloudID(this.assetID);\n            if (!asset.embeddedMetadata.isLoaded) {\n                // First time, we need to load - after that, it'll get updated whenever the asset is refreshed\n                await asset.embeddedMetadata.load();\n            }\n            resolvedAssets.push(asset);\n        } catch (e) {\n            this._core._environment.error(`Failed to resolve link by id (${this.assetID}): ${e}`);\n            handleError(e as SAMError);\n        }\n\n        const parent = this._assetLinkList.containerAsset;\n        if (this.relativePath && parent && parent.repositoryID === this.repositoryID) {\n            // Resolve by relative path, but this only makes sense if the container asset and linked\n            // asset are in the same repository.\n            const repoPath = path.join(path.dirname(parent.repoPath), this.relativePath);\n            try {\n                const asset = await this._context.getAssetWithRepoPath(repoPath, this.repositoryID);\n                if (!asset.embeddedMetadata.isLoaded) {\n                    // First time, we need to load - after that, it'll get updated whenever the asset is refreshed\n                    await asset.embeddedMetadata.load();\n                }\n                // Most of the time, resolution by path will match resolution by asset id - only add an alternate\n                // if they're different.\n                if (!resolvedAssets[0] || resolvedAssets[0].cloudID !== asset.cloudID) {\n                    if (resolvedAssets[0]?.isDiscarded) {\n                        // Special case if the resolution by id is discarded - we want the path-based resolution\n                        // to become the primary adobeAsset\n                        resolvedAssets.unshift(asset);\n                    } else {\n                        resolvedAssets.push(asset);\n                    }\n                }\n            } catch (e) {\n                this._core._environment.error(`Failed to resolve link by path: ${this.repositoryID}, ${repoPath}`);\n                handleError(e as SAMError);\n            }\n        }\n\n        // Attach event listeners so we can notify the link when the asset changes\n        this._resolvedAssets && this._resolvedAssets.forEach(asset => asset.off('change', this._onChange));\n        resolvedAssets.forEach(asset => asset.on('change', this._onChange));\n\n        this._resolvedAssets = resolvedAssets;\n        this._resolutionErrors = resolutionErrors;\n        this._onChange();\n    }\n\n    get _context() {\n        return this._assetLinkList._manager._context;\n    }\n\n    /**\n     * The asset that the link resolves to - this will not be defined if the linkStatus\n     * is Restricted or Broken.\n     */\n    @observable\n    get adobeAsset(): AdobeAsset | undefined {\n        return this._resolvedAssets?.[0];\n    }\n\n    /**\n     * An alternative asset which can be used as link, in case there is ambiguity resolving the link.\n     * This will usually be undefined.\n     */\n    @observable\n    get alternativeAdobeAsset(): AdobeAsset | undefined {\n        return this._resolvedAssets?.[1];\n    }\n\n    /**\n     * The current state of the link (OutOfDate, UpToDate, Restricted or Broken).\n     */\n    @observable\n    get linkStatus(): LinkStatus {\n        if (!this._resolvedAssets) {\n            return 'UpToDate';\n        }\n        if (!this.adobeAsset) {\n            // If we get a 403 resolving an asset, we know it exists but the user doesn't have access\n            // This corresponds to the Restricted state - we can direct the user to request access via assets web.\n            return this._resolutionErrors.some(error => error.code === SAMErrorCode.ACCESS_DENIED) ? 'Restricted' : 'Broken';\n        }\n        if (this.adobeAsset.isDiscarded) {\n            // If the primary asset resolved is discarded, it means that we don't have an undiscarded alternative\n            // (otherwise it would be the primary asset). We therefore treat the link state as Discarded.\n            // This means that the user can be presented the option to restore the asset to fix the link.\n            return 'Discarded';\n        }\n\n        // Check to see if the asset has changed - we check the xmpMM:InstanceID, which should be modified on every save.\n        // There are two exceptions:\n        // 1) If the asset doesn't have any XMP metadata (and neither does the link), we fall back to compare the repo:etag\n        // 2) Illustrator has a bug that it doesn't update the XMP metadata on save - so we also fall back to the repo:etag\n        //    for Illustrator types, in case they were edited in an older version of Illustrator.\n        const instanceID = this.adobeAsset.embeddedMetadata.data['xmpMM:InstanceID'] || '';\n        const shouldCheckEtag = (!instanceID && !this.instanceID) || typesWithUnreliableInstanceID.includes(this.type);\n        const assetHasChanged = instanceID !== this.instanceID || (shouldCheckEtag && this.etag !== this.adobeAsset.etag);\n        if (this.alternativeAdobeAsset || assetHasChanged) {\n            return 'OutOfDate';\n        }\n\n        // Check whether any metadata is out of date\n        const assetLinkData = this._getLinkDataForAsset(this.adobeAsset);\n        const hasMetadataChanges = assetMetadataProperties.some(key => assetLinkData[key] !== this._data[key]);\n        return hasMetadataChanges ? 'MetadataOutOfDate' : 'UpToDate';\n    }\n\n    /**\n     * The fragment specifier which can be used by the client to link to a fragment within the asset.\n     */\n    @observable\n    get fragmentIdentifier(): string {\n        return this._data['stRef:fromPart'] || '';\n    }\n\n    /**\n     * The version of the asset to which the link is referring to. This is only used if linking to a specific\n     * version, and the version must be specified at the time of link creation.\n     */\n    @observable\n    get version(): string {\n        return this._data['repo:version'] || '';\n    }\n\n    /**\n     * The asset ID of the asset which the link refers to.\n     */\n    @observable\n    get assetID(): string {\n        return this._data['repo:assetId'];\n    }\n\n    /**\n     * The repository ID of the asset which the link refers to.\n     */\n    @observable\n    get repositoryID(): string {\n        return this._data['repo:repositoryId'] || '';\n    }\n\n    /**\n     * The owner ID of the asset which the link refers to.\n     */\n    // get ownerID(): string {\n    //     return this._data['stRef:fromPart'] || '';\n    // }\n\n    /**\n     * The name of the asset when the link was created or last updated.\n     */\n    @observable\n    get name(): string {\n        return this._data['repo:name'] || '';\n    }\n\n    /**\n     * The type of the asset when the link was created.\n     */\n    @observable\n    get type(): string {\n        return this._data['dc:format'] || '';\n    }\n\n    /**\n     * The etag of the asset when the link was created or last updated.\n     */\n    @observable\n    get etag(): string {\n        return this._data['repo:etag'] || '';\n    }\n\n    /**\n     * The relative path of the asset when the link was created or last updated.\n     */\n    @observable\n    get relativePath(): string {\n        return this._data['stRef:relativePath'] || '';\n    }\n\n    /**\n     * The document id as per the XMP metadata when the link was created or last updated.\n     */\n    @observable\n    get documentID(): string {\n        return this._data['stRef:documentID'] || '';\n    }\n\n    /**\n     * The instance id as per the XMP metadata when the link was created or last updated.\n     */\n    @observable\n    get instanceID(): string {\n        return this._data['stRef:instanceID'] || '';\n    }\n\n    /**\n     * Obtain the asset link reference to be stored in the container document for the link.\n     * Note: Clients can choose to store this as a string by calling getAssetLinkRefString() instead.\n     */\n    @observable\n    getAssetLinkRef(): LinkReference {\n        return Object.assign({}, this._data);\n    }\n\n    /**\n     * Obtain the asset link reference string to be stored in the container document for the link.\n     * Note: Clients can choose to store this as an object by calling getAssetLinkRef() instead.\n     */\n    @observable\n    getAssetLinkRefString(): string {\n        return this._serializeLinkData(this._data);\n    }\n\n    /**\n     * Obtain the asset link reference corresponding to the given asset. This is useful for knowing\n     * the new link reference that would be obtained by updating to the given asset\n     */\n    @observable\n    getNewAssetLinkRef(asset: AdobeAsset): LinkReference {\n        return this._getLinkDataForAsset(asset);\n    }\n\n    /**\n     * Obtain the asset link reference string corresponding to the given asset. This is useful for knowing\n     * the new linkReference string that would be obtained by updating to the given asset\n     */\n    @observable\n    getNewAssetLinkRefString(asset: AdobeAsset): string {\n        return this._serializeLinkData(this.getNewAssetLinkRef(asset));\n    }\n\n    /**\n     * Called by the clients to accept the latest changes and get the new asset link reference\n     * @param asset The new asset to update to (or the current asset to accept an update)\n     * @returns The new linkReference string.\n     */\n    async updateWithAsset(asset: AdobeAsset): Promise<string> {\n        await this._setLinkedAsset(asset);\n        return this.getAssetLinkRefString();\n    }\n\n    /**\n     * Called by the clients to accept the latest changes and get the new asset link reference\n     * @param linkRef A new link reference to update to\n     * @returns The new link reference.\n     */\n    async updateWithLinkRef(linkRef: LinkReference): Promise<LinkReference> {\n        await this._setLinkData(linkRef);\n        return linkRef;\n    }\n\n    /**\n     * Called by the clients to accept the latest changes and get the new asset link reference\n     * @param linkRef A new link reference string to update to\n     * @returns The new link reference string.\n     */\n    async updateWithLinkRefString(linkRefString: string): Promise<string> {\n        await this._setLinkData(JSON.parse(linkRefString));\n        return linkRefString;\n    }\n\n    /**\n     * Called by the clients to accept metadata updates when the link is in the OutOfDate state.\n     * If called when the link is in a different state, this does nothing.\n     * @returns The new linkReference string.\n     */\n    acceptMetadataChanges(): string {\n        if (this.adobeAsset && this.linkStatus === 'MetadataOutOfDate') {\n            const assetLinkData = this._getLinkDataForAsset(this.adobeAsset);\n            // Note that we substitute fields rather than replacing the whole link reference, because the link reference\n            // may include fragment data that we don't want to delete\n            this._data = { ...this._data, ...assetLinkData };\n            this._onChange();\n        }\n        return this.getAssetLinkRefString();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { SAM } from '@ccx-public/component-types';\n\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport type AssetLinkManager from './AssetLinkManager';\nimport type { LinkReference } from './AssetLink';\nimport AssetLink from './AssetLink';\nimport { observable } from '../core/decorators';\nimport oneTimeWarning from '../utils/oneTimeWarning';\nimport { SAMObjectUntypedEventEmitter } from '../core/SAMObjectEventEmitter';\n\nexport default class AssetLinkList extends SAMObjectUntypedEventEmitter implements SAM.AssetLinkList {\n    private _links: Set<AssetLink> = new Set();\n\n    // We store directly monitored asset ids as a map, where the key is the lower case\n    // asset id, and the value is the asset id passed in. This allows us to easily look\n    // up the original case of the asset id passed in, so we can send notifications in\n    // the correct case, in case a client passed it in with the wrong case\n    private _directlyMonitoredAssetIDs: Map<string, string> = new Map();\n\n    constructor(\n        public _manager: AssetLinkManager,\n        private _containerAsset?: AdobeAsset\n    ) {\n        super(_manager._core);\n    }\n\n    _onChange = () => {\n        this.emit('change');\n    };\n\n    private _refreshLinks = (changedIDs: Set<string> = new Set(this.monitoredAssetIDs)) => {\n        this.forEach(link => {\n            if (!link.adobeAsset && changedIDs.has(link.assetID)) {\n                // Link is broken, but asset id changed - try re-resolving\n                link._resolveWithRetry();\n            }\n            // Note - we do not need to refresh any assets; this will be handled by AssetContext\n            // since it's updating all the assets in the asset pool.\n        });\n    };\n\n    _refreshLinksForChangedAssets = (changedIDs: Set<string>) => {\n        this._refreshLinks(changedIDs);\n\n        // As well as refreshing changed links, we emit a notified event, so clients can know that\n        // we were notified of a change to these assets - this is useful if clients are only monitoring\n        // asset ids directly, not via links.\n        // Compute the intersection of changedIDs and the ones we're monitoring:\n        const monitoredAssetIDs = this._monitoredAssetIDs;\n        const monitoredChangedIDs = new Set();\n        changedIDs.forEach(id => {\n            if (monitoredAssetIDs.has(id)) {\n                monitoredChangedIDs.add(id);\n            }\n            // The client might have passed in an asset id in a different case to the normalized\n            // platform case (e.g. clients like CC Libraries might have some older cached client\n            // ids). We therefore need to map the asset id we get from the notification to the\n            // one passed in.\n            const normalizedId = this._directlyMonitoredAssetIDs.get(id.toLowerCase());\n            if (normalizedId) {\n                monitoredChangedIDs.add(normalizedId);\n            }\n        });\n        this.emit('notified', [ ...monitoredChangedIDs ]);\n    };\n\n    /**\n     * Monitor an asset id directly, rather than going through an AssetLink. This allows you to monitor\n     * a specific asset for changes without maintaining any state (i.e. it will not resolve the assetID\n     * to an AdobeAsset).\n     *\n     * This is a lower-level API and should only be used if you're explicitly not wanting to load the\n     * asset with SAM (for example, the CC Libraries API uses this since it fetches the asset data\n     * from Melville, rather than R-API via SAM, so it just needs the raw notification).\n     */\n    addAssetID(assetID: string) {\n        this._directlyMonitoredAssetIDs.set(assetID.toLowerCase(), assetID);\n        this._onChange();\n    }\n\n    /**\n     * Stop monitoring an asset id that was added via `addAssetId()`. Note that if any links in the list\n     * also reference this asset id, this will not stop monitoring them.\n     */\n    removeAssetID(assetID: string) {\n        this._directlyMonitoredAssetIDs.delete(assetID.toLowerCase());\n        this._onChange();\n    }\n\n    /**\n     * Add one or more existing links (from link reference or link reference strings) to the list.\n     */\n    add(linkReferences: (string | LinkReference)[]): Promise<AssetLink[]> {\n        return Promise.all(linkReferences.map(async linkRef => {\n            // TODO: Should check if already have duplicate link\n            const linkReference = typeof linkRef === 'string' ? JSON.parse(linkRef) : linkRef;\n            const link = new AssetLink(this, linkReference);\n            this._links.add(link);\n            this._onChange();\n            // When adding an existing link we can always return an AssetLink even if it fails\n            // We'll retry the resolution after which the link state will update.\n            await link._resolveWithRetry();\n            return link;\n        }));\n    }\n\n    /**\n     * Create a new link from an asset, and add it to the list.\n     * @param asset\n     * @param [fragmentSpecifier] An optional string containing the fragmentSpecifier within the asset.\n     * @param [version] An optional string containing the version identifier of the Adobe asset.\n     */\n    async create(asset: AdobeAsset | string, fragmentSpecifier?: string, version?: string): Promise<AssetLink> {\n        const assetID = typeof asset === 'string' ? asset : asset.cloudID;\n        const link = new AssetLink(this, {\n            'repo:assetId': assetID,\n            'stRef:fromPart': fragmentSpecifier,\n            'repo:version': version,\n            'stRef:manager': 'Adobe Cloud'\n        });\n        this._links.add(link);\n        this._onChange();\n        // When creating a new link, we do _not_ retry on failure - this is because the link reference needs to be updated.\n        // Errors are propagated to the client.\n        await link._resolve();\n        if (link.adobeAsset) {\n            link._setLinkedAsset(link.adobeAsset);\n        }\n        return link;\n    }\n\n    /**\n     * Remove an asset link from the list. This will cause it to stop being actively monitored for changes.\n     */\n    remove(link: AssetLink) {\n        this._links.delete(link);\n        this._onChange();\n    }\n\n    /**\n     * Clear the whole list.\n     */\n    clear() {\n        this._links.clear();\n        this._onChange();\n    }\n\n    /**\n     * Number of asset links in the list.\n     */\n    @observable\n    get count() {\n        return this._links.size;\n    }\n\n    /**\n     * Get an array of all the asset links in the list.\n     */\n    @observable\n    get links(): AssetLink[] {\n        return [ ...this._links ];\n    }\n\n    /**\n     * Get a set of all the asset ids being monitored by the link list. This includes\n     * asset ids in any links, as well as asset ids being directly monitored.\n     */\n    private get _monitoredAssetIDs(): Set<string> {\n        const assetIDs: Set<string> = new Set(this._directlyMonitoredAssetIDs.values());\n        this.forEach(link => {\n            assetIDs.add(link.assetID);\n            // We also monitor the path-based resolution if it differs from asset-based:\n            if (link.alternativeAdobeAsset) {\n                assetIDs.add(link.alternativeAdobeAsset.cloudID);\n            }\n        });\n        return assetIDs;\n    }\n\n    /**\n     * Get an array of all the asset ids being monitored by the link list. This includes\n     * asset ids in any links, as well as asset ids being directly monitored.\n     */\n    @observable\n    get monitoredAssetIDs(): string[] {\n        return [ ...this._monitoredAssetIDs ];\n    }\n\n    /**\n     * Iterate through all the asset links in the list.\n     */\n    @observable\n    forEach(callback: (link: AssetLink) => void) {\n        this._links.forEach(callback);\n    }\n\n    /**\n     * Get the container asset for the link list (the document that contains the links)\n     */\n    @observable\n    get containerAsset(): AdobeAsset | undefined {\n        return this._containerAsset;\n    }\n\n    /**\n     * Marks a list as active so that the asset link manager can actively start monitoring all the asset links in it.\n     * @param [duration] If a duration is specified (in ms), the list will automatically deactivate after this time. Otherwise it will remain active.\n     * @deprecated This method is deprecated - lists are always monitored for notifications unless you pass in DISABLE_ONS when initializing SAM.\n     *    Will be removed on or after 2024-10-01.\n     */\n    activate(duration: number = 0) {\n        oneTimeWarning('AssetLinkList.activate', `AssetLinkList.activate(${duration}) is deprecated - lists are always monitored for notifications.`\n         + `This method will be removed on or after 2024-10-01.`);\n    }\n\n    /**\n     * Deactivate a list so that the asset link manager can stop monitoring all the asset links in it.\n     * @deprecated This method is deprecated - lists are always monitored for notifications unless you pass in DISABLE_ONS when initializing SAM.\n     *    Will be removed on or after 2024-10-01.\n     */\n    deactivate() {\n        oneTimeWarning('AssetLinkList.deactivate', 'AssetLinkList.deactivate() is deprecated - lists are'\n            + ' always monitored for notifications. This method will be removed on or after 2024-10-01.');\n    }\n\n    /**\n     * Whether the list is active (asset links in it are actively monitored for changes or not).\n     * @deprecated This method is deprecated - lists are always monitored for notifications unless you pass in DISABLE_ONS when initializing SAM.\n     *    Will be removed on or after 2024-10-01.\n     */\n    @observable\n    get isActive(): boolean {\n        oneTimeWarning('AssetLinkList.isActive', 'AssetLinkList.isActive is deprecated - lists are always'\n            + ' monitored for notifications. This method will be removed on or after 2024-10-01.');\n        return true;\n    }\n\n    /**\n     * Change the container asset associated with this list (the document that contains the links in the list)\n     * This will change relative path based resolution of the links\n     */\n    async updateContainerAsset(containerAsset: AdobeAsset) {\n        this._containerAsset = containerAsset;\n        this._onChange();\n        // Need to resolve all the links again, because the relative path could have changed\n        await Promise.all(Array.from(this._links).map(link => link._resolveWithRetry()));\n    }\n\n    /**\n     * Clone the asset list for a another container asset (adding it to this list)\n     */\n    clone(assetLinkList: AssetLinkList) {\n        // TODO: Need to trigger all links to re-resolve, since relative path resolution may have changed\n        assetLinkList.links.forEach(link => this._links.add(link));\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { SAM } from '@ccx-public/component-types';\n\nimport type AssetContext from '../assets/AssetContext';\nimport type AdobeAsset from '../assets/AdobeAsset';\nimport AssetLinkList from './AssetLinkList';\nimport { observable } from '../core/decorators';\nimport { SAMObjectEventEmitter } from '../core/SAMObjectEventEmitter';\n\nexport default class AssetLinkManager extends SAMObjectEventEmitter implements SAM.AssetLinkManager {\n\n    private _lists: Set<AssetLinkList> = new Set();\n\n    constructor(\n        public _context: AssetContext\n    ) {\n        super(_context._core);\n    }\n\n    private _onListChange = () => {\n        // We need to notify the AssetContext whenever a list changes, so it can\n        // update the asset ids it's subscribing to in ONS (if a link is broken,\n        // we still want to get updates even if the asset isn't in the asset pool)\n        this._context._updateONSSubscriptions();\n    };\n\n    createList(containerAsset?: AdobeAsset): AssetLinkList {\n        const list = new AssetLinkList(this, containerAsset);\n        list.on('change', this._onListChange);\n        this._lists.add(list);\n        this.emit('change');\n        return list;\n    }\n\n    removeList(list: AssetLinkList) {\n        this._lists.delete(list);\n        list.off('change', this._onListChange);\n        this.emit('change');\n    }\n\n    /**\n     * Get an array of all the asset link lists.\n     */\n    @observable\n    get lists(): AssetLinkList[] {\n        return [ ...this._lists ];\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport {\n    gql\n} from '@apollo/client';\n\nexport const SHARED_WITH_YOU_ASSETS = gql`query SharedWithYou(\n  $first: Int!\n  $after: String\n  $filter: AssetListFilter\n  $orderBy: SharedWithYouOrderByInput) {\n  sharedWithYou {\n    assetListId\n    assetListConnection(\n      first: $first\n      after: $after\n      filter: $filter\n      orderBy: $orderBy) {\n      edges {\n        cursor\n        node {\n          ... on Asset {\n            sharingInfo {\n              sharedWithYou {\n                shareDate\n                sharedBy {\n                  id\n                }\n              }\n            }\n            repo_assetClass\n            repo_assetType\n            repo_assetSubType\n            labels {\n              lastAccessDate\n            }\n            #defer\n            repository {\n              repo_repositoryId\n            }\n            dc_format\n            storage_deviceCreateDate\n            storage_deviceModifyDate\n            primary_etag\n            effectivePermissions {\n              aclPolicy\n              annotations\n              applicationMetadata\n              default\n              directory\n              primary\n            }\n            primaryLink {\n              href\n            }\n            blockUploadLink {\n              href\n            }\n            repo_ancestors\n            repo_createDate\n            repo_createdBy {\n              id\n            }\n            repo_path\n            repo_representations {\n              composite\n              directory\n              file\n            }\n            repo_modifiedBy\n            repo_modifyDate\n            repo_name\n            repo_state\n            repo_assetId\n            storage_region\n            storage_assignee {\n              id\n              type\n            }\n            ... @defer {\n              appMetadata {\n                valueOf(key: \"\")\n              }\n            }\n          }\n          ... on Composite {\n            repo_version\n            repo_size\n            blockDownloadLink {\n              href\n            }\n            renditionLink {\n              href\n            }\n          }\n          ... on File {\n            repo_version\n            repo_size\n            blockDownloadLink {\n              href\n            }\n            renditionLink {\n              href\n            }\n            tiff_imageLength\n            tiff_imageWidth\n          }\n        }\n      }\n      pageInfo {\n        endCursor\n        hasNextPage\n      }\n    }\n  }\n}\n`;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { gql } from '@apollo/client';\nimport { repoMetadataFragment, appMetadataFragment } from './fragments';\n\nconst assetFragments = repoMetadataFragment + appMetadataFragment;\n\nconst query = assetFragments + `\nquery generationHistoryListing($relativePath: String!, $first: Int!, $after: String, $orderBy: [OrderByInput], $filter: AssetFilter) {\n  homeFolder: resolveUserHome {\n    id: repo_assetId\n\n    ... on Directory {\n      fireflyGenerationsDirectory: assetByRelativePath(\n        relativePath: $relativePath\n      ) {\n        id: repo_assetId\n        name: repo_name\n        ... on Directory {\n          generationAssetsConnection: childrenConnection(first: $first, after: $after, orderBy: $orderBy, filter: $filter) {\n            pageInfo {\n              hasNextPage\n              endCursor\n            }\n            assets: edges {\n              cursor\n              node {\n                ...repoMetadata\n                ...applicationMetadata\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n`;\n\nexport const generationHistoryAssets = gql`${query}`;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2024 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { gql } from '@apollo/client';\n\nexport const recents = gql` query PLSRecents($first: Int!, $after: String, $filter: AssetListFilter) {\n  recents {\n    assetListId\n    assetListConnection(first: $first, after: $after, filter: $filter) {\n      pageInfo {\n        endCursor\n        hasNextPage\n      }\n      edges {\n        cursor\n        node {\n          ... on Asset {\n            dc_format\n            repo_assetId\n            repo_name\n            repo_path\n            primary_etag\n            repo_representations {\n              composite\n              directory\n              file\n            }\n            repo_state\n            repo_ancestors\n            repo_createDate\n            repo_modifyDate\n            repo_modifiedBy\n            repo_createdBy {\n              id\n            }\n            storage_region\n            storage_deviceCreateDate\n            storage_deviceModifyDate\n            storage_assignee {\n              id\n              type\n            }\n            repo_assetClass\n            repo_assetType\n            repo_assetSubType\n            repository {\n              repo_repositoryId\n            }\n            sharingInfo {\n              sharedWithYou {\n                shareDate\n                sharedBy {\n                  id\n                }\n              }\n            }\n            effectivePermissions {\n              aclPolicy\n              annotations\n              applicationMetadata\n              default\n              directory\n              primary\n            }\n            primaryLink {\n              href\n            }\n            blockUploadLink {\n              href\n            }\n            labels {\n              lastAccessDate\n            }\n            ... @defer {\n              appMetadata {\n              valueOf(key: \"\")\n              }\n            }\n            ... on Composite {\n              repo_version\n              repo_size\n              isComposite\n              blockDownloadLink {\n                href\n              }\n              renditionLink {\n                href\n              }\n            }\n            ... on File {\n              repo_version\n              repo_size\n              isFile\n              blockDownloadLink {\n                href\n              }\n              renditionLink {\n                href\n              }\n              tiff_imageLength\n              tiff_imageWidth\n            }\n          }\n        }\n      }\n    }\n  }\n}\n`;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/*\n    Constants\n*/\n\nconst MIME_TYPE_MAP: { [s: string]: string[] } = {\n    'application/andrew-inset': [ 'ez' ],\n    'application/applixware': [ 'aw' ],\n    'application/atom+xml': [ 'atom' ],\n    'application/atomcat+xml': [ 'atomcat' ],\n    'application/atomsvc+xml': [ 'atomsvc' ],\n    'application/ccxml+xml': [ 'ccxml' ],\n    'application/cdmi-capability': [ 'cdmia' ],\n    'application/cdmi-container': [ 'cdmic' ],\n    'application/cdmi-domain': [ 'cdmid' ],\n    'application/cdmi-object': [ 'cdmio' ],\n    'application/cdmi-queue': [ 'cdmiq' ],\n    'application/cu-seeme': [ 'cu' ],\n    'application/davmount+xml': [ 'davmount' ],\n    'application/docbook+xml': [ 'dbk' ],\n    'application/dssc+der': [ 'dssc' ],\n    'application/dssc+xml': [ 'xdssc' ],\n    'application/ecmascript': [ 'ecma' ],\n    'application/emma+xml': [ 'emma' ],\n    'application/epub+zip': [ 'epub' ],\n    'application/exi': [ 'exi' ],\n    'application/font-tdpfr': [ 'pfr' ],\n    'application/gml+xml': [ 'gml' ],\n    'application/gpx+xml': [ 'gpx' ],\n    'application/gxf': [ 'gxf' ],\n    'application/hyperstudio': [ 'stk' ],\n    'application/illustrator': [ 'ai' ],\n    'application/illustrator-text': [ 'ai' ],\n    'application/illustrator.template': [ 'ait' ],\n    'application/inkml+xml': [ 'ink', 'inkml' ],\n    'application/ipfix': [ 'ipfix' ],\n    'application/java-archive': [ 'jar' ],\n    'application/java-serialized-object': [ 'ser' ],\n    'application/java-vm': [ 'class' ],\n    'application/javascript': [ 'js' ],\n    'application/json': [ 'json' ],\n    'application/jsonml+json': [ 'jsonml' ],\n    'application/lost+xml': [ 'lostxml' ],\n    'application/mac-binhex40': [ 'hqx' ],\n    'application/mac-compactpro': [ 'cpt' ],\n    'application/mads+xml': [ 'mads' ],\n    'application/marc': [ 'mrc' ],\n    'application/marcxml+xml': [ 'mrcx' ],\n    'application/mathematica': [ 'ma', 'nb', 'mb' ],\n    'application/mathml+xml': [ 'mathml' ],\n    'application/mbox': [ 'mbox' ],\n    'application/mediaservercontrol+xml': [ 'mscml' ],\n    'application/metalink+xml': [ 'metalink' ],\n    'application/metalink4+xml': [ 'meta4' ],\n    'application/mets+xml': [ 'mets' ],\n    'application/mods+xml': [ 'mods' ],\n    'application/mp21': [ 'm21', 'mp21' ],\n    'application/mp4': [ 'mp4s' ],\n    'application/msword': [ 'doc', 'dot' ],\n    'application/mxf': [ 'mxf' ],\n    'application/octet-stream': [\n        'bin',\n        'dms',\n        'lrf',\n        'mar',\n        'so',\n        'dist',\n        'distz',\n        'pkg',\n        'bpk',\n        'dump',\n        'elc',\n        'deploy'\n    ],\n    'application/oda': [ 'oda' ],\n    'application/oebps-package+xml': [ 'opf' ],\n    'application/ogg': [ 'ogx' ],\n    'application/omdoc+xml': [ 'omdoc' ],\n    'application/onenote': [ 'onetoc', 'onetoc2', 'onetmp', 'onepkg' ],\n    'application/oxps': [ 'oxps' ],\n    'application/patch-ops-error+xml': [ 'xer' ],\n    'application/pdf': [ 'pdf' ],\n    'application/pgp-encrypted': [ 'pgp' ],\n    'application/pgp-signature': [ 'asc', 'sig' ],\n    'application/photoshop': [ 'psd' ],\n    'application/photoshop.large': [ 'psb' ],\n    'application/pics-rules': [ 'prf' ],\n    'application/pkcs10': [ 'p10' ],\n    'application/pkcs7-mime': [ 'p7m', 'p7c' ],\n    'application/pkcs7-signature': [ 'p7s' ],\n    'application/pkcs8': [ 'p8' ],\n    'application/pkix-attr-cert': [ 'ac' ],\n    'application/pkix-cert': [ 'cer' ],\n    'application/pkix-crl': [ 'crl' ],\n    'application/pkix-pkipath': [ 'pkipath' ],\n    'application/pkixcmp': [ 'pki' ],\n    'application/pls+xml': [ 'pls' ],\n    'application/postscript': [ 'ai', 'eps', 'ps' ],\n    'application/prs.cww': [ 'cww' ],\n    'application/pskc+xml': [ 'pskcxml' ],\n    'application/rdf+xml': [ 'rdf' ],\n    'application/reginfo+xml': [ 'rif' ],\n    'application/relax-ng-compact-syntax': [ 'rnc' ],\n    'application/resource-lists+xml': [ 'rl' ],\n    'application/resource-lists-diff+xml': [ 'rld' ],\n    'application/rls-services+xml': [ 'rs' ],\n    'application/rpki-ghostbusters': [ 'gbr' ],\n    'application/rpki-manifest': [ 'mft' ],\n    'application/rpki-roa': [ 'roa' ],\n    'application/rsd+xml': [ 'rsd' ],\n    'application/rss+xml': [ 'rss' ],\n    'application/rtf': [ 'rtf' ],\n    'application/sbml+xml': [ 'sbml' ],\n    'application/scvp-cv-request': [ 'scq' ],\n    'application/scvp-cv-response': [ 'scs' ],\n    'application/scvp-vp-request': [ 'spq' ],\n    'application/scvp-vp-response': [ 'spp' ],\n    'application/sdp': [ 'sdp' ],\n    'application/set-payment-initiation': [ 'setpay' ],\n    'application/set-registration-initiation': [ 'setreg' ],\n    'application/shf+xml': [ 'shf' ],\n    'application/smil+xml': [ 'smi', 'smil' ],\n    'application/sparql-query': [ 'rq' ],\n    'application/sparql-results+xml': [ 'srx' ],\n    'application/srgs': [ 'gram' ],\n    'application/srgs+xml': [ 'grxml' ],\n    'application/sru+xml': [ 'sru' ],\n    'application/ssdl+xml': [ 'ssdl' ],\n    'application/ssml+xml': [ 'ssml' ],\n    'application/tei+xml': [ 'tei', 'teicorpus' ],\n    'application/thraud+xml': [ 'tfi' ],\n    'application/timestamped-data': [ 'tsd' ],\n    'application/vnd.3gpp.pic-bw-large': [ 'plb' ],\n    'application/vnd.3gpp.pic-bw-small': [ 'psb' ],\n    'application/vnd.3gpp.pic-bw-var': [ 'pvb' ],\n    'application/vnd.3gpp2.tcap': [ 'tcap' ],\n    'application/vnd.3m.post-it-notes': [ 'pwn' ],\n    'application/vnd.accpac.simply.aso': [ 'aso' ],\n    'application/vnd.accpac.simply.imp': [ 'imp' ],\n    'application/vnd.acucobol': [ 'acu' ],\n    'application/vnd.acucorp': [ 'atc', 'acutc' ],\n    'application/vnd.adobe.ae.graphic+zip': [ 'aegraphic', 'mogrt' ],\n    'application/vnd.adobe.air-application-installer-package+zip': [ 'air' ],\n    'application/vnd.adobe.animate-xfl+zip': [ 'fla', 'xfl' ],\n    'application/vnd.adobe.animate-oam+zip': [ 'oam' ],\n    'application/vnd.adobe.animate-sym+zip': [ 'sym' ],\n    'application/vnd.adobe.animate-swf+zip': [ 'swa' ],\n    'application/vnd.adobe.characterstyle+json': [ 'style' ],\n    'application/vnd.adobe.characterstyle+snippet': [ 'idms' ],\n    'application/vnd.adobe.charts+zip': [ 'zip' ],\n    'application/vnd.adobe.ch.puppet+zip': [ 'puppet' ],\n    'application/vnd.adobe.color+json': [ 'ase' ],\n    'application/vnd.adobe.colortheme+json': [ 'ase' ],\n    'application/vnd.adobe.cube+txt': [ 'cube' ],\n    'application/vnd.adobe.element.agc+json': [ 'agc' ],\n    'application/vnd.adobe.exr.light+zip': [ 'exr' ],\n    'application/vnd.adobe.fbx.3d+zip': [ 'fbx' ],\n    'application/vnd.adobe.formscentral.fcdt': [ 'fcdt' ],\n    'application/vnd.adobe.fxp': [ 'fxp', 'fxpl' ],\n    'application/vnd.adobe.hz.express+dcxucf': [ 'dcxucf' ],\n    'application/vnd.adobe.ibl.light+zip': [ 'ibl', 'zip' ],\n    'application/vnd.adobe.illustrator.template': [ 'ait' ],\n    'application/vnd.adobe.indesign-idms': [ 'idms' ],\n    'application/vnd.adobe.indesign-idms-text': [ 'idms' ],\n    'application/vnd.adobe.indesign.template': [ 'indt' ],\n    'application/vnd.adobe.layerstyle': [ 'asl' ],\n    'application/vnd.adobe.look+xml': [ 'look' ],\n    'application/vnd.adobe.graphic+json': [ 'json' ],\n    'application/vnd.adobe.mdl.material+zip': [ 'mdl', 'zip' ],\n    'application/vnd.adobe.muse-collection': [ 'muse' ],\n    'application/vnd.adobe.obj.3d+zip': [ 'obj', 'zip' ],\n    'application/vnd.adobe.paragraphstyle+json': [ 'style' ],\n    'application/vnd.adobe.paragraphstyle+snippet': [ 'idms' ],\n    'application/vnd.adobe.photoshop.template': [ 'psdt' ],\n    'application/vnd.adobe.ppro.graphic+zip': [ 'prgraphic', 'mogrt' ],\n    'application/vnd.adobe.ribbon.brush+zip': [ 'brush' ],\n    'application/vnd.adobe.sbsar+zip': [ 'sbsar' ],\n    'application/vnd.adobe.scatter.brush+zip': [ 'brush' ],\n    'application/vnd.adobe.vector.brush+zip': [ 'brush' ],\n    'application/vnd.adobe.text+json': [ 'text-json' ],\n    'application/vnd.adobe.theo.document+dcxucf': [ 'dcxucf' ],\n    'application/vnd.adobe.xdp+xml': [ 'xdp' ],\n    'application/vnd.adobe.xfdf': [ 'xfdf' ],\n    'application/vnd.ahead.space': [ 'ahead' ],\n    'application/vnd.airzip.filesecure.azf': [ 'azf' ],\n    'application/vnd.airzip.filesecure.azs': [ 'azs' ],\n    'application/vnd.amazon.ebook': [ 'azw' ],\n    'application/vnd.americandynamics.acc': [ 'acc' ],\n    'application/vnd.amiga.ami': [ 'ami' ],\n    'application/vnd.android.package-archive': [ 'apk' ],\n    'application/vnd.anser-web-certificate-issue-initiation': [ 'cii' ],\n    'application/vnd.anser-web-funds-transfer-initiation': [ 'fti' ],\n    'application/vnd.antix.game-component': [ 'atx' ],\n    'application/vnd.apple.installer+xml': [ 'mpkg' ],\n    'application/vnd.apple.mpegurl': [ 'm3u8' ],\n    'application/vnd.aristanetworks.swi': [ 'swi' ],\n    'application/vnd.astraea-software.iota': [ 'iota' ],\n    'application/vnd.audiograph': [ 'aep' ],\n    'application/vnd.blueice.multipass': [ 'mpm' ],\n    'application/vnd.bmi': [ 'bmi' ],\n    'application/vnd.businessobjects': [ 'rep' ],\n    'application/vnd.chemdraw+xml': [ 'cdxml' ],\n    'application/vnd.chipnuts.karaoke-mmd': [ 'mmd' ],\n    'application/vnd.cinderella': [ 'cdy' ],\n    'application/vnd.claymore': [ 'cla' ],\n    'application/vnd.cloanto.rp9': [ 'rp9' ],\n    'application/vnd.clonk.c4group': [ 'c4g', 'c4d', 'c4f', 'c4p', 'c4u' ],\n    'application/vnd.cluetrust.cartomobile-config': [ 'c11amc' ],\n    'application/vnd.cluetrust.cartomobile-config-pkg': [ 'c11amz' ],\n    'application/vnd.commonspace': [ 'csp' ],\n    'application/vnd.contact.cmsg': [ 'cdbcmsg' ],\n    'application/vnd.cosmocaller': [ 'cmc' ],\n    'application/vnd.crick.clicker': [ 'clkx' ],\n    'application/vnd.crick.clicker.keyboard': [ 'clkk' ],\n    'application/vnd.crick.clicker.palette': [ 'clkp' ],\n    'application/vnd.crick.clicker.template': [ 'clkt' ],\n    'application/vnd.crick.clicker.wordbank': [ 'clkw' ],\n    'application/vnd.criticaltools.wbs+xml': [ 'wbs' ],\n    'application/vnd.ctc-posml': [ 'pml' ],\n    'application/vnd.cups-ppd': [ 'ppd' ],\n    'application/vnd.curl.car': [ 'car' ],\n    'application/vnd.curl.pcurl': [ 'pcurl' ],\n    'application/vnd.dart': [ 'dart' ],\n    'application/vnd.data-vision.rdz': [ 'rdz' ],\n    'application/vnd.dece.data': [ 'uvf', 'uvvf', 'uvd', 'uvvd' ],\n    'application/vnd.dece.ttml+xml': [ 'uvt', 'uvvt' ],\n    'application/vnd.dece.unspecified': [ 'uvx', 'uvvx' ],\n    'application/vnd.dece.zip': [ 'uvz', 'uvvz' ],\n    'application/vnd.denovo.fcselayout-link': [ 'fe_launch' ],\n    'application/vnd.dna': [ 'dna' ],\n    'application/vnd.dolby.mlp': [ 'mlp' ],\n    'application/vnd.dpgraph': [ 'dpg' ],\n    'application/vnd.dreamfactory': [ 'dfac' ],\n    'application/vnd.ds-keypoint': [ 'kpxx' ],\n    'application/vnd.dvb.ait': [ 'ait' ],\n    'application/vnd.dvb.service': [ 'svc' ],\n    'application/vnd.dynageo': [ 'geo' ],\n    'application/vnd.ecowin.chart': [ 'mag' ],\n    'application/vnd.enliven': [ 'nml' ],\n    'application/vnd.epson.esf': [ 'esf' ],\n    'application/vnd.epson.msf': [ 'msf' ],\n    'application/vnd.epson.quickanime': [ 'qam' ],\n    'application/vnd.epson.salt': [ 'slt' ],\n    'application/vnd.epson.ssf': [ 'ssf' ],\n    'application/vnd.eszigno3+xml': [ 'es3', 'et3' ],\n    'application/vnd.ezpix-album': [ 'ez2' ],\n    'application/vnd.ezpix-package': [ 'ez3' ],\n    'application/vnd.fdf': [ 'fdf' ],\n    'application/vnd.fdsn.mseed': [ 'mseed' ],\n    'application/vnd.fdsn.seed': [ 'seed', 'dataless' ],\n    'application/vnd.flographit': [ 'gph' ],\n    'application/vnd.fluxtime.clip': [ 'ftc' ],\n    'application/vnd.framemaker': [ 'fm', 'frame', 'maker', 'book' ],\n    'application/vnd.frogans.fnc': [ 'fnc' ],\n    'application/vnd.frogans.ltf': [ 'ltf' ],\n    'application/vnd.fsc.weblaunch': [ 'fsc' ],\n    'application/vnd.fujitsu.oasys': [ 'oas' ],\n    'application/vnd.fujitsu.oasys2': [ 'oa2' ],\n    'application/vnd.fujitsu.oasys3': [ 'oa3' ],\n    'application/vnd.fujitsu.oasysgp': [ 'fg5' ],\n    'application/vnd.fujitsu.oasysprs': [ 'bh2' ],\n    'application/vnd.fujixerox.ddd': [ 'ddd' ],\n    'application/vnd.fujixerox.docuworks': [ 'xdw' ],\n    'application/vnd.fujixerox.docuworks.binder': [ 'xbd' ],\n    'application/vnd.fuzzysheet': [ 'fzs' ],\n    'application/vnd.genomatix.tuxedo': [ 'txd' ],\n    'application/vnd.geogebra.file': [ 'ggb' ],\n    'application/vnd.geogebra.tool': [ 'ggt' ],\n    'application/vnd.geometry-explorer': [ 'gex', 'gre' ],\n    'application/vnd.geonext': [ 'gxt' ],\n    'application/vnd.geoplan': [ 'g2w' ],\n    'application/vnd.geospace': [ 'g3w' ],\n    'application/vnd.gmx': [ 'gmx' ],\n    'application/vnd.google-earth.kml+xml': [ 'kml' ],\n    'application/vnd.google-earth.kmz': [ 'kmz' ],\n    'application/vnd.grafeq': [ 'gqf', 'gqs' ],\n    'application/vnd.groove-account': [ 'gac' ],\n    'application/vnd.groove-help': [ 'ghf' ],\n    'application/vnd.groove-identity-message': [ 'gim' ],\n    'application/vnd.groove-injector': [ 'grv' ],\n    'application/vnd.groove-tool-message': [ 'gtm' ],\n    'application/vnd.groove-tool-template': [ 'tpl' ],\n    'application/vnd.groove-vcard': [ 'vcg' ],\n    'application/vnd.hal+xml': [ 'hal' ],\n    'application/vnd.handheld-entertainment+xml': [ 'zmm' ],\n    'application/vnd.hbci': [ 'hbci' ],\n    'application/vnd.hhe.lesson-player': [ 'les' ],\n    'application/vnd.hp-hpgl': [ 'hpgl' ],\n    'application/vnd.hp-hpid': [ 'hpid' ],\n    'application/vnd.hp-hps': [ 'hps' ],\n    'application/vnd.hp-jlyt': [ 'jlt' ],\n    'application/vnd.hp-pcl': [ 'pcl' ],\n    'application/vnd.hp-pclxl': [ 'pclxl' ],\n    'application/vnd.ibm.minipay': [ 'mpy' ],\n    'application/vnd.ibm.modcap': [ 'afp', 'listafp', 'list3820' ],\n    'application/vnd.ibm.rights-management': [ 'irm' ],\n    'application/vnd.ibm.secure-container': [ 'sc' ],\n    'application/vnd.iccprofile': [ 'icc', 'icm' ],\n    'application/vnd.igloader': [ 'igl' ],\n    'application/vnd.immervision-ivp': [ 'ivp' ],\n    'application/vnd.immervision-ivu': [ 'ivu' ],\n    'application/vnd.insors.igm': [ 'igm' ],\n    'application/vnd.intercon.formnet': [ 'xpw', 'xpx' ],\n    'application/vnd.intergeo': [ 'i2g' ],\n    'application/vnd.intu.qbo': [ 'qbo' ],\n    'application/vnd.intu.qfx': [ 'qfx' ],\n    'application/vnd.ipunplugged.rcprofile': [ 'rcprofile' ],\n    'application/vnd.irepository.package+xml': [ 'irp' ],\n    'application/vnd.is-xpr': [ 'xpr' ],\n    'application/vnd.isac.fcs': [ 'fcs' ],\n    'application/vnd.jam': [ 'jam' ],\n    'application/vnd.jcp.javame.midlet-rms': [ 'rms' ],\n    'application/vnd.jisp': [ 'jisp' ],\n    'application/vnd.joost.joda-archive': [ 'joda' ],\n    'application/vnd.kahootz': [ 'ktz', 'ktr' ],\n    'application/vnd.kde.karbon': [ 'karbon' ],\n    'application/vnd.kde.kchart': [ 'chrt' ],\n    'application/vnd.kde.kformula': [ 'kfo' ],\n    'application/vnd.kde.kivio': [ 'flw' ],\n    'application/vnd.kde.kontour': [ 'kon' ],\n    'application/vnd.kde.kpresenter': [ 'kpr', 'kpt' ],\n    'application/vnd.kde.kspread': [ 'ksp' ],\n    'application/vnd.kde.kword': [ 'kwd', 'kwt' ],\n    'application/vnd.kenameaapp': [ 'htke' ],\n    'application/vnd.kidspiration': [ 'kia' ],\n    'application/vnd.kinar': [ 'kne', 'knp' ],\n    'application/vnd.koan': [ 'skp', 'skd', 'skt', 'skm' ],\n    'application/vnd.kodak-descriptor': [ 'sse' ],\n    'application/vnd.las.las+xml': [ 'lasxml' ],\n    'application/vnd.llamagraphics.life-balance.desktop': [ 'lbd' ],\n    'application/vnd.llamagraphics.life-balance.exchange+xml': [ 'lbe' ],\n    'application/vnd.lotus-1-2-3': [ '123' ],\n    'application/vnd.lotus-approach': [ 'apr' ],\n    'application/vnd.lotus-freelance': [ 'pre' ],\n    'application/vnd.lotus-notes': [ 'nsf' ],\n    'application/vnd.lotus-organizer': [ 'org' ],\n    'application/vnd.lotus-screencam': [ 'scm' ],\n    'application/vnd.lotus-wordpro': [ 'lwp' ],\n    'application/vnd.macports.portpkg': [ 'portpkg' ],\n    'application/vnd.mcd': [ 'mcd' ],\n    'application/vnd.medcalcdata': [ 'mc1' ],\n    'application/vnd.mediastation.cdkey': [ 'cdkey' ],\n    'application/vnd.mfer': [ 'mwf' ],\n    'application/vnd.mfmp': [ 'mfm' ],\n    'application/vnd.micrografx.flo': [ 'flo' ],\n    'application/vnd.micrografx.igx': [ 'igx' ],\n    'application/vnd.mif': [ 'mif' ],\n    'application/vnd.mobius.daf': [ 'daf' ],\n    'application/vnd.mobius.dis': [ 'dis' ],\n    'application/vnd.mobius.mbk': [ 'mbk' ],\n    'application/vnd.mobius.mqy': [ 'mqy' ],\n    'application/vnd.mobius.msl': [ 'msl' ],\n    'application/vnd.mobius.plc': [ 'plc' ],\n    'application/vnd.mobius.txf': [ 'txf' ],\n    'application/vnd.mophun.application': [ 'mpn' ],\n    'application/vnd.mophun.certificate': [ 'mpc' ],\n    'application/vnd.mozilla.xul+xml': [ 'xul' ],\n    'application/vnd.ms-artgalry': [ 'cil' ],\n    'application/vnd.ms-cab-compressed': [ 'cab' ],\n    'application/vnd.ms-excel': [ 'xls', 'xlm', 'xla', 'xlc', 'xlt', 'xlw' ],\n    'application/vnd.ms-excel.addin.macroenabled.12': [ 'xlam' ],\n    'application/vnd.ms-excel.sheet.binary.macroenabled.12': [ 'xlsb' ],\n    'application/vnd.ms-excel.sheet.macroenabled.12': [ 'xlsm' ],\n    'application/vnd.ms-excel.template.macroenabled.12': [ 'xltm' ],\n    'application/vnd.ms-fontobject': [ 'eot' ],\n    'application/vnd.ms-htmlhelp': [ 'chm' ],\n    'application/vnd.ms-ims': [ 'ims' ],\n    'application/vnd.ms-lrm': [ 'lrm' ],\n    'application/vnd.ms-officetheme': [ 'thmx' ],\n    'application/vnd.ms-pki.seccat': [ 'cat' ],\n    'application/vnd.ms-pki.stl': [ 'stl' ],\n    'application/vnd.ms-powerpoint': [ 'ppt', 'pps', 'pot' ],\n    'application/vnd.ms-powerpoint.addin.macroenabled.12': [ 'ppam' ],\n    'application/vnd.ms-powerpoint.presentation.macroenabled.12': [ 'pptm' ],\n    'application/vnd.ms-powerpoint.slide.macroenabled.12': [ 'sldm' ],\n    'application/vnd.ms-powerpoint.slideshow.macroenabled.12': [ 'ppsm' ],\n    'application/vnd.ms-powerpoint.template.macroenabled.12': [ 'potm' ],\n    'application/vnd.ms-project': [ 'mpp', 'mpt' ],\n    'application/vnd.ms-word.document.macroenabled.12': [ 'docm' ],\n    'application/vnd.ms-word.template.macroenabled.12': [ 'dotm' ],\n    'application/vnd.ms-works': [ 'wps', 'wks', 'wcm', 'wdb' ],\n    'application/vnd.ms-wpl': [ 'wpl' ],\n    'application/vnd.ms-xpsdocument': [ 'xps' ],\n    'application/vnd.mseq': [ 'mseq' ],\n    'application/vnd.musician': [ 'mus' ],\n    'application/vnd.muvee.style': [ 'msty' ],\n    'application/vnd.mynfc': [ 'taglet' ],\n    'application/vnd.neurolanguage.nlu': [ 'nlu' ],\n    'application/vnd.nitf': [ 'ntf', 'nitf' ],\n    'application/vnd.noblenet-directory': [ 'nnd' ],\n    'application/vnd.noblenet-sealer': [ 'nns' ],\n    'application/vnd.noblenet-web': [ 'nnw' ],\n    'application/vnd.nokia.n-gage.data': [ 'ngdat' ],\n    'application/vnd.nokia.radio-preset': [ 'rpst' ],\n    'application/vnd.nokia.radio-presets': [ 'rpss' ],\n    'application/vnd.novadigm.edm': [ 'edm' ],\n    'application/vnd.novadigm.edx': [ 'edx' ],\n    'application/vnd.novadigm.ext': [ 'ext' ],\n    'application/vnd.oasis.opendocument.chart': [ 'odc' ],\n    'application/vnd.oasis.opendocument.chart-template': [ 'otc' ],\n    'application/vnd.oasis.opendocument.database': [ 'odb' ],\n    'application/vnd.oasis.opendocument.formula': [ 'odf' ],\n    'application/vnd.oasis.opendocument.formula-template': [ 'odft' ],\n    'application/vnd.oasis.opendocument.graphics': [ 'odg' ],\n    'application/vnd.oasis.opendocument.graphics-template': [ 'otg' ],\n    'application/vnd.oasis.opendocument.image': [ 'odi' ],\n    'application/vnd.oasis.opendocument.image-template': [ 'oti' ],\n    'application/vnd.oasis.opendocument.presentation': [ 'odp' ],\n    'application/vnd.oasis.opendocument.presentation-template': [ 'otp' ],\n    'application/vnd.oasis.opendocument.spreadsheet': [ 'ods' ],\n    'application/vnd.oasis.opendocument.spreadsheet-template': [ 'ots' ],\n    'application/vnd.oasis.opendocument.text': [ 'odt' ],\n    'application/vnd.oasis.opendocument.text-master': [ 'odm' ],\n    'application/vnd.oasis.opendocument.text-template': [ 'ott' ],\n    'application/vnd.oasis.opendocument.text-web': [ 'oth' ],\n    'application/vnd.olpc-sugar': [ 'xo' ],\n    'application/vnd.oma.dd2+xml': [ 'dd2' ],\n    'application/vnd.openofficeorg.extension': [ 'oxt' ],\n    'application/vnd.openxmlformats-officedocument.presentationml.presentation': [ 'pptx' ],\n    'application/vnd.openxmlformats-officedocument.presentationml.slide': [ 'sldx' ],\n    'application/vnd.openxmlformats-officedocument.presentationml.slideshow': [ 'ppsx' ],\n    'application/vnd.openxmlformats-officedocument.presentationml.template': [ 'potx' ],\n    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': [ 'xlsx' ],\n    'application/vnd.openxmlformats-officedocument.spreadsheetml.template': [ 'xltx' ],\n    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': [ 'docx' ],\n    'application/vnd.openxmlformats-officedocument.wordprocessingml.template': [ 'dotx' ],\n    'application/vnd.osgeo.mapguide.package': [ 'mgp' ],\n    'application/vnd.osgi.dp': [ 'dp' ],\n    'application/vnd.osgi.subsystem': [ 'esa' ],\n    'application/vnd.palm': [ 'pdb', 'pqa', 'oprc' ],\n    'application/vnd.pawaafile': [ 'paw' ],\n    'application/vnd.pg.format': [ 'str' ],\n    'application/vnd.pg.osasli': [ 'ei6' ],\n    'application/vnd.picsel': [ 'efif' ],\n    'application/vnd.pmi.widget': [ 'wg' ],\n    'application/vnd.pocketlearn': [ 'plf' ],\n    'application/vnd.powerbuilder6': [ 'pbd' ],\n    'application/vnd.previewsystems.box': [ 'box' ],\n    'application/vnd.proteus.magazine': [ 'mgz' ],\n    'application/vnd.publishare-delta-tree': [ 'qps' ],\n    'application/vnd.pvi.ptid1': [ 'ptid' ],\n    'application/vnd.quark.quarkxpress': [ 'qxd', 'qxt', 'qwd', 'qwt', 'qxl', 'qxb' ],\n    'application/vnd.realvnc.bed': [ 'bed' ],\n    'application/vnd.recordare.musicxml': [ 'mxl' ],\n    'application/vnd.recordare.musicxml+xml': [ 'musicxml' ],\n    'application/vnd.rig.cryptonote': [ 'cryptonote' ],\n    'application/vnd.rim.cod': [ 'cod' ],\n    'application/vnd.rn-realmedia': [ 'rm' ],\n    'application/vnd.rn-realmedia-vbr': [ 'rmvb' ],\n    'application/vnd.route66.link66+xml': [ 'link66' ],\n    'application/vnd.sailingtracker.track': [ 'st' ],\n    'application/vnd.seemail': [ 'see' ],\n    'application/vnd.sema': [ 'sema' ],\n    'application/vnd.semd': [ 'semd' ],\n    'application/vnd.semf': [ 'semf' ],\n    'application/vnd.shana.informed.formdata': [ 'ifm' ],\n    'application/vnd.shana.informed.formtemplate': [ 'itp' ],\n    'application/vnd.shana.informed.interchange': [ 'iif' ],\n    'application/vnd.shana.informed.package': [ 'ipk' ],\n    'application/vnd.simtech-mindmapper': [ 'twd', 'twds' ],\n    'application/vnd.smaf': [ 'mmf' ],\n    'application/vnd.smart.teacher': [ 'teacher' ],\n    'application/vnd.solent.sdkm+xml': [ 'sdkm', 'sdkd' ],\n    'application/vnd.spotfire.dxp': [ 'dxp' ],\n    'application/vnd.spotfire.sfs': [ 'sfs' ],\n    'application/vnd.stardivision.calc': [ 'sdc' ],\n    'application/vnd.stardivision.draw': [ 'sda' ],\n    'application/vnd.stardivision.impress': [ 'sdd' ],\n    'application/vnd.stardivision.math': [ 'smf' ],\n    'application/vnd.stardivision.writer': [ 'sdw', 'vor' ],\n    'application/vnd.stardivision.writer-global': [ 'sgl' ],\n    'application/vnd.stepmania.package': [ 'smzip' ],\n    'application/vnd.stepmania.stepchart': [ 'sm' ],\n    'application/vnd.sun.xml.calc': [ 'sxc' ],\n    'application/vnd.sun.xml.calc.template': [ 'stc' ],\n    'application/vnd.sun.xml.draw': [ 'sxd' ],\n    'application/vnd.sun.xml.draw.template': [ 'std' ],\n    'application/vnd.sun.xml.impress': [ 'sxi' ],\n    'application/vnd.sun.xml.impress.template': [ 'sti' ],\n    'application/vnd.sun.xml.math': [ 'sxm' ],\n    'application/vnd.sun.xml.writer': [ 'sxw' ],\n    'application/vnd.sun.xml.writer.global': [ 'sxg' ],\n    'application/vnd.sun.xml.writer.template': [ 'stw' ],\n    'application/vnd.sus-calendar': [ 'sus', 'susp' ],\n    'application/vnd.svd': [ 'svd' ],\n    'application/vnd.symbian.install': [ 'sis', 'sisx' ],\n    'application/vnd.syncml+xml': [ 'xsm' ],\n    'application/vnd.syncml.dm+wbxml': [ 'bdm' ],\n    'application/vnd.syncml.dm+xml': [ 'xdm' ],\n    'application/vnd.tao.intent-module-archive': [ 'tao' ],\n    'application/vnd.tcpdump.pcap': [ 'pcap', 'cap', 'dmp' ],\n    'application/vnd.tmobile-livetv': [ 'tmo' ],\n    'application/vnd.trid.tpt': [ 'tpt' ],\n    'application/vnd.triscape.mxs': [ 'mxs' ],\n    'application/vnd.trueapp': [ 'tra' ],\n    'application/vnd.ufdl': [ 'ufd', 'ufdl' ],\n    'application/vnd.uiq.theme': [ 'utz' ],\n    'application/vnd.umajin': [ 'umj' ],\n    'application/vnd.unity': [ 'unityweb' ],\n    'application/vnd.uoml+xml': [ 'uoml' ],\n    'application/vnd.vcx': [ 'vcx' ],\n    'application/vnd.visio': [ 'vsd', 'vst', 'vss', 'vsw' ],\n    'application/vnd.visionary': [ 'vis' ],\n    'application/vnd.vsf': [ 'vsf' ],\n    'application/vnd.wap.wbxml': [ 'wbxml' ],\n    'application/vnd.wap.wmlc': [ 'wmlc' ],\n    'application/vnd.wap.wmlscriptc': [ 'wmlsc' ],\n    'application/vnd.webturbo': [ 'wtb' ],\n    'application/vnd.wolfram.player': [ 'nbp' ],\n    'application/vnd.wordperfect': [ 'wpd' ],\n    'application/vnd.wqd': [ 'wqd' ],\n    'application/vnd.wt.stf': [ 'stf' ],\n    'application/vnd.xara': [ 'xar' ],\n    'application/vnd.xfdl': [ 'xfdl' ],\n    'application/vnd.yamaha.hv-dic': [ 'hvd' ],\n    'application/vnd.yamaha.hv-script': [ 'hvs' ],\n    'application/vnd.yamaha.hv-voice': [ 'hvp' ],\n    'application/vnd.yamaha.openscoreformat': [ 'osf' ],\n    'application/vnd.yamaha.openscoreformat.osfpvg+xml': [ 'osfpvg' ],\n    'application/vnd.yamaha.smaf-audio': [ 'saf' ],\n    'application/vnd.yamaha.smaf-phrase': [ 'spf' ],\n    'application/vnd.yellowriver-custom-menu': [ 'cmp' ],\n    'application/vnd.zul': [ 'zir', 'zirz' ],\n    'application/vnd.zzazz.deck+xml': [ 'zaz' ],\n    'application/voicexml+xml': [ 'vxml' ],\n    'application/widget': [ 'wgt' ],\n    'application/winhlp': [ 'hlp' ],\n    'application/wsdl+xml': [ 'wsdl' ],\n    'application/wspolicy+xml': [ 'wspolicy' ],\n    'application/x-7z-compressed': [ '7z' ],\n    'application/x-abiword': [ 'abw' ],\n    'application/x-ace-compressed': [ 'ace' ],\n    'application/x-apple-diskimage': [ 'dmg' ],\n    'application/x-authorware-bin': [ 'aab', 'x32', 'u32', 'vox' ],\n    'application/x-authorware-map': [ 'aam' ],\n    'application/x-authorware-seg': [ 'aas' ],\n    'application/x-bcpio': [ 'bcpio' ],\n    'application/x-bittorrent': [ 'torrent' ],\n    'application/x-blorb': [ 'blb', 'blorb' ],\n    'application/x-bzip': [ 'bz' ],\n    'application/x-bzip2': [ 'bz2', 'boz' ],\n    'application/x-cbr': [ 'cbr', 'cba', 'cbt', 'cbz', 'cb7' ],\n    'application/x-cdlink': [ 'vcd' ],\n    'application/x-cfs-compressed': [ 'cfs' ],\n    'application/x-chat': [ 'chat' ],\n    'application/x-chess-pgn': [ 'pgn' ],\n    'application/x-conference': [ 'nsc' ],\n    'application/x-cpio': [ 'cpio' ],\n    'application/x-csh': [ 'csh' ],\n    'application/x-debian-package': [ 'deb', 'udeb' ],\n    'application/x-dgc-compressed': [ 'dgc' ],\n    'application/x-director': [ 'dir', 'dcr', 'dxr', 'cst', 'cct', 'cxt', 'w3d', 'fgd', 'swa' ],\n    'application/x-doom': [ 'wad' ],\n    'application/x-dtbncx+xml': [ 'ncx' ],\n    'application/x-dtbook+xml': [ 'dtb' ],\n    'application/x-dtbresource+xml': [ 'res' ],\n    'application/x-dvi': [ 'dvi' ],\n    'application/x-envoy': [ 'evy' ],\n    'application/x-eva': [ 'eva' ],\n    'application/x-font-bdf': [ 'bdf' ],\n    'application/x-font-ghostscript': [ 'gsf' ],\n    'application/x-font-linux-psf': [ 'psf' ],\n    'application/x-font-otf': [ 'otf' ],\n    'application/x-font-pcf': [ 'pcf' ],\n    'application/x-font-snf': [ 'snf' ],\n    'application/x-font-ttf': [ 'ttf', 'ttc' ],\n    'application/x-font-type1': [ 'pfa', 'pfb', 'pfm', 'afm' ],\n    'application/font-woff': [ 'woff' ],\n    'application/x-freearc': [ 'arc' ],\n    'application/x-futuresplash': [ 'spl' ],\n    'application/x-gca-compressed': [ 'gca' ],\n    'application/x-glulx': [ 'ulx' ],\n    'application/x-gnumeric': [ 'gnumeric' ],\n    'application/x-gramps-xml': [ 'gramps' ],\n    'application/x-gtar': [ 'gtar' ],\n    'application/x-hdf': [ 'hdf' ],\n    'application/x-install-instructions': [ 'install' ],\n    'application/x-iso9660-image': [ 'iso' ],\n    'application/x-java-jnlp-file': [ 'jnlp' ],\n    'application/x-latex': [ 'latex' ],\n    'application/x-lzh-compressed': [ 'lzh', 'lha' ],\n    'application/x-mie': [ 'mie' ],\n    'application/x-mobipocket-ebook': [ 'prc', 'mobi' ],\n    'application/x-ms-application': [ 'application' ],\n    'application/x-ms-shortcut': [ 'lnk' ],\n    'application/x-ms-wmd': [ 'wmd' ],\n    'application/x-ms-wmz': [ 'wmz' ],\n    'application/x-ms-xbap': [ 'xbap' ],\n    'application/x-msaccess': [ 'mdb' ],\n    'application/x-msbinder': [ 'obd' ],\n    'application/x-mscardfile': [ 'crd' ],\n    'application/x-msclip': [ 'clp' ],\n    'application/x-msdownload': [ 'exe', 'dll', 'com', 'bat', 'msi' ],\n    'application/x-msmediaview': [ 'mvb', 'm13', 'm14' ],\n    'application/x-msmetafile': [ 'wmf', 'wmz', 'emf', 'emz' ],\n    'application/x-msmoney': [ 'mny' ],\n    'application/x-mspublisher': [ 'pub' ],\n    'application/x-msschedule': [ 'scd' ],\n    'application/x-msterminal': [ 'trm' ],\n    'application/x-mswrite': [ 'wri' ],\n    'application/x-netcdf': [ 'nc', 'cdf' ],\n    'application/x-nzb': [ 'nzb' ],\n    'application/x-pkcs12': [ 'p12', 'pfx' ],\n    'application/x-pkcs7-certificates': [ 'p7b', 'spc' ],\n    'application/x-pkcs7-certreqresp': [ 'p7r' ],\n    'application/x-rar-compressed': [ 'rar' ],\n    'application/x-research-info-systems': [ 'ris' ],\n    'application/x-sh': [ 'sh' ],\n    'application/x-shar': [ 'shar' ],\n    'application/x-shockwave-flash': [ 'swf' ],\n    'application/x-silverlight-app': [ 'xap' ],\n    'application/x-sql': [ 'sql' ],\n    'application/x-stuffit': [ 'sit' ],\n    'application/x-stuffitx': [ 'sitx' ],\n    'application/x-subrip': [ 'srt' ],\n    'application/x-sv4cpio': [ 'sv4cpio' ],\n    'application/x-sv4crc': [ 'sv4crc' ],\n    'application/x-t3vm-image': [ 't3' ],\n    'application/x-tads': [ 'gam' ],\n    'application/x-tar': [ 'tar' ],\n    'application/x-tcl': [ 'tcl' ],\n    'application/x-tex': [ 'tex' ],\n    'application/x-tex-tfm': [ 'tfm' ],\n    'application/x-texinfo': [ 'texinfo', 'texi' ],\n    'application/x-tgif': [ 'obj' ],\n    'application/x-ustar': [ 'ustar' ],\n    'application/x-wais-source': [ 'src' ],\n    'application/x-x509-ca-cert': [ 'der', 'crt' ],\n    'application/x-xfig': [ 'fig' ],\n    'application/x-xliff+xml': [ 'xlf' ],\n    'application/x-xpinstall': [ 'xpi' ],\n    'application/x-xz': [ 'xz' ],\n    'application/x-zmachine': [ 'z1', 'z2', 'z3', 'z4', 'z5', 'z6', 'z7', 'z8' ],\n    'application/xaml+xml': [ 'xaml' ],\n    'application/xcap-diff+xml': [ 'xdf' ],\n    'application/xenc+xml': [ 'xenc' ],\n    'application/xhtml+xml': [ 'xhtml', 'xht' ],\n    'application/xml': [ 'xml', 'xsl' ],\n    'application/xml-dtd': [ 'dtd' ],\n    'application/xop+xml': [ 'xop' ],\n    'application/xproc+xml': [ 'xpl' ],\n    'application/xslt+xml': [ 'xslt' ],\n    'application/xspf+xml': [ 'xspf' ],\n    'application/xv+xml': [ 'mxml', 'xhvml', 'xvml', 'xvm' ],\n    'application/yang': [ 'yang' ],\n    'application/yin+xml': [ 'yin' ],\n    'application/zip': [ 'zip' ],\n    'audio/adpcm': [ 'adp' ],\n    'audio/aif': [ 'aif' ],\n    'audio/basic': [ 'au', 'snd' ],\n    'audio/m4a': [ 'm4a' ],\n    'audio/midi': [ 'mid', 'midi', 'kar', 'rmi' ],\n    'audio/mp4': [ 'mp4a' ],\n    'audio/mpeg': [ 'mpga', 'mp2', 'mp2a', 'm2a' ],\n    'audio/mpeg3': [ 'mp3', 'm3a' ],\n    'audio/ogg': [ 'oga', 'ogg', 'spx' ],\n    'audio/s3m': [ 's3m' ],\n    'audio/silk': [ 'sil' ],\n    'audio/vnd.dece.audio': [ 'uva', 'uvva' ],\n    'audio/vnd.digital-winds': [ 'eol' ],\n    'audio/vnd.dra': [ 'dra' ],\n    'audio/vnd.dts': [ 'dts' ],\n    'audio/vnd.dts.hd': [ 'dtshd' ],\n    'audio/vnd.lucent.voice': [ 'lvp' ],\n    'audio/vnd.ms-playready.media.pya': [ 'pya' ],\n    'audio/vnd.nuera.ecelp4800': [ 'ecelp4800' ],\n    'audio/vnd.nuera.ecelp7470': [ 'ecelp7470' ],\n    'audio/vnd.nuera.ecelp9600': [ 'ecelp9600' ],\n    'audio/vnd.rip': [ 'rip' ],\n    'audio/wav': [ 'wav' ],\n    'audio/webm': [ 'weba' ],\n    'audio/x-aac': [ 'aac' ],\n    'audio/x-aiff': [ 'aiff', 'aifc' ],\n    'audio/x-caf': [ 'caf' ],\n    'audio/x-flac': [ 'flac' ],\n    'audio/x-matroska': [ 'mka' ],\n    'audio/x-mpegurl': [ 'm3u' ],\n    'audio/x-ms-wax': [ 'wax' ],\n    'audio/x-ms-wma': [ 'wma' ],\n    'audio/x-pn-realaudio': [ 'ram', 'ra' ],\n    'audio/x-pn-realaudio-plugin': [ 'rmp' ],\n    'audio/x-wav': [ 'wav' ],\n    'audio/xm': [ 'xm' ],\n    'chemical/x-cdx': [ 'cdx' ],\n    'chemical/x-cif': [ 'cif' ],\n    'chemical/x-cmdf': [ 'cmdf' ],\n    'chemical/x-cml': [ 'cml' ],\n    'chemical/x-csml': [ 'csml' ],\n    'chemical/x-xyz': [ 'xyz' ],\n    'image/bmp': [ 'bmp' ],\n    'image/cgm': [ 'cgm' ],\n    'image/dng': [ 'dng' ],\n    'image/g3fax': [ 'g3' ],\n    'image/gif': [ 'gif' ],\n    'image/heic': [ 'heic' ],\n    'image/heif': [ 'heif' ],\n    'image/ief': [ 'ief' ],\n    'image/jpeg': [ 'jpeg', 'jpg', 'jpe' ],\n    'image/jpg': [ 'jpeg', 'jpg' ],\n    'image/ktx': [ 'ktx' ],\n    'image/png': [ 'png' ],\n    'image/prs.btif': [ 'btif' ],\n    'image/sgi': [ 'sgi' ],\n    'image/svg+xml': [ 'svg', 'svgz' ],\n    'image/tiff': [ 'tiff', 'tif' ],\n    'image/vnd.adobe.photoshop': [ 'psd' ],\n    'image/vnd.adobe.photoshop.template': [ 'psdt' ],\n    'image/vnd.adobe.pattern+png': [ 'png' ],\n    'image/vnd.adobe.shape+svg': [ 'shape' ],\n    'image/vnd.dece.graphic': [ 'uvi', 'uvvi', 'uvg', 'uvvg' ],\n    'image/vnd.dvb.subtitle': [ 'sub' ],\n    'image/vnd.djvu': [ 'djvu', 'djv' ],\n    'image/vnd.dwg': [ 'dwg' ],\n    'image/vnd.dxf': [ 'dxf' ],\n    'image/vnd.fastbidsheet': [ 'fbs' ],\n    'image/vnd.fpx': [ 'fpx' ],\n    'image/vnd.fst': [ 'fst' ],\n    'image/vnd.fujixerox.edmics-mmr': [ 'mmr' ],\n    'image/vnd.fujixerox.edmics-rlc': [ 'rlc' ],\n    'image/vnd.ms-modi': [ 'mdi' ],\n    'image/vnd.ms-photo': [ 'wdp' ],\n    'image/vnd.net-fpx': [ 'npx' ],\n    'image/vnd.wap.wbmp': [ 'wbmp' ],\n    'image/vnd.xiff': [ 'xif' ],\n    'image/webp': [ 'webp' ],\n    'image/x-3ds': [ '3ds' ],\n    'image/x-adobe-dng': [ 'dng' ],\n    'image/x-adobe-photoshop-brush': [ 'abr' ],\n    'image/x-cmu-raster': [ 'ras' ],\n    'image/x-cmx': [ 'cmx' ],\n    'image/x-freehand': [ 'fh', 'fhc', 'fh4', 'fh5', 'fh7' ],\n    'image/x-icon': [ 'ico' ],\n    'image/x-mrsid-image': [ 'sid' ],\n    'image/x-pcx': [ 'pcx' ],\n    'image/x-pict': [ 'pic', 'pct' ],\n    'image/x-portable-anymap': [ 'pnm' ],\n    'image/x-portable-bitmap': [ 'pbm' ],\n    'image/x-portable-graymap': [ 'pgm' ],\n    'image/x-portable-pixmap': [ 'ppm' ],\n    'image/x-rgb': [ 'rgb' ],\n    'image/x-tga': [ 'tga' ],\n    'image/x-xbitmap': [ 'xbm' ],\n    'image/x-xpixmap': [ 'xpm' ],\n    'image/x-xwindowdump': [ 'xwd' ],\n    'message/rfc822': [ 'eml', 'mime' ],\n    'model/gltf-binary': [ 'glb' ],\n    'model/gltf+json': [ 'gltf' ],\n    'model/iges': [ 'igs', 'iges' ],\n    'model/mesh': [ 'msh', 'mesh', 'silo' ],\n    'model/vnd.usdz+zip': [ 'usdz' ],\n    'model/vnd.adobe.dn+dcx': [ 'dn' ],\n    'model/vnd.adobe.dn+dcxucf': [ 'dn' ],\n    'model/vnd.collada+xml': [ 'dae' ],\n    'model/vnd.dwf': [ 'dwf' ],\n    'model/vnd.gdl': [ 'gdl' ],\n    'model/vnd.gtw': [ 'gtw' ],\n    'model/vnd.mts': [ 'mts' ],\n    'model/vnd.vtu': [ 'vtu' ],\n    'model/vrml': [ 'wrl', 'vrml' ],\n    'model/x3d+binary': [ 'x3db', 'x3dbz' ],\n    'model/x3d+vrml': [ 'x3dv', 'x3dvz' ],\n    'model/x3d+xml': [ 'x3d', 'x3dz' ],\n    'text/cache-manifest': [ 'appcache' ],\n    'text/calendar': [ 'ics', 'ifb' ],\n    'text/css': [ 'css' ],\n    'text/csv': [ 'csv' ],\n    'text/html': [ 'html', 'htm' ],\n    'text/n3': [ 'n3' ],\n    'text/plain': [ 'txt', 'text', 'conf', 'def', 'list', 'log', 'in' ],\n    'text/prs.lines.tag': [ 'dsc' ],\n    'text/richtext': [ 'rtx' ],\n    'text/sgml': [ 'sgml', 'sgm' ],\n    'text/tab-separated-values': [ 'tsv' ],\n    'text/troff': [ 't', 'tr', 'roff', 'man', 'me', 'ms' ],\n    'text/turtle': [ 'ttl' ],\n    'text/uri-list': [ 'uri', 'uris', 'urls' ],\n    'text/vcard': [ 'vcard' ],\n    'text/vnd.curl': [ 'curl' ],\n    'text/vnd.curl.dcurl': [ 'dcurl' ],\n    'text/vnd.curl.scurl': [ 'scurl' ],\n    'text/vnd.curl.mcurl': [ 'mcurl' ],\n    'text/vnd.dvb.subtitle': [ 'sub' ],\n    'text/vnd.fly': [ 'fly' ],\n    'text/vnd.fmi.flexstor': [ 'flx' ],\n    'text/vnd.graphviz': [ 'gv' ],\n    'text/vnd.in3d.3dml': [ '3dml' ],\n    'text/vnd.in3d.spot': [ 'spot' ],\n    'text/vnd.sun.j2me.app-descriptor': [ 'jad' ],\n    'text/vnd.wap.wml': [ 'wml' ],\n    'text/vnd.wap.wmlscript': [ 'wmls' ],\n    'text/x-asm': [ 's', 'asm' ],\n    'text/x-c': [ 'c', 'cc', 'cxx', 'cpp', 'h', 'hh', 'dic' ],\n    'text/x-fortran': [ 'f', 'for', 'f77', 'f90' ],\n    'text/x-java-source': [ 'java' ],\n    'text/x-opml': [ 'opml' ],\n    'text/x-pascal': [ 'p', 'pas' ],\n    'text/x-nfo': [ 'nfo' ],\n    'text/x-setext': [ 'etx' ],\n    'text/x-sfv': [ 'sfv' ],\n    'text/x-uuencode': [ 'uu' ],\n    'text/x-vcalendar': [ 'vcs' ],\n    'text/x-vcard': [ 'vcf' ],\n    'video/3gpp': [ '3gp' ],\n    'video/3gpp2': [ '3g2' ],\n    'video/h261': [ 'h261' ],\n    'video/h263': [ 'h263' ],\n    'video/h264': [ 'h264' ],\n    'video/jpeg': [ 'jpgv' ],\n    'video/jpm': [ 'jpm', 'jpgm' ],\n    'video/mj2': [ 'mj2', 'mjp2' ],\n    'video/mp4': [ 'mp4', 'mp4v', 'mpg4' ],\n    'video/mpeg': [ 'mpeg', 'mpg', 'mpe', 'm1v', 'm2v' ],\n    'video/ogg': [ 'ogv' ],\n    'video/quicktime': [ 'mov', 'qt' ],\n    'video/vnd.dece.hd': [ 'uvh', 'uvvh' ],\n    'video/vnd.dece.mobile': [ 'uvm', 'uvvm' ],\n    'video/vnd.dece.pd': [ 'uvp', 'uvvp' ],\n    'video/vnd.dece.sd': [ 'uvs', 'uvvs' ],\n    'video/vnd.dece.video': [ 'uvv', 'uvvv' ],\n    'video/vnd.dvb.file': [ 'dvb' ],\n    'video/vnd.fvt': [ 'fvt' ],\n    'video/vnd.mpegurl': [ 'mxu', 'm4u' ],\n    'video/vnd.ms-playready.media.pyv': [ 'pyv' ],\n    'video/vnd.uvvu.mp4': [ 'uvu', 'uvvu' ],\n    'video/vnd.vivo': [ 'viv' ],\n    'video/webm': [ 'webm' ],\n    'video/x-f4v': [ 'f4v' ],\n    'video/x-fli': [ 'fli' ],\n    'video/x-flv': [ 'flv' ],\n    'video/x-m4v': [ 'm4v' ],\n    'video/x-matroska': [ 'mkv', 'mk3d', 'mks' ],\n    'video/x-mng': [ 'mng' ],\n    'video/x-ms-asf': [ 'asf', 'asx', 'wmv' ],\n    'video/x-ms-vob': [ 'vob' ],\n    'video/x-ms-wm': [ 'wm' ],\n    'video/x-ms-wmv': [ 'wmv' ],\n    'video/x-ms-wmx': [ 'wmx' ],\n    'video/x-ms-wvx': [ 'wvx' ],\n    'video/x-msvideo': [ 'avi' ],\n    'video/x-quicktime': [ 'mov' ],\n    'video/x-sgi-movie': [ 'movie' ],\n    'video/x-smv': [ 'smv' ],\n    'x-conference/x-cooltalk': [ 'ice' ],\n    '3d/vnd.adobe.dn+dcxucf': [ 'dn' ]\n};\n\n// Renditions: list of supported conversions\n// Obtained from: https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=cloudservices&title=Format+support\n// The Storage Service, which we use to perform conversions, uses the \"SpeedOverQuality\" mode to generate thumbnails.\n// The following table lists all mime-types that can be rendered to PNG using the SpeedOverQuality mode.\nconst SUPPORTED_PNG_MIMETYPES = new Set<string>([\n    'application/x-indesign',\n    'application/postscript',\n    'application/illustrator',\n    'application/pdf',\n    'application/vnd.adobe.psremix',\n    'application/vnd.adobe.pstouch',\n    'application/vnd.adobe.ideas',\n    'application/vnd.adobe.ase',\n    'image/jpeg',\n    'image/jpg',\n    'image/pjpeg',\n    'image/tiff',\n    'image/gif',\n    'image/bmp',\n    'image/x-ms-bmp',\n    'image/svg+xml',\n    'image/png',\n    'image/x-png',\n    'image/jp2',\n    'image/psd',\n    'image/vnd.adobe.photoshop',\n    'image/heic',\n    'application/photoshop',\n    'application/x-photoshop',\n    'image/raw',\n    'image/dng',\n    'image/x-adobe-dng',\n    'video/mp4',\n    'video/mpeg',\n    'video/x-ms-wmv',\n    'video/3gpp',\n    'video/3gpp2',\n    'video/quicktime',\n    'video/x-msvideo',\n    'video/x-flv',\n    'video/x-ms-asf',\n    'video/x-m4v',\n    'video/mp2t',\n    'application/mxf',\n    'application/x-shockwave-flash',\n    'application/vnd.adobe.brushes.brush+ucf',\n    'application/vnd.adobe.collage',\n    'application/vnd.adobe.proto',\n    'application/msword',\n    'application/msexcel',\n    'application/mspowerpoint',\n    'application/vnd.ms-publisher',\n    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n    'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n    'text/plain',\n    'text/rtf',\n    'application/illustrator.template',\n    'application/vnd.adobe.indesign.template',\n    'application/vnd.adobe.photoshop.template',\n    // This is listed in the code in places. It's not clear if we actually need it.\n    'image/vnd.adobe.photoshop.template'\n]);\n\nconst EXTENSION_MAP: { [s: string]: string[] } = {};\n\nfunction extensionForUnresolvedContentType(contentType: string) {\n    const matches = contentType.match(/application\\/x-adobe-libraries-(.+)/);\n    return matches ? [ matches[1] ] : [];\n}\n\nfunction contentTypeForUnresolvedExtension(extension: string) {\n    return [ `application/x-adobe-libraries-${extension}` ];\n}\n\n/*\n    Public API\n*/\n\nexport function getExtensions(mimeType: string) {\n    if (mimeType) {\n        return MIME_TYPE_MAP[mimeType.toLowerCase()] || extensionForUnresolvedContentType(mimeType.toLowerCase());\n    }\n    return [];\n}\n\nexport function getMimeTypes(extension: string | undefined) {\n    if (extension) {\n        return EXTENSION_MAP[extension.toLowerCase()] || contentTypeForUnresolvedExtension(extension.toLowerCase());\n    }\n    return [];\n}\n\nexport function canComputeRenditionFromMimeType(mimeType: string) {\n    return SUPPORTED_PNG_MIMETYPES.has(mimeType);\n}\n\nObject.keys(MIME_TYPE_MAP).forEach((mimeType: any) => {\n    const extensions = MIME_TYPE_MAP[mimeType];\n    extensions.forEach((extension: string) => {\n        EXTENSION_MAP[extension] = EXTENSION_MAP[extension] || [];\n        EXTENSION_MAP[extension].push(mimeType);\n    });\n});\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport const placeholderPrefix = '@PLACEHOLDER';\nexport const backoffIntervals = [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ];\nexport const connectorTimeout = 10000;\nexport const melvilleFirstUseEtag = '\"\"';\nexport const rapiMaxSingleTransferSize = 10 * 1024 * 1024; // 10 MB\nexport const orchestratorQuietPeriodDuration = 0;\nexport const tlsDiscoveryPortRange = [ 45623, 45625 ];\nexport const processDiscoveryRetryDelay = 1000; // ms\nexport const processDiscoveryTimeout = 15000; // ms\nexport const orchestratorRequestRetryTimeoutSequence = [ 15000, 30000 ];\nexport const orchestratorRequestRetryMax = orchestratorRequestRetryTimeoutSequence.length;\n\n// This constant is only used to estimate upload times. Since we have switched to R-API\n// for uploads, we can remove this constant and revisit the upload time estimation.\nexport const asimovMaxChunkSize = 5242880;\n\nexport const maxSockets = 6;\nexport const toolkitNames = {\n    // Photoshop:\n    photoshop: 'TOOLKIT_NAME_PHOTOSHOP',\n    photoshop_swatches: 'TOOLKIT_NAME_PHOTOSHOP_SWATCHES',\n    photoshop_brushes: 'TOOLKIT_NAME_PHOTOSHOP_BRUSHES',\n    photoshop_gradients: 'TOOLKIT_NAME_PHOTOSHOP_GRADIENTS',\n    photoshop_patterns: 'TOOLKIT_NAME_PHOTOSHOP_PATTERNS',\n    photoshop_styles: 'TOOLKIT_NAME_PHOTOSHOP_STYLES',\n    photoshop_shapes: 'TOOLKIT_NAME_PHOTOSHOP_SHAPES',\n    // Photoshop Prerelease (only for private prerelease, a few hundred users):\n    photoshop_swatches_prerelease: 'TOOLKIT_NAME_PHOTOSHOP_SWATCHES_PR',\n    photoshop_brushes_prerelease: 'TOOLKIT_NAME_PHOTOSHOP_BRUSHES_PR',\n    photoshop_gradients_prerelease: 'TOOLKIT_NAME_PHOTOSHOP_GRADIENTS_PR',\n    photoshop_patterns_prerelease: 'TOOLKIT_NAME_PHOTOSHOP_PATTERNS_PR',\n    photoshop_styles_prerelease: 'TOOLKIT_NAME_PHOTOSHOP_STYLES_PR',\n    photoshop_shapes_prerelease: 'TOOLKIT_NAME_PHOTOSHOP_SHAPES_PR'\n};\n\nexport const ElementMimeTypeMap = {\n    IMAGE_ELEMENT_TYPE: 'application/vnd.adobe.element.image+dcx',\n    COLOR_ELEMENT_TYPE: 'application/vnd.adobe.element.color+dcx',\n    COLOR_THEME_ELEMENT_TYPE: 'application/vnd.adobe.element.colortheme+dcx',\n    BRUSH_ELEMENT_TYPE: 'application/vnd.adobe.element.brush+dcx',\n    CHARACTER_STYLE_ELEMENT_TYPE: 'application/vnd.adobe.element.characterstyle+dcx',\n    PARAGRAPH_STYLE_ELEMENT_TYPE: 'application/vnd.adobe.element.paragraphstyle+dcx',\n    FONT_ELEMENT_TYPE: 'application/vnd.adobe.element.font+dcx',\n    LAYER_STYLE_ELEMENT_TYPE: 'application/vnd.adobe.element.layerstyle+dcx',\n    LOOK_ELEMENT_TYPE: 'application/vnd.adobe.element.look+dcx',\n    CAPSULE_ELEMENT_TYPE: 'application/vnd.adobe.element.graphic+dcx',\n    VIDEO_ELEMENT_TYPE: 'application/vnd.adobe.element.video+dcx',\n    THREE_D_ELEMENT_TYPE: 'application/vnd.adobe.element.3d+dcx',\n    LIGHT_ELEMENT_TYPE: 'application/vnd.adobe.element.light+dcx',\n    MATERIAL_ELEMENT_TYPE: 'application/vnd.adobe.element.material+dcx',\n    PATTERN_ELEMENT_TYPE: 'application/vnd.adobe.element.pattern+dcx',\n    TEMPLATE_ELEMENT_TYPE: 'application/vnd.adobe.element.template+dcx',\n    TEXT_ELEMENT_TYPE: 'application/vnd.adobe.element.text+dcx',\n    ANIMATION_ELEMENT_TYPE: 'application/vnd.adobe.element.animation+dcx',\n    LIBRARY_TYPE: 'application/vnd.adobe.library+dcx',\n    GRADIENT_ELEMENT_TYPE: 'application/vnd.adobe.element.gradient+dcx',\n    COMPONENT_ELEMENT_TYPE: 'application/vnd.adobe.element.component+dcx',\n    AUDIO_ELEMENT_TYPE: 'application/vnd.adobe.element.audio+dcx'\n};\n\nexport type ElementMimeType = (typeof ElementMimeTypeMap)[keyof typeof ElementMimeTypeMap];\n\n// Library Configuration constants\nexport const LibraryConstants = {\n    MAX_ELEMENTS: 10000, // Maximum number of elements in a library\n    MAX_REMOVED_ELEMENTS: 2000, // Maximum number of removed elements in a library\n    MAX_COMPONENT_SIZE: 1024 * 1024 * 1024, // Maximum size (in bytes) of a DCX component - currently the storage service limits it to 1GB\n\n    DL_NAMESPACE: 'library', // Reserved library namespace in keys (for custom values/dcx)\n    VALID_RELATIONS: [ 'primary', 'rendition', 'alternate' ], // Valid relationships for a design library representation\n    DEFAULT_GROUP_CLASSIFIER: '$default',\n    ELEMENT_ACTIONS: [ 'edit', 'openStock', 'editInSource' ],\n    LIBRARY_ACTIONS: [ 'editInSource' ],\n    DOCUMENT_LIBRARY_ACTION_PRODUCT_MAP: {\n        types: {\n            'application/vnd.adobe.xd.cloudproject+dcx': [ 'SPKR' ]\n        },\n        products: {}\n    },\n    ELEMENT_ACTION_PRODUCT_MAP: {\n        types: {\n            'application/vnd.adobe.element.image+dcx': {\n                'application/illustrator': [ 'ILST_EDIT', 'ILST_PLACE', 'IDSN_PLACE' ],\n                'image/svg+xml': [ 'ILST_EDIT', 'ILST_PLACE' ],\n                'application/vnd.adobe.indesign-idms': [ 'IDSN_EDIT', 'IDSN_PLACE' ],\n                'image/vnd.adobe.photoshop': [ 'PHXS_EDIT', 'PHXS_PLACE', 'IDSN_PLACE' ],\n                'application/photoshop': [ 'PHXS_EDIT', 'PHXS_PLACE', 'IDSN_PLACE' ],\n                'application/photoshop.large': [ 'PHXS_EDIT', 'PHXS_PLACE', 'IDSN_PLACE' ],\n                'image/png': [ 'PHXS_EDIT', 'PHXS_PLACE', 'ILST_PLACE', 'IDSN_PLACE', 'PPRO_PLACE', 'AEFT_PLACE' ],\n                'image/jpeg': [ 'PHXS_EDIT', 'PHXS_PLACE', 'ILST_PLACE', 'IDSN_PLACE', 'PPRO_PLACE', 'AEFT_PLACE' ],\n                'image/jpg': [ 'PHXS_EDIT', 'PHXS_PLACE', 'IDSN_PLACE', 'ILST_PLACE', 'PPRO_PLACE', 'AEFT_PLACE' ],\n                'image/gif': [ 'PHXS_EDIT', 'PHXS_PLACE', 'ILST_PLACE', 'IDSN_PLACE', 'PPRO_PLACE', 'AEFT_PLACE' ],\n                'image/bmp': [ 'PHXS_EDIT', 'PHXS_PLACE', 'ILST_PLACE', 'IDSN_PLACE', 'PPRO_PLACE', 'AEFT_PLACE' ],\n                'image/x-portable-bitmap': [ 'PHXS_EDIT', 'PHXS_PLACE' ],\n                'image/x-pict': [ 'PHXS_EDIT', 'PHXS_PLACE' ],\n                'image/x-pcx': [ 'PHXS_EDIT', 'PHXS_PLACE' ],\n                'image/x-portable-graymap': [ 'PHXS_EDIT', 'PHXS_PLACE' ],\n                'image/x-portable-anymap': [ 'PHXS_EDIT', 'PHXS_PLACE' ],\n                'image/x-portable-pixmap': [ 'PHXS_EDIT', 'PHXS_PLACE' ],\n                'image/x-tga': [ 'PHXS_EDIT', 'PHXS_PLACE' ],\n                'image/tiff': [ 'PHXS_EDIT', 'PHXS_PLACE' ],\n                'image/vnd.wap.wbmp': [ 'PHXS_EDIT', 'PHXS_PLACE' ]\n            },\n            'application/vnd.adobe.element.text+dcx': {\n                'application/illustrator-text': [ 'ILST_EDIT_TEXT' ],\n                'application/vnd.adobe.indesign-idms-text': [ 'IDSN_EDIT_TEXT' ]\n            },\n            'application/vnd.adobe.element.template+dcx': {\n                'image/vnd.adobe.photoshop.template': [ 'PHXS_PLACE' ],\n                'application/illustrator.template': [ 'ILST_PLACE' ],\n                'application/vnd.adobe.indesign.template': [ 'IDSN_PLACE' ]\n            },\n            'application/vnd.adobe.element.3d+dcx': {\n                'application/vnd.adobe.obj.3d+zip': [ 'ESHR_PLACE' ]\n            },\n            'application/vnd.adobe.element.material+dcx': {\n                'application/vnd.adobe.mdl.material+zip': [ 'ESHR_PLACE' ]\n            },\n            'application/vnd.adobe.element.light+dcx': {\n                'application/vnd.adobe.ibl.light+zip': [ 'ESHR_PLACE' ]\n            },\n            'application/vnd.adobe.element.animation+dcx': {\n                'application/vnd.adobe.animate-xfl+zip': [ 'FLPR_EDIT' ],\n                'application/vnd.adobe.animate-sym+zip': [ 'FLPR_EDIT' ]\n            }\n        },\n        products: {}\n    },\n    VECTOR_RENDITION_ELEMENT_TYPES: [ 'application/illustrator' ],\n    ANALYTICS_ENABLED: false\n};\n\nexport const vulcanLibrariesTargetSpecifier = 'cclibraries';\nexport const vulcanLibrariesSAPCode = 'LIBS';\nexport const vulcanQueryRequestPayload = JSON.stringify({ apiVersion: 12 });\n\nexport const MelvilleParamsAsHeaders = [ 'start', 'limit', 'selector', 'type', 'orderBy', 'group', 'owner' ];\n\nexport const HttpStatus = {\n    OK: 200,\n    CREATED: 201,\n    ACCEPTED: 202,\n    NO_CONTENT: 204,\n    MULTIPLE_CHOICES: 300,\n    BAD_REQUEST: 400,\n    UNAUTHORIZED: 401,\n    FORBIDDEN: 403,\n    NOT_FOUND: 404,\n    CONFLICT: 409,\n    PRECONDITION_FAILED: 412,\n    UNSUPPOERTED_MEDIA_TYPE: 415,\n    IM_A_TEAPOT: 418,\n    INTERNAL_SERVER_ERROR: 500,\n    BAD_GATEWAY: 502,\n    SERVICE_UNAVAILABLE: 503\n};\n\nexport const ABORT_ERROR = 'AbortError';\nexport const REQUEST_NOT_NEEDED = 'REQUEST NOT NEEDED';\n\nexport const syncGroupPath = '/assets/adobe-libraries';\n\nexport const GenStudioProjectName = 'Adobe GenStudio Brands';\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { LibraryData } from '../data/LibraryData';\nimport { v4 as uuid } from 'uuid';\nimport { placeholderPrefix } from '../../config/constants';\nimport type { ResourceRef } from '../../CCLibraries';\nimport type { ItemId } from '../../../core/ItemBase';\n\nconst placeholderRegexString = `${placeholderPrefix}-[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}`;\nconst placeholderRegex = new RegExp(`^${placeholderRegexString}$`);\nconst containsPlaceholderRegex = new RegExp(`(${placeholderRegexString})`);\n\nexport type PlaceholderIdType = ItemId & `${typeof placeholderPrefix}-${string}`;\n\nconst getBaseLibraryData = (): Omit<LibraryData, 'id' | 'name'> => ({\n    ownership: 'private',\n    groups: [],\n    elements: [],\n    documentationElements: [],\n    deletable: true,\n    removedElements: [],\n    areElementsLoaded: true,\n    isLibraryLoaded: true,\n    isWritable: true,\n    isParentWritable: true,\n    details: {\n        elementCount: 0,\n        documentationElementCount: 0,\n        removedElementCount: 0\n    },\n    removeType: 'delete'\n});\n\nexport const createPlaceholderId = () => `${placeholderPrefix}-${uuid()}`;\n\n// @TODO - string.indexOf is much faster of a placeholder verification if we are willing to give up the safety of a complete id match.\n// Cannot do this just now as modifying has the side effect of not completing actions...\n\n/**\n * Check if a given id is a placeholder id\n * @param {string} id id to check\n * @returns {boolean} true if given id is a placeholder id\n */\nexport function isPlaceholder(id: string): id is PlaceholderIdType {\n    return placeholderRegex.test(id);\n}\n\nexport const extractPlaceholder = (path: string) => {\n    const [ placeholder ] = containsPlaceholderRegex.exec(path) || [];\n    return placeholder;\n};\n\n/**\n * Utility to create required data to create a library\n *\n * @param {Partial<LibraryData> & { id: string; name: string }} data Custom data to override base library data\n * @returns {LibraryData} Full data description for creating a library\n */\nexport const createLibraryData = (\n    data: Partial<LibraryData> & { id: string; name: string; documentExtractionData?: ResourceRef[] }\n): LibraryData => Object.assign(getBaseLibraryData(), data);\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { LinkReference } from '../../index';\nimport type { ElementReference, LibraryReference } from '../CCLibraries';\nimport type { Stringified } from '../types';\n\n/**\n * Check if a reference is in the new link schema format (aka valid JSON string or object).\n * Returns the parsed object if it is, and undefined if not.\n * @param reference A string reference that may be serialized JSON\n */\nexport function parseNewLinkSchema(reference: ElementReference): LinkReference | undefined {\n    try {\n        // If reference is already an object, return the object.\n        if (reference && typeof reference === 'object' && !Array.isArray(reference)) {\n            return reference as LinkReference;\n        }\n        const obj = JSON.parse(reference as Stringified<LinkReference>);\n        // Handle non-exception-throwing cases by checking if object: e.g. 'false', '123', false, 123, null\n        // Note: typeof null === \"object\" but luckily null is falsey\n        if (obj && typeof obj === 'object' && !Array.isArray(obj)) {\n            return obj;\n        }\n    } catch (e) {\n        return;\n    }\n}\n\n/**\n * Check if a reference is in the new link schema format (aka valid JSON string or object).\n * Returns the serialized object if it is. Otherwise, parses the legacy reference into a partial new link schema\n * and returns the string that results from serializing that partial reference.\n * @param reference A serialized link reference object or a legacy link reference string.\n */\nexport function serializeLinkReference(\n    reference: ElementReference | LibraryReference\n): Stringified<LinkReference> | string {\n    // Ensure we're working with an object.\n    const linkRef = parseLinkReference(reference);\n    if (!linkRef) {\n        return '';\n    }\n    return JSON.stringify(linkRef, Object.keys(linkRef).sort()) as Stringified<LinkReference>;\n}\n\nconst ELEMENT_REF_REGEXP = new RegExp('([^/]+);node=(.*)');\n\n/**\n * Parse any element reference into an object, including legacy string-based references (though they will parse into partial references).\n * @param reference A link reference object or string.\n */\nexport function parseLinkReference(reference: ElementReference): LinkReference | Partial<LinkReference> | undefined {\n    return parseNewLinkSchema(reference) || parseLegacyLinkSchema(reference as string);\n}\n\nexport function parseLegacyLinkSchema(reference: string): Partial<LinkReference> | undefined {\n    const matches = reference.match(ELEMENT_REF_REGEXP);\n    if (!matches) {\n        return;\n    }\n\n    const [ , libraryId, elementId ] = matches;\n    return {\n        'dc:format': 'application/vnd.adobe.library+dcx',\n        'stRef:documentID': libraryId,\n        'stRef:fromPart': `id=${elementId}`\n    };\n}\n\nexport function getAssetAndFragmentIdFromReference(\n    reference: ElementReference\n): { libraryAssetId: string; libraryId: string; elementId: string } | undefined {\n    const linkRef = parseLinkReference(reference);\n    if (!linkRef) {\n        return;\n    }\n    // The library's assetId should always be available, except for legacy references.\n    const libraryAssetId = linkRef['repo:assetId'] as string;\n    const libraryId = linkRef['stRef:documentID'] as string;\n    const elementId = (linkRef['stRef:fromPart'] as string)?.substring(3); // remove 'id='\n    return { libraryAssetId, libraryId, elementId };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2014 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { canComputeRenditionFromMimeType, getMimeTypes } from '../utils/MimeTypeUtils';\nimport { asimovMaxChunkSize, maxSockets } from '../config/constants';\n\ntype Filelike = Pick<File, 'size'>;\n\nexport function getFileExtension(fileNameOrPath: string) {\n    const fileName = fileNameOrPath && fileNameOrPath.replace(/^.*[\\\\/]/, '');\n    const dotIndex = fileName ? fileName.lastIndexOf('.') : -1;\n    if (dotIndex !== -1) {\n        return fileName.substr(dotIndex + 1).toLowerCase();\n    }\n}\n\nexport function getPrimaryMimetypeForFile(filename: string) {\n    const extension = getFileExtension(filename);\n    const [ mimetype ] = getMimeTypes(extension) || [];\n    return mimetype || 'application/octet-stream';\n}\n\n/**\n * Split a given filelike list into 2 based on filesize being over the threshhold for Asimov api\n *\n * @param {Filelike[]} files list of files to separate\n * @returns {{standard: Filelike[], asimov: Filelike[]}} list split into standard upload api and asimov upload\n */\nfunction _splitFileUploadsByApi(files: Filelike[]): { standard: Filelike[]; asimov: Filelike[] } {\n    return files.reduce<{ standard: Filelike[]; asimov: Filelike[] }>(\n        (acc, val) => {\n            val.size > asimovMaxChunkSize ? acc.asimov.push(val) : acc.standard.push(val);\n            return acc;\n        },\n        { standard: [], asimov: [] }\n    );\n}\n\n/**\n * Break files given into sizable chunks mimicing asimov uploads\n *\n * @param {Filelike[]} files list of files to upload via asimov (all files in this list should be greater than 5242880 bytes in size)\n * @returns {Filelike[]} list of chunks that would be used to upload to asimov\n */\nfunction _chunkAsimovUploads(files: Filelike[]): Filelike[] {\n    return files\n        .map(file => {\n            const { size } = file;\n            const fullChunks = Math.floor(size / asimovMaxChunkSize);\n            const remainingChunk = size % asimovMaxChunkSize;\n            const newChunks = fullChunks + (remainingChunk ? 1 : 0);\n\n            return Array.from({ length: newChunks }, (_, idx) => ({\n                size: idx === newChunks - 1 ? remainingChunk : asimovMaxChunkSize\n            }));\n        })\n        .flat();\n}\n\n/**\n * Utility function to estimate how long it will take to upload a set of files\n *\n * @param {Filelike[]} files files to upload\n * @returns {number} estimated time to upload list of files given\n */\nfunction _estimateTimeToUploadSortedArray(files: Filelike[]) {\n    // Sort in decending order by size\n    files.sort((a: Filelike, b: Filelike) => b.size - a.size);\n\n    // Number of batches we require to upload all files in the given array\n    const numBatches = Math.ceil(files.length / maxSockets);\n\n    // Assume worst case scenario that the largest files are shared equally across batches\n    const largestFilesPerBatch = files.splice(0, numBatches);\n\n    // According to automation data collection it currently takes approximately\n    // 1 sec per 1Mb to upload. Use this as a marker\n    return largestFilesPerBatch.reduce((acc, file) => (acc += Math.round((file.size / 1024) * 2.5)), 0);\n}\n\n/**\n * Some environments require showing a warning to the user if an upload\n * is estimated to take longer than a certain amount of time. Utility\n * estimates the time to upload assets so the UI can make a rough estimate\n * whether to display a message.\n *\n * Utility generates an estimated upload time for standard and asimov api uploaded\n * files and returns the highest estimate of the 2.\n *\n * @example\n * ```ts\n * import { utils } from '@cclibraries/cc-libraries-js';\n *\n * const estimate = utils.estimateUploadTime([{size: 1234567678}]);\n * ```\n * @param {Filelike[]} fileList list of files you want an estimated upload time for\n * @returns {number} estimated time to upload in milliseconds\n */\nexport function estimateUploadTime(fileList: Filelike[]) {\n    // Split the list into 2 arrays. 1 for standard upload, the other for asimov uploads\n    const { standard, asimov } = _splitFileUploadsByApi(fileList);\n\n    // Calculate time to upload files and return the largest of the 2 results\n    return Math.max(\n        _estimateTimeToUploadSortedArray(standard),\n        _estimateTimeToUploadSortedArray(_chunkAsimovUploads(asimov))\n    );\n}\n\nfunction getImageDimensionsWeb(file: File): Promise<undefined | { width: number; height: number }> {\n    return new Promise(resolve => {\n        const reader = new FileReader();\n        reader.onload = event => {\n            const img = new Image();\n            img.onload = () => {\n                resolve({ width: img.width, height: img.height });\n            };\n            img.onerror = () => {\n                resolve(undefined);\n            };\n            img.src = event.target?.result as any;\n        };\n        reader.readAsDataURL(file);\n    });\n}\n\n/**\n * Asynchronously get the dimensions of an image file\n * @param {File} file\n * @param {string} type\n * @returns {Promise<undefined | Object>} the dimensions object, if it's possible to compute.\n */\nexport async function getImageDimensions(\n    file: File,\n    type: string\n): Promise<undefined | { width?: number; height?: number }> {\n    if (!canComputeRenditionFromMimeType(type)) {\n        // If the file type cannot be interpreted as an image,\n        // we can't compute its \"width\" and \"height\".\n        return;\n    }\n    try {\n        if (typeof window !== 'undefined' && window.FileReader && window.Image) {\n            // For Web browser environment\n            return getImageDimensionsWeb(file);\n        } else {\n            // TODO: This should also work in a Node.js environment.\n            // See: https://git.corp.adobe.com/ProjectCentral/cc-libs-firefly-script#areas-to-fix\n            return;\n        }\n    } catch (e) {\n        return;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport SAMError, { SAMErrorCode } from '@sam-js-src/core/SAMError';\n\n/**\n * LibraryError class encompasses all Error types that can be generated internally by the JSAPI\n *\n * @packageDocumentation\n * @module LibraryError\n */\n\nexport const CodePriority = [\n    'NETWORK_ERROR',\n    'EXCEEDS_QUOTA',\n    'LOGGED_OUT',\n    'INVALID_DATA',\n    'NOT_ALLOWED',\n    'NOT_SUPPORTED',\n    'NOT_IMPLEMENTED',\n    'INVALID_PARAMETER',\n    'CONNECTION_FAILED',\n    'REQUEST_FAILED',\n    'INVALID_RESPONSE',\n    'INVALID_JSON'\n] as const;\n\nexport type Code = typeof CodePriority[number];\n\ntype ErrorLike = {\n    code: Code;\n    message: string;\n    libraryId?: string;\n    _additionalInfo?: {\n        underlyingError?: UnderlyingError\n    };\n};\n\nexport type UnderlyingError = Omit<ErrorLike, '_additionalInfo'>;\n\nfunction isErrorLike(errorLikeObj: {}): errorLikeObj is ErrorLike {\n    const errLikeCast = errorLikeObj as ErrorLike;\n    return !!errLikeCast.code && !!errLikeCast.message;\n}\n\nfunction ConvertErrorCode(libraryErrorCode: Code): SAMErrorCode {\n    switch (libraryErrorCode) {\n    case 'EXCEEDS_QUOTA':\n        return SAMErrorCode.FULL_CLOUD_STORAGE;\n    case 'LOGGED_OUT':\n    case 'NOT_ALLOWED':\n        return SAMErrorCode.AUTHORIZATION_ERROR;\n    case 'NETWORK_ERROR':\n        return SAMErrorCode.NETWORK_ERROR;\n    case 'NOT_SUPPORTED':\n    case 'NOT_IMPLEMENTED':\n        return SAMErrorCode.UNSUPPORTED;\n    case 'INVALID_DATA':\n    case 'INVALID_PARAMETER':\n    case 'CONNECTION_FAILED':\n    case 'REQUEST_FAILED':\n    case 'INVALID_RESPONSE':\n    case 'INVALID_JSON' :\n    default:\n        return SAMErrorCode.UNKNOWN;\n    }\n}\n\nexport default class LibraryError extends SAMError {\n    public libraryErrorCode: Code;\n    public libraryId?: string;\n\n    constructor(code: Code, message: string, libraryId?: string, underlyingError?: UnderlyingError);\n    constructor(errorObject: ErrorLike);\n    constructor(\n        codeOrErrorLikeObject: Code | ErrorLike,\n        message?: string,\n        libraryId?: string,\n        underlyingError?: UnderlyingError\n    ) {\n        if (isErrorLike(codeOrErrorLikeObject)) {\n            message = codeOrErrorLikeObject.message;\n            libraryId = codeOrErrorLikeObject.libraryId;\n            underlyingError = codeOrErrorLikeObject._additionalInfo?.underlyingError;\n            codeOrErrorLikeObject = codeOrErrorLikeObject.code;\n        }\n\n        super(ConvertErrorCode(codeOrErrorLikeObject), message || '', { underlyingError });\n        this.libraryErrorCode = codeOrErrorLikeObject;\n        this.libraryId = libraryId;\n    }\n\n    get underlyingError(): UnderlyingError | undefined {\n        return this._additionalInfo?.underlyingError;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { EventEmitter } from 'events';\n\n/**\n * Restrict the ability for clients of JSAPI to remove all listeners on an Event Emitter.\n * Adding the getter for DANGEROUS set of methods ensures the developer understands that\n * their actions could have unforeseen consequences.\n *\n * @export\n * @class RestrictedEventEmitter\n */\nexport default class RestrictedEventEmitter {\n    private _emitter: EventEmitter = new EventEmitter();\n\n    get DANGEROUS(): { removeAllListeners: (event?: string | symbol) => RestrictedEventEmitter } {\n        return {\n            removeAllListeners: (event?: string | symbol) => {\n                // This one is weird. Native EventEmitter has a conditional in the implementation\n                // that checks for the length of arguments... an undefined value still counts as a\n                // argument so it bypasses removal of all event listeners...\n                event ? this._emitter.removeAllListeners(event) : this._emitter.removeAllListeners();\n                return this;\n            }\n        };\n    }\n\n    /**\n     * add a listener for a specified event\n     *\n     * @param {(string | symbol)} eventName name of the event to listen to\n     * @param {(...args: any[]) => void} listener callback that is triggered when an event is emitted\n     * @returns {this}\n     * @memberof RestrictedEventEmitter\n     */\n    addListener(eventName: string | symbol, listener: (...args: any[]) => void): this {\n        this._emitter.addListener(eventName, listener);\n        return this;\n    }\n\n    /**\n     * alias for addListener\n     *\n     * @param {(string | symbol)} eventName name of the event to listen to\n     * @param {(...args: any[]) => void} listener callback that is triggered when an event is emitted\n     * @returns {this}\n     * @memberof RestrictedEventEmitter\n     */\n    on(eventName: string | symbol, listener: (...args: any[]) => void): this {\n        return this.addListener(eventName, listener);\n    }\n\n    /**\n     * add an event listener for a specified event. When that event fires and the given callback\n     * is triggered, the listener will be removed.\n     *\n     * @param {(string | symbol)} eventName name of the event to listen to\n     * @param {(...args: any[]) => void} listener callback that is triggered when an event is emitted\n     * @returns {this}\n     * @memberof RestrictedEventEmitter\n     */\n    once(eventName: string | symbol, listener: (...args: any[]) => void): this {\n        this._emitter.once(eventName, listener);\n        return this;\n    }\n\n    /**\n     * Remove the listener for the given event name\n     *\n     * @param {(string | symbol)} eventName name of the event to listen to\n     * @param {(...args: any[]) => void} listener callback that is to be removed\n     * @returns {this}\n     * @memberof RestrictedEventEmitter\n     */\n    removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this {\n        this._emitter.removeListener(eventName, listener);\n        return this;\n    }\n\n    /**\n     * Alias for removeListener\n     *\n     * @param {(string | symbol)} eventName name of the event to listen to\n     * @param {(...args: any[]) => void} listener callback that is to be removed\n     * @returns {this}\n     * @memberof RestrictedEventEmitter\n     */\n    off(eventName: string | symbol, listener: (...args: any[]) => void): this {\n        return this.removeListener(eventName, listener);\n    }\n\n    /**\n     * By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.\n     * This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the\n     * limit to be modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to\n     * indicate an unlimited number of listeners.\n     *\n     * Returns a reference to the EventEmitter, so that calls can be chained.\n     *\n     * @param {number} n Set the maximum amount of listeners that can be added to this instance of EventEmitter\n     * @returns {this}\n     * @memberof RestrictedEventEmitter\n     */\n    setMaxListeners(n: number): this {\n        this._emitter.setMaxListeners(n);\n        return this;\n    }\n\n    /**\n     * Returns the maximum number of listeners allowed\n     *\n     * @returns {number} The number of listeners allowed on on this instance of EventEmitter\n     * @memberof RestrictedEventEmitter\n     */\n    getMaxListeners(): number {\n        return this._emitter.getMaxListeners();\n    }\n\n    /**\n     * Return an array of function references for a given event name\n     *\n     * @param {(string | symbol)} eventName name of the event we want to match when returning function array.\n     * @returns {Function[]} array of function references that are triggered when an event is emitted\n     * @memberof RestrictedEventEmitter\n     */\n    listeners(eventName: string | symbol): Function[] {\n        return this._emitter.listeners(eventName);\n    }\n\n    /**\n     * Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).\n     *\n     * @example\n     * ```ts\n     * const emitter = new EventEmitter();\n     * emitter.once('log', () => console.log('log once'));\n     *\n     * // Returns a new Array with a function `onceWrapper` which has a property\n     * // `listener` which contains the original listener bound above\n     * const listeners = emitter.rawListeners('log');\n     * const logFnWrapper = listeners[0];\n     *\n     * // Logs \"log once\" to the console and does not unbind the `once` event\n     * logFnWrapper.listener();\n     *\n     * // Logs \"log once\" to the console and removes the listener\n     * logFnWrapper();\n     *\n     * emitter.on('log', () => console.log('log persistently'));\n     * // Will return a new Array with a single function bound by `.on()` above\n     * const newListeners = emitter.rawListeners('log');\n     *\n     * // Logs \"log persistently\" twice\n     * newListeners[0]();\n     * emitter.emit('log');\n     * ```\n     *\n     * @param {(string | symbol)} eventName\n     * @returns {Function[]}\n     * @memberof RestrictedEventEmitter\n     */\n    rawListeners(eventName: string | symbol): Function[] {\n        return this._emitter.rawListeners(eventName);\n    }\n\n    /**\n     * Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments to each.\n     * Returns true if the event had listeners, false otherwise.\n     *\n     * @example\n     * ```ts\n     * const EventEmitter = require('events');\n     * const myEmitter = new EventEmitter();\n     *\n     *\n     * // First listener\n     * myEmitter.on('event', function firstListener() {\n     *   console.log('Helloooo! first listener');\n     * });\n     * // Second listener\n     * myEmitter.on('event', function secondListener(arg1, arg2) {\n     *   console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n     * });\n     * // Third listener\n     * myEmitter.on('event', function thirdListener(...args) {\n     *   const parameters = args.join(', ');\n     *   console.log(`event with parameters ${parameters} in third listener`);\n     * });\n     *\n     * console.log(myEmitter.listeners('event'));\n     *\n     * myEmitter.emit('event', 1, 2, 3, 4, 5);\n     *\n     * // Prints:\n     * // [\n     * //   [Function: firstListener],\n     * //   [Function: secondListener],\n     * //   [Function: thirdListener]\n     * // ]\n     * // Helloooo! first listener\n     * // event with parameters 1, 2 in second listener\n     * // event with parameters 1, 2, 3, 4, 5 in third listener\n     * ```\n     *\n     * @param {(string | symbol)} eventName name of the event to trigger\n     * @param {...any[]} args arguments to pass to the listener\n     * @returns {boolean} Returns true if the event had listeners. False otherwise\n     * @memberof RestrictedEventEmitter\n     */\n    emit(eventName: string | symbol, ...args: any[]): boolean {\n        return this._emitter.emit(eventName, ...args);\n    }\n\n    /**\n     * Number of listeners for a given event name\n     *\n     * @param {(string | symbol)} eventName\n     * @returns {number}\n     * @memberof RestrictedEventEmitter\n     */\n    listenerCount(eventName: string | symbol): number {\n        return this._emitter.listenerCount(eventName);\n    }\n\n    /**\n     * Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple times.\n     *\n     * @example\n     * ```ts\n     * server.prependListener('connection', (stream) => {\n     *   console.log('someone connected!');\n     * });\n     * ```\n     *\n     * Returns a reference to the EventEmitter, so that calls can be chained.\n     *\n     * @param {(string | symbol)} eventName Name of the event to create a listener for\n     * @param {(...args: any[]) => void} listener Function to call when given event name is triggered\n     * @returns {this}\n     * @memberof RestrictedEventEmitter\n     */\n    prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this {\n        this._emitter.prependListener(eventName, listener);\n        return this;\n    }\n\n    /**\n     * Adds a one-timelistener function for the event named eventName to the_beginning_ of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.\n     *\n     * @example\n     * ```ts\n     * server.prependOnceListener('connection', (stream) => {\n     *   console.log('Ah, we have our first user!');\n     * });\n     * ```\n     *\n     * Returns a reference to the EventEmitter, so that calls can be chained.\n     *\n     * @param {(string | symbol)} eventName Name of the event to listen for\n     * @param {(...args: any[]) => void} listener callback to fire when named event is triggered\n     * @returns {this}\n     * @memberof RestrictedEventEmitter\n     */\n    prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this {\n        this._emitter.prependOnceListener(eventName, listener);\n        return this;\n    }\n\n    /**\n     * Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.\n     *\n     * @example\n     * ```ts\n     * const EventEmitter = require('events');\n     * const myEE = new EventEmitter();\n     * myEE.on('foo', () => {});\n     * myEE.on('bar', () => {});\n     *\n     * const sym = Symbol('symbol');\n     * myEE.on(sym, () => {});\n     *\n     * console.log(myEE.eventNames());\n     * // Prints: [ 'foo', 'bar', Symbol(symbol) ]\n     * ```\n     *\n     * @returns {((string | symbol)[])} Array of event names that are being listened for\n     * @memberof RestrictedEventEmitter\n     */\n    eventNames(): (string | symbol)[] {\n        return this._emitter.eventNames();\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { LogLevel } from '../../index';\nimport { MessageLoggedEvent } from '@sam-js-src/core/SAMCoreEvents';\nimport type { EventEmitter } from 'events';\n\nclass Logger {\n    static _loggerInstance: Logger;\n\n    private _eventEmitter?: EventEmitter;\n\n    static get instance(): Logger {\n        if (!Logger._loggerInstance) {\n            Logger._loggerInstance = new Logger();\n        }\n        return Logger._loggerInstance;\n    }\n\n    public setEventEmitter(eventEmitter: EventEmitter) {\n        this._eventEmitter = eventEmitter;\n    }\n\n    private _loggerEvent(message: string, level: LogLevel) {\n        this._eventEmitter?.emit('messageLogged', new MessageLoggedEvent(`[SAMJS LibraryContents] ${message}`, level));\n    }\n\n    log(message: string) {\n        this._loggerEvent(message, LogLevel.Info);\n    }\n\n    warn(message: string) {\n        this._loggerEvent(message, LogLevel.Warn);\n    }\n\n    error(message: string) {\n        this._loggerEvent(message, LogLevel.Err);\n    }\n\n    info(message: string) {\n        this._loggerEvent(message, LogLevel.Info);\n    }\n\n    debug(message: string) {\n        this._loggerEvent(message, LogLevel.Debug);\n    }\n}\n\nexport default Logger.instance;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport BaseError from '../errors/BaseError';\nimport type { UserData } from '../models/data/ConfigurationData';\n\nexport function sleep(time: number, signal?: AbortSignal) {\n    return new Promise<void>((resolve, reject) => {\n        const doReject = () => {\n            clearTimeout(timeout);\n            signal?.removeEventListener('abort', doReject);\n            reject(new DOMException('Request aborted', 'AbortError'));\n        };\n\n        const timeout = setTimeout(() => {\n            signal?.removeEventListener('abort', doReject);\n            resolve();\n        }, time);\n\n        if (signal) {\n            signal.addEventListener('abort', doReject);\n\n            // Signal might already have been aborted\n            if (signal.aborted) {\n                doReject();\n            }\n        }\n    });\n}\n\nfunction isUpperSnakeCase(value: string): boolean {\n    return /^[A-Z_]*$/.test(value);\n}\n\nexport function toLowerCamel(value: string): string {\n    if (!isUpperSnakeCase(value)) {\n        throw new BaseError('String must be upper snake case to convert');\n    }\n\n    return value.toLowerCase().replace(/_([a-z])/g, (match, backReference) => {\n        return backReference.toUpperCase();\n    });\n}\n\nexport function debounceDecorator(wait: number) {\n    let timeoutId: any;\n\n    return function _debounceDecorator(target: any, key: string, descriptor: PropertyDescriptor) {\n        const method = descriptor.value;\n        descriptor.value = function debouncedMethod(...args: Array<any>) {\n            clearTimeout(timeoutId);\n            timeoutId = setTimeout(() => method.apply(this, args), wait);\n        };\n    };\n}\n\nexport function getScopedStorageKey(user: UserData['user'], mode: 'local' | 'cloud') {\n    return `CCLibraries_${user?.id}_${mode}`;\n}\n\nexport enum SignalType {\n    RESOLVE,\n    REJECT\n}\nexport function timoutFutureFactory(signal: SignalType, timeout: number) {\n    let timeoutId: any;\n\n    const future = new Promise<void>((...args) => {\n        timeoutId = setTimeout(args[signal], timeout);\n    });\n\n    return { future, cancel: () => clearTimeout(timeoutId) };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ConfigurationData } from './data/ConfigurationData';\n\nexport default class Configuration {\n    constructor(private data: ConfigurationData) {}\n    get config() {\n        return this.data.config;\n    }\n    get user() {\n        return this.data.user;\n    }\n    get ignoreRenditionGrids() {\n        return this.data.ignoreRenditionGrids;\n    }\n    get installedApps() {\n        return this.data.installedApps || [];\n    }\n    get processInfo() {\n        return this.data.processInfo;\n    }\n    get environment() {\n        return this.data.environment;\n    }\n    get renditionSize() {\n        return this.data.config.RENDITION_SIZES;\n    }\n    get fullRenditionConfig() {\n        return this.data.config.FULL_RENDITION_CONFIG;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport default class BaseError extends Error {\n    constructor(message: string) {\n        super(message);\n        // JS Errors break the prototype chain.\n        // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n        Object.setPrototypeOf(this, new.target.prototype);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport const combineSignals = (...signals: AbortSignal[]) => {\n    const controller = new AbortController();\n    const onAbort = () => {\n        controller.abort();\n        signals.forEach(signal => signal.removeEventListener('abort', onAbort));\n    };\n    if (signals.some(signal => signal.aborted)) {\n        onAbort();\n    } else {\n        signals.forEach(signal => signal.addEventListener('abort', onAbort));\n    }\n    return controller.signal;\n};\n\nclass AbortSignalReasons {\n    private signalToReasonMap = new WeakMap<AbortSignal>();\n\n    private getSignal(aborter: AbortSignal | AbortController): AbortSignal {\n        return (aborter as any).signal ?? aborter;\n    }\n\n    reason(aborter: AbortSignal | AbortController) {\n        return this.signalToReasonMap.get(this.getSignal(aborter));\n    }\n\n    give(aborter: AbortSignal | AbortController, reason: any) {\n        this.signalToReasonMap.set(this.getSignal(aborter), reason);\n    }\n}\n\nexport const abortSignalReasons = new AbortSignalReasons();\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Driver\n * The abstraction layer for communicating via REST APIs (either to Melville or the Process).\n * @packageDocumentation\n * @module Driver\n * @internal\n */\n\nimport type { ElementData } from '../models/data/ElementData';\nimport type { GroupData } from '../models/data/GroupData';\nimport type { LibraryData, Role } from '../models/data/LibraryData';\nimport type { ConfigData } from '../models/data/ConfigurationData';\nimport type { GradientData, TeamData } from '../models/Team';\nimport type Team from '../models/Team';\nimport type { Action } from '../models/Action';\nimport type AsyncResponse from './AsyncResponse';\nimport type ApplicationAction from '../models/ApplicationAction';\nimport type Representation from '../models/Representation';\nimport type { SyncStateNotification } from '../models/SyncStatus';\n\nimport RestrictedEventEmitter from '../models/utils/RestrictedEventEmitter';\nimport type Element from '../models/Element';\n// @ts-expect-error R-TODO\nimport type Library from '../models/Library';\nimport type Operation from './Operation';\nimport { connectorTimeout, backoffIntervals } from '../config/constants';\nimport Logger from '../utils/Logger';\nimport Configuration from '../models/Configuration';\nimport LibraryError from '../errors/LibraryError';\nimport { SignalType, sleep, timoutFutureFactory } from '../utils';\nimport { combineSignals } from '../utils/SignalUtils';\nimport type { RenditionSize } from '../types';\nimport promiseCache from '../utils/PromiseCache';\nimport type { StorageInterface } from './utils/StorageInterface';\nimport type { CollaboratorData } from '../models/data/CollaboratorData';\nimport type { ISAMObject } from '../../core/ISAMObject';\nimport type ISAMCorePrivate from '../../core/ISAMCorePrivate';\nimport type { ElementsResponse } from './CloudDriver/utils/melvilleModelMappers';\n// import { IndexKey } from '../models/ModelCache';\n\nexport type PaginatedResponse<T> = T[];\nexport type Folder = number;\nexport type SearchRequest = number;\nexport type StockSearchRequest = number;\nexport type StockAsset = number;\nexport type SyncStatus = number;\n\nexport type DriverOptions = {\n    enableBrandLifecycleManagement?: boolean;\n    readOnly?: boolean;\n    retryCount?: number;\n    skipConnectingOnInit?: boolean;\n    includeApprovedBrandsInLibraries?: boolean;\n};\n\nexport type SearchFilters = {\n    elements_only?: boolean;\n    library_id?: string;\n    element_types?: string[];\n};\n\nexport type ElementSort = {\n    sectionType?: 'group' | 'type';\n    sections?: string[];\n    field: 'name' | 'modifiedDate';\n    direction: 'ascending' | 'descending';\n};\n\nexport type GetElementsOptions = {\n    types: ('elements' | 'removedElements' | 'documentationElements')[];\n    sort?: ElementSort;\n    abortController?: AbortController;\n    etag?: string;\n    loadProgressively?: boolean; // Should only load progressively if the elements have not already been loaded/restored and areElementsLoaded is false\n};\n\nexport type OperationClass<T> = { supportsAction: (action: Action) => boolean } & (new (\n    driver: T,\n    library: Library\n) => Operation<T>);\n\nexport type GetLibraryOptions = {\n    etag?: string;\n    firstElementsLoad?: boolean;\n    elementParams?: GetElementsOptions;\n    getRenditionGrid?: boolean;\n    getAppMetadata?: boolean;\n    optimisticFetch?: boolean;\n    locallyManaged?: boolean;\n};\n\nexport enum ConnectionState {\n    CONNECTED = 'connected',\n    CONNECTING = 'connecting',\n    LOADING = 'loading',\n    ERROR = 'error'\n}\n\n/**\n * The supported filter values to use when fetching libraries.\n * Matches Melville's API\n * @see https://git.corp.adobe.com/pages/Stormcloud/apidocs/?urls.primaryName=melville#/Libraries/getLibraries\n */\ntype LibrarySelectors = 'default' | 'details' | 'collaboration' | 'groups' | 'rendition_grid' | 'app_metadata';\ntype LibraryOwnership = 'all' | 'private' | 'incoming' | 'public' | 'other';\ntype TeamFilter = 'all' | 'none' | 'other' | TeamData['id'];\ntype LibraryCapabilities = 'write';\ntype RolesFilter = 'none' | Role['type'];\ntype ToolkitFilter = 'all' | 'none' | string;\ntype ItemFilter = 'allBrands' | 'allEditableBrands' | 'publishedBrands';\nexport type LibraryListFilters = {\n    owner?: LibraryOwnership[];\n    team?: TeamFilter[];\n    roles?: RolesFilter[];\n    toolkit?: ToolkitFilter[];\n    selector?: LibrarySelectors[];\n    capabilities?: LibraryCapabilities[];\n    workspace?: string;\n    start?: number;\n    limit?: number;\n    itemFilter?: ItemFilter[];\n};\n\nexport type ConnectorParam<T> = (abortSignal?: AbortSignal) => Promise<void | T>;\n\nexport type FetchRequestInit = RequestInit & { headers?: { [s: string]: string } };\n\nasync function collectAll<T>(iterator: AsyncIterable<T[]>) {\n    const all: T[] = [];\n\n    for await (const page of iterator) {\n        all.push(...page);\n    }\n\n    return all;\n}\n\n/**\n * Interface for an API driver for use in the CC Libraries orchestration API.\n */\nexport default abstract class Driver<T = {}, U extends DriverOptions = DriverOptions> extends RestrictedEventEmitter implements ISAMObject {\n    private _connectionPromise?: Promise<void>;\n    private _isConnected = false;\n    _failedConnectionAttempt = false;\n    protected _options: U = {} as U;\n    protected _localStorage?: StorageInterface;\n    protected _abortController?: AbortController;\n    protected _operationTypes?: OperationClass<any>[];\n    protected _config = new Configuration({ config: {}, environment: 'production' });\n    protected _cachedFetch = promiseCache(fetch);\n    protected _token?: string;\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    public _core: ISAMCorePrivate;\n\n    _loadElementsAbortController = new AbortController();\n\n    constructor(core: ISAMCorePrivate, protected _connector: ConnectorParam<T>) {\n        super();\n        this._core = core;\n    }\n\n    get config() {\n        return this._config;\n    }\n\n    get environment() {\n        return this._config.environment;\n    }\n\n    get token() {\n        return this._token;\n    }\n\n    get isConnected() {\n        return this._isConnected;\n    }\n\n    get connectionState() {\n        if (this._failedConnectionAttempt) {return ConnectionState.ERROR;}\n        if (this.isConnected) {return ConnectionState.CONNECTED;}\n        if (this._connectionPromise) {return ConnectionState.CONNECTING;}\n        return ConnectionState.LOADING;\n    }\n\n    resetAbortController() {\n        this._abortController = new AbortController();\n    }\n\n    /**\n     * @internal\n     */\n    get abortController() {\n        return this._abortController;\n    }\n\n    init(\n        options: U = {} as U,\n        onConnect: (driver: this) => void = () => undefined,\n        onDisconnect: () => void = () => undefined\n    ) {\n        this._options = { ...this._options, ...options };\n        this.on('connect', onConnect);\n        this.on('disconnect', onDisconnect);\n        if (this._options.skipConnectingOnInit) {\n            return Promise.resolve();\n        }\n        return this.connect();\n    }\n\n    private get _isConnectingOrConnected() {\n        return Boolean(this._abortController && !this._abortController.signal.aborted);\n    }\n\n    connect() {\n        if (this._isConnectingOrConnected) {\n            return this._connectionPromise;\n        }\n\n        this.resetAbortController();\n        this._connectionPromise = this._connect();\n        this.emit('connecting');\n\n        return this._connectionPromise;\n    }\n\n    //TODO: restructure this to use promises correctly after unit tests are in place\n    //https://jira.corp.adobe.com/browse/SHARED-4386\n    private async _attemptToConnect(abortSignal?: AbortSignal): Promise<boolean> {\n        const fn = async (resolve: (value: (boolean | PromiseLike<boolean>)) => void) => {\n            try {\n                // forcibly reject a timeout. This way we ensure we always catch and resolve a negative value.\n                const { future, cancel } = timoutFutureFactory(SignalType.REJECT, connectorTimeout);\n\n                // race between the connector getting the information we require and the rejecting timeout above.\n                const abortController = new AbortController();\n                const connectionInfo = (await Promise.race([ this._connector(abortController.signal), future ]).finally(\n                    () => {\n                        abortController.abort();\n                        cancel();\n                    }\n                )) as T;\n\n                // have we aborted in the time we have asked for connection information?\n                if (abortSignal?.aborted) {\n                    return resolve(false);\n                }\n\n                // subclass connection handlers (can also throw)\n                await this._handleConnected(connectionInfo);\n\n                // if we got here we can claim to be connected and resolve truthy\n                this._isConnected = true;\n                return resolve(true);\n            } catch (e) {\n                return resolve(false);\n            }\n        };\n\n        return new Promise<boolean>(resolve => fn(resolve)).then(state => {\n            this._failedConnectionAttempt = !state;\n            if (this._failedConnectionAttempt) {this.emit('failedConnection');}\n            return state;\n        });\n    }\n\n    private async _connect() {\n        const currentAbortSignal = this._abortController?.signal;\n\n        for (let i = 0; !(await this._attemptToConnect(currentAbortSignal)); i += 1) {\n            if (this._options.retryCount !== undefined && this._options.retryCount <= i) {\n                Logger.log(`[DRIVER] Failed to connect to server (Attempt: ${i}). Exceeded max retries.`);\n                return;\n            }\n\n            const interval = backoffIntervals[Math.min(i, backoffIntervals.length - 1)] * 1000;\n            Logger.log(`[DRIVER] Failed to connect to server (Attempt: ${i}). Will retry in ${interval}ms.`);\n\n            try {\n                await sleep(interval, currentAbortSignal);\n            } catch (error) {\n                if (error instanceof Error && error.name === 'AbortError') {\n                    return;\n                }\n\n                throw error;\n            }\n        }\n        this.emit('connect', this);\n    }\n\n    protected abstract _handleConnected(data: T): Promise<void>;\n    protected abstract _handleDisconnected(): void;\n\n    disconnect() {\n        this._abortController?.abort();\n        this._isConnected = false;\n        this._failedConnectionAttempt = false;\n        this._handleDisconnected?.();\n        this.emit('disconnect', this);\n    }\n\n    async reconnect() {\n        Logger.warn('Process restart. Attempting to reconnect');\n        this.disconnect();\n        await this.connect();\n    }\n\n    sleep(time: number, signal?: AbortSignal) {\n        return sleep(\n            time,\n            signal && this._abortController?.signal\n                ? combineSignals(signal, this._abortController.signal)\n                : this._abortController?.signal\n        );\n    }\n\n    abstract fetchAccessToken(userId: string, clientId: string, clientSecret: string, scopes: string): any;\n\n    /**\n     * Loads a page of libraries and optionally rendition grids\n     */\n    abstract getLibraries(\n        signal?: AbortSignal,\n        getRenditionGrids?: boolean\n    ): AsyncGenerator<PaginatedResponse<LibraryData>>;\n\n    abstract getLibrariesList(\n        signal?: AbortSignal,\n        filters?: LibraryListFilters\n    ): AsyncGenerator<PaginatedResponse<LibraryData>>;\n\n    abstract getLibrariesPage(\n        signal?: AbortSignal,\n        filters?: LibraryListFilters\n    ): AsyncGenerator<PaginatedResponse<LibraryData>>;\n\n    getAllLibraries(signal?: AbortSignal, getRenditionGrids?: boolean): Promise<LibraryData[]> {\n        return collectAll(this.getLibraries(signal, getRenditionGrids));\n    }\n\n    /**\n     * Loads a single library.\n     * @param library     The existing library object\n     */\n    abstract getLibrary(library: Library, options?: GetLibraryOptions): AsyncGenerator<Partial<LibraryData>>;\n\n    abstract getLibraryById(idOrAssetId: string, options?: GetLibraryOptions): Promise<LibraryData>;\n\n    /**\n     * Moves a library.\n     * @param libraryId     The ID of the library to be moved\n     * @param folderId      The ID of the folder to which the library will be moved\n     */\n    abstract moveLibrary(libraryId: string, folderId: string, organizationId?: string): Promise<LibraryData | void>;\n\n    /**\n     * Returns a generator that yields a page of Elements.\n     * Note: On CloudDriver, it will fetch *all pages* up front and then yield each page.\n     * Recommendation is to use getElementPage instead moving forward.\n     * @params libraryId    The ID of the parent library\n     */\n    abstract getElements(\n        library: Library,\n        sort?: ElementSort,\n        etag?: string,\n        limit?: number,\n        signal?: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>>;\n\n    /**\n     * Fetches a single page of elements and returns a promise resolving to that page.\n     * Note: Does not manipulate the response in any way. Receiver should map the data as needed.\n     * @params library    The parent library\n     */\n    abstract getElementsPage(\n        library: Library,\n        start?: number,\n        limit?: number,\n        sort?: ElementSort,\n        etag?: string\n    ): Promise<ElementsResponse>;\n\n    /**\n     * Fetches all elements pages and returns a promise resolving to the full array of elements\n     */\n    getAllElements(library: Library, sort?: ElementSort, etag?: string): Promise<ElementData[]> {\n        return collectAll(this.getElements(library, sort, etag));\n    }\n\n    abstract getRepresentationContent(representation: Representation): Promise<Response>;\n\n    /**\n     * Loads a page of elements.\n     * @params libraryId    The ID of the parent library\n     */\n    abstract getSearchResults(\n        searchQuery: string,\n        filters: SearchFilters,\n        elementSort: ElementSort,\n        signal: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>>;\n\n    /**\n     * Loads a page of documentation elements.\n     * @params libraryId    The ID of the parent library\n     */\n    abstract getDocumentationElements(\n        library: Library,\n        sort?: ElementSort,\n        etag?: string,\n        limit?: number\n    ): AsyncGenerator<PaginatedResponse<ElementData>>;\n\n    getAllDocumentationElements(library: Library, sort?: ElementSort, etag?: string): Promise<ElementData[]> {\n        return collectAll(this.getDocumentationElements(library, sort, etag));\n    }\n\n    /**\n     * Loads a page of removed elements.\n     * @params libraryId    The ID of the parent library\n     */\n    abstract getRemovedElements(\n        library: Library,\n        sort?: ElementSort,\n        etag?: string,\n        limit?: number\n    ): AsyncGenerator<PaginatedResponse<ElementData>>;\n\n    getAllRemovedElements(library: Library, sort?: ElementSort, etag?: string): Promise<ElementData[]> {\n        return collectAll(this.getRemovedElements(library, sort, etag));\n    }\n\n    /**\n     * Loads a single element.\n     * @param libraryId     The ID of the parent library\n     * @param elementId     The ID of the element to load\n     */\n    abstract getElement(library: Library, elementId: string): Promise<ElementData>;\n\n    abstract getGroups(libraryId: string): AsyncGenerator<PaginatedResponse<GroupData>>;\n\n    getAllGroups(libraryId: string): Promise<GroupData[]> {\n        return collectAll(this.getGroups(libraryId));\n    }\n\n    abstract getTeams(): Promise<TeamData[]>;\n\n    abstract getProjects(): Promise<TeamData[]>;\n\n    abstract getProjectGradient(project: Team): Promise<GradientData | undefined>;\n\n    abstract getRenditionUrl(element: Element, size: RenditionSize): string;\n\n    abstract getAuthenticatedThumbnailURL(element: Element, size: RenditionSize): Promise<string>;\n\n    /**\n     * Get the path to a rendition on disk.\n     * @param libraryId\n     * @param elementId\n     * @param size\n     */\n    abstract getRenditionPath(libraryId: string, elementId: string, size: RenditionSize): Promise<string>;\n\n    abstract getRendition(element: Element, size: RenditionSize): Promise<Response>;\n\n    abstract followLibrary(assetId: string, libraryId: string): Promise<void>;\n\n    abstract importLibrary(\n        file: string | File,\n        callback: (error?: Error, libraryData?: LibraryData) => unknown\n    ): AsyncResponse<any>;\n\n    abstract exportLibrary(library: Library, path?: string, callback?: (error?: Error) => unknown): AsyncResponse<any>;\n\n    publishBrand(_brand: Library): Promise<Response> {\n        throw new LibraryError('NOT_IMPLEMENTED', 'Driver.publishBrand is not implemented.');\n    }\n\n    unpublishBrand(_brand: Library): Promise<Response> {\n        throw new LibraryError('NOT_IMPLEMENTED', 'Driver.unpublishBrand is not implemented.');\n    }\n\n    // Start watching the given `libraries` for changes, calling `callback` with the ids of any changed libraries.\n    // By default it's assumed that the driver implementation calls the callback with library ids, but if passing in\n    // asset ids (e.g. as we get from the cloud driver via ONS) it can be called with index = 'assetId'.\n    abstract setLibraryChangeListener(\n        libraries: LibraryData[],\n        callback: (ids: string[], index?: any) => any\n    ): void;\n\n    setRenditionCacheChangeListener(_cb: (element: ElementData) => void) {\n        return;\n    }\n\n    // Add a library to the list of assets being watched for changes.\n    addWatchedLibrary(_library: LibraryData): void {\n        return;\n    }\n\n    // Remove a library from the list of assets being watched for changes.\n    removeWatchedLibrary(_library: LibraryData): void {\n        return;\n    }\n\n    addLibrariesSyncGroupListener(_cb: () => void): void {\n        return;\n    }\n    removeLibrariesSyncGroupListener(): void {\n        return;\n    }\n\n    // In LocalDriver mode there are two levels of sync state:\n    // 1. In Browser\n    // 2. In Process\n    //\n    // This API is used to detect the process sync state.\n    abstract setSyncStateListener(callback: (state: SyncStateNotification) => void): void;\n    // This API is used to detect any process system font data changes\n    abstract setFontDataChangeListener(callback: () => void): void;\n\n    abstract removeLibraryChangeListener(): void;\n    abstract removeSyncStateListener(): void;\n    abstract removeFontDataChangeListeners(): void;\n\n    operationFactory(Op: OperationClass<Driver>, driver: Driver, library: Library): Operation<Driver> {\n        return new Op(driver, library);\n    }\n\n    getOperationTypes(_library: Library) {\n        return this._operationTypes;\n    }\n\n    /**\n     * From an array of actions, form an atomic operation\n     * @param actions\n     */\n    constructOperation(library: Library): Operation<Driver> | undefined {\n        if (library.actions.length === 0) {\n            return undefined;\n        }\n\n        // If the driver is set as readOnly, don't allow any operations to be registered\n        if (this._options.readOnly) {\n            throw new LibraryError('NOT_ALLOWED', 'Cannot perform write action -- in read-only mode.');\n        }\n\n        const Op = this.getOperationTypes(library)?.find(klass => klass.supportsAction(library.actions[0]));\n\n        if (!Op) {\n            // If the action cannot be mapped to an operation, we have a problem.\n            // TODO: Error\n            throw new Error();\n        }\n\n        const operation = this.operationFactory(Op, this as Driver, library);\n\n        for (const action of library.actions) {\n            if (!operation.addAction(action)) {\n                break;\n            }\n        }\n\n        return operation;\n    }\n\n    abstract fetch(path: string, init?: RequestInit): Promise<Response>;\n\n    abstract getConfiguration(): Promise<Configuration>;\n\n    abstract sendAction(applicationAction: ApplicationAction): Promise<Response>;\n\n    abstract openInCCD(path: string): Promise<Response>;\n\n    protected getLocalSettings(): ConfigData {\n        const settings = this._localStorage ?? new Map();\n        return { config: Object.fromEntries(settings.entries()) };\n    }\n\n    abstract setLocalSetting(key: string, value: any): Promise<void>;\n\n    abstract getLocalSetting(key: string): any;\n\n    abstract getInstalledVersion(appCode: string): any;\n\n    abstract copyFile(source: string, destination: string, allowOverride?: boolean): Promise<string>;\n\n    abstract getFileSize(path: string): Promise<string>;\n\n    abstract getRenditionGrid(library: Library): Object | undefined;\n\n    abstract stageRepresentationForCommit(library: Library, file: File, type?: string): Promise<string>;\n\n    abstract getTempDir(library: Library): Promise<string>;\n\n    abstract abortOperation(operationId: string): Promise<Response>;\n\n    /**\n     * Loads a page of collaborators.\n     * @param assetId The library's asset ID.\n     */\n    abstract getCollaborators(assetId: string): Promise<CollaboratorData[]>;\n\n    /**\n     * should return whether driver should ignore local syncChanges for sync Status Calculation\n     */\n    abstract ignoreLocalSyncEvents(): boolean;\n}\n","/**\n * Utility that short term caches promises based on the provided arguments to produce\n * the promise from a factory function.\n *\n * @export\n * @param {(...args: Array<any>) => Promise<any>} _asyncFn Promise delivering function that we wish to cache using parameters as key\n * @returns {Promise<any>} Cached or fresh promise based on provided arguments\n */\nexport default function promiseCache(_asyncFn: (...args: Array<any>) => Promise<any>) {\n    const _cache = new Map<string, Promise<any>>();\n    return (...args: Array<any>) => {\n        const serializedArgs = JSON.stringify(args);\n        const cachedPromise = _cache.get(serializedArgs);\n        if (cachedPromise) {return cachedPromise;}\n\n        const newPromise = _asyncFn.apply(undefined, args);\n        _cache.set(serializedArgs, newPromise);\n        setTimeout(() => newPromise.finally(() => _cache.delete(serializedArgs)));\n        return newPromise;\n    };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport RestrictedEventEmitter from '../models/utils/RestrictedEventEmitter';\n\nexport default abstract class AsyncOperation extends RestrictedEventEmitter {\n    protected _abortController = new AbortController();\n    protected _isComplete = false;\n    protected _progress = 0;\n\n    abort() {\n        this.DANGEROUS.removeAllListeners();\n        this._abortController.abort();\n    }\n\n    get isComplete() {\n        return this.progress === 100;\n    }\n\n    get progress() {\n        return this._progress;\n    }\n\n    set progress(progress) {\n        this._progress = Math.min(progress, 100);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport { SAM } from '@ccx-public/component-types';\nimport Logger from '../utils/Logger';\nimport { SAMError } from '@sam-js-src/core/SAMError';\n\ntype Code =\n    | 'UNAUTHORIZED'\n    | 'INVALID_CREDENTIALS'\n    | 'REQUEST_TIMEOUT'\n    | 'PRECONDITION_FAILED'\n    | 'GENERIC_ERROR'\n    | 'UNEXPECTED_RESPONSE'\n    | 'MALFORMED_RESPONSE'\n    | 'NOT_MODIFIED'\n    | 'OUT_OF_SPACE'\n    | 'NOT_FOUND'\n    | 'FS_ERROR'\n    | 'ENOENT'\n    | 'INVALID_DATA';\n\nfunction ConvertErrorCode(requestErrorCode: Code): SAM.SAMErrorCode {\n    switch (requestErrorCode) {\n    case 'UNAUTHORIZED':\n    case 'INVALID_CREDENTIALS':\n        return SAM.SAMErrorCode.AUTHORIZATION_ERROR;\n    case 'REQUEST_TIMEOUT':\n        return SAM.SAMErrorCode.REQUEST_TIMED_OUT;\n    case 'OUT_OF_SPACE':\n        return SAM.SAMErrorCode.FULL_LOCAL_DISK_SPACE;\n    case 'NOT_FOUND':\n    case 'ENOENT':\n        return SAM.SAMErrorCode.NOT_FOUND;\n    case 'PRECONDITION_FAILED':\n    case 'GENERIC_ERROR':\n    case 'UNEXPECTED_RESPONSE':\n    case 'MALFORMED_RESPONSE':\n    case 'NOT_MODIFIED':\n    case 'FS_ERROR':\n    case 'INVALID_DATA':\n    default:\n        return SAM.SAMErrorCode.UNKNOWN;\n    }\n}\n\nexport default class RequestError extends SAMError {\n    private _requestErrorCode: Code;\n    private _response?: Response;\n\n    static isRequestError(error: Error): error is RequestError {\n        return !!(error as RequestError).code;\n    }\n\n    constructor(code: Code, message: string, response?: Response, underlyingError?: Error) {\n        super(ConvertErrorCode(code), message, { underlyingError });\n        this._requestErrorCode = code;\n        this._response = response;\n    }\n\n    get requestErrorCode() {\n        return this._requestErrorCode;\n    }\n\n    get response() {\n        return this._response;\n    }\n\n    get underlyingError() {\n        return this._additionalInfo.underlyingError as Error;\n    }\n\n    set underlyingError(error: Error) {\n        this._additionalInfo.underlyingError = error;\n    }\n\n    setResponse(response: Response) {\n        if (!this.response) {\n            this._response = response;\n        } else {\n            Logger.warn('Request Error response reference is already set.');\n        }\n\n        return this;\n    }\n}\n\nexport function getRequestError(response: Response, errorCode?: String) {\n    return getRequestErrorFromStatus(response?.status, errorCode as Code).setResponse(response);\n}\n\nexport function getRequestErrorFromStatus(statusCode: number, errorCode?: Code) {\n    switch (statusCode) {\n    case 304:\n        return new RequestError('NOT_MODIFIED', 'Response has not changed.');\n    case 401:\n        return new RequestError('UNAUTHORIZED', 'Token expired or invalid');\n    case 403:\n        return new RequestError('INVALID_CREDENTIALS', 'You do not have access to this resource.');\n    case 404:\n        return new RequestError(errorCode === 'ENOENT' ? errorCode : 'NOT_FOUND', 'Resource not found');\n    case 408:\n        return new RequestError('REQUEST_TIMEOUT', 'Server could not respond in a timely manner');\n    case 412:\n        return new RequestError('PRECONDITION_FAILED', 'This resource does not match the requisite conditions.');\n    case 422:\n        return new RequestError('INVALID_DATA', 'Library is corrupt, unzipping failed.');\n    case 507:\n        return new RequestError('OUT_OF_SPACE', 'Hard disk ran out of space.');\n    default:\n        return new RequestError('GENERIC_ERROR', `Something went wrong: ${statusCode}`);\n    }\n}\n\nexport function getSAMRequestError(error: SAMError) {\n    const err = getRequestError(error._additionalInfo.response as Response);\n    err.underlyingError = error;\n    return err;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { HttpStatus } from '../config/constants';\nimport LibraryError from '../errors/LibraryError';\n\n/**\n * Implements the Response structure used as a return value for\n * the `parseAsyncResponse` method below.\n *\n * The class only supports json() and text(), we should not require more than\n * text encoding for the APIs that support Async requests.\n */\nclass AsyncResponse implements Response {\n    constructor(\n        readonly url: string,\n        readonly headers: Headers,\n        readonly status: number,\n        readonly statusText: string,\n        private _text: string\n    ) {}\n\n    get ok(): boolean {\n        const { status } = this;\n        return status >= HttpStatus.OK && status < HttpStatus.MULTIPLE_CHOICES;\n    }\n\n    get redirected(): boolean {\n        return false;\n    }\n\n    get type(): ResponseType {\n        return 'basic';\n    }\n\n    async json(): Promise<any> {\n        try {\n            return JSON.parse(this._text);\n        } catch (err: any) {\n            throw new LibraryError(\n                'INVALID_DATA',\n                `Failed to parse JSON response from '${this.url}' async request.`,\n                undefined,\n                err\n            );\n        }\n    }\n\n    async text(): Promise<string> {\n        return this._text;\n    }\n\n    get trailer(): Promise<Headers> {\n        throw new LibraryError('NOT_IMPLEMENTED', 'AsyncResponse.trailer not implemented.');\n    }\n\n    clone(): Response {\n        const clonedHeaders = new Headers();\n        this.headers.forEach((value, key) => clonedHeaders.set(key, value));\n        return new AsyncResponse(this.url, clonedHeaders, this.status, this.statusText, this._text);\n    }\n\n    get bodyUsed(): boolean {\n        throw new LibraryError('NOT_IMPLEMENTED', 'AsyncResponse.bodyUsed not implemented.');\n    }\n\n    get body(): ReadableStream<Uint8Array> | null {\n        throw new LibraryError('NOT_IMPLEMENTED', 'AsyncResponse.body not implemented.');\n    }\n\n    async arrayBuffer(): Promise<ArrayBuffer> {\n        throw new LibraryError('NOT_IMPLEMENTED', 'AsyncResponse.arrayBuffer not implemented.');\n    }\n\n    async blob(): Promise<Blob> {\n        throw new LibraryError('NOT_IMPLEMENTED', 'AsyncResponse.blob not implemented.');\n    }\n\n    async formData(): Promise<FormData> {\n        throw new LibraryError('NOT_IMPLEMENTED', 'AsyncResponse.formData not implemented.');\n    }\n}\n\n// https://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.1\n\n// OCTET          = <any 8-bit sequence of data>\n// CHAR           = <any US-ASCII character (octets 0 - 127)>\n// CTL            = <any US-ASCII control character\n//                  (octets 0 - 31) and DEL (127)>\n// SP             = <US-ASCII SP, space (32)>\n// HT             = <US-ASCII HT, horizontal-tab (9)>\n// separators     = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n//                | \",\" | \";\" | \":\" | \"\\\" | <\">\n//                | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n//                | \"{\" | \"}\" | SP | HT\n// token          = 1*<any CHAR except CTLs or separators>\n\n// A header is just a <token>, the char ':' and the value.\nfunction createHeaderRegexp() {\n    const separators = '()<@,;:\"/[]={}';\n\n    // Start from the first character that is accepted by the <token>.\n    let start = 33;\n    const regexp = [ '^([' ];\n\n    for (let i = 34; i <= 127; ++i) {\n        // We know 127 is not accepted, so we use it as a terminator for our regexp segments.\n        // None of the separators are allowed.\n        if (i === 127 || separators.indexOf(String.fromCharCode(i)) !== -1) {\n            regexp.push('\\\\' + start.toString(8));\n            if (start < i - 1) {\n                regexp.push('-\\\\' + (i - 1).toString(8));\n            }\n            start = i + 1;\n        }\n    }\n    regexp.push(']+):(.*)$');\n    return new RegExp(regexp.join(''));\n}\n\nconst END_OF_LINE = '\\n';\nconst CR = '\\r';\nconst headerRegexp = createHeaderRegexp();\nconst statusRegexp = /^[^\\s]+\\s+(\\d+)\\s*(.*)$/;\n\nclass HttpResponseParser {\n    private _index = 0;\n\n    constructor(private _text: string) {}\n\n    readLine(): string | undefined {\n        const { _index, _text } = this;\n\n        // The standard expects lines to end with CRLF by default.\n        // However, it recommends to accept a single LF as well,\n        // just in case some implementations do not implement the\n        // standard correctly.\n        // Async responses only use LF.\n        const endOfLine = _text.indexOf(END_OF_LINE, _index);\n        if (endOfLine === -1) {\n            // We're done.\n            return;\n        }\n        this._index = endOfLine + END_OF_LINE.length;\n\n        let line = _text.slice(_index, endOfLine);\n        if (line.endsWith(CR)) {\n            // If we have the CR just before the LF, then we want to skip it too.\n            line = line.slice(0, -1);\n        }\n        return line;\n    }\n\n    get remainderText(): string {\n        return this._text.slice(this._index);\n    }\n}\n\n/**\n * Implements parsing of the async response body.\n * https://git.corp.adobe.com/pages/caf/api-spec/chapters/advanced/asynchronous_invocation.html\n *\n * The caller should check for status code 202 then call this method to extract the contents\n * of final async result. The actual result is very similar to a nested HTTP reply inside the body\n * of the initial request.\n *\n */\nexport function parseAsyncResponse(originalUrl: string, body: string): Response {\n    if (!body) {\n        throw new LibraryError('INVALID_DATA', 'Invalid async response body.');\n    }\n\n    const parser = new HttpResponseParser(body);\n\n    let status: number;\n    let statusText: string;\n\n    const statusLine = parser.readLine();\n    if (!statusLine) {\n        // throw new SAMError('INVALID_DATA', 'Could not find async response status line.');\n        // TODO: R-API does not return the status line for operations api. Any errors are reported in data section.\n        // When this is fixed, then missing status line should be an error.\n        // https://developers.corp.adobe.com/supplemental-resources/docs/async-invocation.md/#operations-api-exception\n        status = HttpStatus.OK;\n        statusText = '';\n    } else {\n        // The status line has 3 parts separated by spaces.\n        // Example status line: HTTP/1.1 200 Status text\n        const statusMatch = statusLine.match(statusRegexp);\n        if (!statusMatch) {\n            throw new LibraryError('INVALID_DATA', 'Invalid status line for async response.');\n        }\n\n        // The status code is the second element\n        status = parseInt(statusMatch[1], 10);\n        if (!status) {\n            throw new LibraryError('INVALID_DATA', 'Could not find status code for async response.');\n        }\n\n        statusText = statusMatch[2];\n    }\n\n    // Now we extract the headers line by line.\n    const headers: [string, string][] = [];\n    let headerName: string | undefined;\n    let headerLine = parser.readLine();\n    while (headerLine) {\n        const match = headerLine.match(headerRegexp);\n        if (!match) {\n            if (headerName) {\n                // If this is not a token, then we just continue with the value.\n                headers.push([ headerName, headerLine ]);\n            }\n        } else {\n            headerName = match[1];\n            headers.push([ headerName, match[2] ]);\n        }\n\n        headerLine = parser.readLine();\n    }\n\n    // 1. The last `readLine()` call above will actually jump over the empty\n    // line that separates the headers from the data section.\n    // 2. The Headers constructor below takes care of multiple headers with the\n    // same name and concatenates them as necessary.\n    return new AsyncResponse(originalUrl, new Headers(headers), status, statusText, parser.remainderText);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport AsyncOperation from '../utils/AsyncOperation';\nimport RequestError from '../errors/RequestError';\nimport { parseAsyncResponse } from './AsyncResponseParser';\nimport Logger from '../utils/Logger';\nimport { HttpStatus } from '../config/constants';\nimport type Driver from './Driver';\n\n/**\n * AsyncResponse roughly mirrors AdobeLibraryOperation for interop reasons.\n * TODO: Clean this up\n */\nexport default class AsyncResponse<T extends Driver> extends AsyncOperation {\n    _error?: Error;\n    _location?: string;\n\n    constructor(private _driver: T, request: Promise<Response>) {\n        super();\n        this._handleResponse(request);\n    }\n\n    cancel() {\n        this.abort();\n        if (this._location) {\n            this._driver.abortOperation(this._location);\n            this._location = undefined;\n        }\n    }\n\n    get error() {\n        return this._error;\n    }\n\n    private async _handleResponse(request: Promise<Response>): Promise<unknown> {\n        try {\n            const response = await request;\n            if ([ HttpStatus.NO_CONTENT, HttpStatus.OK ].includes(response.status)) {\n                this.progress = 100;\n                let rawBody: string, jsonData, headers: Headers | undefined;\n\n                if (response.status === HttpStatus.OK) {\n                    // Async response completion from melville is raw http. We need to parse it out\n                    // first and we use utility from SAMjs to do this. If there is an error parsing json data\n                    // then we can assume this was a json response from local driver request to process\n                    jsonData = await response\n                        .text()\n                        .then(body => {\n                            rawBody = body;\n                            return parseAsyncResponse('', body);\n                        })\n                        .then(res => {\n                            headers = res.headers;\n                            // Body is either JSON or empty, so if we fail to parse just return undefined\n                            return res.json().catch(() => undefined);\n                        })\n                        .catch(() => JSON.parse(rawBody))\n                        .catch(() => {\n                            Logger.error(`Error parsing async response: ${response}`);\n                        });\n                }\n\n                if (jsonData?.exception_code) {\n                    // Example async error response:\n                    // {\n                    //     exception_code: \"4000\",\n                    //     log_id: \"5390a825-144a-429b-bf7d-9f1ae5b52728\",\n                    //     message: \"unexpected error while copying asset - HttpProblemDetail{type='http://ns.adobe.com/adobecloud/problem/operation_failed', title='Unexpected response code when creating collection: 409 != 201', status=409, detail='null', instance='null', properties='{}'}\",\n                    //     status: 409,\n                    //     type: \"InputValidation\"\n                    // }\n                    throw new RequestError(jsonData.status, jsonData.message, response, jsonData);\n                } else {\n                    this.emit('change', true, jsonData, headers);\n                    this.DANGEROUS.removeAllListeners();\n                    return;\n                }\n            }\n\n            if (response.status === HttpStatus.ACCEPTED) {\n                let json: Record<string, any> = {};\n                try {\n                    json = await response.json();\n                } catch {\n                    // R-API async responses don't have a body.\n                }\n\n                if (json.progress) {\n                    this.progress = json.progress;\n                    this.emit('change');\n                }\n\n                // R-API does not return a location from a monitor request.\n                // Reuse the current location if there is not a location in the response.\n                const newLocation = response.headers.get('location') ?? json.href;\n                if (newLocation) {\n                    this._location = newLocation;\n                }\n\n                const retryAfter = response.headers.get('retry-after')\n                    ? parseInt(response.headers.get('retry-after') as string, 10)\n                    : 1;\n\n                if (!this._location) {\n                    throw new RequestError(\n                        'MALFORMED_RESPONSE',\n                        'Location header is missing from ops monitor response'\n                    );\n                }\n\n                await this._driver.sleep(retryAfter * 1000, this._abortController.signal);\n\n                return this._handleResponse(\n                    this._driver.fetch(this._location, {\n                        signal: this._abortController.signal\n                    })\n                );\n            }\n\n            throw new RequestError('UNEXPECTED_RESPONSE', `Unexpected response from ops monitor: ${response.status}`);\n        } catch (error) {\n            this._error = error as Error;\n            this.progress = 100;\n            this.emit('change', true);\n            this.DANGEROUS.removeAllListeners();\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { ENVIRONMENTS, Env as EnvironmentEnv } from '../../core/Environment';\n\nexport type Env = 'staging' | 'production';\n\ntype Config = {\n    [k in Env]: {\n        hostname: string;\n        invitation_hostname: string;\n        teams_hostname: string;\n        platform_hostname: string;\n    };\n};\n\nconst configData: Readonly<Config> = {\n    staging: {\n        hostname: ENVIRONMENTS[EnvironmentEnv.Stage].MELVILLE_EDGE_HOST,\n        invitation_hostname: 'invitations-stage.adobe.io',\n        teams_hostname: 'ccprojects-stage.adobe.io',\n        platform_hostname: 'platform-cs-stage.adobe.io'\n    },\n    production: {\n        hostname: ENVIRONMENTS[EnvironmentEnv.Production].MELVILLE_EDGE_HOST,\n        invitation_hostname: 'invitations.adobe.io',\n        teams_hostname: 'ccprojects.adobe.io',\n        platform_hostname: 'platform-cs.adobe.io'\n    }\n};\n\nexport default configData;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Operation\n * @packageDocumentation\n * @module Operation\n * @internal\n */\n\nimport type { Action } from '../models/Action';\n// @ts-expect-error R-TODO\nimport type Library from '../models/Library';\nimport LibraryError from '../errors/LibraryError';\nimport Logger from '../utils/Logger';\n\nexport type ExecuteResult = { actions: Action[]; etag?: string; linkedActions?: Action[]; linkedEtag?: string };\n\nexport function validatesOperation<T>(\n    target: Operation<T>,\n    propertyKey: string,\n    propertyDescriptor: PropertyDescriptor\n) {\n    const method = propertyDescriptor.value;\n\n    propertyDescriptor.value = async function (this: Operation<T>, ...args: any[]) {\n        if (this._actions.length === 0) {\n            throw new LibraryError(\n                'NOT_SUPPORTED',\n                'Operation must have at least one action to be executed.',\n                this._library.id\n            );\n        }\n\n        Logger.log(`[OPERATION] Performing ${this._actions.length} actions.`);\n\n        return method.apply(this, args);\n    };\n}\n\n/**\n * An operation is an atomic API request. It contains some number of batchable actions.\n */\nexport default abstract class Operation<T> {\n    /**\n     * Is the action supported by this type of operation?\n     * @param action\n     */\n    static supportsAction(action: Action) {\n        return this.prototype.supportsAction(action);\n    }\n\n    protected _actions: Action[] = [];\n    protected _library: Library;\n    protected _driver: T;\n\n    constructor(driver: T, library: Library) {\n        this._driver = driver;\n        this._library = library;\n    }\n\n    /**\n     * Add an action to the operation, but only if it fits in the operation type.\n     * @param action\n     * @returns Did the operation accept the action?\n     */\n    addAction(action: Action): boolean {\n        if (!this.supportsAction(action)) {\n            return false;\n        }\n\n        this._actions.push(action);\n        return true;\n    }\n\n    /**\n     * Executes the operation. Should make a single request to an API.\n     *\n     * This method is also responsible for converting the action into its final form.\n     * For example, when a library is created, we get the ID. We need to add the ID to\n     * the action before applying it to the base state.\n     */\n    abstract execute(): Promise<ExecuteResult>;\n\n    /**\n     * Is the action supported by this type of operation?\n     * @param action\n     */\n    abstract supportsAction(action: Action): boolean;\n\n    get actions() {\n        return this._actions;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * SingleOperation\n * @packageDocumentation\n * @module SingleOperation\n * @internal\n */\n\nimport type { Action } from '../models/Action';\n\nimport type { ExecuteResult } from './Operation';\nimport Operation, { validatesOperation } from './Operation';\n\n/**\n * SingleOperation\n *\n * An operation that can only contain one action.\n */\nexport default abstract class SingleOperation<T> extends Operation<T> {\n    protected _actionMappers: { [s: string]: (action: Action) => Promise<Action> } = {};\n\n    protected get action() {\n        return this._actions[0];\n    }\n\n    @validatesOperation\n    async execute(): Promise<ExecuteResult> {\n        // TODO: Clean me up\n        const action = await (this._actionMappers as any)[this.action.name || ''](this.action);\n        return { actions: [ action ] };\n    }\n\n    addAction(action: Action) {\n        if (this._actions.length === 1) {\n            return false;\n        }\n\n        return super.addAction(action);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Utils\n * @packageDocumentation\n * @module Utils\n * @internal\n */\n\nimport type { IMSProfileData } from '../../../models/data/IMSTokenData';\nimport type { UserData } from '../../../models/data/ConfigurationData';\n\nconst BYTE_SPLIT_REGEX = /[a-f0-9]{2}/gi;\nconst PLATFORM = 'platform-cs';\nconst PLATFORM_EDGE = `${PLATFORM}-edge`;\nconst PLATFORM_DISCOVERY_ENDPOINTS: Array<string> = [\n    `https://${PLATFORM}.adobe.io/index`,\n    `https://${PLATFORM}-stage.adobe.io/index`\n];\nconst PRIORITY_HEADER = { Priority: 'u=1' };\n\nfunction decodeToken(token: string): IMSProfileData | undefined {\n    const parts = token.split('.');\n\n    if (parts.length !== 3) {\n        return undefined;\n    }\n\n    try {\n        return JSON.parse(atob(parts[1]));\n    } catch (e) {\n        return undefined;\n    }\n}\n\nexport function extractUserDataFromToken(token: string): UserData | undefined {\n    const decoded = decodeToken(token);\n\n    if (decoded) {\n        return {\n            user: {\n                id: decoded.user_id,\n                clientId: decoded.client_id\n            }\n        };\n    }\n    return undefined;\n}\n\nexport function extractExpiryFromToken(token: string): number | undefined {\n    const decoded = decodeToken(token);\n\n    if (decoded) {\n        const elapsed = Date.now() - parseInt(decoded.created_at, 10);\n        return Math.max(parseInt(decoded.expires_in, 10) - elapsed, 0);\n    }\n\n    return undefined;\n}\n\nexport function hexToBase64(input: string): string {\n    // Inspired by https://stackoverflow.com/questions/23190056/hex-to-base64-converter-for-javascript\n    return btoa(String.fromCharCode(...(input.match(BYTE_SPLIT_REGEX) as string[]).map(byte => parseInt(byte, 16))));\n}\n\n/**\n * Utility function to inject use of ACP edge functionality with a\n * default priority of 3 set on optional request headers\n *\n * @export\n * @param {string} url URL client wants to promote to edge request\n * @returns modified edge url if provided url is a platform url and header object with set priority header\n */\nexport function useEdge(url: string): { url: string; headers: Record<string, any> } {\n    // Potential relative paths / url with no domain injected yet...\n    let parsedUri: URL;\n    try {\n        parsedUri = new URL(url);\n    } catch (e) {\n        return { url, headers: {} };\n    }\n\n    // Check if the url passed in is a platform endpoint\n    if (!parsedUri.hostname.includes(PLATFORM)) {\n        return { url, headers: {} };\n    }\n\n    // Check if the url is a discovery endpoint and replace hostname with edge endpoint if it is\n    if (PLATFORM_DISCOVERY_ENDPOINTS.includes(url)) {\n        parsedUri.hostname = parsedUri.hostname.replace(PLATFORM, PLATFORM_EDGE);\n    }\n\n    return { url: parsedUri.href, headers: { ...PRIORITY_HEADER } };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type Representation from '../models/Representation';\nimport type Element from '../models/Element';\n// @ts-expect-error R-TODO\nimport type Library from '../models/Library';\nimport type { RepresentationData } from '../models/data/RepresentationData';\nimport type { RenditionTemplateData } from '../models/data/ElementData';\nimport { canComputeRenditionFromMimeType } from './MimeTypeUtils';\nimport uriTemplates from 'uri-templates';\nimport type { RenditionSize } from '../types';\nimport type { RenditionGrid } from '../models/data/LibraryData';\nimport { useEdge } from '../drivers/CloudDriver/utils';\n\nexport function canComputeRendition(reprensentation: Representation) {\n    return canComputeRenditionFromMimeType(reprensentation.type);\n}\n\nexport function getRenditionCandidate(representations: Array<RepresentationData> = []): RepresentationData {\n    let candidate: RepresentationData | undefined;\n    let candidateSize = 0;\n    for (const representation of representations) {\n        const representationSize = representation.isFullSize\n            ? Number.POSITIVE_INFINITY\n            : Math.max(representation.height || 0, representation.width || 0);\n        const replacementCandidate =\n            !candidate ||\n            (representation.isPreferredThumbnail && !candidate.isPreferredThumbnail) ||\n            (representation.relationship === 'primary' && candidate.relationship !== 'primary') ||\n            (representation.relationship === 'rendition' &&\n                ![ 'primary', 'rendition' ].includes(candidate?.relationship as string)) ||\n            (representation.relationship === 'rendition' &&\n                candidate.relationship === 'rendition' &&\n                representationSize > candidateSize);\n\n        if (replacementCandidate && canComputeRenditionFromMimeType(representation.type)) {\n            candidate = representation;\n            candidateSize = representationSize;\n        }\n    }\n\n    return candidate as RepresentationData;\n}\n\nexport function getRenditionUrl(element: Element, size: RenditionSize = 200): string | undefined {\n    // @ts-expect-error TODO-R[SHARED-3961] element.data no longer exists.\n    const { renditionUrl = {} as RenditionTemplateData } = element.data;\n    const { template, substitutions = {} } =\n        typeof renditionUrl === 'string' ? { template: renditionUrl } : renditionUrl;\n    if (template) {\n        const uriTemplate = uriTemplates(template);\n        const populatedUrl = uriTemplate.fill({ ...substitutions, size: `${size}`, type: 'image/png' });\n\n        // Upgrade provided thumbnail url to ACP Edge (switch on http/2)\n        const { url } = useEdge(populatedUrl);\n        return url;\n    }\n}\n\nfunction getRenditionObject(element: Element) {\n    // Make the renditions look like a Melville response\n    let mapper;\n    switch (element.type) {\n    case 'application/vnd.adobe.element.color+dcx':\n        mapper = (element: Element) => {\n            const data = element.representations\n                .map(representation => representation.getValue('color', 'data'))\n                .find(data => data && data.mode === 'RGB');\n\n            if (!data) {\n                return;\n            }\n\n            return {\n                id: element.elementId,\n                type: 'application/vnd.adobe.element.color+dcx',\n                rendition: {\n                    swatches: [\n                        [\n                            {\n                                alpha: data.alpha,\n                                mode: data.mode,\n                                type: data.type,\n                                value: data.value\n                            }\n                        ]\n                    ]\n                }\n            };\n        };\n        break;\n    case 'application/vnd.adobe.element.colortheme+dcx':\n        mapper = (element: Element) => {\n            const representation = element.getPrimaryRepresentation();\n            return (\n                representation && {\n                    id: element.elementId,\n                    type: 'application/vnd.adobe.element.colortheme+dcx',\n                    rendition: representation.getValue('colortheme', 'data')\n                }\n            );\n        };\n        break;\n    case 'application/vnd.adobe.element.gradient+dcx':\n        mapper = (element: Element) => {\n            const representation = element.getPrimaryRepresentation();\n            return (\n                representation && {\n                    id: element.elementId,\n                    type: 'application/vnd.adobe.element.gradient+dcx',\n                    rendition: representation.getValue('gradient', 'data')\n                }\n            );\n        };\n        break;\n    default:\n        mapper = (element: Element) => {\n            let path: any = getRenditionUrl(element); // cloud driver has a remote url\n            if (!path) {\n                // just hard coding size for now\n                path = element.getThumbnailURL(202); // local driver has a localhost url\n            }\n\n            if (path) {\n                return {\n                    id: element.elementId,\n                    type: 'href',\n                    rendition: path\n                };\n            }\n        };\n    }\n    return mapper(element);\n}\n\n/**\n * Rules:\n *   Main Image:\n *     - first image added to library\n *     - if library has no images, most recently modified of any type in library\n *   Tile Images:\n *      - 3 most recently modified elements of any type\n * @param library\n * @returns {Object} Rendition Grid object\n */\nexport function getRenditionGrid(library: Library) {\n    if (library.elements.length === 0) {\n        return undefined;\n    }\n\n    // We want the first created, but the most recently modified, so the sort orders are opposite.\n    const sortedByModified = [ ...library.elements ].sort((a, b) => b.modified - a.modified);\n    const sortedByCreated = [ ...library.elements ].sort((a, b) => a.created - b.created);\n    let firstImage = sortedByCreated.find(element => {\n        // We only want to display the first Graphic, not just any image\n        if (element.type !== 'application/vnd.adobe.element.image+dcx') {\n            return;\n        }\n        const rendition = getRenditionObject(element);\n        return rendition && rendition.type === 'href';\n    });\n\n    const renditionGrid: RenditionGrid = { gridGenerationEtag: library.etag };\n\n    // Get first image\n    if (firstImage) {\n        renditionGrid.main = getRenditionObject(firstImage);\n    }\n\n    // If there isn't a Graphic element, get first created element of any type\n    for (let i = 0; i < sortedByCreated.length && !renditionGrid.main; i++) {\n        renditionGrid.main = getRenditionObject(sortedByCreated[i]) || undefined;\n        firstImage = renditionGrid.main && sortedByCreated[i];\n    }\n\n    // Get tiles\n    renditionGrid.tiles = [];\n    for (let i = 0; i < sortedByModified.length && renditionGrid.tiles.length < 3; i++) {\n        if (sortedByModified[i] === firstImage) {\n            continue;\n        }\n\n        const renditionObject = getRenditionObject(sortedByModified[i]);\n        if (renditionObject) {\n            renditionGrid.tiles.push(renditionObject);\n        }\n    }\n\n    return renditionGrid;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Utils\n * @packageDocumentation\n * @module Utils\n * @internal\n */\n\nimport type { RepresentationData } from '../../../models/data/RepresentationData';\nimport type { ElementData } from '../../../models/data/ElementData';\nimport type { LibraryData } from '../../../models/data/LibraryData';\nimport type { GroupData } from '../../../models/data/GroupData';\nimport type { VersionData } from '../../../models/data/VersionData';\nimport type { CollaboratorData } from '../../../models/data/CollaboratorData';\nimport uriTemplates from 'uri-templates';\nimport { getRenditionCandidate } from '../../../utils/RenditionUtils';\nimport type { AdobeAsset, AssetVersion, Collaborator } from '../../../../index';\nimport type { BlockDownloadData } from '../../../models/data/BlockDownloadData';\n\nexport type DCXNode = {\n    id: string;\n    children?: DCXNode[];\n    components?: DCXNode[];\n    [s: string]: any;\n};\n\ntype DCXGroupMembershipData = {\n    order: string;\n};\n\nexport type Link = {\n    href: string;\n    rel: string;\n    type: string;\n    templated?: boolean;\n    'repo:maxSingleTransferSize'?: number;\n    'repo:minBlockTransferSize'?: number;\n};\n\nexport enum RapiLinkType {\n    DOWNLOAD = 'http://ns.adobe.com/adobecloud/rel/download',\n    MANIFEST = 'http://ns.adobe.com/adobecloud/rel/manifest',\n    APPLICATION = 'http://ns.adobe.com/adobecloud/rel/metadata/application',\n    EMBEDDED = 'http://ns.adobe.com/adobecloud/rel/metadata/embedded',\n    REPOSITORY = 'http://ns.adobe.com/adobecloud/rel/metadata/repository',\n    PRIMARY = 'http://ns.adobe.com/adobecloud/rel/primary',\n    RENDITION = 'http://ns.adobe.com/adobecloud/rel/rendition',\n    COMPONENT = 'http://ns.adobe.com/adobecloud/rel/component',\n    RESOLVE = 'http://ns.adobe.com/adobecloud/rel/resolve/id',\n    BLOCK_INIT = 'http://ns.adobe.com/adobecloud/rel/block/init',\n    BLOCK_TRANSFER = 'http://ns.adobe.com/adobecloud/rel/block/transfer',\n    BLOCK_FINALIZE = 'http://ns.adobe.com/adobecloud/rel/block/finalize'\n}\n\nexport type BlockDownloadResponse = {\n    href: string;\n    size: number;\n    type: string;\n};\n\nexport type VersionResponse = {\n    created: string;\n    created_by: string;\n    version: string;\n    _links: {\n        [s in RapiLinkType]: Link;\n    };\n};\n\nexport function mapManifestToLibraryData(\n    asset: AdobeAsset,\n    manifest: DCXNode = asset.manifest.data\n): Partial<LibraryData> {\n    const etag = asset.manifest?.etag;\n\n    const elements = getElementsFromDCXNode(\n        asset,\n        manifest.children?.find(node => node.name === 'elements') as DCXNode\n    );\n    const removedElements = getElementsFromDCXNode(\n        asset,\n        manifest.children?.find(node => node.name === 'removed_elements') as DCXNode\n    );\n    const documentationElements = getElementsFromDCXNode(\n        asset,\n        manifest.children?.find(node => node.name === 'documentation_elements') as DCXNode\n    );\n\n    const groupsNode = manifest.children?.find(node => node.name === 'groups');\n    const groups: GroupData[] =\n        groupsNode?.children?.map(node => ({\n            id: node.id,\n            name: node.name,\n            classifier: node['library#classifier'],\n            order: node['library#order'],\n            parentId: node['library#parentId'],\n            sourceRef: node['library#sourceRef'],\n            customData: getCustomDCXData(node)\n        })) || [];\n\n    const libraryData: Partial<LibraryData> = {\n        id: manifest.id,\n        name: manifest.name,\n        etag,\n        localizedNames: manifest['library#localizedName'],\n        toolkitId: manifest['toolkit#id'],\n        documentId: manifest['library#documentId'],\n        documentType: manifest['library#documentType'],\n        createdBy: asset.createdBy,\n        modifiedBy: asset.modifiedBy,\n        createdDate: asset.created.valueOf(),\n        modifiedDate: asset.modified.valueOf(),\n        version: manifest.components && manifest.components[0].version,\n        roles: manifest['library#roles'],\n        description: manifest['library#description'],\n        details: {\n            elementCount: elements.length,\n            documentationElementCount: documentationElements.length,\n            removedElementCount: removedElements.length\n        },\n        groups,\n        elements,\n        documentationElements,\n        removedElements,\n        customData: getCustomDCXData(manifest),\n        isLibraryLoaded: true,\n        areElementsLoaded: true,\n        appMetadata: asset.appMetadata?.data\n        // default: can't get from manifest,\n        // ownership: can't get from manifest,\n        // collaboration: can't get from manifest,\n        // assetId: can't get from manifest,\n        // isWritable: can't get from manifest,\n        // isParentWritable: can't get from manifest,\n        // team: can't get from manifest,\n        // owner: can't get from manifest,\n        // ownerType: can't get from manifest\n    }; // TODO\n\n    if (manifest.components && manifest.components[0].version) {\n        libraryData.version = manifest.components[0].version;\n    }\n\n    return libraryData;\n}\n\nfunction getElementsFromDCXNode(asset: AdobeAsset, node: DCXNode): ElementData[] {\n    if (!node) {\n        return [];\n    }\n\n    return (\n        node.children?.map(element => {\n            const elementData: ElementData = {\n                id: element.id,\n                name: element.name,\n                isAutoNamed: element['library#autoName'],\n                type: element.type,\n                tags: element.tags || [],\n                dependencyIds: element['library#dependencies'] || [],\n                localizedNames: element['library#localizedName'],\n                createdDate: element['library#created'],\n                createdLocally: false,\n                createdContext: element['library#createdData'] || {},\n                modifiedDate: element['library#modified'],\n                modifiedLocally: false,\n                description: element['library#description'],\n                descriptionModifiedLocally: false,\n                removedLocally: false,\n                representations: getRepresentationsFromDCXNode(asset, element),\n                groups: element['library#groups']\n                    ? Object.entries<DCXGroupMembershipData>(element['library#groups']).map(\n                        ([ key, { order } ]: [string, DCXGroupMembershipData]) => {\n                            // example key: $default#3c9fea12-e456-4d3f-b209-d76e52b2e89c\n                            const [ classifier, id ] = key.split('#');\n                            return { id, classifier, order };\n                        }\n                    )\n                    : [],\n                sourceRef: element['library#sourceRef'],\n                roles: element['library#roles'],\n                customData: getCustomDCXData(element)\n            };\n\n            // Attempt to set renditionUrl on elementData if a usable representation exists\n            setRenditionUrl(asset, elementData);\n\n            return elementData;\n        }) || []\n    );\n}\n\nfunction getComponentUrl(asset: AdobeAsset, representation: DCXNode): string {\n    // TODO: Get rendition urls from SAM.js\n    const links = asset.links[RapiLinkType.COMPONENT] as any;\n    const templateString = links?.[0]?.href;\n    const renditionTemplate = templateString && uriTemplates(templateString);\n\n    return renditionTemplate?.fill({ revision: representation.version, component_id: representation.id });\n}\n\nfunction setRenditionUrl(asset: AdobeAsset, element: ElementData) {\n    const links = asset.links[RapiLinkType.RENDITION] as any;\n    const templateString = links?.[0]?.href;\n    const candidate = getRenditionCandidate(element.representations);\n    if (candidate) {\n        element.renditionUrl = {\n            template: templateString,\n            substitutions: {\n                fragment: `id=${candidate.id}`,\n                size: 200\n            }\n        };\n    }\n}\n\nfunction getRepresentationsFromDCXNode(asset: AdobeAsset, node: DCXNode): RepresentationData[] {\n    const components: RepresentationData[] =\n        node.components?.map(component => ({\n            id: component.id,\n            type: component.type,\n            relationship: component.rel,\n            url: getComponentUrl(asset, component),\n            isFullSize: component['library#isFullSize'] || component['library#isfullSize'],\n            isExternalLink: false,\n            width: component.width,\n            height: component.height,\n            contentLength: component.length,\n            isPreferredThumbnail: component['library#isPreferredThumbnail'],\n            customData: getCustomDCXData(component)\n        })) || [];\n\n    const children: RepresentationData[] =\n        node.children?.map(child => ({\n            id: child.id,\n            type: child.type,\n            linktype: child['library#linktype'],\n            relationship: child['library#rel'],\n            isFullSize: false,\n            isExternalLink: false,\n            customData: getCustomDCXData(child)\n        })) || [];\n\n    return [ ...components, ...children ];\n}\n\nexport function getCustomDCXData(node: DCXNode) {\n    const customData: { [s: string]: any } = {};\n\n    for (const [ key, value ] of Object.entries(node)) {\n        const [ namespace, entry ] = key.split('#');\n        if (namespace !== 'library' && entry) {\n            customData[key] = value;\n        }\n    }\n\n    return customData;\n}\n\nexport function mapResponseToBlockDownloadData(blockDownloadResponse: BlockDownloadResponse): BlockDownloadData {\n    return {\n        size: blockDownloadResponse.size,\n        type: blockDownloadResponse.type,\n        url: blockDownloadResponse.href\n    };\n}\n\nexport function mapResponseToVersionData(assetId: string, response: AssetVersion): VersionData {\n    const templateString = response.links?.[RapiLinkType.MANIFEST].href;\n    const manifestTemplate = templateString ? uriTemplates(templateString) : undefined;\n\n    return {\n        id: response.versionId,\n        assetId,\n        createdDate: response.created.getTime(),\n        createdBy: response.createdBy,\n        manifestUrl: manifestTemplate?.fill({}) as string\n    };\n}\n\nexport function mapResponseToCollaboratorData(assetId: string, collaborator: Collaborator): CollaboratorData {\n    return {\n        id: collaborator.collaboratorID,\n        assetId,\n        imsUserId: collaborator.imsUserId,\n        email: collaborator.email,\n        name: collaborator.name,\n        role: collaborator.role,\n        type: collaborator.type,\n        inheritances: collaborator.inheritances,\n        isDirect: collaborator.isDirect,\n        hasContributorRole: collaborator.hasContributorRole,\n        hasName: collaborator.hasName,\n        invited: collaborator.invited,\n        isAdmin: collaborator.isAdmin\n    };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Utils\n * @packageDocumentation\n * @module Utils\n * @internal\n */\n\nimport type { LinkReference } from '../../../../index';\nimport type { ElementMimeType } from '../../../config/constants';\nimport type { RepresentationData } from '../../../models/data/RepresentationData';\nimport type { ElementData, ElementRenditionType, GroupMembershipData } from '../../../models/data/ElementData';\nimport type { LibraryData, OwnershipType, Collaboration, Role } from '../../../models/data/LibraryData';\nimport type { GroupData } from '../../../models/data/GroupData';\nimport type { TeamData } from '../../../models/Team';\nimport type { ClientInfo } from '../../CloudDriver';\n\nimport { melvilleFirstUseEtag } from '../../../config/constants';\nimport { v4 as uuid } from 'uuid';\nimport type { Stringified } from '../../../types';\nimport { getCustomDCXData } from './rapiModelMappers';\n\nconst CC_STORAGE_ID_REGEX = /^[A-Z0-9]{30}$/;\n\ntype Permission = 'ack' | 'read' | 'write' | 'delete';\n\nexport type GroupResponse = {\n    id: string;\n    classifier: string;\n    name: string;\n    order: string;\n    parent_id?: string;\n    localized_names: { [s: string]: string };\n    created_date: number;\n    modified_date: number;\n    sourceRef?: Stringified<LinkReference>; // Only present in published libraries.\n};\n\nexport type GroupMembershipResponse = {\n    id: string;\n    classifier: string;\n    order: string;\n};\n\ntype ElementCreationContextResponse = {\n    app?: string;\n    device?: string;\n    deviceId?: string;\n    time?: number;\n    userId?: string;\n};\n\ntype Link = {\n    href: string;\n    rel: string;\n    type: string;\n    templated?: boolean;\n};\n\ntype MelvilleLinkType =\n    | 'http://ns.adobe.com/melville/rel/primary'\n    | 'http://ns.adobe.com/melville/rel/rendition'\n    | 'http://ns.adobe.com/melville/rel/download';\n\nexport type RepresentationResponse = {\n    id: string;\n    type: string;\n    linktype?: string;\n    children: RepresentationResponse[];\n    relationship: 'primary' | 'rendition';\n    is_external_link?: boolean;\n    is_full_size?: boolean;\n    height?: number;\n    width?: number;\n    content_length?: number;\n    _links?: {\n        [s in MelvilleLinkType]: Link;\n    };\n    [s: string]: any;\n};\n\nexport type SearchElementResponse = {\n    id: string;\n    name: string;\n    manifest_etag: string;\n    type: ElementMimeType;\n    created_date: number;\n    modified_date: number;\n    tags: string[];\n    thumbnail: {\n        type: 'href' | ElementMimeType;\n        elemenType: ElementMimeType;\n        elementId: string;\n        rendition: any;\n    };\n    representations: RepresentationResponse[];\n    groups: GroupMembershipResponse[];\n    roles: Role[];\n    parent_id: string;\n};\n\nexport type SearchElementsResponse = {\n    total_items: number;\n    elements: SearchElementResponse[];\n    _links: {\n        page: Link;\n    };\n};\n\n// from: https://git.corp.adobe.com/Stormcloud/melville/blob/integration/com.adobe.melville.core/src/main/java/com/adobe/melville/db/dto/element/DbLibraryElementRenditionData.java\nexport type Rendition = {\n    type: ElementMimeType | ElementRenditionType | 'href'; // Will be href if the rendition is a link or a specific type (application/vnd.adobe.element.colortheme+dcx)\n    rendition_mimetype?: string;\n    rendition: any; // can be a link or json\n    elementId?: string;\n    elementType?: string;\n};\n\nexport type RenditionGrid = {\n    main?: Rendition;\n    tiles?: Rendition[];\n    _fc?: any;\n};\n\n// Note that this is not an exhaustive list of library response properties.\n// See mocks or melville docs for more details.\n// TODO-R[SHARED-4130]: Replace with SAM.LibraryData. (Maybe rename it to LibraryResponse. And/or rename LibraryData in CCLibs to LibraryModelData.)\nexport type LibraryResponse = {\n    id: string;\n    name: string;\n    asset_acl: {\n        '*'?: Permission[];\n        'http://ns.adobe.com/adobecloud/rel/primary'?: Permission[];\n    };\n    version: string;\n    parent_assetId: string;\n    library_urn: string;\n    workspace_urn?: string;\n    manifest_etag?: string; // This might not be present on older libraries\n    workspace_name?: string;\n    created_date: number;\n    modified_date: number;\n    created_by: string;\n    modified_by: string;\n    elements_count: number;\n    removed_elements_count: number;\n    localized_names: {\n        [s: string]: string;\n    };\n    groups?: GroupResponse[];\n    default: boolean;\n    ownership: OwnershipType;\n    elements?: ElementResponse[];\n    toolkit_id?: string;\n    details?: {\n        manifest_id: string;\n    };\n    document_id?: string;\n    document_type?: string;\n    custom_data?: { [s: string]: any };\n    collaboration?: Collaboration;\n    bookmark?: {\n        id: string;\n    };\n    roles: Role[];\n    description: string;\n    rendition_grid?: RenditionGrid;\n    storage_assignee?: {\n        id: string;\n        type: 'user' | 'org';\n    };\n    application_metadata?: { [s: string]: any };\n};\n\nexport type LibrariesResponse = {\n    libraries: LibraryResponse[];\n};\n\nexport type ElementResponse = {\n    id: string;\n    name: string;\n    manifest_etag?: string; // This might not be present on older libraries\n    is_auto_named: boolean;\n    type: ElementMimeType;\n    created_date: number;\n    modified_date: number;\n    tags: string[];\n    dependency_ids: string[];\n    localized_names: {\n        [s: string]: string;\n    };\n    thumbnail: {\n        type: 'href' | ElementMimeType;\n        rendition: any;\n    };\n    groups?: GroupMembershipResponse[];\n    representations: RepresentationResponse[];\n    sourceRef?: Stringified<LinkReference>; // Only present in published libraries.\n    roles: Role[];\n    details?: {\n        created?: ElementCreationContextResponse;\n        description: string;\n    };\n    parent_id?: string;\n};\n\nexport type LibraryRequest = {\n    name: string;\n    document_id: string;\n    roles: Role[];\n    description: string;\n    customData: { [s: string]: any };\n};\n\nexport type ElementMetadata = {\n    id: string;\n    name: string;\n    roles: Role[];\n    description: string;\n    sourceRef: string;\n    tags: string[];\n    group: GroupMembershipData;\n    customData: { [s: string]: any };\n};\n\nexport type ElementMetadataRequest = {\n    elements: Partial<ElementMetadata>[];\n};\n\nexport type ElementRequest = ElementMetadata & {\n    type: string;\n    client: ClientInfo;\n    representations: any[];\n};\n\nexport type GroupRequest = {\n    group: {\n        /** Group name */\n        name: string;\n        /**\n         * Group namespace. Currently defaults to $default. The default should be used unless there's\n         * a specific case to provide a custom classifiers. Non-default classifiers are presently not\n         * supported in any applications.\n         */\n        classifier?: string;\n        /**\n         * Lexicographical string for setting the group's place in the group list, or for an element's\n         * place within a group. The client is responsible for providing and sorting using these strings.\n         */\n        order: string;\n        /**\n         * Defines a relationship between nested groups. If provided, and the specified parent group\n         * exists, this group will be the \"child\" of the parent group. If there is no group in the\n         * library that matches the supplied parentId the group will still be created or updated with\n         * an empty parentId.\n         */\n        parent_id?: string;\n    };\n    client?: ClientInfo;\n    /** Id of group to copy. If present, self cannot be present and target must be present */\n    source?: string;\n    /** Id of group to move. If present, source cannot be present and target must be present */\n    self?: string;\n    /**\n     * Library id to copy or move group into. Can only equal source as a group cannot be moved into\n     * the same library.\n     */\n    target?: string;\n    /** Id of group to set as copied/moved groups parent. */\n    parentId?: string;\n};\n\nexport type RepresentationPreflightResponse = {\n    id: string;\n    name: string;\n    storage_href: string;\n    asset_id: string;\n    type: string;\n    content_length: number;\n    etag: string;\n    md5: string;\n    version: string;\n    width?: number;\n    height?: number;\n};\n\n// https://git.corp.adobe.com/Stormcloud/melville/blob/integration/src/main/java/com/adobe/melville/db/dto/element/DbLibraryElementRepresentationData.java\nconst allowedRepresentationCustomData = [\n    'color#data',\n    'colortheme#data',\n    'channel#data',\n    'imageguideline#data',\n    'gradient#data',\n    'audio#data',\n    'font#data',\n    'characterstyle#data',\n    'paragraphstyle#data',\n    'text#data',\n    '3d#data',\n    'video#data',\n    'pattern#data',\n    'candy#data',\n    'graphic#data',\n    // TODO: For Firefly POC purposes.\n    'clio#data',\n    'firefly#cme'\n] as const;\n\ntype AllowedRepresentationCustomData = (typeof allowedRepresentationCustomData)[number];\n\nexport function isRepresentationPreflightResponse(\n    data: any | RepresentationPreflightResponse\n): data is RepresentationPreflightResponse {\n    return (\n        data?.id\n        && data?.storage_href\n        && data?.asset_id\n        && data?.type\n        && data?.content_length\n        && data?.etag\n        && data?.version\n    );\n}\n\nexport type RepresentationRequestCustomData = Partial<{ [key in AllowedRepresentationCustomData]: any }>;\n\nexport type RepresentationRequest = {\n    id: string;\n    type: string;\n    relationship: 'primary' | 'rendition';\n    path: string;\n    is_full_size: boolean;\n    is_external_link: boolean;\n    width: number;\n    height: number;\n    content_length: number;\n    representation_order?: number;\n    is_preferred_thumbnail: boolean;\n\n    // TODO: What are these and do we need them?\n    // linkurl: string;\n    // linktype: string;\n    // is_component: boolean;\n} & RepresentationRequestCustomData;\n\nexport type ElementsResponse = {\n    total_count: number;\n    elements: ElementResponse[];\n    _links: {\n        next?: {\n            href: string;\n        }\n    }\n    _page?: {\n        next?: number;\n    }\n};\n\nexport type ElementsPage = {\n    total_count: number;\n    elements: ElementData[];\n    _links?: {\n        next?: {\n            href: string;\n        }\n    }\n    _page?: {\n        next?: number,\n    };\n}\n\nexport type TeamsResponse = {\n    teams: TeamResponse[];\n};\n\ntype RepositoryOwner = {\n    id: string;\n    type: 'org' | 'user';\n    email?: string;\n};\n\ntype RepositoryAssignee = {\n    id: string;\n    type: 'org' | 'user';\n};\n\nexport type TeamResponse = {\n    repositoryId: string;\n    repositoryName: string;\n    repositoryOwner: RepositoryOwner;\n    repositoryAssignee: RepositoryAssignee;\n    id: string;\n    name: string;\n    collaboratorRole: 'editor' | 'viewer';\n};\n\nconst isWritable = (libraryResponse: LibraryResponse) => {\n    const permissions = libraryResponse.asset_acl;\n\n    if (!permissions) {\n        return undefined;\n    }\n\n    const primaryPermissions = permissions['http://ns.adobe.com/adobecloud/rel/primary'];\n    if (primaryPermissions) {\n        return primaryPermissions.includes('write');\n    }\n\n    const fullPermissions = permissions['*'];\n    if (fullPermissions) {\n        return fullPermissions.includes('write');\n    }\n\n    return false;\n};\n\nfunction stubRenditionGridElements(\n    grid: RenditionGrid,\n    gridGenerationEtag: string\n): Partial<{\n        elements: ElementData[];\n        renditionGrid: { main: { id: string }; tiles: Array<{ id: string }>; gridGenerationEtag: string };\n    }> {\n    if (!grid || !grid.main) {\n        return {};\n    }\n\n    const main = stubRenditionGridElement(grid.main);\n    const tiles = grid.tiles?.filter(Boolean).map(stubRenditionGridElement) || [];\n\n    return {\n        renditionGrid: {\n            main: main ? { id: main.id } : (undefined as unknown as { id: string }),\n            tiles: tiles\n                .map(tile => (tile ? { id: tile.id } : (undefined as unknown as { id: string })))\n                .filter(Boolean),\n            gridGenerationEtag\n        },\n        elements: [ main, ...tiles ].filter(Boolean) as ElementData[]\n    };\n}\n\nfunction stubRenditionGridElement(rendition: Rendition): ElementData | undefined {\n    const elementData: ElementData = {\n        id: rendition.elementId ?? uuid(),\n        name: 'temp rendition element',\n        type: rendition.type as ElementMimeType,\n        createdDate: Date.now(),\n        modifiedDate: Date.now(),\n        representations: [\n            {\n                id: uuid(),\n                type: rendition.rendition_mimetype as string,\n                relationship: 'primary',\n                isFullSize: false,\n                isExternalLink: false,\n                isPreferredThumbnail: true\n            }\n        ],\n        groups: []\n    };\n\n    // If representation type is 'href' just make an image element. Because who cares.\n    // Melville is inconsistent and sometimes returns the element type rather than the rendition type\n    // So check for either option. See https://git.corp.adobe.com/Stormcloud/melville/blob/integration/src/main/java/com/adobe/melville/storage/operations/RenditionUtils.java#L211\n    // Ideally we can remove the element types after they phase out returning the dcx type in rendition_grid\n    switch (rendition.type) {\n    case 'application/vnd.adobe.gradient.noise+json':\n    case 'href':\n        elementData.type = 'application/vnd.adobe.element.image+dcx';\n        elementData.renditionUrl = rendition.rendition;\n        elementData.representations[0].type = 'image/png';\n        elementData.representations[0].url = rendition.rendition;\n        break;\n    case 'application/vnd.adobe.color+json':\n    case 'application/vnd.adobe.element.color+dcx':\n        elementData.representations[0].customData = {\n            // Rendition swatches will be empty if the color is missing color data (corrupt)\n            'color#data': rendition.rendition.swatches[0]?.find((swatch: any) => swatch.mode === 'RGB')\n        };\n        break;\n    case 'application/vnd.adobe.colortheme+json':\n    case 'application/vnd.adobe.element.colortheme+dcx':\n        elementData.representations[0].type = 'application/vnd.adobe.colortheme+json';\n        elementData.representations[0].customData = {\n            'colortheme#data': rendition.rendition\n        };\n        break;\n    case 'application/vnd.adobe.gradient+json':\n    case 'application/vnd.adobe.element.gradient+dcx':\n        // Gradient data in rendition often has the incorrect type of 'href' and won't hit this block\n        // https://jira.corp.adobe.com/browse/CCXB-14786\n        elementData.representations[0].customData = {\n            'gradient#data': rendition.rendition\n        };\n        break;\n    default:\n        return undefined;\n    }\n\n    return elementData;\n}\n\nfunction hasCCStorageId(libraryResponse: LibraryResponse): boolean {\n    return libraryResponse.ownership === 'public' && CC_STORAGE_ID_REGEX.test(libraryResponse.id as string);\n}\n\n// Map data returned from melville to our internal data structure.\n// This contains only library level metadata. The elements properties aren't returned here, as they are fetched separately by library.\n// Don't initialize a non-existent property with default values here (including []),\n// as we don't want to override pre-existing data with default values during the update of cached models.\n// Put default values for underlying data in the Library constructor instead.\nexport function mapResponseToLibraryData(\n    libraryResponse: LibraryResponse,\n    forceReadOnly = false,\n    injectStubRenditionGridElements = false\n): LibraryData {\n    const etag = libraryResponse.manifest_etag || melvilleFirstUseEtag;\n    const isLibraryWritable = !forceReadOnly && (isWritable(libraryResponse) as boolean);\n\n    const libraryData: LibraryData = {\n        // bookmark.id is used for public library v1 case, since the default id may not be unique\n        id: (libraryResponse.ownership === 'public' && libraryResponse.bookmark?.id) || libraryResponse.id,\n        name: libraryResponse.name,\n        ownership: libraryResponse.ownership === 'team' ? 'incoming' : libraryResponse.ownership,\n        // If there isn't a manifest_etag in the USS response, we can fill later 'If-None-Match' headers with any garbage\n        // and they will still return 304. When the library gets updated, the USS response will return a manifest_etag,\n        // the garbage 'If-None-Match' will return 200 instead of 304, and we will get the right etag.\n        etag,\n        version: libraryResponse.version,\n        default: libraryResponse.default,\n        localizedNames: libraryResponse.localized_names,\n        toolkitId: libraryResponse.toolkit_id,\n        documentId: libraryResponse.document_id,\n        documentType: libraryResponse.document_type,\n        createdDate: libraryResponse.created_date,\n        modifiedDate: libraryResponse.modified_date,\n        createdBy: libraryResponse.created_by,\n        modifiedBy: libraryResponse.modified_by,\n        groups: libraryResponse.groups?.map(mapResponseToGroupData),\n        details: {\n            elementCount: libraryResponse.elements_count,\n            documentationElementCount: 0,\n            removedElementCount: libraryResponse.removed_elements_count\n        },\n        appMetadata: libraryResponse.application_metadata,\n        collaboration: libraryResponse.collaboration,\n        assetId: libraryResponse.library_urn,\n        isWritable: isLibraryWritable,\n        isParentWritable: true,\n        // Melville discards libraries when removing them.\n        removeType: isLibraryWritable ? 'discard' : 'none',\n        deletable: isLibraryWritable,\n        roles: libraryResponse.roles,\n        description: libraryResponse.description,\n        owner: libraryResponse.storage_assignee?.id,\n        ownerType: libraryResponse.ownership ? (libraryResponse.ownership === 'team' ? 'org' : 'user') : undefined,\n        customData: getCustomDCXData(libraryResponse),\n        isLibraryLoaded: true,\n        // TODO: Remove with Durable Links and Invitation Service V4 work\n        publicLinkId: hasCCStorageId(libraryResponse) ? libraryResponse.id : undefined,\n        bookmark: libraryResponse.bookmark,\n        ...(injectStubRenditionGridElements\n            ? stubRenditionGridElements(libraryResponse.rendition_grid as RenditionGrid, etag)\n            : {})\n    };\n\n    // If this is undefined, we don't want to override the current team data with undefined if it already exists.\n    if (libraryResponse.workspace_urn || libraryResponse.parent_assetId) {\n        libraryData.team = {\n            id: libraryResponse.workspace_urn ?? libraryResponse.parent_assetId\n        };\n    }\n\n    return libraryData;\n}\n\nexport function mapResponseToElementData(elementResponse: ElementResponse): ElementData {\n    return {\n        id: elementResponse.id,\n        name: elementResponse.name,\n        isAutoNamed: elementResponse.is_auto_named,\n        type: elementResponse.type,\n        tags: elementResponse.tags || [],\n        dependencyIds: elementResponse.dependency_ids || [],\n        localizedNames: elementResponse.localized_names || {},\n        createdDate: elementResponse.created_date,\n        createdLocally: false,\n        createdContext: elementResponse.details?.created || {},\n        modifiedDate: elementResponse.modified_date,\n        modifiedLocally: false,\n        description: elementResponse.details?.description,\n        descriptionModifiedLocally: false,\n        removedLocally: false,\n        representations: elementResponse.representations?.map(mapResponseToRepresentationData) || [],\n        renditionUrl: elementResponse.thumbnail?.type === 'href' && elementResponse.thumbnail.rendition,\n        groups: elementResponse.groups?.map(mapResponseToGroupMembershipData) || [],\n        sourceRef: elementResponse.sourceRef,\n        roles: elementResponse.roles,\n        customData: getCustomDCXData(elementResponse),\n        libraryAssetId: elementResponse.parent_id\n    };\n}\n\nexport function mapResponseToGroupData(groupResponse: GroupResponse): GroupData {\n    return {\n        id: groupResponse.id,\n        classifier: groupResponse.classifier,\n        name: groupResponse.name,\n        order: groupResponse.order,\n        parentId: groupResponse.parent_id,\n        // localizedNames: groupResponse.localized_names,\n        createdDate: groupResponse.created_date,\n        modifiedDate: groupResponse.modified_date,\n        // customData: {},\n        sourceRef: groupResponse.sourceRef\n    };\n}\n\nexport function mapResponseToGroupMembershipData(\n    groupMembershipResponse: GroupMembershipResponse\n): GroupMembershipData {\n    // This is a no-op, but it is left as an example.\n    return {\n        id: groupMembershipResponse.id,\n        classifier: groupMembershipResponse.classifier,\n        order: groupMembershipResponse.order\n    };\n}\n\nexport function mapResponseToRepresentationData(representationResponse: RepresentationResponse): RepresentationData {\n    return {\n        id: representationResponse.id,\n        type: representationResponse.type,\n        linktype: representationResponse.linktype,\n        relationship: representationResponse.relationship,\n        isFullSize: representationResponse.is_full_size as boolean,\n        isExternalLink: representationResponse.is_external_link as boolean,\n        height: representationResponse.height,\n        width: representationResponse.width,\n        contentLength: representationResponse.content_length,\n        url: representationResponse._links?.['http://ns.adobe.com/melville/rel/primary']?.href,\n        blockDownloadUrl: representationResponse._links?.['http://ns.adobe.com/melville/rel/download']?.href,\n        customData: {\n            'channel#data': representationResponse['channel#data'],\n            'imageguideline#data': representationResponse['imageguideline#data'],\n            'color#data': representationResponse['color#data'],\n            'characterstyle#data': representationResponse['characterstyle#data'],\n            'paragraphstyle#data': representationResponse['paragraphstyle#data'],\n            'gradient#data': representationResponse['gradient#data'],\n            'colortheme#data': representationResponse['colortheme#data'],\n            'font#data': representationResponse['font#data'],\n            'adobestock#trackingdata': representationResponse['adobestock#trackingdata'],\n            'firefly#cme': representationResponse['firefly#cme']\n        }\n    };\n}\n\nexport function mapResponseToTeamData(teamResponse: TeamResponse): TeamData {\n    return {\n        name: teamResponse.name,\n        id: teamResponse.id,\n        isWritable: teamResponse.collaboratorRole === 'editor',\n        owner: teamResponse.repositoryOwner,\n        ownerName: teamResponse.repositoryName\n    };\n}\n\nexport function mapLibraryDataToRequest(libraryData: Partial<LibraryData>): Partial<LibraryRequest> {\n    return {\n        name: libraryData.name,\n        document_id: libraryData.documentId,\n        roles: libraryData.roles,\n        description: libraryData.description,\n        ...extractCustomData(libraryData.customData)\n    };\n}\n\nexport function mapElementDataToElementMetadata(elementData: Partial<ElementData>): Partial<ElementMetadata> {\n    return {\n        id: elementData.id,\n        name: elementData.name,\n        roles: elementData.roles,\n        description: elementData.description,\n        tags: elementData.tags,\n        sourceRef: elementData.sourceRef,\n        group: elementData.groups?.[0],\n        ...extractCustomData(elementData.customData)\n    };\n}\n\nexport function mapSearchResponseToElementData(searchResponse: SearchElementResponse): ElementData {\n    return {\n        id: searchResponse.id,\n        libraryAssetId: searchResponse.parent_id,\n        name: searchResponse.name,\n        type: searchResponse.type,\n        createdDate: searchResponse.created_date,\n        modifiedDate: searchResponse.modified_date,\n        renditionUrl: searchResponse.thumbnail.rendition,\n        tags: searchResponse.tags,\n        roles: searchResponse.roles,\n        representations: searchResponse.representations.map(mapResponseToRepresentationData),\n        groups: (searchResponse.groups || []).map(mapResponseToGroupMembershipData)\n    };\n}\n\nexport function mapRepresentationDataToRequest(\n    representationData: RepresentationData\n): RepresentationRequest & Partial<RepresentationPreflightResponse> {\n    const source = isRepresentationPreflightResponse(representationData.source) ? representationData.source : undefined;\n\n    return {\n        id: source?.id ?? representationData.id,\n        type: source?.type ?? representationData.type,\n        relationship: representationData.relationship as 'primary' | 'rendition',\n        path: representationData.path as string,\n        is_full_size: representationData.isFullSize,\n        is_external_link: representationData.isExternalLink,\n        width: source?.width ?? (representationData.width as number),\n        height: source?.height ?? (representationData.height as number),\n        content_length: source?.content_length ?? (representationData.contentLength as number),\n        is_preferred_thumbnail: representationData.isPreferredThumbnail as boolean,\n        name: source?.name,\n        storage_href: source?.storage_href,\n        asset_id: source?.asset_id,\n        etag: source?.etag,\n        md5: source?.md5,\n        version: source?.version,\n        ...extractCustomData(representationData.customData, allowedRepresentationCustomData as any)\n    };\n}\n\nfunction extractCustomData(\n    customData: { [s: string]: any } = {},\n    allowedKeys?: string[]\n): RepresentationRequestCustomData {\n    const result: RepresentationRequestCustomData = {};\n    for (const [ key, value ] of Object.entries(customData)) {\n        // Typescript is just not that smart\n        const typedKey = key as AllowedRepresentationCustomData;\n\n        // Allow keys by default if allowedKeys is undefined.\n        // Melville will reject any keys it doesn't recognize.\n        if (allowedKeys?.includes(typedKey) || !allowedKeys) {\n            result[typedKey] = value;\n        }\n    }\n    return result;\n}\n\nexport function mapElementDataToRequest(elementData: Partial<ElementData>, clientInfo: ClientInfo) {\n    return {\n        ...mapElementDataToElementMetadata(elementData),\n        client: clientInfo,\n        type: elementData.type,\n        representations: elementData.representations?.map(mapRepresentationDataToRequest)\n    };\n}\n\nexport function mapGroupDataToRequest(groupData: GroupData, clientInfo: ClientInfo): GroupRequest {\n    return {\n        group: {\n            name: groupData.name,\n            classifier: groupData.classifier,\n            order: groupData.order,\n            parent_id: groupData.parentId\n        },\n        client: clientInfo\n    };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../../models/Action';\nimport type CloudDriver from './';\n\nimport SingleOperation from '../SingleOperation';\nimport { mapResponseToLibraryData } from './utils/melvilleModelMappers';\nimport { getRequestError } from '../../errors/RequestError';\nimport AsyncResponse from '../AsyncResponse';\nimport type { ResourceRef } from '../../CCLibraries';\nimport type { LinkReference } from '../../../index';\nimport { trace, traceableAs } from '../../../core/decorators/trace';\n\ntype Access = 'team_view' | 'invite_only' | 'team_edit';\n\ntype ResourceDesignator = {\n    relType: 'http://ns.adobe.com/adobecloud/rel/metadata/application' | 'http://ns.adobe.com/adobecloud/rel/primary';\n};\n\ntype CreateLibraryPayload = {\n    name?: string;\n    roles?: Array<{\n        type: 'brand' | string;\n        usage?: string;\n        priority?: string;\n    }>;\n    source?: string;\n    parent_assetId?: string;\n    access?: Access;\n    includeResources?: Array<ResourceDesignator>;\n    documentExtractionData?: ResourceRefPayload[];\n};\n\ntype ResourceRefPayload = {\n    ['repo:assetId']: string;\n    ['repo:version']: string;\n} & LinkReference;\n\n// Modify attribute names to their full names when interfacing with the API\nconst resourceRefToPayload = (resourceRef: ResourceRef[]): ResourceRefPayload[] => {\n    return resourceRef.map(r => {\n        const { id, version, ...rest } = r;\n        return { ...rest, ['repo:assetId']: id, 'repo:version': version };\n    });\n};\n\nconst PERMISSION_INHERITANCE_MAP: { [s: string]: Access } = {\n    read: 'team_view',\n    all: 'team_edit'\n};\n\nconst supportedActionNames = [\n    'createLibrary',\n    'removeLibrary', // private library\n    'unfollowLibrary', // leave a team or public or even incoming library\n    'leaveLibrary', // leave an incoming library\n    'permanentlyDeleteLibrary',\n    'copyLibrary',\n    'moveLibrary'\n];\n\n@traceableAs('CloudSingleOperation')\nexport default class CloudSingleOperation extends SingleOperation<CloudDriver> {\n    protected _actionMappers = {\n        createLibrary: (action: Action) => this._createLibraryActionMap(action),\n        copyLibrary: (action: Action) => this._createLibraryActionMap(action),\n        removeLibrary: async (action: Action) => {\n            await this._removeLibrary();\n            return action;\n        },\n        permanentlyDeleteLibrary: async (action: Action) => {\n            await this._permanentlyDeleteLibrary();\n            return action;\n        },\n        unfollowLibrary: async (action: Action) => {\n            await this._unfollowLibrary();\n            return action;\n        },\n        leaveLibrary: async (action: Action) => {\n            await this._leaveLibrary();\n            return action;\n        },\n        moveLibrary: async (action: Action) => {\n            const data = await this._moveLibrary();\n            return { ...action, data, originalAction: action };\n        }\n    };\n\n    supportsAction(action: Action) {\n        return supportedActionNames.includes(action.name as string);\n    }\n\n    private _createLibraryActionMap = async (action: Action): Promise<Action> => {\n        const data = await this._createLibrary(action);\n        return { ...action, type: 'update', data, originalAction: action };\n    };\n\n    @trace\n    private _createLibrary(action: Action) {\n        return new Promise((resolve, reject) => {\n            const { name, team, roles, documentExtractionData } = action.data ?? {};\n            const {\n                permissionInheritance,\n                source,\n                includeAppMetadata: includeApplicationMetadata\n            } = action.flags ?? {};\n            const payload: CreateLibraryPayload = {\n                name,\n                roles,\n                documentExtractionData:\n                    documentExtractionData?.length > 0 ? resourceRefToPayload(documentExtractionData) : undefined,\n                // @ts-expect-error R-TODO\n                source: source?.assetId,\n                parent_assetId: team?.id,\n                access: PERMISSION_INHERITANCE_MAP[permissionInheritance as string] || undefined,\n                includeResources: includeApplicationMetadata\n                    ? [\n                        { relType: 'http://ns.adobe.com/adobecloud/rel/metadata/application' },\n                        { relType: 'http://ns.adobe.com/adobecloud/rel/primary' }\n                    ]\n                    : undefined\n            };\n            const request = this._driver.fetch('/api/v1/libraries?invocation_mode=async', {\n                method: 'POST',\n                headers: {\n                    'Content-Type': 'application/json'\n                },\n                body: JSON.stringify(payload)\n            });\n            const asyncResponse = new AsyncResponse(this._driver, request);\n            asyncResponse.on('change', (done, response) => {\n                if (done) {\n                    if (asyncResponse.error) {\n                        reject(asyncResponse.error);\n                    } else if (response) {\n                        const libraryData = mapResponseToLibraryData(response);\n\n                        // TEMPORARY WORKAROUND TO MANUALLY UPDATE APPMETADATA\n                        // CCXB-21559 WILL DO THIS AUTOMATICALLY IN THE BACKEND SOON\n                        if (documentExtractionData?.length > 0 && libraryData.assetId) {\n                            this._patchBrandAppMetadata(\n                                libraryData.assetId,\n                                '/brand:extractedFrom',\n                                resourceRefToPayload(documentExtractionData)\n                            );\n                        }\n\n                        // Implicitly, if we've created a library, we know it and its parent are writable.\n                        // Melville does not return ACLs on create response.\n                        libraryData.isWritable = true;\n                        libraryData.isParentWritable = true;\n                        resolve(libraryData);\n                    } else {\n                        resolve(undefined);\n                    }\n                }\n            });\n        });\n    }\n\n    private _removeLibrary() {\n        return this._driver.fetch(`/api/v1/libraries/${this._library.assetId}`, { method: 'DELETE' });\n    }\n\n    private _permanentlyDeleteLibrary() {\n        return this._driver.fetch(`/api/v1/libraries/${this._library.assetId}?permanent=true`, { method: 'DELETE' });\n    }\n\n    private _unfollowLibrary() {\n        return this._driver.fetch(`/api/v1/libraries/bookmarks/${this._library.bookmark?.id}`, { method: 'DELETE' });\n    }\n\n    private async _leaveLibrary() {\n        const userId = this._driver.config.user?.id;\n        const response = await this._driver.fetch(\n            `https://${this._driver.driverConfig.invitation_hostname}/api/v4/share/${this._library.assetId}`,\n            {\n                method: 'PATCH',\n                headers: {\n                    'Content-Type': 'application/json'\n                },\n                body: JSON.stringify({\n                    collaborators: [\n                        {\n                            action: 'remove',\n                            id: userId\n                        }\n                    ]\n                })\n            }\n        );\n\n        const json = await response.json();\n\n        const error = json.collaborators?.find((collab: any) => collab.statusCode > 300);\n        if (!error) {\n            return this._unfollowLibrary();\n        } else {\n            throw getRequestError(response);\n        }\n    }\n\n    private _moveLibrary() {\n        return this._driver.moveLibrary(\n            this._library.assetId as string,\n            this.action.data.team.id,\n            this.action.data.owner\n        );\n    }\n\n    private async _patchBrandAppMetadata(assetId: string, path: string, newAppMetadata: Object) {\n        const asset = await this._driver._core?.hostAssetContext.getAssetWithCloudID(assetId);\n        asset?.patchAppMetadata([ { op: 'add', path, value: newAppMetadata } ]);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { isPlaceholder } from '../models/utils';\n\nconst stripWhitespace = (str: string) => str.replace(/ |\\t|\\n/g, '');\n\nconst elementRegex = /^(\\$\\.(?:elements|removedElements|documentationElements))\\[\\?\\(@\\.id==\"([^\"]+)\"\\)\\]$/;\nconst groupRegex = /^\\$\\.groups\\[\\?\\(@\\.id==\"([^\"]+)\"\\)\\]$/;\n\nexport function extractElementId(path: string): string | undefined {\n    path = stripWhitespace(path);\n    const [ , , elementId ] = elementRegex.exec(path) || [];\n    return elementId;\n}\n\nexport function extractElementCollection(path: string): string | undefined {\n    path = stripWhitespace(path);\n    const [ , elementCollection ] = elementRegex.exec(path) || [];\n    return elementCollection;\n}\n\nexport function extractGroupId(path: string): string | undefined {\n    path = stripWhitespace(path);\n    const [ , groupId ] = groupRegex.exec(path) || [];\n    return groupId;\n}\n\nexport function getPlaceholderId(path: string) {\n    const id = extractElementId(path) || (extractGroupId(path) as string);\n    return isPlaceholder(id) && id;\n}\n\nexport function replaceId(path: string, oldId: string, newId: string) {\n    return path.replace(oldId, newId);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../models/Action';\n// @ts-expect-error R-TODO\nimport type { default as Library } from '../models/Library';\nimport type { ElementData } from '../models/data/ElementData';\nimport type Driver from './Driver';\nimport { extractElementId } from '../utils/PathUtils';\nimport type { ExecuteResult } from './Operation';\nimport Operation, { validatesOperation } from './Operation';\n\n/**\n * A transfer operation is an operation to move or copy elements or groups.\n * Due to the cross-library nature of these operations, these operations may\n * need to act on two different libraries multiple times.\n */\nexport default abstract class MoveCopyElementOperation<T extends Driver> extends Operation<T> {\n    supportsAction(action: Action) {\n        return [ 'moveElement', 'copyElement', 'dependent' ].includes(action.name as string);\n    }\n\n    addAction(action: Action) {\n        // move/copy are batchable if:\n        //  - the action is a supported action\n        //  - the source and destination libraries are the same\n        //  - the action is the same (move or copy)\n        //  - the linked action is in the same queue position as the action\n        //  - if the source and target libraries are the same:\n        //    * the linked action is in the n+1 position\n\n        if (!this.supportsAction(action)) {\n            return false;\n        }\n\n        const lastAction = this._actions[this._actions.length - 1];\n\n        if (!lastAction && action.name !== 'dependent') {\n            return super.addAction(action);\n        }\n\n        if (action.library === action.link?.library) {\n            if (action.name === 'dependent') {\n                if (lastAction.link === action) {\n                    this._actions.push(action);\n                    return true;\n                }\n                return false;\n            }\n            // @ts-expect-error R-TODO\n            const actionIndex = action.library?.actions.indexOf(action) as number;\n            // @ts-expect-error R-TODO\n            const linkedActionIndex = action.link?.library?.actions.indexOf(action.link as Action);\n\n            if (actionIndex + 1 !== linkedActionIndex) {\n                return false;\n            }\n\n            return super.addAction(action);\n        }\n\n        if (lastAction.link?.library !== action.link?.library || lastAction.type !== action.type) {\n            return false;\n        }\n\n        return super.addAction(action);\n    }\n\n    @validatesOperation\n    async execute(): Promise<ExecuteResult> {\n        const isMove = this._actions[0].name === 'moveElement';\n\n        const targetLibrary = this._actions[0].link?.library as Library;\n        const actualActions = this._actions.filter(action => action.name !== 'dependent');\n        const elementIds = actualActions.map(action => extractElementId(action.path as string) as string);\n\n        const { elements, etag, sourceEtag } = await this._doMoveCopyRequest(\n            isMove,\n            this._library,\n            targetLibrary,\n            elementIds\n        );\n\n        // The elements in the response should be 1:1 with the elements in the actions. If not, something has gone wrong.\n        if (elements.length !== actualActions.length) {\n            // TODO: Better error\n            throw new Error();\n        }\n\n        let linkedActions: Action[];\n        let actions: Action[];\n\n        if (targetLibrary === this._library) {\n            linkedActions = [];\n            actions = this._actions.map(action => {\n                if (action.name !== 'dependent') {\n                    return action;\n                }\n\n                const index = actualActions.findIndex(\n                    a => a === (action.link as Action) || a.originalAction === (action.link as Action)\n                );\n\n                return {\n                    ...action,\n                    data: elements[index],\n                    originalAction: action\n                };\n            });\n        } else {\n            actions = this._actions;\n            linkedActions = this._actions.map(\n                (action, index) =>\n                    ({\n                        ...action.link,\n                        data: elements[index],\n                        originalAction: action.link\n                    } as Action)\n            );\n        }\n\n        return {\n            actions,\n            etag: sourceEtag as string,\n            linkedActions,\n            linkedEtag: etag as string\n        };\n    }\n\n    protected abstract _doMoveCopyRequest(\n        isMove: boolean,\n        sourceLibrary: Library,\n        targetLibrary: Library,\n        elementIds: string[]\n    ): Promise<{ elements: ElementData[]; etag: string | null; sourceEtag: string | null }>;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n// @ts-expect-error R-TODO\nimport type { default as Library } from '../../models/Library';\nimport type { ElementData } from '../../models/data/ElementData';\n\nimport { mapResponseToElementData } from './utils/melvilleModelMappers';\nimport MoveCopyElementOperation from '../MoveCopyElementOperation';\nimport type CloudDriver from '.';\n\n/**\n * A transfer operation is an operation to move or copy elements or groups.\n * Due to the cross-library nature of these operations, these operations may\n * need to act on two different libraries multiple times.\n */\nexport default class CloudMoveCopyElementOperation extends MoveCopyElementOperation<CloudDriver> {\n    protected async _doMoveCopyRequest(\n        isMove: boolean,\n        sourceLibrary: Library,\n        targetLibrary: Library,\n        elementIds: string[]\n    ): Promise<{ elements: ElementData[]; etag: string | null; sourceEtag: string | null }> {\n        const sourceAssetId = this._library.assetId;\n        const targetAssetId = targetLibrary.assetId;\n\n        const response = await this._driver.fetch(`/api/v1/libraries/${targetAssetId}/elements`, {\n            method: 'POST',\n            headers: {\n                'Content-Type': 'application/json',\n                'If-Match': targetLibrary.etag\n            },\n            body: JSON.stringify({\n                [isMove ? 'self' : 'source']: {\n                    id: sourceAssetId,\n                    elements: elementIds,\n                    'if-match': this._library.etag\n                }\n            })\n        });\n\n        const json = await response.json();\n\n        return {\n            elements: json.elements.map(mapResponseToElementData),\n            etag: response.headers.get('etag'),\n            sourceEtag: response.headers.get('x-source-etag')\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../models/Action';\nimport { isPlaceholder } from '../models/utils';\nimport { getPlaceholderId, replaceId } from './PathUtils';\n\nexport function deepCopy<T>(object: T): T {\n    // eslint-disable-next-line no-undef\n    if (typeof structuredClone !== 'undefined') { return structuredClone(object); }\n    return JSON.parse(JSON.stringify(object));\n}\n\nfunction replaceActionPlaceHolders(\n    targetAction: Action,\n    idCache: { [s: string]: Action['data'] },\n    placeholderReplacers: Array<(action: Action, idCache: { [s: string]: Action['data'] }) => Action>\n) {\n    const newAction = placeholderReplacers.reduce((action, replacer) => replacer(action, idCache), targetAction);\n    if (newAction !== targetAction) {\n        newAction.originalAction = targetAction;\n    }\n\n    if (newAction.type === 'aggregate') {\n        newAction.actions = newAction.actions?.map(action =>\n            replaceActionPlaceHolders(action, idCache, placeholderReplacers)\n        );\n    }\n\n    return newAction;\n}\n\nexport function replacePlaceholders(sourceActions: Action[], targetActions?: Action[]): Action[] {\n    if (!targetActions) {\n        targetActions = sourceActions;\n    }\n\n    // If an ID has changed between the original action and the response (placeholder substitution),\n    // we need to replace that id in all pending actions. Otherwise the actions will be pointing at\n    // an element that doesn't exist.\n    const idCache: { [s: string]: Action['data'] } = {};\n    for (const sourceAction of sourceActions) {\n        if (isPlaceholder(sourceAction.originalAction?.data?.id)) {\n            idCache[sourceAction.originalAction?.data.id] = sourceAction.data;\n        }\n    }\n\n    // Replace placeholder ids on queued actions\n    const placeholderReplacers: Array<(action: Action, idCache: { [s: string]: Action['data'] }) => Action> = [\n        pathPlaceholderReplacer,\n        groupDataPlaceholderReplacer,\n        representationDataPlaceholderReplacer\n    ];\n    return targetActions.map(action => replaceActionPlaceHolders(action, idCache, placeholderReplacers));\n}\n\nfunction pathPlaceholderReplacer(action: Action, idCache: { [s: string]: Action['data'] }) {\n    const placeholderId = action.path && getPlaceholderId(action.path);\n\n    if (placeholderId) {\n        const actualId = idCache[placeholderId]?.id;\n\n        if (actualId) {\n            return {\n                ...action,\n                path: replaceId(action.path as string, placeholderId, actualId)\n            };\n        }\n    }\n\n    return action;\n}\n\nfunction groupDataPlaceholderReplacer(action: Action, idCache: { [s: string]: Action['data'] }) {\n    let hasReplacedGroups = false;\n    const newGroups: { id: string }[] = [];\n    action.data?.groups?.forEach((group: { id: string }) => {\n        if (group.id && isPlaceholder(group.id)) {\n            const actualId = idCache[group.id]?.id;\n            if (actualId) {\n                hasReplacedGroups = true;\n                newGroups.push({ ...group, id: actualId });\n                return;\n            }\n        }\n        newGroups.push(group);\n    });\n\n    if (hasReplacedGroups) {\n        return {\n            ...action,\n            data: {\n                ...action.data,\n                groups: newGroups\n            }\n        };\n    }\n\n    // Replacing potential placeholder Ids with actual Ids.\n    if (action.data?.id && isPlaceholder(action.data?.id)) {\n        const actualId = idCache[action.data?.id]?.id;\n        if (actualId) {\n            action.data.id = actualId;\n        }\n    }\n\n    if (action.data?.parentId && isPlaceholder(action.data?.parentId)) {\n        const actualId = idCache[action.data?.parentId]?.id;\n        if (actualId) {\n            action.data.parentId = actualId;\n        }\n    }\n    return action;\n}\n\nfunction representationDataPlaceholderReplacer(action: Action, idCache: { [s: string]: Action['data'] }) {\n    const newRepresentations: { id: string; source?: { id: string } }[] = [];\n    let replacedRepresentations = false;\n\n    const replaceRepresentation = (representation: { id: string }) => {\n        let newRepresentation = { ...representation };\n        if (representation.id && isPlaceholder(representation.id)) {\n            const actualData = idCache[representation.id];\n            // We need to inject the entire representation data, the id alone is not sufficient.\n            if (actualData) {\n                newRepresentation = actualData;\n                replacedRepresentations = true;\n            }\n        }\n        return newRepresentation;\n    };\n\n    action.data?.representations?.forEach((representation: { id: string; source?: { id: string } }) => {\n        if (representation.source) {\n            representation.source = replaceRepresentation(representation.source);\n        }\n        newRepresentations.push(replaceRepresentation(representation));\n    });\n\n    if (replacedRepresentations) {\n        // Don't inject new fields into the action payload that weren't there before.\n        return {\n            ...action,\n            data: {\n                ...action.data,\n                representations: newRepresentations\n            }\n        };\n    }\n    return action;\n}\n\nexport function markSubstitutedPlaceholders(actions: Action[]) {\n    for (const action of actions) {\n        if (action.data && isPlaceholder(action.originalAction?.data?.id)) {\n            action.data.previousPlaceholderId = action.originalAction?.data.id;\n        }\n    }\n}\n","import type { RepresentationData } from '../../models/data/RepresentationData';\nimport { isPlaceholder, extractPlaceholder } from '../../models/utils';\n\ntype Method = 'PUT' | 'POST' | 'DELETE';\n\n// valid Process sub-routes of `.../libraries/{libraryId}`\nexport type ProcessLibrariesRoute = `${\n    | 'elements'\n    | 'removed_elements'\n    | 'groups'\n    | 'documentation_elements'\n    | 'temp_dir'\n    | 'export'\n    | ''}${string}`;\n\nexport type ProcessRESTOperation<T = any> = {\n    body?: T;\n    method: Method;\n    path: ProcessLibrariesRoute;\n    query_params?: Record<string, string>;\n};\n\n// valid Melville sub-routes of `api/v1/libraries/{libraryId}`\nexport type MelvilleV1LibrariesRoute = `${'elements' | 'bookmarks' | 'archive' | 'metadata' | 'groups'}${string}`;\n\nexport type MelvilleRESTOperation<T = any> = {\n    body?: T;\n    method: Method;\n    path: MelvilleV1LibrariesRoute;\n    query_params?: Record<string, string>;\n};\n\ntype RESTOperation = MelvilleRESTOperation | ProcessRESTOperation;\n\nexport function tokenizePlaceholders(requests: RESTOperation[]): RESTOperation[] {\n    const tokenMap: { [s: string]: string } = {};\n\n    for (let i = 0; i < requests.length; i += 1) {\n        const request = requests[i];\n        const id = request.body?.id;\n\n        if (request.method === 'POST' && isPlaceholder(id)) {\n            tokenMap[id] = `$${i}.id`;\n            delete request.body.id;\n        }\n\n        // For PUT and DELETE check the path\n        if ([ 'PUT', 'DELETE' ].includes(request.method)) {\n            const placeholder = extractPlaceholder(request.path);\n\n            if (placeholder) {\n                if (!tokenMap[placeholder]) {\n                    throw new Error(`Unmapped placeholder ID: ${placeholder}`);\n                }\n\n                request.path = request.path.replace(placeholder, tokenMap[placeholder]);\n            }\n        }\n\n        // For PUT AND POST check the content\n        if ([ 'PUT', 'POST' ].includes(request.method)) {\n            if (request.path.startsWith('elements') && request.body.representations) {\n                // Make sure representations in the outgoing requests have no placeholder ID values\n                // Note: this only handles top-level representations. Child representations will be dealt with in this ticket: https://jira.corp.adobe.com/browse/CCXC-18482\n                removeRepresentationPlaceholderIds(request.body.representations);\n            }\n\n            if (request.path.startsWith('elements') && request.body.groups) {\n                for (const group of request.body.groups) {\n                    if (!isPlaceholder(group.id)) {\n                        continue;\n                    }\n\n                    if (!tokenMap[group.id]) {\n                        throw new Error(`Unmapped placeholder ID: ${group.id}`);\n                    }\n\n                    group.id = tokenMap[group.id];\n                }\n            }\n\n            if (request.path.startsWith('groups') && request.body.parent_id && isPlaceholder(request.body.parent_id)) {\n                if (!tokenMap[request.body.parent_id]) {\n                    throw new Error(`Unmapped placeholder ID: ${request.body.parent_id}`);\n                }\n\n                request.body.parent_id = tokenMap[request.body.parent_id];\n            }\n        }\n    }\n\n    return requests;\n}\n\n/**\n * Return an object equivalent to the given one but with any undefined values removed.\n * Exceptions can be made for certain keys, passed as second argument\n */\nexport function omitUndefined<T extends { [key: string]: any }>(object: T, keys?: string[]) {\n    const result = {} as T;\n    for (const [ key, val ] of Object.entries(object)) {\n        if (val !== undefined || keys?.includes(key)) {\n            result[key as T['key']] = val;\n        }\n    }\n    return result;\n}\n\n/**\n * Removes any placeholder IDs from top-level representations\n * This utility method is used to make sure that all outgoing requests have no placeholder IDs in them\n * Note: This needs to be modified to account for nested child representations (see https://jira.corp.adobe.com/browse/CCXC-18482)\n *\n * @param {RepresentationData[]} representations An array of representations associated with an outgoing element request\n * @returns {RepresentationData[]}\n */\nexport function removeRepresentationPlaceholderIds(representations: RepresentationData[]) {\n    for (const representation of representations) {\n        if (isPlaceholder(representation.id)) {\n            // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n            // @ts-expect-error\n            representation.id = undefined;\n        }\n    }\n\n    return representations;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * BatchOperation\n * @packageDocumentation\n * @module BatchOperation\n * @internal\n */\n\nimport type { default as CloudDriver } from '../../drivers/CloudDriver';\nimport type { ElementData } from '../../models/data/ElementData';\nimport type { LibraryData } from '../../models/data/LibraryData';\nimport type { Action, UpdateAction, InsertAction, RemoveAction, AggregateAction } from '../../models/Action';\n\nimport type { ExecuteResult } from '../Operation';\nimport Operation, { validatesOperation } from '../Operation';\nimport type {\n    ElementRequest,\n    ElementMetadataRequest,\n    LibraryRequest,\n    GroupRequest\n} from './utils/melvilleModelMappers';\nimport {\n    mapLibraryDataToRequest,\n    mapElementDataToElementMetadata,\n    mapElementDataToRequest,\n    mapGroupDataToRequest,\n    mapResponseToLibraryData,\n    mapResponseToElementData,\n    mapResponseToGroupData\n} from './utils/melvilleModelMappers';\n\nimport { extractElementId, extractGroupId } from '../../utils/PathUtils';\nimport { replacePlaceholders } from '../../utils/StoreUtils';\nimport type { MelvilleRESTOperation } from '../utils/operationUtils';\nimport { tokenizePlaceholders } from '../utils/operationUtils';\nimport LibraryError from '../../errors/LibraryError';\nimport { omitUndefined } from '../../drivers/utils/operationUtils';\nimport type { GroupData } from '../../models/data/GroupData';\nimport { trace, traceableAs } from '../../../core/decorators/trace';\n\nconst supportedActionNames = [\n    'updateLibrary',\n    'createElement',\n    'updateElement',\n    'removeElement',\n    'restoreElement',\n    'deleteElement',\n    'createGroup',\n    'removeGroup'\n] as const;\n\ntype SupportedAction = Action & {\n    name: (typeof supportedActionNames)[number];\n};\n\nfunction isSupportedAction(action: Action): action is SupportedAction {\n    return supportedActionNames.includes(action.name as any);\n}\n\nfunction replaceData<T>(action: Action, data: T): Action {\n    return { ...action, data, originalAction: action };\n}\n\nconst RESPONSE_MAPPERS: {\n    [s in (typeof supportedActionNames)[number]]: (action: Action, data?: any) => Action;\n} = {\n    updateLibrary: (action, data) => {\n        // Melville does not return ACLs on patch response, so omit any data that is undefined/missing from response\n        const responseData = omitUndefined(mapResponseToLibraryData(data, false, false), [\n            'documentId',\n            'documentType',\n            'roles'\n        ]);\n        return replaceData(action, responseData);\n    },\n    createElement: (action, data) => replaceData(action, mapResponseToElementData(data.elements[0])),\n    updateElement: (action, data) => replaceData(action, mapResponseToElementData(data.elements[0])),\n    restoreElement: action => action,\n    removeElement: action => action,\n    deleteElement: action => action,\n    createGroup: (action, data) => replaceData(action, mapResponseToGroupData(data)),\n    removeGroup: action => action\n};\n\n@traceableAs('BatchOperation')\nexport default class BatchOperation extends Operation<CloudDriver> {\n    private _baseLibraryOperationPath = `/api/v1/libraries/${this._library.assetId}`;\n    private _actionMappers = {\n        updateLibrary: (action: UpdateAction<LibraryData>): MelvilleRESTOperation<Partial<LibraryRequest>> => ({\n            method: 'PUT',\n            path: `metadata`,\n            body: mapLibraryDataToRequest(action.data)\n        }),\n        createElement: (action: InsertAction<ElementData>): MelvilleRESTOperation<Partial<ElementRequest>> => ({\n            method: 'POST',\n            path: `elements`,\n            body: mapElementDataToRequest(action.data, this._driver.getClientInfo())\n        }),\n        updateElement: (action: UpdateAction<ElementData>): MelvilleRESTOperation<ElementMetadataRequest> => ({\n            method: 'PUT',\n            path: `elements/metadata`,\n            body: {\n                elements: [\n                    mapElementDataToElementMetadata({ id: extractElementId(action.path as string), ...action.data })\n                ]\n            }\n        }),\n        removeElement: (action: RemoveAction | AggregateAction): MelvilleRESTOperation<void> => ({\n            method: 'DELETE',\n            path: `elements/${extractElementId(action.path as string)}`\n        }),\n        restoreElement: (action: AggregateAction): MelvilleRESTOperation<{ elementIds: string[] }> => ({\n            method: 'POST',\n            path: `archive`,\n            body: {\n                elementIds: [ `${action.data.id}` ]\n            }\n        }),\n        deleteElement: (action: RemoveAction | AggregateAction): MelvilleRESTOperation<void> => ({\n            method: 'DELETE',\n            path: `elements/${extractElementId(action.path as string)}`,\n            query_params: { permanent: 'true' }\n        }),\n        createGroup: (action: InsertAction<GroupData>): MelvilleRESTOperation<GroupRequest> => ({\n            method: 'POST',\n            path: `groups`,\n            body: mapGroupDataToRequest(action.data, this._driver.getClientInfo())\n        }),\n        removeGroup: (action: RemoveAction | AggregateAction): MelvilleRESTOperation<void> => ({\n            method: 'DELETE',\n            path: `groups/${extractGroupId(action.path as string)}`,\n            query_params: action.flags?.includeElements ? { include_contents: 'true' } : undefined\n        })\n    };\n\n    protected _actions: SupportedAction[] = [];\n\n    @validatesOperation\n    @trace\n    async execute(): Promise<ExecuteResult> {\n        const payload = this._actions.map(action => this._actionMappers[action.name](action as never));\n        const tokenizedPayload = tokenizePlaceholders(payload);\n        const response = await this._driver.fetch(this._baseLibraryOperationPath, {\n            method: 'PATCH',\n            headers: {\n                'Content-Type': 'application/json',\n                'If-Match': this._library.etag\n            },\n            body: JSON.stringify({\n                requests: tokenizedPayload.map(r => ({\n                    ...r,\n                    path: `${this._baseLibraryOperationPath}/${r.path}`\n                }))\n            })\n        });\n\n        const { responses } = await response.json();\n\n        // Response should be an array that's the same size as the number of actions in the batch\n        if (!Array.isArray(responses) || responses.length !== this._actions.length) {\n            throw new LibraryError('INVALID_RESPONSE', 'Malformed batch response.', this._library.id);\n        }\n\n        // Given the responses, map the actual response onto actions and return the new actions.\n        let newActions = this._actions.map((action, index) => {\n            return RESPONSE_MAPPERS[action.name](action, responses[index]);\n        });\n\n        // Replace any placeholders that might exist in the new actions\n        newActions = replacePlaceholders(newActions);\n\n        return { actions: newActions, etag: response.headers.get('ETag') as string };\n    }\n\n    supportsAction(action: Action) {\n        return isSupportedAction(action);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../../models/Action';\nimport type { ElementData } from '../../models/data/ElementData';\nimport type { default as CloudDriver } from './index';\n\nimport type { ExecuteResult } from '../Operation';\nimport Operation, { validatesOperation } from '../Operation';\nimport { extractElementId } from '../../utils/PathUtils';\nimport { mapElementDataToRequest, mapResponseToElementData } from './utils/melvilleModelMappers';\nimport { removeRepresentationPlaceholderIds } from '../utils/operationUtils';\nimport type { RepresentationData } from '../../models/data/RepresentationData';\nimport { trace, traceableAs } from '../../../core/decorators/trace';\n\n/**\n * Element content is always replaced entirely, so if we're doing a bunch of representation changes, it makes\n * sense to batch them together.\n *\n * Also, since this operation isn't supported by the batch API, we want to cut down on requests.\n */\n@traceableAs('ContentOperation')\nexport default class ContentOperation extends Operation<CloudDriver> {\n    supportsAction(action: Action) {\n        return action.name === 'updateElementContent';\n    }\n\n    addAction(action: Action) {\n        // Content operations must operate on the same element\n        if (this._actions[0] && this._actions[0].path !== action.path) {\n            return false;\n        }\n\n        return super.addAction(action);\n    }\n\n    @validatesOperation\n    @trace\n    async execute(): Promise<ExecuteResult> {\n        // The last content update action will always be the most up-to-date. We can omit all of the ones before it.\n        const lastAction = this._actions[this._actions.length - 1];\n\n        const response = await this._updateElementContent(\n            extractElementId(lastAction.path as string) as string,\n            lastAction.data\n        );\n        const json = await response.json();\n        const data = mapResponseToElementData(json.elements[0]);\n\n        const actions = this._actions.map((action, index): Action => {\n            if (index !== this._actions.length - 1) {\n                return { ...action, type: 'no-op', originalAction: action };\n            } else {\n                return { ...action, data, originalAction: action };\n            }\n        });\n\n        return { actions, etag: response.headers.get('ETag') as string };\n    }\n\n    private _updateElementContent(elementId: string, data: Partial<ElementData>) {\n        removeRepresentationPlaceholderIds(data.representations as RepresentationData[]);\n\n        return this._driver.fetch(`/api/v1/libraries/${this._library.assetId}/elements/${elementId}/representations`, {\n            method: 'PUT',\n            headers: {\n                'If-Match': this._library.etag,\n                'Content-Type': 'application/json'\n            },\n            body: JSON.stringify(mapElementDataToRequest(data, this._driver.getClientInfo()))\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * ParallelOperation\n * @packageDocumentation\n * @module ParallelOperation\n * @internal\n */\n\nimport type { Action } from '../models/Action';\n\nimport type { ExecuteResult } from './Operation';\nimport Operation, { validatesOperation } from './Operation';\nimport type Driver from './Driver';\n\n/**\n * ParallelOperation\n *\n * An operation that can execute several actions at the same time.\n *\n * Actions in a ParallelOperation should be able to run without affecting or\n * being affected by other actions that may run concurrently.\n */\nexport default abstract class ParallelOperation<T extends Driver = Driver> extends Operation<T> {\n    protected _actionMappers: { [s: string]: (action: Action) => Promise<Action> } = {};\n\n    @validatesOperation\n    async execute(): Promise<ExecuteResult> {\n        const promises = this.actions.map(action => this._actionMappers[action.name as string](action));\n        // TODO: What about allSettled?\n        return { actions: await Promise.all(promises) };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../../models/Action';\nimport type CloudDriver from './';\n\nimport ParallelOperation from '../ParallelOperation';\n// @ts-expect-error R-TODO\nimport type Library from '../../models/Library';\n\nexport default class CloudParallelOperation extends ParallelOperation<CloudDriver> {\n    protected _actionMappers = {\n        uploadComponent: async (action: Action) => {\n            const data = JSON.parse(\n                await this._driver.stageRepresentationForCommit(\n                    action.library as Library,\n                    action.data.file,\n                    action.data.type\n                )\n            );\n            return { ...action, data, originalAction: action };\n        }\n    };\n\n    supportsAction(action: Action) {\n        return action.name === 'uploadComponent';\n    }\n}\n","import type { Link, RapiLinkType } from './rapiModelMappers';\n\n/**\n * Parses links returned from RAPI in response headers.\n *\n * @param linksList Comma-separated list of link relations.\n * @returns Record of links where the keys are the relation and the value is the link.\n *\n * @example\n * ```\n * const rapiResponse = await fetch('https://platform.adobe.io/some/path');\n * const links = parseLinks(rapiResponse.headers.get('link'));\n * const componentLink = links['http://ns.adobe.com/adobecloud/rel/component'];\n * ```\n */\nexport function parseLinks(linksList: string) {\n    const links: Partial<Record<RapiLinkType, Link>> = {};\n\n    do {\n        const firstLinkIndex = linksList.indexOf('<');\n        if (firstLinkIndex === -1) {\n            break;\n        }\n\n        let secondLinkIndex = linksList.indexOf('<', firstLinkIndex + 1);\n        if (secondLinkIndex === -1) {\n            secondLinkIndex = linksList.length;\n        }\n\n        const linkString = linksList.substring(firstLinkIndex, secondLinkIndex);\n        const link = parseLink(linkString);\n        if (link) {\n            links[link.rel as RapiLinkType] = link;\n        }\n\n        linksList = linksList.substring(secondLinkIndex);\n    } while (linksList.length > 0);\n\n    return links;\n}\n\nfunction parseLink(linkString: string): Link | undefined {\n    // A link string will be in the format:\n    // <https://subdomain.adobe.io/path>; rel=\"http://ns.adobe.com/adobecloud/rel/relation\"; key=\"value\"\n    // Get the href from the link string (the part surrounded with angle brackets).\n    const hrefMatch = linkString.match(/^<(.*)>;/);\n    if (!hrefMatch) {\n        return undefined;\n    }\n    const link: Record<string, any> = { href: hrefMatch[1] };\n\n    // Get each key-value pair from the link string.\n    const matches = linkString.matchAll(/\\s([\\w:]*)=\"([^\"]*)\"[;,]?/g);\n    for (const match of matches) {\n        const key = match[1];\n        const value = match[2];\n        link[key] = convertToPrimitiveType(value);\n    }\n    return link as Link;\n}\n\nfunction convertToPrimitiveType(str: string): string | number | boolean {\n    if (str === 'true' || str === 'false') {\n        return str === 'true';\n    }\n\n    const strAsNumber = +str;\n    const isNumber = !isNaN(strAsNumber);\n    if (isNumber) {\n        return strAsNumber;\n    }\n\n    return str;\n}\n","'use strict';\nmodule.exports = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);\n","'use strict';\nvar token = '%[a-f0-9]{2}';\nvar singleMatcher = new RegExp(token, 'gi');\nvar multiMatcher = new RegExp('(' + token + ')+', 'gi');\n\nfunction decodeComponents(components, split) {\n\ttry {\n\t\t// Try to decode the entire string first\n\t\treturn decodeURIComponent(components.join(''));\n\t} catch (err) {\n\t\t// Do nothing\n\t}\n\n\tif (components.length === 1) {\n\t\treturn components;\n\t}\n\n\tsplit = split || 1;\n\n\t// Split the array in 2 parts\n\tvar left = components.slice(0, split);\n\tvar right = components.slice(split);\n\n\treturn Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));\n}\n\nfunction decode(input) {\n\ttry {\n\t\treturn decodeURIComponent(input);\n\t} catch (err) {\n\t\tvar tokens = input.match(singleMatcher);\n\n\t\tfor (var i = 1; i < tokens.length; i++) {\n\t\t\tinput = decodeComponents(tokens, i).join('');\n\n\t\t\ttokens = input.match(singleMatcher);\n\t\t}\n\n\t\treturn input;\n\t}\n}\n\nfunction customDecodeURIComponent(input) {\n\t// Keep track of all the replacements and prefill the map with the `BOM`\n\tvar replaceMap = {\n\t\t'%FE%FF': '\\uFFFD\\uFFFD',\n\t\t'%FF%FE': '\\uFFFD\\uFFFD'\n\t};\n\n\tvar match = multiMatcher.exec(input);\n\twhile (match) {\n\t\ttry {\n\t\t\t// Decode as big chunks as possible\n\t\t\treplaceMap[match[0]] = decodeURIComponent(match[0]);\n\t\t} catch (err) {\n\t\t\tvar result = decode(match[0]);\n\n\t\t\tif (result !== match[0]) {\n\t\t\t\treplaceMap[match[0]] = result;\n\t\t\t}\n\t\t}\n\n\t\tmatch = multiMatcher.exec(input);\n\t}\n\n\t// Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else\n\treplaceMap['%C2'] = '\\uFFFD';\n\n\tvar entries = Object.keys(replaceMap);\n\n\tfor (var i = 0; i < entries.length; i++) {\n\t\t// Replace all decoded components\n\t\tvar key = entries[i];\n\t\tinput = input.replace(new RegExp(key, 'g'), replaceMap[key]);\n\t}\n\n\treturn input;\n}\n\nmodule.exports = function (encodedURI) {\n\tif (typeof encodedURI !== 'string') {\n\t\tthrow new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');\n\t}\n\n\ttry {\n\t\tencodedURI = encodedURI.replace(/\\+/g, ' ');\n\n\t\t// Try the built in decoder first\n\t\treturn decodeURIComponent(encodedURI);\n\t} catch (err) {\n\t\t// Fallback to a more advanced decoder\n\t\treturn customDecodeURIComponent(encodedURI);\n\t}\n};\n","'use strict';\n\nmodule.exports = (string, separator) => {\n\tif (!(typeof string === 'string' && typeof separator === 'string')) {\n\t\tthrow new TypeError('Expected the arguments to be of type `string`');\n\t}\n\n\tif (separator === '') {\n\t\treturn [string];\n\t}\n\n\tconst separatorIndex = string.indexOf(separator);\n\n\tif (separatorIndex === -1) {\n\t\treturn [string];\n\t}\n\n\treturn [\n\t\tstring.slice(0, separatorIndex),\n\t\tstring.slice(separatorIndex + separator.length)\n\t];\n};\n","'use strict';\nmodule.exports = function (obj, predicate) {\n\tvar ret = {};\n\tvar keys = Object.keys(obj);\n\tvar isArr = Array.isArray(predicate);\n\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar key = keys[i];\n\t\tvar val = obj[key];\n\n\t\tif (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {\n\t\t\tret[key] = val;\n\t\t}\n\t}\n\n\treturn ret;\n};\n","'use strict';\nconst strictUriEncode = require('strict-uri-encode');\nconst decodeComponent = require('decode-uri-component');\nconst splitOnFirst = require('split-on-first');\nconst filterObject = require('filter-obj');\n\nconst isNullOrUndefined = value => value === null || value === undefined;\n\nfunction encoderForArrayFormat(options) {\n\tswitch (options.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tconst index = result.length;\n\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), '[', index, ']'].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [\n\t\t\t\t\t...result,\n\t\t\t\t\t[encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('')\n\t\t\t\t];\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), '[]'].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), '[]=', encode(value, options)].join('')];\n\t\t\t};\n\n\t\tcase 'comma':\n\t\tcase 'separator':\n\t\tcase 'bracket-separator': {\n\t\t\tconst keyValueSep = options.arrayFormat === 'bracket-separator' ?\n\t\t\t\t'[]=' :\n\t\t\t\t'=';\n\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\t// Translate null to an empty string so that it doesn't serialize as 'null'\n\t\t\t\tvalue = value === null ? '' : value;\n\n\t\t\t\tif (result.length === 0) {\n\t\t\t\t\treturn [[encode(key, options), keyValueSep, encode(value, options)].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [[result, encode(value, options)].join(options.arrayFormatSeparator)];\n\t\t\t};\n\t\t}\n\n\t\tdefault:\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, encode(key, options)];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), '=', encode(value, options)].join('')];\n\t\t\t};\n\t}\n}\n\nfunction parserForArrayFormat(options) {\n\tlet result;\n\n\tswitch (options.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /\\[(\\d*)\\]$/.exec(key);\n\n\t\t\t\tkey = key.replace(/\\[\\d*\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = {};\n\t\t\t\t}\n\n\t\t\t\taccumulator[key][result[1]] = value;\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /(\\[\\])$/.exec(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tcase 'comma':\n\t\tcase 'separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tconst isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);\n\t\t\t\tconst isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator));\n\t\t\t\tvalue = isEncodedArray ? decode(value, options) : value;\n\t\t\t\tconst newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : value === null ? value : decode(value, options);\n\t\t\t\taccumulator[key] = newValue;\n\t\t\t};\n\n\t\tcase 'bracket-separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tconst isArray = /(\\[\\])$/.test(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!isArray) {\n\t\t\t\t\taccumulator[key] = value ? decode(value, options) : value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst arrayValue = value === null ?\n\t\t\t\t\t[] :\n\t\t\t\t\tvalue.split(options.arrayFormatSeparator).map(item => decode(item, options));\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = arrayValue;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], arrayValue);\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\t}\n}\n\nfunction validateArrayFormatSeparator(value) {\n\tif (typeof value !== 'string' || value.length !== 1) {\n\t\tthrow new TypeError('arrayFormatSeparator must be single character string');\n\t}\n}\n\nfunction encode(value, options) {\n\tif (options.encode) {\n\t\treturn options.strict ? strictUriEncode(value) : encodeURIComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction decode(value, options) {\n\tif (options.decode) {\n\t\treturn decodeComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction keysSorter(input) {\n\tif (Array.isArray(input)) {\n\t\treturn input.sort();\n\t}\n\n\tif (typeof input === 'object') {\n\t\treturn keysSorter(Object.keys(input))\n\t\t\t.sort((a, b) => Number(a) - Number(b))\n\t\t\t.map(key => input[key]);\n\t}\n\n\treturn input;\n}\n\nfunction removeHash(input) {\n\tconst hashStart = input.indexOf('#');\n\tif (hashStart !== -1) {\n\t\tinput = input.slice(0, hashStart);\n\t}\n\n\treturn input;\n}\n\nfunction getHash(url) {\n\tlet hash = '';\n\tconst hashStart = url.indexOf('#');\n\tif (hashStart !== -1) {\n\t\thash = url.slice(hashStart);\n\t}\n\n\treturn hash;\n}\n\nfunction extract(input) {\n\tinput = removeHash(input);\n\tconst queryStart = input.indexOf('?');\n\tif (queryStart === -1) {\n\t\treturn '';\n\t}\n\n\treturn input.slice(queryStart + 1);\n}\n\nfunction parseValue(value, options) {\n\tif (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {\n\t\tvalue = Number(value);\n\t} else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {\n\t\tvalue = value.toLowerCase() === 'true';\n\t}\n\n\treturn value;\n}\n\nfunction parse(query, options) {\n\toptions = Object.assign({\n\t\tdecode: true,\n\t\tsort: true,\n\t\tarrayFormat: 'none',\n\t\tarrayFormatSeparator: ',',\n\t\tparseNumbers: false,\n\t\tparseBooleans: false\n\t}, options);\n\n\tvalidateArrayFormatSeparator(options.arrayFormatSeparator);\n\n\tconst formatter = parserForArrayFormat(options);\n\n\t// Create an object with no prototype\n\tconst ret = Object.create(null);\n\n\tif (typeof query !== 'string') {\n\t\treturn ret;\n\t}\n\n\tquery = query.trim().replace(/^[?#&]/, '');\n\n\tif (!query) {\n\t\treturn ret;\n\t}\n\n\tfor (const param of query.split('&')) {\n\t\tif (param === '') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [key, value] = splitOnFirst(options.decode ? param.replace(/\\+/g, ' ') : param, '=');\n\n\t\t// Missing `=` should be `null`:\n\t\t// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters\n\t\tvalue = value === undefined ? null : ['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options);\n\t\tformatter(decode(key, options), value, ret);\n\t}\n\n\tfor (const key of Object.keys(ret)) {\n\t\tconst value = ret[key];\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\tfor (const k of Object.keys(value)) {\n\t\t\t\tvalue[k] = parseValue(value[k], options);\n\t\t\t}\n\t\t} else {\n\t\t\tret[key] = parseValue(value, options);\n\t\t}\n\t}\n\n\tif (options.sort === false) {\n\t\treturn ret;\n\t}\n\n\treturn (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => {\n\t\tconst value = ret[key];\n\t\tif (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) {\n\t\t\t// Sort object keys, not values\n\t\t\tresult[key] = keysSorter(value);\n\t\t} else {\n\t\t\tresult[key] = value;\n\t\t}\n\n\t\treturn result;\n\t}, Object.create(null));\n}\n\nexports.extract = extract;\nexports.parse = parse;\n\nexports.stringify = (object, options) => {\n\tif (!object) {\n\t\treturn '';\n\t}\n\n\toptions = Object.assign({\n\t\tencode: true,\n\t\tstrict: true,\n\t\tarrayFormat: 'none',\n\t\tarrayFormatSeparator: ','\n\t}, options);\n\n\tvalidateArrayFormatSeparator(options.arrayFormatSeparator);\n\n\tconst shouldFilter = key => (\n\t\t(options.skipNull && isNullOrUndefined(object[key])) ||\n\t\t(options.skipEmptyString && object[key] === '')\n\t);\n\n\tconst formatter = encoderForArrayFormat(options);\n\n\tconst objectCopy = {};\n\n\tfor (const key of Object.keys(object)) {\n\t\tif (!shouldFilter(key)) {\n\t\t\tobjectCopy[key] = object[key];\n\t\t}\n\t}\n\n\tconst keys = Object.keys(objectCopy);\n\n\tif (options.sort !== false) {\n\t\tkeys.sort(options.sort);\n\t}\n\n\treturn keys.map(key => {\n\t\tconst value = object[key];\n\n\t\tif (value === undefined) {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn encode(key, options);\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length === 0 && options.arrayFormat === 'bracket-separator') {\n\t\t\t\treturn encode(key, options) + '[]';\n\t\t\t}\n\n\t\t\treturn value\n\t\t\t\t.reduce(formatter(key), [])\n\t\t\t\t.join('&');\n\t\t}\n\n\t\treturn encode(key, options) + '=' + encode(value, options);\n\t}).filter(x => x.length > 0).join('&');\n};\n\nexports.parseUrl = (url, options) => {\n\toptions = Object.assign({\n\t\tdecode: true\n\t}, options);\n\n\tconst [url_, hash] = splitOnFirst(url, '#');\n\n\treturn Object.assign(\n\t\t{\n\t\t\turl: url_.split('?')[0] || '',\n\t\t\tquery: parse(extract(url), options)\n\t\t},\n\t\toptions && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}\n\t);\n};\n\nexports.stringifyUrl = (object, options) => {\n\toptions = Object.assign({\n\t\tencode: true,\n\t\tstrict: true\n\t}, options);\n\n\tconst url = removeHash(object.url).split('?')[0] || '';\n\tconst queryFromUrl = exports.extract(object.url);\n\tconst parsedQueryFromUrl = exports.parse(queryFromUrl, {sort: false});\n\n\tconst query = Object.assign(parsedQueryFromUrl, object.query);\n\tlet queryString = exports.stringify(query, options);\n\tif (queryString) {\n\t\tqueryString = `?${queryString}`;\n\t}\n\n\tlet hash = getHash(object.url);\n\tif (object.fragmentIdentifier) {\n\t\thash = `#${encode(object.fragmentIdentifier, options)}`;\n\t}\n\n\treturn `${url}${queryString}${hash}`;\n};\n\nexports.pick = (input, filter, options) => {\n\toptions = Object.assign({\n\t\tparseFragmentIdentifier: true\n\t}, options);\n\n\tconst {url, query, fragmentIdentifier} = exports.parseUrl(input, options);\n\treturn exports.stringifyUrl({\n\t\turl,\n\t\tquery: filterObject(query, filter),\n\t\tfragmentIdentifier\n\t}, options);\n};\n\nexports.exclude = (input, filter, options) => {\n\tconst exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);\n\n\treturn exports.pick(input, exclusionFilter, options);\n};\n","(function() {\n  var base64map\n      = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n  crypt = {\n    // Bit-wise rotation left\n    rotl: function(n, b) {\n      return (n << b) | (n >>> (32 - b));\n    },\n\n    // Bit-wise rotation right\n    rotr: function(n, b) {\n      return (n << (32 - b)) | (n >>> b);\n    },\n\n    // Swap big-endian to little-endian and vice versa\n    endian: function(n) {\n      // If number given, swap endian\n      if (n.constructor == Number) {\n        return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n      }\n\n      // Else, assume array and swap all items\n      for (var i = 0; i < n.length; i++)\n        n[i] = crypt.endian(n[i]);\n      return n;\n    },\n\n    // Generate an array of any length of random bytes\n    randomBytes: function(n) {\n      for (var bytes = []; n > 0; n--)\n        bytes.push(Math.floor(Math.random() * 256));\n      return bytes;\n    },\n\n    // Convert a byte array to big-endian 32-bit words\n    bytesToWords: function(bytes) {\n      for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n        words[b >>> 5] |= bytes[i] << (24 - b % 32);\n      return words;\n    },\n\n    // Convert big-endian 32-bit words to a byte array\n    wordsToBytes: function(words) {\n      for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n        bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n      return bytes;\n    },\n\n    // Convert a byte array to a hex string\n    bytesToHex: function(bytes) {\n      for (var hex = [], i = 0; i < bytes.length; i++) {\n        hex.push((bytes[i] >>> 4).toString(16));\n        hex.push((bytes[i] & 0xF).toString(16));\n      }\n      return hex.join('');\n    },\n\n    // Convert a hex string to a byte array\n    hexToBytes: function(hex) {\n      for (var bytes = [], c = 0; c < hex.length; c += 2)\n        bytes.push(parseInt(hex.substr(c, 2), 16));\n      return bytes;\n    },\n\n    // Convert a byte array to a base-64 string\n    bytesToBase64: function(bytes) {\n      for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n        var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n        for (var j = 0; j < 4; j++)\n          if (i * 8 + j * 6 <= bytes.length * 8)\n            base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n          else\n            base64.push('=');\n      }\n      return base64.join('');\n    },\n\n    // Convert a base-64 string to a byte array\n    base64ToBytes: function(base64) {\n      // Remove non-base-64 characters\n      base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n      for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n          imod4 = ++i % 4) {\n        if (imod4 == 0) continue;\n        bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n            & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n            | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n      }\n      return bytes;\n    }\n  };\n\n  module.exports = crypt;\n})();\n","var charenc = {\n  // UTF-8 encoding\n  utf8: {\n    // Convert a string to a byte array\n    stringToBytes: function(str) {\n      return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n    },\n\n    // Convert a byte array to a string\n    bytesToString: function(bytes) {\n      return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n    }\n  },\n\n  // Binary encoding\n  bin: {\n    // Convert a string to a byte array\n    stringToBytes: function(str) {\n      for (var bytes = [], i = 0; i < str.length; i++)\n        bytes.push(str.charCodeAt(i) & 0xFF);\n      return bytes;\n    },\n\n    // Convert a byte array to a string\n    bytesToString: function(bytes) {\n      for (var str = [], i = 0; i < bytes.length; i++)\n        str.push(String.fromCharCode(bytes[i]));\n      return str.join('');\n    }\n  }\n};\n\nmodule.exports = charenc;\n","/*!\n * Determine if an object is a Buffer\n *\n * @author   Feross Aboukhadijeh <https://feross.org>\n * @license  MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n  return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n  return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n  return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n","(function(){\r\n  var crypt = require('crypt'),\r\n      utf8 = require('charenc').utf8,\r\n      isBuffer = require('is-buffer'),\r\n      bin = require('charenc').bin,\r\n\r\n  // The core\r\n  md5 = function (message, options) {\r\n    // Convert to byte array\r\n    if (message.constructor == String)\r\n      if (options && options.encoding === 'binary')\r\n        message = bin.stringToBytes(message);\r\n      else\r\n        message = utf8.stringToBytes(message);\r\n    else if (isBuffer(message))\r\n      message = Array.prototype.slice.call(message, 0);\r\n    else if (!Array.isArray(message) && message.constructor !== Uint8Array)\r\n      message = message.toString();\r\n    // else, assume byte array already\r\n\r\n    var m = crypt.bytesToWords(message),\r\n        l = message.length * 8,\r\n        a =  1732584193,\r\n        b = -271733879,\r\n        c = -1732584194,\r\n        d =  271733878;\r\n\r\n    // Swap endian\r\n    for (var i = 0; i < m.length; i++) {\r\n      m[i] = ((m[i] <<  8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n             ((m[i] << 24) | (m[i] >>>  8)) & 0xFF00FF00;\r\n    }\r\n\r\n    // Padding\r\n    m[l >>> 5] |= 0x80 << (l % 32);\r\n    m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n    // Method shortcuts\r\n    var FF = md5._ff,\r\n        GG = md5._gg,\r\n        HH = md5._hh,\r\n        II = md5._ii;\r\n\r\n    for (var i = 0; i < m.length; i += 16) {\r\n\r\n      var aa = a,\r\n          bb = b,\r\n          cc = c,\r\n          dd = d;\r\n\r\n      a = FF(a, b, c, d, m[i+ 0],  7, -680876936);\r\n      d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n      c = FF(c, d, a, b, m[i+ 2], 17,  606105819);\r\n      b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n      a = FF(a, b, c, d, m[i+ 4],  7, -176418897);\r\n      d = FF(d, a, b, c, m[i+ 5], 12,  1200080426);\r\n      c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n      b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n      a = FF(a, b, c, d, m[i+ 8],  7,  1770035416);\r\n      d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n      c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n      b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n      a = FF(a, b, c, d, m[i+12],  7,  1804603682);\r\n      d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n      c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n      b = FF(b, c, d, a, m[i+15], 22,  1236535329);\r\n\r\n      a = GG(a, b, c, d, m[i+ 1],  5, -165796510);\r\n      d = GG(d, a, b, c, m[i+ 6],  9, -1069501632);\r\n      c = GG(c, d, a, b, m[i+11], 14,  643717713);\r\n      b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n      a = GG(a, b, c, d, m[i+ 5],  5, -701558691);\r\n      d = GG(d, a, b, c, m[i+10],  9,  38016083);\r\n      c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n      b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n      a = GG(a, b, c, d, m[i+ 9],  5,  568446438);\r\n      d = GG(d, a, b, c, m[i+14],  9, -1019803690);\r\n      c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n      b = GG(b, c, d, a, m[i+ 8], 20,  1163531501);\r\n      a = GG(a, b, c, d, m[i+13],  5, -1444681467);\r\n      d = GG(d, a, b, c, m[i+ 2],  9, -51403784);\r\n      c = GG(c, d, a, b, m[i+ 7], 14,  1735328473);\r\n      b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n      a = HH(a, b, c, d, m[i+ 5],  4, -378558);\r\n      d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n      c = HH(c, d, a, b, m[i+11], 16,  1839030562);\r\n      b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n      a = HH(a, b, c, d, m[i+ 1],  4, -1530992060);\r\n      d = HH(d, a, b, c, m[i+ 4], 11,  1272893353);\r\n      c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n      b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n      a = HH(a, b, c, d, m[i+13],  4,  681279174);\r\n      d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n      c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n      b = HH(b, c, d, a, m[i+ 6], 23,  76029189);\r\n      a = HH(a, b, c, d, m[i+ 9],  4, -640364487);\r\n      d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n      c = HH(c, d, a, b, m[i+15], 16,  530742520);\r\n      b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n      a = II(a, b, c, d, m[i+ 0],  6, -198630844);\r\n      d = II(d, a, b, c, m[i+ 7], 10,  1126891415);\r\n      c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n      b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n      a = II(a, b, c, d, m[i+12],  6,  1700485571);\r\n      d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n      c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n      b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n      a = II(a, b, c, d, m[i+ 8],  6,  1873313359);\r\n      d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n      c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n      b = II(b, c, d, a, m[i+13], 21,  1309151649);\r\n      a = II(a, b, c, d, m[i+ 4],  6, -145523070);\r\n      d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n      c = II(c, d, a, b, m[i+ 2], 15,  718787259);\r\n      b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n      a = (a + aa) >>> 0;\r\n      b = (b + bb) >>> 0;\r\n      c = (c + cc) >>> 0;\r\n      d = (d + dd) >>> 0;\r\n    }\r\n\r\n    return crypt.endian([a, b, c, d]);\r\n  };\r\n\r\n  // Auxiliary functions\r\n  md5._ff  = function (a, b, c, d, x, s, t) {\r\n    var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n    return ((n << s) | (n >>> (32 - s))) + b;\r\n  };\r\n  md5._gg  = function (a, b, c, d, x, s, t) {\r\n    var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n    return ((n << s) | (n >>> (32 - s))) + b;\r\n  };\r\n  md5._hh  = function (a, b, c, d, x, s, t) {\r\n    var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n    return ((n << s) | (n >>> (32 - s))) + b;\r\n  };\r\n  md5._ii  = function (a, b, c, d, x, s, t) {\r\n    var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n    return ((n << s) | (n >>> (32 - s))) + b;\r\n  };\r\n\r\n  // Package private blocksize\r\n  md5._blocksize = 16;\r\n  md5._digestsize = 16;\r\n\r\n  module.exports = function (message, options) {\r\n    if (message === undefined || message === null)\r\n      throw new Error('Illegal argument ' + message);\r\n\r\n    var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n    return options && options.asBytes ? digestbytes :\r\n        options && options.asString ? bin.bytesToString(digestbytes) :\r\n        crypt.bytesToHex(digestbytes);\r\n  };\r\n\r\n})();\r\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport RestrictedEventEmitter from '../../models/utils/RestrictedEventEmitter';\nimport type CloudDriver from '.';\nimport type { LibraryData } from '../../models/data/LibraryData';\nimport type { AssetLinkList, AdobeAsset, SAMError } from '../../../index';\nimport { syncGroupPath } from '../../config/constants';\nimport type IEvent from '../../../core/IEvent';\n\nexport default class AssetNotificationManager extends RestrictedEventEmitter {\n    // The callback to invoke when libraries are updated.\n    private _changeCallback?: (assetIds: string[]) => any;\n\n    // List of library asset ids to monitor - this comes from SAM, and any ids we add to this list will be auto-monitored by ONS.\n    private _librariesToMonitor?: AssetLinkList;\n\n    private _syncGroupListener?: {\n        notify: () => void;\n        asset?: AdobeAsset;\n    };\n\n    constructor(private _driver: CloudDriver) {\n        super();\n    }\n\n    connect() {\n        this._librariesToMonitor = this._driver._core?.assetLinkManager.createList();\n        this._librariesToMonitor?.on('notified', this._onChangeCallback);\n    }\n\n    disconnect() {\n        this._changeCallback = undefined;\n        this._librariesToMonitor?.clear();\n        this._librariesToMonitor?.off('notified', this._onChangeCallback);\n        this._librariesToMonitor = undefined;\n    }\n\n    get isConnected() {\n        return !!this._librariesToMonitor;\n    }\n\n    async setWatchedLibraries(libraries: LibraryData[], callback: (assetIds: string[]) => any) {\n        // No-op if we haven't been initialized.\n        if (!this._librariesToMonitor) {\n            return;\n        }\n\n        const librariesToMonitor = this._librariesToMonitor;\n        const assetIds = new Set(libraries.map(library => library.assetId));\n\n        // Remove any links no longer being watched\n        librariesToMonitor.monitoredAssetIDs.forEach(id => !assetIds.has(id) && librariesToMonitor.removeAssetID(id));\n\n        // Make sure we're watching all the assets we need to watch (this is a no-op if already being monitored)\n        assetIds.forEach(id => id && librariesToMonitor.addAssetID(id));\n        this._changeCallback = callback;\n    }\n\n    private _onChangeCallback = (event: IEvent, sender: AssetLinkList, payload?: any) => {\n        const assetIds = payload as string[];\n        this._changeCallback?.(assetIds);\n    };\n\n    async addWatchedLibrary(library: LibraryData) {\n        library.assetId && this._librariesToMonitor?.addAssetID(library.assetId);\n    }\n\n    removeWatchedLibrary(library: LibraryData) {\n        library.assetId && this._librariesToMonitor?.removeAssetID(library.assetId);\n    }\n\n    // Shallow watch of libraries sync group so we can tell when libraries are added/deleted/renamed/moved\n    // Note: Shallow watch is not working, it's actually a deep watch until eTag propogation is turned off.\n    async addLibrariesSyncGroupListener(cb: () => void) {\n        // ensure listener is only added once\n        if (this._syncGroupListener || !cb) {\n            return;\n        }\n        this._syncGroupListener = { notify: cb };\n        // SAM keeps weak references to AdobeAssets/Lists, so clients must keep a strong reference to stop SAM from garbage collecting them.\n        // Otherwise SAM would hear the ONS event but the AdobeAsset notification would not occur. (See SAM-2711)\n        let syncGroupDirectory = undefined;\n        try {\n            syncGroupDirectory = await this._driver._core?.hostAssetContext.getAssetWithRepoPath(syncGroupPath);\n        } catch (error) {\n            if ((error as SAMError).code === 21) {\n                // If the sync group directory (assets/adobe-libraries) does not exist, we can't listen for changes.\n                // This is expected if the user has not yet created a library.\n                return;\n            }\n            throw error;\n        }\n        if (!syncGroupDirectory) {\n            delete this._syncGroupListener;\n            return;\n        }\n        this._syncGroupListener.asset = syncGroupDirectory;\n        syncGroupDirectory.on('change', cb);\n    }\n\n    removeLibrariesSyncGroupListener() {\n        if (this._syncGroupListener) {\n            const { asset, notify } = this._syncGroupListener;\n            asset?.off('change', notify);\n            delete this._syncGroupListener;\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nfunction _fetchNext(generator: AsyncGenerator, index: number) {\n    return generator.next().then(result => ({ result, index }));\n}\n\n/**\n * Utility to allow combining async generators in a way that runs their tasks in parallel\n *\n * @export\n * @template T\n * @param {...Array<AsyncGenerator<T>>} generators generators to combine\n * @returns {AsyncGenerator<T>} A combined generator that runs individual generators in parallel\n */\nexport async function *combineGenerators<T>(...generators: Array<AsyncGenerator<T>>): AsyncGenerator<T> {\n    const results = generators.map(_fetchNext);\n    let finalized = results.length;\n    while (finalized) {\n        const yielded = await Promise.race(results);\n        if (!yielded.result.done) {\n            yield yielded.result.value as Awaited<T>;\n            results[yielded.index] = _fetchNext(generators[yielded.index], yielded.index);\n        } else {\n            results[yielded.index] = new Promise(() => {\n                /* NOOP */\n            });\n            finalized--;\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport Logger from '../../utils/Logger';\n\n// Fallback implementation of localStorage in case we're not running in a standard browser environment (e.g. node.js)\nclass InMemoryStorage implements Storage {\n    private _data = new Map();\n\n    get length() {\n        return this._data.size;\n    }\n\n    key(index: number) {\n        return Array.from(this._data.keys())[index];\n    }\n    getItem(key: string) {\n        return this._data.get(key);\n    }\n    setItem(key: string, value: any) {\n        this._data.set(key, value);\n    }\n    removeItem(key: string) {\n        this._data.delete(key);\n    }\n    clear() {\n        this._data.clear();\n    }\n}\n\n/**\n * Local/Session Storage interface.\n * Allows getting and setting persistent settings that are local to the\n * current user session of the Libraries JS API.\n * Local Storage: Stores data to disk which is available across tabs/windows to the same user in the same browser.\n * Session Storage: Stores data to memory which is available only to the current tab.\n */\nexport class StorageInterface {\n    _storage: Storage;\n    _storageKey: string;\n    _settings = new Map();\n\n    constructor(storageKey: string, storage?: Storage) {\n        this._storageKey = storageKey;\n        this._storage = storage ?? (typeof window !== 'undefined' ? window.localStorage : new InMemoryStorage());\n        // Restore any previous settings saved to this storage key.\n        this._load();\n    }\n\n    // Expose the storage values\n    entries() {\n        return this._settings.entries();\n    }\n\n    setItem(key: string, value: any) {\n        this._settings.set(key, value);\n        // Write the current settings to storage.\n        this._save();\n    }\n\n    getItem(key: string) {\n        return this._settings.get(key);\n    }\n\n    _setItem(key: string, value: any) {\n        this._storage.setItem(key, value);\n    }\n\n    _load() {\n        const settingsStr = this._storage.getItem(this._storageKey);\n        if (settingsStr) {\n            try {\n                this._settings = new Map(JSON.parse(settingsStr));\n            } catch (e) {\n                Logger.error('Error restoring previous settings.');\n                // Remove the invalid settings.\n                this._storage.removeItem(this._storageKey);\n            }\n        }\n    }\n\n    _save() {\n        const settingsStr = JSON.stringify(Array.from(this._settings.entries()));\n        this._setItem(this._storageKey, settingsStr);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Project, Gradient } from '../../../../index';\nimport type { GradientData, TeamData } from '../../../models/Team';\n\nexport function mapProjectToTeamData(project: Project): TeamData {\n    return {\n        name: project.name,\n        id: project.id,\n        owner: project.storageAssignee,\n        // This should always be defined now, but SAM.js typed it as optional for backward compatibility.\n        ownerName: project.storageAssignee.displayName ?? '',\n        // All project users can edit the project.\n        isWritable: true\n    };\n}\n\nexport function mapGradientToGradientData(gradientData: Gradient): GradientData {\n    return {\n        type: gradientData.type,\n        angle: gradientData.angle,\n        stops: gradientData.stops\n    };\n}\n\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * CloudDriver\n * @packageDocumentation\n * @module CloudDriver\n */\n\nimport type { ElementData } from '../../models/data/ElementData';\nimport type { GroupData } from '../../models/data/GroupData';\nimport type { LibraryData } from '../../models/data/LibraryData';\nimport type { TeamData } from '../../models/Team';\nimport type Team from '../../models/Team';\nimport type { BlockDownloadData } from '../../models/data/BlockDownloadData';\nimport type { VersionData } from '../../models/data/VersionData';\nimport type { CollaboratorData } from '../../models/data/CollaboratorData';\nimport AsyncResponse from '../AsyncResponse';\nimport type Representation from '../../models/Representation';\n\nimport type { Env } from '../../config/CloudDriverConfig';\nimport cloudDriverConfig from '../../config/CloudDriverConfig';\nimport type Library from '../../models/LibraryStub';\nimport type SAMLibrary from '../../../libraries/Library';\nimport type Element from '../../models/Element';\nimport type {\n    PaginatedResponse,\n    SearchFilters,\n    ElementSort,\n    GetLibraryOptions,\n    GetElementsOptions,\n    FetchRequestInit,\n    LibraryListFilters\n} from '../Driver';\nimport Driver from '../Driver';\nimport LocalDriver from '../LocalDriver';\nimport SingleOperation from './SingleOperation';\nimport MoveCopyElementOperation from './MoveCopyElementOperation';\nimport BatchOperation from './BatchOperation';\nimport ContentOperation from './ContentOperation';\nimport ParallelOperation from './ParallelOperation';\n\nimport { extractUserDataFromToken, extractExpiryFromToken, useEdge } from './utils';\nimport { isLibrariesResponse, isTeamsResponse } from './utils/responseUtils';\nimport { parseLinks } from './utils/rapiResponseUtils';\nimport type {\n    ElementResponse,\n    ElementsResponse,\n    LibraryResponse,\n    LibrariesResponse,\n    TeamsResponse,\n    RepresentationPreflightResponse,\n    SearchElementsResponse\n} from './utils/melvilleModelMappers';\nimport {\n    mapResponseToLibraryData,\n    mapResponseToElementData,\n    mapResponseToTeamData,\n    mapSearchResponseToElementData\n} from './utils/melvilleModelMappers';\nimport type {\n    Link } from './utils/rapiModelMappers';\nimport {\n    RapiLinkType,\n    mapManifestToLibraryData,\n    mapResponseToCollaboratorData,\n    mapResponseToVersionData,\n    mapResponseToBlockDownloadData\n} from './utils/rapiModelMappers';\nimport RequestError, {\n    getRequestError,\n    getSAMRequestError,\n    getRequestErrorFromStatus\n} from '../../errors/RequestError';\nimport Configuration from '../../models/Configuration';\nimport type ApplicationAction from '../../models/ApplicationAction';\nimport LibraryError from '../../errors/LibraryError';\nimport {\n    melvilleFirstUseEtag,\n    tlsDiscoveryPortRange,\n    processDiscoveryRetryDelay,\n    processDiscoveryTimeout,\n    rapiMaxSingleTransferSize,\n    REQUEST_NOT_NEEDED,\n    ABORT_ERROR,\n    MelvilleParamsAsHeaders,\n    HttpStatus,\n    GenStudioProjectName\n} from '../../config/constants';\nimport { stringify } from 'query-string';\nimport type {\n    AssetVersion,\n    AssetVersionConfig,\n    IItemList,\n    IPersistentCache,\n    AssetContext,\n    SAMError,\n    CollaboratorConfig } from '../../../index';\nimport {\n    AssetListStatus,\n    AssetVersionOrder,\n    STATE_CHANGED,\n    CollaboratorOrder,\n    ProjectOrder,\n    ProjectFilter\n} from '../../../index';\nimport type Resource from '../../../assets/Resource';\nimport { combineSignals, abortSignalReasons } from '../../utils/SignalUtils';\nimport Logger from '../../utils/Logger';\nimport md5 from 'md5';\nimport { getScopedStorageKey, sleep } from '../../utils';\nimport uriTemplates from 'uri-templates';\nimport { v4 as uuid } from 'uuid';\nimport { getRenditionUrl } from '../../utils/RenditionUtils';\nimport { omitUndefined } from '../utils/operationUtils';\nimport AssetNotificationManager from './AssetNotificationManager';\nimport type { RenditionSize } from '../../types';\nimport { combineGenerators } from '../../utils/GeneratorUtils';\nimport { StorageInterface } from '../utils/StorageInterface';\nimport { mapGradientToGradientData, mapProjectToTeamData } from './utils/samUtils';\n// import { IndexKey } from '../../models/ModelCache';\nimport { getImageDimensions } from '../../utils/FileUtils';\nimport { setTracingSpanAttribute, trace, traceableAs } from '../../../core/decorators/trace';\nimport type { CCLibrariesOptions } from '@sam-js-src/library-contents/CCLibraries';\nimport { waitForListLoad } from '../../../utils/waitForListLoad';\nimport setURLSearchParams from '../../../utils/searchParams';\n\ntype LibraryProcessResponse = {\n    token: string;\n    hostname: string;\n};\n\nexport type Params = {\n    env: Env;\n    token: string;\n    fetch?: (path: string, init?: RequestInit & { headers?: { [s: string]: string } }) => Promise<Response>;\n    localStorage?: Storage;\n    samPersistentCache?: IPersistentCache;\n    samDisableOns?: boolean;\n    refreshAccessToken?: () => Promise<string>;\n    config?: { processInfo: { analyticsEnabled?: boolean; codeVersion: string }; ignoreRenditionGrids?: boolean };\n    handleConnectRetries?: number;\n};\n\nconst defaultElementSort: ElementSort = {\n    field: 'modifiedDate',\n    direction: 'descending'\n};\n\nconst sortFieldMap = {\n    modifiedDate: 'modified_date',\n    name: 'name'\n};\n\nexport type ClientInfo = {\n    deviceId: string;\n    device: string;\n    app: string;\n};\n\n@traceableAs('CloudDriver')\nexport default class CloudDriver extends Driver<Params> {\n    private _env?: Env;\n    private _clientId?: string;\n    private _analyticsEnabled?: boolean;\n    private _codeVersion?: string;\n    private _ignoreRenditionGrids?: boolean;\n    private _refreshAccessToken?: () => Promise<string>;\n    private _fetch: (path: string, init?: RequestInit & { headers?: { [s: string]: string } }) => Promise<Response>\n    = fetch;\n    protected _notificationManager = new AssetNotificationManager(this);\n\n    protected _operationTypes = [\n        MoveCopyElementOperation,\n        SingleOperation,\n        BatchOperation,\n        ContentOperation,\n        ParallelOperation\n    ];\n\n    // TODO-R[SHARED-5281]: will be removed\n    getLibrary(library: SAMLibrary, options?: GetLibraryOptions): AsyncGenerator<Partial<LibraryData>> {\n        return this.getLibraryByAssetId(library.id as string, options);\n    }\n\n    getElements(library: SAMLibrary, ...args: any[]) {\n        return this._getElementsByAssetId(library.id as string, ...args);\n    }\n\n    async getElementsPage(\n        library: SAMLibrary,\n        start: number = 0,\n        limit: number = 100,\n        sort: ElementSort = defaultElementSort,\n        _etag?: string,\n    ): Promise<ElementsResponse> {\n        const orderBy = `${sort.direction === 'descending' ? '-' : ''}${sortFieldMap[sort.field]}`;\n\n        const headers: Record<string, string> = {\n            start: start.toString(),\n            limit: limit.toString(),\n            orderBy,\n            selector: 'default,representations,details'\n        };\n\n        return await this.fetch(\n            `/api/v1/libraries/${library.id}/elements`, { headers }).\n            then(res => res.json());\n    }\n\n    // TODO-R[SHARED-5281]: will be removed\n    getRemovedElements(library: SAMLibrary, ...args: any[]) {\n        return this._getRemovedElementsByAssetId(library.id as string, ...args);\n    }\n\n    // TODO-R[SHARED-5281]: will be removed\n    getDocumentationElements(library: SAMLibrary, ...args: any[]) {\n        return this._getDocumentationElementsByAssetId(library.id as string, ...args);\n    }\n\n    getElement(library: SAMLibrary, elementId: string): Promise<ElementData> {\n        return this._getElement(library.id as string, elementId);\n    }\n\n    protected async _handleConnected(data: Params) {\n        const userData = extractUserDataFromToken(data.token);\n        this._localStorage = new StorageInterface(getScopedStorageKey(userData?.user, 'cloud'), data.localStorage);\n        this._env = data.env;\n        this._token = data.token;\n        this._refreshAccessToken = data.refreshAccessToken;\n        this._clientId = userData?.user?.clientId as string;\n        this._analyticsEnabled = data.config?.processInfo?.analyticsEnabled || false;\n        this._ignoreRenditionGrids = data.config?.ignoreRenditionGrids || false;\n        this._codeVersion = data.config?.processInfo?.codeVersion as string;\n        this._fetch = data.fetch || fetch.bind(globalThis);\n\n        this._notificationManager.connect();\n\n        // This is synchronous, but we want the signature to be the same as the LocalDriver, which is not.\n        await this.getConfiguration();\n    }\n\n    protected _handleDisconnected() {\n        this._notificationManager?.disconnect();\n    }\n\n    async getConfiguration(): Promise<Configuration> {\n        const configurationData = this.getLocalSettings();\n        const userData = extractUserDataFromToken(this._token as string);\n        this._config = new Configuration({\n            ...configurationData,\n            ...userData,\n            environment: this._env as Env,\n            processInfo: {\n                analyticsEnabled: this._analyticsEnabled,\n                codeVersion: this._codeVersion as string,\n                syncingEnabled: true\n            },\n            ignoreRenditionGrids: this._ignoreRenditionGrids\n        });\n        return this.config;\n    }\n\n    get driverConfig() {\n        return cloudDriverConfig[this._env as Env];\n    }\n\n    updateOptions(options: CCLibrariesOptions): void {\n        this._options = options;\n    }\n\n    fetchAccessToken(_userId: string, _clientId: string, _clientSecret: string, _scopes: string) {\n        // NOTE: This will always return the access token for the host, which means we need to make sure\n        // all of the client IDs used in the panel match the host's client ID\n        return Promise.resolve({\n            access_token: this._token,\n            expires_in: extractExpiryFromToken(this._token as string)\n        });\n    }\n\n    /* Library operations */\n\n    // Note that fetching by library id is not recommended, as melville has to make an additional request to find the assetId.\n    // Using the id also only works on private libraries. So use the assetId whenever possible.\n    @trace\n    async getLibraryById(id: Library['id'] | Library['assetId']) {\n        if (!id) {\n            return;\n        }\n        const { value } = await this.getLibraryByAssetId(id).next();\n        return value;\n    }\n\n    async *getLibraryByAssetId(assetId: string, options: GetLibraryOptions = {}): AsyncGenerator<Partial<LibraryData>> {\n        // If we are a new library, attempting to load our contents will just throw errors. Wait till we have a valid ID/assetId\n        // before refreshing ourselves\n        if (!assetId) {\n            return {};\n        }\n\n        let etag = options.etag;\n\n        const selector: LibraryListFilters['selector'] = [ 'default' ];\n        if (options.getRenditionGrid) {\n            selector.push('rendition_grid');\n        }\n        if (options.getAppMetadata) {\n            selector.push('app_metadata');\n        }\n        // Case 1: Not requesting elements. Load library via Melville.\n        if (!options.elementParams) {\n            try {\n                yield this._getLibrary(assetId, etag, selector);\n            } catch (error) {\n                if (!(error instanceof RequestError && error.requestErrorCode === 'NOT_MODIFIED')) {\n                    throw error;\n                }\n            }\n            return;\n        }\n\n        // Case 2: Want to load elements for the first time. Use Melville AND manifest. If manifest finishes first,\n        // cancel Melville requests.\n\n        const manifestPromise = this._getManifest(assetId, options);\n        manifestPromise.then(() => {\n            const controller = options.elementParams?.abortController;\n            if (controller) {\n                controller.abort();\n                abortSignalReasons.give(controller, REQUEST_NOT_NEEDED);\n            }\n        });\n\n        if (options.elementParams?.loadProgressively) {\n            try {\n                try {\n                    const libraryResponse = await this._getLibrary(assetId, etag, selector);\n                    etag = libraryResponse.etag;\n                    yield libraryResponse;\n                } catch (error) {\n                    if (!(error instanceof RequestError && error.requestErrorCode === 'NOT_MODIFIED' && options.elementParams)) {\n                        throw error;\n                    }\n                }\n                yield* this._getAllElements(assetId, { ...options.elementParams, etag });\n            } catch (error) {\n                // If it's an abort, eat it. Otherwise, throw it.\n                // Also swallow the 404. If melville 404s, R-API may still succeed. If R-API fails, it will then throw.\n                if (\n                    !options.elementParams.abortController?.signal.aborted\n                    && !(error instanceof RequestError && error.requestErrorCode === 'NOT_FOUND')\n                ) {\n                    throw error;\n                }\n            }\n        }\n\n        // Case 3: Elements are loaded. Use only manifest to update (do not call Melville)\n        yield manifestPromise;\n    }\n\n    private _getLibrary(assetId: string, etag?: string, selector: LibraryListFilters['selector'] = [ 'default' ]) {\n        const headers: { [s: string]: string } = {};\n\n        // If there is no etag, we need to manually override if-none-match so it does not use the etag\n        headers['if-none-match'] = etag || '*';\n\n        const searchParams = new URLSearchParams({ selector } as any);\n        if (selector.includes('app_metadata')) {\n            // TODO: Remove this once Melville allows Cache-Control in their CORS settings\n            // When fetching app_metadata, set a random query param to bypass the browser cache\n            searchParams.set('randomizer', uuid());\n        }\n        const url = `/api/v1/libraries/${assetId}?${searchParams.toString()}`;\n        return this.fetch(url, { headers })\n            .then(res => res.json())\n            .then((res: LibraryResponse) =>\n                mapResponseToLibraryData(res, this._options.readOnly, selector?.includes('rendition_grid'))\n            );\n    }\n\n    /**\n     * Loads the manifest for the given library, if necessary.\n     * @param assetId The cloud ID of the asset.\n     * @returns The LibraryData derived from the loaded manifest.\n     */\n    private async _getManifest(assetId: string, options: GetLibraryOptions): Promise<Partial<LibraryData>> {\n        let asset;\n        try {\n            asset = await this._core?.hostAssetContext.getAssetWithCloudID(assetId);\n        } catch (error) {\n            throw getSAMRequestError(error as SAMError);\n        }\n\n        if (!asset || asset?.isDiscarded) {\n            // Though it's possible to read a manifest on an discarded Asset,\n            // we want to throw a 404 to let library.load() know to remove the model from the cache\n            throw getRequestErrorFromStatus(404);\n        }\n\n        try {\n            const resources: Resource[] = [ asset.manifest ];\n            if (options.getAppMetadata) {\n                resources.push(asset.appMetadata);\n            }\n\n            // Load all resources in parallel.\n            await Promise.all(resources.map(resource => !resource.isLoaded && resource.load()));\n\n            const libraryData = mapManifestToLibraryData(asset);\n            // Since we're using asset events from ONS directly to refresh the library, we need to unload the manifest after fetching it.\n            // Otherwise, when we get a notification, we'll use the stale data of the previous manifest before SAM has refreshed it.\n            // (Previously we could just keep the manifest loaded since we were listening to change events on the SAM model, but that's\n            // more expensive since it requires resolving every library to an AdobeAsset in order to get notifications).\n            asset.manifest.unload();\n            return libraryData;\n        } catch (error) {\n            throw getSAMRequestError(error as SAMError);\n        }\n    }\n\n    /**\n     * Fetch libraries and optionally rendition grids\n     */\n    async *getLibraries(\n        signal?: AbortSignal,\n        getRenditionGrids: boolean = true\n    ): AsyncGenerator<PaginatedResponse<LibraryData>> {\n        if (this._options.enableBrandLifecycleManagement) {\n            // Fetch project data\n            const project = await this.getProjectByName(GenStudioProjectName);\n            if (!project) {\n                Logger.error('[CLOUD DRIVER] M3 - Adobe GenStudio Brands project not found.');\n                // Mo without access to the project.\n                // Sally account without project created yet.\n                const publishedFilters: LibraryListFilters = {\n                    itemFilter: [ 'publishedBrands' ],\n                    roles: [ 'brand' ]\n                };\n                yield* this.getLibrariesList(signal, publishedFilters);\n                return;\n            } else {\n                Logger.info('[CLOUD DRIVER] M3 - Loading brands inside project.');\n                const projectFilter: LibraryListFilters = {\n                    team: [ project.id ],\n                    roles: [ 'brand' ]\n                };\n                yield* this.getLibrariesList(signal, projectFilter);\n                return;\n            }\n        } else {\n            Logger.info('[CLOUD DRIVER] M2 - Loading all libraries.');\n            const personalFilters: LibraryListFilters = {\n                owner: [ 'private', 'incoming' ],\n                // rendition_grid response contains all the same 'default' properties for each library, plus \"rendition_grid\" and `\"renditionGridMissing\": false`\n                selector: getRenditionGrids ? [ 'rendition_grid' ] : [ 'default' ]\n            };\n            const publicFilters: LibraryListFilters = {\n                owner: [ 'public' ],\n                selector: getRenditionGrids ? [ 'rendition_grid', 'details' ] : [ 'default', 'details' ]\n            };\n\n            // To avoid waiting for one generator to finish before the other begins (i.e. private before public libraries),\n            // we combine them so they run in parallel, and yield each page as soon as it's available.\n            const pageGenerators = [\n                this.getLibrariesList(signal, personalFilters),\n                this.getLibrariesList(signal, publicFilters)\n            ];\n\n            if (this._options.includeApprovedBrandsInLibraries) {\n                Logger.info('[CLOUD DRIVER] M2 - Loading approved brands.');\n                pageGenerators.push(this.getApprovedBrandLibraries(signal));\n            }\n\n            yield* combineGenerators(...pageGenerators);\n        }\n    }\n\n    async *getApprovedBrandLibraries(signal?: AbortSignal): AsyncGenerator<PaginatedResponse<LibraryData>> {\n        yield* this.fetchAllApprovedBrandPages('/api/v1/search', this._getLibrariesResponseMapper(), signal);\n    }\n\n    async *fetchAllApprovedBrandPages<T, U>(\n        firstUrl: string,\n        responseMapper: (response: T) => PaginatedResponse<U>,\n        signal?: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<U>> {\n        let nextUrl = firstUrl;\n        while (nextUrl) {\n            const response = await this.fetch(nextUrl, {\n                signal,\n                method: 'POST',\n                body: JSON.stringify({\n                    library_roles_type: [ 'approvedbrand' ]\n                }),\n                headers: {\n                    owner: 'all',\n                    'content-type': 'application/json'\n                }\n            }).then(res => res.json());\n            yield responseMapper(response);\n            nextUrl = response._links?.next?.href;\n        }\n    }\n\n    async *getLibrariesList(\n        signal?: AbortSignal,\n        filters?: LibraryListFilters\n    ): AsyncGenerator<PaginatedResponse<LibraryData>> {\n        yield* this.fetchAllPages(\n            this._getLibrariesURL(filters),\n            { headers: { directive: 'public-libraries-list-v2' } },\n            this._getLibrariesResponseMapper(filters),\n            signal\n        );\n    }\n\n    async *getLibrariesPage(\n        signal?: AbortSignal,\n        filters?: LibraryListFilters\n    ): AsyncGenerator<PaginatedResponse<LibraryData>> {\n        // For the single-page case, we should send query params in the URL rather than headers\n        // to avoid the browser seeing the requests as the same resource\n        yield* this.fetchOnePage(\n            this._getLibrariesURL(filters),\n            this._getLibrariesResponseMapper(filters),\n            signal,\n            false\n        );\n    }\n\n    async getPresignedDownloadUrl(blockDownloadUrl: string): Promise<BlockDownloadData> {\n        const response = await this.fetch(blockDownloadUrl);\n        const responseJson = await response.json();\n\n        const presignedUrlData = mapResponseToBlockDownloadData(responseJson);\n        return presignedUrlData;\n    }\n\n    async loadVersionHistory(assetId: string): Promise<PaginatedResponse<VersionData>> {\n        const asset = await this._core!.hostAssetContext.getAssetWithCloudID(assetId);\n        let versionList: IItemList<AssetVersionConfig> | undefined;\n        await new Promise<void>((resolve, reject) => {\n            versionList = asset.versions.getList(AssetVersionOrder.default, undefined, { loadAllPages: true });\n            function listStateChange() {\n                if (versionList?.status !== AssetListStatus.Loading) {\n                    versionList?.off(STATE_CHANGED, listStateChange);\n                    if (versionList?.errors) {\n                        reject();\n                    }\n                    resolve();\n                }\n            }\n            versionList.on(STATE_CHANGED, listStateChange);\n        });\n\n        return versionList?.items.map((child: AssetVersion) =>\n            mapResponseToVersionData(assetId, child)\n        ) as PaginatedResponse<VersionData>;\n    }\n\n    async loadVersion(libraryAssetId: string, manifestUrl: string): Promise<Partial<LibraryData>> {\n        const hostContext = this._core!.hostAssetContext as AssetContext;\n        const asset = await hostContext.getAssetWithCloudID(libraryAssetId);\n\n        // This is unfortunate, since the manifest rel doesn't include a version parameter.\n        // The component rel does, but that won't be future-proof, so we're left with just passing in the URL\n        // we got from loadVersions\n\n        const response = await this.fetch(manifestUrl);\n        const data = await response.json();\n\n        return mapManifestToLibraryData(asset, data);\n    }\n\n    async getCollaborators(assetId: string): Promise<PaginatedResponse<CollaboratorData>> {\n        const collaboratorSource = this._core!.collaborationContext.getCollaborators(assetId);\n\n        let collaboratorList: IItemList<CollaboratorConfig> | undefined;\n        await new Promise<void>((resolve, reject) => {\n            collaboratorList = collaboratorSource?.getList(CollaboratorOrder.default, undefined, {\n                loadAllPages: true\n            });\n            function listStateChange() {\n                if (collaboratorList?.status !== AssetListStatus.Loading) {\n                    collaboratorList?.off(STATE_CHANGED, listStateChange);\n                    if (collaboratorList?.errors) {\n                        reject();\n                    } else {\n                        resolve();\n                    }\n                }\n            }\n            collaboratorList?.on(STATE_CHANGED, listStateChange);\n        });\n\n        return collaboratorList?.items.map(collaborator =>\n            mapResponseToCollaboratorData(assetId, collaborator)\n        ) as PaginatedResponse<CollaboratorData>;\n    }\n\n    followLibrary(assetId: string, libraryId: string): Promise<void> {\n        return this.fetch('/api/v1/libraries/bookmarks', {\n            method: 'POST',\n            body: JSON.stringify({\n                bookmarks: [\n                    {\n                        type: 'collab',\n                        id: libraryId,\n                        urn: assetId\n                    }\n                ]\n            }),\n            headers: {\n                'content-type': 'application/json'\n            }\n        }).then((/** bookmark */) => {\n            // The bookmark data is basically a copy of the request body.\n            // It doesn't have anything useful to the caller, so we won't send it back.\n            return;\n        });\n    }\n\n    moveLibrary(assetId: string, folderId: string, organizationId?: string): Promise<LibraryData> {\n        return new Promise((resolve, reject) => {\n            const queryParams: { [s: string]: any } = {\n                invocation_mode: 'async'\n            };\n            const headers: Record<string, string> = { 'content-type': 'application/json' };\n            if (organizationId) {headers['x-organization-id'] = organizationId;}\n            const request = this.fetch(`/api/v1/libraries?${stringify(queryParams)}`, {\n                method: 'POST',\n                body: JSON.stringify({\n                    self: assetId,\n                    repository: folderId\n                }),\n                headers\n            });\n            const asyncResponse = new AsyncResponse(this, request);\n            asyncResponse.on('change', (isDone: boolean, libraryResponse: LibraryResponse) => {\n                if (isDone) {\n                    if (asyncResponse.error) {\n                        reject(asyncResponse.error);\n                    } else {\n                        resolve(omitUndefined(mapResponseToLibraryData(libraryResponse)));\n                    }\n                }\n            });\n        });\n    }\n\n    importLibrary(_file: string | File): AsyncResponse<CloudDriver> {\n        throw new Error('Not implemented');\n    }\n\n    exportLibrary(_library: Library, _path?: string): AsyncResponse<CloudDriver> {\n        throw new Error('Not implemented');\n    }\n\n    publishBrand(brand: Library) {\n        if (!brand.assetId) {\n            throw new LibraryError(\n                'INVALID_PARAMETER',\n                'Brand asset id must be defined for publishing. Please wait before trying again.'\n            );\n        }\n        return this.fetch(`/api/v1/brands/${brand.assetId}/publish`, {\n            method: 'POST',\n            headers: {\n                'content-type': 'application/json'\n            }\n        });\n    }\n\n    unpublishBrand(brand: Library) {\n        let publishedAssetId;\n        if (brand.publishedTo) {\n            publishedAssetId = brand.publishedTo;\n        } else if (brand.publishedFrom) {\n            publishedAssetId = brand.assetId;\n        } else {\n            throw new LibraryError(\n                'INVALID_PARAMETER',\n                'Brand must be publsihed before unpublishing. Please wait before trying again.'\n            );\n        }\n        return this.fetch(`/api/v1/brands/${publishedAssetId}/unpublish`, {\n            method: 'POST',\n            headers: {\n                'content-type': 'application/json'\n            }\n        });\n    }\n\n    async abortOperation(_operationId: string): Promise<Response> {\n        throw new Error('Not supported in cloud mode.');\n    }\n\n    setLibraryChangeListener(libraries: LibraryData[], callback: (ids: string[], index?: any) => any): void {\n        this._notificationManager.setWatchedLibraries(libraries, (assetIds: string[]) => callback(assetIds, 'assetId'));\n    }\n\n    setSyncStateListener() {\n        // NO-OP\n    }\n\n    removeLibraryChangeListener() {\n        this._notificationManager.disconnect();\n    }\n\n    removeSyncStateListener() {\n        // NO-OP\n    }\n\n    removeFontDataChangeListeners() {\n        // NO-OP\n    }\n\n    addWatchedLibrary(library: LibraryData) {\n        this._notificationManager.addWatchedLibrary(library);\n    }\n\n    removeWatchedLibrary(library: LibraryData) {\n        this._notificationManager.removeWatchedLibrary(library);\n    }\n\n    addLibrariesSyncGroupListener(cb: () => void) {\n        this._notificationManager.addLibrariesSyncGroupListener(cb);\n    }\n\n    removeLibrariesSyncGroupListener() {\n        this._notificationManager.removeLibrariesSyncGroupListener();\n    }\n\n    private _getLibrariesURL(filters?: LibraryListFilters): string {\n        return `/api/v1/libraries?${new URLSearchParams(filters as Record<string, string>).toString()}`;\n    }\n\n    private _getLibrariesResponseMapper(filters?: LibraryListFilters): (response: LibrariesResponse) => LibraryData[] {\n        return (response: LibrariesResponse) => {\n            if (!isLibrariesResponse(response)) {\n                return [];\n            }\n            return response.libraries.map(data =>\n                mapResponseToLibraryData(\n                    data,\n                    this._options.readOnly,\n                    filters?.selector?.includes('rendition_grid') ?? true\n                )\n            );\n        };\n    }\n\n    /* Element operations */\n\n    private _getElement(assetId: string, elementId: string): Promise<ElementData> {\n        return this.fetch(\n            `/api/v1/libraries/${assetId}/elements/${elementId}?selector=default,representations,details,tags`\n        )\n            .then(res => res.json())\n            .then((res: ElementResponse) => mapResponseToElementData(res));\n    }\n\n    @trace\n    private async *_getAllElements(assetId: string, options: GetElementsOptions): AsyncGenerator<Partial<LibraryData>> {\n        const elementTypes = [\n            [ 'elements', '_getElementsByAssetId' ],\n            [ 'documentationElements', '_getDocumentationElementsByAssetId' ],\n            [ 'removedElements', '_getRemovedElementsByAssetId' ]\n        ] as const;\n\n        // If the elements aren't loaded yet, update the library page by page\n        // Otherwise, load them all at once.\n        const updateData: Partial<LibraryData> = {};\n\n        // TODO: We want to run all element type iterators at the same time. Right now it doesn't matter since we only deal with normal elements.\n        for (const [ type, generator ] of elementTypes) {\n            if (options.types.includes(type)) {\n                for await (const page of this[generator](\n                    assetId,\n                    options.sort,\n                    options.etag,\n                    undefined,\n                    options.abortController?.signal\n                )) {\n                    updateData[type] = updateData[type] || [];\n                    updateData[type]?.push(...page);\n                    if (options.loadProgressively) {\n                        yield { [type]: updateData[type] };\n                    }\n                }\n            }\n        }\n\n        yield { areElementsLoaded: true, ...(options.loadProgressively ? {} : updateData) };\n    }\n\n    private async *_getElementsByAssetId(\n        assetId: string,\n        sort: ElementSort = defaultElementSort,\n        etag?: string,\n        limit = 100,\n        signal?: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        yield* this._getElementsOfTypeByAssetId('elements', assetId, sort, etag, limit, signal);\n    }\n\n    private async *_getRemovedElementsByAssetId(\n        assetId: string,\n        sort: ElementSort = defaultElementSort,\n        etag?: string,\n        limit = 100,\n        signal?: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        yield* this._getElementsOfTypeByAssetId('archive', assetId, sort, etag, limit, signal);\n    }\n\n    private async *_getDocumentationElementsByAssetId(\n        assetId: string,\n        _sort: ElementSort = defaultElementSort,\n        etag?: string,\n        _limit = 100,\n        _signal?: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        yield Promise.resolve([]);\n    }\n\n    @trace\n    private async *_getElementsOfTypeByAssetId(\n        type: 'elements' | 'archive',\n        assetId: string,\n        sort: ElementSort = defaultElementSort,\n        etag?: string,\n        limit = 100,\n        signal?: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        const responseMapper = (res: ElementsResponse) =>\n            res.elements.map(element => {\n                // The no-etag-set-on-library-response-yet case\n                if ((!element.manifest_etag && etag === melvilleFirstUseEtag) || element.manifest_etag === etag) {\n                    return mapResponseToElementData(element);\n                }\n\n                throw new RequestError('PRECONDITION_FAILED', `An element did not match the provided etag: ${etag}`);\n            });\n\n        const orderBy = `${sort.direction === 'descending' ? '-' : ''}${sortFieldMap[sort.field]}`;\n        const queryParams: { [s: string]: any } = {\n            limit,\n            orderBy,\n            selector: [ 'default', 'representations', 'details' ]\n        };\n\n        yield* this.fetchAllPages(\n            `/api/v1/libraries/${assetId}/${type}?${stringify(queryParams, { arrayFormat: 'comma' })}`,\n            {},\n            responseMapper,\n            signal\n        );\n\n    }\n\n    async *getSearchResults(\n        searchQuery: string,\n        filters: SearchFilters,\n        elementSort: ElementSort,\n        signal: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        const { field, direction } = elementSort;\n        let orderBy = field === 'modifiedDate' ? 'modified_date' : 'name';\n        if (direction === 'descending') {orderBy = `-${orderBy}`;}\n        yield* this.fetchAllPages(\n            '/api/v1/search',\n            {\n                method: 'POST',\n                signal,\n                headers: {\n                    'Content-Type': 'application/json'\n                },\n                body: JSON.stringify({\n                    query_string: searchQuery,\n                    library_id: filters.library_id,\n                    asset_type: [ 'element' ],\n                    orderBy,\n                    limit: 300\n                })\n            },\n            (res: SearchElementsResponse) => {\n                return res.elements.map(mapSearchResponseToElementData);\n            }\n        );\n    }\n\n    /* Team operations */\n    // @deprecated\n    @trace\n    async getTeams(): Promise<TeamData[]> {\n        const response = await this.fetch(`https://${this.driverConfig.teams_hostname}/api/v2/teams`);\n        const teamData: TeamsResponse = await response.json();\n\n        if (!isTeamsResponse(teamData)) {\n            return [];\n        }\n\n        // Remove all CCI teams, as this feature has STILL not shipped.\n        return teamData.teams.filter(team => team.repositoryOwner.type === 'org').map(mapResponseToTeamData);\n    }\n\n    // @deprecated\n    @trace\n    async getProjects(): Promise<TeamData[]> {\n        if (!this._core) {\n            return [];\n        }\n\n        const projectList = await this._core!.projectContext\n            .projects()\n            .getList(ProjectOrder.default, ProjectFilter.AllProjects, { loadAllPages: true });\n\n        await waitForListLoad(projectList);\n        return projectList.items.map(mapProjectToTeamData);\n    }\n\n    @trace\n    async getProjectByName(name: string): Promise<TeamData | undefined> {\n        if (!this._core) {\n            return undefined;\n        }\n\n        const project = await this._core!.projectContext.resolveProjectByName(name);\n        if (!project) {\n            return undefined;\n        }\n        return mapProjectToTeamData(project);\n    }\n\n    // @deprecated\n    @trace\n    async getProjectGradient(project: Team) {\n        if (!this._core) {\n            return;\n        }\n\n        // The project should be cached so this should return immediately.\n        const samProject = await this._core!.projectContext.getProjectbyID(project.id);\n        return this._core!.projectContext.getGradient(samProject.gradientID).then(mapGradientToGradientData);\n    }\n\n    /* Group operations */\n\n    async *getGroups(_assetId: string): AsyncGenerator<PaginatedResponse<GroupData>> {\n        yield Promise.resolve(undefined as unknown as PaginatedResponse<GroupData>);\n    }\n\n    /* Rendition operations */\n\n    getRenditionUrl(element: Element, size: RenditionSize): string {\n        let url: URL | undefined;\n        try {\n            const urlString = getRenditionUrl(element, size);\n            if (!urlString) {\n                return '';\n            }\n            // cannot initialize URL with undefined\n            url = new URL(urlString);\n        } catch (error) {\n            Logger.log(String(error));\n            return '';\n        }\n\n        setURLSearchParams(url, {\n            api_key: this._clientId as string,\n            user_token: this._token as string\n        });\n\n        return url.toString();\n    }\n\n    getAuthenticatedThumbnailURL(element: Element, size: RenditionSize): Promise<string> {\n        return Promise.resolve(this.getRenditionUrl(element, size));\n    }\n\n    getRenditionPath(_assetId: string, _elementId: string, _size: RenditionSize): Promise<string> {\n        return Promise.resolve('');\n    }\n\n    @trace\n    getRendition(element: Element, size: RenditionSize): Promise<Response> {\n        return this.fetch(getRenditionUrl(element, size) as string);\n    }\n\n    async getRepresentationContent(representation: Representation): Promise<Response> {\n        let representationUrl;\n\n        // 10mb ACP API limit on download via `primary` link, otherwise use `download` to get presigned URL\n        if (representation.contentLength < rapiMaxSingleTransferSize) {\n            representationUrl = representation._data.url as string;\n        } else {\n            const blockDownloadData = await this.getPresignedDownloadUrl(\n                representation._data.blockDownloadUrl as string\n            );\n            representationUrl = blockDownloadData && (blockDownloadData.url as string);\n\n            if (!representationUrl) {\n                representationUrl = representation._data.url as string;\n            }\n        }\n\n        return this.fetch(representationUrl as string);\n    }\n\n    /* Local Settings */\n    async setLocalSetting(key: string, value: any): Promise<void> {\n        value = JSON.stringify(value);\n        this._localStorage?.setItem(key, value);\n    }\n\n    getLocalSetting(key: string): any {\n        const value = this._localStorage?.getItem(key);\n        const result = value && JSON.parse(value);\n        return result;\n    }\n\n    getInstalledVersion(_appCode: string): any {\n        throw new Error('Not supported in cloud mode.');\n    }\n\n    setFontDataChangeListener(_callback: () => void) {\n        // No-op\n    }\n\n    /**\n     * Moves query params to headers, for those that are in the MelvilleParamsAsHeaders list\n     * @param melvillePath\n     * @returns tuple of [path, headers], with the path truncated of the query params that were moved to headers\n     */\n    moveUrlQueryParamsToHeaders(\n        melvillePath: string,\n        headers: Record<string, string> = {}\n    ): [string, Record<string, string>] {\n        const [ path, query ] = melvillePath.split('?');\n        const urlParams = new URLSearchParams(query);\n        for (const headerParamKey of MelvilleParamsAsHeaders) {\n            const headerParamValue = urlParams.get(headerParamKey);\n            if (headerParamValue) {\n                headers[headerParamKey] = headerParamValue;\n                urlParams.delete(headerParamKey);\n            }\n        }\n\n        return [ `${path}${[ ...urlParams ].length > 0 ? '?' : ''}${urlParams}`, headers ];\n    }\n\n    async sendAction(applicationAction: ApplicationAction): Promise<Response> {\n        throw new LibraryError(\n            'NOT_SUPPORTED',\n            'Application actions are not supported in a cloud environment',\n            applicationAction.item.id\n        );\n    }\n\n    async openInCCD(_path: string): Promise<Response> {\n        throw new Error('Not supported in cloud mode.');\n    }\n\n    @trace\n    async fetch(path: string, init?: FetchRequestInit, options: { includeAuthHeader?: boolean } = {}) {\n        setTracingSpanAttribute('path', path);\n        init = init || {};\n        init.headers = init.headers || {};\n        init.headers['x-api-key'] = this._clientId as string;\n\n        // Include the auth header, unless the options specifically say not to include it.\n        if (options.includeAuthHeader !== false) {\n            init.headers.Authorization = `Bearer ${this._token}`;\n        }\n\n        // Attempt to upgrade platform urls to use edge workflow\n        // Turns on http/2 for ACP\n        const { url, headers } = useEdge(path);\n        path = url;\n        init.headers = { ...headers, ...init.headers };\n\n        init.signal = init.signal\n            ? combineSignals(init.signal, this._abortController?.signal as AbortSignal)\n            : this._abortController?.signal;\n\n        if (path.startsWith('/')) {\n            path = `https://${this.driverConfig.hostname}${path}`;\n        }\n\n        const startTime = Date.now();\n        const response = await this._fetch(path, init).catch(e => {\n            if (e.name === ABORT_ERROR) {\n                return new Response('{}');\n            }\n            Logger.info(`Error - ${e} (${Date.now() - startTime}ms)`);\n            throw e;\n        });\n        const requestId = response.headers.get('X-Request-Id') || 'no requestId';\n        Logger.info(`[${requestId}] ${init.method || 'GET'} ${path} ${response.status} (${Date.now() - startTime}ms)`);\n\n        if (response.status >= 300) {\n            const requestError = getRequestError(response);\n            // If the fetch fails because it is unauthorized, we want to refresh the access token to make sure we have a valid tokenZXGBVH\n            if (requestError.requestErrorCode === 'UNAUTHORIZED') {\n                this._refreshAccessToken?.();\n            }\n\n            throw await this._getFetchError(response);\n        }\n\n        return response;\n    }\n\n    private async _getFetchError(response: Response) {\n        // Melville may include error details in the response body.\n        if (response.status === 403) {\n            try {\n                const json = await response.json();\n                if (typeof json.type === 'string' && (json.type as string).toLowerCase() === 'quota') {\n                    return new LibraryError('EXCEEDS_QUOTA', json.problem_type_message || 'Storage quota exceeded');\n                }\n            } catch {\n                // If the JSON is invalid, ignore it.\n            }\n        }\n\n        return getRequestError(response);\n    }\n\n    async *fetchAllPages<T, U>(\n        firstUrl: string,\n        init: FetchRequestInit,\n        responseMapper: (response: T) => PaginatedResponse<U>,\n        signal?: AbortSignal,\n        paramsAsHeaders: boolean = true\n    ): AsyncGenerator<PaginatedResponse<U>> {\n        let nextUrl = firstUrl;\n        while (nextUrl) {\n            const { headers = {}, ...rest } = init;\n            if (paramsAsHeaders) {\n                [ nextUrl ] = this.moveUrlQueryParamsToHeaders(nextUrl, headers);\n            }\n\n            const response = await this.fetch(nextUrl, { signal, ...rest, headers }).then(res => res.json());\n            yield responseMapper(response);\n            nextUrl = response._links?.next?.href;\n        }\n    }\n\n    async *fetchOnePage<T, U>(\n        firstUrl: string,\n        responseMapper: (response: T) => PaginatedResponse<U>,\n        signal?: AbortSignal,\n        paramsAsHeaders: boolean = true\n    ): AsyncGenerator<PaginatedResponse<U>> {\n        let headers: { [s: string]: string } | undefined;\n        if (paramsAsHeaders) {\n            [ firstUrl, headers ] = this.moveUrlQueryParamsToHeaders(firstUrl);\n        }\n\n        const response = await this.fetch(firstUrl, { signal, headers }).then(res => res.json());\n        yield responseMapper(response);\n    }\n\n    async copyFile(_source: string, _destination: string, _allowOverride?: boolean): Promise<string> {\n        throw new Error('Not supported in cloud mode.');\n    }\n\n    async getFileSize(_path: string): Promise<string> {\n        throw new Error('Not supported in cloud mode.');\n    }\n\n    getRenditionGrid(_library: Library): Promise<string> {\n        throw new Error('Not supported in cloud mode.');\n    }\n\n    @trace\n    async stageRepresentationForCommit(library: Library, file: File, type?: string): Promise<string> {\n        const fileType = type || file.type;\n\n        // Get a link for uploading components to the library.\n        const links = await this._fetchLibraryLinks(library);\n        const componentLink = links[RapiLinkType.COMPONENT];\n\n        // This is the link for uploading a component in chunks.\n        const blockUploadLink = links[RapiLinkType.BLOCK_INIT];\n        const maxSingleTransferSize = blockUploadLink?.['repo:maxSingleTransferSize'] || rapiMaxSingleTransferSize;\n\n        if (!componentLink) {\n            throw new LibraryError('NOT_ALLOWED', 'Library is missing component upload link', library.id);\n        }\n\n        // Use the component link template to get the URL to the new component.\n        const componentId = uuid();\n        const template = uriTemplates(componentLink.href);\n        const componentUrl = template.fill({ component_id: componentId });\n        const dimensions = await getImageDimensions(file, fileType);\n\n        const preflightResponse: Partial<RepresentationPreflightResponse> & { width?: number; height?: number } = {\n            id: componentId,\n            storage_href: componentUrl,\n            asset_id: library.assetId,\n            type: fileType,\n            content_length: file.size,\n            name: file.name,\n            width: dimensions?.width,\n            height: dimensions?.height\n        };\n\n        if (file.size > maxSingleTransferSize && blockUploadLink) {\n            const transferDocument = await this._initializeBlockUpload(blockUploadLink, componentId, file, fileType);\n            await this._transferBlocks(transferDocument, file);\n            const result = await this._finalizeBlockUpload(transferDocument);\n            Object.assign(preflightResponse, result);\n            return JSON.stringify(preflightResponse);\n        }\n\n        // Upload the new component.\n        const uploadResponse = await this.fetch(componentUrl, {\n            method: 'PUT',\n            headers: {\n                'Content-Type': fileType\n            },\n            body: await file.arrayBuffer()\n        });\n\n        Object.assign(preflightResponse, {\n            etag: uploadResponse.headers.get('etag'),\n            md5: uploadResponse.headers.get('content-md5') ?? undefined,\n            version: uploadResponse.headers.get('revision')\n        });\n        return JSON.stringify(preflightResponse);\n    }\n\n    // This entire method could be replaced by a call to the Links API, except for a CORS issue\n    // between the Links API and Express.\n    // CORS Ticket: https://jira.corp.adobe.com/browse/ACPSDS-4864\n    // Links API: https://developers.corp.adobe.com/storage-api/docs/reference/links.md\n    private async _fetchLibraryLinks(library: Library) {\n        if (!library.assetId) {\n            throw new LibraryError('NOT_SUPPORTED', 'Library does not have an assetId', library.id);\n        }\n\n        // Get a link from the index for resolving assets.\n        // This could be improved by caching links so we don't need a new request each time.\n        // Link caching - https://developers.corp.adobe.com/supplemental-resources/docs/caching-links.md\n        const indexResponse = await this.fetch(`https://${this.driverConfig.platform_hostname}`);\n        const indexLinks = (await indexResponse.json())._links;\n        const resolveLink = indexLinks[RapiLinkType.RESOLVE];\n\n        // Resolve the library to get the links for the library.\n        const resolveTemplate = uriTemplates(resolveLink.href);\n        const resolveUrl = resolveTemplate.fill({ id: library.assetId });\n        const resolveResponse = await this.fetch(resolveUrl, { method: 'HEAD' });\n\n        // Links are returned in the response headers as a comma-separated list of link relations.\n        // The links also appear in the response body of a GET request, but the block/init relation\n        // is not included for some reason. That's why we parse the response headers instead.\n        const linkList = resolveResponse.headers.get('link');\n        return linkList ? parseLinks(linkList) : {};\n    }\n\n    // See: https://developers.corp.adobe.com/storage-api/docs/reference/block-transfer.md\n    private async _initializeBlockUpload(\n        blockUploadLink: Link,\n        componentId: string,\n        file: File,\n        fileType: string\n    ): Promise<Record<string, any>> {\n        const transferDocument: Record<string, any> = {\n            'repo:size': file.size,\n            'repo:blocksize': blockUploadLink['repo:maxSingleTransferSize'] || rapiMaxSingleTransferSize,\n            'repo:reltype': RapiLinkType.COMPONENT,\n            component_id: componentId,\n            'dc:format': fileType\n        };\n        const initResponse = await this.fetch(blockUploadLink.href, {\n            method: 'POST',\n            headers: {\n                'Content-Type': 'application/vnd.adobecloud.bulk-transfer+json'\n            },\n            body: JSON.stringify(transferDocument)\n        });\n\n        // Returns an updated transfer document\n        return await initResponse.json();\n    }\n\n    private async _transferBlocks(transferDocument: Record<string, any>, file: File) {\n        const blockSize = transferDocument['repo:blocksize'];\n        const transferLinks = transferDocument._links[RapiLinkType.BLOCK_TRANSFER];\n        let offset = 0;\n        const blockUploads: Promise<Response>[] = [];\n\n        for (let i = 0; offset <= file.size; i += 1) {\n            const end = Math.min(offset + blockSize, file.size);\n            blockUploads.push(\n                this.fetch(\n                    transferLinks[i].href,\n                    {\n                        method: 'PUT',\n                        headers: {\n                            'Content-Length': String(end - offset)\n                        },\n                        body: file.slice(offset, end),\n                        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n                        // @ts-expect-error - this is a new addition to the fetch standard and required when the body is a ReadableStream (enforced by node.js). See https://github.com/whatwg/fetch/blob/main/fetch.bs#L7510.\n                        duplex: 'half'\n                    },\n                    { includeAuthHeader: false }\n                )\n            );\n            offset += blockSize;\n        }\n        return await Promise.all(blockUploads);\n    }\n\n    private async _finalizeBlockUpload(transferDocument: Record<string, any>) {\n        const finalizeLink = transferDocument._links[RapiLinkType.BLOCK_FINALIZE];\n        let finalizeUrl = finalizeLink.href;\n        if (finalizeLink.templated) {\n            const template = uriTemplates(finalizeLink.href);\n            finalizeUrl = template.fill({});\n        }\n\n        const finalizeRequest = this.fetch(finalizeUrl, {\n            method: 'POST',\n            headers: {\n                'Content-Type': 'application/vnd.adobecloud.bulk-transfer+json'\n            },\n            body: JSON.stringify(transferDocument)\n        });\n        const response = await finalizeRequest;\n\n        // If the response is 202, the request was accepted for asynchronous processing.\n        // Handoff to the AsyncResponse class to handle monitoring the request.\n        if (response.status === HttpStatus.ACCEPTED) {\n            return new Promise((resolve, reject) => {\n                const asyncResponse = new AsyncResponse(this, finalizeRequest);\n                asyncResponse.on('change', (isDone: boolean, json: any, headers: Headers) => {\n                    if (isDone) {\n                        if (asyncResponse.error) {\n                            reject(asyncResponse.error);\n                        } else {\n                            resolve({\n                                etag: headers.get('etag'),\n                                md5: headers.get('content-md5') ?? undefined,\n                                version: headers.get('version')\n                            });\n                        }\n                    }\n                });\n            });\n        }\n\n        // Otherwise, the request was processed synchronously.\n        return {\n            etag: response.headers.get('etag'),\n            md5: response.headers.get('content-md5') ?? undefined,\n            version: response.headers.get('version')\n        };\n    }\n\n    getLocalDriver() {\n        const connector = () => {\n            return this._requestProcessToUploadData(uuid(), Date.now());\n        };\n\n        return new LocalDriver(this._core, connector);\n    }\n\n    private async _requestProcessToUploadData(\n        uuid: string,\n        originalTimeStamp: number\n    ): Promise<LibraryProcessResponse> {\n        if (Date.now() - originalTimeStamp > processDiscoveryTimeout) {\n            Logger.log('Timed out and no response received from process and/or server');\n            throw new Error('Unable to get process connection info (timed out)');\n        }\n\n        const userHash = md5(this.config.user?.id as string);\n\n        // make Urls.\n        const urlWithoutPort = `https://${uuid}.${userHash}.adobelocalhost.com`;\n        const urls = [];\n\n        for (let port = tlsDiscoveryPortRange[0]; port <= tlsDiscoveryPortRange[1]; port += 1) {\n            urls.push(`${urlWithoutPort}:${port}`);\n        }\n\n        // reset the abort controller since we were disconnected\n        this.resetAbortController();\n\n        await Promise.allSettled(urls.map(url => fetch(url)));\n\n        try {\n            const [ result ] = await Promise.all([\n                this._fetchProcessConnectInfo(uuid).catch((): any => undefined),\n                sleep(processDiscoveryRetryDelay)\n            ]);\n\n            if (!result) {\n                throw new RequestError(\n                    'MALFORMED_RESPONSE',\n                    `Invalid response retrieving process connection data for uuid: ${uuid}`\n                );\n            }\n\n            return result;\n        } catch (error) {\n            Logger.error(String(error));\n            return this._requestProcessToUploadData(uuid, originalTimeStamp);\n        }\n    }\n\n    private async _fetchProcessConnectInfo(id: string): Promise<LibraryProcessResponse> {\n        const url = `https://${this.driverConfig.hostname}/api/v1/client-tokens/${id}`;\n\n        const data = await this.fetch(url).then(\n            res => res.json(),\n            err => Logger.error(err)\n        );\n\n        const { restApiToken, restApiPort } = JSON.parse(data.token) as { restApiToken: string; restApiPort: string };\n        if (!restApiToken || !restApiPort) {\n            throw new RequestError('MALFORMED_RESPONSE', 'Response did not include necessary process connection data');\n        }\n\n        return { hostname: `http://127.0.0.1:${restApiPort}`, token: restApiToken };\n    }\n\n    getClientInfo(): ClientInfo {\n        return {\n            deviceId: `${this._clientId}-${this.config.user?.id}`,\n            device: typeof window !== 'undefined' ? window.navigator.userAgent : 'node-js',\n            app: this._clientId as string\n        };\n    }\n\n    async getTempDir(_library: Library): Promise<string> {\n        throw new Error('Not supported in cloud mode.');\n    }\n\n    ignoreLocalSyncEvents(): boolean {\n        // For Cloud driver the sync status is based on the local operations.\n        return false;\n    }\n}\n","import type { LibrariesResponse, TeamsResponse } from './melvilleModelMappers';\n\nexport const isTeamsResponse = (val: {}): val is TeamsResponse => {\n    return (val as TeamsResponse).teams !== undefined;\n};\n\nexport const isLibrariesResponse = (val: {}): val is LibrariesResponse => {\n    return (val as LibrariesResponse).libraries !== undefined;\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport default class LibraryAbortController {\n    private static libAbortControllerMap = new Map();\n\n    public static getInstance(libraryId: string): AbortController {\n        let instance = this.libAbortControllerMap.get(libraryId);\n        if (!instance) {\n            instance = new AbortController();\n            this.libAbortControllerMap.set(libraryId, instance);\n        }\n        return instance;\n    }\n\n    public static removeInstance(libraryId: string) {\n        return this.libAbortControllerMap.delete(libraryId);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Utils\n * @packageDocumentation\n * @module Utils\n * @internal\n */\n\nimport type { Gradient, LinkReference } from '../../../../index';\nimport type { ElementMimeType } from '../../../config/constants';\nimport type { RepresentationData } from '../../../models/data/RepresentationData';\nimport type { ElementData, GroupMembershipData } from '../../../models/data/ElementData';\nimport type { LibraryData, OwnershipType, Collaboration, Role } from '../../../models/data/LibraryData';\nimport type { GroupData } from '../../../models/data/GroupData';\nimport type { UpdateContext } from '../../../models/data/UpdateContext';\nimport type { GradientData, TeamData } from '../../../models/Team';\nimport type { Stringified } from '../../../types';\n\nconst getPublicLinkId = (url?: string) => {\n    return url?.substring(url.lastIndexOf('/') + 1);\n};\n\nexport type GroupResponse = {\n    id: string;\n    classifier: string;\n    name: string;\n    order: string;\n    parent_id?: string;\n    localized_names: { [s: string]: string };\n    created_date: number;\n    created_by?: string;\n    created_context?: UpdateContext;\n    created_locally?: boolean;\n    modified_date: number;\n    modified_by?: string;\n    modified_context?: UpdateContext;\n    modified_locally?: boolean;\n    custom_data?: { [s: string]: any };\n    source_ref?: Stringified<LinkReference>; // Only present in published libraries.\n};\n\nexport type GroupMembershipResponse = {\n    id: string;\n    classifier: string;\n    order: string;\n};\n\nexport type RepresentationResponse = {\n    id: string;\n    type: string;\n    children?: RepresentationResponse[];\n    relationship: 'primary' | 'rendition';\n    is_preferred_thumbnail?: boolean;\n    is_external_link?: boolean;\n    is_full_size?: boolean;\n    content_length?: number;\n    url?: string;\n    custom_data?: { [s: string]: any };\n    width?: number;\n    height?: number;\n    // TODO: Custom data is coming back on the root from REST API\n    [s: string]: any;\n};\n\nexport type LibraryResponse = {\n    id: string;\n    name: string;\n    created_date: number;\n    modified_date: number;\n    etag?: string;\n    rendition_grid?: Object;\n    details: {\n        num_elements: number;\n        num_documentation_elements: number;\n        num_archived_elements: number;\n    };\n    localized_names: {\n        [s: string]: string;\n    };\n    groups: GroupResponse[];\n    default: boolean;\n    ownership: OwnershipType;\n    elements?: ElementResponse[];\n    team_id?: string;\n    team_name?: string;\n    roles?: Role[];\n    asset_id?: string;\n    toolkit_id?: string;\n    document_id?: string;\n    document_type?: string;\n    custom_data?: { [s: string]: any };\n    collaboration?: Collaboration;\n    owner: string;\n    owner_type: 'org' | 'user';\n    is_writable: boolean;\n    is_parent_writable: boolean;\n    storage_used?: number;\n    public_link?: string;\n    bookmark?: { id: string };\n    remove_type: 'delete' | 'discard' | 'none';\n    locally_managed?: boolean;\n};\n\nexport type LibrariesResponse = {\n    libraries: LibraryResponse[];\n};\n\nexport type ElementResponse = {\n    id: string;\n    name: string;\n    is_auto_named: boolean;\n    auto_name?: string;\n    type: ElementMimeType;\n    created_date: number;\n    created_locally: boolean;\n    created_by: string;\n    created_context: UpdateContext;\n    modified_date: number;\n    modified_locally: boolean;\n    modified_by: string;\n    modified_context: UpdateContext;\n    description: string;\n    description_modified_date: number;\n    description_modified_locally: boolean;\n    description_modified_by: string;\n    description_modified_context?: UpdateContext;\n    removed_date: number;\n    removed_locally: boolean;\n    removed_by: string;\n    removed_context?: UpdateContext;\n    source_ref?: Stringified<LinkReference>; // Only present in published libraries.\n    source_modified_date?: number; // Only present in libraries published prior to link schema migration.\n    tags: string[];\n    roles?: Role[];\n    dependency_ids: string[];\n    localized_names: {\n        [s: string]: string;\n    };\n    groups: GroupMembershipResponse[];\n    representations: RepresentationResponse[];\n    custom_data?: { [s: string]: any };\n    library?: { id: string };\n    element_ref: string;\n};\n\nexport type ElementsResponse = {\n    elements: ElementResponse[];\n};\n\nexport type SearchElementsResponse = {\n    results: ElementResponse[];\n};\n\nexport type LibraryChangeBody = {\n    [s: string]: string | number;\n};\n\nexport type LibraryChangeResponse = {\n    [s: string]: string | number | LibraryResponse;\n};\n\ntype LibraryMutation = { mutation: 'add' | 'update' | 'delete'; source: LibraryChangeResponse['id'] };\n\nexport type LibraryMutations = Map<string, LibraryMutation>;\n\nexport type TeamResponse = {\n    createdBy: string;\n    id: string;\n    name: string;\n    ownerId: string;\n    ownerName: string;\n    ownerType: 'org' | 'user';\n    permissions: ('read' | 'write' | 'delete' | 'ack')[];\n};\n\nexport type ProjectResponse = {\n    id: string;\n    name: string;\n    storageAssignee: {\n        id: string;\n        displayName: string;\n        type: 'user' | 'org';\n    };\n    isReadOnly: boolean;\n};\n\nexport type TeamsResponse = { teams: TeamResponse[] };\n\nexport type ProjectsResponse = { projects: ProjectResponse[] };\n\nexport type ProjectGradientResponse = { gradient: Gradient };\n\nexport function mapResponseToLibraryData(libraryResponse: LibraryResponse, forceReadOnly = false): LibraryData {\n    const isWritable = forceReadOnly ? false : libraryResponse.is_writable;\n\n    const data: LibraryData = {\n        id: libraryResponse.id,\n        etag: libraryResponse.etag,\n        name: libraryResponse.name,\n        ownership: libraryResponse.ownership,\n        default: libraryResponse.default,\n        localizedNames: libraryResponse.localized_names,\n        toolkitId: libraryResponse.toolkit_id,\n        documentId: libraryResponse.document_id,\n        documentType: libraryResponse.document_type,\n        createdDate: libraryResponse.created_date,\n        modifiedDate: libraryResponse.modified_date,\n        groups: (libraryResponse.groups || []).map(mapResponseToGroupData),\n        details: {\n            elementCount: libraryResponse.details.num_elements,\n            documentationElementCount: libraryResponse.details.num_documentation_elements,\n            removedElementCount: libraryResponse.details.num_archived_elements\n        },\n        renditionGrid: libraryResponse.rendition_grid,\n        collaboration: libraryResponse.collaboration,\n        assetId: libraryResponse.asset_id,\n        isWritable,\n        isParentWritable: forceReadOnly ? false : libraryResponse.is_parent_writable,\n        team: libraryResponse.team_id\n            ? {\n                id: libraryResponse.team_id\n            }\n            : undefined,\n        roles: libraryResponse.roles,\n        owner: libraryResponse.owner,\n        ownerType: libraryResponse.owner_type,\n        customData: libraryResponse.custom_data,\n        isLibraryLoaded: true, // If the library data is coming from an API we know it is truly loaded\n        storageUsed: libraryResponse.storage_used,\n        publicLinkId: getPublicLinkId(libraryResponse.public_link),\n        locallyManaged: libraryResponse.locally_managed,\n        bookmark: libraryResponse.bookmark,\n        // If `remove_type` is not in the response, then we are connected to an older version\n        // of the process that did not support discard. We can assume the remove type is delete.\n        removeType: libraryResponse.remove_type ?? (isWritable ? 'delete' : 'none'),\n        deletable: isWritable\n    };\n\n    if (libraryResponse.elements) {\n        data.elements = libraryResponse.elements.map(mapResponseToElementData);\n    }\n\n    return data;\n}\n\nexport function mapLibraryDataToRequest(libraryData: Partial<LibraryData>): Partial<LibraryResponse> & { id: string } {\n    return {\n        id: libraryData.id as string,\n        name: libraryData.name,\n        ownership: libraryData.ownership,\n        default: libraryData.default,\n        localized_names: libraryData.localizedNames,\n        toolkit_id: libraryData.toolkitId,\n        document_id: libraryData.documentId,\n        document_type: libraryData.documentType,\n        groups: libraryData.groups?.map(mapGroupDataToRequest),\n        collaboration: libraryData.collaboration,\n        details: {\n            num_elements: 0, // TODO\n            num_documentation_elements: 0, // TODO\n            num_archived_elements: 0 // TODO\n        },\n        // asset_id: '',\n        // isWritable: true,\n        // isParentWritable: true,\n        team_id: libraryData.team?.id,\n        roles: libraryData.roles,\n        custom_data: libraryData.customData\n    };\n}\n\nexport function mapResponseToElementData(elementResponse: ElementResponse): ElementData {\n    return {\n        id: elementResponse.id,\n        name: elementResponse.name,\n        isAutoNamed: elementResponse.is_auto_named,\n        autoName: elementResponse.auto_name,\n        type: elementResponse.type,\n        libraryId: elementResponse.library?.id,\n        sourceRef: elementResponse.source_ref,\n        sourceModifiedDate: elementResponse.source_modified_date,\n        tags: elementResponse.tags,\n        dependencyIds: elementResponse.dependency_ids,\n        localizedNames: elementResponse.localized_names,\n        createdDate: elementResponse.created_date,\n        createdLocally: elementResponse.created_locally,\n        createdBy: elementResponse.created_by,\n        createdContext: elementResponse.created_context,\n        modifiedDate: elementResponse.modified_date,\n        modifiedLocally: elementResponse.modified_locally,\n        modifiedBy: elementResponse.modified_by,\n        modifiedContext: elementResponse.modified_context,\n        description: elementResponse.description,\n        descriptionModifiedDate: elementResponse.description_modified_date,\n        descriptionModifiedLocally: elementResponse.description_modified_locally,\n        descriptionModifiedBy: elementResponse.description_modified_by,\n        descriptionModifiedContext: elementResponse.description_modified_context,\n        removedDate: elementResponse.removed_date,\n        removedLocally: elementResponse.removed_locally,\n        removedBy: elementResponse.removed_by,\n        removedContext: elementResponse.removed_context,\n        representations: elementResponse.representations?.map(mapResponseToRepresentationData),\n        groups: elementResponse.groups?.map(mapResponseToGroupMembershipData),\n        roles: elementResponse.roles,\n        customData: elementResponse.custom_data,\n        elementRef: elementResponse.element_ref\n    };\n}\n\nexport function mapElementDataToRequest(elementData: Partial<ElementData>): Partial<ElementResponse> & { id: string } {\n    return {\n        id: elementData.id as string,\n        name: elementData.name,\n        is_auto_named: elementData.isAutoNamed,\n        auto_name: elementData.autoName,\n        type: elementData.type,\n        source_ref: elementData.sourceRef,\n        description: elementData.description,\n        tags: elementData.tags,\n        dependency_ids: elementData.dependencyIds,\n        localized_names: elementData.localizedNames,\n        created_date: elementData.createdDate,\n        modified_date: elementData.modifiedDate,\n        representations: elementData.representations?.map(rep => mapRepresentationDataToRequest(rep, false)),\n        groups: elementData.groups?.map(mapGroupMembershipDataToRequest),\n        roles: elementData.roles,\n        custom_data: elementData.customData\n    };\n}\n\nexport function mapResponseToGroupData(groupResponse: GroupResponse): GroupData {\n    return {\n        id: groupResponse.id,\n        classifier: groupResponse.classifier,\n        name: groupResponse.name,\n        order: groupResponse.order,\n        parentId: groupResponse.parent_id,\n        localizedNames: groupResponse.localized_names,\n        createdDate: groupResponse.created_date,\n        createdBy: groupResponse.created_by,\n        createdContext: groupResponse.created_context,\n        createdLocally: groupResponse.created_locally,\n        modifiedDate: groupResponse.modified_date,\n        modifiedBy: groupResponse.modified_by,\n        modifiedContext: groupResponse.modified_context,\n        modifiedLocally: groupResponse.modified_locally,\n        sourceRef: groupResponse.source_ref,\n        customData: groupResponse.custom_data\n    };\n}\n\nexport function mapGroupDataToRequest(groupData: Partial<GroupData>): GroupResponse {\n    return {\n        id: groupData.id as string,\n        classifier: groupData.classifier as string,\n        name: groupData.name as string,\n        order: groupData.order as string,\n        parent_id: groupData.parentId,\n        localized_names: groupData.localizedNames as { [key: string]: string },\n        created_date: groupData.createdDate as number,\n        modified_date: groupData.modifiedDate as number,\n        source_ref: groupData.sourceRef,\n        custom_data: groupData.customData\n    };\n}\n\nexport function mapResponseToGroupMembershipData(\n    groupMembershipResponse: GroupMembershipResponse\n): GroupMembershipData {\n    // This is a no-op, but it is left as an example.\n    return {\n        id: groupMembershipResponse.id,\n        classifier: groupMembershipResponse.classifier,\n        order: groupMembershipResponse.order\n    };\n}\n\nexport function mapGroupMembershipDataToRequest(groupMembershipData: GroupMembershipData): GroupMembershipResponse {\n    // This is a no-op, but it is left as an example.\n    return {\n        id: groupMembershipData.id,\n        classifier: groupMembershipData.classifier,\n        order: groupMembershipData.order\n    };\n}\n\nexport function mapResponseToRepresentationData(representationResponse: RepresentationResponse): RepresentationData {\n    return {\n        id: representationResponse.id,\n        type: representationResponse.type,\n        relationship: representationResponse.relationship,\n        isFullSize: representationResponse.is_full_size as boolean,\n        isExternalLink: representationResponse.is_external_link as boolean,\n        isPreferredThumbnail: representationResponse.is_preferred_thumbnail,\n        customData: representationResponse.custom_data,\n        path: representationResponse.path,\n        width: representationResponse.width,\n        height: representationResponse.height,\n        contentLength: representationResponse.content_length,\n        url: representationResponse.url,\n        children: representationResponse.children?.map(mapResponseToRepresentationData)\n    };\n}\n\nexport function mapRepresentationDataToRequest(\n    representationData: RepresentationData,\n    isChild = false\n): RepresentationResponse {\n    return {\n        id: representationData.id,\n        type: representationData.type,\n        relationship: (isChild ? undefined : representationData.relationship) as Exclude<\n        RepresentationData['relationship'],\n        undefined\n        >,\n        is_full_size: false,\n        is_external_link: false,\n        source: representationData.source,\n        children: representationData.children?.map(child => mapRepresentationDataToRequest(child, true)),\n        custom_data: representationData.customData\n    };\n}\n\nexport function mapResponseToTeamData(teamData: TeamResponse): TeamData {\n    return {\n        name: teamData.name,\n        id: teamData.id,\n        owner: {\n            type: teamData.ownerType,\n            id: teamData.ownerId\n        },\n        ownerName: teamData.ownerName,\n        isWritable: teamData.permissions.includes('write')\n    };\n}\n\nexport function mapProjectsResponseToTeamData(projectData: ProjectResponse): TeamData {\n    return {\n        name: projectData.name,\n        id: projectData.id,\n        owner: {\n            type: projectData.storageAssignee.type,\n            id: projectData.storageAssignee.id\n        },\n        ownerName: projectData.storageAssignee.displayName,\n        // SHARED-3702 - Cleanup use of isReadOnly vs isWritable\n        isReadOnly: projectData.isReadOnly,\n        // All project users can edit the project.\n        isWritable: true\n    };\n}\n\nexport function mapResponseToGradientData(gradient: Gradient): GradientData {\n    return {\n        type: gradient.type,\n        angle: gradient.angle,\n        stops: gradient.stops\n    };\n}\n\nexport function mapResponseToLibraryMutations(payload: LibraryChangeResponse): LibraryMutations {\n    const mutations: LibraryMutations = new Map<string, LibraryMutation>();\n\n    if (payload) {\n        Object.entries(payload).forEach(([ id, source ]) => {\n            if (typeof source === 'string') {\n                if (source === '') {return mutations.set(id, { mutation: 'delete', source });}\n                return mutations.set(id, { mutation: 'update', source });\n            } else if (typeof source === 'number') {\n                return mutations.set(id, { mutation: 'update', source });\n            } else if (typeof source === 'object' && source.id) {\n                mutations.set(id, { mutation: 'add', source });\n            }\n        });\n    }\n\n    return mutations;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nexport type RenditionSizeConfig = { [elementType: string]: Array<number> };\nexport type FullRenditionConfig = {\n    [type: string]: [\n        {\n            id: string;\n            condition: string;\n            types: Array<string>;\n        }\n    ];\n};\n\nexport function compareVersions(version1: string, version2: string) {\n    //After effects does not use semver. They append a x before the build number.\n    //We need to replace that with a .\n    version1 = (version1 || '0')\n        .toString()\n        .replace(/(\\.0)*$/, '')\n        .replace(/[^.0-9]+/gim, '.');\n    version2 = (version2 || '0')\n        .toString()\n        .replace(/(\\.0)*$/, '')\n        .replace(/[^.0-9]+/gim, '.');\n    //Workaround for Illustrator CS6 & Illustrator CC returning version as CS6 and the build number instead of semver\n    if (isNaN(parseInt(version1, 10)) || parseInt(version1, 10) > 250) {\n        version1 = '0';\n    }\n    if (isNaN(parseInt(version2, 10)) || parseInt(version2, 10) > 250) {\n        version2 = '0';\n    }\n    if (version1 === version2) {\n        return 0;\n    }\n    const a1 = version1.split('.');\n    const a2 = version2.split('.');\n    let diff;\n    for (let i = 0; i < a1.length && i < a2.length; i++) {\n        diff = parseInt(a1[i], 10) - parseInt(a2[i], 10);\n        if (isNaN(diff)) {\n            if (isNaN(parseInt(a1[i], 10))) {\n                return 1;\n            }\n            return -1;\n        }\n        if (diff > 0) {\n            return -1;\n        }\n        if (diff < 0) {\n            return +1;\n        }\n    }\n    diff = a1.length - a2.length;\n    return diff > 0 ? -1 : diff < 0 ? 1 : 0;\n}\n","import type { TeamsResponse, LibrariesResponse } from './restAPIModelMappers';\n\nexport const isTeamsResponse = (val: {}): val is TeamsResponse => {\n    return (val as TeamsResponse).teams !== undefined;\n};\n\nexport const isLibrariesResponse = (val: {}): val is LibrariesResponse => {\n    return (val as LibrariesResponse).libraries !== undefined;\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * BatchOperation\n * @packageDocumentation\n * @module BatchOperation\n * @internal\n */\n\nimport type { ElementData } from '../../models/data/ElementData';\nimport type { GroupData } from '../../models/data/GroupData';\nimport type { LibraryData } from '../../models/data/LibraryData';\nimport type { Action, UpdateAction, InsertAction, RemoveAction, AggregateAction } from '../../models/Action';\n\nimport type { ExecuteResult } from '../Operation';\nimport Operation, { validatesOperation } from '../Operation';\nimport type {\n    GroupResponse,\n    ElementResponse,\n    LibraryResponse\n} from './utils/restAPIModelMappers';\nimport {\n    mapLibraryDataToRequest,\n    mapGroupDataToRequest,\n    mapElementDataToRequest,\n    mapResponseToLibraryData,\n    mapResponseToElementData,\n    mapResponseToGroupData\n} from './utils/restAPIModelMappers';\nimport type { ProcessRESTOperation } from '../utils/operationUtils';\nimport { tokenizePlaceholders } from '../utils/operationUtils';\n\nimport { extractElementId, extractGroupId } from '../../utils/PathUtils';\nimport { replacePlaceholders } from '../../utils/StoreUtils';\nimport LibraryError from '../../errors/LibraryError';\nimport type LocalDriver from '.';\n\nconst supportedActionNames = [\n    'updateLibrary',\n    'createElement',\n    'updateElement',\n    'removeElement',\n    'restoreElement',\n    'deleteElement',\n    'createGroup',\n    'updateGroup',\n    'removeGroup'\n] as const;\n\ntype SupportedAction = Action & {\n    name: (typeof supportedActionNames)[number];\n};\n\nfunction isSupportedAction(action: Action): action is SupportedAction {\n    return supportedActionNames.includes(action.name as any);\n}\n\nfunction replaceData<T>(action: Action, data: T): Action {\n    return { ...action, data, originalAction: action };\n}\n\nconst RESPONSE_MAPPERS: {\n    [s in (typeof supportedActionNames)[number]]: (action: Action, data?: any) => Action;\n} = {\n    updateLibrary: (action, data) => replaceData(action, mapResponseToLibraryData(data)),\n    createElement: (action, data) => replaceData(action, mapResponseToElementData(data)),\n    updateElement: (action, data) => replaceData(action, mapResponseToElementData(data)),\n    restoreElement: (action, data) => replaceData(action, mapResponseToElementData(data)),\n    removeElement: action => action,\n    deleteElement: action => action,\n    createGroup: (action, data) => replaceData(action, mapResponseToGroupData(data)),\n    updateGroup: (action, data) => replaceData(action, mapResponseToGroupData(data)),\n    removeGroup: action => action\n};\n\nexport default class BatchOperation extends Operation<LocalDriver> {\n    private _actionMappers = {\n        updateLibrary: (action: UpdateAction<LibraryData>): ProcessRESTOperation<Partial<LibraryResponse>> => ({\n            method: 'PUT',\n            path: '',\n            body: mapLibraryDataToRequest(action.data)\n        }),\n        createElement: (action: InsertAction<ElementData>): ProcessRESTOperation<Partial<ElementResponse>> => ({\n            method: 'POST',\n            path: 'elements',\n            body: mapElementDataToRequest(action.data)\n        }),\n        updateElement: (action: UpdateAction<ElementData>): ProcessRESTOperation<Partial<ElementResponse>> => ({\n            method: 'PUT',\n            path: `elements/${extractElementId(action.path as string)}`,\n            body: mapElementDataToRequest(action.data)\n        }),\n        removeElement: (action: RemoveAction | AggregateAction): ProcessRESTOperation<void> => ({\n            method: 'DELETE',\n            path: `elements/${extractElementId(action.path as string)}`\n        }),\n        restoreElement: (action: AggregateAction): ProcessRESTOperation => ({\n            method: 'POST',\n            path: `removed_elements/${action.data.id}/restore`\n        }),\n        deleteElement: (action: RemoveAction): ProcessRESTOperation => ({\n            method: 'DELETE',\n            path: `elements/${extractElementId(action.path as string)}?permanent=true`\n        }),\n        createGroup: (action: InsertAction<GroupData>): ProcessRESTOperation<Partial<GroupResponse>> => ({\n            method: 'POST',\n            path: 'groups',\n            body: mapGroupDataToRequest(action.data)\n        }),\n        updateGroup: (action: UpdateAction<GroupData>): ProcessRESTOperation<Partial<GroupResponse>> => ({\n            method: 'PUT',\n            path: `groups/${extractGroupId(action.path as string)}`,\n            body: mapGroupDataToRequest(action.data)\n        }),\n        removeGroup: (action: RemoveAction | AggregateAction): ProcessRESTOperation => ({\n            method: 'DELETE',\n            path: `groups/${extractGroupId(action.path as string)}${\n                action.flags?.includeElements ? '?include_contents=true' : ''\n            }`\n        })\n    };\n\n    protected _actions: SupportedAction[] = [];\n\n    @validatesOperation\n    async execute(): Promise<ExecuteResult> {\n        const payload = this._actions.map(action => this._actionMappers[action.name](action as never));\n        const tokenizedPayload = tokenizePlaceholders(payload);\n\n        const response = await this._driver.fetch(`/libraries/${this._library.id}`, {\n            method: 'PATCH',\n            headers: {\n                'If-Match': this._library.etag\n            },\n            body: JSON.stringify(tokenizedPayload)\n        });\n\n        const json = await response.json();\n\n        // Response should be an array that's the same size as the number of actions in the batch\n        if (!Array.isArray(json) || json.length !== this._actions.length) {\n            throw new LibraryError('INVALID_RESPONSE', 'Malformed batch response.', this._library.id);\n        }\n\n        // Given the responses, map the actual response onto actions and return the new actions.\n        let newActions = this._actions.map((action, index) => {\n            return RESPONSE_MAPPERS[action.name](action, json[index]);\n        });\n\n        // TODO: Bug here. Any placeholders that need to be replaced not in batch will be missed. We shouldn't do this here.\n        // Replace any placeholders that might exist in the new actions\n        newActions = replacePlaceholders(newActions);\n\n        return { actions: newActions, etag: response.headers.get('ETag') as string };\n    }\n\n    supportsAction(action: Action) {\n        return isSupportedAction(action);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../../models/Action';\nimport type { ElementData } from '../../models/data/ElementData';\n\nimport type { ExecuteResult } from '../Operation';\nimport Operation, { validatesOperation } from '../Operation';\nimport { extractElementId } from '../../utils/PathUtils';\nimport { mapElementDataToRequest, mapResponseToElementData } from './utils/restAPIModelMappers';\nimport type LocalDriver from '.';\nimport { removeRepresentationPlaceholderIds } from '../utils/operationUtils';\nimport { deepCopy } from '../../utils/StoreUtils';\nimport type { RepresentationData } from '../../models/data/RepresentationData';\n\n/**\n * Element content is always replaced entirely, so if we're doing a bunch of representation changes, it makes\n * sense to batch them together.\n *\n * Also, since this operation isn't supported by the batch API, we want to cut down on requests.\n */\nexport default class ContentOperation extends Operation<LocalDriver> {\n    supportsAction(action: Action) {\n        return action.name === 'updateElementContent';\n    }\n\n    addAction(action: Action) {\n        // Content operations must operate on the same element\n        if (this._actions[0] && this._actions[0].path !== action.path) {\n            return false;\n        }\n\n        return super.addAction(action);\n    }\n\n    @validatesOperation\n    async execute(): Promise<ExecuteResult> {\n        // The last content update action will always be the most up-to-date. We can omit all of the ones before it.\n        const lastAction = this._actions[this._actions.length - 1];\n\n        const response = await this._updateElementContent(\n            extractElementId(lastAction.path as string) as string,\n            lastAction.data\n        );\n        const json = await response.json();\n        const data = mapResponseToElementData(json);\n\n        const actions = this._actions.map((action, index): Action => {\n            if (index !== this._actions.length - 1) {\n                return { ...action, type: 'no-op', originalAction: action };\n            } else {\n                return { ...action, data, originalAction: action };\n            }\n        });\n\n        return { actions, etag: response.headers.get('ETag') as string };\n    }\n\n    private _updateElementContent(elementId: string, data: Partial<ElementData>) {\n        // The REST API requires that all new representations not have an ID. If the ID isn't found, then the API\n        // returns an error.\n        const cleanedData = {\n            ...data,\n            representations: removeRepresentationPlaceholderIds(deepCopy(data.representations as RepresentationData[]))\n        };\n\n        return this._driver.fetch(`/libraries/${this._library.id}/elements/${elementId}`, {\n            method: 'PUT',\n            headers: {\n                'If-Match': this._library.etag\n            },\n            body: JSON.stringify(mapElementDataToRequest(cleanedData))\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../../models/Action';\n\nimport SingleOperation from '../SingleOperation';\nimport { mapResponseToLibraryData } from './utils/restAPIModelMappers';\nimport LibraryAbortController from '../LibraryAbortController';\nimport AsyncResponse from '../AsyncResponse';\nimport type LocalDriver from '.';\n\nexport default class LocalSingleOperation extends SingleOperation<LocalDriver> {\n    protected _actionMappers = {\n        createLibrary: (action: Action) => this._createLibraryActionMap(action),\n        copyLibrary: (action: Action) => this._createLibraryActionMap(action),\n        permanentlyDeleteLibrary: (action: Action) => this._permanentlyDeleteLibrary(action),\n        removeLibrary: async (action: Action) => {\n            await this._removeLibrary();\n            return action;\n        },\n        unfollowLibrary: async (action: Action) => {\n            await this._removeLibrary('unfollow');\n            return action;\n        },\n        leaveLibrary: async (action: Action) => {\n            await this._removeLibrary('leave');\n            return action;\n        },\n        moveLibrary: async (action: Action): Promise<Action> => {\n            const data = await this._moveLibrary();\n            return { ...action, data, originalAction: action };\n        }\n    };\n\n    supportsAction(action: Action) {\n        return [\n            'createLibrary',\n            'removeLibrary', // private library\n            'permanentlyDeleteLibrary', // not actually supported, but let it through so we can throw a descriptive error\n            'unfollowLibrary', // leave a team or public or even incoming library\n            'leaveLibrary', // leave an incoming library\n            'copyLibrary',\n            'moveLibrary'\n        ].includes(action.name as string);\n    }\n\n    private async _createLibraryActionMap(action: Action): Promise<Action> {\n        const data = await this._createLibrary(action);\n        return { ...action, type: 'update', data, originalAction: action };\n    }\n\n    private _createLibrary(action: Action) {\n        const { data = {}, flags = {} } = action;\n        return new Promise((resolve, reject) => {\n            const request = this._driver.fetch('/libraries', {\n                method: 'POST',\n                headers: {\n                    'Content-Type': 'application/json'\n                },\n                body: JSON.stringify({\n                    name: data.name,\n                    team_id: data.team?.id,\n                    roles: data.roles,\n                    team_permission_inheritance: flags.permissionInheritance,\n                    source: flags.source?.id\n                })\n            });\n            const asyncResponse = new AsyncResponse(this._driver, request);\n\n            asyncResponse.on('change', (isDone, libraryResponse) => {\n                if (isDone) {\n                    if (asyncResponse.error) {\n                        reject(asyncResponse.error);\n                    }\n                    const libraryData = libraryResponse ? mapResponseToLibraryData(libraryResponse) : undefined;\n                    resolve(libraryData);\n                }\n            });\n        });\n    }\n\n    private _permanentlyDeleteLibrary(_: Action): Promise<Action> {\n        throw new Error('permanentlyDeleteLibrary not supported by LocalDriver, use removeLibrary instead');\n    }\n\n    private _removeLibrary(action: 'unfollow' | 'leave' | 'remove' = 'remove') {\n        // Prevent unnecessary refetching of deleted libraries\n        if (action === 'remove') {\n            LibraryAbortController.getInstance(this._library.id).abort();\n        }\n        const actionPromise = this._driver.fetch(`/libraries/${this._library.id}?action=${action}`, { method: 'DELETE' }).then(() => {\n            // SHARED-2544: Remove instace of library from abort controller's cache after library removal\n            // as this will interfere with fetching restored libraries\n            if (action === 'remove') {\n                LibraryAbortController.removeInstance(this._library.id);\n            }\n        });\n        return actionPromise;\n    }\n\n    private _moveLibrary() {\n        return this._driver.moveLibrary(this._library.id, this.action.data.team.id);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../../models/Action';\nimport type LocalDriver from '.';\n\nimport ParallelOperation from '../ParallelOperation';\n// @ts-expect-error R-TODO\nimport type Library from '../../models/Library';\n\nexport default class LocalParallelOperation extends ParallelOperation<LocalDriver> {\n    protected _actionMappers = {\n        uploadComponent: async (action: Action) => {\n            const path = await this._driver.stageRepresentationForCommit(\n                action.library as Library,\n                action.data.file,\n                action.data.type\n            );\n            return { ...action, data: { path }, originalAction: action };\n        }\n    };\n\n    supportsAction(action: Action) {\n        return action.name === 'uploadComponent';\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n// @ts-expect-error R-TODO\nimport type { default as Library } from '../../models/Library';\nimport type { ElementData } from '../../models/data/ElementData';\n\nimport { mapResponseToElementData } from './utils/restAPIModelMappers';\nimport MoveCopyElementOperation from '../MoveCopyElementOperation';\nimport type LocalDriver from '.';\n\n/**\n * A transfer operation is an operation to move or copy elements or groups.\n * Due to the cross-library nature of these operations, these operations may\n * need to act on two different libraries multiple times.\n */\nexport default class LocalMoveCopyElementOperation extends MoveCopyElementOperation<LocalDriver> {\n    protected async _doMoveCopyRequest(\n        isMove: boolean,\n        sourceLibrary: Library,\n        targetLibrary: Library,\n        elementIds: string[]\n    ): Promise<{ elements: ElementData[]; etag: string | null; sourceEtag: string | null }> {\n        const sourceId = this._library.id;\n        const targetId = targetLibrary.id;\n\n        const response = await this._driver.fetch(`/libraries/${targetId}/elements`, {\n            method: 'POST',\n            headers: {\n                'If-Match': targetLibrary.etag\n            },\n            body: JSON.stringify({\n                [isMove ? 'self' : 'source']: {\n                    id: sourceId,\n                    elements: elementIds,\n                    etag: this._library.etag\n                }\n            })\n        });\n\n        const json = await response.json();\n\n        return {\n            elements: json.elements.map(mapResponseToElementData),\n            etag: response.headers.get('ETag'),\n            sourceEtag: response.headers.get('Source-ETag')\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Action } from '../../models/Action';\n\nimport { extractGroupId } from '../../utils/PathUtils';\nimport type { ExecuteResult } from '../Operation';\nimport Operation, { validatesOperation } from '../Operation';\nimport type LocalDriver from '.';\n\nexport default class MoveCopyGroupOperation extends Operation<LocalDriver> {\n    private get action() {\n        return this._actions[0];\n    }\n\n    supportsAction(action: Action) {\n        return [ 'moveGroup', 'copyGroup', 'dependent' ].includes(action.name as string);\n    }\n\n    addAction(action: Action) {\n        if (!this.supportsAction(action)) {\n            return false;\n        }\n\n        const lastAction = this._actions[this._actions.length - 1];\n\n        if (!lastAction && action.name !== 'dependent') {\n            return super.addAction(action);\n        }\n\n        if (action.name !== 'dependent') {\n            return false;\n        }\n\n        return super.addAction(action);\n    }\n\n    @validatesOperation\n    async execute(): Promise<ExecuteResult> {\n        const isMove = this.action.name === 'moveGroup';\n\n        const sourceId = this._library.id;\n        const targetLibrary = this.action.link?.library;\n        const targetId = targetLibrary?.id;\n        const groupId = extractGroupId(this.action.path as string);\n\n        const response = await this._driver.fetch(`/libraries/${targetId}/groups`, {\n            method: 'POST',\n            headers: {\n                'If-Match': targetLibrary?.etag as string\n            },\n            body: JSON.stringify({\n                [isMove ? 'self' : 'source']: {\n                    id: sourceId,\n                    group_id: groupId,\n                    include_contents: this.action.flags?.includeElements,\n                    etag: this._library.etag\n                }\n            })\n        });\n        const newGroupData = await response.json();\n        let linkedActions: Action[];\n        let actions: Action[];\n\n        if (targetLibrary === this._library) {\n            linkedActions = [];\n            actions = this._actions.map(action => {\n                if (action.name !== 'dependent') {\n                    return action;\n                }\n                return {\n                    ...action,\n                    data: newGroupData,\n                    originalAction: action\n                };\n            });\n        } else {\n            actions = this._actions;\n            linkedActions = this._actions.map(action => ({\n                ...action.link,\n                data: newGroupData,\n                originalAction: action.link\n            })) as Action[];\n        }\n\n        // If this operation succeeds, we wait for the change notification to update the target library.\n        // This operation is only performed optimistically on the source library for now. The reason for this\n        // is that the moveGroup/copyGroup APIs do not provide us the feedback needed to display and reconcile\n        // the optimistic state on that target library. This may change in the future.\n\n        // The result of this is that there will be a lag between when the elements disappear from one library\n        // and appear in the other. This is considered an acceptable compromise in the short-term.\n\n        // linkedEtag intentionally left blank, because we are relying on the pull to update the library to the\n        // correct state.\n        return { actions, etag: response.headers.get('Source-ETag') as string, linkedActions };\n    }\n}\n","'use strict';\n\nmodule.exports = function () {\n  throw new Error(\n    'ws does not work in the browser. Browser clients must use the native ' +\n      'WebSocket object'\n  );\n};\n","import type EventEmitter from 'events';\nimport SSENotificationEventSource from './SSENotificationEventSource';\nimport WebsocketNotificationEventSource from './WebsocketNotificationEventSource';\nimport NodeWebsocketNotificationEventSource from './NodeWebsocketNotificationEventSource';\n\nexport interface INotificationEventSource extends EventEmitter {\n    close(): void;\n}\n\nexport default typeof window === 'undefined'\n    ? NodeWebsocketNotificationEventSource\n    : window?.navigator?.userAgent?.startsWith?.('Adobe UXP Runtime')\n        ? WebsocketNotificationEventSource\n        : SSENotificationEventSource;\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { INotificationEventSource } from './';\n\nimport Logger from '../../../utils/Logger';\nimport LibraryError from '../../../errors/LibraryError';\nimport EventEmitter from 'events';\nimport type { ErrorEvent, MessageEvent } from 'ws';\nimport WebSocket from 'ws';\n\nexport default class NodeWebsocketNotificationEventSource extends EventEmitter implements INotificationEventSource {\n    private _ws: WebSocket;\n\n    constructor(url: string) {\n        super();\n        // Make sure the url has right protocol for websocket connection.\n        const wsUrl = url.replace(/http(s?):\\/\\//, 'ws$1://');\n        this._ws = new WebSocket(wsUrl);\n\n        this._ws.addEventListener('message', (event: MessageEvent) => {\n            try {\n                const { type, message } = JSON.parse(event.data as string) as {\n                    type: string;\n                    message: Record<string, any>;\n                };\n                Logger.log(`[NOTIFICATIONS] Received event: ${type}`);\n                this.emit(type, message);\n            } catch {\n                this.emit('error', new LibraryError('INVALID_JSON', 'Received invalid JSON'));\n            }\n        });\n\n        this._ws.addEventListener('error', (error: ErrorEvent) => {\n            this.close();\n            this.emit('error', error);\n        });\n    }\n\n    get isOpen() {\n        return this._ws.readyState === this._ws.OPEN;\n    }\n\n    close() {\n        if (this.isOpen) {\n            this.removeAllListeners();\n            this._ws.close();\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { INotificationEventSource } from './';\n\nimport Logger from '../../../utils/Logger';\nimport LibraryError from '../../../errors/LibraryError';\nimport EventEmitter from 'events';\n\nexport default class WebsocketNotificationEventSource extends EventEmitter implements INotificationEventSource {\n    private _ws: WebSocket;\n\n    constructor(url: string) {\n        super();\n        // Make sure the url has right protocol for websocket connection.\n        const wsUrl = url.replace(/http(s?):\\/\\//, 'ws$1://');\n        this._ws = new WebSocket(wsUrl);\n\n        this._ws.addEventListener('message', (event: MessageEvent) => {\n            try {\n                const { type, message } = JSON.parse(event.data) as { type: string; message: Record<string, any> };\n                Logger.log(`[NOTIFICATIONS] Received event: ${type}`);\n                this.emit(type, message);\n            } catch {\n                this.emit('error', new LibraryError('INVALID_JSON', 'Received invalid JSON'));\n            }\n        });\n\n        this._ws.addEventListener('error', (error: Event) => {\n            this.close();\n            this.emit('error', error);\n        });\n    }\n\n    get isOpen() {\n        return this._ws.readyState === this._ws.OPEN;\n    }\n\n    close() {\n        if (this.isOpen) {\n            this.removeAllListeners();\n            this._ws.close();\n        }\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { INotificationEventSource } from './';\nimport Logger from '../../../utils/Logger';\nimport LibraryError from '../../../errors/LibraryError';\nimport EventEmitter from 'events';\n\nconst MAX_SILENT_RETRIES = 3;\n\nexport default class SSENotificationEventSource extends EventEmitter implements INotificationEventSource {\n    private _eventSource: EventSource;\n    private _listenedEvents: Set<string> = new Set();\n    private _errorCount = 0;\n\n    constructor(url: string) {\n        super();\n        this._eventSource = new EventSource(url);\n        this._eventSource.onopen = () => {\n            this._errorCount = 0;\n        };\n        this._eventSource.onerror = (error: Event) => {\n            this._errorCount += 1;\n\n            if (this._errorCount >= MAX_SILENT_RETRIES) {\n                this.close();\n                this.emit('error', error);\n            }\n        };\n    }\n\n    on(eventName: string, callback: (...args: any[]) => void): this {\n        super.on(eventName, callback);\n\n        if (!this._listenedEvents.has(eventName)) {\n            this._listenedEvents.add(eventName);\n\n            // We should probably clean this up, but on the other hand ¯\\_(ツ)_/¯\n            this._eventSource.addEventListener(eventName, (message: MessageEvent) => {\n                Logger.log(`[NOTIFICATIONS] Received event: ${eventName}`);\n                try {\n                    this.emit(eventName, JSON.parse(message.data));\n                } catch {\n                    if (!message.data) {\n                        this.emit('error', new LibraryError('INVALID_RESPONSE', 'Received invalid response (no data)'));\n                    } else {\n                        this.emit('error', new LibraryError('INVALID_JSON', 'Received invalid JSON'));\n                    }\n                }\n            });\n        }\n\n        return this;\n    }\n\n    close() {\n        this.removeAllListeners();\n        this._eventSource.close();\n    }\n}\n","import type { UnderlyingError } from '../errors/LibraryError';\nimport LibraryError from '../errors/LibraryError';\n\ntype APIVersionInfo = {\n    apiVersion: number;\n    apiMinVersion: number;\n    apiMaxVersion: number;\n};\n\ntype SuccessfulConnectionInfo = Partial<APIVersionInfo> & {\n    token: string;\n    hostname: string;\n};\n\ntype UpdateRequiredConnectionInfo = Partial<APIVersionInfo> & {\n    updateRequired: 'client' | 'server';\n};\n\nexport type ConnectionInfo = SuccessfulConnectionInfo | UpdateRequiredConnectionInfo;\n\nexport function isUpdateRequiredInfo(info: ConnectionInfo): info is UpdateRequiredConnectionInfo {\n    return 'updateRequired' in info;\n}\n\nexport type VulcanCallback = (message: string) => void;\n\nexport type VulcanMessageType = {\n    REQUEST: string;\n    RESPONSE: string;\n    INITIALIZE: string | null;\n};\n\nexport default abstract class Connector<VulcanInterface, VulcanMessage> {\n    protected vulcanInterface: VulcanInterface;\n    protected VulcanMessage: VulcanMessage;\n    private _timeout: number;\n    private _launchTimeout: number;\n    private _timeoutId?: number;\n\n    constructor(vulcanInterface: VulcanInterface, vulcanMessage?: VulcanMessage, timeout = 2000, launchTimeout = 8000) {\n        this.vulcanInterface = vulcanInterface;\n        this.VulcanMessage = vulcanMessage as VulcanMessage;\n        this._timeout = timeout;\n        this._launchTimeout = launchTimeout;\n    }\n\n    private _generateListener(callback: Function, type?: string): VulcanCallback {\n        const listener: VulcanCallback = (message?: string) => {\n            clearTimeout(this._timeoutId);\n            this.removeListener(listener, type);\n            callback(message);\n        };\n        return listener;\n    }\n\n    private async _connectionInfoHandler(message?: string, abortSignal?: AbortSignal): Promise<ConnectionInfo | void> {\n        if (abortSignal?.aborted) {\n            // At this point the overarching connect workflow has timed out.\n            // So we do not want to throw here\n            return;\n        }\n\n        if (!message) {\n            throw new LibraryError('REQUEST_FAILED', 'No Vulcan response received');\n        }\n\n        try {\n            const payload = JSON.parse(this.getPayload(message));\n            const apiVersionInfo: APIVersionInfo = {\n                apiVersion: payload.apiVersion,\n                apiMinVersion: payload.apiMinVersion,\n                apiMaxVersion: payload.apiMaxVersion\n            };\n            if (payload.updateRequired) {\n                return {\n                    ...apiVersionInfo,\n                    updateRequired: payload.updateRequired\n                };\n            }\n            if (payload.serviceToken && payload.serviceHostname) {\n                return {\n                    ...apiVersionInfo,\n                    token: payload.serviceToken,\n                    hostname: payload.serviceHostname\n                };\n            }\n            throw new LibraryError('INVALID_RESPONSE', 'Incorrect data was returned via Vulcan');\n        } catch (error) {\n            throw new LibraryError(\n                'INVALID_RESPONSE',\n                'Incorrect data was returned via Vulcan',\n                undefined,\n                error as UnderlyingError\n            );\n        }\n    }\n\n    private async _launchProcessHandler(message?: string, abortSignal?: AbortSignal) {\n        if (abortSignal?.aborted) {\n            // At this point the overarching connect workflow has timed out.\n            // So we do not want to throw here\n            return;\n        }\n\n        if (!message) {\n            throw new LibraryError('REQUEST_FAILED', 'No Vulcan response received');\n        }\n        return this._requestConnectionInfo(abortSignal);\n    }\n\n    private _launchProcess(abortSignal?: AbortSignal) {\n        return new Promise<ConnectionInfo | void>(resolve => {\n            const launchProcessCallback = this._generateListener(\n                (message: string) => resolve(this._launchProcessHandler(message, abortSignal)),\n                this.getMessageType('INITIALIZE') as string\n            );\n            this._timeoutId = setTimeout(launchProcessCallback, this._launchTimeout);\n            this.sendMessage(launchProcessCallback, this.getMessageType('INITIALIZE') as string);\n            this.launchApp(launchProcessCallback);\n        });\n    }\n\n    private _requestConnectionInfo(abortSignal?: AbortSignal): Promise<ConnectionInfo | void> {\n        return new Promise(resolve => {\n            const connectionInfoCallback = this._generateListener((message?: string) => {\n                resolve(this._connectionInfoHandler(message, abortSignal));\n            });\n            this._timeoutId = setTimeout(connectionInfoCallback, this._timeout);\n            this.sendMessage(connectionInfoCallback);\n        });\n    }\n\n    public async connect(abortSignal?: AbortSignal) {\n        // Always try connecting first. (local process running bug where connection info is not broadcasted)\n        return this._requestConnectionInfo(abortSignal).catch(async err => {\n            if (!(await this.isAppRunning().catch(() => false))) {\n                return this._launchProcess(abortSignal);\n            }\n            throw err;\n        });\n    }\n\n    protected getMessageType(key: keyof VulcanMessageType) {\n        return this.messageTypes[key];\n    }\n\n    protected abstract messageTypes: VulcanMessageType;\n    abstract removeListener(callback: VulcanCallback, type?: string): void;\n    abstract sendMessage(callback: VulcanCallback, type?: string): void;\n    abstract isAppRunning(): Promise<boolean>;\n    abstract launchApp(callback: VulcanCallback): void;\n    abstract getPayload(message: string | VulcanMessage): string;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * LocalDriver\n * @packageDocumentation\n * @module LocalDriver\n */\n\nimport type { ElementData } from '../../models/data/ElementData';\nimport type { GroupData } from '../../models/data/GroupData';\nimport type { LibraryData } from '../../models/data/LibraryData';\nimport type { CollaboratorData } from '../../models/data/CollaboratorData';\nimport type { GradientData, TeamData } from '../../models/Team';\nimport type Team from '../../models/Team';\nimport type { FontData } from '../../models/data/FontData';\nimport type { SyncStateNotification } from '../../models/SyncStatus';\n\nimport LibraryError from '../../errors/LibraryError';\n// @ts-expect-error R-TODO\nimport type Library from '../../models/Library';\nimport type Element from '../../models/Element';\nimport type {\n    ConnectorParam,\n    DriverOptions,\n    ElementSort,\n    FetchRequestInit,\n    GetElementsOptions,\n    GetLibraryOptions,\n    PaginatedResponse,\n    SearchFilters\n} from '../Driver';\nimport Driver from '../Driver';\nimport CloudDriver from '../CloudDriver';\nimport AsyncResponse from '../AsyncResponse';\nimport LibraryAbortController from '../LibraryAbortController';\nimport type {\n    LibrariesResponse,\n    ElementsResponse,\n    SearchElementsResponse,\n    LibraryChangeBody,\n    LibraryChangeResponse,\n    LibraryResponse,\n    TeamsResponse,\n    ProjectsResponse,\n    ProjectGradientResponse,\n    ElementResponse\n} from './utils/restAPIModelMappers';\nimport {\n    mapResponseToLibraryData,\n    mapResponseToElementData,\n    mapResponseToTeamData,\n    mapProjectsResponseToTeamData,\n    mapResponseToGradientData\n} from './utils/restAPIModelMappers';\nimport type { FullRenditionConfig, RenditionSizeConfig } from './utils/generalUtils';\nimport { compareVersions } from './utils/generalUtils';\nimport { isTeamsResponse, isLibrariesResponse } from './utils/responseUtils';\nimport { combineSignals } from '../../utils/SignalUtils';\nimport BatchOperation from './BatchOperation';\nimport ContentOperation from './ContentOperation';\nimport SingleOperation from './SingleOperation';\nimport ParallelOperation from './ParallelOperation';\nimport RequestError, { getRequestError } from '../../errors/RequestError';\nimport MoveCopyElementOperation from './MoveCopyElementOperation';\nimport MoveCopyGroupOperation from './MoveCopyGroupOperation';\nimport Configuration from '../../models/Configuration';\nimport type ApplicationAction from '../../models/ApplicationAction';\nimport type Representation from '../../models/Representation';\nimport { getMimeTypes } from '../../utils/MimeTypeUtils';\nimport type { INotificationEventSource } from './NotificationEventSource';\nimport NotificationEventSource from './NotificationEventSource';\nimport type { ConfigurationData } from '../../models/data/ConfigurationData';\nimport Logger from '../../utils/Logger';\nimport type { RenditionSize } from '../../types';\nimport { ABORT_ERROR, HttpStatus } from '../../config/constants';\nimport type { ConnectionInfo } from '../../connectors/Connector';\nimport { isUpdateRequiredInfo } from '../../connectors/Connector';\nimport type ISAMCorePrivate from '@sam-js-src/core/ISAMCorePrivate';\nimport type { ElementsResponse as MelvilleElementsResponse } from '../CloudDriver/utils/melvilleModelMappers';\n\ntype CloudParams = {\n    clientId: string;\n    clientSecret: string;\n    scopes: string;\n    core: ISAMCorePrivate;\n};\n\nexport type Params = ConnectionInfo & {\n    cloudParams?: CloudParams;\n};\n\ntype ElementClass = 'elements' | 'documentationElements' | 'removedElements';\ntype ElementGenerator =\n    | '_getElementsByLibraryId'\n    | '_getDocumentationElementsByLibraryId'\n    | '_getRemovedElementsByLibraryId';\n\nconst defaultElementSort: ElementSort = {\n    field: 'modifiedDate',\n    direction: 'descending'\n};\n\ntype FetchOptions = {\n    reconnectOnErrors?: number[];\n    reconnectOnNoResponse?: boolean;\n    optimisticFetch?: boolean;\n};\n\nconst DEFAULT_FETCH_OPTIONS: FetchOptions = {\n    reconnectOnErrors: [ 401, 403 ],\n    reconnectOnNoResponse: true\n};\n\nexport type LocalDriverOptions = DriverOptions & {\n    optimistic?: boolean;\n    ignoreRenditionGrids?: boolean;\n};\n\nexport default class LocalDriver extends Driver<Params, LocalDriverOptions> {\n    private _hostname?: string;\n    private _cloudParams?: CloudParams;\n\n    private _notificationEventSource?: INotificationEventSource;\n\n    private _libraryChangeListener: (libraryIds: string[]) => any = () => {\n        return;\n    };\n    private _renditionCacheChangeListener: (element: ElementData) => any = () => {\n        /**/\n    };\n    private _lastNotificationPayload: any = {};\n\n    protected _operationTypes = [\n        BatchOperation,\n        ContentOperation,\n        SingleOperation,\n        MoveCopyElementOperation,\n        MoveCopyGroupOperation,\n        ParallelOperation\n    ];\n\n    constructor(core: ISAMCorePrivate, connector: ConnectorParam<Params>, options: LocalDriverOptions = {}) {\n        super(core, connector);\n        this._options = options;\n    }\n\n    getLibrary(library: Library, options?: GetLibraryOptions) {\n        return this._getLibraryById(library.id, options);\n    }\n\n    getElements(library: Library, ...args: any[]) {\n        return this._getElementsByLibraryId(library.id, ...args);\n    }\n\n    getRemovedElements(library: Library, ...args: any[]) {\n        return this._getRemovedElementsByLibraryId(library.id, ...args);\n    }\n\n    getDocumentationElements(library: Library, ...args: any[]) {\n        return this._getDocumentationElementsByLibraryId(library.id, ...args);\n    }\n\n    getElement(library: Library, elementId: string) {\n        return this._getElement(library.id, elementId);\n    }\n\n    reconnect() {\n        this._notificationEventSource?.close();\n        if (this.isConnected) {return super.reconnect();}\n        return Promise.resolve();\n    }\n\n    protected async _handleConnected(data: Params) {\n        if (isUpdateRequiredInfo(data)) {\n            this._handleConfigurationMutation({\n                config: {},\n                environment: this._config.environment,\n                processInfo: {\n                    updateRequired: data.updateRequired,\n                    apiVersion: data.apiVersion\n                }\n            });\n            throw new LibraryError(\n                'CONNECTION_FAILED',\n                `LocalDriver failed to connect - ${data.updateRequired} update required`\n            );\n        }\n\n        this._hostname = data.hostname;\n        this._token = data.token;\n        this._cloudParams = data.cloudParams;\n        this._notificationEventSource = new NotificationEventSource(\n            `${this._hostname}/notifications?token=${this._token}`\n        );\n\n        this._notificationEventSource.on('error', (error: Error | LibraryError) => {\n            if (error instanceof LibraryError && error.libraryErrorCode === 'INVALID_JSON') {\n                Logger.log('[NOTIFICATIONS] Received invalid JSON object.');\n                return;\n            }\n\n            this.reconnect();\n        });\n\n        await this.getConfiguration();\n        this._notificationEventSource.on('configurationMutation', this._handleConfigurationMutation.bind(this));\n        this._notificationEventSource.on('libraryMutation', this._handleLibraryMutation.bind(this));\n        this._notificationEventSource.on('renditionCacheMutation', this._handleRenditionCacheMutation.bind(this));\n    }\n\n    protected _handleDisconnected() {\n        this._notificationEventSource?.close();\n    }\n\n    get cloudParams() {\n        if (!this._cloudParams || !this.config.user?.id) {\n            return undefined;\n        }\n\n        return {\n            ...this._cloudParams,\n            userId: this.config.user?.id\n        };\n    }\n\n    getCloudDriver(): CloudDriver {\n        if (!this.cloudParams) {\n            return undefined as unknown as CloudDriver;\n        }\n\n        const connector = async () => {\n            const { userId, clientId, clientSecret, scopes, core } = this.cloudParams as Exclude<\n            LocalDriver['cloudParams'],\n            undefined\n            >;\n\n            const { access_token } = await this.fetchAccessToken(userId, clientId, clientSecret, scopes);\n\n            return {\n                env: this.config.environment,\n                core,\n                token: access_token\n            };\n        };\n\n        return new CloudDriver(this._core, connector);\n    }\n\n    fetchAccessToken(userId: string, clientId: string, clientSecret: string, scopes: string) {\n        return this.fetch('/configuration/access_token', {\n            method: 'POST',\n            body: JSON.stringify({ userId: this._config.user?.id, clientId, clientSecret, scopes })\n        }).then(res => res.json());\n    }\n\n    private _getElement(libraryId: string, elementId: string): Promise<ElementData> {\n        return this.fetch(`/libraries/${libraryId}/elements/${elementId}`)\n            .then(res => res.json())\n            .then(mapResponseToElementData);\n    }\n\n    private async *_getElementsOfType(\n        type: 'elements' | 'removed_elements' | 'documentation_elements',\n        libraryId: string,\n        _sort: ElementSort = defaultElementSort,\n        etag?: string,\n        signal?: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        // TODO: Sort\n\n        const headers: any = {};\n\n        if (etag) {\n            headers['if-none-match'] = etag;\n        }\n\n        const res = await this.fetch(`/libraries/${libraryId}/${type}`, { headers, signal });\n        const json: ElementsResponse = await res.json();\n        yield json.elements.map(mapResponseToElementData);\n    }\n\n    private async *_getElementsByLibraryId(\n        libraryId: string,\n        sort: ElementSort = defaultElementSort,\n        etag?: string,\n        limit?: number,\n        signal?: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        yield* this._getElementsOfType('elements', libraryId, sort, etag, signal);\n    }\n\n    async getElementsPage(\n        _library: Library,\n        _start?: number,\n        _limit?: number,\n        _sort?: ElementSort,\n        _etag?: string,\n    ): Promise<MelvilleElementsResponse> {\n        throw new LibraryError('NOT_IMPLEMENTED', 'LocalDriver.getElementsPage not implemented.');\n    }\n\n    async *getSearchResults(\n        searchQuery: string,\n        filters: SearchFilters,\n        elementSort: ElementSort,\n        signal: AbortSignal\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        filters.elements_only = true;\n        let orderBy = elementSort.field === 'name' ? 'name' : 'modified_date';\n        if (elementSort.direction === 'descending') {\n            orderBy = `-${orderBy}`;\n        }\n\n        const responseMapper = (response: SearchElementsResponse) =>\n            response.results?.map(mapResponseToElementData) ?? [];\n\n        const headers: any = {\n            method: 'POST',\n            headers: {\n                'Content-Type': 'application/json'\n            },\n            signal\n        };\n\n        const limit = 300;\n\n        // We only group search results by type so if the section type is anything\n        // other than \"type\" we just do a normal search of all types\n        if (elementSort.sectionType !== 'type') {\n            headers.body = JSON.stringify({\n                q: searchQuery,\n                order_by: orderBy,\n                filters,\n                limit\n            });\n            yield* this.fetchAllPages('/search', headers, responseMapper);\n        } else {\n            // If there is a list of type sections we want to fetch search results for each type separately\n            // so that we get our results as a list of ordered elements grouped by element type.\n            for (const section of elementSort.sections as string[]) {\n                filters.element_types = filters.element_types = [ section ];\n                headers.body = JSON.stringify({\n                    q: searchQuery,\n                    order_by: orderBy,\n                    filters,\n                    limit\n                });\n                yield* this.fetchAllPages('/search', headers, responseMapper);\n            }\n        }\n    }\n\n    async *fetchAllPages<T, U>(\n        firstUrl: string,\n        headers: any,\n        responseMapper: (response: T) => PaginatedResponse<U>\n    ): AsyncGenerator<PaginatedResponse<U>> {\n        let nextUrl = firstUrl;\n        while (nextUrl) {\n            const response = await this.fetch(nextUrl, headers).then(res => res.json());\n            yield responseMapper(response);\n            nextUrl = response._links?.next?.uri;\n            const newBody = response._links?.next?.body;\n            if (newBody) {\n                headers.body = JSON.stringify(newBody);\n            }\n        }\n    }\n\n    private async *_getDocumentationElementsByLibraryId(\n        libraryId: string,\n        sort: ElementSort = defaultElementSort,\n        etag?: string\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        yield* this._getElementsOfType('documentation_elements', libraryId, sort, etag);\n    }\n\n    private async *_getRemovedElementsByLibraryId(\n        libraryId: string,\n        sort: ElementSort = defaultElementSort,\n        etag?: string\n    ): AsyncGenerator<PaginatedResponse<ElementData>> {\n        yield* this._getElementsOfType('removed_elements', libraryId, sort, etag);\n    }\n\n    async getTeams(): Promise<TeamData[]> {\n        const response = await this.fetch('/teams');\n        const data: TeamsResponse = await response.json();\n        return isTeamsResponse(data) ? data.teams.map(mapResponseToTeamData) : [];\n    }\n\n    async getProjects(): Promise<TeamData[]> {\n        const response = await this.fetch('/projects');\n        const data: ProjectsResponse = await response.json();\n        return data?.projects?.map(mapProjectsResponseToTeamData) ?? [];\n    }\n\n    async getProjectGradient(project: Team): Promise<GradientData | undefined> {\n        const response = await this.fetch(`/projects/${project.id}/gradient`);\n        const data: ProjectGradientResponse = await response.json();\n        return data.gradient ? mapResponseToGradientData(data.gradient) : undefined;\n    }\n\n    async *getGroups(_libraryId: string): AsyncGenerator<PaginatedResponse<GroupData>> {\n        yield Promise.resolve(undefined as unknown as PaginatedResponse<GroupData>);\n    }\n\n    async *getLibraries(): AsyncGenerator<PaginatedResponse<LibraryData>> {\n        // The includeRenditionGrid flag on this endpoint will include only elements in the rendition grid, but setting it to false will not cause all elements to be returned.\n        // The paths of renditions for image elements in the rendition grid will only be returned when cached.\n        // This flag will not cause the imaging service to generate renditions like getRenditionPath would.\n        let endpoint = '/libraries';\n        if (!this._options.ignoreRenditionGrids) {\n            endpoint += '?includeRenditionGrid=true';\n        }\n        yield this.fetch(endpoint)\n            .then(res => res.json())\n            .then((res: LibrariesResponse) =>\n                isLibrariesResponse(res)\n                    ? res.libraries.map(data => mapResponseToLibraryData(data, this._options.readOnly))\n                    : []\n            );\n    }\n\n    async *getLibrariesList(): AsyncGenerator<PaginatedResponse<LibraryData>> {\n        yield Promise.resolve(undefined as unknown as PaginatedResponse<LibraryData>);\n    }\n\n    async *getLibrariesPage(): AsyncGenerator<PaginatedResponse<LibraryData>> {\n        yield Promise.resolve(undefined as unknown as PaginatedResponse<LibraryData>);\n    }\n\n    protected async *_getAllElements(\n        libraryId: string,\n        options: GetElementsOptions\n    ): AsyncGenerator<Partial<LibraryData>> {\n        const elementTypes: [ElementClass, ElementGenerator][] = [\n            [ 'elements', '_getElementsByLibraryId' ],\n            [ 'documentationElements', '_getDocumentationElementsByLibraryId' ],\n            [ 'removedElements', '_getRemovedElementsByLibraryId' ]\n        ];\n\n        // If the elements aren't loaded yet, update the library page by page\n        // Otherwise, load them all at once.\n        const updateData: Partial<LibraryData> = {};\n\n        // TODO: We want to run all element type iterators at the same time. Right now it doesn't matter since we only deal with normal elements.\n        for (const [ type, generator ] of elementTypes) {\n            if (options.types.includes(type)) {\n                for await (const page of this[generator](\n                    libraryId,\n                    options.sort,\n                    options.etag,\n                    undefined,\n                    options.abortController?.signal\n                )) {\n                    updateData[type] = updateData[type] || [];\n                    updateData[type]?.push(...page);\n                    if (options.loadProgressively) {\n                        yield { [type]: updateData[type] };\n                    }\n                }\n            }\n        }\n\n        yield { areElementsLoaded: true, ...(options.loadProgressively ? {} : updateData) };\n    }\n\n    async getLibraryById(libraryId: string, options?: GetLibraryOptions) {\n        const { value } = await this._getLibraryById(libraryId, options).next();\n        return value;\n    }\n\n    async *_getLibraryById(libraryId: string, options: GetLibraryOptions = {}): AsyncGenerator<Partial<LibraryData>> {\n        const etag = options.etag;\n        try {\n            const headers: HeadersInit = {};\n\n            if (etag) {\n                headers['if-none-match'] = etag;\n            }\n\n            let fetchOptions: FetchOptions | undefined;\n            if (options.optimisticFetch !== undefined) {\n                fetchOptions = { optimisticFetch: options.optimisticFetch };\n            }\n\n            // The includeRenditionGrid flag on this endpoint is equivalent to saying do not include elements except those in the rendition grid\n            let endpoint = `/libraries/${libraryId}`;\n            if (!this._options.ignoreRenditionGrids) {\n                endpoint += '?includeRenditionGrid=true';\n            }\n            const res = await this.fetch(endpoint, { headers }, fetchOptions);\n\n            // If we receive a 202 here, the process is optimistically loading the library to disk...\n            // we can return early\n            if (res.status === 202) {\n                return;\n            }\n\n            const json = await res.json();\n            json.etag = res.headers.get('ETag');\n\n            // We do not care about the updated elements from this call unless they are rendition grid elements.\n            // If all elements need to be updated, that will be done by this._getAllElements.\n            if (options.elementParams) {\n                delete json.elements;\n            } else {\n                // Elements path should exist on library data to append new elements, in case of empty library\n                json.elements ??= [];\n            }\n\n            const libraryResponse = mapResponseToLibraryData(json, this._options.readOnly);\n            yield libraryResponse;\n        } catch (error) {\n            if (!(error instanceof RequestError && error.requestErrorCode === 'NOT_MODIFIED' && options.elementParams)) {\n                throw error;\n            }\n        }\n\n        if (options.elementParams) {\n            yield* this._getAllElements(libraryId, {\n                ...options.elementParams,\n                etag: options.firstElementsLoad ? undefined : etag\n            });\n        }\n    }\n\n    followLibrary(assetId: string, libraryId: string): Promise<void> {\n        return this.fetch('/libraries', {\n            method: 'POST',\n            body: JSON.stringify({\n                follow: true,\n                type: 'collab',\n                id: libraryId,\n                assetId\n            })\n        }).then((/** bookmark */) => {\n            // The bookmark data is basically a copy of the request body.\n            // It doesn't have anything useful to the caller, so we won't send it back.\n            return;\n        });\n    }\n\n    moveLibrary(libraryId: string, folderId: string): Promise<LibraryData | void> {\n        return new Promise((resolve, reject) => {\n            const request = this.fetch('/libraries', {\n                method: 'POST',\n                body: JSON.stringify({\n                    self: libraryId,\n                    team_id: folderId\n                })\n            });\n            const asyncResponse = new AsyncResponse(this, request);\n\n            asyncResponse.on('change', (isDone, libraryResponse) => {\n                if (isDone) {\n                    if (asyncResponse.error) {\n                        reject(asyncResponse.error);\n                    } else if (libraryResponse) {\n                        resolve(mapResponseToLibraryData(libraryResponse));\n                    } else {\n                        resolve();\n                    }\n                }\n            });\n        });\n    }\n\n    importLibrary(\n        file: string | File,\n        callback: (error?: Error, libraryData?: LibraryData) => unknown = () => undefined\n    ): AsyncResponse<LocalDriver> {\n        if (typeof file !== 'string') {\n            throw new Error('Input must be a local path in local mode.');\n        }\n\n        const request = this.fetch('/libraries', {\n            method: 'POST',\n            body: JSON.stringify({\n                source: {\n                    path: file\n                }\n            })\n        });\n\n        const asyncResponse = new AsyncResponse(this, request);\n\n        asyncResponse.on('change', (isDone: boolean, libraryResponse: LibraryResponse) => {\n            if (isDone) {\n                const libraryData = libraryResponse ? mapResponseToLibraryData(libraryResponse) : undefined;\n                callback(asyncResponse.error, libraryData);\n            }\n        });\n\n        return asyncResponse;\n    }\n\n    exportLibrary(\n        library: Library,\n        path?: string,\n        callback: (error?: Error) => unknown = () => undefined\n    ): AsyncResponse<LocalDriver> {\n        if (!path) {\n            // TODO\n            throw new Error('Destination path is required in local mode.');\n        }\n\n        const request = this.fetch(`/libraries/${library.id}/export`, {\n            method: 'POST',\n            body: JSON.stringify({ path })\n        });\n\n        const asyncResponse = new AsyncResponse(this, request);\n\n        asyncResponse.on('change', (isDone: boolean) => {\n            if (isDone) {\n                callback(asyncResponse.error);\n            }\n        });\n\n        return asyncResponse;\n    }\n\n    async abortOperation(operationId: string): Promise<Response> {\n        return this.fetch(operationId, {\n            method: 'DELETE'\n        });\n    }\n\n    getRenditionUrl(element: Element, size: RenditionSize): string {\n        return `${this._hostname}/libraries/${element.library.id}/elements/${element.elementId}/renditions/${size}?token=${this._token}`;\n    }\n\n    getAuthenticatedThumbnailURL(element: Element, size: RenditionSize): Promise<string> {\n        return this.fetch(`/libraries/${element.library.id}/elements/${element.elementId}/renditions/${size}/url`, {\n            headers: {\n                'cache-control': 'none'\n            }\n        })\n            .then(res => res.json())\n            .then(res => res.url);\n    }\n\n    getRenditionPath(libraryId: string, elementId: string, size: RenditionSize): Promise<string> {\n        const controllerInstance: AbortController = LibraryAbortController.getInstance(libraryId);\n        return this.fetch(`/libraries/${libraryId}/elements/${elementId}/renditions/${size}/path`, {\n            headers: {\n                'cache-control': 'none' // if the rendition does not exist, it will be generated and added to the cache\n            },\n            signal: controllerInstance.signal\n        })\n            .then(res => res.json())\n            .then(res => res.path);\n    }\n\n    getRendition(element: Element, size: RenditionSize): Promise<Response> {\n        return this.fetch(`/libraries/${element.library.id}/elements/${element.elementId}/renditions/${size}`);\n    }\n\n    getRepresentationContent(representation: Representation): Promise<Response> {\n        return this.fetch(\n            `/libraries/${representation.library.id}/elements/${representation.element.elementId}/representations/${representation.id}`\n        );\n    }\n\n    setLibraryChangeListener(libraries: LibraryData[], callback: (libraryIds: string[]) => any): void {\n        this._libraryChangeListener = callback;\n    }\n\n    setRenditionCacheChangeListener(callback: (elementData: ElementData) => any): void {\n        this._renditionCacheChangeListener = callback;\n    }\n\n    setFontDataChangeListener(callback: () => void): void {\n        this.removeFontDataChangeListeners();\n        this._notificationEventSource?.on('fontDataMutation', callback);\n    }\n\n    setSyncStateListener(callback: (state: SyncStateNotification) => void) {\n        this._notificationEventSource?.removeAllListeners('syncMutation');\n        this._notificationEventSource?.on('syncMutation', callback);\n    }\n\n    removeLibraryChangeListener() {\n        this._notificationEventSource?.removeAllListeners('libraryMutation');\n    }\n\n    removeFontDataChangeListeners() {\n        this._notificationEventSource?.removeAllListeners('fontDataMutation');\n    }\n\n    removeSyncStateListener() {\n        this._notificationEventSource?.removeAllListeners('syncMutation');\n    }\n\n    removeRenditionCacheChangeListener() {\n        this._notificationEventSource?.removeAllListeners('renditionCacheMutation');\n    }\n\n    private _handleConfigurationMutation = (data: ConfigurationData): Configuration => {\n        const configurationUpdate = new Configuration(data);\n\n        if (this._needToReconnect(configurationUpdate)) {\n            this.reconnect();\n        }\n        this._config = configurationUpdate;\n        this.emit('configChange');\n        return this.config;\n    };\n\n    private _handleRenditionCacheMutation = (data: ElementResponse): void => {\n        this._renditionCacheChangeListener(mapResponseToElementData(data));\n    };\n\n    private _handleLibraryMutation = (payload: LibraryChangeResponse): void => {\n        if (!payload) {\n            return;\n        }\n\n        // See what changed / was removed\n        const responseKeys = new Set(Object.keys(payload));\n        const libraryIds: string[] = Object.keys(this._lastNotificationPayload).filter(libraryId => {\n            const libraryResponseEntry = payload[libraryId];\n            responseKeys.delete(libraryId);\n            return (\n                !libraryResponseEntry\n                || (typeof libraryResponseEntry !== 'number' && typeof libraryResponseEntry !== 'string')\n            );\n        });\n\n        // Add in any new libraries\n        libraryIds.push(...responseKeys);\n\n        this._lastNotificationPayload = Object.keys(payload).reduce(\n            (memo: LibraryChangeBody, key: string): LibraryChangeBody => {\n                const value: string | number | LibraryResponse = payload[key];\n                if (typeof value === 'number' || typeof value === 'string') {\n                    if (value) {\n                        // deleted libraries have empty string values\n                        memo[key] = value;\n                    }\n                } else {\n                    memo[key] = value.modified_date;\n                }\n\n                return memo;\n            },\n            {}\n        );\n\n        this._libraryChangeListener(libraryIds);\n    };\n\n    private _needToReconnect(configUpdate: Configuration): boolean {\n        return (\n            // We were previously authenticated with 1 user and that information has changed in the process....\n            // Reconnect\n            (this.config?.user?.id && this.config.user.id !== configUpdate.user?.id) || false\n        );\n    }\n\n    async getConfiguration(): Promise<Configuration> {\n        const response = await this.fetch('/configuration');\n        const json = await response.json();\n        this._handleConfigurationMutation(json);\n        return this.config;\n    }\n\n    async updateRenditionCacheConfiguration(\n        renditionSizes?: RenditionSizeConfig,\n        fullRenditionConfig?: FullRenditionConfig\n    ): Promise<Configuration> {\n        if (!renditionSizes && !fullRenditionConfig) {return this.config;}\n        await this.updateConfiguration({\n            RENDITION_SIZES: renditionSizes,\n            FULL_RENDITION_CONFIG: fullRenditionConfig\n        }).catch(err => {\n            Logger.error(`Unable to update process configuration. ${err}`);\n        });\n        return this.config;\n    }\n\n    async updateConfiguration(update: object): Promise<Configuration> {\n        if (Object.keys(update).length) {\n            const response = await this.fetch('/configuration', {\n                method: 'PATCH',\n                headers: {\n                    'Content-Type': 'application/json'\n                },\n                body: JSON.stringify(update)\n            });\n            const json = await response.json();\n            this._handleConfigurationMutation(json);\n        }\n        return this.config;\n    }\n\n    async setLocalSetting(key: string, value: any) {\n        if (value === undefined) {\n            value = null;\n        }\n        await this.updateConfiguration(Object.fromEntries([ [ key, value ] ]));\n        this._config.config[key] = value;\n    }\n\n    getLocalSetting(key: string) {\n        return this._config.config?.[key];\n    }\n\n    getInstalledVersion(appCode: string): string {\n        return this._config.installedApps\n            .filter(app => app.code.toLowerCase() === appCode.toLowerCase())\n            .map(version => version.version)\n            .sort(compareVersions)[0];\n    }\n\n    async sendAction(applicationAction: ApplicationAction) {\n        return this.fetch('/action', { method: 'POST', body: applicationAction.toJSON() });\n    }\n\n    async openInCCD(path: string) {\n        return this.fetch('/action/open_ccd', { method: 'POST', body: JSON.stringify({ path }) });\n    }\n\n    async fetch(path: string, init?: FetchRequestInit, options: FetchOptions = {}) {\n        init = init || {};\n        init.headers = init.headers || {};\n        init.headers.token = this._token as string;\n        init.headers['Content-Type'] = init.headers['Content-Type'] || 'application/json';\n        // TODO: Get actual client version\n        init.headers['x-client-version'] = '15';\n\n        options = { ...DEFAULT_FETCH_OPTIONS, ...options };\n\n        if (this._options.optimistic && (options.optimisticFetch === undefined || options.optimisticFetch === true)) {\n            init.headers['x-optimism'] = 'true';\n        }\n\n        init.signal = init.signal\n            ? combineSignals(init.signal, this._abortController?.signal as AbortSignal)\n            : this._abortController?.signal;\n\n        try {\n            const response = await fetch(`${/^https?:\\/\\//.test(path) ? '' : this._hostname}${path}`, init);\n\n            if (response.status >= 300) {\n                const responseBody = await response.text();\n                const errorCode = responseBody.replace(/[\"]+/g, '');\n                throw getRequestError(response, errorCode);\n            }\n\n            return response;\n        } catch (e) {\n            if (RequestError.isRequestError(e as Error)) {\n                // By default, reconnect on 401 and 403.\n                // Process REST API can throw 401 (invalid process token) or 403 (If no library collections are loaded).\n                // At this point we assume that the process has restarted or the authenticated user state has changed.\n                const shouldReconnect\n                    = options?.reconnectOnErrors?.includes((e as RequestError).response?.status as number)\n                    && this.isConnected;\n\n                if (shouldReconnect) {\n                    this.reconnect();\n                } else if (!shouldReconnect && (e as RequestError).name === ABORT_ERROR) {\n                    return new Response('{}');\n                }\n            } else if ((e as RequestError).message === 'Failed to fetch' && options?.reconnectOnNoResponse) {\n                // More than likely, libraries process shut down.\n                Logger.warn(`Fetch request failed to respond: ${e}`);\n                this.reconnect();\n            } else if ((e as RequestError).message === 'Network request failed') {\n                // Throws when Process REST API is disconnected in UXP\n                Logger.warn(`Network request failed to respond: ${e}`);\n                this.reconnect();\n            }\n            throw e;\n        }\n    }\n\n    async copyFile(source: string, destination: string, allowOverride = false) {\n        const result = await this.fetch(\n            '/util/file/copy',\n            {\n                method: 'POST',\n                body: JSON.stringify({ source, destination, allowOverride: Boolean(allowOverride) })\n            },\n            { reconnectOnNoResponse: true, reconnectOnErrors: [ 401 ] }\n        );\n\n        const json = await result.json();\n\n        return json.path;\n    }\n\n    async getFileSize(path: string) {\n        const result = await this.fetch('/util/file/size', {\n            method: 'POST',\n            body: JSON.stringify({ path })\n        });\n        const json = await result.json();\n        return json.size;\n    }\n\n    getRenditionGrid(library: Library) {\n        return library.renditionGrid;\n    }\n\n    async stageRepresentationForCommit(\n        library: Library,\n        file: File | { path: string } | any,\n        _type?: string\n    ): Promise<string> {\n        try {\n            if (file instanceof File) {\n                const result = await this.fetch('/util/file', {\n                    method: 'POST',\n                    headers: {\n                        'Content-Type': getMimeTypes(file.name?.split('.')[1])?.[0]\n                    },\n                    body: file\n                });\n                const json = await result.json();\n                return json.path;\n            }\n        } catch (error: any) {\n            // if the fetch request explicitly failed we want to reject the promise\n            if (error?.response?.status === HttpStatus.INTERNAL_SERVER_ERROR) {\n                return Promise.reject(error);\n            }\n            // otherwise, it might be a general uncaught exception from accessing File in UXP (undefined), so do nothing\n        }\n\n        return file.path;\n    }\n\n    async isSystemFontAvailable(fontName: string, matchFamily?: Boolean): Promise<boolean> {\n        const result = await this.fetch(`/util/font/available`, {\n            method: 'POST',\n            body: JSON.stringify({ font_name: fontName, match_family: matchFamily })\n        });\n        const json = await result.json();\n        return json.is_font_available;\n    }\n\n    async getFontData(fontId: string): Promise<FontData> {\n        const result = await this.fetch(`/util/font/data`, {\n            method: 'POST',\n            body: JSON.stringify({ font_id: fontId })\n        });\n        const json = await result.json();\n        return json.font_data;\n    }\n\n    async getTempDir(library: Library): Promise<string> {\n        if (!library || !library.id) {\n            throw new LibraryError('INVALID_PARAMETER', 'Need to pass a library with an ID');\n        }\n        const result = await this.fetch(`/libraries/${library.id}/temp_dir`);\n        const json = await result.json();\n        return json.path;\n    }\n\n    getCollaborators(_assetId: string): Promise<CollaboratorData[]> {\n        throw new LibraryError('NOT_IMPLEMENTED', 'LocalDriver.getCollaborators not implemented.');\n    }\n\n    ignoreLocalSyncEvents(): boolean {\n        // For Local driver the sync status should only be driven by what process is doing.\n        return true;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ConnectorParam, ElementSort, GetLibraryOptions, OperationClass } from '../Driver';\nimport type Driver from '../Driver';\nimport type { Params as CloudDriverParams } from '../CloudDriver';\nimport CloudDriver from '../CloudDriver';\nimport type { LocalDriverOptions, Params as LocalDriverParams } from '../LocalDriver';\nimport LocalDriver from '../LocalDriver';\n// @ts-expect-error R-TODO\nimport type Library from '../../models/Library';\nimport type { LibraryData } from '../../models/data/LibraryData';\nimport type { KeyOfType, RenditionSize } from '../../types';\nimport type Element from '../../models/Element';\nimport type Representation from '../../models/Representation';\nimport type Operation from '../Operation';\nimport type ISAMCorePrivate from '../../../core/ISAMCorePrivate';\n\nexport default class HybridDriver extends CloudDriver {\n    private _localDriver: LocalDriver;\n\n    constructor(\n        core: ISAMCorePrivate,\n        protected _localConnector: ConnectorParam<LocalDriverParams>,\n        protected _cloudConnector: ConnectorParam<CloudDriverParams>,\n        options: LocalDriverOptions = {}\n    ) {\n        super(core, () => _cloudConnector().then(p => ({ samDisableOns: true, ...p } as CloudDriverParams)));\n        this._localDriver = new LocalDriver(core, _localConnector, {\n            ...options,\n            optimistic: true\n        });\n    }\n\n    connect() {\n        return Promise.all([ this.localDriver.connect(), super.connect() ]).then(() => {\n            /** empty **/\n        });\n    }\n\n    private get localDriver() {\n        return this._localDriver;\n    }\n\n    private call(library: Library, fn: KeyOfType<Driver, Function>, ...args: any[]) {\n        return library.locallyManaged ? (this._localDriver[fn] as Function)(...args) : (super[fn] as Function)(...args);\n    }\n\n    protected _handleDisconnected(): void {\n        super._handleDisconnected();\n        if (this.localDriver.isConnected) {this.localDriver.disconnect();}\n    }\n\n    setLibraryChangeListener(libraries: LibraryData[], callback: (libraryIds: string[]) => any): void {\n        this.localDriver.setLibraryChangeListener(libraries, callback);\n    }\n\n    setFontDataChangeListener(callback: () => void) {\n        this.localDriver.setFontDataChangeListener(callback);\n    }\n\n    removeFontDataChangeListeners(): void {\n        this.localDriver.removeFontDataChangeListeners();\n    }\n\n    getLibraries() {\n        return this.localDriver.getLibraries();\n    }\n\n    getLibrary(library: Library, options?: GetLibraryOptions): AsyncGenerator<Partial<LibraryData>> {\n        // If the library is locally managed, or we want to download the library locally\n        // utilize the local driver to return library data from disk\n        if (library.locallyManaged || options?.optimisticFetch) {\n            return this.localDriver.getLibrary(library, options);\n        }\n        // otherwise return the cloud drivers library response\n        return super.getLibrary(library, options);\n    }\n\n    getElements(library: Library, sort?: ElementSort, etag?: string, limit?: number, signal?: AbortSignal) {\n        return this.call(library, 'getElements', sort, etag, limit, signal);\n    }\n\n    getElement(library: Library, elementId: string) {\n        return this.call(library, 'getElement', library, elementId);\n    }\n\n    async getLibraryById(id: string, options?: GetLibraryOptions) {\n        // Introducing the idea of passing locallManaged to options here\n        // to allow for utilizing the local driver if we know the library is local.\n        // Current use cases for this utility are situations where we do not know\n        // the library yet so we fall back to cloud driver in these cases.\n        if (options?.optimisticFetch || options?.locallyManaged) {\n            return this._localDriver._getLibraryById(id, options).next();\n        }\n        return super.getLibraryById(id);\n    }\n\n    getRenditionUrl(element: Element, size: RenditionSize) {\n        return this.call(element.library, 'getRenditionUrl', element, size);\n    }\n\n    getRendition(element: Element, size: RenditionSize) {\n        return this.call(element.library, 'getRendition', element, size);\n    }\n\n    getRepresentationContent(representation: Representation) {\n        return this.call(representation.library, 'getRepresentationContent', representation);\n    }\n\n    getOperationTypes(library: Library) {\n        return library.locallyManaged ? this._localDriver.getOperationTypes(library) : super.getOperationTypes(library);\n    }\n\n    operationFactory(Op: OperationClass<Driver>, driver: Driver, library: Library): Operation<Driver> {\n        return new Op((library.locallyManaged ? this._localDriver : this) as Driver, library);\n    }\n\n    ignoreLocalSyncEvents(): boolean {\n        return this.localDriver.isConnected ? this.localDriver.ignoreLocalSyncEvents() : super.ignoreLocalSyncEvents();\n    }\n}\n","export type VulcanMessageInitializer = {\n    type: string;\n    scope?: string;\n    appId?: string;\n    appVersion?: string;\n    data?: string;\n};\n\nexport type VulcanCallback = (message: string) => void;\nexport type CCDVulcanCallback = (type: string, message: string) => void;\nexport type VulcanCallbacks = VulcanCallback | CCDVulcanCallback;\n\nexport interface IVulcanMessage extends Required<VulcanMessageInitializer> {\n    // eslint-disable-next-line\n    new (type: string): IVulcanMessage;\n    initialize: (message: VulcanMessageInitializer) => void;\n    xmlData: () => string;\n    setPayload: (payload: string) => void;\n    getPayload: () => string | null;\n    toString: () => string;\n}\n\nexport interface IVulcan {\n    addMessageListener: (type: string, callback: VulcanCallbacks, obj?: {}) => void;\n    removeMessageListener: (type: string, callback: VulcanCallbacks, obj?: {}) => void;\n    dispatchMessage: (message: IVulcanMessage) => void;\n    getPayload: (message: string) => string | null;\n}\n\nexport abstract class VulcanInterface implements IVulcan {\n    protected abstract get vulcanInterface(): IVulcan5 | IVulcan7;\n    abstract addMessageListener(type: string, callback: VulcanCallbacks, obj?: {}): void;\n    abstract removeMessageListener(type: string, callback: VulcanCallbacks, obj?: {}): void;\n    abstract dispatchMessage(message: IVulcanMessage): void;\n    abstract getPayload(message: string): string | null;\n    abstract getTargetSpecifiers(): string[];\n    abstract launchApp(focus?: boolean, cmdLine?: string): boolean;\n    abstract isAppRunning(): boolean;\n    abstract isAppInstalled(): boolean;\n    abstract getAppPath(): string;\n}\n\nexport interface IVulcan5 extends IVulcan {\n    getTargetSpecifiers: () => string[];\n    launchApp: (targetSpecifier: string, focus?: boolean, cmdLine?: string) => boolean;\n    isAppRunning: (targetSpecifier: string) => boolean;\n    isAppInstalled: (targetSpecifier: string) => boolean;\n    getAppPath: (targetSpecifier: string) => string;\n}\n\nexport interface IVulcan7 extends IVulcan {\n    getTargetSpecifiersEx: () => string[];\n    launchAppEx: (productSAPCodeSpecifier: string, focus: boolean, cmdLine: string) => boolean;\n    isAppRunningEx: (productSAPCodeSpecifier: string) => boolean;\n    isAppInstalledEx: (productSAPCodeSpecifier: string) => boolean;\n    getAppPathEx: (productSAPCodeSpecifier: string) => string;\n}\n\nexport type UXPInstalledApps = Array<{\n    name: string;\n    sapCode: string;\n    launch: () => Promise<void>;\n    isRunning: () => Promise<boolean>;\n}>;\n\nexport interface IUXPVulcanMessage {\n    payload: string;\n}\n\nexport interface IUXPVulcanDispatcher {\n    addEventListener: (type: string, callback: VulcanCallbacks) => void;\n    removeEventListener: (type: string, callback: VulcanCallbacks) => void;\n    broadcastMessage: (message: IUXPVulcanMessage) => void;\n}\n\nexport interface IUXPVulcanControl {\n    getInstalledApps: () => Promise<UXPInstalledApps>;\n    getInstalledAppsEx?: () => Promise<UXPInstalledApps>;\n}\n\nexport interface IUXPVulcan {\n    message: new (type: string, data: string) => IUXPVulcanMessage;\n    dispatcher: IUXPVulcanDispatcher;\n    control: IUXPVulcanControl;\n}\n","import { vulcanLibrariesSAPCode, vulcanLibrariesTargetSpecifier } from '../../config/constants';\nimport type { IVulcan, IVulcan5, IVulcan7, IVulcanMessage, VulcanCallback } from './IVulcan';\nimport { VulcanInterface } from './IVulcan';\n\nexport default function getVulcanInterface(vulcanInterface: IVulcan): VulcanInterface {\n    if (isVulcan7(vulcanInterface)) {\n        return new Vulcan7(vulcanInterface);\n    }\n\n    return new Vulcan5(vulcanInterface);\n}\n\nfunction isVulcan7(vulcan: IVulcan): vulcan is IVulcan7 {\n    return (vulcan as IVulcan7).launchAppEx !== undefined;\n}\n\nabstract class Vulcan extends VulcanInterface {\n    protected _vulcanInterface: IVulcan;\n    protected _specifer = vulcanLibrariesTargetSpecifier;\n\n    constructor(vulcanInterface: IVulcan) {\n        super();\n        this._vulcanInterface = vulcanInterface;\n    }\n\n    addMessageListener(type: string, callback: VulcanCallback, obj?: string) {\n        this.vulcanInterface.addMessageListener(type, callback, obj);\n    }\n\n    removeMessageListener(type: string, callback: VulcanCallback, obj?: {}) {\n        this.vulcanInterface.removeMessageListener(type, callback, obj);\n    }\n\n    dispatchMessage(message: IVulcanMessage) {\n        this.vulcanInterface.dispatchMessage(message);\n    }\n\n    getPayload(message: string): string | null {\n        return this.vulcanInterface.getPayload(message);\n    }\n}\n\nclass Vulcan5 extends Vulcan {\n    constructor(vulcanInterface: IVulcan) {\n        super(vulcanInterface);\n        this._vulcanInterface = vulcanInterface;\n        this._specifer = vulcanLibrariesTargetSpecifier;\n    }\n\n    protected get vulcanInterface(): IVulcan5 {\n        return this._vulcanInterface as IVulcan5;\n    }\n\n    getTargetSpecifiers(): string[] {\n        return this.vulcanInterface.getTargetSpecifiers();\n    }\n\n    launchApp(focus: boolean, cmdLine: string): boolean {\n        return this.vulcanInterface.launchApp(this._specifer, focus, cmdLine);\n    }\n\n    isAppRunning(): boolean {\n        return this.vulcanInterface.isAppRunning(this._specifer);\n    }\n\n    isAppInstalled(): boolean {\n        return this.vulcanInterface.isAppInstalled(this._specifer);\n    }\n\n    getAppPath(): string {\n        return this.vulcanInterface.getAppPath(this._specifer);\n    }\n}\n\nclass Vulcan7 extends Vulcan {\n    constructor(vulcanInterface: IVulcan) {\n        super(vulcanInterface);\n        this._specifer = vulcanLibrariesSAPCode;\n    }\n\n    protected get vulcanInterface(): IVulcan7 {\n        return this._vulcanInterface as IVulcan7;\n    }\n\n    getTargetSpecifiers(): string[] {\n        return this.vulcanInterface.getTargetSpecifiersEx();\n    }\n\n    launchApp(focus: boolean, cmdLine: string): boolean {\n        return this.vulcanInterface.launchAppEx(this._specifer, focus, cmdLine);\n    }\n\n    isAppRunning(): boolean {\n        return this.vulcanInterface.isAppRunningEx(this._specifer);\n    }\n\n    isAppInstalled(): boolean {\n        return this.vulcanInterface.isAppInstalledEx(this._specifer);\n    }\n\n    getAppPath(): string {\n        return this.vulcanInterface.getAppPathEx(this._specifer);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { vulcanQueryRequestPayload } from '../config/constants';\nimport getVulcanInterface from '../utils/Vulcan';\nimport type { IVulcan, IVulcanMessage, VulcanInterface } from '../utils/Vulcan/IVulcan';\nimport type { ConnectionInfo, VulcanCallback, VulcanMessageType } from './Connector';\nimport Connector from './Connector';\n\nclass CEPConnector extends Connector<VulcanInterface, IVulcanMessage> {\n    protected messageTypes: VulcanMessageType = {\n        REQUEST: 'vulcan.SuiteMessage.cclibraries.api.QueryRequest',\n        RESPONSE: 'vulcan.SuiteMessage.cclibraries.api.QueryResponse',\n        INITIALIZE: 'vulcan.SuiteMessage.cclibraries.service.Initialized'\n    };\n\n    constructor(vulcanInterface: IVulcan, vulcanMessage: IVulcanMessage, timeout: number) {\n        super(getVulcanInterface(vulcanInterface), vulcanMessage, timeout);\n    }\n\n    removeListener(callback: VulcanCallback, type?: string) {\n        return this.vulcanInterface.removeMessageListener(type || this.messageTypes.RESPONSE, callback);\n    }\n\n    sendMessage(callback: VulcanCallback, type?: string) {\n        // Add listener\n        this.vulcanInterface.addMessageListener(type || this.messageTypes.RESPONSE, callback);\n        // Send the request\n        if (type !== this.messageTypes.INITIALIZE) {\n            const request = new this.VulcanMessage(this.messageTypes.REQUEST);\n            request.setPayload(vulcanQueryRequestPayload);\n            this.vulcanInterface.dispatchMessage(request);\n        }\n    }\n\n    async isAppRunning() {\n        return this.vulcanInterface.isAppRunning();\n    }\n\n    launchApp(_callback: VulcanCallback) {\n        this.vulcanInterface.launchApp();\n    }\n\n    getPayload(message: string) {\n        return this.vulcanInterface.getPayload(message) as string;\n    }\n}\n\nexport default (\n    VulcanInterface: IVulcan,\n    VulcanMessage: IVulcanMessage,\n    timeout = 8000\n): ((abortSignal?: AbortSignal) => Promise<ConnectionInfo | void>) => {\n    const connector = new CEPConnector(VulcanInterface, VulcanMessage, timeout);\n    return (abortSignal?: AbortSignal) => connector.connect(abortSignal);\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { vulcanQueryRequestPayload } from '../config/constants';\nimport getVulcanInterface from '../utils/Vulcan';\nimport type { IVulcan, IVulcanMessage, VulcanInterface } from '../utils/Vulcan/IVulcan';\nimport type { VulcanCallback, VulcanMessageType, ConnectionInfo } from './Connector';\nimport Connector from './Connector';\n\nclass CCDConnector extends Connector<VulcanInterface, IVulcanMessage> {\n    protected messageTypes: VulcanMessageType = {\n        REQUEST: 'cclibraries.api.QueryRequest',\n        RESPONSE: 'cclibraries.api.QueryResponse',\n        INITIALIZE: 'cclibraries.service.Initialized'\n    };\n\n    constructor(vulcanInterface: IVulcan, vulcanMessage: IVulcanMessage, timeout: number) {\n        super(getVulcanInterface(vulcanInterface), vulcanMessage, timeout);\n    }\n\n    private _wrapHandler(callback: VulcanCallback) {\n        return (type: string, message: string) => callback(message);\n    }\n\n    removeListener(callback: VulcanCallback, type?: string) {\n        return this.vulcanInterface.removeMessageListener(type || this.messageTypes.RESPONSE, callback);\n    }\n\n    sendMessage(callback: VulcanCallback, type?: string) {\n        // Add listener\n        this.vulcanInterface.addMessageListener(type || this.messageTypes.RESPONSE, this._wrapHandler(callback));\n        // Send the request\n        if (type !== this.messageTypes.INITIALIZE) {\n            const request = new this.VulcanMessage(this.messageTypes.REQUEST);\n            request.data = vulcanQueryRequestPayload;\n            this.vulcanInterface.dispatchMessage(request);\n        }\n    }\n\n    async isAppRunning() {\n        return this.vulcanInterface.isAppRunning();\n    }\n\n    launchApp(_callback: VulcanCallback) {\n        this.vulcanInterface.launchApp();\n    }\n\n    getPayload(message: string) {\n        return message;\n    }\n}\n\nexport default (\n    VulcanInterface: IVulcan,\n    VulcanMessage: IVulcanMessage,\n    timeout = 8000\n): ((abortSignal?: AbortSignal) => Promise<ConnectionInfo | void>) => {\n    const connector = new CCDConnector(VulcanInterface, VulcanMessage, timeout);\n    return (abortSignal?: AbortSignal) => connector.connect(abortSignal);\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { vulcanQueryRequestPayload } from '../config/constants';\nimport getVulcanInterface from '../utils/Vulcan';\nimport type { IVulcan, IVulcanMessage } from '../utils/Vulcan/IVulcan';\nimport type { VulcanCallback, VulcanMessageType, ConnectionInfo } from './Connector';\nimport Connector from './Connector';\n\n// This NodeConnector is for the node-js vulcan implementation used by Stager\n// To debug vulcan messages in Stager you can add the flag SG_DEBUG_VULCAN=1 when opening Stager\n\nclass NodeConnector extends Connector<any, IVulcanMessage> {\n    protected messageTypes: VulcanMessageType = {\n        REQUEST: 'cclibraries.api.QueryRequest',\n        RESPONSE: 'cclibraries.api.QueryResponse',\n        INITIALIZE: 'cclibraries.service.Initialized'\n    };\n\n    constructor(vulcanInterface: any, vulcanMessage: IVulcanMessage, timeout: number) {\n        super(getVulcanInterface(vulcanInterface), vulcanMessage, timeout);\n    }\n\n    private _wrapHandler(callback: any) {\n        return (message: any, _processName: any) => callback(message);\n    }\n\n    removeListener(callback: VulcanCallback, type?: string) {\n        return this.vulcanInterface.removeMessageListener(type || this.messageTypes.RESPONSE, callback);\n    }\n\n    sendMessage(callback: VulcanCallback, type?: string) {\n        // Add listener\n        this.vulcanInterface.addMessageListener(type || this.messageTypes.RESPONSE, this._wrapHandler(callback));\n        // Send the request\n        if (type !== this.messageTypes.INITIALIZE) {\n            const request = { message: vulcanQueryRequestPayload, type: type || this.messageTypes.REQUEST };\n            this.vulcanInterface.dispatchMessage(request);\n        }\n    }\n\n    async isAppRunning() {\n        return this.vulcanInterface.isAppRunning();\n    }\n\n    launchApp(_callback: VulcanCallback) {\n        this.vulcanInterface.launchApp();\n    }\n\n    getPayload(message: string) {\n        return message;\n    }\n}\n\nexport default (\n    VulcanInterface: IVulcan,\n    VulcanMessage: IVulcanMessage,\n    timeout = 8000\n): ((abortSignal?: AbortSignal) => Promise<ConnectionInfo | void>) => {\n    const connector = new NodeConnector(VulcanInterface, VulcanMessage, timeout);\n    return (abortSignal?: AbortSignal) => connector.connect(abortSignal);\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { vulcanLibrariesSAPCode, vulcanLibrariesTargetSpecifier, vulcanQueryRequestPayload } from '../config/constants';\nimport type { IUXPVulcan, IUXPVulcanMessage, UXPInstalledApps } from '../utils/Vulcan/IVulcan';\nimport type { VulcanCallback, VulcanMessageType, ConnectionInfo } from './Connector';\nimport Connector from './Connector';\n\nconst LAUNCH_APP_RESPONSE = 'launched';\n\nclass UXPConnector extends Connector<IUXPVulcan, IUXPVulcanMessage> {\n    protected messageTypes: VulcanMessageType = {\n        REQUEST: 'vulcan.SuiteMessage.cclibraries.api.QueryRequest',\n        RESPONSE: 'vulcan.SuiteMessage.cclibraries.api.QueryResponse',\n        INITIALIZE: null\n    };\n\n    private get _installedAppsFn(): () => Promise<UXPInstalledApps> {\n        const { getInstalledApps, getInstalledAppsEx } = this.vulcanInterface.control;\n        if (getInstalledAppsEx) {\n            return getInstalledAppsEx.bind(this.vulcanInterface.control);\n        }\n        return getInstalledApps.bind(this.vulcanInterface.control);\n    }\n\n    private async _getCCLibrariesInstall() {\n        return (await this._installedAppsFn()).find(\n            app => app.name === vulcanLibrariesTargetSpecifier || app.sapCode === vulcanLibrariesSAPCode\n        );\n    }\n\n    removeListener(callback: VulcanCallback, type?: string) {\n        if (type === null) {\n            return;\n        }\n        this.vulcanInterface.dispatcher.removeEventListener(this.messageTypes.RESPONSE, callback);\n    }\n\n    sendMessage(callback: VulcanCallback, type?: string) {\n        if (type === null) {\n            return;\n        }\n        this.vulcanInterface.dispatcher.addEventListener(this.messageTypes.RESPONSE, callback);\n        this.vulcanInterface.dispatcher.broadcastMessage(\n            // eslint-disable-next-line new-cap\n            new this.vulcanInterface.message(this.messageTypes.REQUEST, vulcanQueryRequestPayload)\n        );\n    }\n\n    async isAppRunning(): Promise<boolean> {\n        return (await this._getCCLibrariesInstall())?.isRunning() as Promise<boolean>;\n    }\n\n    async launchApp(callback: VulcanCallback) {\n        const ccLibrariesInstall = await this._getCCLibrariesInstall();\n        if (ccLibrariesInstall) {\n            await ccLibrariesInstall.launch();\n            callback(LAUNCH_APP_RESPONSE);\n        }\n    }\n\n    getPayload(message: IUXPVulcanMessage) {\n        return message.payload;\n    }\n}\n\nexport default (\n    vulcanInterface: IUXPVulcan,\n    timeout = 8000\n): ((abortSignal?: AbortSignal) => Promise<ConnectionInfo | void>) => {\n    const connector = new UXPConnector(vulcanInterface, undefined, timeout);\n    return (abortSignal?: AbortSignal) => connector.connect(abortSignal);\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport AsyncOperation from './AsyncOperation';\n\nexport default class ProgressiveLoader<T> extends AsyncOperation {\n    private _results: T[] = [];\n\n    constructor(private _generator: (signal: AbortSignal) => AsyncIterableIterator<T[]>) {\n        super();\n        this._getPages();\n    }\n\n    private async _getPages() {\n        for await (const page of this._generator(this._abortController.signal)) {\n            this._results.push(...page);\n            this.emit('change', false);\n        }\n\n        this.progress = 100;\n        this.emit('change', true);\n    }\n\n    get results() {\n        return this._results;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport { v4 as uuid } from 'uuid';\n\ntype Atom = {\n    reportChanged: () => void;\n    reportObserved: () => void;\n};\n\nexport type CreateAtom = (name: string, onBecomeObserved: () => void, onBecomeUnobserved: () => void) => Atom;\nexport type Transaction = (fn: () => unknown) => void;\n\nclass MobXRegistry {\n    _contexts = new Map<string, { createAtom: CreateAtom; transaction: Transaction }>();\n\n    register(createAtom: CreateAtom, transaction: Transaction) {\n        const id = uuid();\n        this._contexts.set(id, { createAtom, transaction });\n        return () => this._contexts.delete(id);\n    }\n\n    transaction(fn: () => unknown) {\n        const nestedTransaction = Array.from(this._contexts.values()).reduce((memo, { transaction }) => {\n            return () => transaction(() => memo());\n        }, fn);\n\n        return nestedTransaction();\n    }\n\n    reportObserved(target: any, event: string) {\n        for (const [ id, { createAtom } ] of this._contexts) {\n            const key = `_atom_${id}_${event}`;\n            let atom = target[key];\n            if (!atom) {\n                const onChange = () => atom.reportChanged();\n                atom = createAtom(\n                    `${target.constructor.name}${key}`,\n                    () => target.on(event, onChange),\n                    () => target.off(event, onChange)\n                );\n                target[key] = atom;\n            }\n            atom.reportObserved();\n        }\n    }\n}\n\nexport default new MobXRegistry();\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport mobXRegistry from './mobXRegistry';\n\n/**\n * Our @observable decorator is not actually making the property observable via MobX's @observable decorator. Instead,\n * it manually hooks into MobX through mobXRegistry.reportObserved, allowing custom event-based tracking.\n * It works more like @computed in terms of where you'd apply it (getters), but only triggers reactions\n * when the listed events are fired on the this context. So if you return a new array every time in the getter,\n * it will not trigger updates unless one of the listed events (\"change\" by default) is reported\n * via mobXRegistry.reportObserved(this, event) and mobXRegistry.reportChanged(this, event) is called elsewhere.\n */\n\n\ntype DecoratorArgs = [target: any, key: string, descriptor: PropertyDescriptor];\ntype BindingArgs = [...events: string[]];\ntype Decorator = (target: any, key: string, descriptor: PropertyDescriptor) => void;\n\nconst isDecoratorArgs = (args: DecoratorArgs | BindingArgs): args is DecoratorArgs => typeof args[0] !== 'string';\n\nfunction getObservableDecorator(...events: string[]) {\n    return function (target: any, key: string, descriptor: PropertyDescriptor) {\n        const bindingKey = descriptor.get ? 'get' : descriptor.value ? 'value' : undefined;\n\n        if (bindingKey) {\n            const method = descriptor[bindingKey];\n\n            descriptor[bindingKey] = function (this: any, ...args: any[]) {\n                for (const event of events) {\n                    // The mobX target observed will be the 'this' context (i.e. the class containing the method being decorated)\n                    mobXRegistry.reportObserved(this, event);\n                }\n                return method.apply(this, args);\n            };\n        }\n    };\n}\n\n// Overload 1: can call with events. e.g. const myDecorator: Decorator = observable('event1', 'event2');\nexport default function observable(...events: string[]): Decorator;\n// Overload 2: can call as a decorator above a method:  @observable.\nexport default function observable(target: any, key: string, descriptor: PropertyDescriptor): void;\n// Implementation overload: observable([target, key, descriptor]) or observable(['event1', 'event2']);\nexport default function observable(...args: DecoratorArgs | BindingArgs) {\n    if (isDecoratorArgs(args)) {\n        // Default to listening to change events on the target\n        return getObservableDecorator('change')(...args);\n    }\n\n    return getObservableDecorator(...args);\n}\n\nexport function transaction(fn: () => unknown) {\n    return mobXRegistry.transaction(fn);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { ModelData } from './data/ModelData';\nimport type { HasModelBindings } from './utils/HasModelBindings';\nimport { isPlaceholder } from './utils';\nimport ItemBase from '../../core/ItemBase';\nimport type ISAMCorePrivate from '../../core/ISAMCorePrivate';\nimport type LibraryContext from '../../libraries/LibraryContext';\nimport type { ICCLibraries } from '../CCLibraries';\nimport type { RepresentationData } from './data/RepresentationData';\nimport type Representation from './Representation';\n\n/**\n * Model\n * @packageDocumentation\n * @module Model\n * @internal\n *\n * Contains placeholder logic for Elements, Groups, and Representations, including when updating.\n * Model extends ItemBase, but given that there are some Model subclasses that don't use the ItemUpdater pattern,\n * because they exist in simple Arrays rather than the item pool, such as Representation,\n * the update logic has been moved down to the subclasses, other than the placeholder logic.\n */\n\n/**\n * REFACTOR TODOs:\n * - When supporting CRUD Operations on Elements: replace commented out calls to this._modelCache with calls to this._itemPool<model>\n *\n * WHAT WORKS:\n * - getters\n *\n * WHAT DOES NOT YET WORK:\n * - updates/commits\n */\n\n// TODO-R[SHARED-4609]: Handle this when refactoring change notifications. It propagates change events on children to the parent.\n// We need to find out whether SAM has the same pattern.\n// export function initializesCaches<D extends ModelData, B extends { new(...args: any[]): Model<D> }>(base: B): B {\n//     return class extends base {\n//         constructor(...args: any[]) {\n//             super(...args);\n\n//             for (const { cache } of Object.values(this._childModelCaches)) {\n//                 cache.on('change', () => this.emit('change'));\n//                 cache.on('modelChange', () => this.emit('change'));\n//             }\n\n//             this._updateChildren();\n//         }\n//     };\n// }\n\nexport default class Model<D extends ModelData> extends ItemBase implements HasModelBindings {\n\n    private _commitFuture: Promise<void>;\n    protected _commitResolver?: () => void;\n    private _isCommitted = false;\n    private _waitingForCommit = false;\n    protected _libraryContext: LibraryContext;\n\n    /**\n     * @package -- for use in SAM.js only\n     * Public because HasModelBindings has this as public\n     */\n    public _apiRoot: ICCLibraries;\n    /**\n     * @package -- for use in SAM.js only\n     * Public because HasModelBindings has this as public\n     */\n    public _driver: ICCLibraries['driver'];\n\n    /*\n    * Subclasses must overwrite the below properties for _updateImplementation, _parent, and optionally _children, _ChildClass, and _childrenData\n    * Note: There may be a better way to enforce this but this is more or less a pre-existing pattern.\n    * TODO-R[SHARED-4623]: Make Model an Abstract class with composable mixin behaviors such as placeholderId management,\n    * separate from ItemBase subclasses, but keep APIs consistent with HasModelBindings.\n    */\n    /**\n     * @package -- only for use in SAM.js\n     */\n    protected _updateImplementation!: (data: Partial<D>) => void;\n    /**\n     * @package -- only for use in SAM.js\n     */\n    protected _parent!: HasModelBindings; // LibraryContents/Element/Representation/Group, etc.\n    /**\n     * @package -- only for use in SAM.js\n     * This should always return the same Array instance and the same Representation instances,\n     * to ensure MobX does not think there was a change when there wasn't.\n     */\n    protected _children: Representation[] = [];\n    /**\n     * @package -- only for use in SAM.js\n     * It is OK for this to return a new Array instance as this is only used internally for data manipulation.\n     */\n    get _childrenData(): RepresentationData[] { return this._children.map(child => child._data); }\n    /**\n     * @package -- only for use in SAM.js\n     */\n    // Avoid circular dependency between Representation and Model by passing it in as the ChildClass\n    protected _ChildClass!: new (\n        core: ISAMCorePrivate,\n        parent: HasModelBindings,\n        data: RepresentationData\n    ) => Representation;\n\n    constructor(\n        readonly core: ISAMCorePrivate,\n        id: string, // same as _data.id\n    ) {\n        super(core, id);\n        // Synchronously get the LibraryContext and ICCLibraries from the core,\n        // as the async `core.getLibraryContext()` should already have been called.\n        this._libraryContext = core._getLibraryContext() as LibraryContext;\n        this._apiRoot = this._libraryContext._getLibrariesModule_NoLoad() as ICCLibraries;\n        this._driver = this._apiRoot.driver;\n\n        // If the model is a placeholder without a real ID, we need to wait for it to be committed.\n        this._commitFuture = new Promise<void>((resolve, reject) => {\n            this._commitResolver = () => {\n                this._isCommitted = true;\n                resolve();\n            };\n            if (!isPlaceholder(id as string)) {\n                this._commitResolver();\n            }\n            // After 'remove' all event listeners are cleared, so we don't need to clean up here.\n            this.on('remove', () => {\n                if (this._waitingForCommit && !this._isCommitted) {\n                    // If we're removing the model, make sure we reject any promises\n                    // that are waiting for it to be committed, so that callers don't hang indefinitely.\n                    reject();\n                }\n            });\n        });\n    }\n\n    /**\n     * Update the model with new data. (Models only have local data.)\n     * @param data\n     * @returns\n     *\n     * @package -- only for use in SAM.js\n     */\n    // TODO-R[SHARED-4149]: This no longer returns data since that property is gone. We need to check that this won't break anything during CRUD operations.\n    _update(data: Partial<D>): void {\n        const committed = isPlaceholder(this.id) && data.id && this.id !== data.id;\n        this._updateImplementation(data); // Could use ItemUpdater pattern (e.g. element/group) or not (e.g. Representation)\n        if (committed && this._commitResolver) { this._commitResolver(); }\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    // Update children aka Representations, which do not use the ItemUpdater pattern as they exist as an array on the Element.\n    _updateChildren(data: RepresentationData[]): void {\n        if (!this._children) { return; } // Only Element and Representations have children defined.\n\n        // Find representation that matches data.id/previousPlaceholderId and update *before* doing any removals\n        const upsertItems = () => {\n            data.forEach(childData => {\n                let model = this._children.find(child => child.id === childData.id || child.id === childData.previousPlaceholderId);\n                if (model) {\n                    // TODO-R[SHARED-5159]: Diff old/new data with deep object equality to check if an update is needed.\n                    // Old data can be accessed through model._data since children are always Representations\n                    model._update(childData);\n                    model.emit('change');\n                } else {\n                    model = new this._ChildClass(this._core, this, childData);\n                    this._children.push(model);\n                }\n            });\n        };\n        const removeItems = () => {\n            // 1. Get a set of IDs from new data\n            const currentDataIds = new Set(data.map(data => data.id));\n            // 2. Find the models that are not included in the updated set\n            const oldData = this._childrenData;\n            const removedItems = oldData.filter(data => !currentDataIds.has(data.id));\n            // 3. Remove those models from the pool\n            removedItems.forEach(data => {\n                const model = this._children.find(child => child.id === data.id);\n                if (model) {\n                    // Emit a remove event so that the model can clean itself up.\n                    model.emit('remove');\n                    model.removeAllListeners();\n                }\n            });\n        };\n        upsertItems();\n        removeItems();\n    }\n\n    // When resolved, we know this element is no longer a placeholder.\n    // TODO-R: Might be clearer to name this waitForCommit().\n    get committed() {\n        this._waitingForCommit = true;\n        return this._commitFuture;\n    }\n\n    // TODO-R: It might be clearer to switch this around and name it `isPlaceholder`, and the util can become isPlaceholderId\n    get isCommitted() {\n        return this._isCommitted;\n    }\n\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { ICCLibraries } from '../../CCLibraries';\nimport LocalDriver from '../../drivers/LocalDriver';\nimport { hasLibrary } from '../utils/HasLibrary';\nimport LibraryError from '../../errors/LibraryError';\nimport type Element from '../../models/Element';\nimport type Representation from '../../models/Representation';\nimport type Group from '../../models/Group';\nimport { Permission } from '../../../index';\n\nexport function requiresWrite(target: unknown, propertyKey: string, propertyDescriptor: PropertyDescriptor) {\n    const key = propertyDescriptor.set ? 'set' : propertyDescriptor.value ? 'value' : undefined;\n\n    if (key) {\n        const method = propertyDescriptor[key];\n\n        propertyDescriptor[key] = function (this: Element | Group | Representation, ...args: any[]) {\n            if (hasLibrary(this) && !this.library.hasPermission(Permission.Write)) {\n                throw new LibraryError('NOT_ALLOWED', `${propertyKey} requires write access`, this.id);\n            }\n\n            return method.apply(this, args);\n        };\n    }\n}\n\nexport function requiresCloudDriver(\n    target: ICCLibraries,\n    propertyKey: string,\n    propertyDescriptor: PropertyDescriptor\n) {\n    const key = propertyDescriptor.set ? 'set' : propertyDescriptor.value ? 'value' : undefined;\n\n    if (key) {\n        const method = propertyDescriptor[key];\n\n        propertyDescriptor[key] = function (this: ICCLibraries, ...args: any[]) {\n            if (!this.apiRoot.cloudDriver) {\n                throw new LibraryError('NOT_ALLOWED', `${propertyKey} requires a cloud driver`);\n            }\n\n            return method.apply(this, args);\n        };\n    }\n}\n\nexport function requiresLocalDriver(\n    target: ICCLibraries,\n    propertyKey: string,\n    propertyDescriptor: PropertyDescriptor\n) {\n    const key = propertyDescriptor.set ? 'set' : propertyDescriptor.value ? 'value' : undefined;\n\n    if (key) {\n        const method = propertyDescriptor[key];\n\n        propertyDescriptor[key] = function (this: ICCLibraries, ...args: any[]) {\n            if (!(this.apiRoot.driver instanceof LocalDriver)) {\n                throw new LibraryError('NOT_ALLOWED', `${propertyKey} requires a local driver`);\n            }\n\n            return method.apply(this, args);\n        };\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type Element from '../../models/Element';\nimport type Representation from '../../models/Representation';\nimport type Group from '../../models/Group';\n\nexport function hasLibrary(object: Element | Group | Representation): boolean {\n    return !!object.library;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { RepresentationData } from '../data/RepresentationData';\n\nimport type Representation from '../Representation';\nimport Element from '../Element';\nimport { deepCopy } from '../../utils/StoreUtils';\n\nfunction findMatchingRepresentationData(\n    target: Representation,\n    candidates: RepresentationData[]\n): RepresentationData | undefined {\n    for (const candidate of candidates) {\n        if (candidate.id === target.id) {\n            return candidate;\n        }\n\n        if (candidate.children) {\n            const result = findMatchingRepresentationData(target, candidate.children);\n\n            if (result) {\n                return result;\n            }\n        }\n    }\n}\n\nexport function replaceRepresentationsOnTarget(\n    target: Representation | Element,\n    newChildren: RepresentationData[]\n): RepresentationData[] {\n    if (target instanceof Element) {\n        return newChildren;\n    }\n\n    const representations = deepCopy(target.element._childrenData);\n    const targetData = findMatchingRepresentationData(target, representations);\n\n    if (targetData) {\n        targetData.children = newChildren;\n    }\n\n    return representations;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n// Converts all the non library related DCXData values to any Array of Objects.\nexport function mapAttributesToArray(customData: { [s: string]: any }) {\n    customData = customData ?? {};\n    const ret = [];\n    for (const [ customKey, value ] of Object.entries(customData)) {\n        const [ namespace, key ] = customKey.split('#', 2);\n        ret.push({ namespace, key, value });\n    }\n    return ret;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Representation\n * @packageDocumentation\n * @module Representation\n */\n\nimport type { RepresentationData } from './data/RepresentationData';\n// @ts-expect-error R-TODO\nimport type Library from './Library';\nimport type Element from './Element';\nimport Model from './Model';\nimport type LibraryContents from './LibraryContents';\nimport { getFileExtension } from '../utils/FileUtils';\nimport { getExtensions } from '../utils/MimeTypeUtils';\nimport { requiresWrite } from './utils/AccessUtils';\nimport { replaceRepresentationsOnTarget } from './utils/representationUtils';\nimport { isRepresentationPreflightResponse } from '../drivers/CloudDriver/utils/melvilleModelMappers';\nimport type { UnderlyingError } from '../errors/LibraryError';\nimport LibraryError from '../errors/LibraryError';\nimport { createPlaceholderId, isPlaceholder } from './utils';\nimport { mapAttributesToArray } from './utils/AttributeUtils';\nimport type ISAMCorePrivate from '../../core/ISAMCorePrivate';\nimport type { HasModelBindings } from './utils/HasModelBindings';\n\nexport default class Representation extends Model<RepresentationData> {\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _ChildClass = Representation;\n\n    // Because Representation is not updated through the ItemUpdater, we can define more parameters,\n    // including passing data in directly.\n    constructor(\n        readonly core: ISAMCorePrivate,\n        parent: HasModelBindings,\n        /**\n         * @package -  -- for use in SAM.js only\n         * Preserving the data object makes it easy to do updates and also to serialize data back.\n         */\n        public _data: RepresentationData\n    ) {\n        super(core, _data.id); // TODO-R[SHARED-4623]: Later, refactor to use abstract/composable classes so that Representation does not need to inherit from Item to get the Model's placeholder logic. It has no other need for core.\n        this._parent = parent;\n    }\n\n    // We have 3 representation types: json, file, multi-state components.\n    // Multi-state components utilize child representations.\n    // e.g. PS and Fresco have brushes with a file/component for the tip of the brush,\n    // and another for the pattern.\n    // Reference: https://wiki.corp.adobe.com/display/ccexperience/Multi-state+Components\n    get children() {\n        return this._children;\n    }\n\n    get parent(): Representation | Element {\n        return this._parent as Representation | Element;\n    }\n\n    get element(): Element {\n        let element = this._parent;\n\n        while (element instanceof Representation) {\n            element = element._parent;\n        }\n\n        return element as Element;\n    }\n\n    get library(): Library {\n        return this.element.library;\n    }\n\n    get isWritable(): boolean {\n        return this.element.isWritable;\n    }\n\n    get type(): string {\n        const type = this._data.type;\n        if (type === 'application/vnd.adobe.library.link+dcx') {\n            return this._data.linktype as string;\n        }\n        return type;\n    }\n\n    get relationship() {\n        return this._data.relationship;\n    }\n\n    @requiresWrite\n    set relationship(relationship: any) {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        this._updateActionDispatch({ relationship });\n    }\n\n    get width(): number {\n        return this._data.width as number;\n    }\n\n    @requiresWrite\n    set width(width: number) {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        this._updateActionDispatch({ width });\n    }\n\n    get height(): number {\n        return this._data.height as number;\n    }\n\n    @requiresWrite\n    set height(height: number) {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        this._updateActionDispatch({ height });\n    }\n\n    get isFullSize(): boolean {\n        return this._data.isFullSize;\n    }\n\n    @requiresWrite\n    set isFullSize(isFullSize: boolean) {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        this._updateActionDispatch({ isFullSize });\n    }\n\n    get isPreferredThumbnail(): boolean {\n        return this._data.isPreferredThumbnail as boolean;\n    }\n\n    @requiresWrite\n    set isPreferredThumbnail(isPreferredThumbnail: boolean) {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        this._updateActionDispatch({ isPreferredThumbnail });\n    }\n\n    get contentLength(): number {\n        return this._data.contentLength as number;\n    }\n\n    @requiresWrite\n    set contentLength(contentLength: number) {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        this._updateActionDispatch({ contentLength });\n    }\n\n    get libraryContents(): LibraryContents {\n        return this.element.libraryContents;\n    }\n\n    /**\n     * @deprecated\n     */\n    get isDeletedLocally(): boolean {\n        return false;\n    }\n\n    get isExternalLink(): boolean {\n        return this._data.isExternalLink;\n    }\n\n    isCompatibleType(type: string): boolean {\n        const path = this.getContentPath();\n        // Check that the representation's component matches the requested type.\n        // Elements sourced from external links don't reference components so we can't enforce this check.\n        if (path && !this.isExternalLink) {\n            const extension = getFileExtension(path);\n            const extensions = getExtensions(type);\n            if (extensions.indexOf(extension as string) === -1) {\n                return false; // Extension and content-type doesn't match therefore not compatible.\n            }\n        }\n        // Fall back to ensuring the requested type matches the actual representation type.\n        return type === this.type;\n    }\n\n    getValue(namespace: string, key: string): any {\n        return this._data.customData?.[`${namespace}#${key}`];\n    }\n\n    getValues(): { namespace: string; key: string; value: any }[] {\n        return mapAttributesToArray(this._data.customData as { [s: string]: any });\n    }\n\n    @requiresWrite\n    setValue(namespace: string, key: string, value: any, _isMetadata?: boolean): void {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        this._updateActionDispatch({\n            customData: {\n                ...this._data.customData,\n                [`${namespace}#${key}`]: value\n            }\n        });\n    }\n\n    @requiresWrite\n    removeValue(namespace: string, key: string, isMetadata?: boolean): void {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        this.setValue(namespace, key, null, isMetadata);\n    }\n\n    @requiresWrite\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    setContent(content: ArrayBuffer | string | Blob, encoding: string, filename: string): Promise<void> {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and uncomment the code below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n\n        // TODO-R [SHARED-4563] All the code below should be uncommented when the setters are enabled\n\n        // if (content instanceof Blob) {\n        //     return this._driver\n        //         .stageRepresentationForCommit(\n        //             this.library,\n        //             new File([ content ], filename, {\n        //                 type: content instanceof File ? content.type : getPrimaryMimetypeForFile(filename)\n        //             })\n        //         )\n        //         .then(payload => {\n        //             return this.setStagedContent(payload);\n        //         });\n        // }\n\n        // let data: string;\n        // if (typeof content === 'string' && [ 'base64', 'utf8' ].includes(encoding)) {\n        //     data = content;\n        // } else {\n        //     throw new Error('Not implemented');\n        // }\n\n        // return this._updateActionDispatch({ source: { filename, data } });\n    }\n\n    @requiresWrite\n    setContentFromPath(path: string, _moveFile?: boolean): Promise<void> {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        if (!this.library.locallyManaged) {\n            // Not supported in this mode\n            throw new Error();\n        }\n\n        return this._updateActionDispatch({ source: { path, moveFile: false } });\n    }\n\n    @requiresWrite\n    setStagedContent(payload: string): Promise<void> {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        try {\n            const source = JSON.parse(payload);\n\n            if (!isRepresentationPreflightResponse(source)) {\n                // Should accept placeholder representations staged to commit.\n                if (!source || !isPlaceholder(source.id)) {\n                    // Caught immediately below\n                    throw new Error();\n                }\n            }\n\n            return this._updateActionDispatch({ source });\n        } catch (e) {\n            throw new LibraryError(\n                'INVALID_PARAMETER',\n                'Payload is not consumable by remote target',\n                this.library.id,\n                e as UnderlyingError\n            );\n        }\n    }\n\n    @requiresWrite\n    setContentFromURL(createLink: boolean, url: string, headers: HeadersInit): Promise<void> {\n        // TODO-R [SHARED-4563] When setters are enabled, remove error thrown and re-enable the linter below.\n        throw new LibraryError('NOT_IMPLEMENTED', 'Only Read Only functionality supported currently.');\n        // eslint-disable-next-line\n        return this._updateActionDispatch({ source: { url, createLink, headers } });\n    }\n\n    getContentPath(): string {\n        return this._data.path as string;\n    }\n\n    /**\n     * Get the data stored in the content of the representation, by reading the file from disk (in a filesystem environment), or by\n     * downloading it (in a browser environment). This is the content set by calling\n     * Representation.setContent, Representation.setContentFromPath, or Representation.setContentFromURL.\n     */\n    getContent(): Promise<Blob> {\n        return this._driver.getRepresentationContent(this).then(res => res.blob());\n    }\n\n    getContentURL(): string {\n        return this._data.url as string;\n    }\n\n    getAuthenticatedContentURL(): Promise<string> {\n        return Promise.resolve('');\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _createChild(type: string): Representation {\n        const id = createPlaceholderId();\n        const children = this._data.children ? [ ...this._data.children ] : [];\n        children.push({\n            id,\n            type,\n            isFullSize: false,\n            isExternalLink: false\n        });\n\n        this.element._actionDispatch({\n            name: 'updateElementContent',\n            type: 'update',\n            data: {\n                representations: replaceRepresentationsOnTarget(this, children)\n            }\n        });\n\n        return this._children.find(child => child.id === id) as Representation;\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _removeChild(representation: Representation) {\n        const children = this._data.children ? [ ...this._data.children ] : [];\n        const index = children.findIndex(rep => rep.id === representation.id);\n\n        if (index === -1) {\n            return;\n        }\n\n        children.splice(index, 1);\n\n        this.element._actionDispatch({\n            name: 'updateElementContent',\n            type: 'update',\n            data: {\n                representations: replaceRepresentationsOnTarget(this, children)\n            }\n        });\n    }\n\n    testExternalLink(): Promise<boolean> {\n        return Promise.resolve(false);\n    }\n\n    clearCachedExternalLink(): void {\n        // TODO\n    }\n\n    getCachedExternalLinkError(): any {\n        return undefined;\n    }\n\n    /**\n     * Get the download progress for a representation that is an external link\n     * keyed in sync state via `libraryId.elementId.representationId`\n     * returns -1 when an error occurs\n     * returns undefined if no progress\n     * returns 0 - 100 specifying percentage of download complete otherwise\n     */\n    getExternalLinkDownloadProgress() {\n        if (this.isExternalLink) {\n            const key = `${this.library.id}.${this.element.elementId}.${this.id}`;\n            return this.library.apiRoot.syncState.getExternalLinkDownloadProgressByKey(key);\n        }\n    }\n\n    get _childrenData() {\n        return this._data.children || [];\n    }\n\n    private _updateActionDispatch(updatedData: Partial<RepresentationData>) {\n        const representations = this.parent._childrenData;\n        const filteredRepresentations = representations.filter((rep: RepresentationData) => rep.id !== this.id);\n        this.element._actionDispatch({\n            name: 'updateElementContent',\n            type: 'update',\n            data: {\n                representations: replaceRepresentationsOnTarget(this.parent, [\n                    ...filteredRepresentations,\n                    {\n                        ...this._data,\n                        ...updatedData\n                    }\n                ])\n            }\n        });\n        return Promise.resolve();\n    }\n\n    // TODO-R: Not ideal to use arrow function property instead of a method. Takes more memory than methods on the prototype.\n    // Solution is to refactor to use Abstract/composable classes.\n    protected _updateImplementation = (data: Partial<RepresentationData>) => {\n        this._data = Object.assign(this._data, data);\n        this._updateChildren(this._data.children || []); // child array is expected to be full list\n        // TODO-R: Need to ensure this gets squelched during Store.begin/endOperation\n        this.emit('change');\n    };\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n// @TODO\n// This needs a little more thought. The test cases and real world cases are not clear\n// replacing words in the string with a dot(.) does not make a lot of sense to me\n// and the removal of the last .0 is also a little strange.\n// This can be cleaned up and should be but this is pulled directly from cc-libraries-api-js and its well tested\n// https://git.corp.adobe.com/ProjectCentral/cc-libraries-api-js/blob/80ebed61ec41b980495c485fe17a6f1bbd5d1b5c/src/utils/AdobeLibraryGeneralUtils.js#L74\nfunction sanitizeVersionInput(version: string) {\n    // After effects does not use semver. They append a x before the build number.\n    // We need to replace that with a .\n    version = version\n        .toString()\n        .replace(/(\\.0)*$/, '')\n        .replace(/[^.0-9]+/gim, '.');\n    // Workaround for Illustrator CS6 & Illustrator CC returning version as CS6 and the build number instead of semver\n    if (isNaN(parseInt(version, 10)) || parseInt(version, 10) > 250) {\n        version = '0';\n    }\n    return version;\n}\n\nexport function compareVersions(version1 = '0', version2 = '0') {\n    if (version1 === version2) {\n        return 0;\n    }\n\n    const a1 = sanitizeVersionInput(version1).split('.');\n    const a2 = sanitizeVersionInput(version2).split('.');\n\n    let diff;\n    for (let i = 0; i < a1.length && i < a2.length; i++) {\n        const a1Part = parseInt(a1[i], 10);\n        diff = a1Part - parseInt(a2[i], 10);\n        if (isNaN(diff)) {\n            if (isNaN(a1Part)) {\n                return 1;\n            }\n            return -1;\n        }\n        if (diff > 0) {\n            return -1;\n        }\n        if (diff < 0) {\n            return 1;\n        }\n    }\n    diff = a1.length - a2.length;\n    return diff > 0 ? -1 : diff < 0 ? 1 : 0;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n// @ts-expect-error R-TODO\nimport type Library from './Library';\nimport Element from './Element';\nimport { compareVersions } from '../utils/ActionUtils';\nimport LibraryError from '../errors/LibraryError';\nimport type { InstalledApp } from './data/ConfigurationData';\n\nexport type ActionType = 'edit' | 'openStock' | 'editInSource';\ntype IApplicationActionData = {\n    minVersion: string;\n    appCode: string;\n    appName: string;\n    action: string;\n};\n\nexport default class ApplicationAction {\n    constructor(private _item: Library | Element, private _applicationActionData: IApplicationActionData) {}\n\n    get item() {\n        return this._item;\n    }\n\n    get minVersion() {\n        return this._applicationActionData.minVersion;\n    }\n\n    get appCode() {\n        return this._applicationActionData.appCode;\n    }\n\n    get appName() {\n        return this._applicationActionData.appName;\n    }\n\n    get action() {\n        return this._applicationActionData.action;\n    }\n\n    get installedVersions() {\n        const { installedApps } = this.item.apiRoot.driver.config;\n        return installedApps\n            .filter((app: InstalledApp) => app.code === this._applicationActionData.appCode)\n            .map((app: InstalledApp) => app.version)\n            .sort(compareVersions);\n    }\n\n    isCompatibleVersionInstalled() {\n        return (\n            this.installedVersions.length &&\n            compareVersions(this._applicationActionData.minVersion, this.installedVersions[0]) >= 0\n        );\n    }\n\n    async invoke() {\n        if (!this.isCompatibleVersionInstalled()) {\n            throw new LibraryError(\n                'NOT_SUPPORTED',\n                'A compatible version of the application is needed for this action',\n                this.item instanceof Element ? this.item.library.id : this.item.id\n            );\n        }\n\n        return this.item.apiRoot.driver.sendAction(this);\n    }\n\n    toJSON() {\n        return JSON.stringify({\n            ...this._applicationActionData,\n            ...(this.item instanceof Element\n                ? { libraryId: this.item.library.id, elementId: this.item.id }\n                : { libraryId: this.item.id })\n        });\n    }\n}\n\nexport function constructActions(\n    item: Library | Element,\n    action: ActionType,\n    codes: string[],\n    products: { [code: string]: IApplicationActionData }\n) {\n    return codes\n        .map(code => {\n            const currentAction = products[code];\n            if (currentAction && (!action || action === currentAction.action)) {\n                return new ApplicationAction(item, currentAction);\n            }\n            return undefined;\n        })\n        .filter(Boolean)\n        .sort((a, b) => {\n            if (a?.isCompatibleVersionInstalled && !b?.isCompatibleVersionInstalled) {\n                return -1;\n            } else if (!a?.isCompatibleVersionInstalled && b?.isCompatibleVersionInstalled) {\n                return 1;\n            }\n            return 0;\n        });\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type Element from '../Element';\n\nconst DEFAULT_SRGB_PROFILE = 'sRGB IEC61966-2.1';\nconst isRGB = (data: any) => data.mode === 'RGB';\nconst isSRGB = (data: any) => isRGB(data) && (!data.profileName || data.profileName === DEFAULT_SRGB_PROFILE);\n\n// Convert RGB values to a hex string (e.g. rgbToHex(50, 50, 50) = '#323232')\nconst rgbToHex = (r: number, g: number, b: number) => {\n    let str = ((Math.round(r) << 16) | (Math.round(g) << 8) | Math.round(b)).toString(16);\n    while (str.length < 6) {\n        str = '0' + str;\n    }\n    return `#${str}`.toUpperCase();\n};\n\n// Convert color data to a hex string. (With a few other color utils encapsulated inside.)\nconst colorDataToHexString = (color: Object) => {\n    // If data is a swatch array of colorData, get the sRGB data\n    const data = Array.isArray(color) ? color.find(isSRGB) || color.find(isRGB) : color;\n    return data && data.value ? rgbToHex(data.value.r, data.value.g, data.value.b) : '';\n};\n\nconst getData = (element: Element, namespace: string, filter?: Function) => {\n    const type = `application/vnd.adobe.${namespace}+json`;\n    for (let i = 0; i < element.representations.length; i++) {\n        const representation = element.representations[i];\n        if (representation.type === type) {\n            const data = representation.getValue(namespace, 'data');\n            if (data && (!filter || filter(data))) {\n                return data;\n            }\n        }\n    }\n};\n\nconst getColorName = (element: Element) => {\n    // Note: Some colors have an RGB representation that's not sRGB. That's technically not allowed,\n    // but we fall back to picking the first RGB representation (regardless of mode) if there's no sRGB\n    // representation\n    const color = getData(element, 'color', isSRGB) || getData(element, 'color', isRGB);\n    return colorDataToHexString(color);\n};\n\nconst getFontName = (element: Element) => {\n    const font = getData(element, 'font');\n    return font?.name || '';\n};\n\nconst getStyleName = (namespace: string) => (element: Element) => {\n    const style = getData(element, namespace);\n    if (style) {\n        const fontStyle = style.adbeFont && style.adbeFont.style.toLowerCase();\n        if (fontStyle && !fontStyle.includes('normal') && !fontStyle.includes('regular')) {\n            return `${style.fontFamily} ${style.adbeFont.style}`;\n        }\n        return style.fontFamily;\n    }\n};\n\nconst generateNameMap: any = {\n    'application/vnd.adobe.element.color+dcx': getColorName,\n    // Note: character and paragraph styles now require names, but some older elements are nameless:\n    'application/vnd.adobe.element.characterstyle+dcx': getStyleName('characterstyle'),\n    'application/vnd.adobe.element.paragraphstyle+dcx': getStyleName('paragraphstyle'),\n    'application/vnd.adobe.element.font+dcx': getFontName\n};\n\nexport const getGeneratedName = (element: Element) => {\n    const getName = generateNameMap[element.type];\n    return getName ? getName(element) : '';\n};\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { LinkReference } from '../../index';\nimport type { PublishedData } from './data/PublishedData';\nimport type { Action } from './Action';\n\nimport observable from '../utils/observable';\nimport { requiresWrite } from './utils/AccessUtils';\nimport { parseNewLinkSchema } from '../utils/LinkUtils';\nimport type { ModelData } from './data/ModelData';\nimport Model from './Model';\nimport type { ActionName } from './Action';\nimport LibraryError from '../errors/LibraryError';\nimport type { Optional } from '../types';\nimport type LibraryContents from './LibraryContents';\n\n/**\n * Defines library items that may have been created by publishing a document's assets.\n * At the time of this writing, that includes only Elements and Groups.\n * @packageDocumentation\n * @module Published\n */\n\nexport default abstract class Published<T extends ModelData & PublishedData> extends Model<T> {\n    private _sourceRef?: PublishedData['sourceRef'];\n    private _sourceModifiedDate?: PublishedData['sourceModifiedDate'];\n\n    protected abstract _updateAction: ActionName;\n    /**\n     * @package -- only for use in SAM.js\n     */\n    abstract _actionDispatch(action: Optional<Action, 'path'>): void;\n\n    /**\n     * A string reference to where the element or group came from.\n     *\n     * This should be in the new migrated link format, of a serialized JSON string storing link data:\n     * https://git.corp.adobe.com/caf/xcm/blob/master/schemas/cc/link/link.schema.json\n     * However, the getter will return whatever any legacy string stored as well, without modification.\n     *\n     * @type {Stringified<LinkReference> | undefined}\n     */\n    @observable\n    get sourceRefString() {\n        return this._sourceRef;\n    }\n\n    /**\n     * An object reference to where the element or group came from.\n     *\n     * This should be in the new migrated link format, of an expanded JSON object storing link data:\n     * https://git.corp.adobe.com/caf/xcm/blob/master/schemas/cc/link/link.schema.json\n     * The getter will convert a legacy reference format into an object.\n     * The sourceRef should be read and written as an object but stored in the manifest as a serialized string.\n     * The stringified JSON will also be available to read through sourceRefString.\n     *\n     * It's highly encouraged to set the sourceRef when creating an element, so that we can trace it back later.\n     *\n     * @type {LinkReference|undefined}\n     */\n    @observable\n    @requiresWrite\n    get sourceRef() {\n        if (!this.sourceRefString) {\n            return undefined;\n        }\n\n        let newLinkSchema = parseNewLinkSchema(this.sourceRefString);\n        if (!newLinkSchema) {\n            // Return legacy sourceRef in the new link schema.\n            // The actual migration of the sourceRef should be handled by the client.\n            const [ urn, fragment ] = this.sourceRefString.split('#');\n            newLinkSchema = {\n                'repo:assetId': urn,\n                'stRef:fromPart': fragment\n            };\n            const legacySourceModified = this._sourceModifiedDate;\n            if (legacySourceModified) {\n                // fromPartInstanceID should be a uuid string, sourceModified is a number.\n                newLinkSchema['stRef:fromPartInstanceID'] = `${legacySourceModified}`;\n            }\n        }\n\n        return newLinkSchema;\n    }\n\n    set sourceRef(sourceRef: LinkReference | undefined) {\n        if (typeof sourceRef !== 'object' || !parseNewLinkSchema(sourceRef)) {\n            const parent = this._parent as LibraryContents;\n            throw new LibraryError('INVALID_PARAMETER', 'sourceRef must be a valid JSON object', parent.library.id);\n        }\n        this._actionDispatch({\n            name: this._updateAction,\n            type: 'update',\n            data: {\n                // The sourceRef should be read and written as an object but stored in the manifest as a serialized string.\n                sourceRef: JSON.stringify(sourceRef, Object.keys(sourceRef).sort())\n            }\n        });\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Element\n * @packageDocumentation\n * @module Element\n */\n\nimport type { LinkReference } from '../../index';\nimport { Permission, SAMError, SAMErrorCode } from '../../index';\nimport type { ElementData } from './data/ElementData';\nimport type { RepresentationData } from './data/RepresentationData';\nimport type { Role } from './data/LibraryData';\nimport type Group from './Group';\nimport type { Action, ActionName } from './Action';\nimport type { UpdateContext } from './data/UpdateContext';\n\nimport observable from '../utils/observable';\nimport Representation from './Representation';\nimport { requiresWrite } from './utils/AccessUtils';\nimport type { ActionType } from './ApplicationAction';\nimport type ApplicationAction from './ApplicationAction';\nimport { constructActions } from './ApplicationAction';\nimport type { PlaceholderIdType } from './utils';\nimport { createPlaceholderId, isPlaceholder } from './utils';\nimport { getGeneratedName } from './utils/elementUtils';\nimport PublishedModel from './PublishedModel';\nimport { serializeLinkReference } from '../utils/LinkUtils';\nimport type { ElementMimeType } from '../config/constants';\nimport { ElementMimeTypeMap, LibraryConstants } from '../config/constants';\nimport { mapAttributesToArray } from './utils/AttributeUtils';\nimport type { Optional, RenditionSize, Stringified } from '../types';\nimport type LibraryContents from './LibraryContents';\n\nimport type { IItemUpdaterBaseOptions } from '../../core/ItemUpdater';\nimport { ItemUpdaterBase } from '../../core/ItemUpdater';\nimport type { IPropertyTypeMap } from '../../core/PropertyUpdater';\nimport PropertyUpdater from '../../core/PropertyUpdater';\nimport type SAMLibrary from '../../libraries/Library';\nimport type ISAMCorePrivate from '../../core/ISAMCorePrivate';\nimport type ItemPool from '../../core/ItemPool';\nimport type { ItemId } from '../../core/ItemBase';\n\n\nexport type CombinedId = ItemId & `${ItemId}#${ItemId}`;\nexport type ElementPoolId = CombinedId | PlaceholderIdType;\nexport const extractElementId = (path: CombinedId): ItemId => {\n    return path.split('#')[1];\n};\n\nexport function getCombinedId(data: Partial<ElementData>): CombinedId {\n    return `${data.libraryAssetId}#${data.id}`;\n}\n\nexport function getCombinedIdOrPlaceholder(data: Partial<ElementData>): ElementPoolId {\n    if (!data.id) {\n        throw SAMError.create(SAMErrorCode.BAD_REQUEST, 'Element data requires an id');\n    }\n    return isPlaceholder(data.id) ? data.id : getCombinedId(data);\n}\n\n// @initializesCaches\nexport default class Element extends PublishedModel<ElementData> {\n    /* New private APIs to replace _data APIs [incomplete] */\n    // Note: Since the Store has a special _data property, wherein element data must be defined, we might as\n    // well keep that as the source of truth and reference it here. If it weren't for that, we could have deprecated ElementData\n    // and moved all its types here.\n    private _roles?: ElementData['roles'];\n    private _description?: ElementData['description'];\n    private _descriptionModifiedDate?: ElementData['descriptionModifiedDate'];\n    private _descriptionModifiedBy?: ElementData['descriptionModifiedBy'];\n    private _descriptionModifiedContext?: ElementData['descriptionModifiedContext'];\n    private _descriptionModifiedLocally?: ElementData['descriptionModifiedLocally'];\n    private _modifiedDate?: ElementData['modifiedDate'];\n    private _modifiedBy?: ElementData['modifiedBy'];\n    private _modifiedContext?: ElementData['modifiedContext'];\n    private _modifiedLocally?: ElementData['modifiedLocally'];\n    private _createdDate?: ElementData['createdDate'];\n    private _createdBy?: ElementData['createdBy'];\n    private _createdContext?: ElementData['createdContext'];\n    private _createdLocally?: ElementData['createdLocally'];\n    private _tags?: ElementData['tags'];\n    private _customData?: ElementData['customData'];\n    private _dependencyIds?: ElementData['dependencyIds'];\n    private _elementRef?: ElementData['elementRef'];\n    private _autoName?: ElementData['autoName'];\n    private _libraryAssetId?: ElementData['libraryAssetId']; // TODO-R: Verify melville response format. Their MIA documentation just says \"libraryIdentifier\" but i don't think that's accurate, sigh.\n    // The following properties are not optional in ElementData, so we added\n    // default values to avoid undefined checks, with the assumption being that these values\n    // should be defined through _update() before calling dependent code.\n    // If you run into these default unexpectedly, then you are failing to update the element properly.\n    // (Previously defaults were not required because ElementData was required by the constructor.)\n    private _groups: ElementData['groups'] = [] as ElementData['groups'];\n    /**\n     * @package -- for use in SAM.js only\n     */\n    private _name: ElementData['name'] = '';\n    private _type: ElementData['type'] = '' as ElementMimeType;\n\n    isElement = true;\n    protected _updateAction: ActionName = 'updateElement';\n\n    protected _lastLocalUpdateDate = 0;\n    /**\n     * @package -- only for use in SAM.js\n     */\n    protected _updater!: typeof ElementUpdater;\n    /**\n     * @package -- only for use in SAM.js\n     */\n    protected _itemPool!: ItemPool<Element, ElementPoolId>;\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _ChildClass = Representation;\n\n    private _elementId!: ItemId;\n\n    // TODO-R: Because element may be created by UpdateSession, we cannot expect parent to be passed in.\n    // However, we should probably refactor the remoteUpdate to handle passing in the parent to avoid the issues noted below in libraryContents\n    constructor(core: ISAMCorePrivate, id: ElementPoolId) {\n        super(core, id);\n        this._updater = this._apiRoot.elementUpdater;\n        this._itemPool = this._apiRoot.elementPool;\n        this._elementId = isPlaceholder(id) ? id : extractElementId(id);\n    }\n\n    // Note: Previously, we could pass the parent directly into the Element constructor.\n    // With the ItemUpdater pattern, only the id is passed in upon instantiation, and the data, including the parent id, is updated later.\n    // In order to avoid breaking APIs depending on the library (or libraryContents) APIs being defined,\n    // we need to throw an error here if the libraryAssetId is undefined. We can revisit this strategy if it becomes a problem.\n    // In other words, we assume that in production the libraryAssetId will always be defined in an Element Response.\n    // TODO-R: Need to verify Melville response format to ensure this assumption is correct.\n    get libraryContents(): LibraryContents {\n        if (!this._parent) {\n            if (!this._libraryAssetId) { throw Error('Element._libraryAssetId is not defined, so we cannot find the Library or LibraryContents.'); }\n            const library = this._core._getAssetPool().getLocalItemById(this._libraryAssetId!) as SAMLibrary;\n            this._parent = library._getContentsSync(); // We assume LibraryContents is already loaded given this Element wouldn't exist otherwise.\n        }\n        return this._parent as LibraryContents;\n    }\n\n    get library(): SAMLibrary {\n        // Rather than holding a reference to the library directly, the element holds a reference to its parent LibraryContents,\n        // which in turn points to its parent library.\n        return this.libraryContents.library;\n    }\n\n    get elementId(): ItemId {\n        return this._elementId;\n    }\n\n    /**\n     * The mimetype of the library element\n     */\n    get type(): string {\n        return this._type;\n    }\n\n    /**\n     * The date the library element was modified\n     */\n    @observable\n    get modified(): Date {\n        return new Date(Math.max(this._modifiedDate as number, this._lastLocalUpdateDate));\n    }\n\n    /**\n     * The date the library element was created\n     */\n    @observable\n    get created(): Date {\n        return new Date(this._createdDate as number);\n    }\n\n    /**\n     * The instanceID (in the case of a library) or fromPartInstanceID (in the case of a fragment),\n     * is used to tell if the content of a link is out of date in the new link reference schema.\n     * For elements, we use the primary representation id, which changes every time a change is made to the element.\n     * Since there is no content that can change when there's no representation, this will be undefined in that case.\n     *\n     * Note that the InstanceID has to be a guid as per XMP semantics -- modified dates are not unique enough.\n     * This is important primarily for references to library elements,\n     * since they will be exposed in XMP as well, as part of the content graph.\n     *\n     */\n    get instanceId(): string | undefined {\n        const primaryRepresentation = this.getPrimaryRepresentation();\n        return primaryRepresentation?.id;\n    }\n\n    /**\n     * Get a unique link reference for the element, which is a JSON object using the [link schema](https://git.corp.adobe.com/caf/xcm/blob/master/schemas/cc/link/link.schema.json).\n     * This reference can be used anytime to retrieve this element.\n     * For more information on linking architecture, see [here](https://wiki.corp.adobe.com/pages/viewpage.action?spaceKey=ccexperience&title=Linking+Architecture).\n     */\n    // TODO-R[SHARED-3693]: We may need to make this async given that the library may not have melville data loaded yet.\n    getReference(): LinkReference {\n        const linkData: LinkReference = {\n            'dc:format': this.library.mediaType,\n            'repo:assetId': this._libraryAssetId as string,\n            'repo:name': this.library.displayName, // important to include the library name to use in broken link messaging\n            'stRef:manager': 'Adobe Cloud',\n            'stRef:documentID': this.library.libraryManifestId,\n            'stRef:fromPart': `id=${this.id}`, // fragment id\n            'stRef:fromPartName': this.name\n        };\n\n        if (this.instanceId) {\n            linkData['stRef:fromPartInstanceID'] = this.instanceId;\n        }\n\n        if (this.sourceRef) {\n            // If this element is derived from a different cloud asset, include the reference to it as well.\n            // But if the element is derived from the Firefly mimetype, then avoid sending this field\n            // because the Firefly mimetype is still being developed and so the sourceRef is still incomplete\n            if (this.sourceRef['dc:format'] !== 'application/vnd.adobe.firefly-recipe+dcx') {\n                linkData['stRef:fromPartDerivedFrom'] = this.sourceRef;\n            }\n        }\n\n        return linkData;\n    }\n\n    /**\n     * Get the serialized version of the unique link reference for the element, returned from getReference()\n     * Getting the object through getReference() is typically more useful and skips serialization steps,\n     * but the serialized string is useful to compare reference equality, since we take care of sorting the object.\n     */\n    getReferenceString(): Stringified<LinkReference> | string {\n        const reference = this.getReference();\n        return serializeLinkReference(reference);\n    }\n\n    // Legacy references are still used by clients that have not migrated to the new link format yet.\n    getLegacyReference(): string {\n        return this._elementRef ?? `cloud-asset://${this.library.id};node=${this.id}`;\n    }\n\n    /**\n     * The display name of the element\n     */\n    @observable\n    @requiresWrite\n    get name(): string {\n        if (this.isAutoNamed) {\n            return getGeneratedName(this);\n        }\n\n        return this._name;\n    }\n\n    set name(name: string) {\n        this._actionDispatch({\n            name: 'updateElement',\n            type: 'update',\n            data: {\n                name: name?.normalize()\n            }\n        });\n    }\n\n    /**\n     * Was this element named automatically?\n     */\n    // TODO-R[SHARED-5404]: This seems buggy. Melville only returns isAutoNamed, not autoName. rapi data from the LocalDriver returns both.\n    // May need to add optional autoName = name to Melville mapping for Elements.\n    @observable\n    get isAutoNamed(): boolean {\n        const name = this._name;\n        const autoName = this._autoName;\n        // An element is auto-named if it doesn't have a name, or its auto-name equals its name.\n        // This lets us detect if older clients renamed an element without updating its name,\n        // since they wouldn't update the autoName field.\n        return !name || name === autoName;\n    }\n\n    /**\n     * Is the element editable?\n     */\n    @observable\n    get isWritable(): boolean {\n        return this.library.hasPermission(Permission.Write);\n    }\n\n    /**\n     * The tags (strings) associated with the element\n     */\n    @observable\n    @requiresWrite\n    get tags(): string[] {\n        return this._tags || [];\n    }\n\n    set tags(tags: string[]) {\n        this._actionDispatch({\n            name: 'updateElement',\n            type: 'update',\n            data: { tags }\n        });\n    }\n\n    /**\n     * The dependencies for the element (other elements)\n     */\n    @observable\n    async getDependencies(): Promise<Element[]> {\n        const elements: Element[] = [];\n\n        // TODO-R[SHARED-5423] Optimize Element.getDependencies fetches\n        if (this._dependencyIds) {\n            for (const dependencyID of this._dependencyIds) {\n                const element = await this.libraryContents.getElementById(dependencyID);\n                if (element !== this) {\n                    elements.push(element);\n                }\n            }\n        }\n\n        return elements;\n    }\n\n    @requiresWrite\n    setDependencies(elements: Element[]) {\n        const dependencyIds = elements.map(element => element.id);\n        this._actionDispatch({\n            name: 'updateElement',\n            type: 'update',\n            data: { dependencyIds }\n        });\n    }\n\n    /**\n     * Why does this exist?\n     * @deprecated\n     */\n    @requiresWrite\n    createGroup() {\n        // TODO\n    }\n\n    @observable\n    getGroups(_classifier: string = '$default'): Group[] {\n        // TODO: Implement this once new groups API decided\n        // return this.library.getGroups(classifier).filter(group => {\n        //     return this._groups.find(membership => membership.id === group.id);\n        // });\n        return [] as Group[];\n    }\n\n    @observable\n    getOrderInGroup(group: Group): string | undefined {\n        if (group.library !== this.library) {\n            return;\n        }\n\n        const groupMembership = this._groups.find(\n            membership => membership.classifier === group.classifierName && membership.id === group.id\n        );\n        return groupMembership && groupMembership.order;\n    }\n\n    @requiresWrite\n    setOrderInGroup(group: Group, order: string, removeExistingGroups: boolean = true): void {\n        const groups = removeExistingGroups\n            ? this._groups.filter(gr => gr.classifier !== group.classifierName)\n            : [ ...this._groups ];\n        const index = this._groups.findIndex(({ id }) => id === group.id);\n        const groupMembership = {\n            id: group.id,\n            classifier: group.classifierName,\n            order\n        };\n\n        if (!order && index !== -1) {\n            groups.splice(index, 1);\n        } else if (order && index !== -1) {\n            groups.splice(index, 1, groupMembership);\n        } else if (index === -1) {\n            groups.push(groupMembership);\n        }\n\n        this._actionDispatch({\n            name: 'updateElement',\n            type: 'update',\n            data: { groups }\n        });\n    }\n\n    @observable\n    @requiresWrite\n    get description(): string {\n        return this._description as string;\n    }\n\n    set description(description: string) {\n        this._actionDispatch({\n            name: 'updateElement',\n            type: 'update',\n            data: { description }\n        });\n    }\n\n    @observable\n    get descriptionModified(): Date {\n        return new Date(this._descriptionModifiedDate as number);\n    }\n\n    @observable\n    get descriptionModifiedBy(): string {\n        return this._descriptionModifiedBy as string;\n    }\n\n    @observable\n    get descriptionModifiedContext(): UpdateContext {\n        return this._descriptionModifiedContext as UpdateContext;\n    }\n\n    @observable\n    get wasDescriptionModifiedLocally(): boolean {\n        return this._descriptionModifiedLocally as boolean;\n    }\n\n    @observable\n    get modifiedBy(): string {\n        return this._modifiedBy as string;\n    }\n\n    @observable\n    get modifiedContext(): UpdateContext {\n        return this._modifiedContext as UpdateContext;\n    }\n\n    @observable\n    get wasModifiedLocally(): boolean {\n        return this._modifiedLocally as boolean;\n    }\n\n    @observable\n    get createdBy(): string {\n        return this._createdBy as string;\n    }\n\n    @observable\n    get createdContext(): UpdateContext {\n        return this._createdContext as UpdateContext;\n    }\n\n    @observable\n    get wasCreatedLocally(): boolean {\n        return this._createdLocally as boolean;\n    }\n\n    @observable\n    get isDeletedLocally(): boolean {\n        return false;\n    }\n\n    beginOperation() {\n        return this.libraryContents.beginOperation();\n    }\n    endOperation(callback?: () => void): Promise<void> {\n        return this.libraryContents.endOperation(callback);\n    }\n\n    @observable\n    get representations(): Representation[] {\n        return this._children;\n    }\n\n    @observable\n    getPrimaryRepresentation(): Representation | undefined {\n        return this.representations.find(representation => representation.relationship === 'primary');\n    }\n\n    @observable\n    getRepresentationById(id: string): Representation | undefined {\n        return this.representations.find(representation => representation.id === id);\n    }\n\n    @requiresWrite\n    createRepresentation(\n        type: string,\n        relationship: 'primary' | 'rendition',\n        _index?: number,\n        _preserveThumbnail?: boolean\n    ): Representation {\n        const id = createPlaceholderId();\n        const representations = [ ...this._childrenData ];\n        representations.splice(1, 0, {\n            id,\n            type,\n            relationship,\n            isFullSize: false,\n            isExternalLink: false\n        });\n\n        this._actionDispatch({\n            name: 'updateElementContent',\n            type: 'update',\n            data: {\n                representations\n            }\n        });\n\n        return this.getRepresentationById(id) as Representation;\n    }\n\n    @requiresWrite\n    removeRepresentation(representation: Representation): void {\n        const representations = [ ...this._childrenData ];\n        const index = representations.findIndex(rep => rep.id === representation.id);\n\n        if (index === -1) {\n            return;\n        }\n\n        representations.splice(index, 1);\n\n        this._actionDispatch({\n            name: 'updateElementContent',\n            type: 'update',\n            data: {\n                representations\n            }\n        });\n    }\n\n    @requiresWrite\n    removeAllRepresentations(): void {\n        this._actionDispatch({\n            name: 'updateElementContent',\n            type: 'update',\n            data: {\n                renditionUrl: {},\n                representations: []\n            }\n        });\n    }\n\n    @observable\n    getValue(namespace: string, key: string): any {\n        return this._customData?.[`${namespace}#${key}`];\n    }\n\n    @observable\n    getValues(): { namespace: string; key: string; value: any }[] {\n        return mapAttributesToArray(this._customData as { [s: string]: any });\n    }\n\n    @requiresWrite\n    setValue(namespace: string, key: string, value: any): void {\n        this._actionDispatch({\n            name: 'updateElement',\n            type: 'update',\n            data: {\n                customData: {\n                    [`${namespace}#${key}`]: value\n                }\n            }\n        });\n    }\n\n    @requiresWrite\n    removeValue(namespace: string, key: string): void {\n        this.setValue(namespace, key, null);\n    }\n\n    getThumbnailURL(size: RenditionSize): string {\n        return this._driver.getRenditionUrl(this, size);\n    }\n\n    async getThumbnailPath(size: RenditionSize = 'full'): Promise<string> {\n        await this.committed;\n        return this._driver.getRenditionPath(this.library.id, this.id, size);\n    }\n\n    getThumbnailContent(size: RenditionSize): Promise<Blob> {\n        return this._driver.getRendition(this, size).then(res => res.blob());\n    }\n\n    @observable\n    supportsVectorThumbnail(): boolean {\n        const primary = this.getPrimaryRepresentation();\n        if (primary) {\n            return LibraryConstants.VECTOR_RENDITION_ELEMENT_TYPES.includes(primary.type);\n        }\n        return false;\n    }\n\n    @observable\n    getActions(actionId: ActionType): ApplicationAction[] {\n        const representation = this.getPrimaryRepresentation();\n\n        if (!representation) {\n            return [];\n        }\n\n        if (this.library.documentType) {\n            const docProductMap = this._apiRoot.getOption('DOCUMENT_LIBRARY_ACTION_PRODUCT_MAP');\n            const docCodes = (docProductMap.types as any)[this.library.documentType] || [];\n            return constructActions(this.library, actionId, docCodes, docProductMap.products) as ApplicationAction[];\n        }\n\n        const productMap = this._apiRoot.getOption('ELEMENT_ACTION_PRODUCT_MAP');\n        const representationTypeMap = (productMap.types as any)[this.type] || {};\n        const codes = representationTypeMap[representation.type] || [];\n        return constructActions(this, actionId, codes, productMap.products) as ApplicationAction[];\n    }\n\n    @observable\n    @requiresWrite\n    get roles(): Role[] {\n        return this._roles || [];\n    }\n\n    set roles(roles: Role[]) {\n        this._actionDispatch({\n            name: 'updateElement',\n            type: 'update',\n            data: { roles }\n        });\n    }\n\n    get isStockAsset(): boolean {\n        const isSupportedElementType = Object.values(ElementMimeTypeMap).includes(this.type as ElementMimeType);\n        const hasStockData = this.getStockDataForElement() !== undefined;\n        return isSupportedElementType && hasStockData;\n    }\n\n    get isLicensed() {\n        return this.getStockDataForElement()?.state === 'purchased';\n    }\n\n    private getStockDataForElement(index?: number) {\n        // First try the primary representation\n        const representation = index === undefined ? this.getPrimaryRepresentation() : this.representations[index];\n        let stockData = representation?.getValue('adobestock', 'trackingdata');\n\n        // If the contentURL is blank, then do not consider it as a download failure\n        if (\n            stockData\n            && representation?.isExternalLink\n            && representation?.getCachedExternalLinkError()\n            && representation?.getContentURL() !== ''\n        ) {\n            // It's an external link, but the external link isn't valid: See if there's a comp representation to try:\n            const compStockData = this.getStockDataForElement(index === undefined ? 0 : index + 1);\n            if (compStockData) {\n                // Use the comp representation's comp data, because the primary isn't licensed\n                stockData = compStockData;\n            } else {\n                // The primary isn't licensed, and we don't have a comp - oh no!\n                // Let's be tricksy and reconstruct the unlicensed stock data\n                stockData = { ...stockData, state: 'not_purchased' };\n            }\n        }\n\n        return stockData;\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _actionDispatch(action: Optional<Action, 'path'>) {\n        if (!action.path) {\n            action.path = `$.elements[?(@.id == \"${this.id}\")]`;\n        }\n\n        this._lastLocalUpdateDate = Date.now();\n        this.libraryContents._actionDispatch(action);\n    }\n\n    // TODO-R[SHARED-4623]: Not ideal to use arrow function property instead of a method. Takes more memory than methods on the prototype.\n    // Solution is to refactor to use Abstract/composable classes.\n    protected _updateImplementation = (data: Partial<ElementData>) => {\n        const session = this._itemPool.createUpdateSession();\n        this._updater.updateLocalItem(session, this, data); // will also call this._updateChildren, which emits change events\n        session.commit(); // emits a change event\n    };\n}\n\nconst propertyUpdaterTypes: IPropertyTypeMap = {\n    '_roles': { name: 'roles', format: 'object', isArray: true },\n    '_name': 'name',\n    '_libraryAssetId': 'libraryAssetId',\n    '_children': {\n        name: 'representations',\n        format: 'object',\n        set: (representationsData: RepresentationData[], dest: any) => {\n            const element = dest as Element;\n            element._updateChildren(representationsData); // updates this._children with the full list of representations\n        }\n    },\n    '_elementId': 'id',\n    '_type': 'type',\n    '_modifiedDate': { name: 'modifiedDate', format: 'number' },\n    '_createdDate': { name: 'createdDate', format: 'number' },\n    '_tags': { name: 'tags', format: 'object', isArray: true },\n    // '_groups': 'groups',\n    '_dependencyIds': { name: 'dependencyIds', format: 'object', isArray: true },\n    '_description': 'description',\n    '_descriptionModifiedDate': { name: 'descriptionModifiedDate', format: 'number' },\n    '_descriptionModifiedBy': 'descriptionModifiedBy',\n    '_descriptionModifiedContext': { name: 'descriptionModifiedContext', format: 'object' },\n    '_descriptionModifiedLocally': { name: 'descriptionModifiedLocally', format: 'boolean' },\n    '_modifiedBy': 'modifiedBy',\n    '_modifiedContext': { name: 'modifiedContext', format: 'object' },\n    '_modifiedLocally': { name: 'modifiedLocally', format: 'boolean' },\n    '_createdBy': 'createdBy',\n    '_createdContext': { name: 'createdContext', format: 'object' },\n    '_createdLocally': { name: 'createdLocally', format: 'boolean' },\n    '_customData': { name: 'customData', format: 'object' },\n    // '_autoName': 'autoName',\n    // '_elementRef': 'elementRef',\n    // '_sourceRef': 'sourceRef',\n    // '_sourceModifiedDate': 'sourceModifiedDate',\n};\n\nexport function getPreviousPlaceholderId(remoteItem: Partial<ElementData>): PlaceholderIdType | undefined {\n    return remoteItem.previousPlaceholderId;\n}\n\nconst elementItemUpdaterOptions: IItemUpdaterBaseOptions<Element, Partial<ElementData>> = {\n    //@ts-expect-error -- Element constructor has a more strict string type parameter than ItemBase requires\n    localItemType: Element,\n    getRemoteId: (data: Partial<ElementData>) => getCombinedIdOrPlaceholder(data),\n    getAlternateId: getPreviousPlaceholderId,\n    // TODO: implement ELEMENT_DATA_CHANGED if necessary\n    // Any changes to these properties from the update will trigger watchers of ELEMENT_DATA_CHANGED.\n    // Other properties updated will trigger the  default 'change' event\n    changeEventMap: new Map([\n    ]),\n    // Mapping ElementData to Element\n    propertyUpdater: new PropertyUpdater(propertyUpdaterTypes)\n};\n\nexport const ElementUpdater = new ItemUpdaterBase<Element, Partial<ElementData>>(elementItemUpdaterOptions);\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type LibraryContents from './LibraryContents';\nimport type SAMLibrary from '../../libraries/Library';\n\nexport type ActionName =\n    | 'createLibrary'\n    | 'removeLibrary'\n    | 'permanentlyDeleteLibrary'\n    | 'leaveLibrary'\n    | 'unfollowLibrary'\n    | 'copyLibrary'\n    | 'moveLibrary'\n    | 'updateLibrary'\n    | 'createElement'\n    | 'updateElement'\n    // updateElementContent is used for setting representations... an operation that is not currently batchable.\n    // It would be nice if we could make it batchable some day.\n    | 'updateElementContent'\n    | 'removeElement'\n    | 'restoreElement'\n    | 'deleteElement'\n    | 'copyElement'\n    | 'moveElement'\n    | 'createGroup'\n    | 'updateGroup'\n    | 'removeGroup'\n    | 'moveGroup'\n    | 'copyGroup'\n    // uploadComponent is used for uploading an un-referenced dcx component to a library.\n    | 'uploadComponent'\n    // A dependent action should block the execution queue, but does nothing.\n    | 'dependent';\n\nexport type ActionType = 'no-op' | 'insert' | 'update' | 'remove' | 'aggregate';\n\nexport type Action = {\n    name?: ActionName;\n    type: ActionType;\n    library?: SAMLibrary;\n    libraryContents?: LibraryContents;\n    path?: string;\n    data?: any;\n    baseData?: any;\n    flags?: {\n        includeElements?: boolean;\n        permissionInheritance?: 'read' | 'all';\n        lockNewLibraries?: boolean;\n        source?: SAMLibrary;\n        includeAppMetadata?: boolean;\n    };\n    actions?: Action[];\n    link?: Action;\n    originalAction?: Action;\n};\n\nexport type InsertAction<T> = Action & {\n    type: 'insert';\n    data: T;\n};\n\nexport type UpdateAction<T> = Action & {\n    type: 'update';\n    data: Partial<T>;\n    baseData: T;\n};\n\nexport type RemoveAction = Action & {\n    type: 'remove';\n    data: void;\n    baseData: {\n        modifiedDate: string;\n    };\n};\n\nexport type AggregateAction = Action & {\n    type: 'aggregate';\n    actions: Action[];\n};\n\nexport function isInsertAction(action: any): action is InsertAction<any> {\n    return action.type === 'insert';\n}\n\nexport function isUpdateAction(action: any): action is UpdateAction<any> {\n    return action.type === 'update';\n}\n\nexport function isRemoveAction(action: any): action is RemoveAction {\n    return action.type === 'remove';\n}\n\nexport function isAggregateAction(action: any): action is AggregateAction {\n    return action.type === 'aggregate';\n}\n\nexport function isAnyRemoveLibraryAction(action: any): action is Action {\n    return [ 'removeLibrary', 'unfollowLibrary', 'leaveLibrary', 'permanentlyDeleteLibrary' ].includes(action.name);\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport LibraryError from '../errors/LibraryError';\nimport Logger from '../utils/Logger';\n\n//TODO: fix this linter error when unit tests are in place\n//https://jira.corp.adobe.com/browse/SHARED-4388\n\n// eslint-disable-next-line no-useless-escape\nconst PATH_REGEX = /(\\.[a-zA-Z0-9]+)|(\\[\\?\\(([^\\[\\]]+)\\)\\])/g;\n// eslint-disable-next-line no-useless-escape\nconst VALID_PATH_REGEX = /^\\$(?:(\\.[a-zA-Z0-9]+)|(\\[\\?\\(([^\\[\\]]+)\\)\\]))*$/;\nconst EXPRESSION_REGEX = /^([^ ]+) *== *\"(.+)\"$/;\n\nfunction validatesPath() {\n    return function (target: JSONPath, propertyKey: string, descriptor: PropertyDescriptor) {\n        const original = descriptor.value;\n\n        descriptor.value = function (object: any, path: string, ...otherArgs: any[]) {\n            if (!VALID_PATH_REGEX.test(path)) {\n                throw new LibraryError('INVALID_PARAMETER', 'JSON Path is not valid');\n            }\n\n            return original.apply(this, [ object, path, ...otherArgs ]);\n        };\n\n        return descriptor;\n    };\n}\n\n/**\n * Super-simplistic subset of JSONPath (https://goessner.net/articles/JsonPath/)\n *\n * ONLY supports:\n * dot syntax ($.fieldName)\n * simple filtering (only field to string comparison) ($[@.fieldName == '2'])\n * composition of the above ($.field[@.innerField1 == 'abc'].innerField2[@.innerInnerField1 == 'xyz'].innerInnerField2)\n *\n * The above would access:\n *\n * {\n *     field: [\n *         {\n *             innerField1: 'abc'\n *             innerField2: [\n *                 {\n *                     innerInnerField1: 'xyz',\n *                     innerInnerField2: 'foo' // <-- THIS\n *                 }\n *             ]\n *         }\n *     ]\n * }\n */\ninterface ParentObject<T> {\n    [key: string]: T;\n}\n\nexport default class JSONPath {\n    @validatesPath()\n    static get<T>(object: any, path: string): T | null {\n        if (path === '$') {\n            return object as T | null;\n        }\n\n        return path\n            .match(PATH_REGEX)\n            ?.reduce((memo, part) => memo && this._handlePathPart(memo, part), object) as T | null;\n    }\n\n    @validatesPath()\n    static set<T>(object: any, path: string, value: T): T | undefined {\n        if (path === '$') {\n            throw new LibraryError('INVALID_PARAMETER', 'Cannot set in root of object');\n        }\n\n        const parts = path.match(PATH_REGEX);\n        if (parts) {\n            const lastPart = parts.pop();\n            const parentPath = parts.join('');\n\n            if (!lastPart) {\n                throw new LibraryError('INVALID_PARAMETER', 'JSON path must end in a field');\n            }\n\n            let parent = object;\n\n            if (parentPath) {\n                parent = this.get(object, `$${parentPath}`);\n\n                if (!parent) {\n                    throw new LibraryError('INVALID_PARAMETER', 'JSON path parent does not exist');\n                }\n            }\n\n            (parent as ParentObject<T>)[lastPart.substring(1)] = value;\n\n            return value;\n        }\n    }\n\n    @validatesPath()\n    static insert<T>(object: any, path: string, value: T) {\n        const array = this.get(object, path) ?? this.set(object, path, []);\n\n        if (!Array.isArray(array)) {\n            Logger.warn('JSONPath.insert failed to insert into non-array');\n            return;\n        }\n\n        array.push(value);\n    }\n\n    @validatesPath()\n    static remove(object: any, path: string): void {\n        const parts = path?.match(PATH_REGEX);\n        const lastPart = parts?.pop();\n\n        const parentArray = parts?.reduce((memo, part) => memo && this._handlePathPart(memo, part), object) || [];\n\n        if (!lastPart?.startsWith('[?(')) {\n            throw new LibraryError('INVALID_PARAMETER', 'JSON Path must end in a filter');\n        }\n\n        if (!Array.isArray(parentArray)) {\n            return;\n        }\n\n        const value = this._handleFilterExpression(parentArray, lastPart.substring(3, lastPart.length - 2));\n        const index = parentArray.indexOf(value);\n\n        if (index !== -1) {\n            parentArray.splice(index, 1);\n        }\n    }\n\n    private static _handlePathPart(object: any, part: string): any {\n        if (part.startsWith('[?(')) {\n            return this._handleFilterExpression(object, part.substring(3, part.length - 2));\n        }\n\n        return object[part.substring(1)];\n    }\n\n    private static _handleFilterExpression(object: any, expression: string): any {\n        const [ , a, b ] = EXPRESSION_REGEX.exec(expression) || [];\n        const path = a.replace(/^@/, '$');\n\n        if (!Array.isArray(object)) {\n            return undefined;\n        }\n\n        return object.find((item: any) => this.get(item, path) === b);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * reducer\n * @packageDocumentation\n * @module reducer\n * @internal\n */\n\nimport JSONPath from '../../utils/JSONPath';\nimport type {\n    InsertAction,\n    UpdateAction,\n    RemoveAction,\n    Action\n} from '../Action';\nimport {\n    isAggregateAction,\n    isInsertAction,\n    isUpdateAction,\n    isRemoveAction\n} from '../Action';\n\nfunction insertObject<T>(state: T, action: InsertAction<any>): T {\n    JSONPath.insert(state, action.path as string, action.data);\n    return state;\n}\n\nfunction updateObject<T>(state: T, action: UpdateAction<any>): T {\n    const itemData = JSONPath.get(state, action.path as string);\n    // TODO: Deep\n    Object.assign(itemData as string, action.data);\n\n    return state;\n}\nfunction removeObject<T>(state: T, action: RemoveAction): T {\n    JSONPath.remove(state, action.path as string);\n    return state;\n}\n\n// Given a state and an Action, use the Action's path and data to update the state\nexport default function reducer<T>(state: T, action: Action): T {\n    if (isAggregateAction(action)) {\n        return action.actions.reduce((memo, subAction) => reducer(memo, subAction), state);\n    }\n\n    if (isInsertAction(action)) {\n        return insertObject<T>(state, action);\n    }\n\n    if (isUpdateAction(action)) {\n        return updateObject<T>(state, action);\n    }\n\n    if (isRemoveAction(action)) {\n        return removeObject<T>(state, action);\n    }\n\n    return state;\n}\n","// keeps `capacity` most recently added strings\nexport default class FIFOStringSet {\n    private _cache: Map<string, number>;\n    private _capacity: number;\n\n    constructor(capacity: number = 10) {\n        this._cache = new Map();\n        this._capacity = capacity;\n    }\n\n    has(key: string): string | undefined {\n        if (this._cache.get(key)) {\n            return key;\n        }\n        return undefined;\n    }\n\n    add(key: string): void {\n        if (this._cache.has(key)) {\n            this._cache.delete(key); // update timestamp if key already exists\n        } else if (this._cache.size >= this._capacity) {\n            // remove least recently added item\n            const oldestKey = Array.from(this._cache.entries()).reduce((oldest, entry) => {\n                return oldest[1] < entry[1] ? oldest : entry;\n            })[0];\n            this._cache.delete(oldestKey);\n        }\n        this._cache.set(key, Date.now());\n    }\n}\n","const richTypes = { Date: true, RegExp: true, String: true, Number: true };\nexport default function diff(\n\tobj,\n\tnewObj,\n\toptions = { cyclesFix: true },\n\t_stack = []\n) {\n\tlet diffs = [];\n\tconst isObjArray = Array.isArray(obj);\n\tfor (const key in obj) {\n\t\tconst objKey = obj[key];\n\t\tconst path = isObjArray ? +key : key;\n\t\tif (!(key in newObj)) {\n\t\t\tdiffs.push({\n\t\t\t\ttype: \"REMOVE\",\n\t\t\t\tpath: [path],\n\t\t\t\toldValue: obj[key],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst newObjKey = newObj[key];\n\t\tconst areObjects =\n\t\t\ttypeof objKey === \"object\" && typeof newObjKey === \"object\";\n\t\tif (\n\t\t\tobjKey &&\n\t\t\tnewObjKey &&\n\t\t\tareObjects &&\n\t\t\t!richTypes[Object.getPrototypeOf(objKey).constructor.name] &&\n\t\t\t(!options.cyclesFix || !_stack.includes(objKey))\n\t\t) {\n\t\t\tconst nestedDiffs = diff(\n\t\t\t\tobjKey,\n\t\t\t\tnewObjKey,\n\t\t\t\toptions,\n\t\t\t\toptions.cyclesFix ? _stack.concat([objKey]) : []\n\t\t\t);\n\t\t\tdiffs.push.apply(\n\t\t\t\tdiffs,\n\t\t\t\tnestedDiffs.map((difference) => {\n\t\t\t\t\tdifference.path.unshift(path);\n\t\t\t\t\treturn difference;\n\t\t\t\t})\n\t\t\t);\n\t\t} else if (\n\t\t\tobjKey !== newObjKey &&\n\t\t\t!(\n\t\t\t\tareObjects &&\n\t\t\t\t(isNaN(objKey)\n\t\t\t\t\t? objKey + \"\" === newObjKey + \"\"\n\t\t\t\t\t: +objKey === +newObjKey)\n\t\t\t)\n\t\t) {\n\t\t\tdiffs.push({\n\t\t\t\tpath: [path],\n\t\t\t\ttype: \"CHANGE\",\n\t\t\t\tvalue: newObjKey,\n\t\t\t\toldValue: objKey,\n\t\t\t});\n\t\t}\n\t}\n\tconst isNewObjArray = Array.isArray(newObj);\n\tfor (const key in newObj) {\n\t\tif (!(key in obj)) {\n\t\t\tdiffs.push({\n\t\t\t\ttype: \"CREATE\",\n\t\t\t\tpath: [isNewObjArray ? +key : key],\n\t\t\t\tvalue: newObj[key],\n\t\t\t});\n\t\t}\n\t}\n\treturn diffs;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { LibraryData, LibraryContentsData } from '../models/data/LibraryData';\nimport type { GroupData } from '../models/data/GroupData';\nimport type { ElementData } from '../models/data/ElementData';\nimport type SAMLibrary from '../../libraries/Library';\nimport microdiff from 'microdiff';\n\n/**\n * REFACTOR NOTES:\n * Anything with LibraryData should move to LibraryContentsData.\n * To avoid too many breaking changes as once, for now I have just added LibraryContentsData to the accepted types on methods that will be used by LibraryContents.\n */\n\nimport type {\n    Action,\n    AggregateAction,\n    UpdateAction,\n    RemoveAction } from '../models/Action';\nimport {\n    isRemoveAction,\n    isUpdateAction,\n    isAggregateAction\n} from '../models/Action';\nimport { deepCopy } from '../utils/StoreUtils';\nimport JSONPath from './JSONPath';\nimport { extractElementCollection, extractGroupId } from './PathUtils';\nimport { createPlaceholderId } from '../models/utils';\n\nconst ACTION_TYPE_HANDLERS = [\n    {\n        test: (action: Action) =>\n            isAggregateAction(action) && [ 'moveGroup', 'copyGroup' ].includes(action.name as string),\n        handler: rebaseGroupActionWithContents\n    },\n    {\n        test: (action: Action) => isUpdateAction(action) && action.name === 'updateElementContent',\n        handler: rebaseContentAction\n    },\n    {\n        test: (action: Action) => isUpdateAction(action) && action.name === 'updateGroup',\n        handler: rebaseUpdateGroupAction\n    },\n    {\n        test: (action: Action) => isUpdateAction(action) && action.name === 'updateElement',\n        handler: rebaseUpdateElementMetadataAction\n    },\n    {\n        test: (action: Action) => isAggregateAction(action) && action.name === 'removeElement',\n        handler: rebaseRemoveElementAction\n    },\n    {\n        test: (action: Action) => isRemoveAction(action),\n        handler: rebaseRemoveAction\n    }\n] as const;\n\nfunction rebaseContentAction(data: LibraryData | LibraryContentsData, action: Action): Action[] {\n    const newBaseData = JSONPath.get(data, action.path as string) as any;\n\n    // 1. If a change to this element has been applied since this action was created\n    if (newBaseData && newBaseData.modifiedDate !== action.baseData.modifiedDate) {\n        if (\n            !microdiff(newBaseData.representations, action.baseData.representations, {\n                cyclesFix: false\n            }).find(\n                d =>\n                    // Disregard changes in id\n                    d.path[1] !== 'id' &&\n                    // Check if changes to representations are only additive\n                    d.type !== 'CREATE' &&\n                    // Disregard removals of undefined values\n                    !(d.oldValue === undefined && d.type === 'REMOVE')\n            )\n        ) {\n            // If this diff is only additive or a no-op, we will do nothing.\n            return [ action ];\n        }\n    }\n\n    // 2. If newBaseData does not exist recreate the element\n    // OR if base modified dates have changed and the changes were more than additive, fork element\n    if (!newBaseData || newBaseData.modifiedDate !== action.baseData.modifiedDate) {\n        return [\n            {\n                name: 'createElement',\n                type: 'insert',\n                path: extractElementCollection(action.path as string),\n                data: deepCopy({\n                    ...action.baseData,\n                    ...action.data,\n                    id: createPlaceholderId()\n                })\n            }\n        ];\n    }\n\n    // 3. Otherwise, nothing to do\n    return [ action ];\n}\n\nfunction rebaseGroupActionWithContents(data: LibraryData | LibraryContentsData, action: AggregateAction) {\n    const actions: Action[] = [];\n\n    const groupId = extractGroupId(action.path as string);\n    const oldElements = action.actions.map(subAction => subAction.name === 'removeElement' && subAction.baseData);\n    const newElements = data.elements?.filter(el => el.groups.find(group => group.id === groupId)) || [];\n\n    // 1. If a group member has been added, remove the element from the group before moving.\n    // - Preprend action removing the element from the group\n    const addedElements = newElements.filter(element => !oldElements.find(oldElement => oldElement.id === element.id));\n    for (const element of addedElements) {\n        actions.push({\n            name: 'updateElement',\n            type: 'update',\n            path: `$.elements[?(@.id == \"${element.id}\")]`,\n            data: {\n                groups: element.groups.filter(group => group.id !== groupId)\n            }\n        });\n    }\n\n    // 2. If a group member has been removed, leave the element removed from the group.\n    // - Remove element from aggregate's local actions\n    const removedElements = oldElements.filter(\n        element => !newElements.find(newElement => newElement.id === element.id)\n    );\n    for (let i = action.actions.length - 1; i >= 0; i -= 1) {\n        const subAction = action.actions[i];\n        if (removedElements.find(element => element.id === subAction.baseData.id)) {\n            action.actions.splice(i, 1);\n        }\n    }\n\n    // 3. If a group member has been changed, remove the changed element from group, create a new element based on the original in group, move group\n    // - Prepend createElement\n    // - Prepend updateElement\n    // - Replace old element with new element in aggregate's local actions\n\n    actions.push(action);\n\n    return actions;\n}\n\nfunction rebaseRemoveElementAction(data: LibraryData | LibraryContentsData, action: AggregateAction) {\n    const newBaseData = JSONPath.get(data, action.path as string) as any;\n    const removeAction = action.actions.find(subAction => subAction.name === 'removeElement');\n\n    // if element is changed, dont want to delete or create in removedElements\n    if (!newBaseData || newBaseData.modifiedDate !== removeAction?.baseData.modifiedDate) {\n        return [];\n    }\n\n    return [ action ];\n}\n\nfunction rebaseUpdateGroupAction(data: LibraryData | LibraryContentsData, action: UpdateAction<GroupData>): Action[] {\n    const newBaseData = JSONPath.get(data, action.path as string) as GroupData;\n\n    // If the target no longer exists, restore the target (group)\n    // TODO: How do we restore the group members?\n    if (!newBaseData) {\n        return [\n            {\n                name: 'createGroup',\n                type: 'insert',\n                path: '$.groups',\n                data: deepCopy({\n                    ...action.baseData,\n                    ...action.data,\n                    id: createPlaceholderId()\n                })\n            }\n        ];\n    }\n\n    // Otherwise rebase the action. This doesn't really matter for a metadata update, but we might as well.\n    return [\n        {\n            ...action,\n            baseData: deepCopy(newBaseData)\n        }\n    ];\n}\n\nfunction rebaseUpdateElementMetadataAction(data: LibraryData | LibraryContentsData, action: UpdateAction<ElementData>) {\n    const newBaseData = JSONPath.get(data, action.path as string) as ElementData;\n\n    // If the target no longer exists, delete the action (element metadata)\n    if (!newBaseData) {\n        return [];\n    }\n\n    // Otherwise rebase the action. This doesn't really matter for a metadata update, but we might as well.\n    return [\n        {\n            ...action,\n            baseData: deepCopy(newBaseData)\n        }\n    ];\n}\n\nfunction rebaseRemoveAction(data: LibraryData | LibraryContentsData, action: RemoveAction) {\n    const newBaseData = JSONPath.get(data, action.path as string) as any;\n\n    // If the target no longer exists, delete the action (nothing to delete)\n    // If the element has been changed, delete the action (keep the changed element/group)\n    if (!newBaseData || newBaseData.modifiedDate !== action.baseData.modifiedDate) {\n        return [];\n    }\n\n    // Otherwise, keep the action (remove element/group)\n    return [ action ];\n}\n\nexport function rebaseAction(data: LibraryData | LibraryContentsData, action: Action): Action[] {\n    for (const { test, handler } of ACTION_TYPE_HANDLERS) {\n        if (test(action)) {\n            return handler(data, action as never);\n        }\n    }\n\n    return [ action ];\n}\n\n// R-TODO: ownership may not be loaded yet on SAMLibrary. Temporarily disabling this until we can move over to a SAM Library util.\n// This isn't used internally but may be used by a client of the JS API.\n// export function isOwnedLibrary(data: LibraryData | SAMLibrary) {\n//     return ['private', 'outgoing'].includes(data.ownership);\n// }\n\nexport function isTeamLibrary(library: SAMLibrary): boolean {\n    return library.isChildOfProject;\n}\n\nexport function isBrandLibrary(library: SAMLibrary): boolean {\n    return !!library.roles?.find(role => role.type === 'brand');\n}\n\nexport function isTrainingSetLibrary(library: SAMLibrary | LibraryData): boolean {\n    return !!library.roles?.some(role => role.type === 'cm_training_set');\n}\n\nexport function isLibraryLoadedByDefault(library: LibraryData, enableBrandLifecycleManagement?: boolean): boolean {\n    if (!library || isTrainingSetLibrary(library)) {\n        return false;\n    }\n\n    const isTeam = library.ownership === 'incoming';\n    const isPersonal = library.ownership === 'private' || library.ownership === 'outgoing';\n    const ownershipFilter = enableBrandLifecycleManagement ? isTeam : isPersonal;\n    const isBookmarked = !!library.bookmark?.id;\n    const isApprovedBrand = !!library.roles?.find(role => role.type === 'approvedbrand');\n    // A library is a loaded by default group if it is personal or bookmarked.\n    // Training Set Libraries are currently excluded from the default listing.\n    return ownershipFilter || isBookmarked || isApprovedBrand;\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { Action, InsertAction, UpdateAction } from './Action';\nimport { isInsertAction, isUpdateAction } from './Action';\nimport Logger from '../utils/Logger';\nimport reducer from './utils/reducer';\nimport { deepCopy, replacePlaceholders, markSubstitutedPlaceholders } from '../utils/StoreUtils';\nimport type Operation from '../drivers/Operation';\nimport { isAnyRemoveLibraryAction } from './Action';\nimport FIFOStringSet from '../utils/FIFOStringSet';\nimport { rebaseAction } from '../utils/LibraryUtils';\nimport type { ElementData } from './data/ElementData';\nimport { extractElementId } from '../utils/PathUtils';\nimport type { LibraryContentsData } from './data/LibraryData';\nimport JSONPath from '../utils/JSONPath';\nimport type { HasModelBindings } from './utils/HasModelBindings';\nimport type ItemPool from '../../core/ItemPool';\nimport type SAMLibrary from '../../libraries/Library';\nimport type AdobeAsset from '../../assets/AdobeAsset';\nimport TypedEventEmitter from '../../core/TypedEventEmitter';\nimport type ISAMCorePrivate from '../../core/ISAMCorePrivate';\nimport type { ICCLibraries } from '../CCLibraries';\nimport type Element from './Element';\nimport type { ElementPoolId, ElementUpdater } from './Element';\nimport { getCombinedId } from './Element';\n\n/**\n * Store\n * @packageDocumentation\n * @module Store\n * @internal\n *\n * The `Store` follows a Redux-like pattern, where the Store holds the app state,\n * and a reducer function processes actions to update the state:\n * `const newState = reducer(state, action);`.\n *\n * ## State Structure\n * The Store maintains two branches of state:\n * - **`currentData` (exposed as `data`)**: Represents the \"current local\" state with changes made by the user.\n *   - All actions are immediately applied.\n * - **`baseData`**: Represents the \"base\" or \"last known remote\" state.\n *   - \"Remote\" may refer to Melville or Process.\n *   - Actions are only applied upon a successful REST API call.\n *\n * ## Store Responsibilities\n * 1. Dispatching actions for processing.\n * 2. Committing actions once a remote response is received.\n * 3. Batching actions using `beginOperation` and `endOperation`.\n *\n * ## Reducer Responsibilities\n * Unlike a typical React/Redux reducer, the Store's reducer handles additional logic beyond just updating state:\n * 1. **Basing the operation** – Capturing the original `currentData` before the operation.\n * 2. **Rebasing the operation** – Reconciling changes if the `baseData` has been updated and no longer matches the original state.\n *\n * ## Rebasing Rules\n * 1. If a field modified by the operation remains unchanged in the base, apply the change.\n * 2. If a field modified by the operation has changed, but the change timestamp is **before** the operation timestamp, apply the change.\n * 3. If a field modified by the operation has changed **after** the operation timestamp, discard the change.\n * 4. If all changes are invalidated by (3), remove the operation entirely.\n *\n * ## ItemUpdater vs. Reducer Pattern\n * SAM does not follow a pure reducer pattern but instead uses an **ItemUpdater** pattern.\n * - All subclasses of `ItemBase` (`Element`, `Group`, `Library`) use the **ItemUpdater** pattern.\n * - `LibraryContents`, however, uses the **reducer** pattern for state updates.\n */\n\n/**\n * REFACTOR TODOs:\n * - When supporting CRUD Operations/commits: replace commented out calls to this._modelCache as no actions are supported on libraries here\n * - Specify which methods are internal/package and which are public\n *\n * WHAT WORKS:\n * - getters\n *\n * WHAT DOES NOT YET WORK:\n * - updates/commits/actions\n *\n * NOTES:\n * Store no longer inherits from Model because it does not need to be a subclass of Item,\n * and no longer supports `committed` as there are currently no placeholder libraries in SAM.\n * (Placeholder logic required the id always be defined but for libraryContents the assetId is always defined and id maybe lazy loaded.)\n * Panel needs to be updated to remove `library.committed` check.\n */\n\nexport type ActionNotification = {\n    // 'type' is really more of a 'state' of the action lifecycle\n    // 1. Dispatch: Both Store._actionDispatch() and Store.endOperation() may call this.emit('action', { type: 'dispatch', action }), which leads to Orchestrator._doOperations()\n    // 2. Processing: Orchestrator calls this.emit('report', { type: 'processing', action}[]) when it is  about to make a server request (execute an Operation) and commit\n    // 3. Commit: Store._commit() updates the base state of the library with one or more actions, removes the action from the library, and calls this.emit('action', { type: 'commit', action })\n    // You can listen to either library/group/element.on('action') or orchestrator/CCLibraries.on('report') to receive ActionNotifications.\n    type: 'dispatch' | 'processing' | 'commit';\n    action: Action;\n};\n\nexport const operationPending: unique symbol = Symbol('operationPending');\n\nexport default class Store extends TypedEventEmitter<any> implements HasModelBindings {\n    protected _baseData: LibraryContentsData;\n    protected _currentData: LibraryContentsData;\n    protected _oldCurrentData_temp: LibraryContentsData | undefined;\n    protected _actions: Action[] = [];\n    protected _reducer = reducer;\n    private _operation: Operation<unknown> | undefined | typeof operationPending = undefined;\n    private _isSquelched = false;\n    private _receivedEventDuringSquelchPeriod = false;\n    private _pendingActionSemaphore = 0; // Track calls to beginOperation()\n    private _pendingOperationResolvers: (() => void)[] = [];\n    protected _lastLocalUpdateDate = 0;\n    protected _previouslySeenEtags = new FIFOStringSet();\n    protected _assetPool: ItemPool<SAMLibrary | AdobeAsset>;\n    /**\n     * @package -- for use in SAM.js only\n    */\n    // TODO-R[SHARED-3520]: Temporarily public for tests, until we implement getElementById API\n    public _elementPool: ItemPool<Element, ElementPoolId>;\n    protected _elementUpdater: typeof ElementUpdater;\n\n    /**\n     * Pending actions are applied to the current state, but aren't yet ready to be committed.\n     * Actions are added to this queue when an operation is in progress.\n     */\n    protected _pendingActions: Action[] = [];\n\n    constructor(\n        readonly _core: ISAMCorePrivate,\n        /**\n         * @internal\n         * @package -- for use in SAM.js only\n         */\n        // TODO: Later, move internal API to using underscores.\n        readonly _apiRoot: ICCLibraries,\n        readonly library: SAMLibrary // holds a hard reference to the parent library\n    ) {\n        super();\n\n        // TODO-R: Consider paring down LibraryContentsData to only these. Might need time stamps though.\n        const startingState: LibraryContentsData = {\n            // Elements/groups need to be initialized even when the data is not yet available,\n            // so that they can be referred to by JSONPath (e.g. '$.elements').\n            groups: [],\n            elements: [],\n            // Not sure if I need these\n            assetId: library.id,\n            id: library._legacyLibraryId_NoLazyLoad,\n        };\n\n        this._baseData = startingState;\n        this._currentData = deepCopy(startingState);\n        this._assetPool = _apiRoot.assetPool;\n        // shared pools across all libraries:\n        this._elementPool = _apiRoot.elementPool;\n        this._elementUpdater = _apiRoot.elementUpdater;\n    }\n\n    // local data (current state in UI)\n    get data(): LibraryContentsData {\n        return this._currentData;\n    }\n\n    // last known remote or process state (regardless of whether the process has pushed the change to the server)\n    get baseData(): LibraryContentsData {\n        return this._baseData;\n    }\n\n    get actions() {\n        return this._actions;\n    }\n\n    /**\n     * @internal\n     * @package -- for use in SAM.js only\n     */\n    _revert() {\n        // Clear any remaining actions\n        this._actions = [];\n        this._pendingActions = [];\n        this._pendingActionSemaphore = 0;\n\n        // Revert data back to last committed stable state\n        const oldData = this._currentData;\n        this._currentData = deepCopy(this._baseData);\n        this._updateChildren(oldData, this._currentData);\n        this.emit('change');\n    }\n\n    /**\n     * Enqueue the user-initiated action to make the request to the remote server/process.\n     * Also update the local state (currentData) optimistically, so the user sees the change immediately.\n     *\n     * Specifically this will:\n     * 1. Put the action in the pendingActions queue\n     * 2. LibraryContents - update currentData using reducer pattern.\n     * 3. Children - update (local) data using the ItemUpdater pattern\n     * 4. Emit a change event\n     *\n     * @param action\n     * @package -- only for use in SAM.js\n     */\n    // uses a reducer to update currentData on libraryContents and propagate to the children using the ItemUpdater pattern.\n    // However, since the Library class does not support optimistic updates, the Library should NOT be updated here.\n    // It will continue to reflect the equivalent of baseData (last known server/process state).\n    _actionDispatch(action: Action) {\n        // TODO: Optimistic updates are not currently supported on the Library itself in SAM.\n        // But SAM does support viewing discarded assets. Therefore, we need to consider preventing actions except for restore on a discarded library.\n        // if (this.isDeletedLocally) {\n        //     Logger.log(`[LIBRARY] Cannot actionDispatch action on deleted library unless it is for a restore: ${this.id}`);\n        //     return;\n        // }\n\n        if (!action.path) {\n            action.path = '$';\n        }\n\n        // TODO: Where should we inject this data? Probably not here.\n        if (action.type === 'aggregate') {\n            action.actions?.map(subAction => {\n                if (subAction.type === 'remove') {\n                    const item = JSONPath.get(this._currentData, action.path as string) as any;\n                    subAction.baseData = {\n                        modifiedDate: item.modifiedDate\n                    };\n                }\n                return subAction;\n            });\n        }\n\n        if (action.type === 'remove') {\n            const item = JSONPath.get(this._currentData, action.path) as any;\n            action.baseData = {\n                modifiedDate: item.modifiedDate\n            };\n        }\n\n        if (action.type === 'update') {\n            action.baseData = deepCopy(JSONPath.get(this._currentData, action.path));\n        }\n\n        // Deep copy the data here so it doesn't get updated via reference.\n        if (isInsertAction(action) || isUpdateAction(action)) {\n            action.data = deepCopy(action.data);\n        }\n\n        const currentData = this._reducer(this._currentData, action);\n\n        if (this.isOperationInProgress) {\n            this._pendingActions.push(action);\n        } else {\n            this._actions.push(action);\n        }\n\n        this._currentData = currentData;\n\n        this._lastLocalUpdateDate = Date.now();\n\n        // If the action is a no-op, then the state hasn't changed. No need to update caches\n        // or emit a change event since the data didn't actually change.\n        if (action.type !== 'no-op') {\n            // TODO-R[SHARED-5159]: A 'no-op' action.type from _actionDispatch will not define old/baseData. We need to account for this when implementing CRUD updates, and diffing, in _updateChildren.\n            this._updateChildren(action.baseData, currentData);\n\n            // Need to call change listener after caches have been updated. Otherwise we may end up in an inconsistent state.\n            this.emit('change');\n        }\n    }\n\n    /**\n     * Post remote modification (on server or process), merge the new data into the store.\n     *\n     * Specifically this will update:\n     * 1. LibraryContents - use reducer pattern to update baseData, then rebase currentData and actions (and placeholderIDs) on top.\n     * 2. Children - update using ItemUpdater pattern (Reflects currentData rebased on top of baseData)\n     * @param actions   The actions that were committed.\n     * @param [etag]    The new etag for the library.\n     */\n    public _commit(actions: Action[], etag?: string) {\n        if (!this._confirmActionsAtHead(actions)) {\n            // TODO: Our action may have changed due to feedback from the server. How do we link these together?\n            // Something catastrophic has happened and our state is corrupt!\n            // throw new Error();\n        }\n\n        markSubstitutedPlaceholders(actions);\n\n        // The same actions that have been replayed on the baseData to get the currentData\n        // are now replayed on baseData to get the new baseData,\n        // effectively bringing baseData up to date with the currentData at commit().\n        let newBaseData = { ...this._baseData };\n        for (const action of actions) {\n            // The actions contain the returned json from each operation in the data property,\n            // so we can use that to update the baseData\n            newBaseData = this._reducer(newBaseData, action);\n            this._actions.shift();\n        }\n\n        this._actions = replacePlaceholders(actions, this._actions);\n\n        // All commits should have an etag from the server. We want to update it now for this batch of committed actions.\n        if (etag) {\n            this._previouslySeenEtags.add(this.etag);\n            newBaseData.etag = etag;\n        }\n\n        this._lastLocalUpdateDate = Date.now();\n        this._update(newBaseData, false);\n\n        actions.forEach(action => {\n            // If locally removed/unfollowed library, remove from cache\n            // Remotely removed libs are handled in the top level listener (e.g. sync group listener)\n            if (isAnyRemoveLibraryAction(action)) {\n                // this._modelCache?.remove(this, false);\n            }\n        });\n\n        this.emit(\n            'action',\n            ...actions.map<ActionNotification>(action => ({ type: 'commit', action }))\n        );\n\n        this.emit('commit');\n    }\n\n    private _confirmActionsAtHead(actions: Action[]) {\n        if (this._actions.length < actions.length) {\n            return false;\n        }\n\n        for (const i in actions) {\n            if (actions[i] !== this._actions[i]) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    // Delay dispatching actions until the outermost endOperation() call, which should result in one atomic batch request, for less server traffic.\n    // Note: A more appropriate name at this point would be something like 'startBatchingActions'/'endBatchingActions'\n    // since we now have a separate 'Operation' concept, which is a portion of the Driver that represents an atomic API request\n    // containing batchable actions, and technically the Operation is not constructed until a _actionDispatch occurs.\n    // Meaning the driver Operation doesn't actually exist until the outermost endOperation() is called.\n    /**\n     * @package -- only for use in SAM.js\n     */\n    beginOperation() {\n        this._squelchChangeEvents();\n        this._pendingActionSemaphore += 1;\n        Logger.log(`[STORE] Starting operation (Depth: ${this._pendingActionSemaphore})`);\n    }\n\n    // On the outermost endOperation call, dispatch all pending actions\n    // After the orchestrator has made the server request(s) and called library._commit,\n    // resolve all endOperation promises.\n    endOperation(_callback?: () => void): Promise<void> {\n        this._pendingActionSemaphore = Math.max(0, this._pendingActionSemaphore - 1);\n        Logger.log(`[STORE] Ending operation (Depth: ${this._pendingActionSemaphore})`);\n\n        if (this._pendingActionSemaphore === 0) {\n            Logger.log(`[STORE] Reached end of operation stack. Adding actions to queue...`);\n            const collapsedActions = this._collapseActions(this._pendingActions);\n            this._actions = this.actions.concat(collapsedActions);\n            this._pendingActions = [];\n\n            this.emit(\n                'action',\n                ...collapsedActions.map<ActionNotification>(action => ({ type: 'dispatch', action }))\n            );\n\n            this._unsquelchChangeEvents();\n\n            return new Promise(resolve => {\n                const onCommit = () => {\n                    if (this._actions.length) {\n                        return; // we still need to listen for 'commit' events\n                    }\n                    // We only want to resolve all operations' promises after all actions have been committed\n                    this._pendingOperationResolvers.forEach(resolve => resolve());\n                    this._pendingOperationResolvers = [];\n                    resolve();\n                    // all side effects following 'commit' events have been handled\n                    this.off('commit', onCommit);\n                };\n                this.on('commit', onCommit);\n            });\n        }\n\n        return new Promise(resolve => {\n            this._pendingOperationResolvers.push(resolve);\n        });\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    // TODO-R: Need to make sure that the refactored change events can be squelched.\n    // That means session.commit() for itemUpdater pattern models such as element\n    // and emit('change') for Representation and Store\n    _squelchChangeEvents() {\n        this._isSquelched = true;\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _unsquelchChangeEvents() {\n        this._isSquelched = false;\n\n        if (this._receivedEventDuringSquelchPeriod) {\n            this._receivedEventDuringSquelchPeriod = false;\n            this.emit('change');\n        }\n    }\n\n    emit(eventName: string | symbol, ...args: any[]): boolean {\n        if (this._isSquelched && eventName === 'change') {\n            this._receivedEventDuringSquelchPeriod = true;\n            return this.listenerCount(eventName) > 0;\n        }\n        return super.emit(eventName, ...args);\n    }\n\n    get etag(): string {\n        return this._baseData.etag as string;\n    }\n\n    set etag(value: string) {\n        this._baseData.etag = value;\n    }\n\n    /*\n        Note: This is a Library operation. (i.e. wait to dispatch until the operation closes)\n     */\n    get isOperationInProgress() {\n        return this._pendingActionSemaphore !== 0;\n    }\n\n    /*\n        Note: This is an Orchestrator operation. (i.e. batch these compatible dispatched actions)\n     */\n    set operation(operation: Operation<unknown> | undefined | typeof operationPending) {\n        this._operation = operation;\n    }\n\n    get operation() {\n        return this._operation;\n    }\n\n    // TODO: I believe we can deprecate this, as I don't see it being used anywhere.\n    // Also, should probably consolidate with library.locallyManaged which comes from data.locallyManaged\n    // get isLocallyManaged(): boolean {\n    //     return this._apiRoot.isLocallyManaged;\n    // }\n\n    /**\n     * Iterates through all of the passed-in actions, combines actions that contain changes upon the same element into one action\n     * This helps reduce the number of requests we send out\n     *\n     * @param {DisaptchAction[]} actions An array of actions to execute within the current operation.\n     * @returns {Action[]} newActions\n     */\n    private _collapseActions(actions: Action[]) {\n        // For now, all we really need to collapse are create element actions and their subsequent updates\n\n        const newActions: Action[] = [];\n        const newElementActions: { [s: string]: InsertAction<ElementData> } = {};\n        const updateElementContentActions: { [s: string]: UpdateAction<ElementData> } = {};\n\n        for (const action of actions) {\n            if ([ 'updateElement', 'updateElementContent' ].includes(action.name as string) && isUpdateAction(action)) {\n                const elementId = extractElementId(action.path as string);\n                const newElementAction = newElementActions[elementId as string];\n\n                if (newElementAction) {\n                    Logger.log(\n                        '[LIBRARY] Identified collapsible action (updateElement). Combining with (createElement)'\n                    );\n\n                    newElementAction.data = { ...newElementAction.data, ...action.data };\n                    continue;\n                }\n\n                const updateElementContentAction = updateElementContentActions[elementId as string];\n\n                if (updateElementContentAction) {\n                    updateElementContentAction.data = { ...updateElementContentAction.data, ...action.data };\n                    continue;\n                }\n            }\n\n            if (action.name === 'createElement' && isInsertAction(action)) {\n                newElementActions[action.data.id] = action;\n            }\n\n            if (action.name === 'updateElementContent' && isUpdateAction(action)) {\n                updateElementContentActions[extractElementId(action.path as string) as string] = action;\n            }\n\n            newActions.push(action);\n        }\n\n        return newActions;\n    }\n\n    /**\n     * Model APIs\n     */\n\n    /**\n     * @internal\n     * @package -- for use in SAM.js only\n     */\n    /**\n     * When new remote data from the server/process arrives, update the base state, and rebase the current state and action queue on top of it.\n     *\n     * Specifically this will update the state of:\n     * LibraryContents - overwrite the baseData, then rebase the currentData and actions using the reducer pattern\n     * Children - update (local) data using the ItemUpdater pattern\n     *\n     * It will NOT update:\n     * Library - When the server update came in, lazy loading library data would already be handled by the Library._load.\n     * (Also fyi, since the Library class does not yet support optimistic updates, there is no currentData to rebase in Library.)\n     * @param newBase - the newest data from the server\n     * @param progressiveLoad\n     *  - should be true if the newBase contains an incomplete elements array (e.g. when loading elements page by page in the ElementLoader).\n     *    Only handles adding/updating elements. Will not result in deleting any elements (from either base or current data).\n     *  - should be false if the newBase contains a full elements array (e.g. when fetching the manifest after a change notification).\n     *    Will delete elements that are not in the newBase, in addition to adding/updating elements.\n     * @returns the updated base data\n    */\n    // TODO-R[SHARED-4629]: Also look into why this returns the baseData, unlike on Model. Ideally we can remove this if not needed to keep the API the same.\n    _update(newBase: Partial<LibraryContentsData>, progressiveLoad: boolean) {\n        // Shallow copy newBase data into existing baseData\n        this._mergeBaseData(newBase, progressiveLoad);\n        // Rebase action queue (e.g. if an element has been removed, remove the removeElement action) and currentData on top of updated baseData\n        this._rebaseCurrentDataAndActions();\n\n        // Unlike the children which use the UpdateSession to emit notifications on the Items upon commit,\n        // the Store should just emit a change.\n        this.emit('change');\n    }\n\n    private _mergeBaseData = (newBase: Partial<LibraryContentsData>, progressiveLoad: Boolean) => {\n        // In the case of progressive loading, we should only add/update elements,\n        // and not remove any elements in baseData that are missing from the newBase\n        if (progressiveLoad === true) {\n            const mergeElements = (newElements: ElementData[], baseElements: ElementData[]): ElementData[] => {\n                const newElementIds = new Set(newElements.map(el => el.id));\n                const unchangedElements = baseElements.filter(el => !newElementIds.has(el.id));\n                return unchangedElements.concat(newElements);\n            };\n\n            const newElements = newBase.elements || [];\n            const baseElements = this._baseData.elements || [];\n            newBase.elements = mergeElements(newElements, baseElements);\n        }\n\n        this._baseData = { ...this._baseData, ...newBase };  // in case the newBase is a partial object, rather than replace baseData, we merge it in.\n    };\n\n    // Rebase currentData and actions on top of the new baseData\n    // See the Library conflicts tests and LibraryUtils.rebaseAction tests for more information\n    private _rebaseCurrentDataAndActions() {\n        let newCurrentData = deepCopy(this._baseData);\n\n        this._actions = this._actions\n            .map(action => {\n                const rebasedActions = rebaseAction(newCurrentData, action);\n                newCurrentData = rebasedActions.reduce(\n                    (memo, rebasedAction) => this._reducer(newCurrentData, rebasedAction),\n                    newCurrentData\n                );\n                return rebasedActions;\n            })\n            .flat();\n\n        this._pendingActions = this._pendingActions\n            .map(action => {\n                const rebasedActions = rebaseAction(newCurrentData, action);\n                newCurrentData = rebasedActions.reduce(\n                    (memo, rebasedAction) => this._reducer(newCurrentData, rebasedAction),\n                    newCurrentData\n                );\n                return rebasedActions;\n            })\n            .flat();\n\n        // This is the local state of models in the pool prior to being updated, which is kept temporarily to diff the latest current data and make appropriate changes to the children.\n        // TODO-R[SHARED-4711]: Later on, when we remove this._currentData after updating the children (since it duplicates the same data now saved in the item),\n        // we won't have this old data available for this short cut. Getting existing currentData would require finding the\n        // elements in the pool for this library, then serializing them into current Data.\n        const oldCurrentData = this._currentData;\n\n        // Update local state on the Store.\n        // TODO-R[SHARED-4711]: This actually duplicates the data that will be saved in the child Items next.\n        // To de-dupe memory usage, we can get rid of this. BUT, currentData will need to be recreated above and in actionDispatch().\n        // For more info: https://wiki.corp.adobe.com/display/ACPCSDK/Additional+Changes+to+State+Management\n        this._currentData = newCurrentData;\n\n        // Update local state of children using diff of current and previous local data from the Store\n        this._updateChildren(oldCurrentData, newCurrentData);\n    }\n\n    /**\n     * Diff previous and new currentData to determine what has changed.\n     * Then update, add, or remove elements accordingly. (Groups to be supported in the future.)\n     * Note: oldData and newData are both expected to have a *full* list of elements, (as far as we have fetched so far in the baseData,\n     * with any local changes (which may include deletes) rebased on top).\n     */\n    _updateChildren(oldData: LibraryContentsData, newData: LibraryContentsData) {\n        // TODO-R[SHARED-5159]: A 'no-op' action.type from _actionDispatch will not define old/baseData. We need to account for this when implementing CRUD updates, and diffing.\n        const elementPool = this._elementPool;\n        const session = elementPool.createUpdateSession();\n        const newElementsData = newData.elements;\n        const oldElementsData = oldData.elements;\n        // Find model that matches data.id/previousPlaceholderId and update *before* doing any removals\n        const upsertItems = () => {\n            /* Note: It would be nice if we could just call `updater.updateRemoteItems(session, newElementsData);`\n                to handle both creating and updating items, but it doesn't handle everything that Model._update does,\n                such as custom placeholder logic and updating children. In theory, it *could* though.\n                We could optimize to combine the compoundId and placeholder logic, and when data comes through the model/elementUpdater,\n                it can call a function to do special handling for the id and for child properties like 'representations'. */\n\n            newElementsData.forEach(data => {\n                // TODO-R[SHARED-4488]: Use compound id once supported.\n                // TODO-R[SHARED-4970]: Make sure placeholderId updates working as expected.\n                // TODO-R[SHARED-4971]: When we support CRUD updates, make sure this item has not been deleted locally before updating it.\n                const item = data.previousPlaceholderId ? elementPool.getLocalItemById(data.previousPlaceholderId) : elementPool.getLocalItemById(getCombinedId(data));\n                if (item) {\n                    // Update existing items in the pool\n                    // TODO-R[SHARED-5159]: Diff old/new data with deep object equality to check if an update is needed\n                    item._update(data); // TODO-R[SHARED-4970]: Ensure this updates the placeholderId to the real id in the Updater\n                } else {\n                    // Create new items in the pool\n                    // TODO-R[SHARED-4970]: Consider whether placeholder IDs will ever need to be considered here.\n                    // I believe that if the change is always coming from the server, there won't be any placeholder IDs.\n                    // But we need to analyze each use case of updateChildren() to be sure.\n                    this._elementUpdater.updateRemoteItem(session, data);\n                }\n            });\n        };\n        const removeItems = () => {\n            // 1. Get a set of IDs from new data\n            const currentDataIds = new Set(newElementsData.map(data => data.id));\n            // 2. Find the models that are not included in the updated set\n            const removedItems = oldElementsData.filter(data => !currentDataIds.has(data.id)); // May include some that had placeholder IDs\n            // 3. Remove those models from the pool\n            removedItems.forEach(data => {\n                const item = elementPool.getLocalItemById(getCombinedId(data)); // Should not return an item if using its old placeholder id\n                if (item) {\n                    session.queueDiscardedItem(item);\n                }\n                // Note: It is sufficient to call queueDiscardedItem and not elementPool.removeLocalItem(item) because\n                // the item should not be updated in upsertItems() as there should be no overlap between the removedItems and newElementsData.\n            });\n        };\n\n        upsertItems();\n        removeItems();\n        session.commit();\n    }\n\n    /**\n     * @internal\n     * @package -- for use in SAM.js only\n     */\n    get _driver() {\n        return this._apiRoot.driver;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\nimport type { IItemLoader, ILoadedPage } from '../../core/ItemLoader';\nimport type ItemPool from '../../core/ItemPool';\nimport type { ISAMCorePrivate } from '../../indexPrivate';\nimport type { ElementSourceConfig } from '../../library-contents/models/ElementSource';\nimport type { ElementPoolId } from './Element';\nimport type Element from './Element';\nimport { ElementUpdater } from './Element';\nimport type Driver from '../../library-contents/drivers/Driver';\nimport type { ElementSort } from '../../library-contents/drivers/Driver';\nimport type Library from '../../libraries/Library';\nimport type { IItemLoaderOptions } from '../../core/ItemLoader';\nimport type ElementOrder from '../../library-contents/models/ElementOrder';\nimport type { ILoadNextPage } from '../../core/ItemLoader';\nimport type { ElementsResponse } from '@sam-js-src/library-contents/drivers/CloudDriver/utils/melvilleModelMappers';\nimport { mapResponseToElementData } from '../../library-contents/drivers/CloudDriver/utils/melvilleModelMappers';\n\n\nfunction ElementOrderToElementSort(order?: ElementOrder): ElementSort | undefined {\n    if (!order) {\n        return undefined;\n    }\n\n    const sortField = order.field === 'name' ? order.field : 'modifiedDate';\n    return {\n        field: sortField,\n        direction: order.direction\n    };\n}\n\nexport default class ElementListLoader implements IItemLoader<ElementSourceConfig> {\n    constructor(\n        private _core: ISAMCorePrivate,\n        private _elementPool: ItemPool<Element, ElementPoolId>,\n        private _driver: Driver,\n        private _library: Library\n    ) {}\n\n\n    public async loadPage(options?: IItemLoaderOptions<ElementSourceConfig>) {\n        return this._loadPage(options);\n    }\n\n    private async _loadPage(options?: IItemLoaderOptions<ElementSourceConfig>, start: number = 0): Promise<ILoadedPage<ElementSourceConfig>> {\n        const response = await this._driver.getElementsPage(this._library, start, options?.loadOptions?.limit, ElementOrderToElementSort(options?.order), this._library.etag);\n\n        const latency = this._core._environment.getValue('USS_LIST_UPDATE_LATENCY');\n        const mostRecentValidMutation = Date.now() - latency;\n\n        const items = await this._updatePoolFromPage(response, mostRecentValidMutation);\n\n        return {\n            items,\n            total: response.total_count,\n            mostRecentValidMutation,\n            loadNextPage: this._nextPageLinkFromResponse(response)\n        };\n    }\n\n    private async _updatePoolFromPage(response: ElementsResponse, mostRecentValidMutation: number): Promise<Element[]> {\n        const elements = response.elements.map(element => {\n            const data = mapResponseToElementData(element);\n\n            // Melville may not always include the library asset id, but we always know it. This data is required by the Element, so we add it in.\n            data.libraryAssetId = this._library.id;\n            return data;\n        });\n\n        const session = this._elementPool.createLoaderUpdateSession<Element>(mostRecentValidMutation);\n        const items = ElementUpdater.updateRemoteItems(session, elements);\n        session.commit();\n\n        return items;\n    }\n\n    private _nextPageLinkFromResponse(response: ElementsResponse):  ILoadNextPage<ElementSourceConfig> | undefined {\n        const nextStart = response._page?.next;\n        if (!nextStart) {\n            return undefined;\n        }\n        return (options) => this._loadPage(options, nextStart);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type Element from './Element';\nimport type { IImplicitFilter } from '../../core/ItemFilter';\n\nexport interface IImplicitCustomModelFilterOptions {\n    libraryId?: string,\n}\n\nexport default class ImplicitElementFilter implements IImplicitFilter<Element> {\n    private readonly _libraryId?: string;\n\n    constructor(options: Partial<IImplicitCustomModelFilterOptions> = {}) {\n        this._libraryId = options.libraryId;\n    }\n\n    matches(item: Element) {\n        return !this._libraryId || this._libraryId === item.library.id;\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n// CCLibs imports using relative paths:\nimport Store from './Store';\n\n// SAM imports using aliases (since this module is symlinked):\nimport type { ISAMObject } from '../../core/ISAMObject';\nimport type { Action } from './Action';\nimport LibraryError from '../errors/LibraryError';\nimport type Element from './Element';\nimport type { ElementPoolId } from './Element';\nimport ItemSource from '../../core/ItemSource';\n\nimport type { ElementSource, ElementSourceConfig } from '../../library-contents/models/ElementSource';\nimport ElementListLoader from '../../library-contents/models/ElementListLoader';\nimport ImplicitElementFilter from '../../library-contents/models/ImplicitElementFilter';\nimport type { CombinedId } from './Element';\nimport type { ItemId } from '../../core/ItemBase';\nimport { SAMError, SAMErrorCode } from '../../core/SAMError';\nimport memoize from '../../core/decorators/memoize';\n\n/**\n * Manager for LibraryContents (Elements, Groups, etc.) which exposes public APIs for fetching elements and groups.\n * This class can be thought of like an ElementContext, except that it has the additional responsibility of managing state.\n * Inherits from Store, which holds the data and updates the state for the library's contents.\n */\nexport default class LibraryContents extends Store implements ISAMObject {\n\n    // async _load() - When there's a change notification, reloads all elements, groups, and applies update\n\n    /**\n     * Returns the ElementSource which will return a list of the user's elements.\n     * @example\n     * const libraryContents = await library.getLibraryContents();\n     * const order = new ElementOrder('ascending', 'modified');\n     * const elementList = libraryContents.elementsSource.getList(order, undefined, loadOptions);\n     * await waitForListLoad(elementList);\n     * Note: loadOptions.limit will be ignored on public libraries, which are not currently paginated.\n     * Other Note: public libraries aren't yet supported\n     * https://jira.corp.adobe.com/browse/SHARED-5316\n     */\n    @memoize\n    get elementsSource(): ElementSource {\n        if (this.library._isPublicLink_NoLazyLoad) {\n            throw SAMError.create(SAMErrorCode.UNSUPPORTED, 'elements source is not currently supported for public libraries');\n        }\n\n        return new ItemSource<ElementSourceConfig, ElementPoolId>(\n            this._elementPool,\n            [\n                new ElementListLoader(\n                    this._core,\n                    this._elementPool,\n                    this._driver,\n                    this.library\n                ),\n            ],\n            new ImplicitElementFilter({ libraryId: this.library.id })\n        );\n    }\n\n    // groupsSource\t - Returns GroupSource for fetching group lists\n\n    // getElementById(id) - Loads a single element. (Note: For the time being, elements will only be kept up to date by ONS notifications when all the elements are loaded in a library.)\n\n    public async getElementById(elementId: ItemId): Promise<Element> {\n        const combinedId: CombinedId = `${this.library.id}#${elementId}`;\n        let element = this._elementPool.getLocalItemById(combinedId);\n\n        if (!element) {\n            const elementData = await this._driver.getElement(this.library, elementId);\n            elementData.libraryAssetId = elementData.libraryAssetId || this.library.id; // Our models require this data, though Melville may not always supply it.\n            this._update({ elements: [ elementData ] }, true);\n            element = this._elementPool.getLocalItemById(combinedId);\n        }\n\n        if (!element) {\n            throw new LibraryError('INVALID_PARAMETER', 'Need to pass a valid element ID');\n        }\n\n        return Promise.resolve(element);\n    }\n\n    /* Store API Overrides */\n\n    /**\n     * @internal\n     * @package -- for use in SAM.js only\n     */\n    // TODO: Move this into Store._actionDispatch\n    _actionDispatch(action: Action) {\n        if (!action.library) {\n            action.library = this.library;\n        }\n        if (!action.libraryContents) {\n            action.libraryContents = this;\n        }\n\n        super._actionDispatch(action);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2020 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * Group\n * @packageDocumentation\n * @module Group\n */\n\nimport type { GroupData } from './data/GroupData';\n// @ts-expect-error R-TODO\nimport type Library from './Library';\nimport type Element from './Element';\nimport type { Action, ActionName } from './Action';\n\nimport observable from '../utils/observable';\nimport { requiresWrite } from './utils/AccessUtils';\nimport { createPlaceholderId } from './utils';\nimport PublishedModel from './PublishedModel';\nimport { mapAttributesToArray } from './utils/AttributeUtils';\nimport type { Optional } from '../types';\n\nexport default class Group extends PublishedModel<GroupData> {\n    isGroup = true;\n\n    private _isDeletedLocally = false;\n    protected _updateAction: ActionName = 'updateGroup';\n\n    // TODO-R: Temporarily avoids breaking code. When updating this file to use ItemUpdater Pattern, remove this.\n    private _data: GroupData = {} as GroupData;\n    get data(): GroupData {\n        return this._data;\n    }\n\n    get classifierName(): string {\n        return this.data.classifier;\n    }\n\n    @observable\n    @requiresWrite\n    get name(): string {\n        return this.data.name;\n    }\n\n    set name(name: string) {\n        this._actionDispatch({\n            name: 'updateGroup',\n            type: 'update',\n            data: { name }\n        });\n    }\n\n    @observable\n    @requiresWrite\n    get order(): string {\n        return this.data.order;\n    }\n\n    set order(order: string) {\n        this._actionDispatch({\n            name: 'updateGroup',\n            type: 'update',\n            data: { order }\n        });\n    }\n\n    @observable\n    get modified(): number {\n        return this.data.modifiedDate as number;\n    }\n\n    @observable\n    get modifiedBy(): string {\n        return this.data.modifiedBy as string;\n    }\n\n    @observable\n    get modifiedContext(): any {\n        return this.data.modifiedContext;\n    }\n\n    @observable\n    get wasModifiedLocally(): boolean {\n        return this.data.modifiedLocally as boolean;\n    }\n\n    @observable\n    get created(): number {\n        return this.data.createdDate as number;\n    }\n\n    @observable\n    get createdBy(): string {\n        return this.data.createdBy as string;\n    }\n\n    @observable\n    get createdContext(): any {\n        return this.data.createdContext;\n    }\n\n    @observable\n    get wasCreatedLocally(): boolean {\n        return this.data.createdLocally as boolean;\n    }\n\n    @observable\n    getValue(namespace: string, key: string): any {\n        return this.data.customData?.[`${namespace}#${key}`];\n    }\n\n    @observable\n    getValues(): { namespace: string; key: string; value: any }[] {\n        return mapAttributesToArray(this.data.customData as { [s: string]: any });\n    }\n\n    @observable\n    get children() {\n        // @ts-expect-error // TODO: Fix this\n        return this.library.getGroups(this.classifierName).filter(group => group.parent && group.parent.id === this.id);\n    }\n\n    @observable\n    getFilteredChildren(predicate: (group: Group) => boolean) {\n        return this.children.filter(predicate);\n    }\n\n    @observable\n    get elements(): Element[] {\n        const elements: Element[] = [];\n        const processElement = (element: Element) =>\n            element.getOrderInGroup(this) !== undefined && elements.push(element);\n        this.library.elements.forEach(processElement);\n        this.library.documentationElements.forEach(processElement);\n        return elements;\n    }\n\n    /**\n     * Returns true if the group has no child groups and no elements associated\n     */\n    @observable\n    isEmpty(): boolean {\n        return this.elements.length === 0 && this.children.length === 0;\n    }\n\n    @requiresWrite\n    setValue(namespace: string, key: string, value: any, _isMetadata?: boolean): void {\n        this._actionDispatch({\n            name: 'updateGroup',\n            type: 'update',\n            data: {\n                customData: {\n                    ...this.data.customData,\n                    [`${namespace}#${key}`]: value\n                }\n            }\n        });\n    }\n\n    @requiresWrite\n    removeValue(namespace: string, key: string, isMetadata?: boolean): void {\n        this.setValue(namespace, key, null, isMetadata);\n    }\n\n    /**\n     * @deprecated\n     */\n    @observable\n    get isDeletedLocally(): boolean {\n        return this._isDeletedLocally;\n    }\n\n    set isDeletedLocally(isDeletedLocally) {\n        this._isDeletedLocally = isDeletedLocally;\n        this.emit('change');\n    }\n\n    get library(): Library {\n        return this._parent as Library;\n    }\n\n    @observable\n    getLocalizedName(locale: string = 'en_US'): string {\n        return this.data.localizedNames?.[locale] as string;\n    }\n\n    @observable\n    getLocalizedNames(): { [s: string]: string } {\n        return this.data.localizedNames || {};\n    }\n\n    @requiresWrite\n    setLocalizedName(locale: string, name: string): void {\n        return this._actionDispatch({\n            name: 'updateGroup',\n            type: 'update',\n            data: {\n                localizedNames: {\n                    ...this.data.localizedNames,\n                    [locale]: name\n                }\n            }\n        });\n    }\n\n    get parent(): Group | undefined {\n        return this.library.getGroupById(this._data.parentId as string);\n    }\n\n    @requiresWrite\n    @observable\n    set parent(group: Group | undefined) {\n        this._actionDispatch({\n            name: 'updateGroup',\n            type: 'update',\n            data: { parentId: group?.id || null }\n        });\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _createChild(name: string, order: string) {\n        const id = createPlaceholderId();\n        this._actionDispatch({\n            name: 'createGroup',\n            type: 'insert',\n            data: { id, name, order, classifier: this.classifierName, parentId: this.id },\n            path: '$.groups'\n        });\n\n        return this.library.getGroupById(id);\n    }\n\n    /**\n     * @package -- only for use in SAM.js\n     */\n    _actionDispatch(action: Optional<Action, 'path'>): void {\n        if (!action.path) {\n            action.path = `$.groups[?(@.id == \"${this.id}\")]`;\n        }\n\n        this.library._actionDispatch(action);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport type { Gradient } from '../../index';\nimport Model from './Model';\nimport observable from '../utils/observable';\n\nexport type GradientData = {\n    type: Gradient['type'];\n    angle: Gradient['angle'];\n    stops: Gradient['stops'];\n};\n\nexport type TeamData = {\n    name: string;\n    id: string;\n    owner: {\n        type: 'org' | 'user';\n        id: string;\n    };\n    ownerName: string;\n    isReadOnly?: boolean;\n    isWritable?: boolean;\n    gradient?: GradientData;\n};\n\nexport default class Team extends Model<TeamData> {\n\n    // TODO-R: Temporarily avoids breaking code. When updating this file to use ItemUpdater Pattern, remove this.\n    private _data: TeamData = {} as TeamData;\n    get data(): TeamData {\n        return this._data;\n    }\n\n    get name() {\n        return this._data.name;\n    }\n\n    get owner() {\n        return this._data.owner;\n    }\n\n    get ownerName() {\n        return this._data.ownerName;\n    }\n\n    get isReadOnly() {\n        return this._data.isReadOnly;\n    }\n\n    get isWritable() {\n        return this._data.isWritable;\n    }\n\n    private async _refreshGradient() {\n        // Don't refetch the gradient.\n        if (this._data.gradient) {\n            return this._data.gradient;\n        }\n        const gradient = await this._apiRoot.driver.getProjectGradient(this);\n        this._update({ gradient });\n    }\n\n    @observable\n    get gradientData() {\n        this._refreshGradient();\n        return this._data.gradient;\n    }\n}\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n  extendStatics = Object.setPrototypeOf ||\n      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n  return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n  if (typeof b !== \"function\" && b !== null)\n      throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n  extendStatics(d, b);\n  function __() { this.constructor = d; }\n  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n  __assign = Object.assign || function __assign(t) {\n      for (var s, i = 1, n = arguments.length; i < n; i++) {\n          s = arguments[i];\n          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n      }\n      return t;\n  }\n  return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n  var t = {};\n  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n      t[p] = s[p];\n  if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n      for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n              t[p[i]] = s[p[i]];\n      }\n  return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n  if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n  return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n  return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n  function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n  var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n  var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n  var _, done = false;\n  for (var i = decorators.length - 1; i >= 0; i--) {\n      var context = {};\n      for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n      for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n      context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n      var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n      if (kind === \"accessor\") {\n          if (result === void 0) continue;\n          if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n          if (_ = accept(result.get)) descriptor.get = _;\n          if (_ = accept(result.set)) descriptor.set = _;\n          if (_ = accept(result.init)) initializers.unshift(_);\n      }\n      else if (_ = accept(result)) {\n          if (kind === \"field\") initializers.unshift(_);\n          else descriptor[key] = _;\n      }\n  }\n  if (target) Object.defineProperty(target, contextIn.name, descriptor);\n  done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n  var useValue = arguments.length > 2;\n  for (var i = 0; i < initializers.length; i++) {\n      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n  }\n  return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n  return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n  if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n  return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n  if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n  return new (P || (P = Promise))(function (resolve, reject) {\n      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n      function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n      step((generator = generator.apply(thisArg, _arguments || [])).next());\n  });\n}\n\nexport function __generator(thisArg, body) {\n  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n  return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n  function verb(n) { return function (v) { return step([n, v]); }; }\n  function step(op) {\n      if (f) throw new TypeError(\"Generator is already executing.\");\n      while (g && (g = 0, op[0] && (_ = 0)), _) try {\n          if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n          if (y = 0, t) op = [op[0] & 2, t.value];\n          switch (op[0]) {\n              case 0: case 1: t = op; break;\n              case 4: _.label++; return { value: op[1], done: false };\n              case 5: _.label++; y = op[1]; op = [0]; continue;\n              case 7: op = _.ops.pop(); _.trys.pop(); continue;\n              default:\n                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                  if (t[2]) _.ops.pop();\n                  _.trys.pop(); continue;\n          }\n          op = body.call(thisArg, _);\n      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n  }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  var desc = Object.getOwnPropertyDescriptor(m, k);\n  if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n  }\n  Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n  for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n  var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n  if (m) return m.call(o);\n  if (o && typeof o.length === \"number\") return {\n      next: function () {\n          if (o && i >= o.length) o = void 0;\n          return { value: o && o[i++], done: !o };\n      }\n  };\n  throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n  var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n  if (!m) return o;\n  var i = m.call(o), r, ar = [], e;\n  try {\n      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n  }\n  catch (error) { e = { error: error }; }\n  finally {\n      try {\n          if (r && !r.done && (m = i[\"return\"])) m.call(i);\n      }\n      finally { if (e) throw e.error; }\n  }\n  return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n  for (var ar = [], i = 0; i < arguments.length; i++)\n      ar = ar.concat(__read(arguments[i]));\n  return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n  for (var r = Array(s), k = 0, i = 0; i < il; i++)\n      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n          r[k] = a[j];\n  return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n      if (ar || !(i in from)) {\n          if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n          ar[i] = from[i];\n      }\n  }\n  return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n  return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var g = generator.apply(thisArg, _arguments || []), i, q = [];\n  return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n  function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n  function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n  function fulfill(value) { resume(\"next\", value); }\n  function reject(value) { resume(\"throw\", value); }\n  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n  var i, p;\n  return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var m = o[Symbol.asyncIterator], i;\n  return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n  if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n  return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n  Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n  o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n  ownKeys = Object.getOwnPropertyNames || function (o) {\n    var ar = [];\n    for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n    return ar;\n  };\n  return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n  if (mod && mod.__esModule) return mod;\n  var result = {};\n  if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n  __setModuleDefault(result, mod);\n  return result;\n}\n\nexport function __importDefault(mod) {\n  return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n  return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n  if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n  return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n  if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n  return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n  if (value !== null && value !== void 0) {\n    if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n    var dispose, inner;\n    if (async) {\n      if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n      dispose = value[Symbol.asyncDispose];\n    }\n    if (dispose === void 0) {\n      if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n      dispose = value[Symbol.dispose];\n      if (async) inner = dispose;\n    }\n    if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n    if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n    env.stack.push({ value: value, dispose: dispose, async: async });\n  }\n  else if (async) {\n    env.stack.push({ async: true });\n  }\n  return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n  var e = new Error(message);\n  return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n  function fail(e) {\n    env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n    env.hasError = true;\n  }\n  var r, s = 0;\n  function next() {\n    while (r = env.stack.pop()) {\n      try {\n        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n        if (r.dispose) {\n          var result = r.dispose.call(r.value);\n          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n        }\n        else s |= 1;\n      }\n      catch (e) {\n        fail(e);\n      }\n    }\n    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n    if (env.hasError) throw env.error;\n  }\n  return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n  if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n      return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n          return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n      });\n  }\n  return path;\n}\n\nexport default {\n  __extends,\n  __assign,\n  __rest,\n  __decorate,\n  __param,\n  __esDecorate,\n  __runInitializers,\n  __propKey,\n  __setFunctionName,\n  __metadata,\n  __awaiter,\n  __generator,\n  __createBinding,\n  __exportStar,\n  __values,\n  __read,\n  __spread,\n  __spreadArrays,\n  __spreadArray,\n  __await,\n  __asyncGenerator,\n  __asyncDelegator,\n  __asyncValues,\n  __makeTemplateObject,\n  __importStar,\n  __importDefault,\n  __classPrivateFieldGet,\n  __classPrivateFieldSet,\n  __classPrivateFieldIn,\n  __addDisposableResource,\n  __disposeResources,\n  __rewriteRelativeImportExtension,\n};\n","//\n// Main\n//\nexport function memoize(fn, options) {\n    var cache = options && options.cache ? options.cache : cacheDefault;\n    var serializer = options && options.serializer ? options.serializer : serializerDefault;\n    var strategy = options && options.strategy ? options.strategy : strategyDefault;\n    return strategy(fn, {\n        cache: cache,\n        serializer: serializer,\n    });\n}\n//\n// Strategy\n//\nfunction isPrimitive(value) {\n    return (value == null || typeof value === 'number' || typeof value === 'boolean'); // || typeof value === \"string\" 'unsafe' primitive for our needs\n}\nfunction monadic(fn, cache, serializer, arg) {\n    var cacheKey = isPrimitive(arg) ? arg : serializer(arg);\n    var computedValue = cache.get(cacheKey);\n    if (typeof computedValue === 'undefined') {\n        computedValue = fn.call(this, arg);\n        cache.set(cacheKey, computedValue);\n    }\n    return computedValue;\n}\nfunction variadic(fn, cache, serializer) {\n    var args = Array.prototype.slice.call(arguments, 3);\n    var cacheKey = serializer(args);\n    var computedValue = cache.get(cacheKey);\n    if (typeof computedValue === 'undefined') {\n        computedValue = fn.apply(this, args);\n        cache.set(cacheKey, computedValue);\n    }\n    return computedValue;\n}\nfunction assemble(fn, context, strategy, cache, serialize) {\n    return strategy.bind(context, fn, cache, serialize);\n}\nfunction strategyDefault(fn, options) {\n    var strategy = fn.length === 1 ? monadic : variadic;\n    return assemble(fn, this, strategy, options.cache.create(), options.serializer);\n}\nfunction strategyVariadic(fn, options) {\n    return assemble(fn, this, variadic, options.cache.create(), options.serializer);\n}\nfunction strategyMonadic(fn, options) {\n    return assemble(fn, this, monadic, options.cache.create(), options.serializer);\n}\n//\n// Serializer\n//\nvar serializerDefault = function () {\n    return JSON.stringify(arguments);\n};\n//\n// Cache\n//\nfunction ObjectWithoutPrototypeCache() {\n    this.cache = Object.create(null);\n}\nObjectWithoutPrototypeCache.prototype.get = function (key) {\n    return this.cache[key];\n};\nObjectWithoutPrototypeCache.prototype.set = function (key, value) {\n    this.cache[key] = value;\n};\nvar cacheDefault = {\n    create: function create() {\n        // @ts-ignore\n        return new ObjectWithoutPrototypeCache();\n    },\n};\nexport var strategies = {\n    variadic: strategyVariadic,\n    monadic: strategyMonadic,\n};\n//# sourceMappingURL=index.js.map","export var ErrorKind;\n(function (ErrorKind) {\n    /** Argument is unclosed (e.g. `{0`) */\n    ErrorKind[ErrorKind[\"EXPECT_ARGUMENT_CLOSING_BRACE\"] = 1] = \"EXPECT_ARGUMENT_CLOSING_BRACE\";\n    /** Argument is empty (e.g. `{}`). */\n    ErrorKind[ErrorKind[\"EMPTY_ARGUMENT\"] = 2] = \"EMPTY_ARGUMENT\";\n    /** Argument is malformed (e.g. `{foo!}``) */\n    ErrorKind[ErrorKind[\"MALFORMED_ARGUMENT\"] = 3] = \"MALFORMED_ARGUMENT\";\n    /** Expect an argument type (e.g. `{foo,}`) */\n    ErrorKind[ErrorKind[\"EXPECT_ARGUMENT_TYPE\"] = 4] = \"EXPECT_ARGUMENT_TYPE\";\n    /** Unsupported argument type (e.g. `{foo,foo}`) */\n    ErrorKind[ErrorKind[\"INVALID_ARGUMENT_TYPE\"] = 5] = \"INVALID_ARGUMENT_TYPE\";\n    /** Expect an argument style (e.g. `{foo, number, }`) */\n    ErrorKind[ErrorKind[\"EXPECT_ARGUMENT_STYLE\"] = 6] = \"EXPECT_ARGUMENT_STYLE\";\n    /** The number skeleton is invalid. */\n    ErrorKind[ErrorKind[\"INVALID_NUMBER_SKELETON\"] = 7] = \"INVALID_NUMBER_SKELETON\";\n    /** The date time skeleton is invalid. */\n    ErrorKind[ErrorKind[\"INVALID_DATE_TIME_SKELETON\"] = 8] = \"INVALID_DATE_TIME_SKELETON\";\n    /** Exepct a number skeleton following the `::` (e.g. `{foo, number, ::}`) */\n    ErrorKind[ErrorKind[\"EXPECT_NUMBER_SKELETON\"] = 9] = \"EXPECT_NUMBER_SKELETON\";\n    /** Exepct a date time skeleton following the `::` (e.g. `{foo, date, ::}`) */\n    ErrorKind[ErrorKind[\"EXPECT_DATE_TIME_SKELETON\"] = 10] = \"EXPECT_DATE_TIME_SKELETON\";\n    /** Unmatched apostrophes in the argument style (e.g. `{foo, number, 'test`) */\n    ErrorKind[ErrorKind[\"UNCLOSED_QUOTE_IN_ARGUMENT_STYLE\"] = 11] = \"UNCLOSED_QUOTE_IN_ARGUMENT_STYLE\";\n    /** Missing select argument options (e.g. `{foo, select}`) */\n    ErrorKind[ErrorKind[\"EXPECT_SELECT_ARGUMENT_OPTIONS\"] = 12] = \"EXPECT_SELECT_ARGUMENT_OPTIONS\";\n    /** Expecting an offset value in `plural` or `selectordinal` argument (e.g `{foo, plural, offset}`) */\n    ErrorKind[ErrorKind[\"EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE\"] = 13] = \"EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE\";\n    /** Offset value in `plural` or `selectordinal` is invalid (e.g. `{foo, plural, offset: x}`) */\n    ErrorKind[ErrorKind[\"INVALID_PLURAL_ARGUMENT_OFFSET_VALUE\"] = 14] = \"INVALID_PLURAL_ARGUMENT_OFFSET_VALUE\";\n    /** Expecting a selector in `select` argument (e.g `{foo, select}`) */\n    ErrorKind[ErrorKind[\"EXPECT_SELECT_ARGUMENT_SELECTOR\"] = 15] = \"EXPECT_SELECT_ARGUMENT_SELECTOR\";\n    /** Expecting a selector in `plural` or `selectordinal` argument (e.g `{foo, plural}`) */\n    ErrorKind[ErrorKind[\"EXPECT_PLURAL_ARGUMENT_SELECTOR\"] = 16] = \"EXPECT_PLURAL_ARGUMENT_SELECTOR\";\n    /** Expecting a message fragment after the `select` selector (e.g. `{foo, select, apple}`) */\n    ErrorKind[ErrorKind[\"EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT\"] = 17] = \"EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT\";\n    /**\n     * Expecting a message fragment after the `plural` or `selectordinal` selector\n     * (e.g. `{foo, plural, one}`)\n     */\n    ErrorKind[ErrorKind[\"EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT\"] = 18] = \"EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT\";\n    /** Selector in `plural` or `selectordinal` is malformed (e.g. `{foo, plural, =x {#}}`) */\n    ErrorKind[ErrorKind[\"INVALID_PLURAL_ARGUMENT_SELECTOR\"] = 19] = \"INVALID_PLURAL_ARGUMENT_SELECTOR\";\n    /**\n     * Duplicate selectors in `plural` or `selectordinal` argument.\n     * (e.g. {foo, plural, one {#} one {#}})\n     */\n    ErrorKind[ErrorKind[\"DUPLICATE_PLURAL_ARGUMENT_SELECTOR\"] = 20] = \"DUPLICATE_PLURAL_ARGUMENT_SELECTOR\";\n    /** Duplicate selectors in `select` argument.\n     * (e.g. {foo, select, apple {apple} apple {apple}})\n     */\n    ErrorKind[ErrorKind[\"DUPLICATE_SELECT_ARGUMENT_SELECTOR\"] = 21] = \"DUPLICATE_SELECT_ARGUMENT_SELECTOR\";\n    /** Plural or select argument option must have `other` clause. */\n    ErrorKind[ErrorKind[\"MISSING_OTHER_CLAUSE\"] = 22] = \"MISSING_OTHER_CLAUSE\";\n    /** The tag is malformed. (e.g. `<bold!>foo</bold!>) */\n    ErrorKind[ErrorKind[\"INVALID_TAG\"] = 23] = \"INVALID_TAG\";\n    /** The tag name is invalid. (e.g. `<123>foo</123>`) */\n    ErrorKind[ErrorKind[\"INVALID_TAG_NAME\"] = 25] = \"INVALID_TAG_NAME\";\n    /** The closing tag does not match the opening tag. (e.g. `<bold>foo</italic>`) */\n    ErrorKind[ErrorKind[\"UNMATCHED_CLOSING_TAG\"] = 26] = \"UNMATCHED_CLOSING_TAG\";\n    /** The opening tag has unmatched closing tag. (e.g. `<bold>foo`) */\n    ErrorKind[ErrorKind[\"UNCLOSED_TAG\"] = 27] = \"UNCLOSED_TAG\";\n})(ErrorKind || (ErrorKind = {}));\n","export var TYPE;\n(function (TYPE) {\n    /**\n     * Raw text\n     */\n    TYPE[TYPE[\"literal\"] = 0] = \"literal\";\n    /**\n     * Variable w/o any format, e.g `var` in `this is a {var}`\n     */\n    TYPE[TYPE[\"argument\"] = 1] = \"argument\";\n    /**\n     * Variable w/ number format\n     */\n    TYPE[TYPE[\"number\"] = 2] = \"number\";\n    /**\n     * Variable w/ date format\n     */\n    TYPE[TYPE[\"date\"] = 3] = \"date\";\n    /**\n     * Variable w/ time format\n     */\n    TYPE[TYPE[\"time\"] = 4] = \"time\";\n    /**\n     * Variable w/ select format\n     */\n    TYPE[TYPE[\"select\"] = 5] = \"select\";\n    /**\n     * Variable w/ plural format\n     */\n    TYPE[TYPE[\"plural\"] = 6] = \"plural\";\n    /**\n     * Only possible within plural argument.\n     * This is the `#` symbol that will be substituted with the count.\n     */\n    TYPE[TYPE[\"pound\"] = 7] = \"pound\";\n    /**\n     * XML-like tag\n     */\n    TYPE[TYPE[\"tag\"] = 8] = \"tag\";\n})(TYPE || (TYPE = {}));\nexport var SKELETON_TYPE;\n(function (SKELETON_TYPE) {\n    SKELETON_TYPE[SKELETON_TYPE[\"number\"] = 0] = \"number\";\n    SKELETON_TYPE[SKELETON_TYPE[\"dateTime\"] = 1] = \"dateTime\";\n})(SKELETON_TYPE || (SKELETON_TYPE = {}));\n/**\n * Type Guards\n */\nexport function isLiteralElement(el) {\n    return el.type === TYPE.literal;\n}\nexport function isArgumentElement(el) {\n    return el.type === TYPE.argument;\n}\nexport function isNumberElement(el) {\n    return el.type === TYPE.number;\n}\nexport function isDateElement(el) {\n    return el.type === TYPE.date;\n}\nexport function isTimeElement(el) {\n    return el.type === TYPE.time;\n}\nexport function isSelectElement(el) {\n    return el.type === TYPE.select;\n}\nexport function isPluralElement(el) {\n    return el.type === TYPE.plural;\n}\nexport function isPoundElement(el) {\n    return el.type === TYPE.pound;\n}\nexport function isTagElement(el) {\n    return el.type === TYPE.tag;\n}\nexport function isNumberSkeleton(el) {\n    return !!(el && typeof el === 'object' && el.type === SKELETON_TYPE.number);\n}\nexport function isDateTimeSkeleton(el) {\n    return !!(el && typeof el === 'object' && el.type === SKELETON_TYPE.dateTime);\n}\nexport function createLiteralElement(value) {\n    return {\n        type: TYPE.literal,\n        value: value,\n    };\n}\nexport function createNumberElement(value, style) {\n    return {\n        type: TYPE.number,\n        value: value,\n        style: style,\n    };\n}\n","// @generated from regex-gen.ts\nexport var SPACE_SEPARATOR_REGEX = /[ \\xA0\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]/;\nexport var WHITE_SPACE_REGEX = /[\\t-\\r \\x85\\u200E\\u200F\\u2028\\u2029]/;\n","/**\n * https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * Credit: https://github.com/caridy/intl-datetimeformat-pattern/blob/master/index.js\n * with some tweaks\n */\nvar DATE_TIME_REGEX = /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvVxX]{1,4})(?=([^']*'[^']*')*[^']*$)/g;\n/**\n * Parse Date time skeleton into Intl.DateTimeFormatOptions\n * Ref: https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * @public\n * @param skeleton skeleton string\n */\nexport function parseDateTimeSkeleton(skeleton) {\n    var result = {};\n    skeleton.replace(DATE_TIME_REGEX, function (match) {\n        var len = match.length;\n        switch (match[0]) {\n            // Era\n            case 'G':\n                result.era = len === 4 ? 'long' : len === 5 ? 'narrow' : 'short';\n                break;\n            // Year\n            case 'y':\n                result.year = len === 2 ? '2-digit' : 'numeric';\n                break;\n            case 'Y':\n            case 'u':\n            case 'U':\n            case 'r':\n                throw new RangeError('`Y/u/U/r` (year) patterns are not supported, use `y` instead');\n            // Quarter\n            case 'q':\n            case 'Q':\n                throw new RangeError('`q/Q` (quarter) patterns are not supported');\n            // Month\n            case 'M':\n            case 'L':\n                result.month = ['numeric', '2-digit', 'short', 'long', 'narrow'][len - 1];\n                break;\n            // Week\n            case 'w':\n            case 'W':\n                throw new RangeError('`w/W` (week) patterns are not supported');\n            case 'd':\n                result.day = ['numeric', '2-digit'][len - 1];\n                break;\n            case 'D':\n            case 'F':\n            case 'g':\n                throw new RangeError('`D/F/g` (day) patterns are not supported, use `d` instead');\n            // Weekday\n            case 'E':\n                result.weekday = len === 4 ? 'long' : len === 5 ? 'narrow' : 'short';\n                break;\n            case 'e':\n                if (len < 4) {\n                    throw new RangeError('`e..eee` (weekday) patterns are not supported');\n                }\n                result.weekday = ['short', 'long', 'narrow', 'short'][len - 4];\n                break;\n            case 'c':\n                if (len < 4) {\n                    throw new RangeError('`c..ccc` (weekday) patterns are not supported');\n                }\n                result.weekday = ['short', 'long', 'narrow', 'short'][len - 4];\n                break;\n            // Period\n            case 'a': // AM, PM\n                result.hour12 = true;\n                break;\n            case 'b': // am, pm, noon, midnight\n            case 'B': // flexible day periods\n                throw new RangeError('`b/B` (period) patterns are not supported, use `a` instead');\n            // Hour\n            case 'h':\n                result.hourCycle = 'h12';\n                result.hour = ['numeric', '2-digit'][len - 1];\n                break;\n            case 'H':\n                result.hourCycle = 'h23';\n                result.hour = ['numeric', '2-digit'][len - 1];\n                break;\n            case 'K':\n                result.hourCycle = 'h11';\n                result.hour = ['numeric', '2-digit'][len - 1];\n                break;\n            case 'k':\n                result.hourCycle = 'h24';\n                result.hour = ['numeric', '2-digit'][len - 1];\n                break;\n            case 'j':\n            case 'J':\n            case 'C':\n                throw new RangeError('`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead');\n            // Minute\n            case 'm':\n                result.minute = ['numeric', '2-digit'][len - 1];\n                break;\n            // Second\n            case 's':\n                result.second = ['numeric', '2-digit'][len - 1];\n                break;\n            case 'S':\n            case 'A':\n                throw new RangeError('`S/A` (second) patterns are not supported, use `s` instead');\n            // Zone\n            case 'z': // 1..3, 4: specific non-location format\n                result.timeZoneName = len < 4 ? 'short' : 'long';\n                break;\n            case 'Z': // 1..3, 4, 5: The ISO8601 varios formats\n            case 'O': // 1, 4: milliseconds in day short, long\n            case 'v': // 1, 4: generic non-location format\n            case 'V': // 1, 2, 3, 4: time zone ID or city\n            case 'X': // 1, 2, 3, 4: The ISO8601 varios formats\n            case 'x': // 1, 2, 3, 4: The ISO8601 varios formats\n                throw new RangeError('`Z/O/v/V/X/x` (timeZone) patterns are not supported, use `z` instead');\n        }\n        return '';\n    });\n    return result;\n}\n","// @generated from regex-gen.ts\nexport var WHITE_SPACE_REGEX = /[\\t-\\r \\x85\\u200E\\u200F\\u2028\\u2029]/i;\n","import { __assign } from \"tslib\";\nimport { WHITE_SPACE_REGEX } from './regex.generated';\nexport function parseNumberSkeletonFromString(skeleton) {\n    if (skeleton.length === 0) {\n        throw new Error('Number skeleton cannot be empty');\n    }\n    // Parse the skeleton\n    var stringTokens = skeleton\n        .split(WHITE_SPACE_REGEX)\n        .filter(function (x) { return x.length > 0; });\n    var tokens = [];\n    for (var _i = 0, stringTokens_1 = stringTokens; _i < stringTokens_1.length; _i++) {\n        var stringToken = stringTokens_1[_i];\n        var stemAndOptions = stringToken.split('/');\n        if (stemAndOptions.length === 0) {\n            throw new Error('Invalid number skeleton');\n        }\n        var stem = stemAndOptions[0], options = stemAndOptions.slice(1);\n        for (var _a = 0, options_1 = options; _a < options_1.length; _a++) {\n            var option = options_1[_a];\n            if (option.length === 0) {\n                throw new Error('Invalid number skeleton');\n            }\n        }\n        tokens.push({ stem: stem, options: options });\n    }\n    return tokens;\n}\nfunction icuUnitToEcma(unit) {\n    return unit.replace(/^(.*?)-/, '');\n}\nvar FRACTION_PRECISION_REGEX = /^\\.(?:(0+)(\\*)?|(#+)|(0+)(#+))$/g;\nvar SIGNIFICANT_PRECISION_REGEX = /^(@+)?(\\+|#+)?[rs]?$/g;\nvar INTEGER_WIDTH_REGEX = /(\\*)(0+)|(#+)(0+)|(0+)/g;\nvar CONCISE_INTEGER_WIDTH_REGEX = /^(0+)$/;\nfunction parseSignificantPrecision(str) {\n    var result = {};\n    if (str[str.length - 1] === 'r') {\n        result.roundingPriority = 'morePrecision';\n    }\n    else if (str[str.length - 1] === 's') {\n        result.roundingPriority = 'lessPrecision';\n    }\n    str.replace(SIGNIFICANT_PRECISION_REGEX, function (_, g1, g2) {\n        // @@@ case\n        if (typeof g2 !== 'string') {\n            result.minimumSignificantDigits = g1.length;\n            result.maximumSignificantDigits = g1.length;\n        }\n        // @@@+ case\n        else if (g2 === '+') {\n            result.minimumSignificantDigits = g1.length;\n        }\n        // .### case\n        else if (g1[0] === '#') {\n            result.maximumSignificantDigits = g1.length;\n        }\n        // .@@## or .@@@ case\n        else {\n            result.minimumSignificantDigits = g1.length;\n            result.maximumSignificantDigits =\n                g1.length + (typeof g2 === 'string' ? g2.length : 0);\n        }\n        return '';\n    });\n    return result;\n}\nfunction parseSign(str) {\n    switch (str) {\n        case 'sign-auto':\n            return {\n                signDisplay: 'auto',\n            };\n        case 'sign-accounting':\n        case '()':\n            return {\n                currencySign: 'accounting',\n            };\n        case 'sign-always':\n        case '+!':\n            return {\n                signDisplay: 'always',\n            };\n        case 'sign-accounting-always':\n        case '()!':\n            return {\n                signDisplay: 'always',\n                currencySign: 'accounting',\n            };\n        case 'sign-except-zero':\n        case '+?':\n            return {\n                signDisplay: 'exceptZero',\n            };\n        case 'sign-accounting-except-zero':\n        case '()?':\n            return {\n                signDisplay: 'exceptZero',\n                currencySign: 'accounting',\n            };\n        case 'sign-never':\n        case '+_':\n            return {\n                signDisplay: 'never',\n            };\n    }\n}\nfunction parseConciseScientificAndEngineeringStem(stem) {\n    // Engineering\n    var result;\n    if (stem[0] === 'E' && stem[1] === 'E') {\n        result = {\n            notation: 'engineering',\n        };\n        stem = stem.slice(2);\n    }\n    else if (stem[0] === 'E') {\n        result = {\n            notation: 'scientific',\n        };\n        stem = stem.slice(1);\n    }\n    if (result) {\n        var signDisplay = stem.slice(0, 2);\n        if (signDisplay === '+!') {\n            result.signDisplay = 'always';\n            stem = stem.slice(2);\n        }\n        else if (signDisplay === '+?') {\n            result.signDisplay = 'exceptZero';\n            stem = stem.slice(2);\n        }\n        if (!CONCISE_INTEGER_WIDTH_REGEX.test(stem)) {\n            throw new Error('Malformed concise eng/scientific notation');\n        }\n        result.minimumIntegerDigits = stem.length;\n    }\n    return result;\n}\nfunction parseNotationOptions(opt) {\n    var result = {};\n    var signOpts = parseSign(opt);\n    if (signOpts) {\n        return signOpts;\n    }\n    return result;\n}\n/**\n * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#skeleton-stems-and-options\n */\nexport function parseNumberSkeleton(tokens) {\n    var result = {};\n    for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {\n        var token = tokens_1[_i];\n        switch (token.stem) {\n            case 'percent':\n            case '%':\n                result.style = 'percent';\n                continue;\n            case '%x100':\n                result.style = 'percent';\n                result.scale = 100;\n                continue;\n            case 'currency':\n                result.style = 'currency';\n                result.currency = token.options[0];\n                continue;\n            case 'group-off':\n            case ',_':\n                result.useGrouping = false;\n                continue;\n            case 'precision-integer':\n            case '.':\n                result.maximumFractionDigits = 0;\n                continue;\n            case 'measure-unit':\n            case 'unit':\n                result.style = 'unit';\n                result.unit = icuUnitToEcma(token.options[0]);\n                continue;\n            case 'compact-short':\n            case 'K':\n                result.notation = 'compact';\n                result.compactDisplay = 'short';\n                continue;\n            case 'compact-long':\n            case 'KK':\n                result.notation = 'compact';\n                result.compactDisplay = 'long';\n                continue;\n            case 'scientific':\n                result = __assign(__assign(__assign({}, result), { notation: 'scientific' }), token.options.reduce(function (all, opt) { return (__assign(__assign({}, all), parseNotationOptions(opt))); }, {}));\n                continue;\n            case 'engineering':\n                result = __assign(__assign(__assign({}, result), { notation: 'engineering' }), token.options.reduce(function (all, opt) { return (__assign(__assign({}, all), parseNotationOptions(opt))); }, {}));\n                continue;\n            case 'notation-simple':\n                result.notation = 'standard';\n                continue;\n            // https://github.com/unicode-org/icu/blob/master/icu4c/source/i18n/unicode/unumberformatter.h\n            case 'unit-width-narrow':\n                result.currencyDisplay = 'narrowSymbol';\n                result.unitDisplay = 'narrow';\n                continue;\n            case 'unit-width-short':\n                result.currencyDisplay = 'code';\n                result.unitDisplay = 'short';\n                continue;\n            case 'unit-width-full-name':\n                result.currencyDisplay = 'name';\n                result.unitDisplay = 'long';\n                continue;\n            case 'unit-width-iso-code':\n                result.currencyDisplay = 'symbol';\n                continue;\n            case 'scale':\n                result.scale = parseFloat(token.options[0]);\n                continue;\n            case 'rounding-mode-floor':\n                result.roundingMode = 'floor';\n                continue;\n            case 'rounding-mode-ceiling':\n                result.roundingMode = 'ceil';\n                continue;\n            case 'rounding-mode-down':\n                result.roundingMode = 'trunc';\n                continue;\n            case 'rounding-mode-up':\n                result.roundingMode = 'expand';\n                continue;\n            case 'rounding-mode-half-even':\n                result.roundingMode = 'halfEven';\n                continue;\n            case 'rounding-mode-half-down':\n                result.roundingMode = 'halfTrunc';\n                continue;\n            case 'rounding-mode-half-up':\n                result.roundingMode = 'halfExpand';\n                continue;\n            // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#integer-width\n            case 'integer-width':\n                if (token.options.length > 1) {\n                    throw new RangeError('integer-width stems only accept a single optional option');\n                }\n                token.options[0].replace(INTEGER_WIDTH_REGEX, function (_, g1, g2, g3, g4, g5) {\n                    if (g1) {\n                        result.minimumIntegerDigits = g2.length;\n                    }\n                    else if (g3 && g4) {\n                        throw new Error('We currently do not support maximum integer digits');\n                    }\n                    else if (g5) {\n                        throw new Error('We currently do not support exact integer digits');\n                    }\n                    return '';\n                });\n                continue;\n        }\n        // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#integer-width\n        if (CONCISE_INTEGER_WIDTH_REGEX.test(token.stem)) {\n            result.minimumIntegerDigits = token.stem.length;\n            continue;\n        }\n        if (FRACTION_PRECISION_REGEX.test(token.stem)) {\n            // Precision\n            // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#fraction-precision\n            // precision-integer case\n            if (token.options.length > 1) {\n                throw new RangeError('Fraction-precision stems only accept a single optional option');\n            }\n            token.stem.replace(FRACTION_PRECISION_REGEX, function (_, g1, g2, g3, g4, g5) {\n                // .000* case (before ICU67 it was .000+)\n                if (g2 === '*') {\n                    result.minimumFractionDigits = g1.length;\n                }\n                // .### case\n                else if (g3 && g3[0] === '#') {\n                    result.maximumFractionDigits = g3.length;\n                }\n                // .00## case\n                else if (g4 && g5) {\n                    result.minimumFractionDigits = g4.length;\n                    result.maximumFractionDigits = g4.length + g5.length;\n                }\n                else {\n                    result.minimumFractionDigits = g1.length;\n                    result.maximumFractionDigits = g1.length;\n                }\n                return '';\n            });\n            var opt = token.options[0];\n            // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#trailing-zero-display\n            if (opt === 'w') {\n                result = __assign(__assign({}, result), { trailingZeroDisplay: 'stripIfInteger' });\n            }\n            else if (opt) {\n                result = __assign(__assign({}, result), parseSignificantPrecision(opt));\n            }\n            continue;\n        }\n        // https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#significant-digits-precision\n        if (SIGNIFICANT_PRECISION_REGEX.test(token.stem)) {\n            result = __assign(__assign({}, result), parseSignificantPrecision(token.stem));\n            continue;\n        }\n        var signOpts = parseSign(token.stem);\n        if (signOpts) {\n            result = __assign(__assign({}, result), signOpts);\n        }\n        var conciseScientificAndEngineeringOpts = parseConciseScientificAndEngineeringStem(token.stem);\n        if (conciseScientificAndEngineeringOpts) {\n            result = __assign(__assign({}, result), conciseScientificAndEngineeringOpts);\n        }\n    }\n    return result;\n}\n","// @generated from time-data-gen.ts\n// prettier-ignore  \nexport var timeData = {\n    \"001\": [\n        \"H\",\n        \"h\"\n    ],\n    \"419\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"AC\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"AD\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"AE\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"AF\": [\n        \"H\",\n        \"hb\",\n        \"hB\",\n        \"h\"\n    ],\n    \"AG\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"AI\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"AL\": [\n        \"h\",\n        \"H\",\n        \"hB\"\n    ],\n    \"AM\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"AO\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"AR\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"AS\": [\n        \"h\",\n        \"H\"\n    ],\n    \"AT\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"AU\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"AW\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"AX\": [\n        \"H\"\n    ],\n    \"AZ\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"BA\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"BB\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"BD\": [\n        \"h\",\n        \"hB\",\n        \"H\"\n    ],\n    \"BE\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"BF\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"BG\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"BH\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"BI\": [\n        \"H\",\n        \"h\"\n    ],\n    \"BJ\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"BL\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"BM\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"BN\": [\n        \"hb\",\n        \"hB\",\n        \"h\",\n        \"H\"\n    ],\n    \"BO\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"BQ\": [\n        \"H\"\n    ],\n    \"BR\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"BS\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"BT\": [\n        \"h\",\n        \"H\"\n    ],\n    \"BW\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"BY\": [\n        \"H\",\n        \"h\"\n    ],\n    \"BZ\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"CA\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"CC\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"CD\": [\n        \"hB\",\n        \"H\"\n    ],\n    \"CF\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"CG\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"CH\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"CI\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"CK\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"CL\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"CM\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"CN\": [\n        \"H\",\n        \"hB\",\n        \"hb\",\n        \"h\"\n    ],\n    \"CO\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"CP\": [\n        \"H\"\n    ],\n    \"CR\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"CU\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"CV\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"CW\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"CX\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"CY\": [\n        \"h\",\n        \"H\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"CZ\": [\n        \"H\"\n    ],\n    \"DE\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"DG\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"DJ\": [\n        \"h\",\n        \"H\"\n    ],\n    \"DK\": [\n        \"H\"\n    ],\n    \"DM\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"DO\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"DZ\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"EA\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"EC\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"EE\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"EG\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"EH\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"ER\": [\n        \"h\",\n        \"H\"\n    ],\n    \"ES\": [\n        \"H\",\n        \"hB\",\n        \"h\",\n        \"hb\"\n    ],\n    \"ET\": [\n        \"hB\",\n        \"hb\",\n        \"h\",\n        \"H\"\n    ],\n    \"FI\": [\n        \"H\"\n    ],\n    \"FJ\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"FK\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"FM\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"FO\": [\n        \"H\",\n        \"h\"\n    ],\n    \"FR\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"GA\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"GB\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"GD\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"GE\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"GF\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"GG\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"GH\": [\n        \"h\",\n        \"H\"\n    ],\n    \"GI\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"GL\": [\n        \"H\",\n        \"h\"\n    ],\n    \"GM\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"GN\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"GP\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"GQ\": [\n        \"H\",\n        \"hB\",\n        \"h\",\n        \"hb\"\n    ],\n    \"GR\": [\n        \"h\",\n        \"H\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"GT\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"GU\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"GW\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"GY\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"HK\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"HN\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"HR\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"HU\": [\n        \"H\",\n        \"h\"\n    ],\n    \"IC\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"ID\": [\n        \"H\"\n    ],\n    \"IE\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"IL\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"IM\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"IN\": [\n        \"h\",\n        \"H\"\n    ],\n    \"IO\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"IQ\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"IR\": [\n        \"hB\",\n        \"H\"\n    ],\n    \"IS\": [\n        \"H\"\n    ],\n    \"IT\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"JE\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"JM\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"JO\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"JP\": [\n        \"H\",\n        \"K\",\n        \"h\"\n    ],\n    \"KE\": [\n        \"hB\",\n        \"hb\",\n        \"H\",\n        \"h\"\n    ],\n    \"KG\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"KH\": [\n        \"hB\",\n        \"h\",\n        \"H\",\n        \"hb\"\n    ],\n    \"KI\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"KM\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"KN\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"KP\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"KR\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"KW\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"KY\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"KZ\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"LA\": [\n        \"H\",\n        \"hb\",\n        \"hB\",\n        \"h\"\n    ],\n    \"LB\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"LC\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"LI\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"LK\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"LR\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"LS\": [\n        \"h\",\n        \"H\"\n    ],\n    \"LT\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"LU\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"LV\": [\n        \"H\",\n        \"hB\",\n        \"hb\",\n        \"h\"\n    ],\n    \"LY\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"MA\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"MC\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"MD\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"ME\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"MF\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"MG\": [\n        \"H\",\n        \"h\"\n    ],\n    \"MH\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"MK\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"ML\": [\n        \"H\"\n    ],\n    \"MM\": [\n        \"hB\",\n        \"hb\",\n        \"H\",\n        \"h\"\n    ],\n    \"MN\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"MO\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"MP\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"MQ\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"MR\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"MS\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"MT\": [\n        \"H\",\n        \"h\"\n    ],\n    \"MU\": [\n        \"H\",\n        \"h\"\n    ],\n    \"MV\": [\n        \"H\",\n        \"h\"\n    ],\n    \"MW\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"MX\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"MY\": [\n        \"hb\",\n        \"hB\",\n        \"h\",\n        \"H\"\n    ],\n    \"MZ\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"NA\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"NC\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"NE\": [\n        \"H\"\n    ],\n    \"NF\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"NG\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"NI\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"NL\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"NO\": [\n        \"H\",\n        \"h\"\n    ],\n    \"NP\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"NR\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"NU\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"NZ\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"OM\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"PA\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"PE\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"PF\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"PG\": [\n        \"h\",\n        \"H\"\n    ],\n    \"PH\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"PK\": [\n        \"h\",\n        \"hB\",\n        \"H\"\n    ],\n    \"PL\": [\n        \"H\",\n        \"h\"\n    ],\n    \"PM\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"PN\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"PR\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"PS\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"PT\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"PW\": [\n        \"h\",\n        \"H\"\n    ],\n    \"PY\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"QA\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"RE\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"RO\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"RS\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"RU\": [\n        \"H\"\n    ],\n    \"RW\": [\n        \"H\",\n        \"h\"\n    ],\n    \"SA\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"SB\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"SC\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"SD\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"SE\": [\n        \"H\"\n    ],\n    \"SG\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"SH\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"SI\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"SJ\": [\n        \"H\"\n    ],\n    \"SK\": [\n        \"H\"\n    ],\n    \"SL\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"SM\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"SN\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"SO\": [\n        \"h\",\n        \"H\"\n    ],\n    \"SR\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"SS\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"ST\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"SV\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"SX\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"SY\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"SZ\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"TA\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"TC\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"TD\": [\n        \"h\",\n        \"H\",\n        \"hB\"\n    ],\n    \"TF\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"TG\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"TH\": [\n        \"H\",\n        \"h\"\n    ],\n    \"TJ\": [\n        \"H\",\n        \"h\"\n    ],\n    \"TL\": [\n        \"H\",\n        \"hB\",\n        \"hb\",\n        \"h\"\n    ],\n    \"TM\": [\n        \"H\",\n        \"h\"\n    ],\n    \"TN\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"TO\": [\n        \"h\",\n        \"H\"\n    ],\n    \"TR\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"TT\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"TW\": [\n        \"hB\",\n        \"hb\",\n        \"h\",\n        \"H\"\n    ],\n    \"TZ\": [\n        \"hB\",\n        \"hb\",\n        \"H\",\n        \"h\"\n    ],\n    \"UA\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"UG\": [\n        \"hB\",\n        \"hb\",\n        \"H\",\n        \"h\"\n    ],\n    \"UM\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"US\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"UY\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"UZ\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"VA\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"VC\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"VE\": [\n        \"h\",\n        \"H\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"VG\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"VI\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"VN\": [\n        \"H\",\n        \"h\"\n    ],\n    \"VU\": [\n        \"h\",\n        \"H\"\n    ],\n    \"WF\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"WS\": [\n        \"h\",\n        \"H\"\n    ],\n    \"XK\": [\n        \"H\",\n        \"hB\",\n        \"h\"\n    ],\n    \"YE\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"YT\": [\n        \"H\",\n        \"hB\"\n    ],\n    \"ZA\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"ZM\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"ZW\": [\n        \"H\",\n        \"h\"\n    ],\n    \"af-ZA\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"ar-001\": [\n        \"h\",\n        \"hB\",\n        \"hb\",\n        \"H\"\n    ],\n    \"ca-ES\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"en-001\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"en-HK\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"en-IL\": [\n        \"H\",\n        \"h\",\n        \"hb\",\n        \"hB\"\n    ],\n    \"en-MY\": [\n        \"h\",\n        \"hb\",\n        \"H\",\n        \"hB\"\n    ],\n    \"es-BR\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"es-ES\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"es-GQ\": [\n        \"H\",\n        \"h\",\n        \"hB\",\n        \"hb\"\n    ],\n    \"fr-CA\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"gl-ES\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"gu-IN\": [\n        \"hB\",\n        \"hb\",\n        \"h\",\n        \"H\"\n    ],\n    \"hi-IN\": [\n        \"hB\",\n        \"h\",\n        \"H\"\n    ],\n    \"it-CH\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"it-IT\": [\n        \"H\",\n        \"h\",\n        \"hB\"\n    ],\n    \"kn-IN\": [\n        \"hB\",\n        \"h\",\n        \"H\"\n    ],\n    \"ml-IN\": [\n        \"hB\",\n        \"h\",\n        \"H\"\n    ],\n    \"mr-IN\": [\n        \"hB\",\n        \"hb\",\n        \"h\",\n        \"H\"\n    ],\n    \"pa-IN\": [\n        \"hB\",\n        \"hb\",\n        \"h\",\n        \"H\"\n    ],\n    \"ta-IN\": [\n        \"hB\",\n        \"h\",\n        \"hb\",\n        \"H\"\n    ],\n    \"te-IN\": [\n        \"hB\",\n        \"h\",\n        \"H\"\n    ],\n    \"zu-ZA\": [\n        \"H\",\n        \"hB\",\n        \"hb\",\n        \"h\"\n    ]\n};\n","var _a;\nimport { __assign } from \"tslib\";\nimport { ErrorKind } from './error';\nimport { SKELETON_TYPE, TYPE, } from './types';\nimport { SPACE_SEPARATOR_REGEX } from './regex.generated';\nimport { parseNumberSkeleton, parseNumberSkeletonFromString, parseDateTimeSkeleton, } from '@formatjs/icu-skeleton-parser';\nimport { getBestPattern } from './date-time-pattern-generator';\nvar SPACE_SEPARATOR_START_REGEX = new RegExp(\"^\".concat(SPACE_SEPARATOR_REGEX.source, \"*\"));\nvar SPACE_SEPARATOR_END_REGEX = new RegExp(\"\".concat(SPACE_SEPARATOR_REGEX.source, \"*$\"));\nfunction createLocation(start, end) {\n    return { start: start, end: end };\n}\n// #region Ponyfills\n// Consolidate these variables up top for easier toggling during debugging\nvar hasNativeStartsWith = !!String.prototype.startsWith && '_a'.startsWith('a', 1);\nvar hasNativeFromCodePoint = !!String.fromCodePoint;\nvar hasNativeFromEntries = !!Object.fromEntries;\nvar hasNativeCodePointAt = !!String.prototype.codePointAt;\nvar hasTrimStart = !!String.prototype.trimStart;\nvar hasTrimEnd = !!String.prototype.trimEnd;\nvar hasNativeIsSafeInteger = !!Number.isSafeInteger;\nvar isSafeInteger = hasNativeIsSafeInteger\n    ? Number.isSafeInteger\n    : function (n) {\n        return (typeof n === 'number' &&\n            isFinite(n) &&\n            Math.floor(n) === n &&\n            Math.abs(n) <= 0x1fffffffffffff);\n    };\n// IE11 does not support y and u.\nvar REGEX_SUPPORTS_U_AND_Y = true;\ntry {\n    var re = RE('([^\\\\p{White_Space}\\\\p{Pattern_Syntax}]*)', 'yu');\n    /**\n     * legacy Edge or Xbox One browser\n     * Unicode flag support: supported\n     * Pattern_Syntax support: not supported\n     * See https://github.com/formatjs/formatjs/issues/2822\n     */\n    REGEX_SUPPORTS_U_AND_Y = ((_a = re.exec('a')) === null || _a === void 0 ? void 0 : _a[0]) === 'a';\n}\ncatch (_) {\n    REGEX_SUPPORTS_U_AND_Y = false;\n}\nvar startsWith = hasNativeStartsWith\n    ? // Native\n        function startsWith(s, search, position) {\n            return s.startsWith(search, position);\n        }\n    : // For IE11\n        function startsWith(s, search, position) {\n            return s.slice(position, position + search.length) === search;\n        };\nvar fromCodePoint = hasNativeFromCodePoint\n    ? String.fromCodePoint\n    : // IE11\n        function fromCodePoint() {\n            var codePoints = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                codePoints[_i] = arguments[_i];\n            }\n            var elements = '';\n            var length = codePoints.length;\n            var i = 0;\n            var code;\n            while (length > i) {\n                code = codePoints[i++];\n                if (code > 0x10ffff)\n                    throw RangeError(code + ' is not a valid code point');\n                elements +=\n                    code < 0x10000\n                        ? String.fromCharCode(code)\n                        : String.fromCharCode(((code -= 0x10000) >> 10) + 0xd800, (code % 0x400) + 0xdc00);\n            }\n            return elements;\n        };\nvar fromEntries = \n// native\nhasNativeFromEntries\n    ? Object.fromEntries\n    : // Ponyfill\n        function fromEntries(entries) {\n            var obj = {};\n            for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n                var _a = entries_1[_i], k = _a[0], v = _a[1];\n                obj[k] = v;\n            }\n            return obj;\n        };\nvar codePointAt = hasNativeCodePointAt\n    ? // Native\n        function codePointAt(s, index) {\n            return s.codePointAt(index);\n        }\n    : // IE 11\n        function codePointAt(s, index) {\n            var size = s.length;\n            if (index < 0 || index >= size) {\n                return undefined;\n            }\n            var first = s.charCodeAt(index);\n            var second;\n            return first < 0xd800 ||\n                first > 0xdbff ||\n                index + 1 === size ||\n                (second = s.charCodeAt(index + 1)) < 0xdc00 ||\n                second > 0xdfff\n                ? first\n                : ((first - 0xd800) << 10) + (second - 0xdc00) + 0x10000;\n        };\nvar trimStart = hasTrimStart\n    ? // Native\n        function trimStart(s) {\n            return s.trimStart();\n        }\n    : // Ponyfill\n        function trimStart(s) {\n            return s.replace(SPACE_SEPARATOR_START_REGEX, '');\n        };\nvar trimEnd = hasTrimEnd\n    ? // Native\n        function trimEnd(s) {\n            return s.trimEnd();\n        }\n    : // Ponyfill\n        function trimEnd(s) {\n            return s.replace(SPACE_SEPARATOR_END_REGEX, '');\n        };\n// Prevent minifier to translate new RegExp to literal form that might cause syntax error on IE11.\nfunction RE(s, flag) {\n    return new RegExp(s, flag);\n}\n// #endregion\nvar matchIdentifierAtIndex;\nif (REGEX_SUPPORTS_U_AND_Y) {\n    // Native\n    var IDENTIFIER_PREFIX_RE_1 = RE('([^\\\\p{White_Space}\\\\p{Pattern_Syntax}]*)', 'yu');\n    matchIdentifierAtIndex = function matchIdentifierAtIndex(s, index) {\n        var _a;\n        IDENTIFIER_PREFIX_RE_1.lastIndex = index;\n        var match = IDENTIFIER_PREFIX_RE_1.exec(s);\n        return (_a = match[1]) !== null && _a !== void 0 ? _a : '';\n    };\n}\nelse {\n    // IE11\n    matchIdentifierAtIndex = function matchIdentifierAtIndex(s, index) {\n        var match = [];\n        while (true) {\n            var c = codePointAt(s, index);\n            if (c === undefined || _isWhiteSpace(c) || _isPatternSyntax(c)) {\n                break;\n            }\n            match.push(c);\n            index += c >= 0x10000 ? 2 : 1;\n        }\n        return fromCodePoint.apply(void 0, match);\n    };\n}\nvar Parser = /** @class */ (function () {\n    function Parser(message, options) {\n        if (options === void 0) { options = {}; }\n        this.message = message;\n        this.position = { offset: 0, line: 1, column: 1 };\n        this.ignoreTag = !!options.ignoreTag;\n        this.locale = options.locale;\n        this.requiresOtherClause = !!options.requiresOtherClause;\n        this.shouldParseSkeletons = !!options.shouldParseSkeletons;\n    }\n    Parser.prototype.parse = function () {\n        if (this.offset() !== 0) {\n            throw Error('parser can only be used once');\n        }\n        return this.parseMessage(0, '', false);\n    };\n    Parser.prototype.parseMessage = function (nestingLevel, parentArgType, expectingCloseTag) {\n        var elements = [];\n        while (!this.isEOF()) {\n            var char = this.char();\n            if (char === 123 /* `{` */) {\n                var result = this.parseArgument(nestingLevel, expectingCloseTag);\n                if (result.err) {\n                    return result;\n                }\n                elements.push(result.val);\n            }\n            else if (char === 125 /* `}` */ && nestingLevel > 0) {\n                break;\n            }\n            else if (char === 35 /* `#` */ &&\n                (parentArgType === 'plural' || parentArgType === 'selectordinal')) {\n                var position = this.clonePosition();\n                this.bump();\n                elements.push({\n                    type: TYPE.pound,\n                    location: createLocation(position, this.clonePosition()),\n                });\n            }\n            else if (char === 60 /* `<` */ &&\n                !this.ignoreTag &&\n                this.peek() === 47 // char code for '/'\n            ) {\n                if (expectingCloseTag) {\n                    break;\n                }\n                else {\n                    return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(this.clonePosition(), this.clonePosition()));\n                }\n            }\n            else if (char === 60 /* `<` */ &&\n                !this.ignoreTag &&\n                _isAlpha(this.peek() || 0)) {\n                var result = this.parseTag(nestingLevel, parentArgType);\n                if (result.err) {\n                    return result;\n                }\n                elements.push(result.val);\n            }\n            else {\n                var result = this.parseLiteral(nestingLevel, parentArgType);\n                if (result.err) {\n                    return result;\n                }\n                elements.push(result.val);\n            }\n        }\n        return { val: elements, err: null };\n    };\n    /**\n     * A tag name must start with an ASCII lower/upper case letter. The grammar is based on the\n     * [custom element name][] except that a dash is NOT always mandatory and uppercase letters\n     * are accepted:\n     *\n     * ```\n     * tag ::= \"<\" tagName (whitespace)* \"/>\" | \"<\" tagName (whitespace)* \">\" message \"</\" tagName (whitespace)* \">\"\n     * tagName ::= [a-z] (PENChar)*\n     * PENChar ::=\n     *     \"-\" | \".\" | [0-9] | \"_\" | [a-z] | [A-Z] | #xB7 | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x37D] |\n     *     [#x37F-#x1FFF] | [#x200C-#x200D] | [#x203F-#x2040] | [#x2070-#x218F] | [#x2C00-#x2FEF] |\n     *     [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]\n     * ```\n     *\n     * [custom element name]: https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name\n     * NOTE: We're a bit more lax here since HTML technically does not allow uppercase HTML element but we do\n     * since other tag-based engines like React allow it\n     */\n    Parser.prototype.parseTag = function (nestingLevel, parentArgType) {\n        var startPosition = this.clonePosition();\n        this.bump(); // `<`\n        var tagName = this.parseTagName();\n        this.bumpSpace();\n        if (this.bumpIf('/>')) {\n            // Self closing tag\n            return {\n                val: {\n                    type: TYPE.literal,\n                    value: \"<\".concat(tagName, \"/>\"),\n                    location: createLocation(startPosition, this.clonePosition()),\n                },\n                err: null,\n            };\n        }\n        else if (this.bumpIf('>')) {\n            var childrenResult = this.parseMessage(nestingLevel + 1, parentArgType, true);\n            if (childrenResult.err) {\n                return childrenResult;\n            }\n            var children = childrenResult.val;\n            // Expecting a close tag\n            var endTagStartPosition = this.clonePosition();\n            if (this.bumpIf('</')) {\n                if (this.isEOF() || !_isAlpha(this.char())) {\n                    return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));\n                }\n                var closingTagNameStartPosition = this.clonePosition();\n                var closingTagName = this.parseTagName();\n                if (tagName !== closingTagName) {\n                    return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(closingTagNameStartPosition, this.clonePosition()));\n                }\n                this.bumpSpace();\n                if (!this.bumpIf('>')) {\n                    return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));\n                }\n                return {\n                    val: {\n                        type: TYPE.tag,\n                        value: tagName,\n                        children: children,\n                        location: createLocation(startPosition, this.clonePosition()),\n                    },\n                    err: null,\n                };\n            }\n            else {\n                return this.error(ErrorKind.UNCLOSED_TAG, createLocation(startPosition, this.clonePosition()));\n            }\n        }\n        else {\n            return this.error(ErrorKind.INVALID_TAG, createLocation(startPosition, this.clonePosition()));\n        }\n    };\n    /**\n     * This method assumes that the caller has peeked ahead for the first tag character.\n     */\n    Parser.prototype.parseTagName = function () {\n        var startOffset = this.offset();\n        this.bump(); // the first tag name character\n        while (!this.isEOF() && _isPotentialElementNameChar(this.char())) {\n            this.bump();\n        }\n        return this.message.slice(startOffset, this.offset());\n    };\n    Parser.prototype.parseLiteral = function (nestingLevel, parentArgType) {\n        var start = this.clonePosition();\n        var value = '';\n        while (true) {\n            var parseQuoteResult = this.tryParseQuote(parentArgType);\n            if (parseQuoteResult) {\n                value += parseQuoteResult;\n                continue;\n            }\n            var parseUnquotedResult = this.tryParseUnquoted(nestingLevel, parentArgType);\n            if (parseUnquotedResult) {\n                value += parseUnquotedResult;\n                continue;\n            }\n            var parseLeftAngleResult = this.tryParseLeftAngleBracket();\n            if (parseLeftAngleResult) {\n                value += parseLeftAngleResult;\n                continue;\n            }\n            break;\n        }\n        var location = createLocation(start, this.clonePosition());\n        return {\n            val: { type: TYPE.literal, value: value, location: location },\n            err: null,\n        };\n    };\n    Parser.prototype.tryParseLeftAngleBracket = function () {\n        if (!this.isEOF() &&\n            this.char() === 60 /* `<` */ &&\n            (this.ignoreTag ||\n                // If at the opening tag or closing tag position, bail.\n                !_isAlphaOrSlash(this.peek() || 0))) {\n            this.bump(); // `<`\n            return '<';\n        }\n        return null;\n    };\n    /**\n     * Starting with ICU 4.8, an ASCII apostrophe only starts quoted text if it immediately precedes\n     * a character that requires quoting (that is, \"only where needed\"), and works the same in\n     * nested messages as on the top level of the pattern. The new behavior is otherwise compatible.\n     */\n    Parser.prototype.tryParseQuote = function (parentArgType) {\n        if (this.isEOF() || this.char() !== 39 /* `'` */) {\n            return null;\n        }\n        // Parse escaped char following the apostrophe, or early return if there is no escaped char.\n        // Check if is valid escaped character\n        switch (this.peek()) {\n            case 39 /* `'` */:\n                // double quote, should return as a single quote.\n                this.bump();\n                this.bump();\n                return \"'\";\n            // '{', '<', '>', '}'\n            case 123:\n            case 60:\n            case 62:\n            case 125:\n                break;\n            case 35: // '#'\n                if (parentArgType === 'plural' || parentArgType === 'selectordinal') {\n                    break;\n                }\n                return null;\n            default:\n                return null;\n        }\n        this.bump(); // apostrophe\n        var codePoints = [this.char()]; // escaped char\n        this.bump();\n        // read chars until the optional closing apostrophe is found\n        while (!this.isEOF()) {\n            var ch = this.char();\n            if (ch === 39 /* `'` */) {\n                if (this.peek() === 39 /* `'` */) {\n                    codePoints.push(39);\n                    // Bump one more time because we need to skip 2 characters.\n                    this.bump();\n                }\n                else {\n                    // Optional closing apostrophe.\n                    this.bump();\n                    break;\n                }\n            }\n            else {\n                codePoints.push(ch);\n            }\n            this.bump();\n        }\n        return fromCodePoint.apply(void 0, codePoints);\n    };\n    Parser.prototype.tryParseUnquoted = function (nestingLevel, parentArgType) {\n        if (this.isEOF()) {\n            return null;\n        }\n        var ch = this.char();\n        if (ch === 60 /* `<` */ ||\n            ch === 123 /* `{` */ ||\n            (ch === 35 /* `#` */ &&\n                (parentArgType === 'plural' || parentArgType === 'selectordinal')) ||\n            (ch === 125 /* `}` */ && nestingLevel > 0)) {\n            return null;\n        }\n        else {\n            this.bump();\n            return fromCodePoint(ch);\n        }\n    };\n    Parser.prototype.parseArgument = function (nestingLevel, expectingCloseTag) {\n        var openingBracePosition = this.clonePosition();\n        this.bump(); // `{`\n        this.bumpSpace();\n        if (this.isEOF()) {\n            return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));\n        }\n        if (this.char() === 125 /* `}` */) {\n            this.bump();\n            return this.error(ErrorKind.EMPTY_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));\n        }\n        // argument name\n        var value = this.parseIdentifierIfPossible().value;\n        if (!value) {\n            return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));\n        }\n        this.bumpSpace();\n        if (this.isEOF()) {\n            return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));\n        }\n        switch (this.char()) {\n            // Simple argument: `{name}`\n            case 125 /* `}` */: {\n                this.bump(); // `}`\n                return {\n                    val: {\n                        type: TYPE.argument,\n                        // value does not include the opening and closing braces.\n                        value: value,\n                        location: createLocation(openingBracePosition, this.clonePosition()),\n                    },\n                    err: null,\n                };\n            }\n            // Argument with options: `{name, format, ...}`\n            case 44 /* `,` */: {\n                this.bump(); // `,`\n                this.bumpSpace();\n                if (this.isEOF()) {\n                    return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));\n                }\n                return this.parseArgumentOptions(nestingLevel, expectingCloseTag, value, openingBracePosition);\n            }\n            default:\n                return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));\n        }\n    };\n    /**\n     * Advance the parser until the end of the identifier, if it is currently on\n     * an identifier character. Return an empty string otherwise.\n     */\n    Parser.prototype.parseIdentifierIfPossible = function () {\n        var startingPosition = this.clonePosition();\n        var startOffset = this.offset();\n        var value = matchIdentifierAtIndex(this.message, startOffset);\n        var endOffset = startOffset + value.length;\n        this.bumpTo(endOffset);\n        var endPosition = this.clonePosition();\n        var location = createLocation(startingPosition, endPosition);\n        return { value: value, location: location };\n    };\n    Parser.prototype.parseArgumentOptions = function (nestingLevel, expectingCloseTag, value, openingBracePosition) {\n        var _a;\n        // Parse this range:\n        // {name, type, style}\n        //        ^---^\n        var typeStartPosition = this.clonePosition();\n        var argType = this.parseIdentifierIfPossible().value;\n        var typeEndPosition = this.clonePosition();\n        switch (argType) {\n            case '':\n                // Expecting a style string number, date, time, plural, selectordinal, or select.\n                return this.error(ErrorKind.EXPECT_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));\n            case 'number':\n            case 'date':\n            case 'time': {\n                // Parse this range:\n                // {name, number, style}\n                //              ^-------^\n                this.bumpSpace();\n                var styleAndLocation = null;\n                if (this.bumpIf(',')) {\n                    this.bumpSpace();\n                    var styleStartPosition = this.clonePosition();\n                    var result = this.parseSimpleArgStyleIfPossible();\n                    if (result.err) {\n                        return result;\n                    }\n                    var style = trimEnd(result.val);\n                    if (style.length === 0) {\n                        return this.error(ErrorKind.EXPECT_ARGUMENT_STYLE, createLocation(this.clonePosition(), this.clonePosition()));\n                    }\n                    var styleLocation = createLocation(styleStartPosition, this.clonePosition());\n                    styleAndLocation = { style: style, styleLocation: styleLocation };\n                }\n                var argCloseResult = this.tryParseArgumentClose(openingBracePosition);\n                if (argCloseResult.err) {\n                    return argCloseResult;\n                }\n                var location_1 = createLocation(openingBracePosition, this.clonePosition());\n                // Extract style or skeleton\n                if (styleAndLocation && startsWith(styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style, '::', 0)) {\n                    // Skeleton starts with `::`.\n                    var skeleton = trimStart(styleAndLocation.style.slice(2));\n                    if (argType === 'number') {\n                        var result = this.parseNumberSkeletonFromString(skeleton, styleAndLocation.styleLocation);\n                        if (result.err) {\n                            return result;\n                        }\n                        return {\n                            val: { type: TYPE.number, value: value, location: location_1, style: result.val },\n                            err: null,\n                        };\n                    }\n                    else {\n                        if (skeleton.length === 0) {\n                            return this.error(ErrorKind.EXPECT_DATE_TIME_SKELETON, location_1);\n                        }\n                        var dateTimePattern = skeleton;\n                        // Get \"best match\" pattern only if locale is passed, if not, let it\n                        // pass as-is where `parseDateTimeSkeleton()` will throw an error\n                        // for unsupported patterns.\n                        if (this.locale) {\n                            dateTimePattern = getBestPattern(skeleton, this.locale);\n                        }\n                        var style = {\n                            type: SKELETON_TYPE.dateTime,\n                            pattern: dateTimePattern,\n                            location: styleAndLocation.styleLocation,\n                            parsedOptions: this.shouldParseSkeletons\n                                ? parseDateTimeSkeleton(dateTimePattern)\n                                : {},\n                        };\n                        var type = argType === 'date' ? TYPE.date : TYPE.time;\n                        return {\n                            val: { type: type, value: value, location: location_1, style: style },\n                            err: null,\n                        };\n                    }\n                }\n                // Regular style or no style.\n                return {\n                    val: {\n                        type: argType === 'number'\n                            ? TYPE.number\n                            : argType === 'date'\n                                ? TYPE.date\n                                : TYPE.time,\n                        value: value,\n                        location: location_1,\n                        style: (_a = styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style) !== null && _a !== void 0 ? _a : null,\n                    },\n                    err: null,\n                };\n            }\n            case 'plural':\n            case 'selectordinal':\n            case 'select': {\n                // Parse this range:\n                // {name, plural, options}\n                //              ^---------^\n                var typeEndPosition_1 = this.clonePosition();\n                this.bumpSpace();\n                if (!this.bumpIf(',')) {\n                    return this.error(ErrorKind.EXPECT_SELECT_ARGUMENT_OPTIONS, createLocation(typeEndPosition_1, __assign({}, typeEndPosition_1)));\n                }\n                this.bumpSpace();\n                // Parse offset:\n                // {name, plural, offset:1, options}\n                //                ^-----^\n                //\n                // or the first option:\n                //\n                // {name, plural, one {...} other {...}}\n                //                ^--^\n                var identifierAndLocation = this.parseIdentifierIfPossible();\n                var pluralOffset = 0;\n                if (argType !== 'select' && identifierAndLocation.value === 'offset') {\n                    if (!this.bumpIf(':')) {\n                        return this.error(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, createLocation(this.clonePosition(), this.clonePosition()));\n                    }\n                    this.bumpSpace();\n                    var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, ErrorKind.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE);\n                    if (result.err) {\n                        return result;\n                    }\n                    // Parse another identifier for option parsing\n                    this.bumpSpace();\n                    identifierAndLocation = this.parseIdentifierIfPossible();\n                    pluralOffset = result.val;\n                }\n                var optionsResult = this.tryParsePluralOrSelectOptions(nestingLevel, argType, expectingCloseTag, identifierAndLocation);\n                if (optionsResult.err) {\n                    return optionsResult;\n                }\n                var argCloseResult = this.tryParseArgumentClose(openingBracePosition);\n                if (argCloseResult.err) {\n                    return argCloseResult;\n                }\n                var location_2 = createLocation(openingBracePosition, this.clonePosition());\n                if (argType === 'select') {\n                    return {\n                        val: {\n                            type: TYPE.select,\n                            value: value,\n                            options: fromEntries(optionsResult.val),\n                            location: location_2,\n                        },\n                        err: null,\n                    };\n                }\n                else {\n                    return {\n                        val: {\n                            type: TYPE.plural,\n                            value: value,\n                            options: fromEntries(optionsResult.val),\n                            offset: pluralOffset,\n                            pluralType: argType === 'plural' ? 'cardinal' : 'ordinal',\n                            location: location_2,\n                        },\n                        err: null,\n                    };\n                }\n            }\n            default:\n                return this.error(ErrorKind.INVALID_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));\n        }\n    };\n    Parser.prototype.tryParseArgumentClose = function (openingBracePosition) {\n        // Parse: {value, number, ::currency/GBP }\n        //\n        if (this.isEOF() || this.char() !== 125 /* `}` */) {\n            return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));\n        }\n        this.bump(); // `}`\n        return { val: true, err: null };\n    };\n    /**\n     * See: https://github.com/unicode-org/icu/blob/af7ed1f6d2298013dc303628438ec4abe1f16479/icu4c/source/common/messagepattern.cpp#L659\n     */\n    Parser.prototype.parseSimpleArgStyleIfPossible = function () {\n        var nestedBraces = 0;\n        var startPosition = this.clonePosition();\n        while (!this.isEOF()) {\n            var ch = this.char();\n            switch (ch) {\n                case 39 /* `'` */: {\n                    // Treat apostrophe as quoting but include it in the style part.\n                    // Find the end of the quoted literal text.\n                    this.bump();\n                    var apostrophePosition = this.clonePosition();\n                    if (!this.bumpUntil(\"'\")) {\n                        return this.error(ErrorKind.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE, createLocation(apostrophePosition, this.clonePosition()));\n                    }\n                    this.bump();\n                    break;\n                }\n                case 123 /* `{` */: {\n                    nestedBraces += 1;\n                    this.bump();\n                    break;\n                }\n                case 125 /* `}` */: {\n                    if (nestedBraces > 0) {\n                        nestedBraces -= 1;\n                    }\n                    else {\n                        return {\n                            val: this.message.slice(startPosition.offset, this.offset()),\n                            err: null,\n                        };\n                    }\n                    break;\n                }\n                default:\n                    this.bump();\n                    break;\n            }\n        }\n        return {\n            val: this.message.slice(startPosition.offset, this.offset()),\n            err: null,\n        };\n    };\n    Parser.prototype.parseNumberSkeletonFromString = function (skeleton, location) {\n        var tokens = [];\n        try {\n            tokens = parseNumberSkeletonFromString(skeleton);\n        }\n        catch (e) {\n            return this.error(ErrorKind.INVALID_NUMBER_SKELETON, location);\n        }\n        return {\n            val: {\n                type: SKELETON_TYPE.number,\n                tokens: tokens,\n                location: location,\n                parsedOptions: this.shouldParseSkeletons\n                    ? parseNumberSkeleton(tokens)\n                    : {},\n            },\n            err: null,\n        };\n    };\n    /**\n     * @param nesting_level The current nesting level of messages.\n     *     This can be positive when parsing message fragment in select or plural argument options.\n     * @param parent_arg_type The parent argument's type.\n     * @param parsed_first_identifier If provided, this is the first identifier-like selector of\n     *     the argument. It is a by-product of a previous parsing attempt.\n     * @param expecting_close_tag If true, this message is directly or indirectly nested inside\n     *     between a pair of opening and closing tags. The nested message will not parse beyond\n     *     the closing tag boundary.\n     */\n    Parser.prototype.tryParsePluralOrSelectOptions = function (nestingLevel, parentArgType, expectCloseTag, parsedFirstIdentifier) {\n        var _a;\n        var hasOtherClause = false;\n        var options = [];\n        var parsedSelectors = new Set();\n        var selector = parsedFirstIdentifier.value, selectorLocation = parsedFirstIdentifier.location;\n        // Parse:\n        // one {one apple}\n        // ^--^\n        while (true) {\n            if (selector.length === 0) {\n                var startPosition = this.clonePosition();\n                if (parentArgType !== 'select' && this.bumpIf('=')) {\n                    // Try parse `={number}` selector\n                    var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, ErrorKind.INVALID_PLURAL_ARGUMENT_SELECTOR);\n                    if (result.err) {\n                        return result;\n                    }\n                    selectorLocation = createLocation(startPosition, this.clonePosition());\n                    selector = this.message.slice(startPosition.offset, this.offset());\n                }\n                else {\n                    break;\n                }\n            }\n            // Duplicate selector clauses\n            if (parsedSelectors.has(selector)) {\n                return this.error(parentArgType === 'select'\n                    ? ErrorKind.DUPLICATE_SELECT_ARGUMENT_SELECTOR\n                    : ErrorKind.DUPLICATE_PLURAL_ARGUMENT_SELECTOR, selectorLocation);\n            }\n            if (selector === 'other') {\n                hasOtherClause = true;\n            }\n            // Parse:\n            // one {one apple}\n            //     ^----------^\n            this.bumpSpace();\n            var openingBracePosition = this.clonePosition();\n            if (!this.bumpIf('{')) {\n                return this.error(parentArgType === 'select'\n                    ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT\n                    : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT, createLocation(this.clonePosition(), this.clonePosition()));\n            }\n            var fragmentResult = this.parseMessage(nestingLevel + 1, parentArgType, expectCloseTag);\n            if (fragmentResult.err) {\n                return fragmentResult;\n            }\n            var argCloseResult = this.tryParseArgumentClose(openingBracePosition);\n            if (argCloseResult.err) {\n                return argCloseResult;\n            }\n            options.push([\n                selector,\n                {\n                    value: fragmentResult.val,\n                    location: createLocation(openingBracePosition, this.clonePosition()),\n                },\n            ]);\n            // Keep track of the existing selectors\n            parsedSelectors.add(selector);\n            // Prep next selector clause.\n            this.bumpSpace();\n            (_a = this.parseIdentifierIfPossible(), selector = _a.value, selectorLocation = _a.location);\n        }\n        if (options.length === 0) {\n            return this.error(parentArgType === 'select'\n                ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR\n                : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, createLocation(this.clonePosition(), this.clonePosition()));\n        }\n        if (this.requiresOtherClause && !hasOtherClause) {\n            return this.error(ErrorKind.MISSING_OTHER_CLAUSE, createLocation(this.clonePosition(), this.clonePosition()));\n        }\n        return { val: options, err: null };\n    };\n    Parser.prototype.tryParseDecimalInteger = function (expectNumberError, invalidNumberError) {\n        var sign = 1;\n        var startingPosition = this.clonePosition();\n        if (this.bumpIf('+')) {\n        }\n        else if (this.bumpIf('-')) {\n            sign = -1;\n        }\n        var hasDigits = false;\n        var decimal = 0;\n        while (!this.isEOF()) {\n            var ch = this.char();\n            if (ch >= 48 /* `0` */ && ch <= 57 /* `9` */) {\n                hasDigits = true;\n                decimal = decimal * 10 + (ch - 48);\n                this.bump();\n            }\n            else {\n                break;\n            }\n        }\n        var location = createLocation(startingPosition, this.clonePosition());\n        if (!hasDigits) {\n            return this.error(expectNumberError, location);\n        }\n        decimal *= sign;\n        if (!isSafeInteger(decimal)) {\n            return this.error(invalidNumberError, location);\n        }\n        return { val: decimal, err: null };\n    };\n    Parser.prototype.offset = function () {\n        return this.position.offset;\n    };\n    Parser.prototype.isEOF = function () {\n        return this.offset() === this.message.length;\n    };\n    Parser.prototype.clonePosition = function () {\n        // This is much faster than `Object.assign` or spread.\n        return {\n            offset: this.position.offset,\n            line: this.position.line,\n            column: this.position.column,\n        };\n    };\n    /**\n     * Return the code point at the current position of the parser.\n     * Throws if the index is out of bound.\n     */\n    Parser.prototype.char = function () {\n        var offset = this.position.offset;\n        if (offset >= this.message.length) {\n            throw Error('out of bound');\n        }\n        var code = codePointAt(this.message, offset);\n        if (code === undefined) {\n            throw Error(\"Offset \".concat(offset, \" is at invalid UTF-16 code unit boundary\"));\n        }\n        return code;\n    };\n    Parser.prototype.error = function (kind, location) {\n        return {\n            val: null,\n            err: {\n                kind: kind,\n                message: this.message,\n                location: location,\n            },\n        };\n    };\n    /** Bump the parser to the next UTF-16 code unit. */\n    Parser.prototype.bump = function () {\n        if (this.isEOF()) {\n            return;\n        }\n        var code = this.char();\n        if (code === 10 /* '\\n' */) {\n            this.position.line += 1;\n            this.position.column = 1;\n            this.position.offset += 1;\n        }\n        else {\n            this.position.column += 1;\n            // 0 ~ 0x10000 -> unicode BMP, otherwise skip the surrogate pair.\n            this.position.offset += code < 0x10000 ? 1 : 2;\n        }\n    };\n    /**\n     * If the substring starting at the current position of the parser has\n     * the given prefix, then bump the parser to the character immediately\n     * following the prefix and return true. Otherwise, don't bump the parser\n     * and return false.\n     */\n    Parser.prototype.bumpIf = function (prefix) {\n        if (startsWith(this.message, prefix, this.offset())) {\n            for (var i = 0; i < prefix.length; i++) {\n                this.bump();\n            }\n            return true;\n        }\n        return false;\n    };\n    /**\n     * Bump the parser until the pattern character is found and return `true`.\n     * Otherwise bump to the end of the file and return `false`.\n     */\n    Parser.prototype.bumpUntil = function (pattern) {\n        var currentOffset = this.offset();\n        var index = this.message.indexOf(pattern, currentOffset);\n        if (index >= 0) {\n            this.bumpTo(index);\n            return true;\n        }\n        else {\n            this.bumpTo(this.message.length);\n            return false;\n        }\n    };\n    /**\n     * Bump the parser to the target offset.\n     * If target offset is beyond the end of the input, bump the parser to the end of the input.\n     */\n    Parser.prototype.bumpTo = function (targetOffset) {\n        if (this.offset() > targetOffset) {\n            throw Error(\"targetOffset \".concat(targetOffset, \" must be greater than or equal to the current offset \").concat(this.offset()));\n        }\n        targetOffset = Math.min(targetOffset, this.message.length);\n        while (true) {\n            var offset = this.offset();\n            if (offset === targetOffset) {\n                break;\n            }\n            if (offset > targetOffset) {\n                throw Error(\"targetOffset \".concat(targetOffset, \" is at invalid UTF-16 code unit boundary\"));\n            }\n            this.bump();\n            if (this.isEOF()) {\n                break;\n            }\n        }\n    };\n    /** advance the parser through all whitespace to the next non-whitespace code unit. */\n    Parser.prototype.bumpSpace = function () {\n        while (!this.isEOF() && _isWhiteSpace(this.char())) {\n            this.bump();\n        }\n    };\n    /**\n     * Peek at the *next* Unicode codepoint in the input without advancing the parser.\n     * If the input has been exhausted, then this returns null.\n     */\n    Parser.prototype.peek = function () {\n        if (this.isEOF()) {\n            return null;\n        }\n        var code = this.char();\n        var offset = this.offset();\n        var nextCode = this.message.charCodeAt(offset + (code >= 0x10000 ? 2 : 1));\n        return nextCode !== null && nextCode !== void 0 ? nextCode : null;\n    };\n    return Parser;\n}());\nexport { Parser };\n/**\n * This check if codepoint is alphabet (lower & uppercase)\n * @param codepoint\n * @returns\n */\nfunction _isAlpha(codepoint) {\n    return ((codepoint >= 97 && codepoint <= 122) ||\n        (codepoint >= 65 && codepoint <= 90));\n}\nfunction _isAlphaOrSlash(codepoint) {\n    return _isAlpha(codepoint) || codepoint === 47; /* '/' */\n}\n/** See `parseTag` function docs. */\nfunction _isPotentialElementNameChar(c) {\n    return (c === 45 /* '-' */ ||\n        c === 46 /* '.' */ ||\n        (c >= 48 && c <= 57) /* 0..9 */ ||\n        c === 95 /* '_' */ ||\n        (c >= 97 && c <= 122) /** a..z */ ||\n        (c >= 65 && c <= 90) /* A..Z */ ||\n        c == 0xb7 ||\n        (c >= 0xc0 && c <= 0xd6) ||\n        (c >= 0xd8 && c <= 0xf6) ||\n        (c >= 0xf8 && c <= 0x37d) ||\n        (c >= 0x37f && c <= 0x1fff) ||\n        (c >= 0x200c && c <= 0x200d) ||\n        (c >= 0x203f && c <= 0x2040) ||\n        (c >= 0x2070 && c <= 0x218f) ||\n        (c >= 0x2c00 && c <= 0x2fef) ||\n        (c >= 0x3001 && c <= 0xd7ff) ||\n        (c >= 0xf900 && c <= 0xfdcf) ||\n        (c >= 0xfdf0 && c <= 0xfffd) ||\n        (c >= 0x10000 && c <= 0xeffff));\n}\n/**\n * Code point equivalent of regex `\\p{White_Space}`.\n * From: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt\n */\nfunction _isWhiteSpace(c) {\n    return ((c >= 0x0009 && c <= 0x000d) ||\n        c === 0x0020 ||\n        c === 0x0085 ||\n        (c >= 0x200e && c <= 0x200f) ||\n        c === 0x2028 ||\n        c === 0x2029);\n}\n/**\n * Code point equivalent of regex `\\p{Pattern_Syntax}`.\n * See https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt\n */\nfunction _isPatternSyntax(c) {\n    return ((c >= 0x0021 && c <= 0x0023) ||\n        c === 0x0024 ||\n        (c >= 0x0025 && c <= 0x0027) ||\n        c === 0x0028 ||\n        c === 0x0029 ||\n        c === 0x002a ||\n        c === 0x002b ||\n        c === 0x002c ||\n        c === 0x002d ||\n        (c >= 0x002e && c <= 0x002f) ||\n        (c >= 0x003a && c <= 0x003b) ||\n        (c >= 0x003c && c <= 0x003e) ||\n        (c >= 0x003f && c <= 0x0040) ||\n        c === 0x005b ||\n        c === 0x005c ||\n        c === 0x005d ||\n        c === 0x005e ||\n        c === 0x0060 ||\n        c === 0x007b ||\n        c === 0x007c ||\n        c === 0x007d ||\n        c === 0x007e ||\n        c === 0x00a1 ||\n        (c >= 0x00a2 && c <= 0x00a5) ||\n        c === 0x00a6 ||\n        c === 0x00a7 ||\n        c === 0x00a9 ||\n        c === 0x00ab ||\n        c === 0x00ac ||\n        c === 0x00ae ||\n        c === 0x00b0 ||\n        c === 0x00b1 ||\n        c === 0x00b6 ||\n        c === 0x00bb ||\n        c === 0x00bf ||\n        c === 0x00d7 ||\n        c === 0x00f7 ||\n        (c >= 0x2010 && c <= 0x2015) ||\n        (c >= 0x2016 && c <= 0x2017) ||\n        c === 0x2018 ||\n        c === 0x2019 ||\n        c === 0x201a ||\n        (c >= 0x201b && c <= 0x201c) ||\n        c === 0x201d ||\n        c === 0x201e ||\n        c === 0x201f ||\n        (c >= 0x2020 && c <= 0x2027) ||\n        (c >= 0x2030 && c <= 0x2038) ||\n        c === 0x2039 ||\n        c === 0x203a ||\n        (c >= 0x203b && c <= 0x203e) ||\n        (c >= 0x2041 && c <= 0x2043) ||\n        c === 0x2044 ||\n        c === 0x2045 ||\n        c === 0x2046 ||\n        (c >= 0x2047 && c <= 0x2051) ||\n        c === 0x2052 ||\n        c === 0x2053 ||\n        (c >= 0x2055 && c <= 0x205e) ||\n        (c >= 0x2190 && c <= 0x2194) ||\n        (c >= 0x2195 && c <= 0x2199) ||\n        (c >= 0x219a && c <= 0x219b) ||\n        (c >= 0x219c && c <= 0x219f) ||\n        c === 0x21a0 ||\n        (c >= 0x21a1 && c <= 0x21a2) ||\n        c === 0x21a3 ||\n        (c >= 0x21a4 && c <= 0x21a5) ||\n        c === 0x21a6 ||\n        (c >= 0x21a7 && c <= 0x21ad) ||\n        c === 0x21ae ||\n        (c >= 0x21af && c <= 0x21cd) ||\n        (c >= 0x21ce && c <= 0x21cf) ||\n        (c >= 0x21d0 && c <= 0x21d1) ||\n        c === 0x21d2 ||\n        c === 0x21d3 ||\n        c === 0x21d4 ||\n        (c >= 0x21d5 && c <= 0x21f3) ||\n        (c >= 0x21f4 && c <= 0x22ff) ||\n        (c >= 0x2300 && c <= 0x2307) ||\n        c === 0x2308 ||\n        c === 0x2309 ||\n        c === 0x230a ||\n        c === 0x230b ||\n        (c >= 0x230c && c <= 0x231f) ||\n        (c >= 0x2320 && c <= 0x2321) ||\n        (c >= 0x2322 && c <= 0x2328) ||\n        c === 0x2329 ||\n        c === 0x232a ||\n        (c >= 0x232b && c <= 0x237b) ||\n        c === 0x237c ||\n        (c >= 0x237d && c <= 0x239a) ||\n        (c >= 0x239b && c <= 0x23b3) ||\n        (c >= 0x23b4 && c <= 0x23db) ||\n        (c >= 0x23dc && c <= 0x23e1) ||\n        (c >= 0x23e2 && c <= 0x2426) ||\n        (c >= 0x2427 && c <= 0x243f) ||\n        (c >= 0x2440 && c <= 0x244a) ||\n        (c >= 0x244b && c <= 0x245f) ||\n        (c >= 0x2500 && c <= 0x25b6) ||\n        c === 0x25b7 ||\n        (c >= 0x25b8 && c <= 0x25c0) ||\n        c === 0x25c1 ||\n        (c >= 0x25c2 && c <= 0x25f7) ||\n        (c >= 0x25f8 && c <= 0x25ff) ||\n        (c >= 0x2600 && c <= 0x266e) ||\n        c === 0x266f ||\n        (c >= 0x2670 && c <= 0x2767) ||\n        c === 0x2768 ||\n        c === 0x2769 ||\n        c === 0x276a ||\n        c === 0x276b ||\n        c === 0x276c ||\n        c === 0x276d ||\n        c === 0x276e ||\n        c === 0x276f ||\n        c === 0x2770 ||\n        c === 0x2771 ||\n        c === 0x2772 ||\n        c === 0x2773 ||\n        c === 0x2774 ||\n        c === 0x2775 ||\n        (c >= 0x2794 && c <= 0x27bf) ||\n        (c >= 0x27c0 && c <= 0x27c4) ||\n        c === 0x27c5 ||\n        c === 0x27c6 ||\n        (c >= 0x27c7 && c <= 0x27e5) ||\n        c === 0x27e6 ||\n        c === 0x27e7 ||\n        c === 0x27e8 ||\n        c === 0x27e9 ||\n        c === 0x27ea ||\n        c === 0x27eb ||\n        c === 0x27ec ||\n        c === 0x27ed ||\n        c === 0x27ee ||\n        c === 0x27ef ||\n        (c >= 0x27f0 && c <= 0x27ff) ||\n        (c >= 0x2800 && c <= 0x28ff) ||\n        (c >= 0x2900 && c <= 0x2982) ||\n        c === 0x2983 ||\n        c === 0x2984 ||\n        c === 0x2985 ||\n        c === 0x2986 ||\n        c === 0x2987 ||\n        c === 0x2988 ||\n        c === 0x2989 ||\n        c === 0x298a ||\n        c === 0x298b ||\n        c === 0x298c ||\n        c === 0x298d ||\n        c === 0x298e ||\n        c === 0x298f ||\n        c === 0x2990 ||\n        c === 0x2991 ||\n        c === 0x2992 ||\n        c === 0x2993 ||\n        c === 0x2994 ||\n        c === 0x2995 ||\n        c === 0x2996 ||\n        c === 0x2997 ||\n        c === 0x2998 ||\n        (c >= 0x2999 && c <= 0x29d7) ||\n        c === 0x29d8 ||\n        c === 0x29d9 ||\n        c === 0x29da ||\n        c === 0x29db ||\n        (c >= 0x29dc && c <= 0x29fb) ||\n        c === 0x29fc ||\n        c === 0x29fd ||\n        (c >= 0x29fe && c <= 0x2aff) ||\n        (c >= 0x2b00 && c <= 0x2b2f) ||\n        (c >= 0x2b30 && c <= 0x2b44) ||\n        (c >= 0x2b45 && c <= 0x2b46) ||\n        (c >= 0x2b47 && c <= 0x2b4c) ||\n        (c >= 0x2b4d && c <= 0x2b73) ||\n        (c >= 0x2b74 && c <= 0x2b75) ||\n        (c >= 0x2b76 && c <= 0x2b95) ||\n        c === 0x2b96 ||\n        (c >= 0x2b97 && c <= 0x2bff) ||\n        (c >= 0x2e00 && c <= 0x2e01) ||\n        c === 0x2e02 ||\n        c === 0x2e03 ||\n        c === 0x2e04 ||\n        c === 0x2e05 ||\n        (c >= 0x2e06 && c <= 0x2e08) ||\n        c === 0x2e09 ||\n        c === 0x2e0a ||\n        c === 0x2e0b ||\n        c === 0x2e0c ||\n        c === 0x2e0d ||\n        (c >= 0x2e0e && c <= 0x2e16) ||\n        c === 0x2e17 ||\n        (c >= 0x2e18 && c <= 0x2e19) ||\n        c === 0x2e1a ||\n        c === 0x2e1b ||\n        c === 0x2e1c ||\n        c === 0x2e1d ||\n        (c >= 0x2e1e && c <= 0x2e1f) ||\n        c === 0x2e20 ||\n        c === 0x2e21 ||\n        c === 0x2e22 ||\n        c === 0x2e23 ||\n        c === 0x2e24 ||\n        c === 0x2e25 ||\n        c === 0x2e26 ||\n        c === 0x2e27 ||\n        c === 0x2e28 ||\n        c === 0x2e29 ||\n        (c >= 0x2e2a && c <= 0x2e2e) ||\n        c === 0x2e2f ||\n        (c >= 0x2e30 && c <= 0x2e39) ||\n        (c >= 0x2e3a && c <= 0x2e3b) ||\n        (c >= 0x2e3c && c <= 0x2e3f) ||\n        c === 0x2e40 ||\n        c === 0x2e41 ||\n        c === 0x2e42 ||\n        (c >= 0x2e43 && c <= 0x2e4f) ||\n        (c >= 0x2e50 && c <= 0x2e51) ||\n        c === 0x2e52 ||\n        (c >= 0x2e53 && c <= 0x2e7f) ||\n        (c >= 0x3001 && c <= 0x3003) ||\n        c === 0x3008 ||\n        c === 0x3009 ||\n        c === 0x300a ||\n        c === 0x300b ||\n        c === 0x300c ||\n        c === 0x300d ||\n        c === 0x300e ||\n        c === 0x300f ||\n        c === 0x3010 ||\n        c === 0x3011 ||\n        (c >= 0x3012 && c <= 0x3013) ||\n        c === 0x3014 ||\n        c === 0x3015 ||\n        c === 0x3016 ||\n        c === 0x3017 ||\n        c === 0x3018 ||\n        c === 0x3019 ||\n        c === 0x301a ||\n        c === 0x301b ||\n        c === 0x301c ||\n        c === 0x301d ||\n        (c >= 0x301e && c <= 0x301f) ||\n        c === 0x3020 ||\n        c === 0x3030 ||\n        c === 0xfd3e ||\n        c === 0xfd3f ||\n        (c >= 0xfe45 && c <= 0xfe46));\n}\n","import { timeData } from './time-data.generated';\n/**\n * Returns the best matching date time pattern if a date time skeleton\n * pattern is provided with a locale. Follows the Unicode specification:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#table-mapping-requested-time-skeletons-to-patterns\n * @param skeleton date time skeleton pattern that possibly includes j, J or C\n * @param locale\n */\nexport function getBestPattern(skeleton, locale) {\n    var skeletonCopy = '';\n    for (var patternPos = 0; patternPos < skeleton.length; patternPos++) {\n        var patternChar = skeleton.charAt(patternPos);\n        if (patternChar === 'j') {\n            var extraLength = 0;\n            while (patternPos + 1 < skeleton.length &&\n                skeleton.charAt(patternPos + 1) === patternChar) {\n                extraLength++;\n                patternPos++;\n            }\n            var hourLen = 1 + (extraLength & 1);\n            var dayPeriodLen = extraLength < 2 ? 1 : 3 + (extraLength >> 1);\n            var dayPeriodChar = 'a';\n            var hourChar = getDefaultHourSymbolFromLocale(locale);\n            if (hourChar == 'H' || hourChar == 'k') {\n                dayPeriodLen = 0;\n            }\n            while (dayPeriodLen-- > 0) {\n                skeletonCopy += dayPeriodChar;\n            }\n            while (hourLen-- > 0) {\n                skeletonCopy = hourChar + skeletonCopy;\n            }\n        }\n        else if (patternChar === 'J') {\n            skeletonCopy += 'H';\n        }\n        else {\n            skeletonCopy += patternChar;\n        }\n    }\n    return skeletonCopy;\n}\n/**\n * Maps the [hour cycle type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle)\n * of the given `locale` to the corresponding time pattern.\n * @param locale\n */\nfunction getDefaultHourSymbolFromLocale(locale) {\n    var hourCycle = locale.hourCycle;\n    if (hourCycle === undefined &&\n        // @ts-ignore hourCycle(s) is not identified yet\n        locale.hourCycles &&\n        // @ts-ignore\n        locale.hourCycles.length) {\n        // @ts-ignore\n        hourCycle = locale.hourCycles[0];\n    }\n    if (hourCycle) {\n        switch (hourCycle) {\n            case 'h24':\n                return 'k';\n            case 'h23':\n                return 'H';\n            case 'h12':\n                return 'h';\n            case 'h11':\n                return 'K';\n            default:\n                throw new Error('Invalid hourCycle');\n        }\n    }\n    // TODO: Once hourCycle is fully supported remove the following with data generation\n    var languageTag = locale.language;\n    var regionTag;\n    if (languageTag !== 'root') {\n        regionTag = locale.maximize().region;\n    }\n    var hourCycles = timeData[regionTag || ''] ||\n        timeData[languageTag || ''] ||\n        timeData[\"\".concat(languageTag, \"-001\")] ||\n        timeData['001'];\n    return hourCycles[0];\n}\n","import { __extends } from \"tslib\";\nexport var ErrorCode;\n(function (ErrorCode) {\n    // When we have a placeholder but no value to format\n    ErrorCode[\"MISSING_VALUE\"] = \"MISSING_VALUE\";\n    // When value supplied is invalid\n    ErrorCode[\"INVALID_VALUE\"] = \"INVALID_VALUE\";\n    // When we need specific Intl API but it's not available\n    ErrorCode[\"MISSING_INTL_API\"] = \"MISSING_INTL_API\";\n})(ErrorCode || (ErrorCode = {}));\nvar FormatError = /** @class */ (function (_super) {\n    __extends(FormatError, _super);\n    function FormatError(msg, code, originalMessage) {\n        var _this = _super.call(this, msg) || this;\n        _this.code = code;\n        _this.originalMessage = originalMessage;\n        return _this;\n    }\n    FormatError.prototype.toString = function () {\n        return \"[formatjs Error: \".concat(this.code, \"] \").concat(this.message);\n    };\n    return FormatError;\n}(Error));\nexport { FormatError };\nvar InvalidValueError = /** @class */ (function (_super) {\n    __extends(InvalidValueError, _super);\n    function InvalidValueError(variableId, value, options, originalMessage) {\n        return _super.call(this, \"Invalid values for \\\"\".concat(variableId, \"\\\": \\\"\").concat(value, \"\\\". Options are \\\"\").concat(Object.keys(options).join('\", \"'), \"\\\"\"), ErrorCode.INVALID_VALUE, originalMessage) || this;\n    }\n    return InvalidValueError;\n}(FormatError));\nexport { InvalidValueError };\nvar InvalidValueTypeError = /** @class */ (function (_super) {\n    __extends(InvalidValueTypeError, _super);\n    function InvalidValueTypeError(value, type, originalMessage) {\n        return _super.call(this, \"Value for \\\"\".concat(value, \"\\\" must be of type \").concat(type), ErrorCode.INVALID_VALUE, originalMessage) || this;\n    }\n    return InvalidValueTypeError;\n}(FormatError));\nexport { InvalidValueTypeError };\nvar MissingValueError = /** @class */ (function (_super) {\n    __extends(MissingValueError, _super);\n    function MissingValueError(variableId, originalMessage) {\n        return _super.call(this, \"The intl string context variable \\\"\".concat(variableId, \"\\\" was not provided to the string \\\"\").concat(originalMessage, \"\\\"\"), ErrorCode.MISSING_VALUE, originalMessage) || this;\n    }\n    return MissingValueError;\n}(FormatError));\nexport { MissingValueError };\n","import { __assign } from \"tslib\";\nimport { ErrorKind } from './error';\nimport { Parser } from './parser';\nimport { isDateElement, isDateTimeSkeleton, isNumberElement, isNumberSkeleton, isPluralElement, isSelectElement, isTagElement, isTimeElement, } from './types';\nfunction pruneLocation(els) {\n    els.forEach(function (el) {\n        delete el.location;\n        if (isSelectElement(el) || isPluralElement(el)) {\n            for (var k in el.options) {\n                delete el.options[k].location;\n                pruneLocation(el.options[k].value);\n            }\n        }\n        else if (isNumberElement(el) && isNumberSkeleton(el.style)) {\n            delete el.style.location;\n        }\n        else if ((isDateElement(el) || isTimeElement(el)) &&\n            isDateTimeSkeleton(el.style)) {\n            delete el.style.location;\n        }\n        else if (isTagElement(el)) {\n            pruneLocation(el.children);\n        }\n    });\n}\nexport function parse(message, opts) {\n    if (opts === void 0) { opts = {}; }\n    opts = __assign({ shouldParseSkeletons: true, requiresOtherClause: true }, opts);\n    var result = new Parser(message, opts).parse();\n    if (result.err) {\n        var error = SyntaxError(ErrorKind[result.err.kind]);\n        // @ts-expect-error Assign to error object\n        error.location = result.err.location;\n        // @ts-expect-error Assign to error object\n        error.originalMessage = result.err.message;\n        throw error;\n    }\n    if (!(opts === null || opts === void 0 ? void 0 : opts.captureLocation)) {\n        pruneLocation(result.val);\n    }\n    return result.val;\n}\nexport * from './types';\n// only for testing\nexport var _Parser = Parser;\n","import { isArgumentElement, isDateElement, isDateTimeSkeleton, isLiteralElement, isNumberElement, isNumberSkeleton, isPluralElement, isPoundElement, isSelectElement, isTagElement, isTimeElement, } from '@formatjs/icu-messageformat-parser';\nimport { ErrorCode, FormatError, InvalidValueError, InvalidValueTypeError, MissingValueError, } from './error';\nexport var PART_TYPE;\n(function (PART_TYPE) {\n    PART_TYPE[PART_TYPE[\"literal\"] = 0] = \"literal\";\n    PART_TYPE[PART_TYPE[\"object\"] = 1] = \"object\";\n})(PART_TYPE || (PART_TYPE = {}));\nfunction mergeLiteral(parts) {\n    if (parts.length < 2) {\n        return parts;\n    }\n    return parts.reduce(function (all, part) {\n        var lastPart = all[all.length - 1];\n        if (!lastPart ||\n            lastPart.type !== PART_TYPE.literal ||\n            part.type !== PART_TYPE.literal) {\n            all.push(part);\n        }\n        else {\n            lastPart.value += part.value;\n        }\n        return all;\n    }, []);\n}\nexport function isFormatXMLElementFn(el) {\n    return typeof el === 'function';\n}\n// TODO(skeleton): add skeleton support\nexport function formatToParts(els, locales, formatters, formats, values, currentPluralValue, \n// For debugging\noriginalMessage) {\n    // Hot path for straight simple msg translations\n    if (els.length === 1 && isLiteralElement(els[0])) {\n        return [\n            {\n                type: PART_TYPE.literal,\n                value: els[0].value,\n            },\n        ];\n    }\n    var result = [];\n    for (var _i = 0, els_1 = els; _i < els_1.length; _i++) {\n        var el = els_1[_i];\n        // Exit early for string parts.\n        if (isLiteralElement(el)) {\n            result.push({\n                type: PART_TYPE.literal,\n                value: el.value,\n            });\n            continue;\n        }\n        // TODO: should this part be literal type?\n        // Replace `#` in plural rules with the actual numeric value.\n        if (isPoundElement(el)) {\n            if (typeof currentPluralValue === 'number') {\n                result.push({\n                    type: PART_TYPE.literal,\n                    value: formatters.getNumberFormat(locales).format(currentPluralValue),\n                });\n            }\n            continue;\n        }\n        var varName = el.value;\n        // Enforce that all required values are provided by the caller.\n        if (!(values && varName in values)) {\n            throw new MissingValueError(varName, originalMessage);\n        }\n        var value = values[varName];\n        if (isArgumentElement(el)) {\n            if (!value || typeof value === 'string' || typeof value === 'number') {\n                value =\n                    typeof value === 'string' || typeof value === 'number'\n                        ? String(value)\n                        : '';\n            }\n            result.push({\n                type: typeof value === 'string' ? PART_TYPE.literal : PART_TYPE.object,\n                value: value,\n            });\n            continue;\n        }\n        // Recursively format plural and select parts' option — which can be a\n        // nested pattern structure. The choosing of the option to use is\n        // abstracted-by and delegated-to the part helper object.\n        if (isDateElement(el)) {\n            var style = typeof el.style === 'string'\n                ? formats.date[el.style]\n                : isDateTimeSkeleton(el.style)\n                    ? el.style.parsedOptions\n                    : undefined;\n            result.push({\n                type: PART_TYPE.literal,\n                value: formatters\n                    .getDateTimeFormat(locales, style)\n                    .format(value),\n            });\n            continue;\n        }\n        if (isTimeElement(el)) {\n            var style = typeof el.style === 'string'\n                ? formats.time[el.style]\n                : isDateTimeSkeleton(el.style)\n                    ? el.style.parsedOptions\n                    : formats.time.medium;\n            result.push({\n                type: PART_TYPE.literal,\n                value: formatters\n                    .getDateTimeFormat(locales, style)\n                    .format(value),\n            });\n            continue;\n        }\n        if (isNumberElement(el)) {\n            var style = typeof el.style === 'string'\n                ? formats.number[el.style]\n                : isNumberSkeleton(el.style)\n                    ? el.style.parsedOptions\n                    : undefined;\n            if (style && style.scale) {\n                value =\n                    value *\n                        (style.scale || 1);\n            }\n            result.push({\n                type: PART_TYPE.literal,\n                value: formatters\n                    .getNumberFormat(locales, style)\n                    .format(value),\n            });\n            continue;\n        }\n        if (isTagElement(el)) {\n            var children = el.children, value_1 = el.value;\n            var formatFn = values[value_1];\n            if (!isFormatXMLElementFn(formatFn)) {\n                throw new InvalidValueTypeError(value_1, 'function', originalMessage);\n            }\n            var parts = formatToParts(children, locales, formatters, formats, values, currentPluralValue);\n            var chunks = formatFn(parts.map(function (p) { return p.value; }));\n            if (!Array.isArray(chunks)) {\n                chunks = [chunks];\n            }\n            result.push.apply(result, chunks.map(function (c) {\n                return {\n                    type: typeof c === 'string' ? PART_TYPE.literal : PART_TYPE.object,\n                    value: c,\n                };\n            }));\n        }\n        if (isSelectElement(el)) {\n            var opt = el.options[value] || el.options.other;\n            if (!opt) {\n                throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);\n            }\n            result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values));\n            continue;\n        }\n        if (isPluralElement(el)) {\n            var opt = el.options[\"=\".concat(value)];\n            if (!opt) {\n                if (!Intl.PluralRules) {\n                    throw new FormatError(\"Intl.PluralRules is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-pluralrules\\\"\\n\", ErrorCode.MISSING_INTL_API, originalMessage);\n                }\n                var rule = formatters\n                    .getPluralRules(locales, { type: el.pluralType })\n                    .select(value - (el.offset || 0));\n                opt = el.options[rule] || el.options.other;\n            }\n            if (!opt) {\n                throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);\n            }\n            result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values, value - (el.offset || 0)));\n            continue;\n        }\n    }\n    return mergeLiteral(result);\n}\n","/*\nCopyright (c) 2014, Yahoo! Inc. All rights reserved.\nCopyrights licensed under the New BSD License.\nSee the accompanying LICENSE file for terms.\n*/\nimport { __assign, __rest, __spreadArray } from \"tslib\";\nimport { memoize, strategies } from '@formatjs/fast-memoize';\nimport { parse, } from '@formatjs/icu-messageformat-parser';\nimport { formatToParts, PART_TYPE, } from './formatters';\n// -- MessageFormat --------------------------------------------------------\nfunction mergeConfig(c1, c2) {\n    if (!c2) {\n        return c1;\n    }\n    return __assign(__assign(__assign({}, (c1 || {})), (c2 || {})), Object.keys(c1).reduce(function (all, k) {\n        all[k] = __assign(__assign({}, c1[k]), (c2[k] || {}));\n        return all;\n    }, {}));\n}\nfunction mergeConfigs(defaultConfig, configs) {\n    if (!configs) {\n        return defaultConfig;\n    }\n    return Object.keys(defaultConfig).reduce(function (all, k) {\n        all[k] = mergeConfig(defaultConfig[k], configs[k]);\n        return all;\n    }, __assign({}, defaultConfig));\n}\nfunction createFastMemoizeCache(store) {\n    return {\n        create: function () {\n            return {\n                get: function (key) {\n                    return store[key];\n                },\n                set: function (key, value) {\n                    store[key] = value;\n                },\n            };\n        },\n    };\n}\nfunction createDefaultFormatters(cache) {\n    if (cache === void 0) { cache = {\n        number: {},\n        dateTime: {},\n        pluralRules: {},\n    }; }\n    return {\n        getNumberFormat: memoize(function () {\n            var _a;\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n        }, {\n            cache: createFastMemoizeCache(cache.number),\n            strategy: strategies.variadic,\n        }),\n        getDateTimeFormat: memoize(function () {\n            var _a;\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n        }, {\n            cache: createFastMemoizeCache(cache.dateTime),\n            strategy: strategies.variadic,\n        }),\n        getPluralRules: memoize(function () {\n            var _a;\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArray([void 0], args, false)))();\n        }, {\n            cache: createFastMemoizeCache(cache.pluralRules),\n            strategy: strategies.variadic,\n        }),\n    };\n}\nvar IntlMessageFormat = /** @class */ (function () {\n    function IntlMessageFormat(message, locales, overrideFormats, opts) {\n        if (locales === void 0) { locales = IntlMessageFormat.defaultLocale; }\n        var _this = this;\n        this.formatterCache = {\n            number: {},\n            dateTime: {},\n            pluralRules: {},\n        };\n        this.format = function (values) {\n            var parts = _this.formatToParts(values);\n            // Hot path for straight simple msg translations\n            if (parts.length === 1) {\n                return parts[0].value;\n            }\n            var result = parts.reduce(function (all, part) {\n                if (!all.length ||\n                    part.type !== PART_TYPE.literal ||\n                    typeof all[all.length - 1] !== 'string') {\n                    all.push(part.value);\n                }\n                else {\n                    all[all.length - 1] += part.value;\n                }\n                return all;\n            }, []);\n            if (result.length <= 1) {\n                return result[0] || '';\n            }\n            return result;\n        };\n        this.formatToParts = function (values) {\n            return formatToParts(_this.ast, _this.locales, _this.formatters, _this.formats, values, undefined, _this.message);\n        };\n        this.resolvedOptions = function () {\n            var _a;\n            return ({\n                locale: ((_a = _this.resolvedLocale) === null || _a === void 0 ? void 0 : _a.toString()) ||\n                    Intl.NumberFormat.supportedLocalesOf(_this.locales)[0],\n            });\n        };\n        this.getAst = function () { return _this.ast; };\n        // Defined first because it's used to build the format pattern.\n        this.locales = locales;\n        this.resolvedLocale = IntlMessageFormat.resolveLocale(locales);\n        if (typeof message === 'string') {\n            this.message = message;\n            if (!IntlMessageFormat.__parse) {\n                throw new TypeError('IntlMessageFormat.__parse must be set to process `message` of type `string`');\n            }\n            var _a = opts || {}, formatters = _a.formatters, parseOpts = __rest(_a, [\"formatters\"]);\n            // Parse string messages into an AST.\n            this.ast = IntlMessageFormat.__parse(message, __assign(__assign({}, parseOpts), { locale: this.resolvedLocale }));\n        }\n        else {\n            this.ast = message;\n        }\n        if (!Array.isArray(this.ast)) {\n            throw new TypeError('A message must be provided as a String or AST.');\n        }\n        // Creates a new object with the specified `formats` merged with the default\n        // formats.\n        this.formats = mergeConfigs(IntlMessageFormat.formats, overrideFormats);\n        this.formatters =\n            (opts && opts.formatters) || createDefaultFormatters(this.formatterCache);\n    }\n    Object.defineProperty(IntlMessageFormat, \"defaultLocale\", {\n        get: function () {\n            if (!IntlMessageFormat.memoizedDefaultLocale) {\n                IntlMessageFormat.memoizedDefaultLocale =\n                    new Intl.NumberFormat().resolvedOptions().locale;\n            }\n            return IntlMessageFormat.memoizedDefaultLocale;\n        },\n        enumerable: false,\n        configurable: true\n    });\n    IntlMessageFormat.memoizedDefaultLocale = null;\n    IntlMessageFormat.resolveLocale = function (locales) {\n        if (typeof Intl.Locale === 'undefined') {\n            return;\n        }\n        var supportedLocales = Intl.NumberFormat.supportedLocalesOf(locales);\n        if (supportedLocales.length > 0) {\n            return new Intl.Locale(supportedLocales[0]);\n        }\n        return new Intl.Locale(typeof locales === 'string' ? locales : locales[0]);\n    };\n    IntlMessageFormat.__parse = parse;\n    // Default format options used as the prototype of the `formats` provided to the\n    // constructor. These are used when constructing the internal Intl.NumberFormat\n    // and Intl.DateTimeFormat instances.\n    IntlMessageFormat.formats = {\n        number: {\n            integer: {\n                maximumFractionDigits: 0,\n            },\n            currency: {\n                style: 'currency',\n            },\n            percent: {\n                style: 'percent',\n            },\n        },\n        date: {\n            short: {\n                month: 'numeric',\n                day: 'numeric',\n                year: '2-digit',\n            },\n            medium: {\n                month: 'short',\n                day: 'numeric',\n                year: 'numeric',\n            },\n            long: {\n                month: 'long',\n                day: 'numeric',\n                year: 'numeric',\n            },\n            full: {\n                weekday: 'long',\n                month: 'long',\n                day: 'numeric',\n                year: 'numeric',\n            },\n        },\n        time: {\n            short: {\n                hour: 'numeric',\n                minute: 'numeric',\n            },\n            medium: {\n                hour: 'numeric',\n                minute: 'numeric',\n                second: 'numeric',\n            },\n            long: {\n                hour: 'numeric',\n                minute: 'numeric',\n                second: 'numeric',\n                timeZoneName: 'short',\n            },\n            full: {\n                hour: 'numeric',\n                minute: 'numeric',\n                second: 'numeric',\n                timeZoneName: 'short',\n            },\n        },\n    };\n    return IntlMessageFormat;\n}());\nexport { IntlMessageFormat };\n","import { __extends } from \"tslib\";\nexport var IntlErrorCode;\n(function (IntlErrorCode) {\n    IntlErrorCode[\"FORMAT_ERROR\"] = \"FORMAT_ERROR\";\n    IntlErrorCode[\"UNSUPPORTED_FORMATTER\"] = \"UNSUPPORTED_FORMATTER\";\n    IntlErrorCode[\"INVALID_CONFIG\"] = \"INVALID_CONFIG\";\n    IntlErrorCode[\"MISSING_DATA\"] = \"MISSING_DATA\";\n    IntlErrorCode[\"MISSING_TRANSLATION\"] = \"MISSING_TRANSLATION\";\n})(IntlErrorCode || (IntlErrorCode = {}));\nvar IntlError = /** @class */ (function (_super) {\n    __extends(IntlError, _super);\n    function IntlError(code, message, exception) {\n        var _this = this;\n        var err = exception\n            ? exception instanceof Error\n                ? exception\n                : new Error(String(exception))\n            : undefined;\n        _this = _super.call(this, \"[@formatjs/intl Error \".concat(code, \"] \").concat(message, \"\\n\").concat(err ? \"\\n\".concat(err.message, \"\\n\").concat(err.stack) : '')) || this;\n        _this.code = code;\n        // @ts-ignore just so we don't need to declare dep on @types/node\n        if (typeof Error.captureStackTrace === 'function') {\n            // @ts-ignore just so we don't need to declare dep on @types/node\n            Error.captureStackTrace(_this, IntlError);\n        }\n        return _this;\n    }\n    return IntlError;\n}(Error));\nexport { IntlError };\nvar UnsupportedFormatterError = /** @class */ (function (_super) {\n    __extends(UnsupportedFormatterError, _super);\n    function UnsupportedFormatterError(message, exception) {\n        return _super.call(this, IntlErrorCode.UNSUPPORTED_FORMATTER, message, exception) || this;\n    }\n    return UnsupportedFormatterError;\n}(IntlError));\nexport { UnsupportedFormatterError };\nvar InvalidConfigError = /** @class */ (function (_super) {\n    __extends(InvalidConfigError, _super);\n    function InvalidConfigError(message, exception) {\n        return _super.call(this, IntlErrorCode.INVALID_CONFIG, message, exception) || this;\n    }\n    return InvalidConfigError;\n}(IntlError));\nexport { InvalidConfigError };\nvar MissingDataError = /** @class */ (function (_super) {\n    __extends(MissingDataError, _super);\n    function MissingDataError(message, exception) {\n        return _super.call(this, IntlErrorCode.MISSING_DATA, message, exception) || this;\n    }\n    return MissingDataError;\n}(IntlError));\nexport { MissingDataError };\nvar IntlFormatError = /** @class */ (function (_super) {\n    __extends(IntlFormatError, _super);\n    function IntlFormatError(message, locale, exception) {\n        var _this = _super.call(this, IntlErrorCode.FORMAT_ERROR, \"\".concat(message, \"\\nLocale: \").concat(locale, \"\\n\"), exception) || this;\n        _this.locale = locale;\n        return _this;\n    }\n    return IntlFormatError;\n}(IntlError));\nexport { IntlFormatError };\nvar MessageFormatError = /** @class */ (function (_super) {\n    __extends(MessageFormatError, _super);\n    function MessageFormatError(message, locale, descriptor, exception) {\n        var _this = _super.call(this, \"\".concat(message, \"\\nMessageID: \").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.id, \"\\nDefault Message: \").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.defaultMessage, \"\\nDescription: \").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.description, \"\\n\"), locale, exception) || this;\n        _this.descriptor = descriptor;\n        _this.locale = locale;\n        return _this;\n    }\n    return MessageFormatError;\n}(IntlFormatError));\nexport { MessageFormatError };\nvar MissingTranslationError = /** @class */ (function (_super) {\n    __extends(MissingTranslationError, _super);\n    function MissingTranslationError(descriptor, locale) {\n        var _this = _super.call(this, IntlErrorCode.MISSING_TRANSLATION, \"Missing message: \\\"\".concat(descriptor.id, \"\\\" for locale \\\"\").concat(locale, \"\\\", using \").concat(descriptor.defaultMessage\n            ? \"default message (\".concat(typeof descriptor.defaultMessage === 'string'\n                ? descriptor.defaultMessage\n                : descriptor.defaultMessage\n                    .map(function (e) { var _a; return (_a = e.value) !== null && _a !== void 0 ? _a : JSON.stringify(e); })\n                    .join(), \")\")\n            : 'id', \" as fallback.\")) || this;\n        _this.descriptor = descriptor;\n        return _this;\n    }\n    return MissingTranslationError;\n}(IntlError));\nexport { MissingTranslationError };\n","import { __assign, __spreadArray } from \"tslib\";\nimport { IntlMessageFormat } from 'intl-messageformat';\nimport { memoize, strategies } from '@formatjs/fast-memoize';\nimport { UnsupportedFormatterError } from './error';\nexport function filterProps(props, allowlist, defaults) {\n    if (defaults === void 0) { defaults = {}; }\n    return allowlist.reduce(function (filtered, name) {\n        if (name in props) {\n            filtered[name] = props[name];\n        }\n        else if (name in defaults) {\n            filtered[name] = defaults[name];\n        }\n        return filtered;\n    }, {});\n}\nvar defaultErrorHandler = function (error) {\n    // @ts-ignore just so we don't need to declare dep on @types/node\n    if (process.env.NODE_ENV !== 'production') {\n        console.error(error);\n    }\n};\nvar defaultWarnHandler = function (warning) {\n    // @ts-ignore just so we don't need to declare dep on @types/node\n    if (process.env.NODE_ENV !== 'production') {\n        console.warn(warning);\n    }\n};\nexport var DEFAULT_INTL_CONFIG = {\n    formats: {},\n    messages: {},\n    timeZone: undefined,\n    defaultLocale: 'en',\n    defaultFormats: {},\n    fallbackOnEmptyString: true,\n    onError: defaultErrorHandler,\n    onWarn: defaultWarnHandler,\n};\nexport function createIntlCache() {\n    return {\n        dateTime: {},\n        number: {},\n        message: {},\n        relativeTime: {},\n        pluralRules: {},\n        list: {},\n        displayNames: {},\n    };\n}\nfunction createFastMemoizeCache(store) {\n    return {\n        create: function () {\n            return {\n                get: function (key) {\n                    return store[key];\n                },\n                set: function (key, value) {\n                    store[key] = value;\n                },\n            };\n        },\n    };\n}\n/**\n * Create intl formatters and populate cache\n * @param cache explicit cache to prevent leaking memory\n */\nexport function createFormatters(cache) {\n    if (cache === void 0) { cache = createIntlCache(); }\n    var RelativeTimeFormat = Intl.RelativeTimeFormat;\n    var ListFormat = Intl.ListFormat;\n    var DisplayNames = Intl.DisplayNames;\n    var getDateTimeFormat = memoize(function () {\n        var _a;\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n    }, {\n        cache: createFastMemoizeCache(cache.dateTime),\n        strategy: strategies.variadic,\n    });\n    var getNumberFormat = memoize(function () {\n        var _a;\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n    }, {\n        cache: createFastMemoizeCache(cache.number),\n        strategy: strategies.variadic,\n    });\n    var getPluralRules = memoize(function () {\n        var _a;\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i] = arguments[_i];\n        }\n        return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArray([void 0], args, false)))();\n    }, {\n        cache: createFastMemoizeCache(cache.pluralRules),\n        strategy: strategies.variadic,\n    });\n    return {\n        getDateTimeFormat: getDateTimeFormat,\n        getNumberFormat: getNumberFormat,\n        getMessageFormat: memoize(function (message, locales, overrideFormats, opts) {\n            return new IntlMessageFormat(message, locales, overrideFormats, __assign({ formatters: {\n                    getNumberFormat: getNumberFormat,\n                    getDateTimeFormat: getDateTimeFormat,\n                    getPluralRules: getPluralRules,\n                } }, (opts || {})));\n        }, {\n            cache: createFastMemoizeCache(cache.message),\n            strategy: strategies.variadic,\n        }),\n        getRelativeTimeFormat: memoize(function () {\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            return new (RelativeTimeFormat.bind.apply(RelativeTimeFormat, __spreadArray([void 0], args, false)))();\n        }, {\n            cache: createFastMemoizeCache(cache.relativeTime),\n            strategy: strategies.variadic,\n        }),\n        getPluralRules: getPluralRules,\n        getListFormat: memoize(function () {\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            return new (ListFormat.bind.apply(ListFormat, __spreadArray([void 0], args, false)))();\n        }, {\n            cache: createFastMemoizeCache(cache.list),\n            strategy: strategies.variadic,\n        }),\n        getDisplayNames: memoize(function () {\n            var args = [];\n            for (var _i = 0; _i < arguments.length; _i++) {\n                args[_i] = arguments[_i];\n            }\n            return new (DisplayNames.bind.apply(DisplayNames, __spreadArray([void 0], args, false)))();\n        }, {\n            cache: createFastMemoizeCache(cache.displayNames),\n            strategy: strategies.variadic,\n        }),\n    };\n}\nexport function getNamedFormat(formats, type, name, onError) {\n    var formatType = formats && formats[type];\n    var format;\n    if (formatType) {\n        format = formatType[name];\n    }\n    if (format) {\n        return format;\n    }\n    onError(new UnsupportedFormatterError(\"No \".concat(type, \" format named: \").concat(name)));\n}\n","import { __assign } from \"tslib\";\nimport { invariant } from '@formatjs/ecma402-abstract';\nimport { IntlMessageFormat, } from 'intl-messageformat';\nimport { MissingTranslationError, MessageFormatError } from './error';\nimport { TYPE } from '@formatjs/icu-messageformat-parser';\nfunction setTimeZoneInOptions(opts, timeZone) {\n    return Object.keys(opts).reduce(function (all, k) {\n        all[k] = __assign({ timeZone: timeZone }, opts[k]);\n        return all;\n    }, {});\n}\nfunction deepMergeOptions(opts1, opts2) {\n    var keys = Object.keys(__assign(__assign({}, opts1), opts2));\n    return keys.reduce(function (all, k) {\n        all[k] = __assign(__assign({}, (opts1[k] || {})), (opts2[k] || {}));\n        return all;\n    }, {});\n}\nfunction deepMergeFormatsAndSetTimeZone(f1, timeZone) {\n    if (!timeZone) {\n        return f1;\n    }\n    var mfFormats = IntlMessageFormat.formats;\n    return __assign(__assign(__assign({}, mfFormats), f1), { date: deepMergeOptions(setTimeZoneInOptions(mfFormats.date, timeZone), setTimeZoneInOptions(f1.date || {}, timeZone)), time: deepMergeOptions(setTimeZoneInOptions(mfFormats.time, timeZone), setTimeZoneInOptions(f1.time || {}, timeZone)) });\n}\nexport var formatMessage = function (_a, state, messageDescriptor, values, opts) {\n    var locale = _a.locale, formats = _a.formats, messages = _a.messages, defaultLocale = _a.defaultLocale, defaultFormats = _a.defaultFormats, fallbackOnEmptyString = _a.fallbackOnEmptyString, onError = _a.onError, timeZone = _a.timeZone, defaultRichTextElements = _a.defaultRichTextElements;\n    if (messageDescriptor === void 0) { messageDescriptor = { id: '' }; }\n    var msgId = messageDescriptor.id, defaultMessage = messageDescriptor.defaultMessage;\n    // `id` is a required field of a Message Descriptor.\n    invariant(!!msgId, \"[@formatjs/intl] An `id` must be provided to format a message. You can either:\\n1. Configure your build toolchain with [babel-plugin-formatjs](https://formatjs.io/docs/tooling/babel-plugin)\\nor [@formatjs/ts-transformer](https://formatjs.io/docs/tooling/ts-transformer) OR\\n2. Configure your `eslint` config to include [eslint-plugin-formatjs](https://formatjs.io/docs/tooling/linter#enforce-id)\\nto autofix this issue\");\n    var id = String(msgId);\n    var message = \n    // In case messages is Object.create(null)\n    // e.g import('foo.json') from webpack)\n    // See https://github.com/formatjs/formatjs/issues/1914\n    messages &&\n        Object.prototype.hasOwnProperty.call(messages, id) &&\n        messages[id];\n    // IMPORTANT: Hot path if `message` is AST with a single literal node\n    if (Array.isArray(message) &&\n        message.length === 1 &&\n        message[0].type === TYPE.literal) {\n        return message[0].value;\n    }\n    // IMPORTANT: Hot path straight lookup for performance\n    if (!values &&\n        message &&\n        typeof message === 'string' &&\n        !defaultRichTextElements) {\n        return message.replace(/'\\{(.*?)\\}'/gi, \"{$1}\");\n    }\n    values = __assign(__assign({}, defaultRichTextElements), (values || {}));\n    formats = deepMergeFormatsAndSetTimeZone(formats, timeZone);\n    defaultFormats = deepMergeFormatsAndSetTimeZone(defaultFormats, timeZone);\n    if (!message) {\n        if (fallbackOnEmptyString === false && message === '') {\n            return message;\n        }\n        if (!defaultMessage ||\n            (locale && locale.toLowerCase() !== defaultLocale.toLowerCase())) {\n            // This prevents warnings from littering the console in development\n            // when no `messages` are passed into the <IntlProvider> for the\n            // default locale.\n            onError(new MissingTranslationError(messageDescriptor, locale));\n        }\n        if (defaultMessage) {\n            try {\n                var formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats, opts);\n                return formatter.format(values);\n            }\n            catch (e) {\n                onError(new MessageFormatError(\"Error formatting default message for: \\\"\".concat(id, \"\\\", rendering default message verbatim\"), locale, messageDescriptor, e));\n                return typeof defaultMessage === 'string' ? defaultMessage : id;\n            }\n        }\n        return id;\n    }\n    // We have the translated message\n    try {\n        var formatter = state.getMessageFormat(message, locale, formats, __assign({ formatters: state }, (opts || {})));\n        return formatter.format(values);\n    }\n    catch (e) {\n        onError(new MessageFormatError(\"Error formatting message: \\\"\".concat(id, \"\\\", using \").concat(defaultMessage ? 'default message' : 'id', \" as fallback.\"), locale, messageDescriptor, e));\n    }\n    if (defaultMessage) {\n        try {\n            var formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats, opts);\n            return formatter.format(values);\n        }\n        catch (e) {\n            onError(new MessageFormatError(\"Error formatting the default message for: \\\"\".concat(id, \"\\\", rendering message verbatim\"), locale, messageDescriptor, e));\n        }\n    }\n    if (typeof message === 'string') {\n        return message;\n    }\n    if (typeof defaultMessage === 'string') {\n        return defaultMessage;\n    }\n    return id;\n};\n","import { __spreadArray } from \"tslib\";\nimport { memoize, strategies } from '@formatjs/fast-memoize';\n/**\n * Cannot do Math.log(x) / Math.log(10) bc if IEEE floating point issue\n * @param x number\n */\nexport function getMagnitude(x) {\n    // Cannot count string length via Number.toString because it may use scientific notation\n    // for very small or very large numbers.\n    return Math.floor(Math.log(x) * Math.LOG10E);\n}\nexport function repeat(s, times) {\n    if (typeof s.repeat === 'function') {\n        return s.repeat(times);\n    }\n    var arr = new Array(times);\n    for (var i = 0; i < arr.length; i++) {\n        arr[i] = s;\n    }\n    return arr.join('');\n}\nexport function setInternalSlot(map, pl, field, value) {\n    if (!map.get(pl)) {\n        map.set(pl, Object.create(null));\n    }\n    var slots = map.get(pl);\n    slots[field] = value;\n}\nexport function setMultiInternalSlots(map, pl, props) {\n    for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {\n        var k = _a[_i];\n        setInternalSlot(map, pl, k, props[k]);\n    }\n}\nexport function getInternalSlot(map, pl, field) {\n    return getMultiInternalSlots(map, pl, field)[field];\n}\nexport function getMultiInternalSlots(map, pl) {\n    var fields = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        fields[_i - 2] = arguments[_i];\n    }\n    var slots = map.get(pl);\n    if (!slots) {\n        throw new TypeError(\"\".concat(pl, \" InternalSlot has not been initialized\"));\n    }\n    return fields.reduce(function (all, f) {\n        all[f] = slots[f];\n        return all;\n    }, Object.create(null));\n}\nexport function isLiteralPart(patternPart) {\n    return patternPart.type === 'literal';\n}\n/*\n  17 ECMAScript Standard Built-in Objects:\n    Every built-in Function object, including constructors, that is not\n    identified as an anonymous function has a name property whose value\n    is a String.\n\n    Unless otherwise specified, the name property of a built-in Function\n    object, if it exists, has the attributes { [[Writable]]: false,\n    [[Enumerable]]: false, [[Configurable]]: true }.\n*/\nexport function defineProperty(target, name, _a) {\n    var value = _a.value;\n    Object.defineProperty(target, name, {\n        configurable: true,\n        enumerable: false,\n        writable: true,\n        value: value,\n    });\n}\n/**\n * 7.3.5 CreateDataProperty\n * @param target\n * @param name\n * @param value\n */\nexport function createDataProperty(target, name, value) {\n    Object.defineProperty(target, name, {\n        configurable: true,\n        enumerable: true,\n        writable: true,\n        value: value,\n    });\n}\nexport var UNICODE_EXTENSION_SEQUENCE_REGEX = /-u(?:-[0-9a-z]{2,8})+/gi;\nexport function invariant(condition, message, Err) {\n    if (Err === void 0) { Err = Error; }\n    if (!condition) {\n        throw new Err(message);\n    }\n}\nexport var createMemoizedNumberFormat = memoize(function () {\n    var _a;\n    var args = [];\n    for (var _i = 0; _i < arguments.length; _i++) {\n        args[_i] = arguments[_i];\n    }\n    return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n}, {\n    strategy: strategies.variadic,\n});\nexport var createMemoizedDateTimeFormat = memoize(function () {\n    var _a;\n    var args = [];\n    for (var _i = 0; _i < arguments.length; _i++) {\n        args[_i] = arguments[_i];\n    }\n    return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n}, {\n    strategy: strategies.variadic,\n});\nexport var createMemoizedPluralRules = memoize(function () {\n    var _a;\n    var args = [];\n    for (var _i = 0; _i < arguments.length; _i++) {\n        args[_i] = arguments[_i];\n    }\n    return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArray([void 0], args, false)))();\n}, {\n    strategy: strategies.variadic,\n});\nexport var createMemoizedLocale = memoize(function () {\n    var _a;\n    var args = [];\n    for (var _i = 0; _i < arguments.length; _i++) {\n        args[_i] = arguments[_i];\n    }\n    return new ((_a = Intl.Locale).bind.apply(_a, __spreadArray([void 0], args, false)))();\n}, {\n    strategy: strategies.variadic,\n});\nexport var createMemoizedListFormat = memoize(function () {\n    var _a;\n    var args = [];\n    for (var _i = 0; _i < arguments.length; _i++) {\n        args[_i] = arguments[_i];\n    }\n    return new ((_a = Intl.ListFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n}, {\n    strategy: strategies.variadic,\n});\n","import { __assign } from \"tslib\";\nimport { filterProps, getNamedFormat } from './utils';\nimport { IntlFormatError } from './error';\nvar DATE_TIME_FORMAT_OPTIONS = [\n    'formatMatcher',\n    'timeZone',\n    'hour12',\n    'weekday',\n    'era',\n    'year',\n    'month',\n    'day',\n    'hour',\n    'minute',\n    'second',\n    'timeZoneName',\n    'hourCycle',\n    'dateStyle',\n    'timeStyle',\n    'calendar',\n    // 'dayPeriod',\n    'numberingSystem',\n    'fractionalSecondDigits',\n];\nexport function getFormatter(_a, type, getDateTimeFormat, options) {\n    var locale = _a.locale, formats = _a.formats, onError = _a.onError, timeZone = _a.timeZone;\n    if (options === void 0) { options = {}; }\n    var format = options.format;\n    var defaults = __assign(__assign({}, (timeZone && { timeZone: timeZone })), (format && getNamedFormat(formats, type, format, onError)));\n    var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, defaults);\n    if (type === 'time' &&\n        !filteredOptions.hour &&\n        !filteredOptions.minute &&\n        !filteredOptions.second &&\n        !filteredOptions.timeStyle &&\n        !filteredOptions.dateStyle) {\n        // Add default formatting options if hour, minute, or second isn't defined.\n        filteredOptions = __assign(__assign({}, filteredOptions), { hour: 'numeric', minute: 'numeric' });\n    }\n    return getDateTimeFormat(locale, filteredOptions);\n}\nexport function formatDate(config, getDateTimeFormat) {\n    var _a = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        _a[_i - 2] = arguments[_i];\n    }\n    var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n    var date = typeof value === 'string' ? new Date(value || 0) : value;\n    try {\n        return getFormatter(config, 'date', getDateTimeFormat, options).format(date);\n    }\n    catch (e) {\n        config.onError(new IntlFormatError('Error formatting date.', config.locale, e));\n    }\n    return String(date);\n}\nexport function formatTime(config, getDateTimeFormat) {\n    var _a = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        _a[_i - 2] = arguments[_i];\n    }\n    var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n    var date = typeof value === 'string' ? new Date(value || 0) : value;\n    try {\n        return getFormatter(config, 'time', getDateTimeFormat, options).format(date);\n    }\n    catch (e) {\n        config.onError(new IntlFormatError('Error formatting time.', config.locale, e));\n    }\n    return String(date);\n}\nexport function formatDateTimeRange(config, getDateTimeFormat) {\n    var _a = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        _a[_i - 2] = arguments[_i];\n    }\n    var from = _a[0], to = _a[1], _b = _a[2], options = _b === void 0 ? {} : _b;\n    var timeZone = config.timeZone, locale = config.locale, onError = config.onError;\n    var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, timeZone ? { timeZone: timeZone } : {});\n    try {\n        return getDateTimeFormat(locale, filteredOptions).formatRange(from, to);\n    }\n    catch (e) {\n        onError(new IntlFormatError('Error formatting date time range.', config.locale, e));\n    }\n    return String(from);\n}\nexport function formatDateToParts(config, getDateTimeFormat) {\n    var _a = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        _a[_i - 2] = arguments[_i];\n    }\n    var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n    var date = typeof value === 'string' ? new Date(value || 0) : value;\n    try {\n        return getFormatter(config, 'date', getDateTimeFormat, options).formatToParts(date); // TODO: remove this when https://github.com/microsoft/TypeScript/pull/50402 is merged\n    }\n    catch (e) {\n        config.onError(new IntlFormatError('Error formatting date.', config.locale, e));\n    }\n    return [];\n}\nexport function formatTimeToParts(config, getDateTimeFormat) {\n    var _a = [];\n    for (var _i = 2; _i < arguments.length; _i++) {\n        _a[_i - 2] = arguments[_i];\n    }\n    var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n    var date = typeof value === 'string' ? new Date(value || 0) : value;\n    try {\n        return getFormatter(config, 'time', getDateTimeFormat, options).formatToParts(date); // TODO: remove this when https://github.com/microsoft/TypeScript/pull/50402 is merged\n    }\n    catch (e) {\n        config.onError(new IntlFormatError('Error formatting time.', config.locale, e));\n    }\n    return [];\n}\n","import { filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar DISPLAY_NAMES_OPTONS = [\n    'style',\n    'type',\n    'fallback',\n    'languageDisplay',\n];\nexport function formatDisplayName(_a, getDisplayNames, value, options) {\n    var locale = _a.locale, onError = _a.onError;\n    var DisplayNames = Intl.DisplayNames;\n    if (!DisplayNames) {\n        onError(new FormatError(\"Intl.DisplayNames is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-displaynames\\\"\\n\", ErrorCode.MISSING_INTL_API));\n    }\n    var filteredOptions = filterProps(options, DISPLAY_NAMES_OPTONS);\n    try {\n        return getDisplayNames(locale, filteredOptions).of(value);\n    }\n    catch (e) {\n        onError(new IntlFormatError('Error formatting display name.', locale, e));\n    }\n}\n","import { __assign } from \"tslib\";\nimport { filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar LIST_FORMAT_OPTIONS = [\n    'type',\n    'style',\n];\nvar now = Date.now();\nfunction generateToken(i) {\n    return \"\".concat(now, \"_\").concat(i, \"_\").concat(now);\n}\nexport function formatList(opts, getListFormat, values, options) {\n    if (options === void 0) { options = {}; }\n    var results = formatListToParts(opts, getListFormat, values, options).reduce(function (all, el) {\n        var val = el.value;\n        if (typeof val !== 'string') {\n            all.push(val);\n        }\n        else if (typeof all[all.length - 1] === 'string') {\n            all[all.length - 1] += val;\n        }\n        else {\n            all.push(val);\n        }\n        return all;\n    }, []);\n    return results.length === 1 ? results[0] : results.length === 0 ? '' : results;\n}\nexport function formatListToParts(_a, getListFormat, values, options) {\n    var locale = _a.locale, onError = _a.onError;\n    if (options === void 0) { options = {}; }\n    var ListFormat = Intl.ListFormat;\n    if (!ListFormat) {\n        onError(new FormatError(\"Intl.ListFormat is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-listformat\\\"\\n\", ErrorCode.MISSING_INTL_API));\n    }\n    var filteredOptions = filterProps(options, LIST_FORMAT_OPTIONS);\n    try {\n        var richValues_1 = {};\n        var serializedValues = values.map(function (v, i) {\n            if (typeof v === 'object') {\n                var id = generateToken(i);\n                richValues_1[id] = v;\n                return id;\n            }\n            return String(v);\n        });\n        return getListFormat(locale, filteredOptions)\n            .formatToParts(serializedValues)\n            .map(function (part) {\n            return part.type === 'literal'\n                ? part\n                : __assign(__assign({}, part), { value: richValues_1[part.value] || part.value });\n        });\n    }\n    catch (e) {\n        onError(new IntlFormatError('Error formatting list.', locale, e));\n    }\n    // @ts-ignore\n    return values;\n}\n","import { filterProps } from './utils';\nimport { IntlFormatError } from './error';\nimport { ErrorCode, FormatError } from 'intl-messageformat';\nvar PLURAL_FORMAT_OPTIONS = ['type'];\nexport function formatPlural(_a, getPluralRules, value, options) {\n    var locale = _a.locale, onError = _a.onError;\n    if (options === void 0) { options = {}; }\n    if (!Intl.PluralRules) {\n        onError(new FormatError(\"Intl.PluralRules is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-pluralrules\\\"\\n\", ErrorCode.MISSING_INTL_API));\n    }\n    var filteredOptions = filterProps(options, PLURAL_FORMAT_OPTIONS);\n    try {\n        return getPluralRules(locale, filteredOptions).select(value);\n    }\n    catch (e) {\n        onError(new IntlFormatError('Error formatting plural.', locale, e));\n    }\n    return 'other';\n}\n","import { getNamedFormat, filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar RELATIVE_TIME_FORMAT_OPTIONS = ['numeric', 'style'];\nfunction getFormatter(_a, getRelativeTimeFormat, options) {\n    var locale = _a.locale, formats = _a.formats, onError = _a.onError;\n    if (options === void 0) { options = {}; }\n    var format = options.format;\n    var defaults = (!!format && getNamedFormat(formats, 'relative', format, onError)) || {};\n    var filteredOptions = filterProps(options, RELATIVE_TIME_FORMAT_OPTIONS, defaults);\n    return getRelativeTimeFormat(locale, filteredOptions);\n}\nexport function formatRelativeTime(config, getRelativeTimeFormat, value, unit, options) {\n    if (options === void 0) { options = {}; }\n    if (!unit) {\n        unit = 'second';\n    }\n    var RelativeTimeFormat = Intl.RelativeTimeFormat;\n    if (!RelativeTimeFormat) {\n        config.onError(new FormatError(\"Intl.RelativeTimeFormat is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-relativetimeformat\\\"\\n\", ErrorCode.MISSING_INTL_API));\n    }\n    try {\n        return getFormatter(config, getRelativeTimeFormat, options).format(value, unit);\n    }\n    catch (e) {\n        config.onError(new IntlFormatError('Error formatting relative time.', config.locale, e));\n    }\n    return String(value);\n}\n","import { IntlFormatError } from './error';\nimport { filterProps, getNamedFormat } from './utils';\nvar NUMBER_FORMAT_OPTIONS = [\n    'style',\n    'currency',\n    'unit',\n    'unitDisplay',\n    'useGrouping',\n    'minimumIntegerDigits',\n    'minimumFractionDigits',\n    'maximumFractionDigits',\n    'minimumSignificantDigits',\n    'maximumSignificantDigits',\n    // ES2020 NumberFormat\n    'compactDisplay',\n    'currencyDisplay',\n    'currencySign',\n    'notation',\n    'signDisplay',\n    'unit',\n    'unitDisplay',\n    'numberingSystem',\n    // ES2023 NumberFormat\n    'trailingZeroDisplay',\n    'roundingPriority',\n    'roundingIncrement',\n    'roundingMode',\n];\nexport function getFormatter(_a, getNumberFormat, options) {\n    var locale = _a.locale, formats = _a.formats, onError = _a.onError;\n    if (options === void 0) { options = {}; }\n    var format = options.format;\n    var defaults = ((format &&\n        getNamedFormat(formats, 'number', format, onError)) ||\n        {});\n    var filteredOptions = filterProps(options, NUMBER_FORMAT_OPTIONS, defaults);\n    return getNumberFormat(locale, filteredOptions);\n}\nexport function formatNumber(config, getNumberFormat, value, options) {\n    if (options === void 0) { options = {}; }\n    try {\n        return getFormatter(config, getNumberFormat, options).format(value);\n    }\n    catch (e) {\n        config.onError(new IntlFormatError('Error formatting number.', config.locale, e));\n    }\n    return String(value);\n}\nexport function formatNumberToParts(config, getNumberFormat, value, options) {\n    if (options === void 0) { options = {}; }\n    try {\n        return getFormatter(config, getNumberFormat, options).formatToParts(value);\n    }\n    catch (e) {\n        config.onError(new IntlFormatError('Error formatting number.', config.locale, e));\n    }\n    return [];\n}\n","import { __assign } from \"tslib\";\nimport { createFormatters, DEFAULT_INTL_CONFIG } from './utils';\nimport { InvalidConfigError, MissingDataError } from './error';\nimport { formatNumber, formatNumberToParts } from './number';\nimport { formatRelativeTime } from './relativeTime';\nimport { formatDate, formatDateToParts, formatTime, formatTimeToParts, formatDateTimeRange, } from './dateTime';\nimport { formatPlural } from './plural';\nimport { formatMessage } from './message';\nimport { formatList, formatListToParts } from './list';\nimport { formatDisplayName } from './displayName';\nfunction messagesContainString(messages) {\n    var firstMessage = messages ? messages[Object.keys(messages)[0]] : undefined;\n    return typeof firstMessage === 'string';\n}\nfunction verifyConfigMessages(config) {\n    if (config.onWarn &&\n        config.defaultRichTextElements &&\n        messagesContainString(config.messages || {})) {\n        config.onWarn(\"[@formatjs/intl] \\\"defaultRichTextElements\\\" was specified but \\\"message\\\" was not pre-compiled. \\nPlease consider using \\\"@formatjs/cli\\\" to pre-compile your messages for performance.\\nFor more details see https://formatjs.io/docs/getting-started/message-distribution\");\n    }\n}\n/**\n * Create intl object\n * @param config intl config\n * @param cache cache for formatter instances to prevent memory leak\n */\nexport function createIntl(config, cache) {\n    var formatters = createFormatters(cache);\n    var resolvedConfig = __assign(__assign({}, DEFAULT_INTL_CONFIG), config);\n    var locale = resolvedConfig.locale, defaultLocale = resolvedConfig.defaultLocale, onError = resolvedConfig.onError;\n    if (!locale) {\n        if (onError) {\n            onError(new InvalidConfigError(\"\\\"locale\\\" was not configured, using \\\"\".concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl/api#intlshape for more details\")));\n        }\n        // Since there's no registered locale data for `locale`, this will\n        // fallback to the `defaultLocale` to make sure things can render.\n        // The `messages` are overridden to the `defaultProps` empty object\n        // to maintain referential equality across re-renders. It's assumed\n        // each <FormattedMessage> contains a `defaultMessage` prop.\n        resolvedConfig.locale = resolvedConfig.defaultLocale || 'en';\n    }\n    else if (!Intl.NumberFormat.supportedLocalesOf(locale).length && onError) {\n        onError(new MissingDataError(\"Missing locale data for locale: \\\"\".concat(locale, \"\\\" in Intl.NumberFormat. Using default locale: \\\"\").concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl#runtime-requirements for more details\")));\n    }\n    else if (!Intl.DateTimeFormat.supportedLocalesOf(locale).length &&\n        onError) {\n        onError(new MissingDataError(\"Missing locale data for locale: \\\"\".concat(locale, \"\\\" in Intl.DateTimeFormat. Using default locale: \\\"\").concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl#runtime-requirements for more details\")));\n    }\n    verifyConfigMessages(resolvedConfig);\n    return __assign(__assign({}, resolvedConfig), { formatters: formatters, formatNumber: formatNumber.bind(null, resolvedConfig, formatters.getNumberFormat), formatNumberToParts: formatNumberToParts.bind(null, resolvedConfig, formatters.getNumberFormat), formatRelativeTime: formatRelativeTime.bind(null, resolvedConfig, formatters.getRelativeTimeFormat), formatDate: formatDate.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatDateToParts: formatDateToParts.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatTime: formatTime.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatDateTimeRange: formatDateTimeRange.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatTimeToParts: formatTimeToParts.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatPlural: formatPlural.bind(null, resolvedConfig, formatters.getPluralRules), \n        // @ts-expect-error TODO: will get to this later\n        formatMessage: formatMessage.bind(null, resolvedConfig, formatters), \n        // @ts-expect-error TODO: will get to this later\n        $t: formatMessage.bind(null, resolvedConfig, formatters), formatList: formatList.bind(null, resolvedConfig, formatters.getListFormat), formatListToParts: formatListToParts.bind(null, resolvedConfig, formatters.getListFormat), formatDisplayName: formatDisplayName.bind(null, resolvedConfig, formatters.getDisplayNames) });\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2023 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * IntlInterface\n * @packageDocumentation\n * @module IntlInterface\n */\n\nimport type { IntlShape } from '@formatjs/intl';\nimport { createIntl, createIntlCache } from '@formatjs/intl';\nimport Logger from './utils/Logger';\n\nconst DEFAULT_LOCALE = 'en-US';\n\n/**\n * Set of supported locales that the jsapi has predefinds translations for.\n * Falls back on English if the locale requested does not exist in the list below.\n *\n * This may seem a little disgusting but with the typescript update (v4.9.5)\n * The ES5 target throws a wedge in dynamic imports. E.g.\n *\n * This:\n * ```\n * const locale = 'en-US';\n * async import(`./locale/${en-US}.json`)\n * ```\n *\n * Gets converted into this:\n * ```\n * var locale = 'en-US';\n * var path = './locale/'.concat(locale, '.json');\n * return Promise.resolve().then(() => require(path))\n * ```\n *\n * This breaks Webpack's dynamic import flow. It is raised as a warning but webpack attempts to\n * load the locale data from the wrong location. We then end up in a perpetual loop.\n * This needs to stay as is so the dynamic import knows exactly where to pull the files from.\n * At least till the underlying transformation is fixed.\n */\nconst SUPPORTED_LOCALES: Record<string, () => Promise<Record<string, any>>> = {\n    'cs-CZ': () => import('./locale/cs-CZ.json'),\n    'da-DK': () => import('./locale/da-DK.json'),\n    'de-DE': () => import('./locale/de-DE.json'),\n    'en-US': () => import('./locale/en-US.json'),\n    'es-ES': () => import('./locale/es-ES.json'),\n    'fi-FI': () => import('./locale/fi-FI.json'),\n    'fr-CA': () => import('./locale/fr-CA.json'),\n    'fr-FR': () => import('./locale/fr-FR.json'),\n    'fr-MA': () => import('./locale/fr-MA.json'),\n    'hu-HU': () => import('./locale/hu-HU.json'),\n    'it-IT': () => import('./locale/it-IT.json'),\n    'ja-JP': () => import('./locale/ja-JP.json'),\n    'ko-KR': () => import('./locale/ko-KR.json'),\n    'nb-NO': () => import('./locale/nb-NO.json'),\n    'nl-NL': () => import('./locale/nl-NL.json'),\n    'pl-PL': () => import('./locale/pl-PL.json'),\n    'pt-BR': () => import('./locale/pt-BR.json'),\n    'ru-RU': () => import('./locale/ru-RU.json'),\n    'sv-SE': () => import('./locale/sv-SE.json'),\n    'tr-TR': () => import('./locale/tr-TR.json'),\n    'uk-UA': () => import('./locale/uk-UA.json'),\n    'zh-CN': () => import('./locale/zh-CN.json'),\n    'zh-TW': () => import('./locale/zh-TW.json'),\n    'zu-ZU': () => import('./locale/zu-ZU.json'),\n    'zz-ZZ': () => import('./locale/zz-ZZ.json')\n} as const;\n\n// Export supported locales as type.\nexport type SupportedLocale = keyof typeof SUPPORTED_LOCALES;\n\nexport default class IntlInterface {\n    private _intl?: IntlShape;\n    private _locale?: SupportedLocale;\n\n    constructor(locale: SupportedLocale = DEFAULT_LOCALE) {\n        this.setLocale(locale);\n    }\n\n    get locale() {\n        return this._locale;\n    }\n\n    async setLocale(locale: SupportedLocale) {\n        if (!SUPPORTED_LOCALES[locale]) {\n            Logger.log(`[INTL] ${locale} is not a supported language. Falling back to en-US`);\n            locale = DEFAULT_LOCALE;\n        }\n        const { messages, locale: _locale } = await this._loadLocaleData(locale);\n        // We load the localized strings manually, but we still need to specify `locale`\n        // for localization of non-string values like numbers, dates, etc.\n        // We give a fallback `defaultLocale` to use if the given `locale` doesn't have a\n        // defined localization configuration for those non-string values.\n        this._intl = createIntl({ locale, messages, defaultLocale: DEFAULT_LOCALE }, createIntlCache());\n        this._locale = _locale;\n        return locale;\n    }\n\n    _loadLocaleData(locale: SupportedLocale): Promise<{\n        messages: Record<string, string>;\n        locale: SupportedLocale;\n    }> {\n        return SUPPORTED_LOCALES[locale]()\n            .then(messages => ({ messages, locale }))\n            .catch(_e => this._loadLocaleData(DEFAULT_LOCALE));\n    }\n\n    formatMessage(id: string, values?: Record<string, any>) {\n        if (!this._intl) {\n            Logger.log(`[INTL] no localization data loaded`);\n            return;\n        }\n        return this._intl.formatMessage({ id }, values);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2021 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport RestrictedEventEmitter from './utils/RestrictedEventEmitter';\nimport type LocalDriver from '../drivers/LocalDriver';\nimport observable from '../utils/observable';\nimport type { FontData } from './data/FontData';\n/**\n * Element\n * @packageDocumentation\n * @module FontManager\n */\n\nexport default class FontManager extends RestrictedEventEmitter {\n    _fontsCache: { [s: string]: FontData };\n\n    constructor(protected _driver: LocalDriver) {\n        super();\n        this._fontsCache = {};\n    }\n\n    /**\n     * Returns the cached font data else goes ahead and fetches it\n     */\n    @observable\n    async getFontData(fontId: string): Promise<FontData> {\n        const fontData = this._fontsCache[fontId];\n        if (fontData) {\n            // Already exists in the cache\n            return fontData;\n        }\n        const data: FontData = await this._driver.getFontData(fontId);\n        this._updateFontData(fontId, data);\n        return data;\n    }\n\n    private _updateFontData(fontId: string, fontData: FontData) {\n        this._fontsCache[fontId] = fontData;\n    }\n\n    /**\n     * Returns whether the given font is installed on the system (this queries the CC Library Process).\n     */\n    @observable\n    async isSystemFontAvailable(fontName: string, matchFamily?: boolean): Promise<boolean> {\n        return await this._driver.isSystemFontAvailable(fontName, matchFamily);\n    }\n\n    _clearCache() {\n        this._fontsCache = {};\n        this.emit('change');\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2022 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport RestrictedEventEmitter from '../models/utils/RestrictedEventEmitter';\nimport observable from './observable';\n\n/**\n * Utility for creating limited map objects with observable getters\n * and that emit change events when they're modified.\n */\nexport default class ObservableMap extends RestrictedEventEmitter {\n    private _map = new Map();\n\n    set(key: any, value: any) {\n        this._map.set(key, value);\n        this.emit('change');\n    }\n\n    delete(key: any) {\n        this._map.delete(key);\n        this.emit('change');\n    }\n\n    clear() {\n        this._map.clear();\n        this.emit('change');\n    }\n\n    @observable('change')\n    entries() {\n        return this._map.entries();\n    }\n\n    @observable('change')\n    get(key: any) {\n        return this._map.get(key);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2025 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n// @deprecated: This file is a stub and kept for build compatibility only.\n// DO NOT use or extend this class in new code.\n\nexport default class ModelCache<T extends any, D = any > {\n    constructor(_parent?: any, _Class?: new (...args: any[]) => T, _driver?: any) {\n        // console.warn('ModelCache is a stub and should not be used.');÷\n    }\n\n    registerIndex(_key: string): void {\n        // console.warn('ModelCache.registerIndex() is a stub and should not be used.');\n    }\n\n    updateIndices(_model: T, _newData: Partial<D>): void {\n        // console.warn('ModelCache.updateIndices() is a stub and should not be used.');\n    }\n\n    get(_id: string): T | undefined {\n        // console.warn('ModelCache.get() is a stub and should not be used.');\n        return undefined;\n    }\n\n    getByIndex(_index: string, _key: any): T | undefined {\n        // console.warn('ModelCache.getByIndex() is a stub and should not be used.');\n        return undefined;\n    }\n\n    add(data: D, _shouldNotify = true): T {\n        // console.warn('ModelCache.add() is a stub and should not be used.');\n        return {} as T;\n    }\n\n    remove(idOrModel: string | T, _shouldNotify = true): void {\n        // console.warn('ModelCache.remove() is a stub and should not be used.');\n    }\n\n    replace(data: D | D[], _shouldNotify = true): void {\n        // console.warn('ModelCache.replace() is a stub and should not be used.');\n    }\n\n    upsert(..._dataArray: D[]): void {\n        // console.warn('ModelCache.upsert() is a stub and should not be used.');\n    }\n\n    all(): T[] {\n        // console.warn('ModelCache.all() is a stub and should not be used.');\n        return [];\n    }\n\n    get length(): number {\n        // console.warn('ModelCache.length is a stub and should not be used.');\n        return 0;\n    }\n\n    get driver(): any {\n        // console.warn('ModelCache.driver is a stub and should not be used.');\n        return undefined;\n    }\n\n    get changes(): any[] {\n        // console.warn('ModelCache.changes is a stub and should not be used.');\n        return [];\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    on(event: string, _listener: (...args: any[]) => void): void {\n        // console.warn(`ModelCache.on('${event}', listener) is a stub and should not be used.`);\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    off(event: string, _listener: (...args: any[]) => void): void {\n        // console.warn(`ModelCache.off('${event}', listener) is a stub and should not be used.`);\n    }\n}\n","// Temporary stub for orchestrator\n// @ts-expect-error R-TODO\nimport type Library from './Library';\n\nimport { EventEmitter } from 'events';\n\nexport default class Orchestrator extends EventEmitter {\n    constructor(_parent: any, _driver: any, _options: any = {}) {\n        super();\n        // console.warn('Orchestrator is stubbed and does not perform actual operations.');\n    }\n\n    // Placeholder for changeDriver method\n    async changeDriver(_newDriver: any): Promise<void> {\n        // console.warn('changeDriver is called on a stubbed Orchestrator.');\n    }\n\n    // Placeholder for initialLibrariesLoad method\n    initialLibrariesLoad(): void {\n        // console.warn('initialLibrariesLoad is called on a stubbed Orchestrator.');\n    }\n\n    // Placeholder for all method\n    all(): any[] {\n        // console.warn('all is called on a stubbed Orchestrator.');\n        return [];\n    }\n\n    // Placeholder for loadList method\n    async loadList(_filters: any): Promise<any[]> {\n        // console.warn('loadList is called on a stubbed Orchestrator.');\n        return [];\n    }\n\n    // Placeholder for loadPage method\n    async loadPage(_filters: any, _signal?: AbortSignal): Promise<any[]> {\n        // console.warn('loadPage is called on a stubbed Orchestrator.');\n        return [];\n    }\n\n    // Placeholder for isLoaded property\n    get isLoaded(): boolean {\n        // console.warn('Accessing isLoaded on a stubbed Orchestrator.');\n        return false;\n    }\n\n    // Placeholder for isLoading property\n    get isLoading(): boolean {\n        // console.warn('Accessing isLoading on a stubbed Orchestrator.');\n        return false;\n    }\n\n    // Placeholder for changes property\n    get changes(): any[] {\n        // console.warn('Accessing changes on a stubbed Orchestrator.');\n        return [];\n    }\n\n    // Placeholder for syncStatus property\n    get syncStatus(): any {\n        // console.warn('Accessing syncStatus on a stubbed Orchestrator.');\n        return {};\n    }\n\n    // Placeholder for pause method\n    pause(_halt: boolean = false): void {\n        // console.warn('pause is called on a stubbed Orchestrator.');\n    }\n\n    // Placeholder for resume method\n    resume(): void {\n        // console.warn('resume is called on a stubbed Orchestrator.');\n    }\n\n    // Placeholder for waitForHydrate method\n    async waitForHydrate(): Promise<void> {\n        // console.warn('waitForHydrate is called on a stubbed Orchestrator.');\n    }\n\n    /**\n     * Stub for retrieving a library by ID.\n     */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    get(libraryId: string) {\n        // console.warn(`Stub: Orchestrator.get() called for libraryId: ${libraryId}.`);\n        return { syncStatus: {} } as Library;\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    getByIndex(indexType: string, assetId: string) {\n        // console.warn(`Stub: Orchestrator.getByIndex() called for assetId: ${assetId}.`);\n        return { syncStatus: {} } as Library;\n    }\n\n    /**\n     * Stub for simulating operations.\n     */\n    doOperations() {\n        // console.warn('Stub: Orchestrator.doOperations() called.');\n    }\n\n    /**\n     * Stub for emitting events (e.g., syncChange).\n     */\n    onSyncChange(_listener: () => void) {\n        // console.warn('Stub: Orchestrator.onSyncChange() called.');\n    }\n\n    /**\n     * Stub for removing listeners for events (e.g., syncChange).\n     */\n    offSyncChange(_listener: () => void) {\n        // console.warn('Stub: Orchestrator.offSyncChange() called.');\n    }\n\n    get DANGEROUS() {\n        return { removeAllListeners: (_s?: string) => {} };\n    }\n\n    add(_lib: any) {\n        // console.warn('Stub: Orchestrator.add() called.');\n        return {} as Library;\n    }\n\n    upsert(_libraryData: any) {\n        // console.warn('Stub: Orchestrator.upsert() called.');\n        return {} as Library;\n    }\n\n    hydrate() {\n\n    }\n\n    remove(_id: string) {\n\n    }\n\n    _halt() {\n\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2019 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\n/**\n * The main entry point for the Creative Cloud Libraries Javascript API is available via the default export.\n *\n * This class provides methods for configuring and initialising the API.\n *\n * @packageDocumentation\n * @module CCLibraries\n */\n\n/*\n    AdobePatentID=\"P5086-US\"\n    AdobePatentID=\"P5087-US\"\n*/\n\n// Polyfill for global in the browser environment\nif (typeof window !== 'undefined' && typeof global === 'undefined') {\n    (window as any).global = window;\n}\n\nimport type { CreateAtomFn, LinkReference } from '../index';\nimport type { LibraryData, Role } from './models/data/LibraryData';\nimport type { UserQuotaData, ProcessInfo } from './models/data/ConfigurationData';\nimport type { default as Driver, SearchFilters, ElementSort, LibraryListFilters } from './drivers/Driver';\n\nimport observable from './utils/observable';\nimport type { CreateAtom, Transaction } from './utils/mobXRegistry';\nimport mobXRegistry from './utils/mobXRegistry';\nimport RestrictedEventEmitter from './models/utils/RestrictedEventEmitter';\nimport CloudDriver from './drivers/CloudDriver';\nimport LocalDriver from './drivers/LocalDriver';\nimport HybridDriver from './drivers/HybridDriver';\nimport { requiresCloudDriver, requiresLocalDriver } from './models/utils/AccessUtils';\nimport Team from './models/Team';\nimport LibraryError from './errors/LibraryError';\nimport type { ElementPoolId } from './models/Element';\nimport Element, { ElementUpdater, getCombinedId } from './models/Element';\nimport ProgressiveLoader from './utils/ProgressiveLoader';\nimport { toLowerCamel } from './utils';\nimport { getExtensions, getMimeTypes } from './utils/MimeTypeUtils';\nimport { ABORT_ERROR, LibraryConstants } from './config/constants';\nimport { createPlaceholderId, createLibraryData } from './models/utils';\nimport type { SupportedLocale } from './IntlInterface';\nimport IntlInterface from './IntlInterface';\nimport { toolkitNames } from './config/constants';\nimport FontManager from './models/FontManager';\nimport { getAssetAndFragmentIdFromReference, serializeLinkReference } from './utils/LinkUtils';\nimport Logger from './utils/Logger';\nimport type RequestError from './errors/RequestError';\nimport ObservableMap from './utils/ObservableMap';\nimport type SyncStatus from './models/SyncStatus';\nimport { extractElementId, extractGroupId } from './utils/PathUtils';\nimport type { Stringified } from './types';\nimport { isLibraryLoadedByDefault } from './utils/LibraryUtils';\nimport type { ElementData } from './models/data/ElementData';\nimport type { FileSystem } from './cache/FileSystemDatabaseAdapter';\nimport type { FullRenditionConfig, RenditionSizeConfig } from './drivers/LocalDriver/utils/generalUtils';\nimport LibraryContents from './models/LibraryContents';\n\n// Unlike in other files, we cannot just use \"@ts-expect-error\" to suppress errors\n// from importing a missing/broken deprecated file. This is the entry point file,\n// and all imports must build without error.\n// Therefore all deprecated files will be supplied with stubs until they can be fully removed.\nimport type Library from './models/LibraryStub'; // Deprecated\nimport ModelCache from './models/ModelCacheStub'; // Deprecated\n// Orchestrator is not deprecated, but needs to be refactored to no longer use ModelCache, and this allows us to deal with those errors later.\nimport Orchestrator from './models/OrchestratorStub';\n\n// SAM imports using aliases (since this module is symlinked):\nimport type ISAMCorePrivate from '../core/ISAMCorePrivate';\nimport ItemPool from '../core/ItemPool';\n// For now, we are keeping the old Library class around (and thereby avoiding updating all existing APIs),\n// until we can start removing code. The new APIs will use SAM's version of a Library\nimport type SAMLibrary from '../libraries/Library';\nimport type AdobeAsset from '../assets/AdobeAsset';\n\n/**\n * INCREMENTAL REFACTOR NOTES:\n * - Switch from Library to SAMLibrary or LibraryContents usage incrementally.\n * - Once an API is supported, add it to ICCLibraries.\n * - Orchestrator, Library, and ModelCache are currently stubbed, with the original files in an archive/ folder that wont be built.\n *   Once Orchestrator is refactored, the stub can be retired.\n *   Library and ModelCache stubs and archived files can be removed once they are no longer referenced.\n */\n\n// Defines the new APIs for CCLibraries that are currently in use.\n// Note that though these are public methods on the class, this class is no longer exposed directly to the client,\n// so there is no need to add this to component-types.\n// When all APIs are supported and the rest deprecated, we could actually replace ICCLibraries with CCLibraries itself.\n// Note: As you add APIs here, enable the respective tests.\nexport interface ICCLibraries {\n    assetPool: ItemPool<SAMLibrary | AdobeAsset>;\n    elementPool: ItemPool<Element, ElementPoolId>;\n    elementUpdater: typeof ElementUpdater;\n    apiRoot: ICCLibraries;\n    driver: Driver;\n    cloudDriver?: CloudDriver;\n    getOption: (key: keyof typeof LibraryConstants) => any;\n    getLibraryContents(library: SAMLibrary): LibraryContents;\n}\n\nexport type CCLibrariesOptions = {\n    elementTypes?: ('elements' | 'removedElements' | 'documentationElements')[];\n    renditionSizes?: RenditionSizeConfig;\n    fullRenditionConfig?: FullRenditionConfig;\n    readOnly?: boolean;\n    cloudDriver?: CloudDriver;\n    disableLocalFallthrough?: boolean;\n    disablePreemptiveLibraryLoad?: boolean;\n    disableFallbackDefaultLibrary?: boolean;\n    enableBrandLifecycleManagement?: boolean;\n    includeApprovedBrandsInLibraries?: boolean;\n    skipConnectingOnInit?: boolean;\n    mobXCreateAtom?: CreateAtom;\n    mobXTransaction?: Transaction;\n    locale?: SupportedLocale;\n\n    /**\n     * An API key for Ingest for analytics reporting. This property is optional, but must be set if reporting metrics.\n     */\n    ingestApiKey?: string;\n\n    /**\n     * Information about the host application. This property is optional, but must be set if reporting metrics.\n     *\n     * @remarks\n     * The code and version of the application is preferred. Example: \"PHXS/1.2.3\" for Photoshop.\n     */\n    product?: string;\n\n    /**\n     * Information about the client who is reporting metrics. This property is optional, but must be set if reporting metrics.\n     *\n     * @remarks\n     * The name and version of the application is preferred. Example: \"CCLibrariesPanel/1.2.3\".\n     */\n    productLocation?: string;\n\n    /**\n     * Whether running on desktop, mobile. This property is optional. It is used when reporting metrics.\n     */\n    platform?: 'DESKTOP' | 'MOBILE';\n\n    /**\n     * Information about the IMS session. This property is optional. It is used when reporting metrics.\n     */\n    sessionGuid?: string;\n\n    /**\n     * The license state of the user. Examples: 'subscription', 'paid', 'expired', 'trial', 'team_trial', 'team_trial_expired'.\n     * This property is optional. It is used when reporting metrics.\n     */\n    userAccountStatus?: string;\n\n    /**\n     * The set of WIP features to enable.\n     */\n    featureFlags?: {\n        enableProjects?: boolean;\n        enableGenStudioAPIs?: boolean;\n    };\n\n    /**\n     * Optional caching system to use if IndexedDB is not available. CCLibraries will use IndexedDB for caching\n     * when available. This option provides a way to read and write files, as well as a directory to store the\n     * cache file in.\n     *\n     * Note: The directory should be a fully resolved path and end with a path separator.\n     */\n    fileSystemCache?: { fs: FileSystem; dir: string };\n};\n\ntype Utils = {\n    getExtensions: any;\n    getMimeTypes: any;\n    copyFile: any;\n    getInstalledVersion: any;\n    getFileSize: any;\n    getRenditionGrid: any;\n    extractElementId: any;\n    extractGroupId: any;\n};\n\n// Could update the LinkReference imported from SAM to have both ElementLinkReference type and a LibraryLinkReference type\n// But this is fine for now.\ntype LibraryLinkReference = {\n    ['repo:assetId']: string;\n    ['repo:repositoryId']?: string;\n    ['repo:name']?: string;\n    ['repo:etag']?: string;\n    ['repo:version']?: string;\n    ['dc:format']?: string;\n    ['stRef:relativePath']?: string;\n    ['stRef:documentID']?: string;\n};\n\nexport type ElementReference = LinkReference | Stringified<LinkReference> | string;\nexport type LibraryReference = LibraryLinkReference | Stringified<LibraryLinkReference> | string;\n\n// ResourceRef for referencing assets, and fragments of assets, stored in the ACP. Represents data returned from repoMetadata RAPI call.\n// See https://git.corp.adobe.com/caf/xcm/blob/main/schemas/cc/link/resource-ref.schema.json for schema definition.\n// Identical to LinkReference, but both repo:assetId and repo:version are required.\nexport type ResourceRef = {\n    ['id']: string;\n    ['version']: string;\n} & LinkReference;\n\nexport type CopyLibraryOptions = {\n    permissionInheritance?: 'read' | 'all';\n    team?: Team;\n    // Include application metadata copy when copying a library (CloudDriver only)\n    includeAppMetadata?: boolean;\n    newName?: string;\n    documentExtractionData?: ResourceRef[];\n};\n\nexport type CreateLibraryOptions = CopyLibraryOptions & {\n    // Create a new library with a role. Required for brand libraries\n    roles?: Array<Role>;\n    documentExtractionData?: ResourceRef[];\n};\n\nconst defaultOptions: CCLibrariesOptions = {\n    enableBrandLifecycleManagement: false,\n    includeApprovedBrandsInLibraries: false,\n    elementTypes: [ 'elements' ],\n    readOnly: false,\n    skipConnectingOnInit: false\n};\n\ntype TransactionFn<T> = (action: () => T, thisArg?: undefined) => T;\n\n//TODO-R [SHARED-4137]: change to TypedEventEmitter wherever RestrictedEventEmitter is used\nexport default class CCLibraries extends RestrictedEventEmitter implements ICCLibraries {\n    private _libraryCache: Orchestrator;\n    private _driver: Driver;\n    private _cloudDriver?: CloudDriver;\n    private _options: CCLibrariesOptions;\n    private _intl: IntlInterface;\n    private _fontManager?: FontManager;\n    private _missingResolutionTargetsMap = new ObservableMap();\n    private _resolutionProgressMap = new Map();\n    private _disposeDefaultLibraryMonitor?: () => void;\n    private _elementPool: ItemPool<Element, ElementPoolId>;\n\n    private _teamsCache: ModelCache<Team> = new ModelCache(this, Team); // R-TODO[SHARED-4223]: Remove\n    private _searchLoader: any;\n\n    public utils: Utils;\n\n    constructor(private _core: ISAMCorePrivate, public assetPool: ItemPool<SAMLibrary | AdobeAsset>, driver: Driver, options: CCLibrariesOptions = {}) {\n        super();\n\n        // Provide window level access to the JSAPI\n        globalThis.CCLIBS = globalThis.CCLIBS ?? this;\n\n        this._options = { ...defaultOptions, ...options };\n        this._driver = driver;\n\n        if (this._options.mobXCreateAtom && this._options.mobXTransaction) {\n            mobXRegistry.register(this._options.mobXCreateAtom, this._options.mobXTransaction);\n        }\n\n        if (driver instanceof CloudDriver) {\n            this._cloudDriver = driver;\n        } else if (this._options.cloudDriver instanceof CloudDriver) {\n            this._cloudDriver = this._options.cloudDriver;\n        }\n\n        if (driver instanceof LocalDriver) {\n            this._fontManager = new FontManager(driver);\n        }\n\n        this.utils = {\n            ...CCLibraries.utils,\n            copyFile: this.copyFile.bind(this),\n            getInstalledVersion: this.getInstalledVersion.bind(this),\n            getFileSize: this.getFileSize.bind(this),\n            getRenditionGrid: this.getRenditionGrid.bind(this),\n            extractElementId,\n            extractGroupId\n        };\n\n        this._elementPool = new ItemPool<Element>(this._core, 'element');\n\n        this._teamsCache.on('change', () => this.emit('teamChange'));\n\n        // Emit an event when cached element resolution data changes.\n        this._missingResolutionTargetsMap.on('change', () => this.emit('resolutionStatusChange'));\n\n        // _handleDriverConnect only applies to the initial driver (not subsequent changes)\n        this._driver.on('connect', this._handleDriverConnect);\n        this._driver.on('disconnect', this._handleDriverDisconnect);\n        this._bindDriverEvents();\n\n        this._intl = new IntlInterface(this._options.locale);\n        this._libraryCache = new Orchestrator(this, this._driver, {\n            readOnly: this._options.readOnly,\n            skipConnectingOnInit: this._options.skipConnectingOnInit,\n            fileSystemCache: this._options.fileSystemCache,\n            enableBrandLifecycleManagement: this._options.enableBrandLifecycleManagement,\n            includeApprovedBrandsInLibraries: this._options.includeApprovedBrandsInLibraries\n        });\n\n        this._bindLibraryCacheEvents();\n\n        //Set the core as the event emitter on the Logger instance so we can emit message events via the SAMJS core\n        Logger.setEventEmitter(this._core);\n    }\n\n    /* New APIs */\n\n    get elementPool(): ItemPool<Element, ElementPoolId> {\n        return this._elementPool;\n    }\n\n    readonly elementUpdater = ElementUpdater; // This is an instance, not a class\n\n    /**\n     * Creates the LibraryContents API instance for a given library.\n     * LibraryContents controls and exposes the state of the library's contents, including elements and groups.\n     * Warning: This creates a new instance on each call. Call library.getContents() instead to access the cached instance stored on the library.\n     * @param library\n     * @returns LibraryContents\n     */\n    getLibraryContents(library: SAMLibrary): LibraryContents {\n        return new LibraryContents(this._core, this, library);\n    }\n\n    /* Old APIs */\n\n    /**\n     * Changes out the current driver for a new one. Any data in memory will be kept\n     * and refreshed when the new driver connects. This will wait for any in-flight\n     * operations to finish before switching to the new driver.\n     * @param newDriver The new driver to use.\n     * @returns A promise that resolves once the new driver has connected.\n     */\n    async changeDriver(newDriver: Driver) {\n        await this._libraryCache.changeDriver(newDriver);\n        this._driver = newDriver;\n\n        if (this._driver instanceof LocalDriver) {\n            this._fontManager = new FontManager(this._driver);\n        }\n\n        this._driver.on('connect', this._handleDriverConnect);\n        this._driver.on('disconnect', this._handleDriverDisconnect);\n        this._bindDriverEvents();\n\n        // Return a promise that tracks when the new driver has connected.\n        let driverConnectResolver: () => void;\n        const driverConnectPromise = new Promise<void>(resolve => (driverConnectResolver = resolve));\n        this._driver.once('connect', () => driverConnectResolver());\n        return driverConnectPromise;\n    }\n\n    private _handleDriverConnect = (driver: Driver) => {\n        if (driver instanceof CloudDriver) {\n            return this._handleCloudDriverConnect(driver);\n        }\n\n        if (driver instanceof LocalDriver) {\n            return this._handleLocalDriverConnect(driver);\n        }\n    };\n\n    private _handleDriverDisconnect = (driver: Driver) => {\n        if (driver instanceof LocalDriver) {\n            return this._handleLocalDriverDisconnect();\n        }\n    };\n\n    private _handleCloudDriverConnect(driver: CloudDriver) {\n        if (this.driver instanceof HybridDriver || this._options.disableLocalFallthrough) {\n            this.emit('change');\n            this.emit('driverConnect');\n            return;\n        }\n\n        driver\n            .getLocalDriver()\n            .init(\n                { retryCount: 3, skipConnectingOnInit: this._options.skipConnectingOnInit },\n                (localDriver: LocalDriver) => {\n                    // Unbind old cache and driver\n                    this._libraryCache.pause(true);\n                    this._libraryCache.DANGEROUS.removeAllListeners();\n                    this._driver.DANGEROUS.removeAllListeners();\n\n                    // Bind new cache\n                    this._libraryCache = new Orchestrator(this, localDriver, {\n                        readOnly: this._options.readOnly,\n                        skipConnectingOnInit: this._options.skipConnectingOnInit\n                    });\n                    this._bindLibraryCacheEvents();\n\n                    // Bind new driver\n                    this._driver = localDriver;\n                    this._bindDriverEvents();\n\n                    this.emit('change');\n                }\n            );\n    }\n\n    private _handleLocalDriverConnect(driver: LocalDriver) {\n        driver.updateRenditionCacheConfiguration(this.options.renditionSizes, this.options.fullRenditionConfig);\n\n        const cloudDriver = this.cloudDriver ?? driver.getCloudDriver();\n        cloudDriver?.init({ readOnly: true }, (cloudDriver: CloudDriver) => {\n            this._cloudDriver = cloudDriver;\n        });\n        this.emit('driverConnect');\n    }\n\n    private _handleLocalDriverDisconnect() {\n        this.emit('driverDisconnect');\n    }\n\n    private _bindDriverEvents() {\n        this._driver.on('configChange', () => this.emit('configChange'));\n        this._driver.on('connecting', () => this.emit('connecting'));\n        this._driver.on('failedConnection', () => this.emit('failedConnection'));\n    }\n\n    private _bindLibraryCacheEvents() {\n        this._libraryCache.on('connect', () => this.emit('connect'));\n        this._libraryCache.on('loaded', () => this.emit('loaded'));\n        this._libraryCache.on('hydrate', () => this.emit('restore'));\n        this._libraryCache.on('sync', () => this.emit('sync'));\n        this._libraryCache.on('report', (...args: any[]) => this.emit('report', ...args));\n        this._libraryCache.on('change', this._libraryCacheChangeHandler.bind(this));\n        this._libraryCache.on('modelChange', this._libraryCacheChangeHandler.bind(this));\n        this._libraryCache.on('fontDataChange', () => this.fontManager?._clearCache());\n    }\n\n    private _libraryCacheChangeHandler() {\n        this.emit('change', { libraries: this._libraryCache.changes });\n    }\n\n    /**\n     * For MobX clients.\n     * Hook up the JS API to your MobX instance so that it's observable.\n     * This is equivalent to passing mobXCreateAtom and mobXTransaction to the constructor.\n     * This simply allows clients other than the API constructor to hook up their own MobX instances.\n     * Make sure to call the returned disposer function during teardown to avoid memory leaks.\n     * @param createAtom mobx#createAtom\n     * @param transaction mobx#transaction\n     * @returns {Function} disposer function - Make sure to call it during teardown to avoid memory leaks.\n     */\n    makeObservable(createAtom: CreateAtomFn, transaction: TransactionFn<any>): () => void {\n        return mobXRegistry.register(createAtom, transaction);\n    }\n\n    /**\n     * @internal\n     */\n    get apiRoot() {\n        return this;\n    }\n\n    get apiVersion() {\n        return 2;\n    }\n\n    /**\n     * May include loading options, and so is expected to be set in the constructor.\n     *  @internal\n     */\n    @observable\n    get options() {\n        return this._options;\n    }\n\n    /**\n     * @internal\n     */\n    updateOptions(options: CCLibrariesOptions) {\n        this._options = options;\n    }\n\n    /**\n     * @internal\n     */\n    get driver() {\n        return this._driver;\n    }\n\n    /**\n     * @internal\n     */\n    get cloudDriver() {\n        return this._cloudDriver;\n    }\n\n    @observable\n    get libraries(): Library[] {\n        this._libraryCache.initialLibrariesLoad();\n        return this._libraryCache.all().filter(lib => {\n            const isDeleted = lib.isDeletedLocally;\n            // The client may have used CCLibraries.getLibraries() to load libraries that\n            // wouldn't normally appear in the user's default collection.\n            // Make sure we don't include any of those here.\n            return !isDeleted && isLibraryLoadedByDefault(lib.data, this._options.enableBrandLifecycleManagement);\n        });\n    }\n\n    @observable\n    async getLibraries(filters?: LibraryListFilters): Promise<Library[]> {\n        return this._libraryCache.loadList(filters);\n    }\n\n    @observable\n    async getLibrariesPage(filters?: LibraryListFilters, signal?: AbortSignal): Promise<Library[]> {\n        return this._libraryCache.loadPage(filters, signal);\n    }\n\n    @observable('driverConnect', 'driverDisconnect', 'loaded')\n    get connected(): boolean {\n        return Boolean(this.driver.isConnected);\n    }\n\n    @observable('loaded')\n    get areLibrariesLoaded(): boolean {\n        return Boolean(this._libraryCache?.isLoaded);\n    }\n\n    @observable('loaded', 'sync')\n    get areLibrariesLoading(): boolean {\n        return this._libraryCache?.isLoading;\n    }\n\n    @observable('configChange')\n    get userQuota(): UserQuotaData {\n        return this.driver.config.user?.quota as UserQuotaData;\n    }\n\n    @requiresLocalDriver\n    @observable('configChange')\n    get processInfo(): ProcessInfo & { environment: string } {\n        return {\n            ...this.driver.config.processInfo,\n            environment: this.driver.config.environment\n        };\n    }\n\n    @observable\n    get storageUsed(): Number {\n        return this.libraries.reduce((memo, library) => {\n            if (library.ownership === 'private') {\n                return memo + library.storageUsed;\n            }\n            return memo;\n        }, 0);\n    }\n\n    async _refreshTeams(): Promise<Team[]> {\n        try {\n            const projectsEnabled = this._options.featureFlags?.enableProjects;\n            const getTeams = (projectsEnabled ? this._driver.getProjects : this._driver.getTeams).bind(this._driver);\n            const teams = await getTeams();\n            this._teamsCache.replace(teams);\n        } catch (err) {\n            if ((err as Error).name !== ABORT_ERROR) {\n                throw err;\n            }\n        }\n        return this._teamsCache.all();\n    }\n\n    /**\n     * @deprecated\n     * Will be removed with https://jira.corp.adobe.com/browse/CCXC-20136\n     */\n    @observable('teamChange')\n    async refreshTeams(): Promise<Team[]> {\n        if (this.driver.config.environment === 'staging') {\n            Logger.warn('CCLibraries.refreshTeams is deprecated. Use CCLibraries.refreshProjects instead.');\n        }\n        return this._refreshTeams();\n    }\n\n    @observable('teamChange')\n    async refreshProjects(): Promise<Team[]> {\n        return this._refreshTeams();\n    }\n\n    /**\n     * @deprecated\n     * Will be removed with https://jira.corp.adobe.com/browse/CCXC-20136\n     */\n    @observable('teamChange')\n    get teams(): Team[] {\n        if (this.driver.config.environment === 'staging') {\n            Logger.warn('CCLibraries.teams is deprecated. Use CCLibraries.projects instead.');\n        }\n        return this._teamsCache.all();\n    }\n\n    // @deprecated\n    @observable('teamChange')\n    get projects(): Team[] {\n        // For now, Project data is wrapped using Team models.\n        // Later on, we will rename it everything that says \"team\" to \"project\".\n        // https://jira.corp.adobe.com/browse/CCXC-20136\n        return this._teamsCache.all();\n    }\n\n    @observable('configChange')\n    get userId(): string {\n        return this._driver?.config?.user?.id as string;\n    }\n\n    translate: IntlInterface['formatMessage'] = (messageId, values) => {\n        return this._intl.formatMessage(messageId, values);\n    };\n\n    /**\n     * Create a library. Optionally, a team library.\n     * @param name  Name of the library\n     * @param team  The team where the library should be created\n     */\n    createLibrary(name: string, opts: CreateLibraryOptions = {}) {\n        // First, we want to create the object locally. So create the minimum necessary data object that we need to\n        // render the library. This create the Library object and also the **action queue** for the Library.\n        const library = this._libraryCache.add(\n            createLibraryData({\n                id: createPlaceholderId(),\n                name,\n                documentExtractionData: opts.documentExtractionData,\n                roles: opts.roles,\n                team: opts.team?.data,\n                bookmark: opts.team\n                    ? {\n                        // When the user creates a team library, it is automatically bookmarked.\n                        id: createPlaceholderId()\n                    }\n                    : undefined\n            })\n        );\n\n        // Second, we want to tell the backend to actually create the library, so we enqueue an action to make\n        // the request.\n        library.actionDispatch({\n            name: 'createLibrary',\n            type: 'no-op',\n            data: library.data,\n            flags: {\n                lockNewLibraries: true,\n                permissionInheritance: opts.permissionInheritance\n            }\n        });\n\n        return library;\n    }\n\n    /**\n     * Fires an action to delete a library. While the asynchronous action is\n     * taking place, JSAPI sets the library as locally deleted.\n     *\n     * @example\n     * Get a reference to the library object you want to delete\n     * and fire the remove library action.\n     *\n     * ```ts\n     * const libToDelete = CCLIBS.getLibraryById('abc123');\n     * CCLIBS.removeLibrary(libToDelete);\n     * ```\n     *\n     * @param library   Library to remove.\n     */\n    removeLibrary(library: Library) {\n        library.actionDispatch({\n            name: 'removeLibrary',\n            type: 'no-op',\n            path: '$'\n        });\n        // isDeletedLocally causes the libraries getter to filter these libraries from view.\n        // However, actually removing the library from the cache is handled by the change listeners.\n        library.isDeletedLocally = true;\n    }\n\n    /**\n     * NOTE: This action is not supported when using the LocalDriver\n     *\n     * Fires an action to permanently delete a library. While the asynchronous action is\n     * taking place, JSAPI sets the library as locally deleted.\n     *\n     * @example\n     * Get a reference to the library object you want to delete\n     * and fire the remove library action.\n     *\n     * ```ts\n     * const libToDelete = CCLIBS.getLibraryById('abc123');\n     * CCLIBS.removeLibrary(libToDelete);\n     * ```\n     *\n     * @param library   Library to remove.\n     */\n    permanentlyDeleteLibrary(library: Library) {\n        library.actionDispatch({\n            name: 'permanentlyDeleteLibrary',\n            type: 'no-op',\n            path: '$'\n        });\n\n        library.isDeletedLocally = true;\n    }\n\n    /**\n     * Leave a library.\n     * @param library   Library to leave.\n     */\n    leaveLibrary(library: Library) {\n        library.actionDispatch({\n            name: 'leaveLibrary',\n            type: 'no-op',\n            path: '$'\n        });\n\n        library.isDeletedLocally = true;\n    }\n\n    /**\n     * Follow a library.\n     * @param assetId   assetId of the library to follow.\n     * @param libraryId id of the library to follow.\n     */\n    followLibrary(assetId: string, libraryId: string) {\n        return this._driver.followLibrary(assetId, libraryId);\n    }\n\n    /**\n     * Unfollow a library.\n     * @param library   Library to unfollow.\n     */\n    unfollowLibrary(library: Library) {\n        library.actionDispatch({\n            name: 'unfollowLibrary',\n            type: 'no-op',\n            path: '$'\n        });\n\n        library.isDeletedLocally = true;\n    }\n\n    importLibrary(path: string, callback: (err?: Error, library?: Library) => unknown = () => undefined) {\n        const asyncResponse = this._driver.importLibrary(path, (error?: Error, libraryData?: LibraryData) => {\n            if (error) {\n                return callback(error);\n            }\n\n            this._libraryCache.upsert(libraryData as LibraryData);\n            const library = this._libraryCache.get(libraryData?.id as string);\n            callback(undefined, library);\n        });\n\n        return asyncResponse;\n    }\n\n    exportLibrary(library: Library, path?: string, callback: (err?: Error) => unknown = () => undefined) {\n        return this._driver.exportLibrary(library, path, callback);\n    }\n\n    getLibraryById(libraryId: string): Library | undefined {\n        return this._libraryCache.get(libraryId);\n    }\n\n    getLibraryByAssetId(assetId: string): Library | undefined {\n        return this._libraryCache.getByIndex('assetId', assetId);\n    }\n\n    copyLibrary(library: Library, opts: CopyLibraryOptions = {}) {\n        const libraryCopy = this._libraryCache.add(\n            createLibraryData({\n                id: createPlaceholderId(),\n                name: opts.newName ?? library.name,\n                roles: library.roles,\n                team: opts.team?.data,\n                bookmark: opts.team\n                    ? {\n                        // When the user copies a library into a team, it is automatically bookmarked.\n                        id: createPlaceholderId()\n                    }\n                    : undefined\n            })\n        );\n\n        libraryCopy.actionDispatch({\n            name: 'copyLibrary',\n            type: 'no-op',\n            data: {\n                name: opts.newName,\n                team: opts.team?.data,\n                documentExtractionData: opts.documentExtractionData\n            },\n            flags: {\n                lockNewLibraries: true,\n                permissionInheritance: opts.permissionInheritance,\n                source: library,\n                includeAppMetadata: opts.includeAppMetadata\n            }\n        });\n\n        return libraryCopy;\n    }\n\n    /**\n     * Promote private library to team library\n     * @param library   Library to promote.\n     */\n    moveLibrary(library: Library, team: Team) {\n        library.actionDispatch({\n            name: 'moveLibrary',\n            type: 'update',\n            data: {\n                team: {\n                    id: team.id,\n                    name: team.name\n                },\n                bookmark: {\n                    // When a personal library is moved to a team, it is automatically bookmarked.\n                    id: createPlaceholderId()\n                },\n                ownership: 'incoming',\n                ownerType: 'org',\n                owner: team.owner.id\n            }\n        });\n    }\n\n    private getHybridSearchResults(searchQuery: string, filters?: SearchFilters, elementSort?: ElementSort) {\n        const generator = async function *(this: CCLibraries, abort: AbortSignal) {\n            // Firstly, lets return Elements that have already been loaded in this instance.\n            const rex = new RegExp(searchQuery, 'ig');\n            const currentLoadedMatchingElements = this.libraries\n                .filter(l => filters?.library_id === l.id || !filters?.library_id)\n                .reduce((acc: Element[], lib: Library) => {\n                    const matches = lib.elements.filter((e: Element) => rex.test(e.name));\n                    acc.push(...matches);\n                    return acc;\n                }, []);\n            yield currentLoadedMatchingElements;\n\n            // Keep tabs of the already found elements so we do not repeat results\n            const previouslyMatchedElementIds: string[] = currentLoadedMatchingElements.map((e: Element) => e.id);\n\n            // Melville search needs the asset id of the library. not its legacy id\n            if (filters?.library_id) {\n                const searchWithinLibrary = this.getLibraryById(filters.library_id);\n                filters = { ...filters, library_id: searchWithinLibrary?.assetId };\n            }\n\n            // Use USS to return the rest of the elements for us\n            for await (const searchResults of this.driver.getSearchResults(\n                searchQuery,\n                filters as SearchFilters,\n                elementSort as ElementSort,\n                abort\n            )) {\n                yield searchResults\n                    .map((e: ElementData) => {\n                        if (previouslyMatchedElementIds.includes(e.id)) { return; }\n                        const library = this.getLibraryByAssetId(e.libraryAssetId as string);\n\n                        // Due to a limitation with USS right now we cannot assume that a result will\n                        // be part of a users set of libraries. For now we can ignore this\n                        if (!library) { return; }\n                        const el = new Element(this._core, getCombinedId(e));\n                        el._update(e);\n                        return el;\n                    })\n                    .filter(Boolean);\n            }\n        }.bind(this);\n        this._searchLoader = new ProgressiveLoader(generator);\n        return this._searchLoader;\n    }\n\n    getSearchResults(searchQuery: string, filters?: SearchFilters, elementSort?: ElementSort) {\n        this.abortSearch();\n        filters = filters || {};\n        const filteredLibraryId = filters && filters.library_id;\n\n        if (this._driver instanceof HybridDriver) { return this.getHybridSearchResults(searchQuery, filters, elementSort); }\n\n        const generator: (signal: AbortSignal) => AsyncIterableIterator<Element[]> = async function *(\n            this: CCLibraries,\n            signal: AbortSignal\n        ) {\n            const elementsToLoadPerLibrary = new Map<Library, ElementData[]>();\n            // Need to store libraryIds for libraries we have cleared so we dont clear any search results we have loaded from previous pages\n            const cleared: string[] = [];\n            for await (const page of this._driver.getSearchResults(\n                searchQuery,\n                filters as SearchFilters,\n                elementSort as ElementSort,\n                signal\n            )) {\n                await page.forEach((elementData: any) => {\n                    const libraryId: string = elementData.libraryId || filteredLibraryId;\n                    let library = this.getLibraryById(libraryId);\n\n                    // If the library and its elements are already loaded, we don't need to do anything\n                    if (library && library.areElementsLoaded) {\n                        return elementData;\n                    }\n\n                    if (!library) {\n                        library = this._libraryCache.add(\n                            createLibraryData({\n                                id: libraryId,\n                                name: libraryId, // Just make it the library ID for now, since this doesn't appear anywhere,\n                                areElementsLoaded: false,\n                                isLibraryLoaded: false\n                            })\n                        );\n\n                        // We don't need to clear the library elements since we are creating this library, so we know it's empty\n                        cleared.push(libraryId);\n                    }\n\n                    // We only want to clear the library elements once so we dont clear any search results we have loaded from previous pages\n                    // We also want to abort the loadElements here so that we dont continue to load elements\n                    if (!cleared.includes(libraryId)) {\n                        library!.abortLoadElements();\n                        library!.clearElements(false);\n                        cleared.push(libraryId);\n                    }\n\n                    // Add this as an element to load for the library\n                    const elementsToLoad: ElementData[] = elementsToLoadPerLibrary.get(library!) || [];\n                    elementsToLoad.push(elementData);\n                    elementsToLoadPerLibrary.set(library!, elementsToLoad);\n\n                    return elementData;\n                });\n\n                for (const [ library, elements ] of elementsToLoadPerLibrary) {\n                    await library.loadGivenElements(elements, false, false);\n                }\n\n                elementsToLoadPerLibrary.clear();\n\n                yield page.map((elementData: ElementData) => {\n                    const libraryId = elementData.libraryId || filteredLibraryId;\n                    if (!libraryId) {\n                        return;\n                    }\n                    const library = this.getLibraryById(libraryId);\n                    return library?.getElementById(elementData.id);\n                }) as Element[];\n            }\n        }.bind(this);\n        this._searchLoader = new ProgressiveLoader(generator);\n        return this._searchLoader;\n    }\n\n    abortSearch(): void {\n        if (this._searchLoader) {\n            this._searchLoader.abort();\n        }\n    }\n\n    /* Utils */\n\n    /**\n     * The {@link LibraryError} class, which gives you access to all the error codes.\n     *\n     * @type {LibraryError}\n     * @memberof CCLibraries\n     */\n    static errors = LibraryError;\n\n    /**\n     * @memberof CCLibraries\n     */\n    static utils = {\n        getExtensions,\n        getMimeTypes\n    };\n\n    private copyFile(source: string, destination: string, allowOverride?: boolean) {\n        return this.driver.copyFile(source, destination, allowOverride);\n    }\n\n    private getInstalledVersion(appCode: string) {\n        return this.driver.getInstalledVersion(appCode);\n    }\n\n    private getFileSize(path: string) {\n        return this.driver.getFileSize(path);\n    }\n\n    private getRenditionGrid(library: Library) {\n        return this.driver.getRenditionGrid(library);\n    }\n\n    /* Configuration and Settings */\n\n    /**\n     * Get a value from the current configuration\n     *\n     * @param {String} option The name of the option.\n     * @returns {*} The value of the option.\n     * @memberof CCLibraries\n     */\n    @observable('configChange')\n    getOption(key: keyof typeof LibraryConstants): any {\n        const lowerCamelKey = toLowerCamel(key);\n        // Prefer options provided from the REST API, fall back onto library constants\n        return (this._driver?.config?.processInfo as any)?.[lowerCamelKey] || (LibraryConstants as any)[key];\n    }\n\n    /**\n     * Store a local setting. In shared local storage mode, this persists to the local machine via the CCLibrary process, and is shared across apps.\n     *\n     * @param {String} key The key for the setting.\n     * @param {*} value The value of the setting (must be serializable to JSON)\n     * @throws {LibraryError.INVALID_PARAMETER}\n     * @memberof CCLibraries\n     */\n    async setLocalSetting(key: string, value: any) {\n        try {\n            JSON.stringify(value);\n        } catch (e) {\n            throw new LibraryError('INVALID_PARAMETER', 'Value must be serializable to JSON');\n        }\n        await this._driver.setLocalSetting(key, value);\n    }\n\n    /**\n     * Retrieve a local setting. (In Shared Local Storage mode, this is a setting on disk shared with other apps.)\n     *\n     * @param {String} key The key for the setting.\n     * @returns {*} The value of the setting.\n     * @memberof CCLibraries\n     */\n    @observable('configChange')\n    getLocalSetting(key: string) {\n        return this._driver.getLocalSetting(key);\n    }\n\n    /**\n     * Get the current locale of the API (there are a few strings internal to the API that depend on this locale) - this can be configured\n     * via {@link CCLibraries.setLocale}.\n     *\n     * @returns {SupportedLocale} The current locale (e.g. `'en-US'`)\n     * @memberof CCLibraries\n     */\n    getLocale(): SupportedLocale {\n        return this._intl.locale as SupportedLocale;\n    }\n\n    /**\n     * Set the current locale of the API (there are a few strings internal to the API that depend on this locale).\n     *\n     * @returns {Promise<SupportedLocale>} a promise resolving to the locale that was set (could be different than locale requested if not supported).\n     * @memberof CCLibraries\n     */\n    setLocale(locale: SupportedLocale): Promise<SupportedLocale> {\n        return this._intl.setLocale(locale);\n    }\n\n    /* (Shared Local Storage) CC Libraries Process */\n\n    /**\n     * Test whether the API is connected to the shared local storage service.\n     *\n     * This is only supported if the `SHARED_LOCAL_STORAGE` option is enabled.\n     *\n     * @returns {Boolean} Whether or not the API is connected to the shared local storage service.\n     * @throws {LibraryError.NOT_SUPPORTED}\n     * @memberof CCLibraries\n     */\n\n    @observable('driverConnect', 'driverDisconnect', 'loaded')\n    isConnected(): boolean {\n        return Boolean(this.driver.isConnected);\n    }\n\n    @observable('driverConnect', 'driverDisconnect', 'loaded', 'connecting', 'failedConnection')\n    get connectionState() {\n        return this.driver.connectionState;\n    }\n\n    /**\n     * Try to reconnect to the shared local storage service, if the connection was broken.\n     *\n     * This is only supported if the `SHARED_LOCAL_STORAGE` option is enabled.\n     *\n     * @throws {LibraryError.NOT_SUPPORTED}\n     * @memberof CCLibraries\n     */\n    reconnect() {\n        if (this.isConnected()) {\n            return;\n        }\n        this._driver?.connect();\n    }\n\n    /**\n     * Disconnect from shared local storage service.\n     *\n     * This is only supported if the `SHARED_LOCAL_STORAGE` option is enabled.\n     *\n     * @throws {LibraryError.NOT_SUPPORTED}\n     * @memberof CCLibraries\n     */\n    disconnect() {\n        this._driver?.disconnect();\n    }\n\n    /**\n     * Returns `true` if library syncing is enabled. If syncing is disabled, libraries will not be automatically pushed\n     * when modified and we will not get remote updates.\n     */\n    @observable('configChange')\n    isSyncingEnabled() {\n        return this._driver.config.processInfo?.syncingEnabled;\n    }\n\n    /**\n     * Turn on library syncing, if it's not already enabled. This causes all loaded libraries to be pulled.\n     * Any queued actions will be pushed.\n     */\n    enableSyncing() {\n        this._libraryCache.resume();\n        return this._setSyncEnabledConfig(true);\n    }\n\n    /**\n     * Turn off library syncing. In-flight requests will be allowed to finish, unless explicitly specified.\n     *\n     * @param halt  Should in-flight requests be aborted?\n     */\n    async disableSyncing(halt = false) {\n        await this._setSyncEnabledConfig(false);\n        this._libraryCache.pause(halt);\n    }\n\n    private async _setSyncEnabledConfig(enabled: boolean) {\n        return this.setLocalSetting('processInfo', { ...this._driver.config.processInfo, syncingEnabled: enabled });\n    }\n\n    private async _resolveLibrary(idOrAssetId: string): Promise<Library | void> {\n        const resolutionKey = `library#${idOrAssetId}`;\n        // If we're already resolving this library, return the existing promise.\n        if (!this._resolutionProgressMap.has(resolutionKey)) {\n            const resolveLibrary = this.driver\n                .getLibraryById(idOrAssetId)\n                .then(libraryData => {\n                    // Add the library to the cache so we can find it synchronously next time.\n                    this._libraryCache.upsert(libraryData);\n                    return this._libraryCache.get(libraryData.id);\n                })\n                .catch(error => {\n                    if ((error as RequestError).requestErrorCode !== 'NOT_FOUND') {\n                        // If we got an error other than 404, make sure we log it and let it float for handling.\n                        Logger.log(String(error));\n                        throw error;\n                    }\n                })\n                .finally(() => {\n                    // Remove the promise from the map so we can try again next time.\n                    this._resolutionProgressMap.delete(resolutionKey);\n                });\n            this._resolutionProgressMap.set(resolutionKey, resolveLibrary);\n        }\n        return this._resolutionProgressMap.get(resolutionKey);\n    }\n\n    private async _resolveElementById(\n        library: Library,\n        elementId: string,\n        includeRemovedElements = false\n    ): Promise<Element | undefined> {\n        if (!library) {\n            return;\n        }\n\n        // First try to get locally.\n        const element = library.getElementById(elementId, !includeRemovedElements);\n\n        if (element) {\n            return element;\n        }\n\n        // Otherwise, fetch the element from the services.\n        try {\n            const elementData = await this.driver.getElement(library, elementId);\n            // Add it to the library for next time.\n            library.loadGivenElements([ elementData ], false, true);\n            return library.getElementById(elementId, !includeRemovedElements);\n        } catch (error) {\n            if ((error as RequestError).requestErrorCode !== 'NOT_FOUND') {\n                // If we got an error other than 404, make sure we log it and let it float for handling.\n                Logger.log(String(error));\n                throw error;\n            }\n            return;\n        }\n    }\n\n    /**\n     * Resolve the given library id against cloud storage.\n     * This is different from {@link CCLibraries.getLibraryById} in that\n     * a resolved value of `undefined` means that the library does not exist in cloud storage, not merely in the local cache.\n     * @param {string} id\n     * @returns {Promise<Library | undefined>}\n     */\n    async resolveLibraryById(id: string) {\n        // If the library is loaded and cached, return it.\n        await this._libraryCache.waitForHydrate();\n        const cachedLibrary = this.getLibraryById(id);\n        if (cachedLibrary) {\n            return cachedLibrary;\n        }\n\n        // Otherwise, fetch the library from the services.\n        return this._resolveLibrary(id);\n    }\n\n    /**\n     * Resolve the given asset id against cloud storage.\n     * This is different from {@link CCLibraries.getLibraryByAssetId} in that\n     * a resolved value of `undefined` means that the library does not exist in cloud storage, not merely in the local cache.\n     * @param {string} assetId\n     * @returns {Promise<Library | undefined>}\n     */\n    async resolveLibraryByAssetId(assetId: string) {\n        // If the library is loaded and cached, return it.\n        await this._libraryCache.waitForHydrate();\n        const cachedLibrary = this.getLibraryByAssetId(assetId);\n        if (cachedLibrary) {\n            return cachedLibrary;\n        }\n        // Otherwise, fetch the library from the services.\n        return this._resolveLibrary(assetId);\n    }\n\n    /**\n     * Resolve the given asset id by fetching it from cloud storage.\n     * This bypasses the cache to force and element to be re-fetched.\n     * @param {string} assetId\n     * @returns {Promise<Library | undefined>}\n     */\n    async resolveLibraryWithoutCache(assetId: string) {\n        return this._resolveLibrary(assetId);\n    }\n\n    /**\n     * Resolve the given library reference to a library object using the libraries in memory.\n     * If the reference cannot be resolved against the cache, a background request will be made to\n     * {@link CCLibraries#resolveLibraryReference} to attempt resolving the reference against Library services;\n     * if resolved in the background, the library will be entered into the cache and a 'change' event will be emitted,\n     * making this method observable with respect to the libraries list/libraries cache.\n     * While the remote resolution request is in progress, this method will return `undefined`;\n     * if the remote resolution comes back empty, the return value will be `null`. Additionally,\n     * once the state of the reference is known, a 'resolutionStatusChange' event will be emitted,\n     * making this method observable with respect to that as well.\n     * Usually it's better to call {@link CCLibraries#resolveLibraryReference} directly.\n     * @param libraryRef library reference to be resolved\n     * @returns {Library} The library object that is represented with the given library reference (or `undefined` if library cannot be found).\n     * @memberof CCLibraries\n     */\n    @observable('change', 'resolutionStatusChange')\n    resolveCachedLibraryReference(linkRef: ElementReference | LibraryReference): Library | null | undefined {\n        if (!linkRef) {\n            return;\n        }\n\n        const { libraryId } = getAssetAndFragmentIdFromReference(linkRef) as NonNullable<\n        ReturnType<typeof getAssetAndFragmentIdFromReference>\n        >;\n        if (!libraryId) {\n            return;\n        }\n\n        const cachedLibrary = this.getLibraryById(libraryId);\n        if (cachedLibrary) {\n            return cachedLibrary;\n        }\n\n        // No cached match was found, return the status of the reference and trigger an async resolution in the background, if unknown.\n        return this._getLinkReferenceStatus(linkRef);\n    }\n\n    /**\n     * Resolve the given library reference to a library, if it exists. This is useful if {@link CCLibraries#resolveElementReference} returns\n     * undefined (i.e. the element doesn't exist), since it lets you check whether the library exists.\n     * A reference for an element can be retrieved using {@link Element.getReference}.\n     * Compatible with legacy element references, and the parsed and stringified new link schemas.\n     *\n     * @param libraryRef element reference to be resolved\n     */\n    async resolveLibraryReference(libraryRef: LibraryReference): Promise<Library | void> {\n        if (!libraryRef) {\n            return;\n        }\n\n        const { libraryAssetId, libraryId } = getAssetAndFragmentIdFromReference(libraryRef) as NonNullable<\n        ReturnType<typeof getAssetAndFragmentIdFromReference>\n        >;\n        if (!libraryAssetId && !libraryId) {\n            return;\n        }\n\n        if (this.isLocallyManaged) {\n            // The LocalDriver resolver handles only libraryIds.\n            return this.resolveLibraryById(libraryId);\n        }\n\n        // The CloudDriver resolver handles assetIds, it can also handle libraryIds but only for libraries in personal storage.\n        // A link reference should always have an assetId. The exception are legacy links, but we only support those on desktop.\n        return this.resolveLibraryByAssetId(libraryAssetId);\n    }\n\n    /**\n     * Resolve the given element reference to an element object if exists.\n     * A reference for an element can be retrieved using {@link Element#getReference}.\n     *\n     * @param reference of an element that is requested to be resolved.\n     * @param includeRemovedElements whether to allow resolving to an available removed element.\n     * @returns {Element} The element object that is represented with the given element reference (or `undefined` if element cannot be found).\n     * @memberof CCLibraries\n     */\n    async resolveElementReference(\n        elementRef: ElementReference,\n        includeRemovedElements = false\n    ): Promise<Element | undefined> {\n        if (!elementRef) {\n            return;\n        }\n\n        const { elementId } = getAssetAndFragmentIdFromReference(elementRef) as NonNullable<\n        ReturnType<typeof getAssetAndFragmentIdFromReference>\n        >;\n        if (!elementId) {\n            return;\n        }\n        const library = await this.resolveElementReferenceToLibrary(elementRef);\n        if (!library) {\n            return;\n        }\n        return this._resolveElementById(library, elementId, includeRemovedElements);\n    }\n\n    /**\n     * Resolve the given element reference to an element object using the libraries and elements in memory.\n     * If the reference cannot be resolved against the cache, a background request will be made to\n     * {@link CCLibraries#resolveElementReference} to attempt resolving the reference against Library services;\n     * if resolved in the background, the element will be entered into the cache and a 'change' event will be emitted,\n     * making this method observable with respect to the libraries model.\n     * While the remote resolution request is in progress, this method will return `undefined`;\n     * if the remote resolution comes back empty, the return value will be `null`. Additionally,\n     * once the state of the reference is known, a 'resolutionStatusChange' event will be emitted,\n     * making this method observable with respect to that as well.\n     * Usually it's better to call {@link CCLibraries#resolveElementReference} directly.\n     * @param elementRef element reference to be resolved\n     * @param reference of an element that is requested to be resolved.\n     * @param includeRemovedElements whether to allow resolving to an available removed element.\n     * @returns {Element} The element object that is represented with the given element reference (or `undefined` if element cannot be found).\n     * @memberof CCLibraries\n     */\n    @observable('change', 'resolutionStatusChange')\n    resolveCachedElementReference(\n        elementRef: ElementReference,\n        includeRemovedElements = false\n    ): Element | null | undefined {\n        if (!elementRef) {\n            return;\n        }\n\n        const { libraryId, elementId } = getAssetAndFragmentIdFromReference(elementRef) as NonNullable<\n        ReturnType<typeof getAssetAndFragmentIdFromReference>\n        >;\n        if (!libraryId || !elementId) {\n            return;\n        }\n\n        const cachedLibrary = this.getLibraryById(libraryId);\n        const cachedElement = cachedLibrary?.getElementById(elementId, !includeRemovedElements);\n        if (cachedElement) {\n            return cachedElement;\n        }\n\n        // No cached match was found, return the status of the reference and trigger an async resolution in the background, if unknown.\n        return this._getLinkReferenceStatus(elementRef, true, includeRemovedElements);\n    }\n\n    /**\n     * Resolve the given element reference to a library, if it exists. This is useful if {@link CCLibraries#resolveElementReference} returns\n     * undefined (i.e. the element doesn't exist), since it lets you check whether the library exists.\n     * A reference for an element can be retrieved using {@link Element.getReference}.\n     * Compatible with legacy element references, and the parsed and stringified new link schemas.\n     *\n     * @param elementRef element reference to be resolved\n     */\n    async resolveElementReferenceToLibrary(elementRef: ElementReference): Promise<Library | void> {\n        if (!elementRef) {\n            return;\n        }\n\n        const { libraryAssetId, libraryId } = getAssetAndFragmentIdFromReference(elementRef) as NonNullable<\n        ReturnType<typeof getAssetAndFragmentIdFromReference>\n        >;\n        if (!libraryAssetId && !libraryId) {\n            return;\n        }\n\n        if (this.isLocallyManaged) {\n            // The LocalDriver resolver handles only libraryIds.\n            return this.resolveLibraryById(libraryId);\n        }\n\n        // The CloudDriver resolver handles assetIds, it can also handle libraryIds but only for libraries in personal storage.\n        // A link reference should always have an assetId. The exception are legacy links, but we only support those on desktop.\n        return this.resolveLibraryByAssetId(libraryAssetId);\n    }\n\n    /**\n     * Resolve the given element reference to the library, using libraries in memory.\n     * If the reference cannot be resolved against the cache, a background request will be made to\n     * {@link CCLibraries#resolveElementReferenceToLibrary} to attempt resolving the reference against Library services;\n     * if resolved in the background, the library will be entered into the cache and a 'change' event will be emitted,\n     * making this method observable with respect to the libraries model.\n     * While the remote resolution request is in progress, this method will return `undefined`;\n     * if the remote resolution comes back empty, the return value will be `null`. Additionally,\n     * once the state of the reference is known, a 'resolutionStatusChange' event will be emitted,\n     * making this method observable with respect to that as well.\n     * Usually it's better to call {@link CCLibraries#resolveElementReferenceToLibrary} directly.\n     * @param elementRef element reference to be resolved\n     */\n    @observable('change', 'resolutionStatusChange')\n    resolveCachedElementReferenceToLibrary(elementRef: ElementReference): Library | null | undefined {\n        return this.resolveCachedLibraryReference(elementRef);\n    }\n\n    /**\n     * Returns whether an element reference is known to be missing for the given resolution target.\n     * If the reference is known to be missing, `null` will be returned.\n     * Otherwise, `undefined` will be returned and an async resolution request will be performed against Libraries services\n     * to clarify the status of the element reference.\n     */\n    private _getLinkReferenceStatus(\n        linkRef: ElementReference | LibraryReference,\n        resolveToElement = false,\n        includeRemovedElements = false\n    ): null | undefined {\n        // We need to distinguish between the three resolution target cases (libraries, elements, elements including removed)\n        // so that we don't mark a resolution target as \"missing\" just because the same reference can't be resolved to a different resolution target.\n        const resolutionTargetKey = resolveToElement ? 'element' : 'library';\n        const includeRemovedKey = includeRemovedElements && 'removed';\n        const resolutionKey = `${serializeLinkReference(linkRef)}#${resolutionTargetKey}#${includeRemovedKey}`;\n        const isMissing = this._missingResolutionTargetsMap.get(resolutionKey);\n        // If we've already attempted to resolve this reference asynchronously and failed, we know that the target really is missing,\n        // so no point in searching again. Because the cached resolution methods are observable with respect to changes to the libraries model,\n        // if the target does come in later, watchers will get notified to retry the cache and they'll get a hit.\n        if (isMissing) {\n            return null;\n        }\n        // Status unknown, return `undefined` and trigger an async resolution in the background.\n        this._resolveElementReferenceAndNotify(linkRef, resolutionKey, resolveToElement, includeRemovedElements);\n        return undefined;\n    }\n\n    /**\n     * Performs a previously failed cached element reference resolution asynchronously in the background.\n     * After the async resolution is performed, if a match was found, a 'change' event will be emitted to\n     * notify watchers that they should recompute any values dependent on the result of this resolution.\n     * See {@link CCLibraries#resolveCachedElementReference} and {@link CCLibraries#resolveCachedElementReferenceToLibrary}\n     */\n    private _resolveElementReferenceAndNotify(\n        elementRef: ElementReference,\n        resolutionKey: string,\n        resolveToElement = false,\n        includeRemovedElements = false\n    ) {\n        // Don't make the same request more than once at the same time.\n        if (!this._resolutionProgressMap.has(resolutionKey)) {\n            const resolveMethod = resolveToElement\n                ? this.resolveElementReference.bind(this)\n                : this.resolveElementReferenceToLibrary.bind(this);\n            // A successful resolution will result in a 'change' event that watchers can use to know they should re-attempt the cached resolution.\n            const resolveReference = resolveMethod(elementRef, includeRemovedElements)\n                .then((item: void | Element | Library) => {\n                    // Mark whether we were able to resolve the reference asynchronously, so that we don't try again.\n                    this._missingResolutionTargetsMap.set(resolutionKey, !item);\n                })\n                .finally(() => {\n                    // Remove the operation from the in-progress map.\n                    this._resolutionProgressMap.delete(resolutionKey);\n                });\n            // Add this resolution to an in-progress map, to avoid the same request being performed at the same time.\n            this._resolutionProgressMap.set(resolutionKey, resolveReference);\n        }\n        return this._resolutionProgressMap.get(resolutionKey);\n    }\n\n    /**\n     * Opens a specific view in Creative Cloud Desktop\n     * @param path\n     */\n    openInCCD(path: string) {\n        return this._driver.openInCCD(path);\n    }\n\n    /**\n     * Does the libraries API have a connection to the local system process?\n     */\n    get canAccessLocalProcess() {\n        return this._driver instanceof LocalDriver;\n    }\n\n    getAccessToken(userId: string, clientId: string, clientSecret: string, scopes: string) {\n        return this._driver.fetchAccessToken(userId, clientId, clientSecret, scopes);\n    }\n\n    getLibraryByToolkitId(toolkitId: keyof typeof toolkitNames): Library {\n        let [ toolkitLibrary ] = this.libraries\n            .filter(library => library.toolkitId === toolkitId)\n            .sort((t1, t2) => t1.created - t2.created);\n\n        if (!toolkitLibrary) {\n            const toolkitName = this.translate(toolkitNames[toolkitId]);\n            toolkitLibrary = this.createLibrary(toolkitName as string);\n            toolkitLibrary.toolkitId = toolkitId;\n        }\n\n        return toolkitLibrary;\n    }\n\n    /**\n     * Get the default library - this is the oldest library that belongs to you, or a custom default library\n     * set via {@link CCLibraries#setDefaultLibrary}. If a custom default library is set and we need to load it asynchronously,\n     * then while the resolution request is in progress, this method will return `undefined`, and if\n     * the remote resolution comes back empty, the return value will fall back to the oldest library.\n     * A custom default library can be any library, as long as the user has write access to it,\n     * but only personal libraries can be the fallback default library, so it's possible to have a non-zero number of libraries, but no default library.\n     *\n     * @returns {Library|undefined|null} The default library, `undefined` if trying to resolve the custom default, or `null` if there is no default library\n     */\n    getDefaultLibrary(): Library | undefined | null {\n        // This call makes `getDefaultLibrary` observable with respect to `configChange` events.\n        const customDefaultLibrary = this.getLocalSetting('defaultLibrary');\n        if (customDefaultLibrary) {\n            const { id, assetId } = customDefaultLibrary;\n            // The custom default library may not have been loaded yet.\n            // We use `resolveCachedElementReferenceToLibrary` to try and find the library in the cache,\n            // triggering a fetch on the library if not found. By using `resolveCachedElementReferenceToLibrary` we\n            // make `getDefaultLibrary` observable with respect to a potential resolution attempt,\n            // allowing this function to remain synchronous while enabling observers to react to an asynchronous resolution.\n            const result = this.resolveCachedElementReferenceToLibrary({\n                'repo:assetId': assetId,\n                'stRef:documentID': id,\n                'stRef:fromPart': ''\n            });\n            if (result === undefined || result?.isWritable) {\n                // If we're still trying to resolve the library, inform the caller by returning undefined.\n                return result;\n            }\n        }\n\n        // If we've reached this point, the user has no library selected as the default library or the selected\n        // default library is deleted.\n        // If the \"disableFallbackDefaultLibrary\" option is true, then we are configured to return nothing\n        if (this._options.disableFallbackDefaultLibrary) {\n            return null;\n        }\n\n        // If the user has no default library selected and the application is configured to always return a library,\n        // then find and return the oldest private library as the default library\n        return this.libraries.reduce((defaultLibrary: Library | null, library) => {\n            const isOlder = !defaultLibrary || (defaultLibrary.created || 0) > (library.created || 0);\n            return library.ownership === 'private' && isOlder ? library : defaultLibrary;\n        }, null);\n    }\n\n    /**\n     * Set a custom default library - this overrides the default value returned by {@link CCLibraries#getDefaultLibrary}\n     * Only libraries that the user has edit access to can be marked as the default library.\n     * Passing a falsy value will result in the default library being reset.\n     */\n    setDefaultLibrary(library?: Library) {\n        if (library && !library.isWritable) {\n            throw new LibraryError('INVALID_PARAMETER', 'Read-only libraries cannot be set as default');\n        }\n        this.setLocalSetting('defaultLibrary', { id: library?.id, assetId: library?.assetId });\n        // We need to monitor the library for id changes, so that we can keep the local setting entry up to date.\n        this._setDefaultLibraryMonitor();\n    }\n\n    private _setDefaultLibraryMonitor() {\n        // Clear any existing monitor.\n        this._disposeDefaultLibraryMonitor?.();\n\n        const defaultLibrary = this.getDefaultLibrary();\n        if (defaultLibrary) {\n            const { id, assetId } = defaultLibrary;\n            const defaultLibraryMonitor = () => {\n                if (defaultLibrary.id !== id || defaultLibrary.assetId !== assetId) {\n                    // If the default library identifiers have changed, update the local setting entry.\n                    this.setDefaultLibrary(defaultLibrary);\n                }\n            };\n\n            // Keep a reference to the monitor so we can dispose of it later.\n            this._disposeDefaultLibraryMonitor = () => defaultLibrary.off('change', defaultLibraryMonitor);\n            defaultLibrary.on('change', defaultLibraryMonitor);\n        }\n    }\n\n    /**\n     * Sync Status information including overarching state and progress information\n     *\n     * @readonly\n     * @type {SyncStatus}\n     * @memberof CCLibraries\n     */\n    @observable('sync')\n    get syncState(): SyncStatus {\n        return this._libraryCache.syncStatus;\n    }\n\n    /**\n     * @deprecated\n     */\n    get retryTime(): undefined {\n        return undefined;\n    }\n\n    /**\n     * @deprecated\n     */\n    getTempDir(library: Library): Promise<string> {\n        return this.driver.getTempDir(library);\n    }\n\n    /*\n     * END: Sync stubs\n     */\n    @requiresLocalDriver\n    get fontManager() {\n        return this._fontManager;\n    }\n\n    get isLocallyManaged(): boolean {\n        return this.driver instanceof LocalDriver;\n    }\n\n    /**\n     * Publishes a brand.\n     * NOTE: The brand role must be set on a brand's app metadata before it can be published.\n     * @param brand The brand that should be published\n     */\n    @requiresCloudDriver\n    publishBrand(brand: Library) {\n        return this._driver.publishBrand(brand);\n    }\n\n    /**\n     * Unpublish a brand.\n     * @param brand The brand that should be unpublished.\n     */\n    @requiresCloudDriver\n    unpublishBrand(brand: Library) {\n        return this._driver.unpublishBrand(brand);\n    }\n}\n","/*************************************************************************\n *\n * ADOBE CONFIDENTIAL\n * ___________________\n *\n *  Copyright 2019 Adobe Systems Incorporated\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Adobe Systems Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Adobe Systems Incorporated and its\n * suppliers and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe Systems Incorporated.\n **************************************************************************/\n\nimport 'abort-controller/polyfill';\n\nimport { getExtensions, getMimeTypes, canComputeRenditionFromMimeType } from './utils/MimeTypeUtils';\nimport { tlsDiscoveryPortRange } from './config/constants';\nimport { isPlaceholder } from './models/utils';\nimport { parseLinkReference, serializeLinkReference } from './utils/LinkUtils';\nimport { estimateUploadTime } from './utils/FileUtils';\n\nexport const utils = {\n    mimeTypeToExtensions: getExtensions,\n    extensionToMimeTypes: getMimeTypes,\n    canComputeRenditionFromMimeType,\n    getSNISettings: () => ({\n        TLS_DISCOVERY_PORT_RANGE: tlsDiscoveryPortRange\n    }),\n    isPlaceholderId: isPlaceholder,\n    parseLinkReference,\n    serializeLinkReference,\n    estimateUploadTime\n};\nexport { default as LocalDriver } from './drivers/LocalDriver';\nexport { default as CloudDriver } from './drivers/CloudDriver';\nexport { default as HybridDriver } from './drivers/HybridDriver';\nexport { default as cepConnector } from './connectors/cepConnector';\nexport { default as ccdConnector } from './connectors/ccdConnector';\nexport { default as nodeConnector } from './connectors/nodeConnector';\nexport { default as uxpConnector } from './connectors/uxpConnector';\nexport { default as ProgressiveLoader } from './utils/ProgressiveLoader';\nexport { default as Element } from './models/Element';\nexport { default as LibraryContents } from './models/LibraryContents';\nexport { default as Representation } from './models/Representation';\nexport { default as Group } from './models/Group';\n\nexport { default } from './CCLibraries';\n"],"names":["ShowModalResultType","CDO","ContentViewType","OtherFileTypeValues","GenericFileTypeValues","AdobeFileTypeValues","LibrariesAndBrandsTypeValues","GenStudioBrandTypeValues","FireflyGenerationTypeValues","SharedViewTypeValues","SAMLogLevel","CDOLogLevel","AccountType","PickerMode","GetBlockedAssetsResponse","Capability","LinkStatus","Role","MessageType","RequestActionTypes","ElementType","Relationship","AssetSyncStatus","AssetSyncSuspensionReason","CommitStatus","CloudSyncStatus","NetworkStatus","PostType","BoardMemberRole","BoardType","AvatarSizes","Env","AssetListStatus","OrderDirection","OrderField","LogLevel","SAMErrorCode","SAMErrorSubCode","ProblemType","IFrameioAuthenticationStatus","CustomModelPublishedState","CustomModelOrderBy","RelType","IProjectPatchKeys","ProjectViews","ProjectCapabilities","ProjectLeaveReason","CanCreateProjectReason","ProjectDirectorySubtype","Permission","AssignmentStatus","AssignmentSubmissionOwnershipEnums","AssignmentTaskIDEnums","ClassroomMemberRole","ClassroomMemberStatus","ClassroomMemberInviteSource","LearningManagementSystems","LearningManagementSystemRoles","RosterImportState","ImportSourceType","ClassroomStatus","ClassroomType","SubjectTypes","ClassroomRole","BlockApiSuccessResponses","MembershipStatus","CoTeacherEligibilityStatus","CoTeacherIneligibilityReason","GenerationHistoryAssetType","GenerationHistoryAssetOrderBy","GenerationHistoryAssetState","LibraryOrderBy","LibraryOwnerFilter","LibraryProjectFilterEnum","LibraryReferenceFilter","LibraryRolesFilter","BrandPublishMetadataFilter","MoveWarning","CannotMoveReason","StudentAssignmentStatus","StudentAssignmentOwner","RenditionStatus","RenditionSize","RenditionType","Mode","View","ActionType","ClickSelectType","Object","assign","SAM.SAMErrorCode","SAM.SAMErrorSubCode","errorCodeInfos","Map","code","AUTHORIZATION_ERROR","message","href","ACCESS_DENIED","NOT_FOUND","CONFLICT","validateRepositoryCode","parseInt","Math","floor","SAMErrorName","SAMError","Error","description","additionalInfo","subCode","undefined","underlyingError","errorStr","String","formatUnderlyingError","super","cause","this","_additionalInfo","name","wrapErrorIfNeeded","create","createWithResponse","response","status","info","get","responseUrl","url","reqId","headers","breadcrumbTrail","UNKNOWN","createWithResponseAndDescription","createWithRepositoryCode","problemType","QUOTA_EXCEEDED","FULL_CLOUD_STORAGE","validHTTPCode","createWithApolloError","error","networkError","graphQLErrors","length","createWithGraphQLError","extensions","httpErrorCode","type","isSAMError","__rest","s","e","t","p","prototype","hasOwnProperty","call","indexOf","getOwnPropertySymbols","i","propertyIsEnumerable","__decorate","decorators","target","key","desc","d","c","arguments","r","getOwnPropertyDescriptor","Reflect","decorate","defineProperty","__param","paramIndex","decorator","__await","v","__asyncGenerator","thisArg","_arguments","generator","Symbol","asyncIterator","TypeError","g","apply","q","verb","n","Promise","a","b","push","resume","value","resolve","then","fulfill","reject","settle","f","shift","__asyncDelegator","o","iterator","done","__asyncValues","m","next","__values","KeysProperty","propertyKey","parameterIndex","map","has","BAD_REQUEST","set","cacheImpl","validate","descriptor","method","async","args","keyIndex","_core","_environment","cache","getItem","arg1","arg2","arg3","memo","property","SAMEvent","constructor","_type","toString","CHANGE","ChangeEvent","SharedChangeEvent","$OBSERVABLE_MAP","observableImpl","event","privatePropNames","forEach","prop","obj","setEventForProp","getter","mobx","reportObserved","newMethod","observable","Array","isArray","concat","global","factory","module","exports","UriTemplate","uriTemplateGlobalModifiers","uriTemplateSuffices","notReallyPercentEncode","string","encodeURI","replace","doubleEncoded","substring","isPercentEncoded","encodeURIComponent","uriTemplateSubstitution","spec","modifier","charAt","separator","prefix","shouldEscape","showVariables","trimEmptyString","varNames","varList","split","varSpecs","varSpecMap","varName","truncate","parts","suffices","varSpec","substitution","valueFunction","result","startIndex","keys","j","first","unSubstitution","stringValue","resultObj","strict","arrayValue","hasEquals","splice","innerArrayValue","objectValue","innerValue","innerVarName","decodeURIComponent","k","specIndexMap","firstStarred","lastStarred","template","textParts","prefixes","substitutions","unSubstitutions","part","remainder","funcs","fill","fromUri","substituted","options","nextPart","offset","endPart","nextPartPos","fillFromObject","test","uri","JSON_MIME_TYPE","JSON_PATCH_MIME_TYPE","validateLinks","links","requirements","hasMissingHrefs","some","link","hasAllParameters","every","params","templateString","getTemplateFromLinks","param","validateLinkParameters","getLink","getURLFromLinks","preparedParams","JSON","parse","stringify","val","getRetryAfterHeader","retryAfterHeader","retryTime","max","retryDate","Date","now","random","fillURLTemplate","queryParams","VALID_HTTP_RESPONSE_CODES","RETRY_HTTP_RESPONSE_CODES","timeout","attempt","timeoutId","clearTimeout","interval","includes","getValue","retryAfter","getRetryInterval","log","setTimeout","promisesMapProperty","promise","outerResolve","delete","$WeakCacheProperty","originalFn","keyArgs","input","sortedObject","sort","reduce","newObj","stringifyWithSortedKeys","deref","WeakRef","DEFAULT_CACHE_KEEP_ALIVE_TTL","KeepAliveManager","_ttl","_keepAliveMap","getInstance","_instance","setTTL","ttl","add","existingTimer","keepAlive","originalMethod","catch","privateData","WeakMap","wrappers","pd","retv","console","assert","setCancelFlag","data","passiveListener","cancelable","canceled","preventDefault","Event","eventTarget","eventPhase","currentTarget","stopped","immediateStopped","timeStamp","enumerable","defineRedirectDescriptor","configurable","defineCallDescriptor","getWrapper","proto","wrapper","BaseEvent","CustomEvent","writable","isFunc","defineWrapper","getPrototypeOf","isStopped","setPassiveListener","composedPath","NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","stopPropagation","stopImmediatePropagation","bubbles","Boolean","defaultPrevented","composed","srcElement","cancelBubble","returnValue","initEvent","window","setPrototypeOf","listenersMap","ATTRIBUTE","isObject","x","getListeners","listeners","defineEventAttribute","eventTargetPrototype","eventName","node","listenerType","listener","prev","newNode","passive","once","defineEventAttributeDescriptor","defineCustomEventTarget","eventNames","CustomEventTarget","EventTarget","types","addEventListener","optionsIsObj","capture","removeEventListener","dispatchEvent","wrappedEvent","wrapEvent","err","handleEvent","setEventPhase","setCurrentTarget","AbortSignal","aborted","abortedFlags","defineProperties","toStringTag","AbortController","signals","signal","createAbortSignal","getSignal","abort","controller","self","ac.AbortController","ac.AbortSignal","getRandomValues","crypto","bind","msCrypto","rnds8","Uint8Array","rngBrowserModule","rnds","byteToHex","substr","_nodeId","_clockseq","buf","bth","join","rng","require$$0","bytesToUuid","require$$1","_lastMSecs","_lastNSecs","v1","clockseq","seedBytes","msecs","getTime","nsecs","dt","tl","tmh","v4","ii","uuid","samJsUuid","randomUUID","MobX","_contexts","register","createAtom","instanceInfo","id","references","Set","refId","size","object","atom","onChange","reportChanged","on","off","NotFound","IndexedDBCache","_name","isSupported","indexedDB","request","open","onsuccess","close","_transaction","transactionType","requestsFn","database","_connect","transaction","objectStore","promResult","onerror","oncomplete","ex","itemKey","expiry","setItem","put","deleteItem","_database","version","onupgradeneeded","objectStoreNames","contains","deleteObjectStore","createObjectStore","keyPath","onversionchange","evt","_clear","clear","LocalStorageCache","localStorage","_getKey","storedValue","removeItem","InMemoryCache","items","existingItem","cleanupTimeout","requestedExpiry","MAX_TIME_IN_MEMORY_MS","cleanupTime","min","item","Cache","_userId","_persistentCache","_localCache","computeValue","validateValue","expiryMs","cachedItem","isInvalid","isExpired","expirationDurMsec","synchronized","MESSAGE_LOGGED","CONFIG_CHANGE","ItemListStateChangedEvent","list","MessageLoggedEvent","logLevel","FolderContentChangedEvent","COLLABORATOR_CHANGED","SharedCollaboratorChangedEvent","AppMetadataField","SHELL_VISIBILITY","CC_INHERITED","REVIEW_SOURCE_ASSET","CONVERTED_TO","NON_AUTO_MIGRATABLE","COPIED_IN_LEGACY_SPARK_TO","CC_INHERITABLE","PROJECT_RENDITION","FIREFLY","RapiAppMetadataWildcardNamespaces","CC","CLASSROOM_ASSIGNMENTS","CCX","HZ","NewFormatAppMetadataField","HZ_DOCUMENT_METADATA","CC_CREATED_FROM_UPLOAD","AppMetadataNamespacesRapiFormat","values","element","EmbedAppMetadataFieldsRapiFormat","filter","ns","EmbedAppMetadataFieldsUSSFormat","USSFetchFields","from","COLLABORATION_METADATA","COLLABMETADATA_MINE","REPO_CREATED_BY_CLIENT_ID","CUSTOM_MODEL_METADATA","getUSSFetchFields","SAM.Permission","PERMISSION_ALL","entries","acc","Ack","None","parseEffectivePermissions","permissions","primary","PRIMARY","policy","AC_POLICY","directory","DIRECTORY","appMetadata","APP_METADATA","annotations","ANNOTATIONS","mask","perm","Read","Duplicate","Write","Discard","Restore","Delete","Share","ReadAppMetadata","WriteComment","Rename","Move","CLOUD_CONTENT_ROOT_FOLDER","PROJECTS_INDEX_LINKS","PROJECTS_PRIMARY","PROJECTS_COLLECTION","PROJECTS_CREATE","RESOLVE_PATH","PROJECTS_GRADIENTS_COLLECTION","PROJECTS_CONTEXT","PROJECTS_CAPABILITY","ORGANIZATIONS_COLLECTION","PROJECTS_RECENT","PROJECTS_REFERENCE_PRIMARY","PROJECTS_REFERENCE_CREATE","SAM.ProjectViews","PROJECT_VIEW_TO_SERVICE_MAP","All","Yours","SWY","Admin","Organization","Recent","SAM.ProjectDirectorySubtype","CUSTOM_MODEL_MEDIA_TYPE","CUSTOM_MODEL_RESTRICTED_METADATA_KEYS","isStrictEqual","deepClone","isDeepEqual","ignoreArrayOrder","partialMatch","toISOString","arry1","arry2","slice","keysA","keysB","firstInSet","CacheableResponse","statusText","body","str","_body","TextEncoder","encode","buffer","octets","codePoint","codePointAt","bits","utf8ToArrayBufferWithoutTextEncoder","fromResponse","arrayBuffer","ArrayBuffer","deserialize","json","Headers","base64","binString","atob","base64ToBytes","serialize","headersToObject","bytesToBase64","matches","other","buffer1","buffer2","all","array1","array2","byteLength","index","ok","redirected","text","INTERNAL_ERROR","bytes","TextDecoder","decode","octet","bytesNeeded","fromCodePoint","arrayBufferToStringWithoutTextDecoder","arrayBufferToUtf8","clone","clonedHeaders","bodyUsed","UNSUPPORTED","blob","Blob","formData","responseHeaders","byte","btoa","ResponseCache","getCacheKey","getCachedResponse","cachedResponseData","saveResponseToCache","deleteCachedResponse","DEFAULT_CONFIG","USER_ID","USER_EMAIL","CLIENT_ID","ACCESS_TOKEN","ENVIRONMENT","Production","HOST_PRODUCT_DATA","PRODUCT_ID","PRODUCT_LOCATION","FETCH_REQUEST_TIMEOUT","ASYNC_DEFAULT_DELAY","CACHE_DEFAULT_TTL","CACHE_KEEP_ALIVE_TTL","MIN_RETRY_INTERVAL","MAX_RETRY_INTERVAL","ONS_DOCUMENT_VISIBILITY_TIMEOUT","ONS_DEFAULT_MAX_SUBSCRIPTIONS","ONS_DEFAULT_MAX_ASSETS_PER_SUBSCRIPTION","GRAPHQL_WATCH_QUERY_TTL","ONS_SUBSCRIPTION_TIME_TO_LIVE","ONS_SUBSCRIPTION_RENEW_TIME","INDEXED_DB_VERSION","PROJECTS_LIST_UPDATE_LATENCY","PROJECTS_ITEM_UPDATE_LATENCY","CLASSROOMS_LIST_UPDATE_LATENCY","ASSETS_LIST_UPDATE_LATENCY","USS_LIST_UPDATE_LATENCY","VERSIONS_LIST_UPDATE_LATENCY","GQL_LIST_UPDATE_LATENCY","ASSET_COPY_NAME_FORMAT","ASSET_CONFLICT_NAME_FORMAT","DISABLE_ONS","ENABLE_ONS_CACHE","_VERSION_OVERRIDE_FOR_TEST","HIGH_PRIORITY_RAPI_REQUESTS","LOCALE","SESSION_TYPE","ONS_OVER_AXON","FEATURE_FLAGS","REQUEST_EDGE_BASED_PUBLISHED_LINKS","EXECUTION_CONTEXT_CLIENT_AGENT","ENVIRONMENTS","Stage","LABEL","ACP_CS_HOST","SYNC_SERVICE_HOST","PROJECTS_HOST","ASSIGNMENTS_HOST","INVITATIONS_HOST","TRANSFER_SERVICE_HOST","USS_HOST","XDCE_HOST","REVIEW_SERVICE_HOST","MELVILLE_HOST","MELVILLE_EDGE_HOST","USSv3_HOST","PPS_HOST","BEHANCE_HOST","CLASSROOMS_HOST","COMMENT_HOST","AXON_HOST","ACPC_SUPERGRAPH_HOST","ACPC_SUPERGRAPH_EDGE_HOST","ABS_HOST","WORKFRONT_HOST","isNonEmptyString","configItemValidators","validator","isNumber","hostProductData","Environment","userConfig","_hooks","_isTokenInvalid","featureFlagsConfig","config","invalidOptions","invalidKeys","refreshAccessToken","_config","_cache","persistentCache","_responseCache","setValue","eventPayload","configurationKeyName","dispatch","endpoints","env","getDeviceId","getUserId","_maxNumberOfRetries","logSink","warn","debug","_loggerEvent","level","listenerCount","emit","Info","Debug","Err","Warn","_refreshAccessToken","fetch","numRetries","session","token","authHeader","noOtherHeaders","requestTimeoutMs","noApiKeyHeader","requestInit","auth","requestHeaders","abortController","uncombineSignals","removeListeners","onAbort","combineSignals","timeoutLength","startTime","requestIdString","NETWORK_ERROR","memoize","BECOME_OBSERVED","BECOME_UNOBSERVED","TypedEventEmitter","EventEmitter","ev","payload","callback","_onEventListenerAdded","_onEventListenerRemoved","$OVERRIDE_SET","for","$EXTENSION_SET","$OBSERVABLE_SET","$EMITTER","$OVERRIDDEN_GETTERS","ExtendClass","klass","core","overrides","eventMap","defaultObservableEvent","observableMap","originalProps","getOwnPropertyDescriptors","emitterProps","makePropertyDesc","propertyDesc","emitter","trigger","addListener","removeListener","rest","mappedEventName","handledProps","extendedProps","propertyName","overriddenProps","original","propToEventMap","seenPropNames","propName","observedProps","assertPath","path","normalizeStringPosix","allowAboveRoot","res","lastSegmentLength","lastSlash","dots","charCodeAt","lastSlashIndex","lastIndexOf","posix","cwd","resolvedPath","resolvedAbsolute","process","normalize","isAbsolute","trailingSeparator","joined","arg","relative","to","fromStart","fromEnd","fromLen","toStart","toLen","lastCommonSep","fromCode","out","_makeLong","dirname","hasRoot","end","matchedSlash","basename","ext","start","extIdx","firstNonSlashEnd","extname","startDot","startPart","preDotState","format","pathObject","sep","dir","root","base","_format","ret","delimiter","win32","ItemExclusiveTaskChain","task","onGotOwnership","registerNewTask","newTask","itemTask","ItemBase","lastKnownClientMutation","_lastKnownClientMutation","updateLastKnownClientMutation","waitForMutationPropagationIfNeeded","delay","mutation","waitTime","exclusiveTask","_exclusiveTaskChain","_setExclusiveTaskChain","itemTaskChain","_setId","newId","runExclusiveTask","schedule","runTask","finally","waitCount","COMPATIBLE_ENCODING_PATTERN","WS_TRIM_PATTERN","WS_CHAR_PATTERN","WS_FOLD_PATTERN","DELIMITER_PATTERN","WS_DELIMITER_PATTERN","TOKEN_PATTERN","trim","hasWhitespace","skipWhitespace","needsQuotes","Link","refs","rel","toLowerCase","attr","setUnique","ref","shallowCompareObjects","object1","object2","state","expandRelations","attrValue","isSingleOccurenceAttr","parseExtendedValue","formatAttribute","isCompatibleEncoding","isTokenAttr","escapeQuotes","exec","language","encoding","formatExtendedAttribute","toUpperCase","Buffer","isBuffer","headerRegexp","regexp","fromCharCode","RegExp","createHeaderRegexp","statusRegexp","HttpResponseParser","_text","_index","readLine","endOfLine","END_OF_LINE","line","endsWith","remainderText","clamp","SAMObjectEventEmitter","SAMObjectUntypedEventEmitter","isResponse","isGraphQLResult","Resource","_options","_isLoaded","_etag","isDirty","_activeRevalidations","_loadData","loadData","_onChange","details","load","forceRefresh","isLoaded","unload","_data","_error","etag","_setData","_mergeData","_parse","_parserOverride","parseResponse","errors","parseGraphQLResult","parser","skipRevalidation","skipCache","_setError","onError","getDefaultCacheKey","_cacheKey","responseCache","_interceptFetch","performFetch","cachedResponse","subsequentResponseExpected","performRevalidation","changed","loading","Response","revalidate","existingPromise","PassthroughResource","InterfaceBase","_useHighPriorityRequestsIfEnabled","_sharedResponses","_fetch","successResponseCodes","resource","fetchOptions","_fetchImpl","retryCount","additionalRetryErrorCodes","retryErrorCodes","_getFetchOptionOverrides","_monitorResponse","handleError","_getRetryErrorDelay","_checkResponseStatus","_getMonitorRetryAfter","_fetchMonitorResponse","originalUrl","asyncUrl","asyncResponse","_shouldRetryMonitorResponse","newDelay","statusLine","statusMatch","match","headerName","headerLine","parseAsyncResponse","pow","_doGet","additionalFetchOptions","_doHead","_doPost","_doPatch","_doPut","_doDelete","_getResponse","_getSharedResponse","_getPagedResponse","_page","_links","PAGE","nextHref","_getAllPages","fullResult","readPages","requestFn","children","_getLinksFromHeaders","linkHeader","LinkHeader","otherData","adminModeOrgID","startsWith","requestAsUserID","requestID","executionContextClientAgent","finalizationRegistry","FinalizationRegistry","objUrl","URL","revokeObjectURL","THUMBNAIL_SIZE","Size512","SUPPORTED_SIZES","Size64","Size128","Size256","Size1024","RenditionFetcher","_availableSizes","_fetchRenditionBlob","_entries","_versionToken","_getStandardSize","targetSize","sizes","sortedArray","findIndex","_findURLEntry","clampedSize","find","u","_clearStaleEntries","outdatedVersionToken","filteredEntries","entry","versionToken","_getEntryWithFallback","foundEntry","sizesArray","foundSize","renditionURLStatus","urlStatus","NotStarted","getURL","versionTokenChanged","renditionEntry","newEntry","Fetching","recentlyAddedEntry","renditionBlob","createObjectURL","Done","clearRenditionError","foundErrorEntryIndex","release","unregister","MAX_LENGTH","RESERVED_NAME_REGEX","RESERVED_CHAR_REGEX","validatePlatformRepoName","PATH_REGEX","formatFileName","fullPath","counter","getRegexFormat","extPresent","regexFormat","formatWithoutCount","regexFormatWithoutCount","resultMatchedRegexWithoutCount","newPath","fileExtension","extension","currentCount","filename","newName","countUsed","batchFormatFileName","assetId","sameFolder","assetConflictMap","localCounter","conflictWithOtherFilesInBatch","conflictedAssetIds","formatFileResult","currentValue","ARCHIVE_GUID_REGEX","removeArchiveGuidFromName","ARCHIVE_TO_RESTORE_LOCATION","getRestorePath","archiveIndex","restoreFolder","renameFileInPath","asset","repoPath","updateCachedDescendents","assetPool","operation","assetContext","isFolder","newChildPath","_adobeAssetUpdater","updateLocalItem","ancestorIDs","isDiscarded","_isDiscardedWithParent","getBatchRenamedAssetName","createMilestoneJsonParams","versionId","hasExistingMilestone","label","op","VersionPatchTypes","validateAssetName","assetList","locale","getOtherAssetName","trimmedName","matchingAsset","toLocaleLowerCase","isTopLevelFolder","setURLSearchParams","searchParams","URLSearchParams","search","getBlockTransferThreshold","preferredThreshold","blockInitLink","BLOCK_INITIALIZE","lowerLimit","DEFAULT_MIN_SINGLE_TRANSFER_SIZE","upperLimit","DEFAULT_MAX_SINGLE_TRANSFER_SIZE","FOLDER_TYPE","FOLDER_ALTERNATE_TYPE","BLOCK_SIZE","BULK_TRANSFER_MIME_TYPE","DENY_SHARE_ACE","DENY_EDIT_ACE","EMBEDDED_METADATA","REPO_METADATA","RENDITION","DefaultAssetsListingOptions","orderDirection","orderBy","limit","DefaultVersionsListingOptions","createPageTemplate","templateValues","getDirectionValue","userOptions","getAssetVersionsListingURL","VERSION","createVersionTemplate","TransferURLExpiredError","AssetInterface","_rapi","_assetId","_version","assetID","getChildAssets","embed","assetTypes","excludeAssetTypes","assetSubTypes","filters","getAssetsListingURL","getRepoMetadata","getEmbeddedMetadata","getURLWithVersion","Accept","getAppMetadata","patchAppMetadata","getEffectivePermissions","AC_EFFECTIVE","getAssetPolicy","getManifest","MANIFEST","getVersions","getPerUserMetadata","PERUSER_METADATA","restoreVersionManifest","versionManifestLink","versionManifest","assetManifest","getVersion","patchVersion","createFolder","relativePath","renameOnConflict","CREATE","intermediates","respondWith","nameConflictPolicy","extendTransferUrls","extendLink","useBlockStore","_uploadIndividualBlock","file","_blockUpload","mediaType","isUpdate","milestoneProperties","uploadInfoResult","getBlockUploadInfo","blockSize","initResponse","totalBlocks","ceil","blockIndex","blocksInBatch","blockPromises","_","currentBlockIndex","transferInfo","BLOCK_EXTEND","newBlockInfo","BLOCK_TRANSFER","finalizeBlockUpload","finalizeHref","importFile","preferredBlockTransferThreshold","blockUploadTransferThreshold","versionHistoryPatch","updateFile","metaData","commitFileChanges","initialBlockUploadHref","initBody","blockUploadInfo","BLOCK_FINALIZE","getBlockDownloadURL","presignedUrlExpirationSeconds","getContent","getResourceGenerationNumber","relType","localETag","eTag","restore","_counter","runOperation","discard","runOperationWithEmptyResponse","getRendition","renditionURL","newURL","getCustomRendition","PNG","urlTemplateOptions","additionalHeaders","getAllCustomRenditions","getAccessControlList","accessControlHref","responseJson","_getACPatchData","ace","principal","privileges","inheritance","relations","addAccessControlEntries","aces","aclEtag","acesJSONPatch","_patchACL","updateAccessControlList","deleteAccessControlEntries","setEditingInheritanceRestricted","restrictEdit","addCurrentUserAsEditor","userId","addPatches","userACEs","getRestrictEditUserGrantACEs","policyResponse","denyEditAceIndex","denyShareAceIndex","_getEditingInheritanceRestrictedInfo","removePatches","ace1","ace2","patches","getEditingInheritanceRestricted","acl","denyEditAce","denyShareAce","removeLastAccessed","bodyData","shownWarnings","oneTimeWarning","topic","ManagedPromise","$LAZY_LOAD_MANAGERS","LoadStatus","LazyLoadManager","fetchData","prefetchTimeout","retryErrorTimeout","Number","POSITIVE_INFINITY","cancelFetchData","_loadStatus","NotLoaded","_prefetchTimeout","_retryErrorTimeout","_retriesRemaining","_onBecomeUnobserved","_event","Pending","Loading","_cancelFetchData","_target","setLoadStatus","_prefetchResolve","_fetchData","manageLazyLoading","configs","instance","cfg","manager","getManager","foundEvent","hasManager","loadStatus","getLoadStatus","fetchIfNeeded","updatedExternally","updatedByItemUpdater","_prefetchDelay","onPropertyAccess","_pendingFetchPromise","Loaded","lazyLoaded","ShareableItem","_collaboratorsArray","_shareFlagsAreDirty","_itemPoolDelegate","onItemsUpdated","_setCollaboratorData","_queueCollaborators","_dequeueCollaborators","isShared","_fetchShareFlagsIfNeeded","_isShared","isSharedWithYouAsset","_isSharedWithYouAsset","directCollaboratorCount","_directCollaboratorCount","isPublicLink","_isPublicLink","_isSWYAsset_NoLazyLoad","_isShared_NoLazyLoad","_directCollaboratorCount_NoLazyLoad","_isPublicLink_NoLazyLoad","isSharedWithMe","_isCollaboratorDataLoaded","collaborationContext","_collaboratorRequestQueue","enqueue","dequeue","collaboratorArray","collaborators","_collaboratorSources","_getCollaboratorSources","collaboratorPool","addDelegate","collaboratorSource","removeCollaborator","collaborator","_removeCollaborator","removeCurrentUserFromCollaborationList","_removeCurrentUserFromCollaborationList","createPublicLink","canComment","publicLinkCollaborator","recipient","role","canShare","_addCollaborators","removePublicLink","predefinedPrincipal","shareWithOwnerOrganization","orgEverybody","failedCollaborators","invitedCollaborators","invitedCollaboratorSource","removeInvitedCollaborator","invitedCollaborator","collaboratorItemPool","toArray","isDirect","isCurrentUserDirectCollaborator","isCurrentUser","_isSWYGroup","AdobeAssetResource","_parent","hostAssetContext","onsContext","isActive","setParent","parentAsset","EmbeddedMetadataResource","_ensureLink","assetInterface","_getAssetInterface","AppMetadataResource","_patch","ManifestResource","AssetClassChoices","AssetStateChoices","LocalItemUpdater","_propertyUpdater","propertyUpdater","_changeEvent","changeEvent","_changeEventsMap","changeEventMap","updateSession","localItem","remoteItem","checkIfItemAllowsMutations","ensureItemIsAdded","changedFields","update","changeEvents","changedProperty","getEventForProp","queueChangedItem","ItemUpdaterBase","_localItemType","localItemType","_getRemoteId","getRemoteId","_getAlternateId","getAlternateId","updateRemoteItem","altId","getItemById","reindexItem","LocalItemType","updateRemoteItems","remoteItems","ItemUpdater","remoteIdProperty","formats","isEqual","number","date","date_as_number","boolean","object_subset","destObj","sourceObj","destObjSubset","KEY_REGEXP","makeGetFn","newKeys","getKeys","source","makeSetFn","parsedSource","dest","makeMergeSetFn","normalizeFormat","mapByKey","choices","createPropertyUpdater","userType","sourceName","normalizeType","anyDest","destValGetter","destVal","parsedItem","array","PropertyUpdater","_updaters","updater","propertyChanges","updateObj","SearchProps","USS_ARTIFACT_MEDIATYPE","LastAccessedOrderField","OrderByToUSSOrderBy","created","modified","shared","lastAccessed","EXPRESS_ARTIFACT_TYPE","excludeExpressArtifacts","FIELD_MATCHES","ImplicitAdobeAssetFilterBase","_isDiscarded","_isPublished","_isSharedWithYou","_includeHiddenRecursive","isComposite","sizeInBytes","isLibrary","localID","isPublished","reviewLinkSourceType","shellVisibility","AdobeAssetSearchFilter","_query","query","_deepSearch","deepSearch","_asset","repositoryID","assetRepoPath","compareStrings","localeCompare","compareValues","ItemOrder","direction","field","comparator","hash","sortItems","createItemOrderFactory","comparatorMap","reverseComparator","OrderFieldToIAdobeAssetOrderBy","OrderFieldToComparator","AdobeAssetOrder","default","STORAGE_ASSIGNEE_CHANGED","SharedStorageAssigneeChangedEvent","ModernSet","isDisjointFrom","isSubsetOf","isSupersetOf","intersection","union","difference","symmetricDifference","getMediaTypesFromFilters","implicitFilter","explicitFilter","implicitFilterMediaTypes","getVariableFromObj","explicitFilterMediaTypes","variable","AdobeAssetDirectoryLoader","_assetPool","_includePermissions","_loadLibraryData","supportsFilter","loadPage","_loadPage","pageCursor","order","loadOptions","mediaTypes","librariesDataPromise","isProject","_libraryInterface","getLibrariesForProject","latency","mostRecentValidMutation","createLoaderMutationSession","childrenData","nextPageCursor","ancestors","gqlManager","_getGQLManager","listData","getChildren","after","pageInfo","hasNextPage","endCursor","rapiPage","updaters","_adobeAssetFactory","getRepoMetadataUpdaters","assetsFromRepoMetadata","excludeMediaTypes","librariesInPage","loadNextPage","library","_setLibraryLoadState","_storageAssignee_NoLazyLoad","commit","librariesData","_updateLibrariesData","_getSafeLibraryData","libraryData","library_urn","bookmark","ownership","roles","rendition_grid","librariesToUpdate","createUpdateSession","libraryContext","getLibraryContext","librarySpecificData","_libraryUpdater","DEFAULT_LIMIT","USSv3LoaderHelper","_loader","_getItemData","rm","sharedViaInvite","cm","sharedBy","am","_embedded","shareFlagsAreDirty","getUSSV3ItemData","queryResult","_getUSSResults","queryResults","resultItems","getUSSV3Updaters","createLoaderUpdateSession","_extractItems","total","metadata","totalHits","pageItemCount","nextStartIndex","page","_postProcessPage","assetsFromUSSV3Response","USSAssetFilterName","USSv3OrderField","USSv3OrderFieldMap","Name","Created","Modified","USSv3OrderDir","USSv3OrderDirMap","Ascending","Descending","USSv3FilterField","USSv3Function","USSv3DirectoryType","FetchFields","NOT","funcParams","REVIEW_SOURCE_TYPE","AdobeAssetDirectorySearchLoader","_adobeAssetSearchInterface","_implicitFilter","_ussLoaderHelper","cloudID","ussFilter","uploadedFrom","getFilteredAssets","getFiltersRelation","requestedFilter","getRelationToFilter","getDateRangeRelation","startThis","endThis","startOther","endOther","getMultiValueFilterRelation","thisVal","otherVal","thisValM","otherValM","LOADER_STATE_CHANGED","LOADER_REFRESH_NEEDED","ItemLoaderStateChangeEvent","hasUpdatedItems","ItemLoaderRefreshNeededEvent","revalidateAtPage","SharedEventWithoutItemChanges","SharedEventWithItemChanges","ItemLoaderPage","startedGeneration","loadedGeneration","ItemLoaderState","_order","_filter","_pages","_generation","_nextPageIndex","_revalidateAtPage","_invalidateCache","_mostRecentValidMutation","generation","_nextPageCallback","_pendingLoad","loadAllPages","collectAllItems","_ensurePage","pageIndex","pendingLoad","_loadPageImpl","nextPageCallback","startGeneration","previousPageGeneration","loaderError","revalidationPromise","validatedPromise","_updateStatus","_value","flags","HadLoaderErrors","_updateStatusAndLinkToNextPage","ReadyHasMorePages","pagesAwaitingValidation","ReadyFullyLoaded","didLoadNextPageBefore","newStatus","hasItemChanges","EverythingFilter","STATE_CHANGED","LIST_CHANGED","LIST_FULLY_LOADED","LOADER_UPDATE_CONTEXT","SharedListChangedEvent","SharedStateChangedEvent","GlobalGeneration","ItemList","_itemPool","loaders","similarItemList","_loadOptions","_status","_items","_completedGeneration","_loaderStates","_lastFetchTime","_needsRefresh","_invalidateCacheForNextLoad","_itemUpdatesByGeneration","_listId","_onUnhandledPromiseError","_updateListStatusFromItemLoaderStates","_errors","_handlePendingLoad","invalidateCache","_debug","_runLoaders","loaderState","_onItemLoaderStateChanged","_cleanPreviousGenerationItemsIfNeeded","_updateListItemsFromItemLoaderStates","_onItemLoaderRefreshNeeded","_loadAsync","_globalStateChangedEvent","updateContext","pendingNotifications","_pendingNotifications","loader","_copyInitialItemsFrom","msg","_updateLoadOptions","refreshTimeout","completedGeneration","hasLoaders","lastFetchTime","itemGeneration","_applyListItemsFrom","_dispatchItemsChangedEvent","_dispatchStateChangedEvents","_total","globalMostRecentValidMutation","_cleanPreviousGenerationItems","_applyItemsChangedEvents","currentGeneration","newState","hadChanges","mostRecentDeletedGeneration","refresh","_load","previousLoadPromise","_previousLoadPromise","_ensureAllPagesAreLoaded","_loadNextPageAsync","fn","setNeedsRefresh","itemSet","notification","addedItems","changedItems","included","discardedItems","WeakRefPolyfill","_ref","waitForListLoad","listEventSource","onStatusChange","candidateSort","filterRelation","ItemSource","_lists","_loaders","getList","_getExistingList","mostCompleteList","_getMostCompleteCompatibleList","_onListFullyLoaded","_getListHash","getListWithTypes","orderDir","orderField","existingHash","listWeakRef","_getLists","candidates","lists","listRef","loadedList","RenditionBlobHelper","_resource","_shouldDeleteCachedResponse","RenditionTileBlobHelper","renditionUrl","RenditionResource","_size","AssetVersion","_assetEtag","_createdAt","_createdBy","_manifest","_getHeadAssetInterface","getAssetContext","_assetLinks","__links","createdBy","manifest","milestone","_label","_description","_getRenditionFetcher","_renditionFetcher","_renditionBlobHelper","getRenditionURL","getPresignedRenditionURL","getPresignedURL","blockDownloadServiceURL","DOWNLOAD","getAssetWithCloudID","headInterface","copy","moveToAsset","targetAssetID","deleteHeadAssetIfLastVersion","copyPrimaryToAsset","permanentlyDelete","headAsset","getLocalItemById","remove","_versionPool","queueDiscardedItem","copyToAsset","resources","reltype","copyToNewAsset","newAssetPath","newAssetName","repositoryId","setMilestone","jsonParams","VersionUpdater","removeMilestone","AssetVersionLoader","_assetInterfacePromise","versions","assetEtag","assetLinks","nextStart","total_children","updateLastKnownClientMutationValues","updateLastKnownClientMutationKeys","UpdateSession","_delegate","hasChanges","_addedItems","_changedItems","_discardedItems","changedItemsWithEvents","delegate","isItemDiscarded","queueAddedItem","oldId","events","itemEvents","findItem","commitUpdateSession","ITEMS_CHANGED","ItemsChangedEvent","compareDelegatesByPriority","priority","ItemPool","_objectsById","_discardedObjects","WeakSet","_delegates","_hasUnsortedDelegates","_getObjectsById","removeLocalItems","ids","_updateSessionDelegate","objectsById","discardedObjects","delegates","hasEmptyWeakRefs","delegateRef","createMutationSession","itemRef","results","FileContentResource","AssetVersionFilter","_isMilestone","isMilestone","_createdAfter","createdAfter","_createdBefore","createdBefore","matchesBookmark","matchesCollab","matchesDateRange","matchesVersion","_getRelationWrtMilestone","_getRelationWrtCreatedBy","_getRelationWrtDateRange","_getRelationWrtVersion","BookmarkedVersions","ImplicitDirectoryListingFilter","addProjectIdToMetadata","parentId","RepoMetadataResource","repoMetadata","resolveHref","getAssetResolveByIdHref","_handleResourceUpdates","EffectivePermissionsResource","effectivePermission","ACPLModelInterface","acplModel","getACPLModel","getLocalAsset","localAsset","getLocalAssets","_getAssetPool","assetFromLocalMetadata","_expandRepositoryPath","homeFolder","subscribeToLocalAssetChanges","eventData","context","getHomeFolder","pool","supportsDownloadComposite","downloadComposite","supportsUnpin","unpin","supportsLocalAssets","rawAssets","LocalAssetLoader","acplModelInterface","cachedAssets","assetsFromLocalMetadata","FIREFLY_GENERATIONS_DIRECTORY","GENERATION_HISTORY_IMAGE_MEDIA_TYPE","GENERATION_HISTORY_VIDEO_MEDIA_TYPE","GENERATION_HISTORY_AUDIO_MEDIA_TYPE","GENERATION_HISTORY_VECTOR_MEDIA_TYPE","GENERATION_HISTORY_MEDIA_TYPES","MEDIA_TO_HISTORY_ASSET_TYPE","SAM.GenerationHistoryAssetType","IMAGE","VIDEO","AUDIO","VECTOR","HISTORY_ASSET_TYPE_TO_MEDIA_TYPE","isGenerationHistoryAsset","makeComponentURL","componentData","inputAsset","forceBlockDownload","COMPONENT","revision","isBlockDownload","componentId","downloadURL","getGenerationGroupId","firefly","generationGroupId","getOutputComponentURLs","outputComponents","componentPromises","outputComponent","componentURL","fromEntries","getOutputComponentURL","getInputComponent","_getGenerationModelDisplayName","prompt","detailLevel","generationModel","MELVILLE_FIREFLY_GENERATION_CANCEL","MELVILLE_FIREFLY_GENERATION_RESULT","seed","customModelId","outputComponentURLs","_getGenerationHistoryInterface","getOutputComponentDownloadURLs","outputComponentURL","getOutputComponentDownloadURL","inputComponent","components","parseLibraryAndElementID","libraryElementID","pop","getLibraryAccessOption","moveUrlQueryParamsToHeaders","melvilleUrl","urlParams","paramAsHeader","urlParamsString","LibraryInterface","_getUrl","endpoint","_getEdgeUrl","getLibraryData","libraryId","selectors","sortedSelectors","getLibraries","parameters","urlWithQueryParams","finalHeaders","directive","projectId","team","selector","libraries","getLibrariesWithLink","pageLink","restoreLibraryElement","elementID","libraryID","elements","permanentlyDeleteLibraryElement","discardLibrary","permanentlyDeleteLibrary","restoreLibrary","copyLibrary","destName","parentAssetID","accessString","access","parent_assetId","moveLibrary","featureFlags","createLibrary","nameOrOptions","syncCreate","requestOptions","bookmarkLibraries","bookmarks","urn","getBookmarks","unbookmarkLibrary","bookmarkId","updateMetadata","searchLibraries","searchQuery","query_string","asset_type","searchLibrariesWithLink","getRenditionTileImage","GenerationHistoryInterface","getGenerationHistoryAssets","sortParameters","getGenerationHistoryAssetsUsingPageLink","getGenerationHistoryAssetById","componentURLs","downloadURLPromises","componentLinkResponse","blobUrl","PerUserMetadataResource","perUserMetadata","RequestHeaders","getSAMVersionRequestHeader","SAM_VERSION","packageJSON","assignmentPath","assignmentPathRegex","materialsFilePath","materialsFilePathRegex","isMaterialsFilePath","studentAssignmentPath","studentAssignmentPathRegex","studentAssignmentFilePath","studentAssignmentFilePathRegex","isStudentAssignmentFilePath","validateString","shouldThrow","validateType","isRequired","toDateString","enumValue","validateTypes","validationMap","article","errMsg","getMemberComputedKey","classroomId","boardMediaTypeString","repoMetadataIsBoard","libraryMediaTypeString","repoMetadataIsLibrary","repoMetadataIsGenerationHistoryAsset","metadataIsAssignment","app_metadata","appMetadataIsAssignment","isAssignmentPath","appMetadataIsProject","ussV3ItemMetadataIsProject","ussV3ItemMetadataIsLibrary","metadataIsStudentAssignment","appMetadataIsStudentAssignment","isStudentAssignmentPath","ussMetadataIsLibrary","ussMetadataIsCustomModel","appMetadataIsStudentAssignmentFile","metadataIsStudentAssignmentFile","ussV3ToProjectMetadata","ussToProjectData","asset_id","ussToLibraryData","ussToStudentAssignmentFileData","studentAssignmentId","ussV3ToStudentAssignmentFileData","ussToCustomModelData","ussV3ToLibraryData","AdobeAssetFactory","ussItemMetadata","getItemData","libraryUpdater","studentAssignmentFileUpdater","itemMetadata","projectUpdater","resultsItems","projectContext","getProjectContext","_projectUpdater","getUSSUpdaters","customModelContext","getCustomModelContext","_customModelUpdaterMelville","_ussAdobeAssetUpdater","repoMetadatas","boardContext","getBoardContext","_boardUpdater","classroomContext","getClassroomContext","_studentAssignmentFileUpdater","_studentAssignmentUpdater","_assignmentUpdater","generationHistoryContext","getGenerationHistoryContext","_generationHistoryAssetUpdater","assetsFromUSSMetadata","projects","project","_applyRestorePermission","asset_name_path","asset_name","ussIsStudentAssignmentFilePath","customModelUpdater","assetFromRepoMetadata","projectMetadata","studentAssignmentMetadata","generationHistoryMetadata","assetMetadata","assetUpdater","typedProjectMetadata","boardUpdater","boardData","studentAssignmentFileData","repoToStudentAssignmentFileData","computedStudentAssignmentId","studentAssignmentUpdater","studentAssignmentData","repoToStudentAssignmentData","assignmentUpdater","assignmentData","repoToAssignmentData","generationHistoryUpdater","_findLocalAssetByRepoPath","_setNeedsRepoMetadata","localMetadata","APP_METADATA_REFRESH_IGNORE_REGEX","AdobeAsset","isVirtual","_localID","isAvailableOffline","downloadStatus","_downloadStatus","uploadStatus","_uploadStatus","syncStatus","_syncStatus","syncSuspensionReason","_syncSuspensionReason","xmpNumberOfPages","_xmpNumberOfPages","_acplModelInterface","_repositoryID","_path","_storageRegion","_assetClass","_assetState","_created","_modified","_modifiedBy","_permissions","_storageAssignee","_effectivePermissionsResource","_repoMetadataResource","_isArchivedLibraryElement","_representations","composite","_isExplicitlyLoading","_needsRepoMetadata","isCustomModel","_linksCameFromResolveAPI","isUserPinned","isNameDCTitle","_embeddedMetadata","_appMetadata","_perUserMetadataResource","_fileContent","fr","_finalizer","_populateStorageAssignee","createdFromUpload","createdByClientId","_createdByClientId","_getAssetContext","_loadWithRetry","preferredVersion","_generationModelDisplayName","_resources","_setResources","appMetadataResource","repoMetadataResource","effectivePermissionsResource","perUserMetadataResource","_reloadPermissions","hasLostAccess","allSettled","_refreshLoadedResources","_loadRepoMetadata","needsRepoMetadata","resourcesToReload","localVersion","versionMetadata","setVersionAsMilestone","existingVersion","getCommentsResource","assetType","_assetType","assetSubType","_assetSubType","isAssignment","isBoard","isFile","isStudentAssignment","isLibraryElement","isOwnCreation","imageLength","_imageLength","imageWidth","_imageWidth","parentAssignmentID","at","isChildOfAssignment","parentClassroomId","parentClassroomName","getClassroomNameFromSAFPath","getClassroomNameFromMaterialsFilePath","isChildOfClassroom","parentAssignmentMaterialsId","isChildOfAssignmentMaterials","parentStudentAssignmentId","isChildOfStudentAssignment","_isPathInsideProject","pattern","parentProjectID","parentIsMissingFromAncestorIDs","_ancestorIDs","createTimeAgoMs","_fixParentProjectID","_callContextAPI","isChildOfProject","isChildOfCSCProject","getProjectbyID","WF_PROJECT","WF_PORTFOLIO","WF_PROGRAM","WF_TEMPLATE","directorySubtype","isArtifact","isReviewLink","displayName","storageAssignee","repositoryName","_repositoryName","_populateRepositoryName","storageRegion","_lastAccessed","isFavorite","_isFavorite","setIsFavorite","setFavorite","updateLastAccessed","accessDate","_shared","assetRefString","cloud_id","display_name","repository_id","representations","embedPermissions","localAssetLoader","searchChildren","opts","handleOnsChangedResources","changedResources","INVALID_OPERATION","_hasArtifacts","_deleteAssetOutputsFolder","hasArtifacts","_clearRepositoryName","_repositoryNameFromID","_getStorageAssigneeFromID","newFolderMetaData","_createAssetFromMetadata","getAssetWithRepoPath","_setCreatedFromUploadData","_mediaType","_retryOnConflict","_setCreatedFrom","_preferredBlockTransferThreshold","_milestoneProperties","retryOnConflict","optionsRenameOnConflict","setCreatedFrom","newFileMetaData","fileAsset","fileOrOptions","mediaTypeOrThreshold","_useBlockStore","getDownloadURL","optionsOrForceBlockDownload","expirationSeconds","fallbackToDirectDownloadThreshold","threshold","shouldFallbackToPrimary","fileContent","newFileDetails","NoErr","committedEtag","Conflict","parentRepoPath","parentDeleted","samError","ParentDeletedConflict","newFile","DeleteConflict","newAsset","restoreLocation","_move","PARENT_DISCARDED","permanentlyDeleteAssets","failedResults","modifiedBy","discarded","_discarded","discardedBy","_discardedBy","hasPermission","permission","invitationServiceCapabilities","isReadOnly","embeddedMetadata","_releaseRenditions","thumbnailURL","thumbnailStatus","spaceID","isSpaceAsset","getSpace","space","spaceContext","getEnclosingSpace","_canLoadNewChildrenFromONSNotification","pinnedVersion","_pinnedVersion","pinnedVersionModifyDate","_pinnedVersionModifyDate","getAssetLinks","_copy","destFolder","modelUpdater","resultOps","newModels","currCounter","_finalizePath","assetsById","ops","_getCopyOp","_runOperations","_copyWithDestMetadata","destFolderRepoId","destFolderRepoPath","targetName","includeResources","selectionType","duplicate","rename","newMetadata","historySession","move","assetRenameMap","moveAssets","transferToSpace","transfer","getPermission","retry","StorageAssigneeFormat","AssetItemUpdaterOptions","AdobeAssetUpdater","USSAssetItemUpdaterOptions","composite_manifest_etag","creative_cloud_asset_type","asset_sub_type","lastAccessedISOString","region","appMetadata1","appMetadata2","USSAdobeAssetUpdater","reloadSpace","clearLastReloadError","USSLoaderHelper","implicitSet","explicitSet","getExcludeMediaTypesFromFilters","ussAssetFilter","resultSet","result_sets","total_items","publicLink","directCount","collaboration_metadata","collaborator_id","collabMetadataMine","isSWYGroup","getUSSV2ItemData","SpaceSearchAssetLoader","_ussInterface","_artifactFilter","_embedPermissions","_getItemDataWithRepoId","supportedFilters","artifactFilter","searchSpace","sort_orderby","sort_order","start_index","repoID","SpaceSearchAssetFilter","Space","_pathName","_contributorCount","_role","_color","_isBookmarked","_teamID","_teamName","_thumbnail","_access","_state","_loadedGeneration","_teamRole","pathName","contributorCount","color","isBookmarked","teamID","teamName","thumbnail","teamRole","ensureDescription","getChild","_children","searchWorkingFiles","workingFilesFolder","spaceSearchAssetLoader","searchArtifacts","spaceAdobeAsset","getWorkingFiles","lastReload","_lastReload","pending","requestTime","inProgress","_executeReload","reload","spacePool","assertedCondition","isReloading","lastReloadError","updateSpace","archive","archiveSpaces","nameMap","restoreSpaces","SpaceUpdater","REVIEW_SERVICE_LINKS","REVIEW_SERVICE_PROVISION","REVIEW_SERVICE_DISCARD","REVIEW_SERVICE_OUTPUTS","REVIEW_SERIVCE_HAS_OUTPUTS","mapAssetsToAssetIndentifier","assets","AssetReviewServiceInterface","baseURL","baseEndpoint","indexEndpoint","getEndpointURL","_discoverLinks","rootHref","_getHeaders","contentType","discoverLinks","discardOutputsForAsset","assetRegion","hasOutputs","_createFrameLinkUrl","createReviewLink","reviewLinkId","artifactId","getReviewLinks","updateReviewLink","deleteReviewLink","CommentInterface","_getCommonHeaders","getCommentList","getComment","annotationId","createComment","editComment","deleteComment","getMetadata","annotId","read","Comment","_creator","_bodyValue","_motivation","_generator","_mentions","_uri","_replies","_readStatus","creator","bodyValue","motivation","mentions","replies","readStatus","toJSON","assetUrn","_pool","_commentsResource","_commentPool","_interface","_commentInterface","edit","changes","commentInterface","commentPool","current","CommentUpdater","updateResolvedStatus","isResolved","updateReadStatus","isRead","creationId","reply","required","CommentLoader","_retryAfter","comments","comment","CommentOrder","COMMENTS_CHANGED","CommentsResourceChangeEvent","annotationIds","CommentsChangedEventInstance","CommentsResource","_source","_unreadCount","_list","_updateMetadata","unreadCount","readStatuses","currentUserId","_poll","_stopTimeout","startShortPoll","stopShortPoll","isShortPollActive","_onONSNotification","assetInfo","throttle","LIST_CHANGE_DELAY_MS","parseVersion","major","minor","patch","padStart","isSAMCppVer","comparison","aVer","bVer","SharedThumbnailChangeEvent","SharedPermissionsChangeEvent","replacer","_key","Logger","_isoTime","_epochToIsoTimeString","epoch","_formatMessage","optionalParams","timestamp","includeTimestamp","padEnd","_prefix","_logSink","WARN","logDebug","DEBUG","logInfo","INFO","logWarn","logError","ERROR","AxonClientConfig","authGet","_locale","_logger","_authenticatedGet","_getSignedUrlRequestUrl","_reconnectSignedUrl","_sessionId","_getSignedUrl","signedUrl","websocketUrl","reconnectSignedUrl","sessionId","logger","_authentication","resetSession","authenticate","isAuthenticated","ws","WebSocket","MozWebSocket","FrameType","VcStatus","ReconnectReason","AxonVirtualConnectionState","AxonSessionState","AxonHttpStatusCodes","AxonWebSocketStatusCodes","AxonProtocolStatusCodes","AxonClientState","StateMachineEventEmitter","initalState","logSourceName","logSourceId","_logSourceName","_sourceString","transitionTo","AxonUtils","CreateFrame","frameType","frameId","AxonVirtualConnection","VcIdToVcIndex","idx","isNaN","_session","_frameSenderHook","_vcIndex","_serviceName","_headers","CREATE_IN_PROGRESS","frame","CreateVc","isCreated","isEstablished","CREATED","ensureActive","timeoutMs","DELETE_IN_PROGRESS","DELETED","timer","handleAxonErrorFrame","errorMessage","handleAxonMessageFrame","messageString","sendMessageAck","handleAxonMessageAckFrame","_frame","sendMessage","Message","messageFrameId","MessageAck","AxonSession","_axonClient","DISCONNECTED","_virtualConnections","_lastVcMonotonicIndex","_handleWsAckFrame","existingVirtualConnections","_heartbeatIntervalInSec","vc","heartbeatFrequencyInSec","CLOSED","_notifyVirtualConnectionsAboutStatusChange","reconnectUrl","vcId","vcIds","vcIndex","existingVc","Active","DeleteVc","ESTABLISHED","_handleCreateVcAckFrame","_handleDeleteVcAckFrame","_handleReconnectFrame","_handleCloseSessionFrame","_handleVcFrame","heartbeatIntervalInSec","handleAxonFrame","WsAck","CreateVcAck","DeleteVcAck","Reconnect","Closesession","ensureEstablished","deadline","ensureConnected","CONNECTION_IN_PROGRESS","expectReconnection","RECONNECTION_IN_PROGRESS","expectDisconnection","DISCONNECTION_IN_PROGRESS","disconnect","createVc","serviceName","deleteVc","State","AxonClient","_createAxonClientFrameSenderHook","send","_txBuffer","_connectionIteration","_wsIndex","_reconnectAttempt","_onWsOpen","DISCONNECTING","CONNECTING","RECONNECTING","_clearReconnectTimer","CONNECTED","_onWsClose","reason","wasClean","isConnected","DISCONNECTED_SESSION_CLOSED","_scheduleReconnectWithExponentialBackoff","terminate","_onWsError","_onWsMessage","_handleTextMessage","_cancelHeartbeatMonitoring","_heartbeatMonitorTimeout","_restartHeartbeatMonitoring","_cancelHeartbeatMessage","_heartbeatSenderTimeout","_rescheduleHeartbeatMessage","_transmit","_ws","readyState","OPEN","connect","WS_CONNECT_TIMEOUT_MS","currentConnectionCycle","binaryType","onopen","onclose","onmessage","_waitForConnection","reconnect","setInterval","clearInterval","_deinitialize","wsCloseCode","DISCONNECTED_NORMAL","CLOSING","serializedFrameData","_reconnectTimer","delay_ms","acplAssetToLocalAsset","adobeAsset","LocalAssetUpdateTracker","applicationContext","onChangedAssets","previews","properties","isAssetInRecents","emitLocalAssetChange","onListUpdated","onAddedToRecents","onRemovedFromRecents","recentsList","recentsSource","$SAM_INSTANCE_MAP","SAMCore","hooks","_fetchIndexState","_setAssetContextFromBindings","nativeAssetContext","_AssetContext","AssetContext","_AssetContextJS","_gqlManager","GQLManager","initialize","_getONSContext","getCollaborationContext","assetLinkManager","_getAssetLinkManager","_SpaceContext","getSpaceContext","SpaceContext","_getSpaceContext","_CollaborationContext","CollaborationContext","_getCollaborationContext","_ProjectContext","ProjectContext","_getProjectContext","_ClassroomContext","ClassroomContext","_getClassroomContext","_BoardContext","BoardContext","_getBoardContext","_getAxonClient","_AxonClient","axonConfig","SyncServicesLogLevel","frameioContext","_FrameioContext","getFrameioContext","FrameioContext","_getFrameioContext","_LibraryContext","LibraryContext","_getLibraryContext","_CustomModelContext","CustomModelContext","_GenerationHistoryContext","GenerationHistoryContext","_getCustomModelContext","makeObservable","environment","updateConfig","updatableKey","_getWorkfrontContext","_WorkfrontContext","getWorkfrontContext","WorkfrontContext","_getKnowledgeWorkspaceContext","_KnowledgeWorkspaceContext","getKnowledgeWorkspaceContext","KnowledgeWorkspaceContext","getAccessControlContext","AccessControlContext","getSharingContext","_SharingContext","SharingContext","initializeSharedAssetModel","samInstances","loadedVersions","compatibleLoadedVersion","loadedVersion","loadedMajor","loadedMinor","loadedPatch","enableACPLNextPolyfills","disableSamCppModels","loadAndSetContexts","useLazyContext","initialLoadPromise","waitForApplicationContextReady","applicationAssetContext","patchACPLNext","loadedAssetContext","getAssetLinkManager","_DISABLE_SAM_CPP","race","rootFolderProto","rootFolder","isPatchableVersion","ACPLAsset","updatedCollaborators","routesToAcplV2","discardOutputs","hasPermissions","_hasLoadedPermissions","resolveById","_refreshThumbnail","_thumbnailInfo","_thumbnailStatus","getThumbnailRendition","force","_onAssetChanged","_onRenditionChanged","_assetVersionSource","versionPool","getAssetInterface","patchAdobeAsset","_searchWorkingFilesSource","lookupSpaceById","_searchArtifactsSource","patchSpaceJS","SAM_CPP_ITEM_EVENTS","AssetList","loadMoreItems","_addEventInterceptors","_onError","_onListNotification","_onStatusChange","patchAssetList","dirMap","ascending","descending","fieldMap","Shared","AssetSource","maybeOrder","maybeFilter","patchAssetSource","AssetContextJS","confirmAccess","getAssetWithAssetRefString","getUserRepoID","_userRepoID","getHomeDirectoryMetadata","homeDirectoryMetadata","targetId","workingFiles","sourceRepoID","targetRepoID","_assetTransferService","isOnline","networkStatus","Offline","recentAssetsSource","getRootFolder","assetsHaveArtifacts","assetReviewServiceInterface","assetIndentifiers","foundAsset","onAssetsChanged","_isForwardingAssetChangeEvents","patchAssetContext","samCore","hasProperty","DefaultSearchQuery","scope","asset_id_opacity","USSInterface","_getEndpointHref","getQueryResponse","endpointHref","parentFolderId","hints","acp_platform_v2","creative_cloud_rendition_v2","fetch_fields","TYPE","container","op_field_exists","op_none_of","VISIBILITY","InvitationInterface","_batchRequestLimit","batchRequestLimit","getCollaborators","addCollaborators","addResult","addedCollaborators","statusCode","errorCode","modifyCollaborators","getCollaboratorListForUrns","urns","jobStatus","declineAccess","getPendingInvitations","createAccessRequest","assetIds","requestedPermissions","requestBody","accessRequestResult","successfulRequests","failedRequests","RepositoryInterface","repositoryIndex","repositoryNameIndex","workfrontRepositoryIndex","_getAndCacheDocument","_getIndexHeaders","_getRepositoryHref","getRootLink","getIndex","fetchIndexState","pendingCacheClear","hasChildren","existing","indexJson","getWorkfrontIndex","orgId","_clearIndexCache","_getAndCacheLinksFromHref","getCloudQuotaUsedAndMax","QUOTA","used","getRepoMetadataById","RESOLVE_ID","getRepoMetadataByPath","mode","_getHomeDirectoryMetadata","opHref","OPS","firstOp","moveResources","OPERATION_FAILED","title","_chunkArray","chunkSize","chunks","_combineOperationResults","combinedResult","runOperationsForContext","modelsById","itemPool","updateLocalModel","errorHandlers","operations","chunkPromises","chunk","_runOperationsForContextBatch","chunkResults","promises","currentModel","updatedModelMetaData","errorHandler","action","failedOp","model","newModel","getRepositoriesData","getRepositoryName","getStorageAssignee","getRepoOwnerMap","targetRepoId","ownerMap","repoData","getRepositoryLinks","createFolderByPath","createIntermediates","createHref","ONS_FIRST_LONG_POLL_STARTED","ONS_FIRST_LONG_POLL_COMPLETED","ONS_MONITORING_STATUS_CHANGED","OnsMonitoringStatus","ONSAssetChangeEvent","changedAssets","ONSFirstLongPollStartedEvent","cachedSubscriptionsUsed","ONSFirstLongPollCompletedEvent","expired","ONSMonitoringStatusChangedEvent","updateAssetTypeForUSS","DefaultSBMAssetsListingOptions","SBMInterface","getSharedByMeAssets","parent_id","DefaultSWYAssetsListingOptions","SWYInterface","getSWYAssets","shared_via_invite","CREATIVE_CLOUD_TOPLEVEL_COLLECTION_NAME","STORAGE_ASSIGNEE_ID","DefaultAssetsListingSearchOptions","AdobeAssetSearchInterface","MEDIA_TYPE","REPO_ANCESTORS","PARENT_ID","CREATED_FROM_UPLOAD","CREATED_BY_CLIENT_ID","__ussInterfaceV3","sorts","sortOrderBy","sortOrder","textQuery","DefaultAssetsListingGlobalSearchOptions","AdobeAssetGlobalSearchInterface","STORAGE_ASSIGNEE_TYPE","op_or","SHARED_VIA_INVITE","DefaultRecentAssetsListingOptions","RecentInterface","_getCommonFilters","FIELD_EXISTS","OP_AND","op_and","OP_OR","getRecentAssets","storageAssigneeQuery","getMRUAssets","AssetTransferInterface","ATS_MOVE","getUrl","RecentAdobeAssetLoader","_recentInterface","_libraryContext","loaderOptions","_lastModificationDate","RecentAdobeAssetFilter","retryFailedOpsDueToConflict","destination","conflictMap","conflictRetryOp","failedAssetsDueToConflict","otherFailedOps","newResultOps","MRUAdobeAssetFilter","LIBRARY_DATA_CHANGED","LibraryDataChangedEventInstance","RESTRICT_EDIT_CHANGED","RestrictEditChangedEventInstance","RenditionTileResource","_renditionUrl","_getLibraryInterface","RenditionTile","_library","rendition","_renditionTileBlobHelper","_renditionData","mimetype","rendition_mimetype","elementId","elementType","imageUrl","imageStatus","CustomModelInterface","_getMelvilleUrl","searchCustomModelsUsingPageLink","headerParams","finalUrl","searchCustomModels","getCustomModels","getCustomModelById","getCustomModelsUsingPageLink","createTrainingSet","cmeOptions","schemaVersion","trainingMode","creationOptions","_createLibrary","getTrainingSetById","_getLibraryRemotely","createCustomModel","updateCustomModel","deleteCustomModel","discardCustomModel","restoreCustomModel","publish","unpublish","CustomModel","_displayName","_conceptId","_trainingMode","_compression","_schemaVersion","_customModelInterface","trainingSet","getLibraryByAssetId","trainingSetInfo","publishedState","customModelData","inferenceReady","category","signature","baseModelName","baseModelVersion","trainingInfo","trainingState","progress","jobId","samplePrompt","conceptId","baseModelSuperclass","_baseModelSuperclass","deltaWeightsID","_deltaWeightsID","_contentType","compression","hasDefaultGeneratorPermissions","unsupportedKeys","unsupportedPatches","CustomModelUpdaterMelville","ffmodel","asset_acl","ImplicitCustomModelFilter","trainingSetId","generatorOnly","_trainingSetId","_generatorOnly","TrainingSetCustomModelLoader","_libraryId","trainingSetLibraryData","customModels","custom_models","cmSession","Library","_libraryDataLoadInfo","_refreshEditingRestricted","getContents","_contents","CCLibraries","_getLibrariesModule","getLibraryContents","_getContentsSync","_getLibrariesModule_NoLoad","_libraryLoaded","priorState","_waitForLibraryLoad","canRetry","_populateLibraryDataIfNotLoading","requireLibraryDataFetch","elementsCount","_elementsCount","documentType","_documentType","orgID","_orgID","publishedTo","publishedFrom","lastPublishedVersion","extractedFrom","customThumbnail","_customThumbnail","_libraryRoles","customModelInfo","_customModelInfo","renditionGrid","_renditionGridTiles","setRoles","newRoles","_bookmark","_isPublic","_ownership","libraryManifestId","_legacyLibraryId","_parentAssetId","bookmarkData","unbookmark","isEditingRestricted","_isEditingRestricted","_isCCIProjectLibrary","setEditingRestricted","_roles_NoLazyLoad","_ownership_NoLazyLoad","_isBookmarked_NoLazyLoad","_displayName_NoLazyLoad","_legacyLibraryId_NoLazyLoad","isReferencedByProject","_referencedByProjectIDs","_updateReferencedByProjectIDs","isReference","safePropertyUpdaterTypes","destTiles","sourceTiles","main","tiles","tile","sourceTile","destTile","updateRenditionGrid","_renditionGridRaw","reference","rapiOverridesPropertyUpdaterTypes","collaboration","currentUser","inheritanceType","public","propertyUpdaterTypes","LibraryUpdater","DefaultPublishedAssetsListingOptions","PublishedInterface","getPublishedAssets","OrderFieldToIUSSAdobeAssetOrderBy","OrderFieldToUSSv3OrderField","USSAdobeAssetOrder","PublishedAdobeAssetLoader","_publishedInterface","published","PublishedAdobeAssetFilter","DiscardedAdobeAssetFilter","isSyncedAsset","isMobileCreation","DEFAULT_OPTIONS","DISCARD_FETCH_FIELDS","MOBILE_CREATIONS_MIMETYPES","DiscardedInterface","getDiscardedAssets","creative_cloud_archive","creative_cloud_discarded_directly","REPO_ACL_MODIFIER","REPO_ACL_PRIVILEGES","REPO_ACL_RELATIONS","DiscardedAdobeAssetLoader","_discardedInterface","_discardedSourcePrefetch","projectIndexPromise","_prefetchIndex","repositoriesPromise","_getListOfRepositoryIDs","canRestorePromises","repositories","repository","_canRestoreProject","LERenditionURL","creative_cloud_colortheme","creative_cloud_gradient","isArchivedLibraryElement","AdobeAssetGlobalSearchFilter","_projectsOnly","projectsOnly","_matchingIDsFromSearch","USSv3Interface","queryPath","queryEntry","experienceId","queries","SharedBy","ShellVisibility","ReviewSourceAssetType","ConvertedTo","NonAutoMigratable","CopiedLegacySparkId","CreatedFromUpload","GlobalSearchLoader","_globalSearchInterface","excludeInheritanceTypes","globalSearch","GlobalSearchInterface","DIRECTORY_TYPE","PROJECT","MISSING","fields","ASSET_TYPE","ASSET_SUB_TYPE","AdobeAssetGlobalSearchLoader","_adobeAssetGlobalSearchInterface","SWYAdobeAssetFilter","DefaultEmbeddedResources","PROJECTS_CREATOR","REPOSITORY","DefaultProjectsListingOptions","DefaultRecentProjectsListingOptions","ProjectsInterface","_gradientResourcesByLanguage","_getCreateEndpointHref","_discoverProjectLinks","getProjects","view","ownerId","nameContains","directorySubtypes","getProjectsListingPath","getRecentProjects","getRecentProjectsListingURL","_getProjectLink","getProject","getProjectsWithLink","_getCreateLink","createProject","jsonResponse","CHILDREN_LIMIT_EXCEEDED","PROJECT_LIMIT_EXCEEDED","createCSCProject","parentAssetId","projectDirectorySubType","projectCreateRepoData","createLink","resolveProjectByName","_getResolveByPathLink","renameProject","PROJECTS_RENAME","validateProjectName","discardProject","DISCARD","restoreProject","RESTORE","getGradientsResource","loadedOnceThisSession","_response","_getGradientsLink","getGradients","languageCode","patchProject","jsonData","gradientID","GRADIENT_ID","_getCapabilityLink","capability","privilege","getCapability","errorResponse","ADMIN_ONLY","PROJECTS_ADMIN_ONLY","NO_HOME_REPOSITORY","PROJECTS_NO_HOME_REPOSITORY","INVALID_HOME_REPOSITORY","PROJECTS_INVALID_REPOSITORY","createLibraryReference","_issueContextAPIRequest","repoId","_getOrganizationsCollectionLink","getOrganizations","moveCSCProject","targetProjectId","PROJECTS_MOVE","deleteLibraryReference","referenceId","ORGANIZATIONS_CHANGED","OrganizationsChangedEventInstance","OrderFieldToISWYAdobeAssetOrderBy","SWYAdobeAssetOrder","AdobeAssetFilter","_mediaTypes","_excludeMediaTypes","_assetTypes","_excludeAssetTypes","_assetSubTypes","makeSet","getMediaRelationToFilter","_getAssetTypeRelationToFilter","_getDiscardedTypeRelationToFilter","_getExcludeIncludeFilterRelation","thisInclude","thisExclude","otherInclude","otherExclude","USSAdobeAssetFilter","_excludeInheritanceTypes","_uploadedFrom","StudentAssignmentAssetId","existingFilter","arrayRelationship","AssetVersionOrder","STUDENT_ASSIGNMENTS_INDEX_LINKS","STUDENT_ASSIGNMENTS_COLLECTION","STUDENT_ASSIGNMENTS_PRIMARY","ALL_STATUSES","IN_PROGRESS","NOT_STARTED","RETURNED","SUBMITTED","DefaultStudentAssignmentsListingOptions","includeStudentDocuments","StudentAssignmentsInterface","discoverStudentAssignmentLinks","getStudentAssignments","identifier","assignmentId","assignmentCode","loadDocuments","dataForQuery","getStudentAssignmentsListingPath","getStudentAssignment","preparedOptions","submissionId","ASSIGNMENTS_RETURN","ASSIGNMENTS_START","submit","ASSIGNMENTS_SUBMIT","ONS_SUBSCRIPTION_MIME_TYPE","ONS_SUBSCRIPTION_AUTH_HEADER","SubscriptionMonitoringStatus","defaultAssetProperties","defaultPLSAssetListProperties","includeLabels","ONSSubscriptionChangeEvent","fromCache","ONSSubscription","_onsContext","cachedSubscription","_pendingONSObjects","_watchedONSObjects","_initializedFromCache","_monitoringStatus","Inactive","onsObjects","expiresAt","_subscriptionId","_subscriptionHref","_expiresAt","subscriptionId","subscriptionHref","lastError","_lastError","watchedONSObjects","continuationToken","_continuationToken","monitoringStatus","_retryTimeout","pendingONSObjects","_update","tryAttempt","ONSObjects","_deleteSubscriptionFromServer","_updateSubscriptionOnServer","_createSubscriptionOnServer","DEFAULT_RETRY_INTERVAL_SEC","_parseSubscriptionResponse","getResponse","jsonError","SUBSCRIPTION_COUNT","_createRequestBody","objects","createObjectsRequestBody","deviceId","device","SUBSCRIPTION_CREATE","defaultProps","refreshSubscriptionExpiryDate","_fetchChangeLogPage","_nextChangeLogLinks","GENERIC_NEXT","ONS_CHANGELOG","LIMIT_CHANGELOGRETENTION","changedSubscription","subscriptionInfo","onsResourceInfo","onsResourcesChanged","changedLabels","existingAsset","nextPage","fetchAndNotifyChanges","_retryChangeLogTimeout","hasMorePages","checkResponse","cacheKey","ONSLongPollWorker","_subscriptions","_maxAssetsPerSubscription","_cachedSubscriptionsUsed","_ONSObjectIds","_onSubscriptionChange","_updateCachedSubscriptions","_restartMonitoring","_abortController","subscriptions","ensureReady","deinitialize","stop","sub","activeSubscriptionIds","_activeSubscriptionIds","newPollURL","NOTIFICATIONS_LONGPOLL","includeJournal","isUrlChanged","_pollURL","_notifyFirstLongPollStarted","_notifyFirstLongPollCompleted","_validateAndUpdateSubscriptionExpiration","_truncateAssetIdsByMaxSizeIfNeeded","plsAssetListIds","maxTotalAssets","combinedAssetIds","truncatedArray","_getAndParseCachedSubscriptions","cacheEnabled","existingCreatedSubscriptions","newCachedSubscriptions","subscription","updatedCache","_ensureSubscriptions","subscriptionConfig","getSubscriptionConfig","maxSubscriptions","maxSubscriptionPerLongPoll","maxAssetsPerRequest","parsedCachedSubscriptions","watch","assetIdsToMonitor","plsAssetListIdsToMonitor","getProps","listLevel","directoryLevel","existingObjectIds","subscriptionToOnsObjects","nextIndex","checkSubscriptions","ONSAxonWorker","_isActive","_registrationOperationIds","_onVcMessage","operationName","_handleNotification","operationId","_closeAxonVc","_onVcError","_onVcDeleted","_onVcSessionStatusChanged","_axonVc","Restarting","checkSub","_ensureAxonVc","axonClient","_deactivate","onsSubscriptionConfig","onsAxonServiceName","_monitorActiveSubscriptions","_activeSubscriptions","_subscriptionsWithAssets","_monitoredSubscriptions","subscriptionsToMonitor","_createMonitoringRegistrationRequest","Registering","registerationRequest","REQUIRED_LINKS","ONSContext","_cacheEnabled","_isStarted","_assetsIds","_plsAssetListIds","_onsMonitoringStatus","Unknown","_onONSMonitoringStatusChanged","onsMonitoringStatus","_onVisibilityChange","_document","visibilityState","worker","_useAxon","useAxon","newValue","_reinitialize","_onsAxonWorker","_onsLongPollWorker","isStarted","_getAxonWorker","_getLongPollWorker","watchedObjectIds","objectIds","objectId","document","Document","_documentSupportsVisibility","onvisibilitychange","newModeName","wasStarted","ensureInitialized","_getSyncServiceDiscovery","discovery","rootDocument","LocalAdobeAssetFilter","ImplicitFavoriteAdobeAssetFilter","FavoriteAdobeAssetLoader","assetListId","_assetListId","favorites","getFavorites","dc_format","PLSListLoader","_getAssetListFilter","readyToProcessIncrementalData","plsRemoteItems","_getPLSData","incrementalData","_processIncrementalData","_extractRemoteItems","nin","in","getAssetNodesFromData","valueOf","repo_assetId","OrderFieldToSharedWithYouOrderBy","OrderDirectionToSortOrder","PLSSWYAdobeAssetLoader","processIncrementalData","getSharedWithYou","sharedWithYou","assetListConnection","edges","edge","PLSRecentAdobeAssetLoader","recents","IsSharedViewSelection","IsSharedFilter","isSharedWithYou","ownedBy","AddressBookContact","_countryCode","_email","_firstName","_lastName","_addressBookIdent","_images","_linkedIdentity","_urn","ident","countryCode","email","firstName","lastName","addressBookIdent","images","linkPolicy","_linkPolicy","linkedIdentity","AddressBookContactUpdater","GroupMemberLoader","_addressBookUrl","_groupMemberPool","_addressBookInterface","_groupMemberUpdater","nextPageLink","getMembersNextPage","getMembersFirstPage","contacts","AddressBookInterface","getAddressBookURL","addressBookUrn","addressBookUrl","getAddressBooks","getContactInAddressBook","CollaboratorRoles","ContributorRoles","InheritanceTypes","Collaborator","_isDirect","_assetID","_canDiscover","_canShare","_commentPermissions","hasProfile","collaboratorID","imsUserId","_additionalData","additionalData","groupName","organizationName","commentPermissions","inheritances","_inheritances","hasContributorRole","hasName","invited","isAdmin","canDiscover","avatarURL","getAvatarURL","Size138","addressBookGroupUrn","groupUrn","getGroupMemberSource","abs","pathname","extractAddressBookIdent","_getAddressBookContactPool","CollaboratorUpdater","CollaboratorLoader","_collaboratorPool","_invitationInterface","collaboratorUpdateSession","directSet","directCollaborators","collaboratorsWithComputedProps","dc","InvitedCollaboratorUpdater","_canComment","_acceptanceRequired","invitationID","acceptanceRequired","_inheritance","InvitedCollaboratorLoader","_invitedCollaboratorPool","invitedCollaboratorUpdateSession","invitations","CollaboratorFormat","ErrorFormat","CollaboratorsByAssetIDUpdater","_collaborators","getAssetID","collaboratorsWithID","collab","CollaboratorsByAssetIDLoader","_collaboratorsByAssetIDPool","_assetIDs","Infinity","slicedAssetIDs","batchInvitationResponse","collaboratorByAssetIDs","BatchOperationQueue","_batchProcessor","_maxItemsPerBatch","_delay","_maxInFlightBatches","_itemQueue","_itemPromises","_inFlightBatches","_processQueue","_timer","inFlightCount","inFlightBatch","batch","rejectItemPromise","resolveItemPromise","isInQueue","isInFlight","managedPromise","hasItem","_processNow","AddressBook","_ownerId","adobeId","AddressBookUpdater","AddressBookLoader","_addressBookPool","_addressBookUpdater","addressBooks","CollaboratorOrder","InvitedCollaboratorOrder","AddressBookOrder","_collaboratorSourceMap","_accessConfirmedIDs","_addressBookContactPoolMap","_handleBatchRequest","assetMap","sources","invitationResponse","collaboratorsWithAssetIds","collaboratorData","isDirectCollaborator","_getCollaboratorsNow","getCollaboratorsForAssets","assetsIDs","collaboratorLoader","invitedCollaboratorPool","invitedCollaboratorLoader","collaboratorSources","collaboratorResponse","errorSubcode","getInvitedCollaborators","getCollaborator","userID","configuration","captcha","inviterLabel","recipients","ans","_modifyCollaborators","addressBookSource","getAddressBookOrder","contact","getCollaboratorOrder","getInvitedCollaboratorOrder","_requestAccess","FFBoardsLoader","_ffBoardsInterface","_getListingOptionsFromFilters","getAssets","DefaultListingOptions","FFBoardsInterface","listingOptions","SWYAdobeAssetLoader","_swyInterface","MRUAdobeAssetLoader","_SBMInterface","_assetReviewServiceInterface","_globalSearchInterfaceV3","_commentsById","_onHomeFolderChange","_onOnsAssetChangeEvent","changedFolders","commentsResource","kwContext","isMinimalAsset","_isMinimalAsset","_getAssetById","folder","changedIDs","alm","_refreshLinksForChangedAssets","_onAssetsChanged","excludeAssetIDs","_updateONSSubscriptions","_organizationsResource","organizationsResponse","_defaultOrganizationId","_organizations","org","_fetchOrganizations","sender","_OnsContext","repoInterface","ussInterface","ussInterfaceV3","sbmInterface","swyInterface","recentInterface","invitationInterface","publishedInterface","sharedSource","localAssetsLoader","swyloader","recentAssetsLoader","favoriteAssetsSource","MRUAssetsSource","MRUAssetsLoader","publishedSource","publishedLoader","discardedSource","localRecentsSource","_AssetLinkManager","AssetLinkManager","getGlobalSearchAssetsSource","globalSearchLoader","getGlobalSearchAssetsSourceV3","ffBoardsSource","ffBoardsLoader","OnlineUnknown","forONSNotification","assetPerUserMetadata","getAssetResourcesById","projectInterface","studentAssignmentInterface","remoteStudentAssignment","PREFER_RAPI","computedRepositoryMetadata","_generationHistoryInterface","doFetchStudentAssignmentMetadata","_homeFolder","_setHomeFolder","loadHints","_rootFolder","listingHints","hint","effectivePermissions","internalLoadHints","assetPath","getAssetByPath","_getAssetWithRepoPathImpl","_getAssetRepoDataWithCloudID","_getRepoDataByPath","_getTopLevelFolder","userContentRootFolder","topLevelFolders","topLevelFolder","topLevelPath","appearsOnlyOnce","assetRefStr","parsedAssetRef","assetMetaData","repositoryInfo","getXDCEData","removeAssetsFromAssetsPool","assetResults","onItemsChanged","permanentDeletedAssetsIds","deleteOp","recursive","_moveAssets","getMoveCapability","targetFolder","canMove","NotAFolder","PermissionDeniedDestination","PermissionDeniedSource","warning","warnings","assetRepoOwnerById","targetRepoOwner","CrossBucketMoveDisabled","sourceOwner","OwnerChange","DifferentOwner","maybeHasEditors","CollaboratorMaybeEditing","needsProcessing","w","_copyAssets","copyAssets","duplicateAssets","newFolderMetadata","newFolder","updatedAssetMetaData","_collectPLSAssetListIds","assetIDs","_isCuratedCollectionAsset","monitoredAssetIDs","commentsRef","organizations","defaultOrganizationId","getAdobeAssetOrder","getSWYAdobeAssetOrder","getUSSAdobeAssetOrder","getAssetVersionOrder","getAdobeAssetFilter","getSWYAdobeAssetFilter","getUSSAdobeAssetFilter","getRecentAdobeAssetFilter","getAssetVersionFilter","getIsSharedFilter","ALL","SHARED_WITH_YOU","YOURS","additionalMetadata","_linksFromAdditionalMetadata","restAdditionalMetadata","_linksFromItem","restItem","OrderFieldToLibraryOrderBy","NAME","CREATED_DATE","MODIFIED_DATE","LibraryOrder","itemMatchesOwnerFilter","owner","Incoming","Discovery","itemMatchesRolesFilter","checkOwnerRelation","newOwnerSet","existingOwnerSet","Public","LibraryFilter","EditorBrands","brandsProjectId","Brand","publishMetadata","AllBrands","filterOptions","_project","_roles","_reference","_owner","DEFAULT","_publishMetadata","_hash","Only","itemMatchesProjectFilter","PublishedBrands","AllEditableBrands","itemMatchesPublishMetadataFilter","newRolesSet","existingRolesSet","newValuesSet","existingValuesSet","checkSetOverlap","newProjectFilter","existingProjectFilter","projectFilter","newPublishMetadataFilter","existingPublishMetadataFilter","newReference","existingReference","ElementOrderBy","AllLibraries","Personal","CollaboratorBrands","ElementOrder","ClassroomOrder","ClassroomMember","_classroomId","_inviteSource","_membershipStatus","NOT_A_MEMBER","inviteSource","membershipStatus","ClassroomMemberUpdater","ClassroomMemberOrder","ClassroomMemberFilter","STUDENT","TEACHER","ASSIGNMENTS_INDEX_LINKS","ASSIGNMENTS_COLLECTION","ASSIGNMENTS_CREATE","ASSIGNMENTS_PRIMARY","assignmentRemoteFieldMapping","canClassroomReadSubmissions","instructions","dueDate","externalTemplateIds","templateIds","tasks","referenceIds","externalTutorials","StatusOrderValues","DRAFT","ASSIGNED","compareAssignmentNames","AssignmentOrder","AssignmentFilter","campaignId","submissions","StudentAssignmentFilter","student","statusRelation","compareStudentDisplayName","studentDisplayName","submissionDate","StudentAssignmentOrder","StudentAssignmentFileAppMetadataResource","StudentAssignmentFileUpdater","StudentAssignmentFile","_studentAssignmentId","_parentAssignmentId","_parentClassroomId","_sourceAssets","_sourceTasks","_sourceTutorials","_studentAssignmentFileAppMetadata","sourceAsset","_sourceAsset","sourceAssets","sourceTasks","sourceTutorials","updateStudentAssignmentFile","StudentAssignmentFileOrder","StudentAssignmentFilesListFilter","StudentAssignmentFileFilter","doesMediaTypeMatch","doesPathMatch","isAssetAWebsiteTemplate","enumKeys","BOARDS_REQUIRED_INDEX_LINKS","BOARDS_PRIMARY","PostRemoteType","PostTypeMap","enumA","enumB","valuesA","valuesB","aToB","bToA","valueA","valueB","toB","toA","enumMap","Text","TEXT","AssetLink","ASSET_LINK","PostListLoader","_board","posts","getBoardById","_postPool","PostOwner","avatarImageURLs","avatarUrl","Post","_boardId","boardId","isDeletable","_isBoardReadOnly","_isOwner","_isBoardOwner","isEditable","_getBoard","OWNER","getChildPostUpdater","post","postOwner","AssetLinkPost","_remoteLink","publicUrl","AssetLinkPostUpdater","TextPostUpdater","Board","_memberRole","_hasLoadedPostsProp","_posts","_boardContext","_ensureBoardContext","_hasLoadedPosts","boardNameSuffix","_idOfBaseAsset","_baseAssetId","publishedBoardInfo","_publishedBoardInfo","isPublishedToAnotherBoard","sourceBoardInfo","_sourceBoardInfo","isPublishedFromAnotherBoard","addPost","removePost","postId","updatePost","updateBoard","discardBoard","publishBoard","unpublishBoard","canAddPost","POSTER","canUnpublish","canPublish","getPostById","getPostByBoardAndPostId","_fetchBoardById","BoardUpdater","_id","_remotePosts","remotePosts","board","itemsToRemoveFromPool","remotePost","remotePostWithComputedValues","computedBoardId","memberRole","VIEWER","showPosterName","publishedVersion","noop","PostOrder","compareBoardNames","compareBoardTimes","BoardOrder","BoardFilter","baseAssetId","shouldGetDirectlyInBaseAsset","OrgRepository","createTeam","OrgRepositoryUpdater","FavoriteAdobeAssetOrder","MRUAdobeAssetOrder","PublishedAdobeAssetOrder","OrderFieldToIProjectsOrderBy","ProjectOrder","createdDesc","OrderFieldToCustomModelOrderBy","CREATE_DATE","MODIFY_DATE","CustomModelOrder","GenerationHistoryAssetOrder","LegacyOrderFieldToCustomModelOrderBy","LegacyCustomModelOrder","OrgRepositoryOrder","OrderFieldToIProjectsTeamsOrderBy","TeamOrder","OrderFieldToIProjectsSpaceOrderBy","SpaceOrder","CollaboratorsByAssetIDOrder","whitespaceFilter","ProjectStringRelationResult","DIRECT_COMPARE_VIEWS","ProjectFilter","_view","_directorySubtypes","CC_PROJECTS","organizationID","_organizationID","_nameContains","_getRelationToNameContains","otherName","IDENTICAL","nameTerms","otherNameTerms","subsetMatches","supersetMatches","nameTerm","findMatch","otherTerm","superSet","subSet","SUBSET","SUPERSET","DISJOINTED","_searchTarget","searchString","targetString","searchTerms","targetTerms","searchTerm","targetTerm","_isRecent","_allowInLists","repositoryOwner","searchMatch","subTypeArrayComparison","YourProjects","AllProjects","SWYProjects","AdminProjects","CustomModelFilter","_listingOptions","createDateMin","createDateMax","modifyDateMin","modifyDateMax","trainingJobId","trainingSetVersion","relationWrtCreatedAt","relationWrtModifiedAt","allRelations","getRelationForParam","paramName","getRelationPublishedState","getRelationCreatedBy","getRelationTrainingSetId","getRelationBaseModelName","getRelationBaseModelVersion","getRelationCategory","getRelationInferenceReady","getRelationTrainingJobId","getRelationTrainingState","getRelationTrainingSetVersion","GenerationHistoryAssetFilter","_generationGroupId","_featureFlags","allowedMediaTypes","generationHistoryVectors","generationHistoryAudio","historyAssetTypes","historyAssetType","_historyAssetTypes","requestedFilterType","_getGenerationGroupIdRelation","previousGenerationGroupId","newGenerationGroupId","previousFilter","previousHistoryAssetTypes","newHistoryAssetTypes","relationWrtPublishedState","relationWrtCreatedBy","SpaceFilter","_bookmarked","bookmarked","ActiveSpacesFromTeam","otherSpaceFilter","StringRelationResult","ActiveSpaces","ArchivedSpaces","ActiveBookmarkedSpaces","ActiveSpacesFromOtherTeams","TeamFilter","TeamsContainingName","ActiveTeams","DiscardedTeams","Team","repositoryOwnerID","_repositoryOwnerID","repositoryOwnerEmail","_repositoryOwnerEmail","repositoryOwnerType","_repositoryOwnerType","collaboratorRole","archiveTeam","createSpace","permanentlyDeleteTeam","renameTeam","restoreTeam","updateTeam","loadTeamProperties","TeamUpdater","AddressBookContactOrder","GradientUpdater","_isDefault","_angle","_stops","_languageCode","_gradientID","_textAlpha","_textMode","_textColorValue","_textType","isDefault","angle","stops","textAlpha","textMode","textColorValue","textType","FRAMEIO_AUTHORIZATION_CHANGE","SharedFrameioAuthorizationChangeEvent","FRAMEIO_REVIEW_LINKS_CHANGE","SharedFrameioReviewLinksChangeEvent","FRAMEIO_API_BASE","FRAMEIO_LINKS","ME","ACCOUNT","ACCOUNTS","TEAMS","TEAM","PROJECTS","SHAREDPROJECTS","REVIEWS","REVIEW","ITEMCREATE","ASSETS","ASSET","CREATEASSET","CREATECOMMENT","GETCOMMENT","GETCOMMENTS","IMPRESSIONS","COMMENT","REPLY","GETREPLIES","LIKE","COMPLETE","FOLDERTREE","ANCESTORS","ADOBE_SUSI_USER","ADOBE_SUSI","FrameioInterface","ctx","_frameioContext","frameioClient","_frameioClientId","nativeContext","_nativeContext","workflows","Workflows","createShareForReviewWorkflow","shareForReviewWorkflow","getFrameioAssetContext","_handleReviewLinksChangeEvent","nativeAuthInfo","authenticationInfo","frameioToken","_cacheCredentials","_updateCurrentUserId","frameioUserId","_cachedCredentialsId","_authenticationId","_getRefreshTokenExpiration","lastRefresh","lastRefreshVal","secondsPerHour","_getCachedCredentials","credentialsId","existingCredentials","credentials","millisecondsPerHour","ccUserId","imsToken","xFrameioClient","productKey","checkForCachedCredentials","cachedCredentials","parsedCredentials","refreshExpiration","frameioLastRefresh","authExpired","authenticateUser","authLoggedIn","authLoggedOut","authenticationStatus","nativeAuthStatus","_authenticationInfo","kExpiresHours","setUTCSeconds","getToken","refreshToken","isUserAuthenticated","nativeInfo","frameioRefreshToken","frameioTokenExpires","deauthenticate","deauthenticateUser","openFile","dispatchReviewLinksChangeEvent","getAdobeSusiInfo","respJson","_adobeSusiUserRequest","userExists","exists","susiAvailable","restriction","authenticateAdobeSusi","_adobeSusiRequest","access_token","respHeaders","respBody","tokenExpires","useAdobeSusi","_getMultiPageResponse","readPage","nextPageUri","getCurrentUser","getAccount","accountId","getAccounts","getTeams","getTeam","teamId","getSharedProjects","getReviewLink","createFile","fileSize","mimeType","filetype","filesize","uploadFile","init","reviewLinkAddAsset","asset_ids","getAsset","addVersionToAsset","nextAssetId","next_asset_id","commentId","getComments","getImpressions","updateComment","createReply","getReplies","createLike","deleteLike","completeComment","uncompleteComment","getFolderTree","getAncestors","FrameioBase","FrameioUserUpdater","_accountId","_profileImage","_userDefaultColor","profileImage","userDefaultColor","_account","FrameioAsset","_projectId","_teamId","insertedAt","_insertedAt","_parentId","getParent","updatedAt","_updatedAt","FrameioLikeUpdater","anonymousUserId","_anonymousUserId","_comment","_commentId","deletedAt","_deletedAt","like","_objectPool","FrameioCommentUpdater","_completed","_hasReplies","_likeCount","_private","_readCount","_timestamp","_timestampMicroseconds","completed","completedAt","_completedAt","completerId","_completerId","hasReplies","likeCount","private","readCount","_reviewLinkId","targetAssetId","_targetAssetId","textEditedAt","_textEditedAt","timestampMicroseconds","_frameioInterface","FrameioFileUpdater","_comments","FrameioFolderUpdater","frameioAssetUpdater","_uploadFile","urls","fp","numChunks","iChunk","nextChunk","FrameioTeamUpdater","_projects","projectsResponse","FrameioProjectUpdater","FrameioVersionStack","_coverAssetId","_versions","coverAssetId","getCoverAsset","_coverAsset","coverAsset","FrameioVersionStackUpdater","stack","FrameioReviewLinkUpdater","_shortUrl","_active","_inviteOnly","shortUrl","active","inviteOnly","itemId","_itemId","getArtifactCount","getArtifact","_item","_dispatchReviewLinksChangeEvent","reviewLink","short_url","owner_id","project_id","is_active","access_control","invite_only","parent","artifactPath","_reviewServiceInterface","_rootAssetId","rootAssetId","_team","reviews","_reviews","that","review","FrameioAccountUpdater","teams","_teams","teamsResponse","_sharedProjects","getSharedTeams","getProjectTree","account","_reviewLinksForDocument","_currentUserId","_currentUser","_accounts","_mapKeyForSourceDocument","documentId","_retainUntilTimeout","weak","milliseconds","user","accounts","_getLocalAncestors","unshift","getReviewLinksForDocument","fileSession","folderSession","versionStackSession","AccessControlPrincipalType","AccessControlPrivileges","AccessControlModifier","AccessControlInheritance","RelTypePlatform","extendStatics","__proto__","__extends","__","__assign","__awaiter","P","fulfilled","step","rejected","__generator","y","sent","trys","__spreadArray","pack","ar","l","genericMessage","_a","InvariantError","_super","_this","framesToPop","invariant","condition","verbosityLevels","verbosityLevel","wrapConsoleMethod","maybe","thunk","globalThis","prefixCounts","makeUniqueId","count","stringifyForDisplay","undefId","wrap","_i","arg0","getHandledErrorMsg","getFallbackErrorMsg","originalInvariant","newInvariantError","ApolloErrorMessageHandler","messageArgs","devAssert","LineRegExp","getLocation","position","lastLineStart","matchAll","column","printSourceLocation","sourceLocation","firstLineColumnOffset","locationOffset","lineIndex","lineOffset","lineNum","columnOffset","columnNum","locationStr","lines","locationLine","subLineIndex","subLineColumnNum","subLines","printPrefixedLines","subLine","existingLines","padLen","GraphQLError","rawArgs","_this$nodes","_nodeLocations$","nodes","positions","originalError","firstArg","toNormalizedOptions","undefinedIfEmpty","nodeLocations","loc","locations","pos","originalExtensions","captureStackTrace","output","location","formattedError","syntaxError","Location","startToken","endToken","Token","kind","QueryDocumentKeys","OperationDefinition","VariableDefinition","Variable","SelectionSet","Field","Argument","FragmentSpread","InlineFragment","FragmentDefinition","IntValue","FloatValue","StringValue","BooleanValue","NullValue","EnumValue","ListValue","ObjectValue","ObjectField","Directive","NamedType","ListType","NonNullType","SchemaDefinition","OperationTypeDefinition","ScalarTypeDefinition","ObjectTypeDefinition","FieldDefinition","InputValueDefinition","InterfaceTypeDefinition","UnionTypeDefinition","EnumTypeDefinition","EnumValueDefinition","InputObjectTypeDefinition","DirectiveDefinition","SchemaExtension","ScalarTypeExtension","ObjectTypeExtension","InterfaceTypeExtension","UnionTypeExtension","EnumTypeExtension","InputObjectTypeExtension","kindValues","isNode","maybeNode","maybeKind","OperationTypeNode","DirectiveLocation","Kind","TokenKind","isWhiteSpace","isDigit","isLetter","isNameStart","dedentBlockStringLines","_firstNonEmptyLine2","commonIndent","MAX_SAFE_INTEGER","firstNonEmptyLine","lastNonEmptyLine","_firstNonEmptyLine","indent","leadingWhitespace","Lexer","startOfFileToken","SOF","lastToken","lineStart","advance","lookahead","EOF","nextToken","readNextToken","isUnicodeScalarValue","isSupplementaryCodePoint","isLeadingSurrogate","isTrailingSurrogate","printCodePointAt","lexer","char","createToken","col","bodyLength","readComment","BANG","DOLLAR","AMP","PAREN_L","PAREN_R","SPREAD","COLON","EQUALS","AT","BRACKET_L","BRACKET_R","BRACE_L","PIPE","BRACE_R","readBlockString","readString","readNumber","readName","firstCode","isFloat","readDigits","FLOAT","INT","chunkStart","STRING","escape","readEscapedUnicodeVariableWidth","readEscapedUnicodeFixedWidth","readEscapedCharacter","point","readHexDigit","read16BitHexCode","trailingCode","currentLine","blockLines","BLOCK_STRING","MAX_ARRAY_LENGTH","MAX_RECURSIVE_DEPTH","inspect","formatValue","seenValues","previouslySeenValues","isJSONable","jsonValue","len","remaining","formatArray","tag","getObjectTag","formatObject","formatObjectValue","instanceOf","_value$constructor","className","stringifiedValue","Source","Parser","isSource","_lexer","_tokenCounter","parseName","expectToken","parseDocument","DOCUMENT","definitions","many","parseDefinition","peek","parseOperationDefinition","hasDescription","peekDescription","keywordToken","parseSchemaDefinition","parseScalarTypeDefinition","parseObjectTypeDefinition","parseInterfaceTypeDefinition","parseUnionTypeDefinition","parseEnumTypeDefinition","parseInputObjectTypeDefinition","parseDirectiveDefinition","parseFragmentDefinition","parseTypeSystemExtension","unexpected","OPERATION_DEFINITION","QUERY","variableDefinitions","directives","selectionSet","parseSelectionSet","parseOperationType","parseVariableDefinitions","parseDirectives","operationToken","MUTATION","SUBSCRIPTION","optionalMany","parseVariableDefinition","VARIABLE_DEFINITION","parseVariable","parseTypeReference","defaultValue","expectOptionalToken","parseConstValueLiteral","parseConstDirectives","VARIABLE","SELECTION_SET","selections","parseSelection","parseFragment","parseField","nameOrAlias","alias","FIELD","parseArguments","isConst","parseConstArgument","parseArgument","ARGUMENT","parseValueLiteral","hasTypeCondition","expectOptionalKeyword","FRAGMENT_SPREAD","parseFragmentName","INLINE_FRAGMENT","typeCondition","parseNamedType","expectKeyword","allowLegacyFragmentVariables","FRAGMENT_DEFINITION","parseList","parseObject","advanceLexer","parseStringLiteral","BOOLEAN","NULL","ENUM","block","LIST","any","OBJECT","parseObjectField","OBJECT_FIELD","parseDirective","DIRECTIVE","innerType","LIST_TYPE","NON_NULL_TYPE","NAMED_TYPE","parseDescription","operationTypes","parseOperationTypeDefinition","SCHEMA_DEFINITION","OPERATION_TYPE_DEFINITION","SCALAR_TYPE_DEFINITION","interfaces","parseImplementsInterfaces","parseFieldsDefinition","OBJECT_TYPE_DEFINITION","delimitedMany","parseFieldDefinition","parseArgumentDefs","FIELD_DEFINITION","parseInputValueDef","INPUT_VALUE_DEFINITION","INTERFACE_TYPE_DEFINITION","parseUnionMemberTypes","UNION_TYPE_DEFINITION","parseEnumValuesDefinition","ENUM_TYPE_DEFINITION","parseEnumValueDefinition","parseEnumValueName","ENUM_VALUE_DEFINITION","getTokenDesc","parseInputFieldsDefinition","INPUT_OBJECT_TYPE_DEFINITION","parseSchemaExtension","parseScalarTypeExtension","parseObjectTypeExtension","parseInterfaceTypeExtension","parseUnionTypeExtension","parseEnumTypeExtension","parseInputObjectTypeExtension","SCHEMA_EXTENSION","SCALAR_TYPE_EXTENSION","OBJECT_TYPE_EXTENSION","INTERFACE_TYPE_EXTENSION","UNION_TYPE_EXTENSION","ENUM_TYPE_EXTENSION","INPUT_OBJECT_TYPE_EXTENSION","repeatable","parseDirectiveLocations","DIRECTIVE_DEFINITION","parseDirectiveLocation","noLocation","getTokenKindDesc","atToken","openKind","parseFn","closeKind","delimiterKind","maxTokens","isPunctuatorTokenKind","escapedRegExp","escapedReplacer","escapeSequences","BREAK","freeze","visit","visitor","visitorKeys","enterLeaveMap","getEnterLeaveForKind","inArray","edits","isLeaving","isEdited","editOffset","editKey","editValue","arrayKey","_enterLeaveMap$get","_enterLeaveMap$get2","visitFn","leave","enter","_node$kind","kindVisitor","printDocASTReducer","varDefs","argsLine","isBlockString","escapedValue","isSingleLine","forceLeadingNewLine","hasTrailingTripleQuotes","hasTrailingQuote","hasTrailingSlash","forceTrailingNewline","printAsMultipleLines","skipLeadingNewLine","printBlockString","hasMultilineItems","maybeArray","_maybeArray$filter$jo","maybeString","_maybeArray$some","isSelectionNode","shouldInclude","variables","isInclusionDirective","directiveArguments","directiveName","ifArgument","ifValue","getInclusionDirectives","evaledValue","hasDirectives","names","nameSet","uniqueCount","hasClientExports","defaultMakeData","Trie","weakness","makeData","lookup","lookupArray","getChildTrie","peekArray","mapFor","removeArray","head","child","strong","isObjRef","isReactNative","navigator","product","canUseWeakMap","HermesInternal","canUseWeakSet","canUseSymbol","canUseAsyncIteratorSymbol","isNonNullObject","getFragmentQueryDocument","fragmentName","actualFragmentName","fragments","definition","createFragmentMap","symTable","fragment","getFragmentFromSelection","selection","fragmentMap","defaultDispose","createElement","userAgent","StrongCache","dispose","newest","oldest","getNode","older","newer","clean","_WeakRef","_WeakMap","_FinalizationRegistry","WeakCache","unfinalizedNodes","finalizationScheduled","finalize","keyRef","registry","queueMicrotask","deleteNode","scheduleFinalization","scheduledCleanup","AutoCleanedWeakCache","AutoCleanedStrongCache","cacheSizeSymbol","cacheSizes","globalCaches","registerGlobalCache","getSize","getApolloClientMemoryInternals","__DEV__","_b","_c","_d","_e","limits","canonicalStringify","print","linkInfo","queryManager","getDocumentInfo","documentTransforms","transformInfo","documentTransform","getMemoryInternals","getInMemoryCacheMemoryInternals","_getApolloCacheMemoryInternals","addTypenameDocumentTransform","inMemoryCache","executeSelectionSet","getWrapperInformation","executeSubSelectedArray","maybeBroadcastWatch","fragmentRegistry","findFragmentSpreads","transform","getApolloCacheMemoryInternals","fragmentQueryDocuments","isWrapper","isDefined","recurseTransformInfo","left","right","sortingMap","stableObjectReplacer","reset","everyKeyInOrder","unsortedKey","sortedKeys","sortedKey","sortedObject_1","makeReference","__ref","valueToObjectRepresentation","argObj","isIntValue","isFloatValue","isBooleanValue","isStringValue","isObjectValue","nestedArgObj_1","isVariable","variableValue","isListValue","listValue","nestedArgArrayObj","isEnumValue","isNullValue","KNOWN_DIRECTIVES","storeKeyNameStringify","getStoreKeyName","fieldName","filterKeys","filteredArgs_1","completeFieldName","stringifiedArgs","setStringify","previous","argumentsObjectFromField","argObj_1","resultKeyNameFromField","getTypenameFromResult","isField","__typename","fragments_1","typename","checkDocument","doc","getOperationDefinition","getOperationName","getFragmentDefinitions","getQueryDefinition","queryDef","getMainDefinition","queryDoc","fragmentDefinition","getDefaultValues","defaultValues","defs","def","currentContext","MISSING_VALUE","idCounter","ignored","globalKey","globalHost","Slot","hasValue","slots","withValue","saved","noContext","parentEntrySlot","arrayFromSet","maybeUnsubscribe","entryOrDep","unsubscribe","emptySetPool","POOL_TARGET_SIZE","optionalMessage","valueIs","valueGet","valueCopy","Entry","parents","childValues","dirtyChildren","dirty","recomputing","deps","mightBeDirty","rememberParent","recompute","forgetChildren","recomputeNewValue","subscribe","setDirty","maybeSubscribe","reportClean","setClean","reallyRecompute","reportDirty","eachParent","forgetChild","forget","dependOn","dep","forgetDeps","reportDirtyChild","reportCleanChild","normalizeResult","oldValueCopy","parentCount","parentWasClean","childValue","removeDirtyChild","EntryMethods","depsByKey","depend","entryMethodName","defaultKeyTrie","defaultMakeCacheKey","caches","originalFunction","makeCacheKey","cacheOption","optimistic","dirtyKey","peekKey","forgetKey","getKey","identity","printCache","DocumentTransform","resultCache","cached","resetCache","predicate","transformDocument","stableCacheKeys_1","performWork","cacheKeys","transformedDocument","otherTransform","ast","origPrint","isNonEmptyArray","TYPENAME_FIELD","isEmpty","nullIfDocIsEmpty","fragmentDef","getFragmentDefinition","makeInUseGetterFunction","defaultKey","inUse","fragmentSpreads","removeDirectivesFromDocument","getInUseByOperationName","getInUseByFragmentName","getInUse","ancestor","operationCount","tests","directiveMatcher","testConfig","shouldRemoveField","nodeDirectives","originalFragmentDefsByPath","firstVisitMadeChanges","fieldOrInlineFragmentVisitor","docWithoutDirectiveSubtrees","removed","populateTransitiveVars","transitiveVars","childFragmentName","allFragmentNamesUsed","enterVisitor","usedVariableNames_1","varDef","addTypenameToDocument","added","buildQueryFromSelectionSet","removeClientSetsFromDocument","mergeDeep","mergeDeepArray","merger","DeepMerger","merge","defaultReconciler","reconciler","pastCopies","sourceKey","targetValue","shallowCopyForMerge","_arrayLikeToArray","arr","arr2","_defineProperties","props","_createClass","Constructor","protoProps","staticProps","hasSymbols","hasSymbol","getSymbol","SymbolIterator","SymbolObservable","SymbolSpecies","getMethod","getSpecies","ctor","Observable","isObservable","hostReportError","cleanupSubscription","cleanup","_cleanup","closeSubscription","_observer","_queue","notifySubscription","observer","onNotify","queue","flushSubscription","Subscription","subscriber","subscriptionObserver","SubscriptionObserver","_subscription","_proto2","complete","_subscriber","_proto3","_this2","_this3","_this4","C","hasSeed","_this5","_len","startNext","flatMap","_this6","outer","inner","completeIfDone","closed","_step","_iterator","allowArrayLike","it","minLen","_unsupportedIterableToArray","_createForOfIteratorHelperLoose","of","_len2","_key2","symbol","Function","ponyfill","fakeObsSymbol","cloneDeep","cloneDeepHelper","seen","copy_1","copy_2","maybeDeepFreeze","workSet","isFrozen","shallowFreeze","getOwnPropertyNames","iterateObserversSafely","observers","argument","observersWithMethod","obs","asyncMap","mapFn","catchFn","promiseQueue","makeCallback","examiner","both","handler","fixObservableSubclass","subclass","species","isPromiseLike","Concast","addObserver","removeObserver","handlers","latest","notify","nextResultListeners","cancel","iterable","deliverLastMessage","nextOrError","beforeNext","called","isExecutionPatchIncrementalResult","isApolloPayloadResult","mergeIncrementalData","prevResult","mergedData","incremental","parent_1","graphQLResultHasError","getGraphQLErrorsFromResult","incrementalResult","compact","mergeOptions","defaults","fromError","errorValue","throwServerError","passthrough","forward","toLink","ApolloLink","isTerminating","empty","leftLink","rightLink","execute","starting","createOperation","transformedOperation","transformOperation","OPERATION_FIELDS","validateOperation","second","firstLink","nextLink","setOnError","readerIterator","reader","responseIterator","resolved","getReader","isReadableStream","stream","isStreamableBlob","isBlob","pipe","isNodeReadableStream","waiting","onData","shiftedArr","pair","onEnd","nodeStreamIterator","PROTOCOL_ERRORS_SYMBOL","isApolloError","ApolloError","protocolErrors","clientErrors","extraInfo","parseHeaders","headerText","headersInit","name_1","parseJsonBody","bodyText","getResult","parseError","serializeFetchParameter","serialized","fallbackHttpConfig","http","includeQuery","includeExtensions","preserveHeaderCase","accept","defaultPrinter","printer","selectHttpOptionsAndBodyInternal","normalizedHeaders_1","headerData","originalName","normalizedHeaders","removeDuplicateHeaders","backupFetch","HttpLink","linkOptions","preferredFetch","useGETForQueries","includeUnusedVariables","fetcher","checkFetcher","linkConfig","chosenURI","fallbackURI","getContext","selectURI","clientAwarenessHeaders","clientAwareness","contextHeaders","contextConfig","transformedQuery","unusedNames","isSubscription","hasDefer","acceptHeader","addQueryParam","serializedVariables","serializedExtensions","preFragment","fragmentStart","queryParamsPrefix","newURI","rewriteURIForGET","currentFetch","observerNext","setContext","ctype","nextValue","decoder","boundaryVal","boundary","running","searchFrom","bi","contentType_1","hasNext","readMultipartBody","createHttpLink","fnToStr","previousComparisons","equal","check","aTag","previouslyCompared","aKeys","definedKeys","bKeys","keyCount","aIterator","isMap","aKey","aValue","aCode","full","suffix","fromIndex","nativeCodeSuffix","isDefinedKey","bSet","equalByQuery","aData","aRest","bData","equalBySelectionSet","aResult","bResult","seenSelections","selectionHasNonreactiveDirective","resultKey","aResultChild","bResultChild","childSelectionSet","aChildIsArray","bChildIsArray","length_1","directiveIsNonreactive","ApolloCache","assumeImmutableResults","getFragmentDoc","updateResult","optimisticId","performTransaction","recordOptimisticTransaction","transformForLink","identify","gc","modify","readQuery","rootId","watchFragment","latestDiff","otherOptions","diffOptions","returnPartialData","immediate","diff","missing","readFragment","writeQuery","write","dataId","writeFragment","updateQuery","updateFragment","MissingFieldError","hasOwn","isNullish","defaultDataIdFromObject","keyObject","defaultConfig","dataIdFromObject","addTypename","resultCaching","canonizeResults","shouldCanonizeResults","TypeOrFieldNameRegExp","fieldNameFromStoreName","storeFieldName","selectionSetMatchesResult","storeValueIsStoreObject","extractFragmentContext","lookupFragment","DELETE","delModifier","INVALIDATE","EntityStore","policies","group","rootIds","getFieldValue","objectOrReference","canRead","objOrRef","toReference","objOrIdOrRef","mergeIntoStore","toObject","storeObject","rootTypenamesById","Layer","dependOnExistence","incoming","merged","storeObjectReconciler","caching","fieldsToDirty_1","__exists","hasKeyArgs","changedFields_1","needToMerge_1","allDeleted_1","sharedDetails_1","readField","fieldNameOrOptions","store","fieldValue","storage","getStorage","checkReference","seenReference","someNonReference","newValue_1","getStoreFieldName","evict","evicted","extract","extraRootIds","getRootIdSet","__META","newData","rest_1","retain","snapshot","findChildRefIds","idsToRemove","root_1","found_1","workSet_1","keyMaker","CacheGroup","resetCaching","makeDepKey","maybeDependOnExistenceOfEntity","entityId","supportsResultCaching","Root","stump","Stump","storageTrie","addLayer","layerId","replay","removeLayer","ownStoreObject","parentStoreObject","fromParent","existingObject","incomingObject","existingValue","incomingValue","ObjectCanon","known","passes","keysByJSON","admit","isKnown","isObjectOrArray","pass","shallowCopy","proto_1","array_1","firstValueIndex_1","sorted","obj_1","execSelectionSetKeyArgs","StoreReader","knownResults","canon","peekArgs","enclosingRef","execSelectionSetImpl","resultCacheMaxSize","varString","execSubSelectedArrayImpl","resetCanon","diffQueryAgainstStore","rootRef","execResult","firstMissing","isFresh","objectsToMerge","missingMerger","handleMissing","resultName","rootIdsByTypename","fragmentMatches","finalResult","frozen","childResult","getTypenameFromStoreObject","assertSelectionSetForIdValue","tree","cacheSlot","cacheInfoMap","getCacheInfo","vars","forgetCache","rv","makeVar","broadcastWatches","broadcast","oldListeners","attach","onNextChange","attachCache","specifierInfoCache","lookupSpecifierInfo","keyFieldsFnFromSpecifier","specifier","keyFieldsFn","collectSpecifierPaths","schemaKeyPath","extracted","extractKeyPath","extractKey","keyArgsFnFromSpecifier","keyArgsFn","collected","firstKey","firstChar","variableName","varKeyPath","directiveName_1","directiveArgs","extractor","getSpecifierPaths","toMerge","paths","paths_1","currentPath_1","reducer","argsFromFieldSpecifier","nullKeyFieldsFn","simpleKeyArgsFn","_args","mergeTrueFn","mergeObjects","mergeFalseFn","Policies","typePolicies","toBeAdded","supertypeMap","fuzzySubtypes","usingPossibleTypes","setRootTypename","possibleTypes","addPossibleTypes","addTypePolicies","partialContext","ROOT_QUERY","normalizeReadFieldOptions","getTypePolicy","keyFn","specifierOrId","queryType","mutationType","subscriptionType","updateTypePolicy","keyFields","setMerge","getFieldPolicy","which","old","supertype","getSupertypeSet","subtype","policy_1","supertypes_1","regExp","fuzzy","fuzzySupertypes","inbox","createIfMissing","fieldPolicies","supertypeSet","typenameSupertypeSet","workQueue_1","maybeEnqueue_1","needToCheckFuzzySubtypes","checkingFuzzySubtypes","fuzzyString","fieldSpec","specifierOrString","directivesObj","storeKeyNameFromField","readOptions","makeFieldFunctionOptions","getReadFunction","getMergeFunction","parentTypename","childTypename","runMergeFunction","makeMergeObjectsFunction","overwrite","readFieldArgs","argc","eType","iType","getContextFlavor","clientOnly","deferred","flavored","flavors","StoreWriter","writeToStore","operationDefinition","written","incomingById","processSelectionSet","mergeTree","fieldNodeSet","entityRef","applied","applyMerges","fieldsWithSelectionSets_1","hasSelectionSet_1","childTree","hasMergeFunction_1","existingRef","incomingObj","parentType","typeDotName","childTypenames","warnAboutDataLoss","result_1","flattenFields","resultFieldKey","getChildMergeTree","processFieldValue","maybeRecycleChildMergeTree","dataRef","sets","previous_1","mergeMergeTrees","mergeTreeIsEmpty","limitingTrie","flatten","inheritedContext","visitedNode","visited","if","getStorageArgs","e_1","i_1","getValue_1","eVal","iVal","aVal","emptyMergeTreePool","needToMergeMaps","remainingRightKeys_1","leftTree","watches","addTypenameTransform","txCount","normalizeConfig","rootStore","optimisticData","resetResultCache","resetResultIdentities","previousReader","storeReader","storeWriter","broadcastWatch","recallCache","resetCaches","discardWatches","removeOptimistic","idToRemove","newOptimisticData","onWatchUpdated","perform","layer","alreadyDirty","addFragmentsToDocument","lastDiff","fromOptimisticTransaction","isNetworkRequestInFlight","ObservableQuery","queryInfo","subObserver","defaultSubscriptionObserverErrorCallback","last","reobserve","tearDownQuery","waitForOwnResult","skipCacheDataFor","fetchPolicy","isTornDown","subscribeToMore","defaultOptions","watchQuery","defaultFetchPolicy","_f","initialFetchPolicy","queryId","generateQueryId","opDef","queryName","lastQuery","removeQuery","resetDiff","getCurrentResult","saveAsLastResult","lastResult","getLastResult","ready","hasForcedResolvers","getDiff","partial","partialRefetch","logMissingFieldErrors","updateLastResult","isDifferentFromLastResult","newResult","hasNonreactiveDirective","getLast","variablesMustMatch","getLastError","resetLastResults","resetQueryStoreErrors","resetErrors","refetch","reobserveOptions","pollInterval","resetLastWrite","fetchMore","fetchMoreOptions","combinedOptions","qid","originalNetworkStatus","notifyOnNetworkStatusChange","observe","updatedQuerySet","isCached","fetchQuery","fetchMoreResult","reportResult","reobserveCacheFirst","startGraphQLSubscription","subscriptionData","setOptions","newOptions","silentSetOptions","mergedOptions","setVariables","broadcastQueries","startPolling","updatePolling","stopPolling","applyNextFetchPolicy","nextFetchPolicy","newNetworkStatus","setObservableQuery","ssrMode","pollingInfo","hasObservers","maybeFetch","skipPollAttempt","poll","reobserveAsConcast","useDisposableConcast","oldVariables","oldFetchPolicy","finishWaitingForOwnResult","concast","fromLink","reportError","resubscribeAfterError","isDifferent","errorResult","stopQuery","obsQuery","currentFetchPolicy","destructiveMethodCounts","wrapDestructiveCacheMethod","methodName","cancelNotifyTimeout","QueryInfo","lastRequestId","observableQuery","getDiffOptions","updateWatch","oq","updateLastDiff","setDiff","oldDiff","notifyTimeout","oqListener","shouldNotify","watchOptions","watcher","lastWatch","lastWrite","shouldWrite","dmCount","markResult","cacheWriteBehavior","shouldWriteResult","errorPolicy","markReady","markError","ignoreErrors","writeWithErrors","IGNORE","QueryManager","fetchCancelFns","transformCache","queryIdCounter","requestIdCounter","mutationIdCounter","inFlightLinkObservables","defaultDocumentTransform","queryDeduplication","localState","defaultContext","onBroadcast","mutationStore","_info","stopQueryNoBroadcast","cancelPendingFetches","mutate","mutationId","mutationStoreValue","isOptimistic","optimisticResponse","updateQueries","refetchQueries","awaitRefetchQueries","updateWithProxyFn","onQueryUpdated","_g","_h","keepRootFields","_j","generateMutationId","getVariables","addExportedVariables","markMutationOptimistic","getObservableFromLink","storeResult","markMutationResult","cacheWrites","asQuery","updateQueries_1","currentQueryResult","nextQueryResult","mutationResult","queryVariables","results_1","updateCache","isFinalResult","isExecutionPatchInitialResult","include","fetchConcastWithInfo","getQueryStore","cacheEntry","shouldForceResolvers","clientQuery","serverQuery","defaultVars","generateRequestId","stopQueryInStore","stopQueryInStoreNoBroadcast","clearStore","getObservableQueries","queryNamesAndDocs","legacyQueryOptions","getQuery","nameOrDoc","reFetchObservableQueries","includeStandby","observableQueryPromises","hasErrors","hasProtocolErrors","graphQLResultHasProtocolErrors","observablePromise_1","getLocalState","deduplication","inFlightLinkObservables_1","prepareContext","forceFetch","printedServerQuery_1","varJson_1","runResolvers","remoteResult","getResultsFromLink","requestId","linkDocument","aqr","containsDataFromLink","normalized","fromVariables","sourcesWithInfo","fetchQueryByPolicy","cleanupCancelFn","includedQueriesById","refetchWritePolicy","oldNetworkStatus","readCache","resultsFromCache","fromData","onlyRunForcedResolvers","resultsFromLink","newContext","LocalState","client","resolvers","fragmentMatcher","selectionsToResolveCache","addResolvers","setFragmentMatcher","resolverGroup","setResolvers","getResolvers","resolveDocument","localResult","getFragmentMatcher","document_1","buildRootValueFromCache","exportedVariables","forceResolvers","rootValue_1","rootValue","mainDefinition","selectionsToResolve","definitionOperation","defaultOperationType","execContext","collectSelectionsToResolve","resolveSelectionSet","isClientFieldDescendant","resultsToMerge","resolveField","fieldResult","isInlineFragment","fragmentResult","aliasedFieldName","aliasUsed","defaultResult","resultPromise","resolverType","resolverMap","isClientField","resolveSubSelectedArray","isSingleASTNode","collectByDefinition","definitionNode","matches_1","___","spread","fragmentSelections","hasSuggestedDevtools","ApolloClient","resetStoreCallbacks","clearStoreCallbacks","ssrForceFetchDelay","connectToDevTools","typeDefs","clientAwarenessName","clientAwarenessVersion","devtools","disableNetworkFetches","devtoolsConfig","enabled","resetStore","devToolsHookCb","mutations","dataWithOptimisticResults","windowWithDevTools","devtoolsSymbol","__APOLLO_CLIENT__","top","protocol","__APOLLO_DEVTOOLS_GLOBAL_HOOK__","nav","ua","__actionHookForDevTools","cb","__requestRaw","onResetStore","onClearStore","serializedState","setLocalStateFragmentMatcher","setLink","newLink","docCache","fragmentSourceMap","printFragmentWarnings","experimentalFragmentVariables","seenKeys","parsed","stripLoc","sourceKeySet","gql","literals","gql_1","extras","disableFragmentWarnings","enableExperimentalFragmentVariables","disableExperimentalFragmentVariables","RetryableOperation","delayFor","retryIf","currentSubscription","scheduleRetry","try","timerId","RetryLink","attempts","delayOptions","initial","jitter","baseDelay","buildDelayFunction","retryOptions","buildRetryFunction","retryable","compositeAndFileFields","GQLResolveAssetFields","favorite","Privelege","OrderFieldToGQLOrderBy","OperationType","OperationType_1","Utils_1","NestedField_1","Utils","resolveVariables","operations_1","getNestedVariables","queryDataNameAndArgumentMap","dataString","queryFieldsMap","isNestedField","queryNestedFieldMap","operationOrAlias","isFragment","operationOrFragment","getFragment","queryVariablesMap","variablesMapped","getDeepestVariables","innerFields","queryDataType","candidateValue","DefaultAppSyncMutationAdapter_1","DefaultAppSyncMutationAdapter","mutationBuilder","operationWrapperTemplate","operationTemplate","mutationsBuilder","content","queryDataArgumentAndTypeMap","Mutation","DefaultAppSyncQueryAdapter_1","DefaultAppSyncQueryAdapter","queryBuilder","queriesBuilder","tmpl","Query","DefaultMutationAdapter_1","DefaultMutationAdapter","variablesUsed","DefaultQueryAdapter_1","DefaultQueryAdapter","DefaultSubscriptionAdapter_1","DefaultSubscriptionAdapter","subscriptionBuilder","subscriptionsBuilder","adapters_1","require$$2","require$$3","adapter","repoMetadataFragment","appMetadataFragment","effectivePermissionsFragment","getListingQuery","listingFragment","assetByPathDataQuery","needEffectivePermissionsFragment","needAppMetadataFragment","resolveAssetByPathQuery","assetByRelativePathQuery","UPDATE_LAST_ACCESSED","Log","tailLogs","getLogs","Storage","purge","Persistor","maxSize","persistenceMapper","paused","persist","error_1","error_2","error_3","Trigger","persistor","fire","debounce","defaultDebounce","uninstall","onCacheWrite","onAppBackground","pause","CachePersistor","SynchronousCachePersistor","SynchronousStorage","SynchronousPersistor","restoreSync","readSync","Asset","Repository","ResourceQueryWatcher","firstResultPromise","onQueryIdle","queryIdleTimeout","watchQueryTTL","parsedResult","previousResult","apolloError","GQLInterface","_client","_addTypeName","useEdge","httpLink","authMiddleware","authorization","retryLink","_operation","maxRetries","hasExceededMaxRetries","isUnauthorizedError","isServerError","samCache","queryOptions","queryWatcher","gqlArgs","getAssetById","resolveAssetById","resolveAssetByPath","getAssetByRelativePath","sharedWithYouQuery","SHARED_WITH_YOU_ASSETS","generationHistoryAssets","fireflyGenerationsDirectory","generationAssetsConnection","recentsQuery","updateLabel","GET_GENERATION_MODEL_DISPLAY_NAME","getGenerationModelDisplayName","GenerationHistoryAssetUpdater","filterUndefinedProperties","filtered","convertGQLAssetToAdobeAssetData","repoRepresentations","repo_representations","rapiPermissions","aclPolicy","applicationMetadata","parseGQLEffectivePermissions","repo_ancestors","repo_assetClass","repo_assetType","repo_assetSubType","primary_etag","repo_createDate","repo_createdBy","repo_modifyDate","repo_name","repo_path","repo_modifiedBy","repo_repositoryId","repo_state","repo_size","repo_version","storage_assignee","storage_region","storage_deviceCreateDate","storage_deviceModifyDate","tiff_imageLength","tiff_imageWidth","generationModelDisplayName","labels","primaryLink","blockUploadLink","blockDownloadLink","renditionLink","sharingInfo","GraphQLAssetResource","onResult","resultHandlers","addResultHandler","addAssetFromResult","assetFromResult","maybeAssetInfo","_applyDataToAsset","addAssetResourcesFromResult","subresources","_applyDataToAssetResources","adobeAssetData","_gqlInterface","_listData","_handleListingHints","assetByPath","listItem","generateDirectoryLoaderHash","existingData","resolveUserHome","assetByRelativePath","assetResources","gqlFilter","neq","eq","childrenConnection","lastAccessDate","WORKSPACE_INDEX_LINKS","WORKSPACES_CONTEXT","TEAMS_PAGE","WORKSPACES_PRIMARY","WORKSPACES_PAGE","REPOSITORIES_PAGE","TEAMS_CREATE","TEAM_PROVISION","WORKSPACES_BOOKMARKS_BATCH","TEAM_PROVISION_SUCCESS_CODES","SPACE_FULL_SELECTOR","DefaultTeamListingOptions","DefaultSpacesListingOptions","getDefaultOptions","Defaults","WorkspacesInterface","getTeamListingPath","getOrgRepositories","TEAMS_PRIMARY","TEAMS_DISCARD","teamLinks","TEAMS_RESTORE","TEAMS_RENAME","patchTeam","TEAMS_PROPERTIES","getTeamProperties","provisionTeam","getSpaces","bookmarkFilter","teamAccess","getSpacesListingPath","spaceLink","spaceLinks","bookmarkOp","WORKSPACES_CREATE","patchSpace","getEnclosingSpaces","SpaceLoader","_spacePool","_workspaceInterface","_teamRoleGetterFactory","teamRoleFn","pageSpec","totalLimit","TeamLoader","_teamPool","_projectInterface","OrgRepositoryLoader","_orgRepositoryPool","createTeamRoleGetter","getLinks","ProjectInterface","_hostAssetContext","_fetchTeams","_teamPoolDelegate","getTeamRole","spaceSession","newTeamRole","orgRepositoryPool","teamPool","provisionType1Team","orgRepository","_renameAsset","_renameTeam","adobeAssetPool","localAdobeAsset","adobeAssetSession","_validateDescription","_validateColor","_getPatchOP","_patchTeam","localUpdate","_checkForRejection","permDeleteTeamIDs","_moveSpaces","spaces","targetAsset","spacesById","moveSpaces","restoreNameMap","additionalSpaceUpdates","remoteRepoPath","assetSession","createSpaceBookmarks","_bookmarkSpaces","removeSpaceBookmarks","change","localSession","spaceById","wasBookmarked","projectUrn","responses","restoreSession","mutationSession","onRemoveItem","_renameSpace","_patchSpace","onUserLeftTeam","computeGradientID","rawGradientId","ImplicitDirectoryListingAssetFilter","baseOpts","_implicitDirectoryListingFilter","_adobeAssetFilter","Project","_projectPermissions","_repositoryOwner","_directorySubtype","_projectLinks","projectLinks","_getGradient","gradient","_gradient","getGradient","inaccessibleLibraryReferencesCount","_inaccessibleLibraryReferences","allOwners","projectPool","_updateProjectLinksFromService","returnProject","_isProjectLinkType","validateProjectNameForRename","validateProjectNameForCreate","updateProperties","leaveStatus","PENDING","CANNOT_LEAVE_NO_COLLABORATORS","currentUserCollaborator","CANNOT_LEAVE_IS_OWNER","CANNOT_LEAVE_IS_ADMIN_OF_PROJECT","CANNOT_LEAVE_LAST_COLLABORATOR","CAN_LEAVE","CANNOT_LEAVE_ADDRESS_BOOK_GROUP_MEMBER","CANNOT_LEAVE_LAST_DIRECT_COLLAB_WITH_SHARE_PERMISSION","userCanLeaveProject","updateProject","canRestore","_getCachedRestoreCapability","restorePermissionChanged","librariesSource","directoryLoader","isRecent","referenced_by_project","localLibrary","requestAccessToLibraryReferences","ProjectUpdater","computedGradientID","projectPrimary","parseProjectEffectivePermissions","ProjectsListLoader","_projectPool","recentOptions","ownerIds","homeOrgId","allowInLists","ImplicitProjectFilter","_gradientPool","_canRestoreProjectCache","_getGradients","originalGradient","updatedName","_checkForInvite","gradientData","defaultGradientId","computedGradients","rawGradientData","computedID","computeGradients","gradients","newGradient","_defaultGradient","gradientId","canCreateProjects","canCreateProjectReason","ALLOWED","ADMIN_DISABLED","INVALID_REPOSITORY","getProjectsSearchSource","getProjectOrder","getProjectFilter","createCSCProjectByPath","subType","_createCSCProject","createCSCProjectInParent","sourceProjectId","sourceProjectLinks","newTargetMetadata","baseCSCCreateOptions","createData","cscProjectMetadata","cscProject","API_ROOT","ClassroomsInterface","createClassroom","subject","grades","period","teachers","createClassroomFromVirtual","virtualClassroomId","updateClassroomFromVirtual","deleteClassroom","deleteVirtualClassroom","getClassroom","classroom","importedFrom","getClassrooms","classrooms","refreshClassroomCode","updateClassroom","getClassroomTeachers","getClassroomMembers","getClassroomStudents","urlFilter","classroomResponse","members","member","computedKey","getMembership","blockStudent","studentId","unblockStudent","removeStudent","removeTeacher","checkCoTeacherEligibility","emails","ClassroomMemberListLoader","_ClassroomMemberPool","_classroomsInterface","classroomMemberFilter","SubjectChoices","Classroom","_code","_importSource","_isDeleted","_isVirtual","_grades","_period","ACTIVE","_subject","noSubject","_classroomMemberPool","_members","importSource","isDeleted","userCount","_userCount","refreshCode","ClassroomUpdater","virtualId","remoteImportSource","sourceId","synced","lastUpdatedAt","_virtualId","ClassroomListLoader","_classroomPool","DefaultAssignmentsListingOptions","AssignmentsInterface","getAssignments","getAssignmentsListingPath","getAssignmentBy","identifierType","ASSIGNMENTS_CODE","getAssignment","getAssignmentByCode","createAssignment","hasTasks","extTemplateIds","extTutorials","patchAssignment","discardAssignment","restoreAssignment","StudentAssignmentAppMetadataResource","_studentAssignmentsInterface","rapiLinks","humeLinks","StudentAssignmentUpdater","StudentAssignmentFilesListLoader","studentAssignmentsInterface","cachedStudentAssignment","studentAssignmentFiles","_hasLoadedChildren","_updateStudentAssignmentFilesCache","remoteStudentAssignmentFiles","StudentAssignment","_assignmentId","_assignmentCode","_inheritedClassroomId","_hasLoadedChildrenProp","_student","_studentAssignmentFiles","_studentAssignmentAppMetadata","parentAssignmentId","studentDirectoryId","_studentDirectoryId","submission","_submission","_submissionDate","getFiles","getStudentAssignmentFiles","files","_studentAssignmentFilesSource","studentAssignmentLinks","canStart","canReturn","_returnAssignment","_startAssignment","submitAssignment","studentAssignment","remoteAssignee","AssignmentAppMetadataResource","AssignmentUpdater","ImplicitStudentAssignmentFilter","studentAssignmentItem","AssignmentStatusChoices","Assignment","_assignmentInterface","_canClassroomReadSubmissions","_externalTemplateIds","_externalTemplateIdsRemote","_instructions","_isAutoCreated","_studentAssignments","_externalTutorials","_isExternalTutorialsDirty","_materialsAssetId","_studentsAssetId","_parentAssignmentsFolderAssetId","_assignmentAppMetadata","_campaignId","studentAssignments","_getStudentAssignmentsFilter","_getStudentAssignmentsSource","isAutoCreated","_dueDate","_tasks","_templateIds","materialsAssetId","studentsAssetId","_parentAssignmentsAssetId","templateIdOrTutorial","_referenceIds","didLinksComeFromHume","isPartialAssignment","assignmentMetadata","updateAssignment","setTemplates","templateAssetIds","_parentClassroomAssetId","assignment","studentAssignmentsWithComputedValues","sa","cachedStudentAssignments","externalTemplateIdsAndTutorials","AssignmentsListLoader","observeAssignmentsFolder","assignmentsFolderId","validateStudentAssignmentsFilter","_monitoredFolder","StudentAssignmentListLoader","_StudentAssignmentsInterface","observeStudentsFolder","remoteStudentAssignments","studentAssignmentsWithCode","_globalThis","re","isCompatible","ownVersion","acceptedVersions","rejectedVersions","myVersionMatch","ownVersionParsed","globalVersion","_reject","_accept","globalVersionMatch","globalVersionParsed","_makeCompatibilityCheck","GLOBAL_OPENTELEMETRY_API_KEY","_global","registerGlobal","diag","allowOverride","api","getGlobal","unregisterGlobal","DiagLogLevel","DiagComponentLogger","_namespace","namespace","logProxy","verbose","funcName","__read","DiagAPI","_logProxy","setLogger","optionsOrLogLevel","oldLogger","newLogger","maxLevel","_filterFunc","theLevel","theFunc","VERBOSE","createLogLevelDiagLogger","suppressOverrideMessage","disable","createComponentLogger","BaggageImpl","getEntry","getAllEntries","setEntry","newBaggage","removeEntry","removeEntries","keys_1","keys_1_1","e_1_1","return","createBaggage","createContextKey","TraceFlags","ROOT_CONTEXT","BaseContext","parentContext","_currentContext","deleteValue","NoopMeter","createHistogram","NOOP_HISTOGRAM_METRIC","createCounter","NOOP_COUNTER_METRIC","createUpDownCounter","NOOP_UP_DOWN_COUNTER_METRIC","createObservableGauge","NOOP_OBSERVABLE_GAUGE_METRIC","createObservableCounter","NOOP_OBSERVABLE_COUNTER_METRIC","createObservableUpDownCounter","NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC","addBatchObservableCallback","_callback","_observables","removeBatchObservableCallback","NoopMetric","NoopCounterMetric","_attributes","NoopUpDownCounterMetric","NoopHistogramMetric","record","NoopObservableMetric","addCallback","removeCallback","NoopObservableCounterMetric","NoopObservableGaugeMetric","NoopObservableUpDownCounterMetric","NOOP_METER","defaultTextMapGetter","carrier","defaultTextMapSetter","NoopContextManager","with","_context","enable","API_NAME","NOOP_CONTEXT_MANAGER","ContextAPI","setGlobalContextManager","contextManager","_getContextManager","INVALID_SPANID","INVALID_TRACEID","INVALID_SPAN_CONTEXT","traceId","spanId","traceFlags","NonRecordingSpan","_spanContext","spanContext","setAttribute","setAttributes","addEvent","setStatus","updateName","_endTime","isRecording","recordException","_exception","_time","SPAN_KEY","getSpan","getActiveSpan","setSpan","span","deleteSpan","setSpanContext","getSpanContext","VALID_TRACEID_REGEX","VALID_SPANID_REGEX","isSpanContextValid","wrapSpanContext","contextApi","NoopTracer","startSpan","parentFromContext","startActiveSpan","arg4","contextWithSpanSet","NOOP_TRACER","ProxyTracer","_provider","_getTracer","_fn","tracer","getDelegateTracer","NOOP_TRACER_PROVIDER","NoopTracerProvider","getTracer","ProxyTracerProvider","getDelegate","setDelegate","NOOP_METER_PROVIDER","NoopMeterProvider","getMeter","MetricsAPI","setGlobalMeterProvider","provider","getMeterProvider","metrics","NoopTextMapPropagator","inject","_carrier","BAGGAGE_KEY","getBaggage","getActiveBaggage","setBaggage","baggage","deleteBaggage","NOOP_TEXT_MAP_PROPAGATOR","PropagationAPI","setGlobalPropagator","propagator","setter","_getGlobalPropagator","propagation","TraceAPI","_proxyTracerProvider","setGlobalTracerProvider","success","getTracerProvider","trace","traceableAs","targetConstructor","spanName","opentelemetry","getClassroomById","classroomInterface","_processRemoteClassroomItem","getClassroomByCode","classCode","ClassroomListListLoader","getClassroomByAssetId","classroomList","getClassroomByBoardId","cleanAssignmentName","trimEnd","classroomValidationErrors","classroomDataToValidate","hasId","validateClassroomData","assignmentValidateErrors","assignmentDataToValidate","tutorial","validateTutorialData","hasTemplates","hasTutorials","hasExternalTemplates","validateAssignmentData","recentMigratedClassroom","incomingTemplateIds","incomingReferences","hasMaterials","_findAssignment","alreadyCreated","materialsUpdateData","assignmentName","getAssignmentByID","submissionsType","getStudentAssignmentById","_discardAssignment","_restoreAssignment","_computeRemoteStudentAssignmentFiles","remoteStudentAssignmentFileWithComputedValues","computedAssignmentId","computedClassroomAssetId","remoteStudentAssignmentFilesWithComputedValues","validAssignmentId","validStudentAssignmentId","SELF","submittedAsset","_isFloating","formattedDate","_getFormattedCreatedDateHelper","includeFormattedDate","studentAssignmentFile","isUsingPreferredInterface","isUsingDeprecatedInterface","patchData","assetToPatch","validateAssignmentNameForCreate","_validateAssignmentName","ANY","getClassroomMembership","validateAssignmentNameForUpdate","assignmentList","getAssignmentOrder","getAssignmentFilter","matchingAssignment","_renameAssignment","otherAssignmentData","materialUpdates","_getUpdatedAssignmentMaterials","shouldUpdateTemplates","updatedTemplateIds","shouldUpdateReferences","updatedReferenceIds","_updateAssignmentMetadata","_discardAssets","assetsToDiscard","mappedData","localKey","remoteKey","_getUpdateAssignmentOps","_getAssignmentMaterialsFolderAsset","materialsFolderPath","materialsFolderAsset","_getAssets","_copyAssetsToMaterialsFolder","copyPromises","clonedAssets","dateTimeFormat","year","month","day","hour","minute","fractionalSecondDigits","hourCycle","Intl","DateTimeFormat","_determineAssetDifferences","incomingAssetIds","assetsToCopy","assetsToKeep","templateId","splitIdx","materialsPromises","templateDifferences","referencesToImport","cur","referenceDifferences","importedReferenceAssetIds","importNewReferencesForAssignment","clonedAssetIds","clonedTemplates","clonedReferences","materialsFolder","refreshClassroomCodes","classIds","classroomsToUpdate","successfullyUpdatedClassrooms","classcode","deleteClassrooms","updatedClassroomData","remoteClassroom","cachedClassroom","blockStudentFromClassroom","unblockStudentFromClassroom","removeStudentFromClassroom","removeResponse","removeUserFromPool","removeTeacherFromClassroom","teacherId","getClassroomOrder","getStudentAssignmentOrder","getStudentAssignmentFilter","getStudentAssignmentFileOrder","getStudentAssignmentFileFilter","getClassroomMemberOrder","getClassroomMemberFilter","_getClassroomByIdOrCode","classroomCode","_getAssignmentId","getClassroomBoards","getBoards","getAssignmentBoards","getAssignmentBoard","boardList","_getRealClassroomGivenClassroomIdOrCode","currentClassroomId","classroomIdentifier","migratedClassroom","isVirtualClassroomJustMigrated","createClassroomBoard","currentClassroomAssetId","createBoard","CLASSROOM","shouldCheckForDuplicateName","validateClassroomBoardNameForCreate","validateBoardNameForCreate","validateClassroomBoardNameForUpdate","validateBoardNameForUpdate","weakCache","GetBoardByIdResponse","BoardsInterface","dataToPost","mapPostCreationData","BOARDS_CREATE","useBaseAssetDirectory","shouldCreateDirectlyInBaseAsset","getBoard","BOARDS_COLLECTION","boardDescription","postsToAdd","postsToRemove","postsToUpdate","updateUsers","BOARDS_DISCARD","boardTitle","boardSubTitle","BOARDS_PUBLISH","BOARDS_UNPUBLISH","BoardListLoader","_boardsInterface","observeBoardsFolder","remoteBoards","boardsAssetId","boards","updateBoardInPool","remoteBoard","hasLoadedPosts","updatedBoard","existingBoard","currentBoard","promiseToResolve","errorFromBoardFetch","cachedBoard","_discardBoardFromPool","shouldValidateDirectlyInBaseAsset","_validateBoardName","getBoardFilter","getBoardOrder","processNewPost","_getUserHomeUploadsFolder","uploadsPath","_uploadFileForAssetLinkPost","destinationFolder","fileName","_updateBoardAfterPatchingBoard","updateData","postData","cleanedFileName","maxLength","shouldValidate","cleanedName","replaceAll","cleanAssetName","uploadOptions","uploadedAsset","_cleanBoardName","_validateAndCleanBoardNameBeforeRenamingBoard","cleanedBoardName","shouldUpdateBoardName","isNewBoardDescriptionProvided","sourceBoard","publishedRemoteBoard","updatedLocalSourceBoard","publishedBoardId","publishedBoard","getPostOrder","ImplicitLibraryFilter","TrainingSets","TrainingSet","LibraryListLoader","_libraryPool","ownerFilter","rolesFilter","itemFilter","_decorateLibraryDataWithReferencedByProject","_updateProjectInaccessibleReferences","inaccessibleReferences","total_count","LibrarySearchLoader","LibrarySearchFilter","SubscriptionLocation","ensureExistence","libraryInterface","_setAsset","_create","_setUpWatcher","SyncGroupLocation","BookmarkLocation","CollabBookmarkLocation","PublicBookmarkLocation","__assetPool","_syncGroupLocation","_publicBookmarkLocation","_collabBookmarkLocation","_ensureSubscriptionLocationExistence","_onPublicBookmarksChanged","_onCollabBookmarksChanged","getLibrarySearchSource","ImplicitLibrarySearchFilter","createPersonalLibrary","_getLibraryLocally","updatedLibrary","_isValidURN","tryLocalThenRemote","tryRemoteOnly","getLibraryOrder","getLibraryFilter","_ccLibraries","CloudDriver","cloudDriver","initializationOptions","disableLocalFallthrough","skipConnectingOnInit","disablePreemptiveLibraryLoad","CustomModelLoader","effectiveOrder","createdDateMin","createdDateMax","modifiedDateMin","modifiedDateMax","nextOptions","makeDateRange","getDateString","CustomModelSearchLoader","_customModelContext","customModelOrder","createDateRange","modifyDateRange","ussQuery","itemOrder","sync_created_date","range","sync_updated_date","CustomModelSearchFilter","LegacyCustomModel","_inferenceReady","_publishedState","UNPUBLISHED","_samplePrompt","_baseModelName","_baseModelVersion","LegacyCustomModelUpdater","listOptions","REGION_MAP","VA6C2","VA6","VA7","JPN3","IRL1","originalHref","originalOptions","acpHost","subdomain","regionalizedSubdomain","idString","customModelSearchFilter","LegacyImplicitCustomModelFilter","LegacyCustomModelContext","LegacyCustomModelInterface","_customModelUpdater","getCustomModelOrder","getCustomModelFilter","LegacyCustomModelFilter","customModelSearchSource","LegacyCustomModelSearchFilter","LegacyCustomModelSearchLoader","customModelSource","LegacyCustomModelLoader","trainingSetsSource","TrainingSetFilter","ImplicitCustomModelDashboardFilter","_customModelFilter","customModelFilter","_trainingSetFilter","trainingSetFilter","legacyCustomModelContext","_LegacyCustomModelContext","customModelDashboardSource","updateTrainingSet","customModel","_fetchAndUpdateCustomModelById","getTrainingSetOrder","getTrainingSetFilter","ImplicitGenerationHistoryAssetFilter","$GH_DIR_REF","$GH_FAVORITES_LIST_REF","GenerationHistoryAssetLoader","_loadAssetsFromSupergraph","generationType","assetsPromise","assetsResponse","getDefaultGHAFolder","listings","_fireflyGenerationsDirectoryID","_fireflyGenrationsDirectoryID","generationsDirectory","assetData","GenerationSiblingLoader","_throwIfFailedCollaborators","updateAccessResult","generationHistorySource","GenerationHistorySiblingLoader","remoteHistoryAssetData","historyAsset","generationHistoryUtils","getGenerationHistoryAssetFilter","getGenerationHistoryAssetOrder","getPublicLink","updateRequest","targetPermission","sharingContext","updateAccess","WorkfrontInterface","_getWorkfrontLinkURL","getWorkfrontLink","ordId","_workfrontInterface","getRepository","repositoryInterface","repositoryData","newWorkfrontParentDir","organizationsResource","workfrontURL","setDenyWithDeepOverride","_getPrivileges","ACK","READ","WRITE","setDeny","accessControlContext","getACL","addACES","DENY","removeDeny","findAce","isDeny","removeACES","removeDenyWithDeepOverride","_getResourceGenerationNumber","rgn","convertedRGN","getPrimaryRGN","getRepoMetadataRGN","getAppMetadataRGN","DefaultMinimalAssetLoadOptions","isCuratedCollectionAsset","_minimalAssets","assetProps","getMinimalAssetWithAssetId","_getMinimalAssetById","loadConfig","getMinimalAssetWithRepoPath","_getMinimalAssetWithRepoPathImpl","repositoryMetadata","AdobeACL","_aces","_assetInterface","_forceRefreshACL","_handleConflict","hasDirtyACES","_isDirty","updateACES","dirtyACES","AdobeACE","_privileges","_modifier","_relations","_principal","__isDirty","__isDeleted","_checkIfDeleted","isGrant","GRANT","isDeepInheritance","DEEP","isSelfInheritance","isDeepOverrideInheritance","DEEP_OVERRIDE","isUserPrincipal","PRINCIPAL_TYPE_IMS_USER","isGroupPrincipal","PRINCIPAL_TYPE_IMS_GROUP","_aclCache","_getCachedACL","localACL","aclDeref","assetRepoData","aclResponse","mapACES","isPredefinedPrincipal","_getAdobeAsset","_getPrincipalCollaborators","existingPredefinedPrincipals","patchEntries","postEntries","accessOptions","patchesToRemoveExistingPPs","ppToUpdate","existingPredefinedPrincipal","returnPromise","patchResult","postResult","patchResultMap","postResultMap","assetMetadataProperties","isBrokenAsset","typesWithUnreliableInstanceID","_assetLinkList","_resolutionErrors","brokenAssets","_resolvedAssets","_setLinkData","linkData","_resolveWithRetry","_setLinkedAsset","_getLinkDataForAsset","containerAsset","_serializeLinkData","_resolve","resolvedAssets","resolutionErrors","_manager","alternativeAdobeAsset","linkStatus","instanceID","shouldCheckEtag","assetHasChanged","assetLinkData","hasMetadataChanges","fragmentIdentifier","documentID","getAssetLinkRef","getAssetLinkRefString","getNewAssetLinkRef","getNewAssetLinkRefString","updateWithAsset","updateWithLinkRef","linkRef","updateWithLinkRefString","linkRefString","acceptMetadataChanges","AssetLinkList","_containerAsset","_directlyMonitoredAssetIDs","_refreshLinks","_monitoredAssetIDs","monitoredChangedIDs","normalizedId","addAssetID","removeAssetID","linkReferences","linkReference","fragmentSpecifier","activate","duration","deactivate","updateContainerAsset","assetLinkList","_onListChange","createList","removeList","MIME_TYPE_MAP","SUPPORTED_PNG_MIMETYPES","EXTENSION_MAP","getExtensions","extensionForUnresolvedContentType","getMimeTypes","contentTypeForUnresolvedExtension","canComputeRenditionFromMimeType","placeholderPrefix","backoffIntervals","rapiMaxSingleTransferSize","tlsDiscoveryPortRange","asimovMaxChunkSize","toolkitNames","photoshop","photoshop_swatches","photoshop_brushes","photoshop_gradients","photoshop_patterns","photoshop_styles","photoshop_shapes","photoshop_swatches_prerelease","photoshop_brushes_prerelease","photoshop_gradients_prerelease","photoshop_patterns_prerelease","photoshop_styles_prerelease","photoshop_shapes_prerelease","ElementMimeTypeMap","IMAGE_ELEMENT_TYPE","COLOR_ELEMENT_TYPE","COLOR_THEME_ELEMENT_TYPE","BRUSH_ELEMENT_TYPE","CHARACTER_STYLE_ELEMENT_TYPE","PARAGRAPH_STYLE_ELEMENT_TYPE","FONT_ELEMENT_TYPE","LAYER_STYLE_ELEMENT_TYPE","LOOK_ELEMENT_TYPE","CAPSULE_ELEMENT_TYPE","VIDEO_ELEMENT_TYPE","THREE_D_ELEMENT_TYPE","LIGHT_ELEMENT_TYPE","MATERIAL_ELEMENT_TYPE","PATTERN_ELEMENT_TYPE","TEMPLATE_ELEMENT_TYPE","TEXT_ELEMENT_TYPE","ANIMATION_ELEMENT_TYPE","LIBRARY_TYPE","GRADIENT_ELEMENT_TYPE","COMPONENT_ELEMENT_TYPE","AUDIO_ELEMENT_TYPE","LibraryConstants","MAX_ELEMENTS","MAX_REMOVED_ELEMENTS","MAX_COMPONENT_SIZE","DL_NAMESPACE","VALID_RELATIONS","DEFAULT_GROUP_CLASSIFIER","ELEMENT_ACTIONS","LIBRARY_ACTIONS","DOCUMENT_LIBRARY_ACTION_PRODUCT_MAP","products","ELEMENT_ACTION_PRODUCT_MAP","VECTOR_RENDITION_ELEMENT_TYPES","ANALYTICS_ENABLED","vulcanLibrariesTargetSpecifier","vulcanLibrariesSAPCode","vulcanQueryRequestPayload","apiVersion","MelvilleParamsAsHeaders","HttpStatus","OK","ACCEPTED","NO_CONTENT","MULTIPLE_CHOICES","UNAUTHORIZED","FORBIDDEN","PRECONDITION_FAILED","UNSUPPOERTED_MEDIA_TYPE","IM_A_TEAPOT","INTERNAL_SERVER_ERROR","BAD_GATEWAY","SERVICE_UNAVAILABLE","ABORT_ERROR","placeholderRegexString","placeholderRegex","containsPlaceholderRegex","createPlaceholderId","isPlaceholder","extractPlaceholder","placeholder","createLibraryData","groups","documentationElements","deletable","removedElements","areElementsLoaded","isLibraryLoaded","isWritable","isParentWritable","elementCount","documentationElementCount","removedElementCount","removeType","parseNewLinkSchema","serializeLinkReference","parseLinkReference","ELEMENT_REF_REGEXP","parseLegacyLinkSchema","getAssetAndFragmentIdFromReference","libraryAssetId","_estimateTimeToUploadSortedArray","numBatches","round","LibraryError","codeOrErrorLikeObject","errorLikeObj","errLikeCast","isErrorLike","libraryErrorCode","ConvertErrorCode","RestrictedEventEmitter","_emitter","DANGEROUS","removeAllListeners","setMaxListeners","getMaxListeners","rawListeners","prependListener","prependOnceListener","_loggerInstance","setEventEmitter","eventEmitter","_eventEmitter","SignalType","Configuration","ignoreRenditionGrids","installedApps","processInfo","renditionSize","RENDITION_SIZES","fullRenditionConfig","FULL_RENDITION_CONFIG","BaseError","sleep","time","doReject","DOMException","abortSignalReasons","signalToReasonMap","aborter","give","ConnectionState","collectAll","Driver","_connector","_isConnected","_failedConnectionAttempt","_cachedFetch","_asyncFn","serializedArgs","cachedPromise","newPromise","promiseCache","_loadElementsAbortController","_token","connectionState","_connectionPromise","LOADING","resetAbortController","onConnect","onDisconnect","_isConnectingOrConnected","_attemptToConnect","abortSignal","future","timoutFutureFactory","REJECT","connectionInfo","_handleConnected","currentAbortSignal","_handleDisconnected","getAllLibraries","getRenditionGrids","getAllElements","getElements","getAllDocumentationElements","getDocumentationElements","getAllRemovedElements","getRemovedElements","getAllGroups","getGroups","publishBrand","_brand","unpublishBrand","setRenditionCacheChangeListener","_cb","addWatchedLibrary","removeWatchedLibrary","addLibrariesSyncGroupListener","removeLibrariesSyncGroupListener","operationFactory","Op","driver","getOperationTypes","_operationTypes","constructOperation","actions","readOnly","supportsAction","addAction","getLocalSettings","settings","_localStorage","AsyncOperation","_isComplete","_progress","isComplete","RequestError","isRequestError","requestErrorCode","REQUEST_TIMED_OUT","FULL_LOCAL_DISK_SPACE","_requestErrorCode","setResponse","getRequestError","getRequestErrorFromStatus","getSAMRequestError","AsyncResponse","trailer","_driver","_handleResponse","_location","abortOperation","rawBody","exception_code","newLocation","configData","staging","hostname","EnvironmentEnv","invitation_hostname","teams_hostname","platform_hostname","production","validatesOperation","propertyDescriptor","_actions","Operation","SingleOperation","_actionMappers","PLATFORM","PLATFORM_EDGE","PLATFORM_DISCOVERY_ENDPOINTS","PRIORITY_HEADER","Priority","decodeToken","extractUserDataFromToken","decoded","user_id","clientId","client_id","extractExpiryFromToken","elapsed","created_at","expires_in","parsedUri","getRenditionUrl","populatedUrl","uriTemplates","RapiLinkType","mapManifestToLibraryData","getElementsFromDCXNode","groupsNode","classifier","sourceRef","customData","getCustomDCXData","localizedNames","toolkitId","createdDate","modifiedDate","elementData","isAutoNamed","tags","dependencyIds","createdLocally","createdContext","modifiedLocally","descriptionModifiedLocally","removedLocally","getRepresentationsFromDCXNode","candidate","candidateSize","representation","representationSize","isFullSize","height","width","isPreferredThumbnail","relationship","getRenditionCandidate","setRenditionUrl","getComponentUrl","renditionTemplate","component_id","component","isExternalLink","contentLength","linktype","CC_STORAGE_ID_REGEX","allowedRepresentationCustomData","stubRenditionGridElement","swatches","swatch","hasCCStorageId","libraryResponse","mapResponseToLibraryData","forceReadOnly","injectStubRenditionGridElements","manifest_etag","isLibraryWritable","primaryPermissions","fullPermissions","localized_names","toolkit_id","document_id","document_type","created_date","modified_date","created_by","modified_by","mapResponseToGroupData","elements_count","removed_elements_count","application_metadata","ownerType","publicLinkId","grid","gridGenerationEtag","stubRenditionGridElements","workspace_urn","mapResponseToElementData","elementResponse","is_auto_named","dependency_ids","mapResponseToRepresentationData","mapResponseToGroupMembershipData","groupResponse","groupMembershipResponse","representationResponse","is_full_size","is_external_link","content_length","blockDownloadUrl","mapResponseToTeamData","teamResponse","ownerName","mapElementDataToElementMetadata","extractCustomData","mapSearchResponseToElementData","searchResponse","mapRepresentationDataToRequest","representationData","storage_href","is_preferred_thumbnail","md5","allowedKeys","typedKey","mapElementDataToRequest","clientInfo","resourceRefToPayload","resourceRef","PERMISSION_INHERITANCE_MAP","supportedActionNames","CloudSingleOperation","_createLibraryActionMap","removeLibrary","_removeLibrary","_permanentlyDeleteLibrary","unfollowLibrary","_unfollowLibrary","leaveLibrary","_leaveLibrary","_moveLibrary","originalAction","documentExtractionData","permissionInheritance","includeAppMetadata","includeApplicationMetadata","_patchBrandAppMetadata","driverConfig","newAppMetadata","stripWhitespace","elementRegex","groupRegex","extractElementId","extractElementCollection","elementCollection","extractGroupId","groupId","MoveCopyElementOperation","lastAction","isMove","targetLibrary","actualActions","elementIds","sourceEtag","_doMoveCopyRequest","linkedActions","linkedEtag","CloudMoveCopyElementOperation","sourceLibrary","sourceAssetId","deepCopy","structuredClone","replaceActionPlaceHolders","targetAction","idCache","placeholderReplacers","newAction","replacePlaceholders","sourceActions","targetActions","sourceAction","pathPlaceholderReplacer","groupDataPlaceholderReplacer","representationDataPlaceholderReplacer","placeholderId","getPlaceholderId","actualId","hasReplacedGroups","newGroups","newRepresentations","replacedRepresentations","replaceRepresentation","newRepresentation","actualData","tokenizePlaceholders","requests","tokenMap","removeRepresentationPlaceholderIds","omitUndefined","replaceData","RESPONSE_MAPPERS","updateLibrary","updateElement","restoreElement","removeElement","deleteElement","createGroup","removeGroup","BatchOperation","_baseLibraryOperationPath","getClientInfo","query_params","permanent","groupData","includeElements","include_contents","tokenizedPayload","newActions","isSupportedAction","ContentOperation","_updateElementContent","ParallelOperation","CloudParallelOperation","uploadComponent","stageRepresentationForCommit","parseLink","linkString","hrefMatch","convertToPrimitiveType","strAsNumber","singleMatcher","multiMatcher","decodeComponents","tokens","encodedURI","replaceMap","customDecodeURIComponent","separatorIndex","isArr","strictUriEncode","decodeComponent","splitOnFirst","filterObject","validateArrayFormatSeparator","keysSorter","removeHash","hashStart","queryStart","parseValue","parseNumbers","parseBooleans","arrayFormat","arrayFormatSeparator","formatter","accumulator","isEncodedArray","parserForArrayFormat","shouldFilter","skipNull","skipEmptyString","keyValueSep","encoderForArrayFormat","objectCopy","parseUrl","url_","parseFragmentIdentifier","stringifyUrl","queryFromUrl","parsedQueryFromUrl","queryString","getHash","pick","exclude","exclusionFilter","base64map","crypt","rotl","rotr","endian","randomBytes","bytesToWords","words","wordsToBytes","bytesToHex","hex","hexToBytes","triplet","imod4","cryptModule","charenc","utf8","stringToBytes","bin","unescape","bytesToString","readFloatLE","isSlowBuffer","_isBuffer","FF","_ff","GG","_gg","HH","_hh","II","_ii","aa","bb","cc","dd","_blocksize","_digestsize","md5Module","digestbytes","asBytes","asString","AssetNotificationManager","_onChangeCallback","_changeCallback","_librariesToMonitor","setWatchedLibraries","librariesToMonitor","_syncGroupListener","syncGroupDirectory","_fetchNext","InMemoryStorage","StorageInterface","storageKey","_settings","_storageKey","_storage","_save","_setItem","settingsStr","mapProjectToTeamData","mapGradientToGradientData","defaultElementSort","sortFieldMap","_notificationManager","getLibrary","_getElementsByAssetId","getElementsPage","_getRemovedElementsByAssetId","_getDocumentationElementsByAssetId","getElement","_getElement","userData","_env","_clientId","_analyticsEnabled","analyticsEnabled","_ignoreRenditionGrids","_codeVersion","codeVersion","getConfiguration","configurationData","syncingEnabled","cloudDriverConfig","updateOptions","fetchAccessToken","_clientSecret","_scopes","getLibraryById","getRenditionGrid","elementParams","_getLibrary","manifestPromise","_getManifest","loadProgressively","_getAllElements","enableBrandLifecycleManagement","getProjectByName","getLibrariesList","publishedFilters","personalFilters","publicFilters","pageGenerators","includeApprovedBrandsInLibraries","getApprovedBrandLibraries","generators","finalized","yielded","combineGenerators","fetchAllApprovedBrandPages","_getLibrariesResponseMapper","firstUrl","responseMapper","nextUrl","library_roles_type","fetchAllPages","_getLibrariesURL","getLibrariesPage","fetchOnePage","getPresignedDownloadUrl","blockDownloadResponse","loadVersionHistory","versionList","listStateChange","manifestTemplate","manifestUrl","mapResponseToVersionData","loadVersion","hostContext","collaboratorList","mapResponseToCollaboratorData","followLibrary","folderId","organizationId","invocation_mode","isDone","importLibrary","_file","exportLibrary","brand","publishedAssetId","_operationId","setLibraryChangeListener","setSyncStateListener","removeLibraryChangeListener","removeSyncStateListener","removeFontDataChangeListeners","elementTypes","_getElementsOfTypeByAssetId","_sort","_limit","_signal","getSearchResults","elementSort","library_id","teamData","projectList","getProjectGradient","samProject","urlString","api_key","user_token","getAuthenticatedThumbnailURL","getRenditionPath","_elementId","getRepresentationContent","representationUrl","blockDownloadData","setLocalSetting","getLocalSetting","getInstalledVersion","_appCode","setFontDataChangeListener","melvillePath","headerParamKey","headerParamValue","sendAction","applicationAction","openInCCD","setTracingSpanAttribute","includeAuthHeader","Authorization","_getFetchError","problem_type_message","paramsAsHeaders","copyFile","_destination","_allowOverride","getFileSize","fileType","_fetchLibraryLinks","componentLink","BLOCK_INIT","maxSingleTransferSize","componentUrl","dimensions","FileReader","Image","onload","img","src","readAsDataURL","getImageDimensionsWeb","getImageDimensions","preflightResponse","transferDocument","_initializeBlockUpload","_transferBlocks","_finalizeBlockUpload","uploadResponse","indexResponse","resolveLink","RESOLVE","resolveUrl","linkList","linksList","firstLinkIndex","secondLinkIndex","parseLinks","transferLinks","blockUploads","duplex","finalizeLink","finalizeUrl","templated","finalizeRequest","getLocalDriver","LocalDriver","_requestProcessToUploadData","originalTimeStamp","urlWithoutPort","port","_fetchProcessConnectInfo","restApiToken","restApiPort","app","getTempDir","ignoreLocalSyncEvents","LibraryAbortController","libAbortControllerMap","removeInstance","is_writable","num_elements","num_documentation_elements","num_archived_elements","is_parent_writable","team_id","owner_type","custom_data","storageUsed","storage_used","public_link","locallyManaged","locally_managed","remove_type","mapLibraryDataToRequest","mapGroupDataToRequest","autoName","auto_name","source_ref","sourceModifiedDate","source_modified_date","created_locally","created_context","modified_locally","modifiedContext","modified_context","descriptionModifiedDate","description_modified_date","description_modified_locally","descriptionModifiedBy","description_modified_by","descriptionModifiedContext","description_modified_context","removedDate","removed_date","removed_locally","removedBy","removed_by","removedContext","removed_context","elementRef","element_ref","rep","mapGroupMembershipDataToRequest","groupMembershipData","isChild","mapProjectsResponseToTeamData","projectData","compareVersions","version1","version2","a1","a2","updateGroup","cleanedData","LocalSingleOperation","team_permission_inheritance","LocalParallelOperation","LocalMoveCopyElementOperation","MoveCopyGroupOperation","group_id","newGroupData","wsUrl","isOpen","_listenedEvents","_errorCount","_eventSource","EventSource","Connector","vulcanInterface","vulcanMessage","launchTimeout","VulcanMessage","_timeout","_launchTimeout","_generateListener","_timeoutId","_connectionInfoHandler","getPayload","apiVersionInfo","apiMinVersion","apiMaxVersion","updateRequired","serviceToken","serviceHostname","_launchProcessHandler","_requestConnectionInfo","_launchProcess","launchProcessCallback","getMessageType","launchApp","connectionInfoCallback","isAppRunning","messageTypes","DEFAULT_FETCH_OPTIONS","reconnectOnErrors","reconnectOnNoResponse","connector","_libraryChangeListener","_renditionCacheChangeListener","_lastNotificationPayload","_handleConfigurationMutation","configurationUpdate","_needToReconnect","_handleRenditionCacheMutation","_handleLibraryMutation","responseKeys","libraryIds","libraryResponseEntry","_getLibraryById","_getElementsByLibraryId","_getRemovedElementsByLibraryId","_getDocumentationElementsByLibraryId","_notificationEventSource","_hostname","_cloudParams","cloudParams","NotificationEventSource","getCloudDriver","clientSecret","scopes","_getElementsOfType","_start","elements_only","sectionType","order_by","section","sections","element_types","newBody","optimisticFetch","firstElementsLoad","follow","controllerInstance","removeRenditionCacheChangeListener","configUpdate","updateRenditionCacheConfiguration","renditionSizes","updateConfiguration","appCode","responseBody","shouldReconnect","File","isSystemFontAvailable","fontName","matchFamily","font_name","match_family","is_font_available","getFontData","fontId","font_id","font_data","HybridDriver","_localConnector","_cloudConnector","samDisableOns","_localDriver","localDriver","VulcanInterface","getVulcanInterface","launchAppEx","Vulcan7","Vulcan5","Vulcan","_specifer","_vulcanInterface","addMessageListener","removeMessageListener","dispatchMessage","getTargetSpecifiers","focus","cmdLine","isAppInstalled","getAppPath","getTargetSpecifiersEx","isAppRunningEx","isAppInstalledEx","getAppPathEx","CEPConnector","REQUEST","RESPONSE","INITIALIZE","setPayload","CCDConnector","_wrapHandler","NodeConnector","_processName","UXPConnector","_installedAppsFn","getInstalledApps","getInstalledAppsEx","control","_getCCLibrariesInstall","sapCode","dispatcher","broadcastMessage","isRunning","ccLibrariesInstall","launch","ProgressiveLoader","_results","_getPages","nestedTransaction","getObservableDecorator","bindingKey","mobXRegistry","isDecoratorArgs","Model","_childrenData","_isCommitted","_waitingForCommit","_apiRoot","_commitFuture","_commitResolver","committed","_updateImplementation","_updateChildren","childData","previousPlaceholderId","_ChildClass","upsertItems","currentDataIds","removedItems","removeItems","isCommitted","requiresWrite","requiresCloudDriver","apiRoot","requiresLocalDriver","findMatchingRepresentationData","replaceRepresentationsOnTarget","newChildren","Element","targetData","mapAttributesToArray","customKey","Representation","libraryContents","isDeletedLocally","isCompatibleType","getContentPath","fileNameOrPath","dotIndex","getFileExtension","getValues","_isMetadata","removeValue","isMetadata","setContent","setContentFromPath","_moveFile","setStagedContent","setContentFromURL","getContentURL","getAuthenticatedContentURL","_createChild","_actionDispatch","_removeChild","testExternalLink","clearCachedExternalLink","getCachedExternalLinkError","getExternalLinkDownloadProgress","syncState","getExternalLinkDownloadProgressByKey","_updateActionDispatch","updatedData","filteredRepresentations","sanitizeVersionInput","a1Part","ApplicationAction","_applicationActionData","minVersion","appName","installedVersions","isCompatibleVersionInstalled","invoke","constructActions","codes","currentAction","isRGB","isSRGB","profileName","getData","getStyleName","style","fontStyle","adbeFont","fontFamily","generateNameMap","rgbToHex","colorDataToHexString","font","Published","sourceRefString","_sourceRef","newLinkSchema","legacySourceModified","_sourceModifiedDate","_updateAction","getCombinedId","PublishedModel","_groups","isElement","_lastLocalUpdateDate","_updater","elementUpdater","elementPool","_libraryAssetId","_modifiedDate","_createdDate","instanceId","primaryRepresentation","getPrimaryRepresentation","getReference","getReferenceString","getLegacyReference","_elementRef","getName","getGeneratedName","_autoName","_tags","getDependencies","_dependencyIds","dependencyID","getElementById","setDependencies","_classifier","getOrderInGroup","groupMembership","membership","classifierName","setOrderInGroup","removeExistingGroups","gr","descriptionModified","_descriptionModifiedDate","_descriptionModifiedBy","_descriptionModifiedContext","wasDescriptionModifiedLocally","_descriptionModifiedLocally","_modifiedContext","wasModifiedLocally","_modifiedLocally","_createdContext","wasCreatedLocally","_createdLocally","beginOperation","endOperation","getRepresentationById","createRepresentation","_preserveThumbnail","removeRepresentation","removeAllRepresentations","_customData","getThumbnailURL","getThumbnailPath","getThumbnailContent","supportsVectorThumbnail","getActions","actionId","docProductMap","getOption","docCodes","productMap","isStockAsset","isSupportedElementType","hasStockData","getStockDataForElement","isLicensed","stockData","elementItemUpdaterOptions","getCombinedIdOrPlaceholder","representationsData","ElementUpdater","isInsertAction","isUpdateAction","isRemoveAction","isAggregateAction","VALID_PATH_REGEX","EXPRESSION_REGEX","validatesPath","otherArgs","JSONPath","_handlePathPart","lastPart","parentPath","insert","parentArray","_handleFilterExpression","expression","subAction","insertObject","itemData","updateObject","removeObject","FIFOStringSet","capacity","_capacity","oldestKey","richTypes","cyclesFix","_stack","diffs","isObjArray","objKey","oldValue","newObjKey","areObjects","nestedDiffs","isNewObjArray","ACTION_TYPE_HANDLERS","oldElements","baseData","newElements","el","addedElements","oldElement","newElement","newBaseData","microdiff","removeAction","rebaseAction","Store","_reducer","_isSquelched","_receivedEventDuringSquelchPeriod","_pendingActionSemaphore","_pendingOperationResolvers","_previouslySeenEtags","_pendingActions","_mergeBaseData","newBase","progressiveLoad","mergeElements","baseElements","newElementIds","_baseData","startingState","_currentData","_elementPool","_elementUpdater","_revert","oldData","currentData","isOperationInProgress","_commit","_confirmActionsAtHead","markSubstitutedPlaceholders","isAnyRemoveLibraryAction","_squelchChangeEvents","collapsedActions","_collapseActions","_unsquelchChangeEvents","onCommit","newElementActions","updateElementContentActions","newElementAction","updateElementContentAction","_rebaseCurrentDataAndActions","newCurrentData","rebasedActions","rebasedAction","flat","oldCurrentData","newElementsData","oldElementsData","ElementListLoader","ElementOrderToElementSort","_updatePoolFromPage","_nextPageLinkFromResponse","ImplicitElementFilter","LibraryContents","elementsSource","combinedId","Group","isGroup","_isDeletedLocally","getFilteredChildren","processElement","getLocalizedName","getLocalizedNames","setLocalizedName","getGroupById","_refreshGradient","cacheDefault","serializer","serializerDefault","strategy","strategyDefault","monadic","computedValue","variadic","assemble","SuppressedError","ObjectWithoutPrototypeCache","ErrorKind","SKELETON_TYPE","strategies","isLiteralElement","literal","isArgumentElement","isNumberElement","isDateElement","isTimeElement","isSelectElement","select","isPluralElement","plural","isPoundElement","pound","isTagElement","isNumberSkeleton","isDateTimeSkeleton","dateTime","SPACE_SEPARATOR_REGEX","DATE_TIME_REGEX","parseDateTimeSkeleton","skeleton","era","RangeError","weekday","hour12","timeZoneName","WHITE_SPACE_REGEX","FRACTION_PRECISION_REGEX","SIGNIFICANT_PRECISION_REGEX","INTEGER_WIDTH_REGEX","CONCISE_INTEGER_WIDTH_REGEX","parseSignificantPrecision","roundingPriority","g1","g2","minimumSignificantDigits","maximumSignificantDigits","parseSign","signDisplay","currencySign","parseConciseScientificAndEngineeringStem","stem","notation","minimumIntegerDigits","parseNotationOptions","opt","parseNumberSkeleton","tokens_1","scale","currency","useGrouping","maximumFractionDigits","unit","compactDisplay","currencyDisplay","unitDisplay","parseFloat","roundingMode","g3","g4","g5","minimumFractionDigits","trailingZeroDisplay","signOpts","conciseScientificAndEngineeringOpts","timeData","getDefaultHourSymbolFromLocale","hourCycles","regionTag","languageTag","maximize","SPACE_SEPARATOR_START_REGEX","SPACE_SEPARATOR_END_REGEX","createLocation","hasNativeStartsWith","hasNativeFromCodePoint","hasNativeFromEntries","hasNativeCodePointAt","hasTrimStart","trimStart","hasTrimEnd","isSafeInteger","isFinite","REGEX_SUPPORTS_U_AND_Y","RE","matchIdentifierAtIndex","codePoints","entries_1","flag","IDENTIFIER_PREFIX_RE_1","lastIndex","_isWhiteSpace","_isPatternSyntax","ErrorCode","ignoreTag","requiresOtherClause","shouldParseSkeletons","parseMessage","nestingLevel","parentArgType","expectingCloseTag","isEOF","UNMATCHED_CLOSING_TAG","clonePosition","_isAlpha","parseTag","parseLiteral","bump","startPosition","tagName","parseTagName","bumpSpace","bumpIf","childrenResult","endTagStartPosition","INVALID_TAG","closingTagNameStartPosition","UNCLOSED_TAG","startOffset","parseQuoteResult","tryParseQuote","parseUnquotedResult","tryParseUnquoted","parseLeftAngleResult","tryParseLeftAngleBracket","codepoint","ch","openingBracePosition","EXPECT_ARGUMENT_CLOSING_BRACE","EMPTY_ARGUMENT","parseIdentifierIfPossible","MALFORMED_ARGUMENT","parseArgumentOptions","startingPosition","endOffset","bumpTo","typeStartPosition","argType","typeEndPosition","EXPECT_ARGUMENT_TYPE","styleAndLocation","styleStartPosition","parseSimpleArgStyleIfPossible","EXPECT_ARGUMENT_STYLE","styleLocation","argCloseResult","tryParseArgumentClose","location_1","parseNumberSkeletonFromString","EXPECT_DATE_TIME_SKELETON","dateTimePattern","skeletonCopy","patternPos","patternChar","extraLength","hourLen","dayPeriodLen","hourChar","getBestPattern","parsedOptions","typeEndPosition_1","EXPECT_SELECT_ARGUMENT_OPTIONS","identifierAndLocation","pluralOffset","EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE","tryParseDecimalInteger","INVALID_PLURAL_ARGUMENT_OFFSET_VALUE","optionsResult","tryParsePluralOrSelectOptions","location_2","pluralType","INVALID_ARGUMENT_TYPE","nestedBraces","apostrophePosition","bumpUntil","UNCLOSED_QUOTE_IN_ARGUMENT_STYLE","stringTokens_1","stemAndOptions","options_1","INVALID_NUMBER_SKELETON","expectCloseTag","parsedFirstIdentifier","hasOtherClause","parsedSelectors","selectorLocation","EXPECT_PLURAL_ARGUMENT_SELECTOR","INVALID_PLURAL_ARGUMENT_SELECTOR","DUPLICATE_SELECT_ARGUMENT_SELECTOR","DUPLICATE_PLURAL_ARGUMENT_SELECTOR","EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT","EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT","EXPECT_SELECT_ARGUMENT_SELECTOR","MISSING_OTHER_CLAUSE","expectNumberError","invalidNumberError","sign","hasDigits","decimal","currentOffset","targetOffset","nextCode","pruneLocation","els","SyntaxError","originalMessage","captureLocation","PART_TYPE","FormatError","InvalidValueError","variableId","INVALID_VALUE","InvalidValueTypeError","MissingValueError","isFormatXMLElementFn","formatToParts","locales","formatters","currentPluralValue","els_1","getNumberFormat","getDateTimeFormat","medium","value_1","formatFn","PluralRules","MISSING_INTL_API","rule","getPluralRules","createFastMemoizeCache","IntlErrorCode","IntlMessageFormat","overrideFormats","defaultLocale","formatterCache","pluralRules","resolvedOptions","resolvedLocale","NumberFormat","supportedLocalesOf","getAst","resolveLocale","__parse","parseOpts","c1","c2","mergeConfigs","createDefaultFormatters","memoizedDefaultLocale","Locale","supportedLocales","integer","percent","short","long","IntlError","exception","UnsupportedFormatterError","UNSUPPORTED_FORMATTER","InvalidConfigError","INVALID_CONFIG","MissingDataError","MISSING_DATA","IntlFormatError","FORMAT_ERROR","MessageFormatError","defaultMessage","MissingTranslationError","MISSING_TRANSLATION","filterProps","allowlist","DEFAULT_INTL_CONFIG","messages","timeZone","defaultFormats","fallbackOnEmptyString","onWarn","getNamedFormat","formatType","setTimeZoneInOptions","deepMergeOptions","opts1","opts2","deepMergeFormatsAndSetTimeZone","f1","mfFormats","ListFormat","formatMessage","messageDescriptor","defaultRichTextElements","msgId","getMessageFormat","DATE_TIME_FORMAT_OPTIONS","getFormatter","filteredOptions","timeStyle","dateStyle","formatDate","formatTime","formatDateTimeRange","formatRange","formatDateToParts","formatTimeToParts","DISPLAY_NAMES_OPTONS","formatDisplayName","getDisplayNames","DisplayNames","LIST_FORMAT_OPTIONS","formatList","getListFormat","formatListToParts","richValues_1","serializedValues","generateToken","PLURAL_FORMAT_OPTIONS","formatPlural","RELATIVE_TIME_FORMAT_OPTIONS","formatRelativeTime","getRelativeTimeFormat","RelativeTimeFormat","NUMBER_FORMAT_OPTIONS","formatNumber","formatNumberToParts","createIntl","relativeTime","displayNames","createFormatters","resolvedConfig","verifyConfigMessages","$t","DEFAULT_LOCALE","SUPPORTED_LOCALES","IntlInterface","setLocale","_loadLocaleData","_intl","FontManager","_fontsCache","fontData","_updateFontData","_clearCache","ObservableMap","_map","ModelCache","_Class","registerIndex","updateIndices","_model","_newData","getByIndex","_shouldNotify","idOrModel","upsert","_dataArray","_listener","Orchestrator","changeDriver","_newDriver","initialLibrariesLoad","loadList","_filters","isLoading","_halt","waitForHydrate","indexType","doOperations","onSyncChange","offSyncChange","_s","_lib","_libraryData","hydrate","_missingResolutionTargetsMap","_resolutionProgressMap","_teamsCache","_handleDriverConnect","_handleCloudDriverConnect","_handleLocalDriverConnect","_handleDriverDisconnect","_handleLocalDriverDisconnect","translate","messageId","CCLIBS","mobXCreateAtom","mobXTransaction","_cloudDriver","_fontManager","utils","_bindDriverEvents","_libraryCache","fileSystemCache","_bindLibraryCacheEvents","newDriver","driverConnectResolver","driverConnectPromise","_libraryCacheChangeHandler","fontManager","lib","isTrainingSetLibrary","isTeam","isPersonal","ownershipFilter","isApprovedBrand","isLibraryLoadedByDefault","connected","areLibrariesLoaded","areLibrariesLoading","userQuota","quota","_refreshTeams","enableProjects","refreshTeams","refreshProjects","actionDispatch","lockNewLibraries","libraryCopy","getHybridSearchResults","rex","currentLoadedMatchingElements","previouslyMatchedElementIds","searchWithinLibrary","searchResults","_searchLoader","abortSearch","filteredLibraryId","elementsToLoadPerLibrary","cleared","abortLoadElements","clearElements","elementsToLoad","loadGivenElements","lowerCamelKey","isUpperSnakeCase","backReference","toLowerCamel","getLocale","isSyncingEnabled","enableSyncing","_setSyncEnabledConfig","disableSyncing","halt","_resolveLibrary","idOrAssetId","resolutionKey","resolveLibrary","_resolveElementById","includeRemovedElements","resolveLibraryById","resolveLibraryByAssetId","resolveLibraryWithoutCache","resolveCachedLibraryReference","_getLinkReferenceStatus","resolveLibraryReference","libraryRef","isLocallyManaged","resolveElementReference","resolveElementReferenceToLibrary","resolveCachedElementReference","cachedLibrary","resolveCachedElementReferenceToLibrary","resolveToElement","resolutionTargetKey","includeRemovedKey","_resolveElementReferenceAndNotify","resolveReference","canAccessLocalProcess","getAccessToken","getLibraryByToolkitId","toolkitLibrary","t1","t2","toolkitName","getDefaultLibrary","customDefaultLibrary","disableFallbackDefaultLibrary","defaultLibrary","isOlder","setDefaultLibrary","_setDefaultLibraryMonitor","_disposeDefaultLibraryMonitor","defaultLibraryMonitor","mimeTypeToExtensions","extensionToMimeTypes","getSNISettings","TLS_DISCOVERY_PORT_RANGE","isPlaceholderId","estimateUploadTime","fileList","standard","asimov","fullChunks","remainingChunk","newChunks"],"sourceRoot":""}