balena-sdk
Version:
The Balena JavaScript SDK
3 lines • 632 kB
JavaScript
!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).balenaSdk=e()}(function(){return function n(i,o,a){function s(t,e){if(!o[t]){if(!i[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}r=o[t]={exports:{}},i[t][0].call(r.exports,function(e){return s(i[t][1][e]||e)},r,r.exports,n,i,o,a)}return o[t].exports}for(var l="function"==typeof require&&require,e=0;e<a.length;e++)s(a[e]);return s}({1:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});r.default=function(e,t){let{auth:r,request:n}=e,i=t.apiUrl;async function o(e){e=(await n.send({method:"POST",url:"/auth/totp/verify",baseUrl:i,body:{code:e}})).body;return e}return{isEnabled:async function(){return"not_required"!==await r.get2FAStatus()},isPassed:async function(){return!await r.needs2FA()},getSetupKey:async function(){var e=(await n.send({method:"GET",url:"/auth/totp/setup",baseUrl:i})).body;return e},enable:async e=>{e=await o(e);return await r.setKey(e),e},verify:o,challenge:async function(e){e=await o(e),await r.setKey(e)},disable:async function(e){return e=(await n.send({method:"POST",url:"/auth/totp/disable",baseUrl:i,body:{password:e}})).body,await r.setKey(e),e}}}},{}],2:[function(h,e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=h("tslib");let y=r.__importStar(h("balena-errors")),g=r.__importDefault(h("memoizee"));t.default=function(e,t){let{auth:n,pubsub:i,request:r,pine:o}=e,a=t.apiUrl,s=function(e){return 401===e.statusCode||"BalenaMalformedToken"===e.code?new y.BalenaNotLoggedIn:e};var l=(t,r)=>async function(...e){try{return await r.apply(n,e)}finally{i.publish(t)}};let u=Object.assign(Object.assign({},n),{setKey:l("auth.keyChange",n.setKey),removeKey:l("auth.keyChange",n.removeKey)});l=h("./2fa").default(Object.assign(Object.assign({},e),{auth:u}),t);let c=(0,g.default)(async()=>{var e=(await r.send({method:"GET",url:"/actor/v1/whoami",baseUrl:a})).body;return e},{primitive:!0,promise:!0}),f=async(e=!1)=>{e&&c.clear();try{return await c()}catch(e){throw s(e)}};async function p(e){try{var t=(await r.send({method:"POST",baseUrl:a,url:"/login_",body:{username:e.email,password:String(e.password)},sendToken:!1})).body;return t}catch(e){if(401===e.statusCode)throw new y.BalenaInvalidLoginCredentials;if(429===e.statusCode)throw new y.BalenaTooManyRequests;throw e}}async function d(){var e=await f();if("user"!==e.actorType)throw new Error("The authentication credentials in use are not of a user");return{id:e.actorTypeId,actor:e.id,email:e.email,username:e.username}}return{twoFactor:l,whoami:async function(){try{return await f()}catch(e){if(!(e instanceof y.BalenaNotLoggedIn))throw e}},authenticate:p,login:async function(e){c.clear(),e=await p(e),await u.setKey(e)},loginWithToken:async function(e){return c.clear(),u.setKey(e)},isLoggedIn:async function(){try{return await f(!0),!0}catch(e){if(e instanceof y.BalenaNotLoggedIn||e instanceof y.BalenaExpiredToken)return!1;throw e}},getToken:function(){return u.getKey().catch(function(e){throw s(e)})},getActorId:async function(){return(await f()).id},getUserInfo:d,logout:async function(){return c.clear(),u.removeKey()},register:async function(e){return e=(await r.send({method:"POST",url:"/user/register",baseUrl:a,body:e,sendToken:!1})).body},verifyEmail:async function(e){var t=e.email,e=e.token;return e=(await r.send({method:"POST",url:"/user/v1/verify-email",body:{verificationToken:e,email:t},baseUrl:a,sendToken:!1})).body},requestVerificationEmail:async function(){var e=(await d()).id;await o.patch({resource:"user",id:e,body:{has_been_sent_verification_email:!0}})}}}},{"./2fa":1,"balena-errors":60,memoizee:416,tslib:560}],3:[function(p,e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.fromSharedOptions=t.setSharedOptions=t.getSdk=void 0;var r=p("tslib");let n=p("./util/global-env"),i=(r.__exportStar(p("./types/models"),t),r.__exportStar(p("./types/jwt"),t),r.__exportStar(p("./types/contract"),t),r.__exportStar(p("./types/user-invite"),t),r.__exportStar(p("./types/auth"),t),"BALENA_SDK_SHARED_OPTIONS"),o="BALENA_SDK_HAS_USED_SHARED_OPTIONS",a="BALENA_SDK_HAS_SET_SHARED_OPTIONS",d={auth(){return p("./auth").default},models(){return p("./models")},logs(){return p("./logs").default},settings(){return p("./settings").default}};t.getSdk=function(e){let t,i=Object.assign({apiUrl:"https://api.balena-cloud.com/",builderUrl:"https://builder.balena-cloud.com/",isBrowser:"undefined"!=typeof window&&null!==window,apiVersion:"v7"},e),r=p("./util/sdk-version").default;var e=p("balena-request").getRequest,n=p("balena-auth").default,o=p("./pine").PinejsClient,a=p("balena-errors"),s=p("./util/pubsub").PubSub,l=p("./util/settings-client").loadSettingsClient(i),n=(i.isBrowser||null!=i.dataDirectory||(i.dataDirectory=l.get("dataDirectory")),"apiKey"in i&&delete i.apiKey,new n(i));let u=e(Object.assign(Object.assign({},i),{auth:n}));null!=i.requestLimit&&0<i.requestLimit&&(e=p("p-throttle"),u.send=e({limit:i.requestLimit,interval:null!=(t=i.requestLimitInterval)?t:6e4,strict:!0})(u.send));e=new o({},Object.assign(Object.assign({},i),{auth:n,request:u})),o=new s;let c={},f={settings:l,request:u,auth:n,pine:e,pubsub:o,sdkInstance:c};return Object.keys(d).forEach(function(t){Object.defineProperty(c,t,{enumerable:!0,configurable:!0,get(){var e=d[t]();return delete this[t],this[t]=e(f,i)}})}),Object.defineProperty(c,"interceptors",{get(){return u.interceptors},set(e){return u.interceptors=e}}),Object.defineProperty(c,"utils",{enumerable:!0,configurable:!0,get(){var e=p("./util").mergePineOptions;return{mergePineOptions:e}}}),c.interceptors.push({request(e){let t=e.url;return"string"==typeof t&&0===(t="string"==typeof e.baseUrl?e.baseUrl+t:t).indexOf(i.apiUrl)&&(e.headers["X-Balena-Client"]="balena-sdk/"+r),e}}),i.retryRateLimitedRequests&&c.interceptors.push({async responseError(e){if(!(e instanceof c.errors.BalenaRequestError)||429!==e.statusCode)throw e;var t=e.requestOptions;if(!t.doNotRetry){var r=null==(r=e.responseHeaders)?void 0:r.get("Retry-After"),r=null!=r?parseInt(r,10):void 0;if(null!=r&&Number.isInteger(r)&&!(r<0)){var n,r=1e3*r;if("function"!=typeof i.retryRateLimitedRequests||i.retryRateLimitedRequests(r))return n=p("./util").delay,await n(r),c.request.send(t)}}throw e}}),c.request=u,c.pine=e,c.errors=a,c.version=r,c},t.setSharedOptions=function(e){n.globalEnv[o]&&console.error("Shared SDK options have already been used. You may have a race condition in your code."),n.globalEnv[a]&&console.error("Shared SDK options have already been set. You may have a race condition in your code."),n.globalEnv[i]=e,n.globalEnv[a]=!0};t.fromSharedOptions=function(){var e=n.globalEnv[i];return n.globalEnv[o]=!0,(0,t.getSdk)(e)}},{"./auth":2,"./logs":4,"./models":17,"./pine":27,"./settings":28,"./types/auth":29,"./types/contract":30,"./types/jwt":33,"./types/models":34,"./types/user-invite":35,"./util":47,"./util/global-env":46,"./util/pubsub":49,"./util/sdk-version":51,"./util/settings-client":53,"balena-auth":57,"balena-errors":60,"balena-request":67,"p-throttle":448,tslib:560}],4:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});let s=e("events"),l=e("ndjson");var n=e("./util/global-env");let u=("AbortController"in n.globalEnv?n.globalEnv:e("abortcontroller-polyfill/dist/cjs-ponyfill")).AbortController;r.default=function({request:o,sdkInstance:r},a){return{async subscribe(e,i){if(null!=i&&"start"in i&&null!=i.start&&null==i.count)throw new Error("The count parameter is required when specifying the start parameter");e=await r.models.device.get(e,{$select:"uuid"});{null==i&&(i={});let t=new s.EventEmitter,r=new u,n=(0,l.parse)({strict:!0===a.debug});return o.stream({url:`/device/v2/${e.uuid}/logs`,qs:Object.assign(Object.assign({},i),{stream:1}),baseUrl:a.apiUrl,signal:r.signal}).then(function(e){return e.on("error",e=>{n.emit("error",e)}),n.on("data",function(e){r.signal.aborted||t.emit("line",e)}),n.on("error",function(e){r.signal.aborted||t.emit("error",e)}),e.pipe(n)}).catch(function(e){r.signal.aborted||t.emit("error",e)}),t.unsubscribe=function(){r.abort(),n.destroy()},t}},async history(e,t){return(async(e,t)=>e=(await o.send({url:`/device/v2/${e.uuid}/logs`,qs:null!=t?t:{},baseUrl:a.apiUrl})).body)(await r.models.device.get(e,{$select:"uuid"}),t)}}}},{"./util/global-env":46,"abortcontroller-polyfill/dist/cjs-ponyfill":54,events:178,ndjson:428}],5:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});let s=e("tslib").__importStar(e("balena-errors")),l=e("../util");r.default=function({pine:r,request:i,sdkInstance:n},{apiUrl:o}){let a={async create({name:e,expiryDate:t,description:r=null}){if(void 0===t)throw new s.BalenaInvalidParameterError("createApiKeyParams.expiryDate",t);e={name:e,expiryDate:t};"string"==typeof r&&r&&(e.description=r);try{var n=(await i.send({method:"POST",url:"/api-key/user/full",baseUrl:o,body:e})).body;return n}catch(e){throw new s.BalenaNotLoggedIn}},async getAll(e){return r.get({resource:"api_key",options:(0,l.mergePineOptions)({$orderby:{name:"asc"}},e)})},async getAllNamedUserApiKeys(e){return a.getAll((0,l.mergePineOptions)({$filter:{is_of__actor:await n.auth.getActorId(),name:{$ne:null}}},e))},async getProvisioningApiKeysByApplication(e,t){e=await n.models.application.get(e,{$select:"actor"});return a.getAll((0,l.mergePineOptions)({$filter:{is_of__actor:e.actor.__id}},t))},async getDeviceApiKeysByDevice(e,t){e=(await n.models.device.get(e,{$select:"actor"})).actor;return r.get({resource:"api_key",options:(0,l.mergePineOptions)({$filter:{is_of__actor:e.__id},$orderby:{name:"asc"}},t)})},async update(e,t){if(!t)throw new s.BalenaInvalidParameterError("apiKeyInfo",t);if(null===t.name||""===t.name)throw new s.BalenaInvalidParameterError("apiKeyInfo.name",t.name);await r.patch({resource:"api_key",id:e,body:{name:t.name,description:t.description,expiry_date:t.expiryDate}})},async revoke(e){await r.delete({resource:"api_key",id:e})}};return a}},{"../util":47,"balena-errors":60,tslib:560}],6:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});let s=e("tslib").__importStar(e("balena-errors")),l=e("../util"),u="invitee__is_invited_to__application";r.default=function(e,t,o){let{request:r,pine:a}=e,n=t.apiUrl,i={getAll(e){return a.get({resource:u,options:e})},async getAllByApplication(e,t){e=(await o(e,{$select:"id"})).id;return i.getAll((0,l.mergePineOptions)({$filter:{is_invited_to__application:e}},t))},async create(e,{invitee:t,roleName:r,message:n}){var[{id:e},i]=await Promise.all([o(e,{$select:"id"}),r?a.get({resource:"application_membership_role",options:{$top:1,$select:"id",$filter:{name:r}}}):void 0]),e={is_invited_to__application:e,invitee:t,message:n};if(i){n=null==(t=i[0])?void 0:t.id;if(!n&&r)throw new s.BalenaApplicationMembershipRoleNotFound(r);e.application_membership_role=n}return a.post({resource:u,body:e})},async revoke(e){await a.delete({resource:u,id:e})},async accept(e){try{await r.send({method:"POST",url:"/user/v1/invitation/"+e,baseUrl:n})}catch(e){if(401===e.statusCode)throw new s.BalenaNotLoggedIn;throw e}}};return i}},{"../util":47,"balena-errors":60,tslib:560}],7:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});let n=e("tslib").__importStar(e("balena-errors")),i=e("../util"),l="user_application_membership";r.default=function(e,o){let a=e.pine,s=async e=>{var t=await a.get({resource:"application_membership_role",id:{name:e},options:{$select:"id"}});if(t)return t.id;throw new n.BalenaApplicationMembershipRoleNotFound(e)};return{async get(e,t){if("number"!=typeof e&&"object"!=typeof e)throw new n.BalenaInvalidParameterError("membershipId",e);t=await a.get({resource:l,id:e,options:t});if(null==t)throw new n.BalenaError("Application Membership not found: "+e);return t},async getAllByApplication(e,t){e=(await o(e,{$select:"id"})).id;return a.get({resource:l,options:(0,i.mergePineOptions)({$filter:{is_member_of__application:e}},t)})},async getAllByUser(e,t){if("number"!=typeof e&&"string"!=typeof e)throw new n.BalenaInvalidParameterError("usernameOrId",e);return a.get({resource:l,options:(0,i.mergePineOptions)({$filter:{user:"number"==typeof e?e:{$any:{$alias:"u",$expr:{u:{username:e}}}}}},t)})},async create({application:e,username:t,roleName:r}){var[{id:e,organization:n},i]=await Promise.all([o(e,{$select:"id",$expand:{organization:{$select:"id",$expand:{organization_membership:{$select:"id",$filter:{user:{$any:{$alias:"u",$expr:{u:{username:t}}}}}}}}}}),r?s(r):void 0]);if(0===n[0].organization_membership.length)throw new Error("It is necessary that each user (Auth) that is member of an application that has an organization, is member of the organization");n={username:t,is_member_of__application:e};return r&&(n.application_membership_role=i),a.post({resource:l,body:n})},async changeRole(e,t){t=await s(t);await a.patch({resource:l,id:e,body:{application_membership_role:t}})},async remove(e){await a.delete({resource:l,id:e})}}}},{"../util":47,"balena-errors":60,tslib:560}],8:[function(m,e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=m("tslib");let v=r.__importStar(m("url")),b=r.__importDefault(m("lodash/once")),_=r.__importStar(m("balena-errors")),w=m("../util"),S=m("../util/device-service-details");t.default=function(e,t){let r,{request:i,pine:s,sdkInstance:l}=e,o=t.apiUrl;var n=m("./application-membership").default(e,(...e)=>g.get(...e)),e=m("./application-invite").default(e,t,(...e)=>g.get(...e)),a=m("../util/dependent-resource").buildDependentResource;let u=(0,b.default)(()=>m("../util/request-batching").batchResourceOperationFactory({getAll:g.getAll,NotFoundError:_.BalenaApplicationNotFound,AmbiguousResourceError:_.BalenaAmbiguousApplication,chunkSize:t.requestBatchingChunkSize}));var c=a({pine:s},{resourceName:"application_tag",resourceKeyField:"tag_key",parentResourceName:"application",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for slugOrUuidOrId provided in application tagsModel getResourceId: "+typeof e);e=(await g.get(e,{$select:"id"})).id;return e}}),f=a({pine:s},{resourceName:"application_config_variable",resourceKeyField:"name",parentResourceName:"application",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for slugOrUuidOrId provided in application configVarModel getResourceId: "+typeof e);e=(await g.get(e,{$select:"id"})).id;return e}}),p=a({pine:s},{resourceName:"application_environment_variable",resourceKeyField:"name",parentResourceName:"application",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for slugOrUuidOrId provided in application envVarModel getResourceId: "+typeof e);e=(await g.get(e,{$select:"id"})).id;return e}}),a=a({pine:s},{resourceName:"build_environment_variable",resourceKeyField:"name",parentResourceName:"application",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for slugOrUuidOrId provided in application buildVarModel getResourceId: "+typeof e);e=(await g.get(e,{$select:"id"})).id;return e}});let d=null!=(r=t.dashboardUrl)?r:o.replace(/api/,"dashboard"),h=async e=>(0,w.isId)(e)?e:(e=(await g.get(e,{$select:"id"})).id,e),y={is_directly_accessible_by__user:{$any:{$alias:"dau",$expr:{1:1}}}},g={_getId:h,getDashboardUrl(e){if("number"==typeof e&&Number.isFinite(e))return v.resolve(d,"/apps/"+e);throw new Error("The id option should be a finite number")},async getAll(e,t){return await s.get({resource:"application",options:(0,w.mergePineOptions)(Object.assign(Object.assign({},"directly_accessible"===t&&{$filter:y}),{$orderby:{app_name:"asc"}}),e)})},async getAllDirectlyAccessible(e){return g.getAll(e,"directly_accessible")},async getAllByOrganization(e,t){e=(await l.models.organization.get(e,{$select:"id"})).id;return await s.get({resource:"application",options:(0,w.mergePineOptions)({$filter:{organization:e},$orderby:{app_name:"asc"}},t)})},async get(e,t,r){r="directly_accessible"===r?y:null;let n;if((0,w.isId)(e))n=await s.get({resource:"application",id:e,options:(0,w.mergePineOptions)(null!=r?{$filter:r}:{},t)});else if("string"==typeof e){var i=e.toLowerCase(),r=await s.get({resource:"application",options:(0,w.mergePineOptions)({$filter:Object.assign(Object.assign({},r),{$or:{slug:i,uuid:i}})},t)});if(1<r.length)throw new _.BalenaAmbiguousApplication(e);n=r[0]}if(null==n)throw new _.BalenaApplicationNotFound(e);return n},async getDirectlyAccessible(e,t){return g.get(e,t,"directly_accessible")},async getWithDeviceServiceDetails(e,t){var r={$expand:{owns__device:{$expand:S.getCurrentServiceDetailsPineExpand}}},r=(0,w.mergePineOptions)(r,t),t=await g.get(e,r),e=t.owns__device.map(S.generateCurrentServiceDetails);return t.owns__device=e,t},async getAppByName(e,t,r){r="directly_accessible"===r?y:null,r=await s.get({resource:"application",options:(0,w.mergePineOptions)({$filter:Object.assign(Object.assign({},r),{app_name:e})},t)});if(0===r.length)throw new _.BalenaApplicationNotFound(e);if(1<r.length)throw new _.BalenaAmbiguousApplication(e);var[t]=r;return t},has:async e=>{try{return await g.get(e,{$select:["id"]}),!0}catch(e){if(e instanceof _.BalenaApplicationNotFound)return!1;throw e}},hasAny:async()=>0!==(await g.getAll({$select:["id"]},"directly_accessible")).length,async create({name:e,uuid:t,applicationClass:r,deviceType:n,organization:i}){if(null==i)throw new _.BalenaInvalidParameterError("organization",i);var o=(async()=>(await l.models.deviceType.get(n,{$select:"id"})).id)(),a=s.get({resource:"organization",id:{[(0,w.isId)(i)?"id":"handle"]:i},options:{$select:["id"]}}).then(function(e){if(e)return e.id;throw new _.BalenaOrganizationNotFound(i)}),[o,a]=await Promise.all([o,a]),e={app_name:e,uuid:t,is_for__device_type:o};return a&&(e.organization=a),r&&(e.is_of__class=r),s.post({resource:"application",body:e})},remove:async e=>{var t;"string"==typeof e?(t=(await l.models.application.get(e,{$select:"id"})).id,await s.delete({resource:"application",id:t})):await u()({parameterName:"slugOrUuidOrIdOrIds",uuidOrIdOrArray:e,fn:async e=>{await s.delete({resource:"application",options:{$filter:{id:{$in:e.map(e=>e.id)}}}})}})},rename:async(e,t)=>{e=(await l.models.application.get(e,{$select:"id"})).id;await s.patch({resource:"application",id:e,body:{app_name:t}})},restart:t=>(0,w.withSupervisorLockedError)(async()=>{var e=(await l.models.application.get(t,{$select:"id"})).id;await i.send({method:"POST",url:`/application/${e}/restart`,baseUrl:o})}),generateProvisioningKey:async({slugOrUuidOrId:e,keyExpiryDate:t,keyName:r,keyDescription:n})=>{e=(await l.models.application.get(e,{$select:"id"})).id,e=(await i.send({method:"POST",url:"/api-key/v2/",baseUrl:o,body:{actorType:"application",actorTypeId:e,roles:["provisioning-api-key"],name:r,description:n,expiryDate:t}})).body;return e},purge:e=>(0,w.withSupervisorLockedError)(async()=>{await i.send({method:"POST",url:"/supervisor/v1/purge",baseUrl:o,body:{appId:e,data:{appId:""+e}}})}),shutdown:(e,t)=>(0,w.withSupervisorLockedError)(async()=>{null==t&&(t={}),await i.send({method:"POST",url:"/supervisor/v1/shutdown",baseUrl:o,body:{appId:e,data:{force:Boolean(t.force)}}})}),reboot:(e,t)=>(0,w.withSupervisorLockedError)(async()=>{null==t&&(t={}),await i.send({method:"POST",url:"/supervisor/v1/reboot",baseUrl:o,body:{appId:e,data:{force:Boolean(t.force)}}})}),willTrackNewReleases:async e=>{e=(await g.get(e,{$select:"should_track_latest_release"})).should_track_latest_release;return e},isTrackingLatestRelease:async e=>{var e=await g.get(e,{$select:"should_track_latest_release",$expand:{should_be_running__release:{$select:"id"},owns__release:{$select:"id",$top:1,$filter:{is_final:!0,is_passing_tests:!0,is_invalidated:!1,status:"success"},$orderby:{created_at:"desc"}}}}),t=e.should_be_running__release[0],r=e.owns__release[0];return e.should_track_latest_release&&(!r||(null==t?void 0:t.id)===r.id)},pinToRelease:async(e,t)=>{e=await h(e),t=await l.models.release.get(t,{$select:"id",$top:1,$filter:{belongs_to__application:e,status:"success"}});await s.patch({resource:"application",id:e,body:{should_be_running__release:t.id,should_track_latest_release:!1}})},getTargetReleaseHash:async e=>null==(e=(await g.get(e,{$select:"id",$expand:{should_be_running__release:{$select:"commit"}}})).should_be_running__release[0])?void 0:e.commit,trackLatestRelease:async e=>{var e=await g.get(e,{$select:"id",$expand:{owns__release:{$select:"id",$top:1,$filter:{is_final:!0,is_passing_tests:!0,is_invalidated:!1,status:"success"},$orderby:{created_at:"desc"}}}}),t={should_track_latest_release:!0},r=e.owns__release[0];r&&(t.should_be_running__release=r.id),await s.patch({resource:"application",id:e.id,body:t})},enableDeviceUrls:async e=>{e=(await g.get(e,{$select:"id"})).id;await s.patch({resource:"device",body:{is_web_accessible:!0},options:{$filter:{belongs_to__application:e}}})},disableDeviceUrls:async e=>{e=(await g.get(e,{$select:"id"})).id;await s.patch({resource:"device",body:{is_web_accessible:!1},options:{$filter:{belongs_to__application:e}}})},async grantSupportAccess(e,t){if(null==t||t<=Date.now())throw new _.BalenaInvalidParameterError("expiryTimestamp",t);e=(await l.models.application.get(e,{$select:"id"})).id;await s.patch({resource:"application",id:e,body:{is_accessible_by_support_until__date:t}})},revokeSupportAccess:async e=>{e=(await l.models.application.get(e,{$select:"id"})).id;await s.patch({resource:"application",id:e,body:{is_accessible_by_support_until__date:null}})},tags:{getAllByApplication:c.getAllByParent,set:c.set,remove:c.remove},configVar:{getAllByApplication:f.getAllByParent,get:f.get,set:f.set,remove:f.remove},envVar:{getAllByApplication:p.getAllByParent,get:p.get,set:p.set,remove:p.remove},buildVar:{getAllByApplication:a.getAllByParent,get:a.get,set:a.set,remove:a.remove},membership:n,invite:e};return g}},{"../util":47,"../util/dependent-resource":39,"../util/device-service-details":44,"../util/request-batching":50,"./application-invite":6,"./application-membership":7,"balena-errors":60,"lodash/once":394,tslib:560,url:567}],9:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.aliases=r.BalenaOS=void 0,r.BalenaOS={name:"balenaOS",slug:"balenaos",type:"sw.os",description:"Balena OS",partials:{image:["{{#each deviceType.partials.instructions}}{{{this}}} {{/each}}"],internalFlash:["{{#each deviceType.partials.connectDevice}}{{{this}}} {{/each}}","Write the {{name}} file you downloaded to the {{deviceType.name}}. We recommend using [Etcher](https://etcher.balena.io/).","Wait for writing of {{name}} to complete.","{{#each deviceType.partials.disconnectDevice}}{{{this}}} {{/each}}","{{{deviceType.partials.bootDevice}}} to boot the device."],externalFlash:["{{#each deviceType.partials.instructions}}{{{this}}} {{/each}}","Insert the {{resolveContractAlias deviceType.data.media.altBoot.[0]}} to the host machine.","Write the {{name}} file you downloaded to the {{resolveContractAlias deviceType.data.media.altBoot.[0]}}. We recommend using [Etcher](https://etcher.balena.io/).","Wait for writing of {{name}} to complete.","Remove the {{resolveContractAlias deviceType.data.media.altBoot.[0]}} from the host machine.","Insert the freshly flashed {{resolveContractAlias deviceType.data.media.altBoot.[0]}} into the {{deviceType.name}}.",'<strong role="alert">Warning!</strong> This will also completely erase internal storage medium, so please make a backup first.',"{{#each deviceType.partials.bootDeviceExternal}}{{{this}}} {{/each}}","Wait for the {{deviceType.name}} to finish flashing and shutdown. {{#if deviceType.partials.flashIndicator}}Please wait until {{deviceType.partials.flashIndicator}}.{{/if}}","Remove the {{resolveContractAlias deviceType.data.media.altBoot.[0]}} from the {{deviceType.name}}.","{{#each deviceType.partials.bootDeviceInternal}}{{{this}}} {{/each}}","{{{deviceType.partials.bootDevice}}} to boot the device."],externalBoot:["Insert the {{resolveContractAlias deviceType.data.media.defaultBoot}} to the host machine.","Write the {{name}} file you downloaded to the {{resolveContractAlias deviceType.data.media.defaultBoot}}. We recommend using [Etcher](https://etcher.balena.io/).","Wait for writing of {{name}} to complete.","Remove the {{resolveContractAlias deviceType.data.media.defaultBoot}} from the host machine.","Insert the freshly flashed {{resolveContractAlias deviceType.data.media.defaultBoot}} into the {{deviceType.name}}.","{{{deviceType.partials.bootDevice}}} to boot the device."],jetsonFlash:["To provision {{deviceType.name}}, follow the instructions using our [Jetson Flash tool](https://github.com/balena-os/jetson-flash/blob/master/docs/{{deviceType.slug}}.md) to make the process more streamlined."],usbMassStorage:[`{{#each deviceType.partials.instructions}}{{{this}}}
{{/each}}`],edisonFlash:{Linux:["{{#each deviceType.partials.Linux.flashDependencies}}{{{this}}} {{/each}}","Unplug the {{deviceType.name}} from your system","Unzip the downloaded {{name}} file","{{#each deviceType.partials.Linux.flashInstructions}}{{{this}}} {{/each}}","Plug the {{deviceType.name}} as per the instructions on your terminal.","You can check the progress of the provisioning on your terminal."],MacOS:["{{#each deviceType.partials.MacOS.flashDependencies}}{{{this}}} {{/each}}","Unplug the {{deviceType.name}} from your system","Unzip the downloaded {{name}} file","{{#each deviceType.partials.MacOS.flashInstructions}}{{{this}}} {{/each}}","Plug the {{deviceType.name}} as per the instructions on your terminal.","You can check the progress of the provisioning on your terminal."],Windows:["{{#each deviceType.partials.Windows.flashDependencies}}{{{this}}} {{/each}}","Unplug the {{deviceType.name}} from your system","Unzip the downloaded {{name}} file","{{#each deviceType.partials.Windows.flashInstructions}}{{{this}}} {{/each}}","Plug the {{deviceType.name}} as per the instructions on your terminal.","You can check the progress of the provisioning on your terminal."]}}},r.aliases={sdcard:"SD card",usb_mass_storage:"USB key"}},{}],10:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});let a=e("tslib");r.default=function({request:n,sdkInstance:t},{apiUrl:i,isBrowser:r}){let o=async e=>{e=(await t.models.organization.get(e,{$select:"id"})).id;return e};return{getAccount:async e=>{e=await o(e),e=(await n.send({method:"GET",url:"/billing/v1/account/"+e,baseUrl:i})).body;return e},getPlan:async e=>{e=await o(e),e=(await n.send({method:"GET",url:`/billing/v1/account/${e}/plan`,baseUrl:i})).body;return e},getBillingInfo:async e=>{e=await o(e),e=(await n.send({method:"GET",url:`/billing/v1/account/${e}/info`,baseUrl:i})).body;return e},createSetupIntent:async e=>{var t=e.organization,e=a.__rest(e,["organization"]),t=await o(t),t=(await n.send({method:"POST",url:`/billing/v1/account/${t}/setup-intent`,baseUrl:i,body:e})).body;return t},updateBillingInfo:async(e,t)=>{e=await o(e),e=(await n.send({method:"PATCH",url:`/billing/v1/account/${e}/info`,baseUrl:i,body:t})).body;return e},removeBillingInfo:async e=>{e=await o(e),e=(await n.send({method:"DELETE",url:`/billing/v1/account/${e}/info`,baseUrl:i})).body;return e},updateAccountInfo:async(e,t)=>{e=await o(e);await n.send({method:"PATCH",url:"/billing/v1/account/"+e,baseUrl:i,body:t})},changePlan:async(e,t)=>{var r=t.cycle,t=a.__rest(t,["cycle"]),e=await o(e);await n.send({method:"PATCH",url:`/billing/v1/account/${e}/plan`,baseUrl:i,body:Object.assign({annual:"annual"===r},t)})},getInvoices:async e=>{e=await o(e),e=(await n.send({method:"GET",url:`/billing/v1/account/${e}/invoices`,baseUrl:i})).body;return e},async downloadInvoice(e,t){e=`/billing/v1/account/${await o(e)}/invoices/${t}/download`;return r?(t=(await n.send({method:"GET",url:e,baseUrl:i,responseFormat:"blob"})).body,t):n.stream({method:"GET",url:e,baseUrl:i})}}}},{tslib:560}],11:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});var n=e("tslib");let o=n.__importStar(e("balena-errors")),a=n.__importDefault(e("lodash/union"));r.default=function(e,t){let r=e.request,n=t.apiUrl,i={getAll:async()=>{var e=(await r.send({method:"GET",url:"/config",baseUrl:n,sendToken:!1})).body;return"deviceTypes"in e&&delete e.deviceTypes,e},getDeviceTypes:async()=>{var e=(await r.send({method:"GET",url:"/device-types/v1",baseUrl:n})).body;if(null==e)throw new Error("No device types");return e.map(function(e){return delete e.instructions,e})},getDeviceTypeManifestBySlug:async t=>{var e=(await i.getDeviceTypes()).find(e=>e.name===t||e.slug===t||(null==(e=e.aliases)?void 0:e.includes(t)));if(null==e)throw new o.BalenaInvalidDeviceType(t);return e},getDeviceOptions:async e=>{var e=await i.getDeviceTypeManifestBySlug(e);return(0,a.default)(e.options,null==(e=e.initialization)?void 0:e.options)},getConfigVarSchema:async e=>{e=(await r.send({method:"GET",url:"/config/vars"+("string"==typeof e?"?deviceType="+e:""),baseUrl:n,sendToken:"string"==typeof e})).body;return e}};return i}},{"balena-errors":60,"lodash/union":400,tslib:560}],12:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});let o=e("../util");r.default=function({pine:n,sdkInstance:t}){let i=async e=>{e=(await t.models.organization.get(e,{$select:"id"})).id;return e};return{getAllByOrg:async(e,t)=>{e=await i(e);return await n.get({resource:"credit_bundle",options:(0,o.mergePineOptions)({$filter:{belongs_to__organization:e},$orderby:{created_at:"desc"}},t)})},create:async(e,t,r)=>{e=await i(e);return n.post({resource:"credit_bundle",body:{belongs_to__organization:e,is_for__feature:t,original_quantity:r}})}}}},{"../util":47}],13:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=e("tslib");let o=e("../util"),a=n.__importStar(e("balena-errors")),s=n.__importStar(e("handlebars")),l=n.__importDefault(e("lodash/cloneDeep")),u=e("./balenaos-contract"),c={helpers:{resolveContractAlias:e=>{var t;return null!=(t=u.aliases[e])?t:e}}},f=(e,t,r)=>{let n=Object.assign({},t);for(var i of Object.keys(e)){var o=e[i];if(Array.isArray(o)){let e=n;for(var a of r)e=e[a];e[i]=o.flatMap(e=>s.compile(e)(n,c).split(`
`)).map(e=>e.trim()).filter(e=>e)}else n=f(o,n,r.concat([i]))}return n},p=e=>e.partials?f(e.partials,e,["partials"]):e,d=e=>{var t=null==(t=e.data)?void 0:t.flashProtocol,r=null==(r=null==(r=e.data)?void 0:r.media)?void 0:r.defaultBoot;if(t)return"RPIBOOT"===t?"internalFlash":t;if(r)return"image"===r?"image":"internal"===r?"externalFlash":"externalBoot";throw new a.BalenaError("Unable to determine installation method for contract: "+e.slug)};r.default=function(e){let n=e.pine,i={async get(e,t){if(null==e)throw new a.BalenaInvalidDeviceType(e);let r;if(null==(r="string"==typeof e?(await i.getAll((0,o.mergePineOptions)({$top:1,$filter:{device_type_alias:{$any:{$alias:"dta",$expr:{dta:{is_referenced_by__alias:e}}}}}},t)))[0]:await n.get({resource:"device_type",id:e,options:t})))throw new a.BalenaInvalidDeviceType(e.toString());return r},async getAll(e){return n.get({resource:"device_type",options:(0,o.mergePineOptions)({$orderby:{name:"asc"}},e)})},async getAllSupported(e){return await i.getAll((0,o.mergePineOptions)({$filter:{is_default_for__application:{$any:{$alias:"idfa",$expr:{idfa:{is_host:!0,is_archived:!1,owns__release:{$any:{$alias:"r",$expr:{r:{status:"success",is_final:!0,is_invalidated:!1}}}}}}}}}},e))},getBySlugOrName:async(e,t)=>{var[t]=await i.getAll((0,o.mergePineOptions)({$top:1,$filter:{$or:{name:e,slug:e}}},t));if(null==t)throw new a.BalenaInvalidDeviceType(e);return t},getName:async e=>(await i.getBySlugOrName(e,{$select:"name"})).name,getSlugByName:async e=>(await i.getBySlugOrName(e,{$select:"slug"})).slug,getInterpolatedPartials:async e=>{var t=(await i.getBySlugOrName(e,{$select:"contract"})).contract;if(t)return t=t,p(t);throw new Error("Could not find contract for device type "+e)},getInstructions:async e=>{if(Array.isArray(e))throw new a.BalenaInvalidParameterError("deviceTypeSlugOrContract",e);let t;if("string"==typeof e){var r=(await i.getBySlugOrName(e,{$select:"contract"})).contract;if(null==(t=r)||!t.partials)throw new Error("Instruction partials not defined for "+e)}else t=e;return r=t,e=d(r),r={deviceType:p(r)},null==(r=p(Object.assign(Object.assign({},(0,l.default)(u.BalenaOS)),r)).partials)?void 0:r[e]},getInstallMethod:async e=>{var e=(await i.getBySlugOrName(e,{$select:"contract"})).contract;return e?(e=e,d(e)):null}};return i}},{"../util":47,"./balenaos-contract":9,"balena-errors":60,handlebars:197,"lodash/cloneDeep":373,tslib:560}],14:[function(E,e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.DeviceState=void 0;var r=E("tslib");let O=E("../types/device-overall-status"),x=r.__importStar(E("url")),j=r.__importDefault(E("lodash/once")),A=r.__importStar(E("balena-semver")),P=r.__importStar(E("balena-errors")),k=r.__importDefault(E("memoizee")),I=E("../util"),T=E("../util/device-os-version"),R=E("../util/device-service-details"),$=E("../util/local-mode"),M=E("./device.supervisor-api.partial"),C=E("date-fns/subDays"),L="RESIN_OVERRIDE_LOCK";t.DeviceState=r.__importStar(E("../types/device-state"));t.default=function(e,t){let r,{pine:s,request:i,sdkInstance:f}=e,{apiUrl:a,deviceUrlsBase:n}=t,l=(0,j.default)(()=>E("balena-register-device").getRegisterDevice({request:i}));var o=E("../util/dependent-resource").buildDependentResource;let u=(0,j.default)(()=>E("../util/device-actions/os-update/utils").hupActionHelper),c=(0,j.default)(()=>E("../util/date")),p=(0,j.default)(()=>E("../util/request-batching").batchResourceOperationFactory({getAll:w,NotFoundError:P.BalenaDeviceNotFound,AmbiguousResourceError:P.BalenaAmbiguousDevice,chunkSize:t.requestBatchingChunkSize})),d=(0,j.default)(async()=>{var e=await v();return(0,E("../util/device-actions/os-update").getOsUpdateHelper)(e,i)}),h=o({pine:s},{resourceName:"device_tag",resourceKeyField:"tag_key",parentResourceName:"device",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for uuidOrId provided in device tagsModel getResourceId: "+typeof e);e=(await S.get(e,{$select:"id"})).id;return e}}),y=o({pine:s},{resourceName:"device_config_variable",resourceKeyField:"name",parentResourceName:"device",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for uuidOrId provided in device configVarModel getResourceId: "+typeof e);e=(await S.get(e,{$select:"id"})).id;return e}}),g=o({pine:s},{resourceName:"device_environment_variable",resourceKeyField:"name",parentResourceName:"device",async getResourceId(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("Unexpected type for uuidOrId provided in device envVarModel getResourceId: "+typeof e);e=(await S.get(e,{$select:"id"})).id;return e}}),m=null!=(r=t.dashboardUrl)?r:a.replace(/api/,"dashboard"),v=(0,j.default)(async function(){return null!=n?n:(await f.models.config.getAll()).deviceUrlsBase}),b=async(e,t)=>{await p()({uuidOrIdOrArray:e,fn:async e=>{await s.patch({resource:"device",options:{$filter:{id:{$in:e.map(e=>e.id)}}},body:t})}})},_=(e,t)=>{let r,n;if(null!=e){if(!(e instanceof Date))throw new P.BalenaInvalidParameterError("fromDate",e);r={$ge:e}}if(null!=t){if(!(t instanceof Date))throw new P.BalenaInvalidParameterError("toDate",t);n={$le:t}}return r||n?{created_at:Object.assign(Object.assign({},r),n)}:{}};async function w(e){return s.get({resource:"device",options:(0,I.mergePineOptions)({$orderby:{device_name:"asc"}},e)})}let S=Object.assign(Object.assign({OverallStatus:O.DeviceOverallStatus,getDashboardUrl(e){if("string"!=typeof e||0===e.length)throw new Error("The uuid option should be a non empty string");return x.resolve(m,`/devices/${e}/summary`)},async getAllByApplication(e,t){e=(await f.models.application.get(e,{$select:"id"})).id;return w((0,I.mergePineOptions)({$filter:{belongs_to__application:e}},t))},async getAllByOrganization(e,t){e=(await f.models.organization.get(e,{$select:"id"})).id;return w((0,I.mergePineOptions)({$filter:{belongs_to__application:{$any:{$alias:"bta",$expr:{bta:{organization:e}}}}}},t))},async get(e,t){if(null==e)throw new P.BalenaDeviceNotFound(e);if(""===e)throw new P.BalenaInvalidParameterError("uuidOrId",e);let r;var n=(0,I.isFullUuid)(e);if(n||(0,I.isId)(e))r=await s.get({resource:"device",id:n?{uuid:e}:e,options:t});else{n=await s.get({resource:"device",options:(0,I.mergePineOptions)({$filter:{uuid:{$startswith:e}}},t)});if(1<n.length)throw new P.BalenaAmbiguousDevice(e);r=n[0]}if(null==r)throw new P.BalenaDeviceNotFound(e);return r},async getWithServiceDetails(e,t){e=await S.get(e,(0,I.mergePineOptions)({$expand:R.getCurrentServiceDetailsPineExpand},t));return(0,R.generateCurrentServiceDetails)(e)},async getByName(e,t){t=await w((0,I.mergePineOptions)({$filter:{device_name:e}},t));if(0===t.length)throw new P.BalenaDeviceNotFound(e);return t},getName:async e=>{e=(await S.get(e,{$select:"device_name"})).device_name;return e},getApplicationName:async e=>(await S.get(e,{$select:"id",$expand:{belongs_to__application:{$select:"app_name"}}})).belongs_to__application[0].app_name,has:async e=>{try{return await S.get(e,{$select:["id"]}),!0}catch(e){if(e instanceof P.BalenaDeviceNotFound)return!1;throw e}},isOnline:async e=>{e=(await S.get(e,{$select:"is_online"})).is_online;return e},getLocalIPAddresses:async e=>{var{is_online:t,ip_address:r}=await S.get(e,{$select:["is_online","ip_address"]});if(t)return(null!=r?r:"").split(" ");throw new Error("The device is offline: "+e)},getMACAddresses:async e=>{e=(await S.get(e,{$select:["mac_address"]})).mac_address;return null==e?[]:e.split(" ")},getMetrics:async e=>await S.get(e,{$select:["memory_usage","memory_total","storage_block_device","storage_usage","storage_total","cpu_usage","cpu_temp","cpu_id","is_undervolted"]}),remove:async e=>{await p()({uuidOrIdOrArray:e,fn:async e=>{await s.delete({resource:"device",options:{$filter:{id:{$in:e.map(e=>e.id)}}}})}})},deactivate:async e=>{await b(e,{is_active:!1})},rename:async(e,t)=>{await b(e,{device_name:t})},setNote:async(e,t)=>{await b(e,{note:t})},setCustomLocation:async(e,t)=>{await b(e,{custom_latitude:String(t.latitude),custom_longitude:String(t.longitude)})},unsetCustomLocation:async e=>{await S.setCustomLocation(e,{latitude:"",longitude:""})},move:async(e,r)=>{let n=await f.models.application.get(r,{$select:"id",$expand:{is_for__device_type:{$select:"id",$expand:{is_of__cpu_architecture:{$select:"slug"}}}}}),i=n.is_for__device_type[0].is_of__cpu_architecture[0].slug;await p()({uuidOrIdOrArray:e,options:{$select:"is_of__device_type",$expand:{is_of__device_type:{$select:"is_of__cpu_architecture",$expand:{is_of__cpu_architecture:{$select:"slug"}}}}},groupByNavigationPoperty:"belongs_to__application",fn:async e=>{for(var t of e)if(!f.models.os.isArchitectureCompatibleWith(t.is_of__device_type[0].is_of__cpu_architecture[0].slug,i))throw new P.BalenaInvalidDeviceType("Incompatible application: "+r);await s.patch({resource:"device",options:{$filter:{id:{$in:e.map(e=>e.id)}}},body:{belongs_to__application:n.id}})}})}},(0,M.getSupervisorApiHelper)(e,t)),{getSupervisorTargetState:async(e,t=2)=>{e=(await S.get(e,{$select:"uuid"})).uuid,t=(await i.send({url:`/device/v${t}/${e}/state`,baseUrl:a})).body;return t},getSupervisorTargetStateForApp:async(e,t)=>{e=(await f.models.application.get(e,{$select:"uuid"})).uuid,e=(await i.send({url:`/device/v3/fleet/${e}/state/?releaseUuid=`+(null!=t?t:""),baseUrl:a})).body;return e},generateUniqueKey(){return l().generateUniqueKey()},async register(e,t,r){var n={$select:"id",$expand:{is_for__device_type:{$select:"slug",$expand:{is_of__cpu_architecture:{$select:"slug"}}}}},[{id:e},n,i,o]=await Promise.all([f.auth.getUserInfo(),f.models.application.generateProvisioningKey({slugOrUuidOrId:e,keyExpiryDate:new Date(Date.now()+6e5).toISOString(),keyDescription:"Created by SDK to register a device"}),f.models.application.get(e,n),"string"==typeof r?f.models.deviceType.get(r,{$select:"slug",$expand:{is_of__cpu_architecture:{$select:"slug"}}}):null]);if(null!=o&&!f.models.os.isArchitectureCompatibleWith(o.is_of__cpu_architecture[0].slug,i.is_for__device_type[0].is_of__cpu_architecture[0].slug))throw new P.BalenaInvalidDeviceType("Incompatible device type: "+r);return l().register({userId:e,applicationId:i.id,uuid:t,deviceType:(null!=o?o:i.is_for__device_type[0]).slug,provisioningApiKey:n,apiEndpoint:a})},generateDeviceKey:async(e,t,r,n)=>{e=(await f.models.device.get(e,{$select:"id"})).id,e=(await i.send({method:"POST",url:`/api-key/device/${e}/device-key`,baseUrl:a,body:{name:t,description:r,expiryDate:n}})).body;return e},hasDeviceUrl:async e=>{e=(await S.get(e,{$select:"is_web_accessible"})).is_web_accessible;return e},getDeviceUrl:async e=>{var{is_web_accessible:t,uuid:r}=await S.get(e,{$select:["is_web_accessible","uuid"]});if(t)return`https://${r}.`+await v();throw new Error("Device is not web accessible: "+e)},enableDeviceUrl:async e=>{await b(e,{is_web_accessible:!0})},disableDeviceUrl:async e=>{await b(e,{is_web_accessible:!1})},async enableLocalMode(e){var t=["id",...$.LOCAL_MODE_SUPPORT_PROPERTIES],e=await S.get(e,{$select:t});(0,$.checkLocalModeSupported)(e),await S.configVar.set(e.id,$.LOCAL_MODE_ENV_VAR,"1")},disableLocalMode:e=>S.configVar.set(e,$.LOCAL_MODE_ENV_VAR,"0"),isInLocalMode:async e=>"1"===await S.configVar.get(e,$.LOCAL_MODE_ENV_VAR),getLocalModeSupport:$.getLocalModeSupport,enableLockOverride:e=>y.set(e,L,"1"),disableLockOverride:e=>y.set(e,L,"0"),hasLockOverride:async e=>"1"===await(async(e,t)=>{var t={$expand:{device_config_variable:{$select:"value",$filter:{name:t}},belongs_to__application:{$select:"id",$expand:{application_config_variable:{$select:"value",$filter:{name:t}}}}}},{device_config_variable:[e],belongs_to__application:[{application_config_variable:[t]}]}=await S.get(e,t);return null==(e=null!=e?e:t)?void 0:e.value})(e,L),async getStatus(e){if("string"!=typeof e&&"number"!=typeof e)throw new P.BalenaInvalidParameterError("uuidOrId",e);e=(await S.get(e,{$select:"overall_status"})).overall_status;return e},async getProgress(e){if("string"!=typeof e&&"number"!=typeof e)throw new P.BalenaInvalidParameterError("uuidOrId",e);e=(await S.get(e,{$select:"overall_progress"})).overall_progress;return e},async grantSupportAccess(e,t){if(null==t||t<=Date.now())throw new P.BalenaInvalidParameterError("expiryTimestamp",t);await b(e,{is_accessible_by_support_until__date:t})},revokeSupportAccess:async e=>{await b(e,{is_accessible_by_support_until__date:null})},lastOnline(e){var t,r=e.last_connectivity_event;return r?(t=c().timeSince,e.is_online?`Connected (for ${t(r,!1)})`:t(r)):"Connecting..."},getOsVersion:e=>(0,T.getDeviceOsSemverWithVariant)(e),isTrackingApplicationRelease:async e=>{e=(await S.get(e,{$select:"is_pinned_on__release"})).is_pinned_on__release;return!e},getTargetReleaseHash:async e=>{var e=(await S.get(e,{$select:"id",$expand:{should_be_running__release:{$select:"commit"}}})).should_be_running__release;return null==(e=e[0])?void 0:e.commit},pinToRelease:async(e,r)=>{let n=(0,k.default)(async e=>{var t=(0,I.isId)(r)?"id":"commit";return f.models.release.get(r,{$top:1,$select:"id",$filter:{[t]:r,status:"success",belongs_to__application:e},$orderby:{created_at:"desc"}})},{primitive:!0,promise:!0});await p()({uuidOrIdOrArray:e,groupByNavigationPoperty:"belongs_to__application",fn:async(e,t)=>{t=await n(t);await s.patch({resource:"device",options:{$filter:{id:{$in:e.map(e=>e.id)}}},body:{is_pinned_on__release:t.id}})}})},trackApplicationRelease:async e=>{await b(e,{is_pinned_on__release:null})},setSupervisorRelease:async(e,t)=>{let r=(0,I.isId)(t)?"id":"raw_version",n=(0,k.default)(async e=>{var[e]=await f.models.os.getSupervisorReleasesForCpuArchitecture(e,{$top:1,$select:"id",$filter:{[r]:t}});if(null==e)throw new P.BalenaReleaseNotFound(t);return e},{primitive:!0,promise:!0});await p()({uuidOrIdOrArray:e,options:{$select:["id","supervisor_version","os_version"],$expand:{is_of__device_type:{$select:"is_of__cpu_architecture"}}},fn:async e=>{e.forEach(e=>{(0,T.ensureVersionCompatibility)(e.supervisor_version,M.MIN_SUPERVISOR_MC_API,"supervisor"),(0,T.ensureVersionCompatibility)(e.os_version,"2.12.0","host OS")});e=(0,I.groupByMap)(e,e=>e.is_of__device_type[0].is_of__cpu_architecture.__id);await Promise.all([...e.entries()].map(async([e,t])=>{e=await n(e);await s.patch({resource:"device",options:{$filter:{id:{$in:t.map(e=>e.id)}}},body:{should_be_managed_by__release:e.id}})}))}})},_checkOsUpdateTarget({uuid:e,is_of__device_type:t,is_online:r,os_version:n,os_variant:i},o){if(!e)throw new Error("The uuid of the device is not available");if(!r)throw new Error("The device is offline: "+e);if(!n)throw new Error("The current os version of the device is not available: "+e);t=null==(r=null==t?void 0:t[0])?void 0:r.slug;if(!t)throw new Error("The device type of the device is not available: "+e);if(void 0===i)throw new Error("The os variant of the device is not available: "+e);e=null!=(r=(0,T.getDeviceOsSemverWithVariant)({os_version:n,os_variant:i}))?r:n;u().getHUPActionType(t,e,o)},startOsUpdate:async function(e,i,o={runDetached:!0}){var t;if(!i)throw new P.BalenaInvalidParameterError("targetOsVersion",i);let a=0<(null!=(t=null==(t=A.parse(i))?void 0:t.prerelease.length)?t:0),s=(0,k.default)(async e=>f.models.deviceType.get(e,{$select:"slug"}),{primitive:!0,promise:!0}),l=(0,k.default)(async(e,t)=>f.models.os.getAvailableOsVersions(e,{includeDraft:t}),{primitive:!0,promise:!0}),u=await d(),c={};return await p()({uuidOrIdOrArray:e,options:{$select:["uuid","is_online","os_version","supervisor_version","os_variant"]},groupByNavigationPoperty:"is_of__device_type",fn:async(e,t)=>{var r,n=await s(t);for(r of e)if(S._checkOsUpdateTarget(Object.assign(Object.assign({},r),{is_of__device_type:[n]}),i),!(await l(n.slug,a)).some(e=>0===A.compare(e.raw_version,i)))throw new P.BalenaInvalidParameterError("targetOsVersion",i);await(0,I.limitedMap)(e,async e=>{c[e.uuid]=await u.startOsUpdate(e.uuid,i,!0===o.runDetached?"v2":"v1")})}}),Array.isArray(e)?c:c[e]},tags:{async getAllByApplication(e,t){e=(await f.models.application.get(e,{$select:"id"})).id;return h.getAll((0,I.mergePineOptions)({$filter:{device:{$any:{$alias:"d",$expr:{d:{belongs_to__application:e}}}}}},t))},getAllByDevice:h.getAllByParent,set:h.set,remove:h.remove},configVar:{getAllByDevice:y.getAllByParent,async getAllByApplication(e,t){e=(await f.models.application.get(e,{$select:"id"})).id;return y.getAll((0,I.mergePineOptions)({$filter:{device:{$any:{$alias:"d",$expr:{d:{belongs_to__application:e}}}}},$orderby:{name:"asc"}},t))},get:y.get,set:y.set,remove:y.remove},envVar:{getAllByDevice:g.getAllByParent,async getAllByApplication(e,t){e=(await f.models.application.get(e,{$select:"id"})).id;return g.getAll((0,I.mergePineOptions)({$filter:{device:{$any:{$alias:"d",$expr:{d:{belongs_to__application:e}}}}},$orderby:{name:"asc"}},t))},get:g.get,set:g.set,remove:g.remove},serviceVar:{async getAllByDevice(e,t){e=(await S.get(e,{$select:"id"})).id;return s.get({resource:"device_service_environment_variable",options:(0,I.mergePineOptions)({$filter:{service_install:{$any:{$alias:"si",$expr:{si:{device:e}}}}}},t)})},async getAllByApplication(e,t){e=(await f.models.application.get(e,{$select:"id"})).id;return s.get({resource:"device_service_environment_variable",options:(0,I.mergePineOptions)({$filter:{service_install:{$any:{$alias:"si",$expr:{si:{device:{$any:{$alias:"d",$expr:{d:{belongs_to__application:e}}}}}}}}},$orderby:{name:"asc"}},t)})},async get(e,t,r){var e=(await S.get(e,{$select:"id"})).id,[e]=await s.get({resource:"device_service_environment_variable",options:{$select:"value",$filter:{service_install:{$any:{$alias:"si",$expr:{si:{device:e,installs__service:"number"==typeof t?t:{$any:{$alias:"is",$expr:{is:{service_name:t}}}}}}}},name:r}}});return null==e?void 0:e.value},async set(e,t,r,n){n=String(n);let i;i=(0,I.isId)(e)?e:(0,I.isFullUuid)(e)?{$any:{$alias:"d",$expr:{d:{uuid:e}}}}:(await S.get(e,{$select:"id"})).id;var o=await s.get({resource:"service_install",options:{$select:"id",$filter:{device:i,installs__service:"number"==typeof t?t:{$any:{$alias:"s",$expr:{s:{service_name:t}}}}}}}),[a]=o;if(null==a)throw new P.BalenaServiceNotFound(t);if(1<o.length)throw new P.BalenaAmbiguousDevice(e);await s.upsert({resource:"device_service_environment_variable",id:{service_install:a.id,name:r},body:{value:n}})},async remove(e,t,r){e=(await S.get(e,{$select:"id"})).id;await s.delete({resource:"device_service_environment_variable",options:{$filter:{service_install:{$any:{$alias:"si",$expr:{si:{device:e,installs__service:"number"==typeof t?t:{$any:{$alias:"is",$expr:{is:{service_name:t}}}}}}}},name:r}}})}},history:{async getAllByDevice(e,{fromDate:t=(0,C.subDays)(new Date,7),toDate:r}={},n){let i=_(t,r);if((0,I.isId)(e))i=Object.assign(Object.assign({},i),{tracks__device:e});else{if(!(0,I.isFullUuid)(e))throw new P.BalenaInvalidParameterError("uuidOrId",e);i=Object.assign(Object.assign({},i),{uuid:e})}return s.get({resource:"device_history",options:(0,I.mergePineOptions)({$filter:i},n)})},async getAllByApplication(e,{fromDate:t=(0,C.subDays)(new Date,7),toDate:r}={},n){e=(await f.models.application.get(e,{$select:"id"})).id;return s.get({resource:"device_history",options:(0,I.mergePineOptions)({$filter:Object.assign(Object.assign({},_(t,r)),{belongs_to__application:e})},n)})}}});return S}},{"../types/device-overall-status":31,"../types/device-state":32,"../util":47,"../util/date":38,"../util/dependent-resource":39,"../util/device-actions/os-update":41,"../util/device-actions/os-update/utils":42,"../util/device-os-version":43,"../util/device-service-details":44,"../ut