@oddington/sdk 0.1.68 → 0.1.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ ${suffix}`}function identifyRegistrationError({error,options}){var _a,_b,_c;cons
18
18
  `);const maybeSignature=await resolvedWallet.signMessage(new TextEncoder().encode(message),"utf8");if(!maybeSignature||!(maybeSignature instanceof Uint8Array)){throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value")}signature=maybeSignature}}try{const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message,signature:bytesToBase64URL(signature)},((_m=credentials.options)===null||_m===undefined?undefined:_m.captchaToken)?{gotrue_meta_security:{captcha_token:(_o=credentials.options)===null||_o===undefined?undefined:_o.captchaToken}}:null),xform:_sessionResponse});if(error){throw error}if(!data2||!data2.session||!data2.user){const invalidTokenError=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:invalidTokenError})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers("SIGNED_IN",data2.session)}return this._returnResult({data:Object.assign({},data2),error})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async _exchangeCodeForSession(authCode,options){const hasExplicitFlowId=(options===null||options===undefined?undefined:options.flowId)!=null;const requestedFlowId=hasExplicitFlowId?validatePKCEFlowId(options===null||options===undefined?undefined:options.flowId):isBrowser()?validatePKCEFlowId(parseParametersFromURL(window.location.href)[PKCE_FLOW_ID_PARAM]):null;if(hasExplicitFlowId&&!requestedFlowId){this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",options===null||options===undefined?undefined:options.flowId)}const{verifier:storageItem,flowId}=hasExplicitFlowId&&!requestedFlowId?{verifier:null,flowId:null}:await retrievePKCEVerifier(this.storage,this.storageKey,requestedFlowId);const[codeVerifier,redirectType]=(storageItem!==null&&storageItem!==undefined?storageItem:"").split("/");try{if(!codeVerifier&&this.flowType==="pkce"){throw new AuthPKCECodeVerifierMissingError}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:authCode,code_verifier:codeVerifier},xform:_sessionResponse});await removePKCEVerifier(this.storage,this.storageKey,flowId);if(error){throw error}if(!data2||!data2.session||!data2.user){const invalidTokenError=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:invalidTokenError})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers(redirectType==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",data2.session)}return this._returnResult({data:Object.assign(Object.assign({},data2),{redirectType:redirectType!==null&&redirectType!==undefined?redirectType:null}),error})}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:{user:null,session:null,redirectType:null},error})}throw error}}async signInWithIdToken(credentials){try{const{options,provider,token,access_token,nonce}=credentials;const res=await _request(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider,id_token:token,access_token,nonce,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken}},xform:_sessionResponse});const{data:data2,error}=res;if(error){return this._returnResult({data:{user:null,session:null},error})}else if(!data2||!data2.session||!data2.user){const invalidTokenError=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:invalidTokenError})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers("SIGNED_IN",data2.session)}return this._returnResult({data:data2,error})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async signInWithOtp(credentials){var _a,_b,_c,_d,_f;let flowId=null;try{if("email"in credentials){const{email,options}=credentials;let codeChallenge=null;let codeChallengeMethod=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod()}const{error}=await _request(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email,data:(_a=options===null||options===undefined?undefined:options.data)!==null&&_a!==undefined?_a:{},create_user:(_b=options===null||options===undefined?undefined:options.shouldCreateUser)!==null&&_b!==undefined?_b:true,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken},code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod},redirectTo:this._maybeAppendFlowIdToRedirect(options===null||options===undefined?undefined:options.emailRedirectTo,flowId)});return this._returnResult({data:{user:null,session:null},error})}if("phone"in credentials){const{phone,options}=credentials;const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone,data:(_c=options===null||options===undefined?undefined:options.data)!==null&&_c!==undefined?_c:{},create_user:(_d=options===null||options===undefined?undefined:options.shouldCreateUser)!==null&&_d!==undefined?_d:true,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken},channel:(_f=options===null||options===undefined?undefined:options.channel)!==null&&_f!==undefined?_f:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:data2===null||data2===undefined?undefined:data2.message_id},error})}throw new AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async verifyOtp(params){var _a,_b;try{let redirectTo=undefined;let captchaToken=undefined;if("options"in params){redirectTo=(_a=params.options)===null||_a===undefined?undefined:_a.redirectTo;captchaToken=(_b=params.options)===null||_b===undefined?undefined:_b.captchaToken}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},params),{gotrue_meta_security:{captcha_token:captchaToken}}),redirectTo,xform:_sessionResponse});if(error){throw error}if(!data2){const tokenVerificationError=new Error("An error occurred on token verification.");throw tokenVerificationError}const session=data2.session;const user=data2.user;if(session===null||session===undefined?undefined:session.access_token){await this._saveSession(session);await this._notifyAllSubscribers(params.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",session)}return this._returnResult({data:{user,session},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async signInWithSSO(params){var _a,_b,_c,_d;let flowId=null;try{let codeChallenge=null;let codeChallengeMethod=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod()}const result2=await _request(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in params?{provider_id:params.providerId}:null),"domain"in params?{domain:params.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((_a=params.options)===null||_a===undefined?undefined:_a.redirectTo,flowId)}),((_b=params===null||params===undefined?undefined:params.options)===null||_b===undefined?undefined:_b.captchaToken)?{gotrue_meta_security:{captcha_token:params.options.captchaToken}}:null),{skip_http_redirect:true,code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod}),headers:this.headers,xform:_ssoResponse});if(((_c=result2.data)===null||_c===undefined?undefined:_c.url)&&isBrowser()&&!((_d=params.options)===null||_d===undefined?undefined:_d.skipBrowserRedirect)){window.location.assign(result2.data.url)}return this._returnResult(result2)}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async reauthenticate(){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._reauthenticate()})}return await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError)throw sessionError;if(!session)throw new AuthSessionMissingError;const{error}=await _request(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:session.access_token});return this._returnResult({data:{user:null,session:null},error})})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async resend(credentials){let flowId=null;try{const endpoint=`${this.url}/resend`;if("email"in credentials){const{email,type,options}=credentials;let codeChallenge=null;let codeChallengeMethod=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod()}const{error}=await _request(this.fetch,"POST",endpoint,{headers:this.headers,body:{email,type,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken},code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod},redirectTo:this._maybeAppendFlowIdToRedirect(options===null||options===undefined?undefined:options.emailRedirectTo,flowId)});if(error){await removePKCEVerifier(this.storage,this.storageKey,flowId)}return this._returnResult({data:{user:null,session:null},error})}else if("phone"in credentials){const{phone,type,options}=credentials;const{data:data2,error}=await _request(this.fetch,"POST",endpoint,{headers:this.headers,body:{phone,type,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:data2===null||data2===undefined?undefined:data2.message_id},error})}throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async getSession(){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return this._useSession(async(result2)=>{return result2})})}return await this._useSession(async(result2)=>{return result2})}async _acquireLock(acquireTimeout,fn){this._debug("#_acquireLock","begin",acquireTimeout);try{if(this.lockAcquired){const last=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve();const result2=(async()=>{await last;return await fn()})();this.pendingInLock.push((async()=>{try{await result2}catch(_e){}})());return result2}return await this.lock(`lock:${this.storageKey}`,acquireTimeout,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=true;const result2=fn();this.pendingInLock.push((async()=>{try{await result2}catch(e){}})());await result2;while(this.pendingInLock.length){const waitOn=[...this.pendingInLock];await Promise.all(waitOn);this.pendingInLock.splice(0,waitOn.length)}return await result2}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey);this.lockAcquired=false}})}finally{this._debug("#_acquireLock","end")}}async _useSession(fn){this._debug("#_useSession","begin");try{const result2=await this.__loadSession();return await fn(result2)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin");if(this.lock!=null&&!this.lockAcquired){this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack)}try{let currentSession=null;const maybeSession=await getItemAsync(this.storage,this.storageKey);this._debug("#getSession()","session from storage",maybeSession);if(maybeSession!==null){if(this._isValidSession(maybeSession)){currentSession=maybeSession}else{this._debug("#getSession()","session from storage is not valid");await this._removeSession()}}if(!currentSession){return{data:{session:null},error:null}}const hasExpired=currentSession.expires_at?currentSession.expires_at*1000-Date.now()<EXPIRY_MARGIN_MS:false;this._debug("#__loadSession()",`session has${hasExpired?"":" not"} expired`,"expires_at",currentSession.expires_at);if(!hasExpired){if(this.userStorage){const maybeUser=await getItemAsync(this.userStorage,this.storageKey+"-user");if(maybeUser===null||maybeUser===undefined?undefined:maybeUser.user){currentSession.user=maybeUser.user}else{currentSession.user=userNotAvailableProxy()}}if(this.storage.isServer&&currentSession.user&&!currentSession.user.__isUserNotAvailableProxy){const suppressWarningRef={value:this.suppressGetSessionWarning};currentSession.user=insecureUserWarningProxy(currentSession.user,suppressWarningRef);if(suppressWarningRef.value){this.suppressGetSessionWarning=true}}return{data:{session:currentSession},error:null}}const{data:session,error}=await this._callRefreshToken(currentSession.refresh_token);if(error){const accessTokenStillValid=!!(currentSession.expires_at&&currentSession.expires_at*1000>Date.now());if(accessTokenStillValid){const stillStored=await getItemAsync(this.storage,this.storageKey);if(stillStored&&stillStored.refresh_token===currentSession.refresh_token){return this._returnResult({data:{session:currentSession},error:null})}}return this._returnResult({data:{session:null},error})}return this._returnResult({data:{session},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(jwt){if(jwt){return await this._getUser(jwt)}await this.initializePromise;let result2;if(this.lock!=null){result2=await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._getUser()})}else{result2=await this._getUser()}if(result2.data.user){this.suppressGetSessionWarning=true}return result2}async _getUser(jwt){try{if(jwt){return await _request(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt,xform:_userResponse})}return await this._useSession(async(result2)=>{var _a,_b,_c;const{data:data2,error}=result2;if(error){throw error}if(!((_a=data2.session)===null||_a===undefined?undefined:_a.access_token)&&!this.hasCustomAuthorizationHeader){return{data:{user:null},error:new AuthSessionMissingError}}return await _request(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(_c=(_b=data2.session)===null||_b===undefined?undefined:_b.access_token)!==null&&_c!==undefined?_c:undefined,xform:_userResponse})})}catch(error){if(isAuthError(error)){if(isAuthSessionMissingError(error)){await this._removeSession()}return this._returnResult({data:{user:null},error})}throw error}}async updateUser(attributes,options={}){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._updateUser(attributes,options)})}return await this._updateUser(attributes,options)}async _updateUser(attributes,options={}){let flowId=null;try{return await this._useSession(async(result2)=>{const{data:sessionData,error:sessionError}=result2;if(sessionError){throw sessionError}if(!sessionData.session){throw new AuthSessionMissingError}const session=sessionData.session;let codeChallenge=null;let codeChallengeMethod=null;if(this.flowType==="pkce"&&attributes.email!=null){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod()}const{data:data2,error:userError}=await _request(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(options===null||options===undefined?undefined:options.emailRedirectTo,flowId),body:Object.assign(Object.assign({},attributes),{code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod}),jwt:session.access_token,xform:_userResponse});if(userError){throw userError}session.user=data2.user;await this._saveSession(session);await this._notifyAllSubscribers("USER_UPDATED",session);return this._returnResult({data:{user:session.user},error:null})})}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:{user:null},error})}throw error}}async setSession(currentSession){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._setSession(currentSession)})}return await this._setSession(currentSession)}async _setSession(currentSession){try{if(!currentSession.access_token||!currentSession.refresh_token){throw new AuthSessionMissingError}const timeNow=Date.now()/1000;let expiresAt2=timeNow;let hasExpired=true;let session=null;const{payload}=decodeJWT(currentSession.access_token);if(payload.exp){expiresAt2=payload.exp;hasExpired=expiresAt2<=timeNow}if(hasExpired){const{data:refreshedSession,error}=await this._callRefreshToken(currentSession.refresh_token);if(error){return this._returnResult({data:{user:null,session:null},error})}if(!refreshedSession){return{data:{user:null,session:null},error:null}}session=refreshedSession}else{const{data:data2,error}=await this._getUser(currentSession.access_token);if(error){return this._returnResult({data:{user:null,session:null},error})}session={access_token:currentSession.access_token,refresh_token:currentSession.refresh_token,user:data2.user,token_type:"bearer",expires_in:expiresAt2-timeNow,expires_at:expiresAt2};await this._saveSession(session);await this._notifyAllSubscribers("SIGNED_IN",session)}return this._returnResult({data:{user:session.user,session},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:{session:null,user:null},error})}throw error}}async refreshSession(currentSession){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._refreshSession(currentSession)})}return await this._refreshSession(currentSession)}async _refreshSession(currentSession){try{return await this._useSession(async(result2)=>{var _a;if(!currentSession){const{data:data2,error:error2}=result2;if(error2){throw error2}currentSession=(_a=data2.session)!==null&&_a!==undefined?_a:undefined}if(!(currentSession===null||currentSession===undefined?undefined:currentSession.refresh_token)){throw new AuthSessionMissingError}const{data:session,error}=await this._callRefreshToken(currentSession.refresh_token);if(error){return this._returnResult({data:{user:null,session:null},error})}if(!session){return this._returnResult({data:{user:null,session:null},error:null})}return this._returnResult({data:{user:session.user,session},error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async _getSessionFromURL(params,callbackUrlType){var _a;try{if(!isBrowser())throw new AuthImplicitGrantRedirectError("No browser detected.");if(params.error||params.error_description||params.error_code){throw new AuthImplicitGrantRedirectError(params.error_description||"Error in URL with unspecified error_description",{error:params.error||"unspecified_error",code:params.error_code||"unspecified_code"})}switch(callbackUrlType){case"implicit":if(this.flowType==="pkce"){throw new AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.")}break;case"pkce":if(this.flowType==="implicit"){throw new AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.")}break;default:}if(callbackUrlType==="pkce"){this._debug("#_initialize()","begin","is PKCE flow",true);if(!params.code)throw new AuthPKCEGrantCodeExchangeError("No code detected.");const{data:data3,error:error2}=await this._exchangeCodeForSession(params.code,{flowId:params[PKCE_FLOW_ID_PARAM]});if(error2)throw error2;const url=new URL(window.location.href);url.searchParams.delete("code");url.searchParams.delete(PKCE_FLOW_ID_PARAM);window.history.replaceState(window.history.state,"",url.toString());return{data:{session:data3.session,redirectType:(_a=data3.redirectType)!==null&&_a!==undefined?_a:null},error:null}}const{provider_token,provider_refresh_token,access_token,refresh_token,expires_in,expires_at,token_type}=params;if(!access_token||!expires_in||!refresh_token||!token_type){throw new AuthImplicitGrantRedirectError("No session defined in URL")}const timeNow=Math.round(Date.now()/1000);const expiresIn=parseInt(expires_in);let expiresAt2=timeNow+expiresIn;if(expires_at){expiresAt2=parseInt(expires_at)}const actuallyExpiresIn=expiresAt2-timeNow;if(actuallyExpiresIn*1000<=AUTO_REFRESH_TICK_DURATION_MS){console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`)}const issuedAt=expiresAt2-expiresIn;if(timeNow-issuedAt>=120){console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",issuedAt,expiresAt2,timeNow)}else if(timeNow-issuedAt<0){console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",issuedAt,expiresAt2,timeNow)}const{data:data2,error}=await this._getUser(access_token);if(error)throw error;const session={provider_token,provider_refresh_token,access_token,expires_in:expiresIn,expires_at:expiresAt2,refresh_token,token_type,user:data2.user};window.location.hash="";this._debug("#_getSessionFromURL()","clearing window.location.hash");return this._returnResult({data:{session,redirectType:params.type},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:{session:null,redirectType:null},error})}throw error}}_isImplicitGrantCallback(params){if(typeof this.detectSessionInUrl==="function"){return this.detectSessionInUrl(new URL(window.location.href),params)}return Boolean(params.access_token||params.error||params.error_description||params.error_code)}async _isPKCECallback(params){if(!params.code){return false}const flowId=validatePKCEFlowId(params[PKCE_FLOW_ID_PARAM]);if(flowId&&await getItemAsync(this.storage,pkceVerifierSlotKey(this.storageKey,flowId))){return true}const currentStorageContent=await getItemAsync(this.storage,`${this.storageKey}-code-verifier`);return!!currentStorageContent}async signOut(options={scope:"global"}){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._signOut(options)})}return await this._signOut(options)}async _signOut({scope}={scope:"global"}){return await this._useSession(async(result2)=>{var _a;const removeCurrentSession=async()=>{await this._removeSession()};const{data:data2,error:sessionError}=result2;if(sessionError&&!isAuthSessionMissingError(sessionError)){return this._returnResult({error:sessionError})}const accessToken=(_a=data2.session)===null||_a===undefined?undefined:_a.access_token;if(accessToken){const{error}=await this.admin.signOut(accessToken,scope);if(error){if(!(isAuthApiError(error)&&(error.status===404||error.status===401||error.status===403)||isAuthSessionMissingError(error))){if(scope!=="others"){await removeCurrentSession()}return this._returnResult({error})}}}if(scope!=="others"){await removeCurrentSession()}return this._returnResult({error:null})})}onAuthStateChange(callback){const id3=generateCallbackId();const subscription={id:id3,callback,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",id3);this.stateChangeEmitters.delete(id3)}};this._debug("#onAuthStateChange()","registered callback with id",id3);this.stateChangeEmitters.set(id3,subscription);(async()=>{await this.initializePromise;if(this.lock!=null){await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(id3)})}else{await this._emitInitialSession(id3)}})();return{data:{subscription}}}async _emitInitialSession(id3){return await this._useSession(async(result2)=>{var _a,_b;try{const{data:{session},error}=result2;if(error)throw error;await((_a=this.stateChangeEmitters.get(id3))===null||_a===undefined?undefined:_a.callback("INITIAL_SESSION",session));this._debug("INITIAL_SESSION","callback id",id3,"session",session)}catch(err){await((_b=this.stateChangeEmitters.get(id3))===null||_b===undefined?undefined:_b.callback("INITIAL_SESSION",null));this._debug("INITIAL_SESSION","callback id",id3,"error",err);if(isAuthRefreshDiscardedError(err)){return}if(isAuthSessionMissingError(err)||isAuthRetryableFetchError(err)||isAuthApiError(err)&&(err.code==="refresh_token_not_found"||err.code==="refresh_token_already_used"||err.code==="session_expired")){console.warn(err)}else{console.error(err)}}})}async resetPasswordForEmail(email,options={}){let codeChallenge=null;let codeChallengeMethod=null;let flowId=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod(true)}try{return await _request(this.fetch,"POST",`${this.url}/recover`,{body:{email,code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod,gotrue_meta_security:{captcha_token:options.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(options.redirectTo,flowId)})}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async getUserIdentities(){var _a;try{const{data:data2,error}=await this.getUser();if(error)throw error;return this._returnResult({data:{identities:(_a=data2.user.identities)!==null&&_a!==undefined?_a:[]},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async linkIdentity(credentials){if("token"in credentials){return this.linkIdentityIdToken(credentials)}return this.linkIdentityOAuth(credentials)}async linkIdentityOAuth(credentials){var _a;let flowId=null;try{const{data:data2,error}=await this._useSession(async(result2)=>{var _a2,_b,_c,_d,_f;const{data:data3,error:error2}=result2;if(error2)throw error2;const{url,flowId:urlFlowId}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,credentials.provider,{redirectTo:(_a2=credentials.options)===null||_a2===undefined?undefined:_a2.redirectTo,scopes:(_b=credentials.options)===null||_b===undefined?undefined:_b.scopes,queryParams:(_c=credentials.options)===null||_c===undefined?undefined:_c.queryParams,skipBrowserRedirect:true});flowId=urlFlowId;return await _request(this.fetch,"GET",url,{headers:this.headers,jwt:(_f=(_d=data3.session)===null||_d===undefined?undefined:_d.access_token)!==null&&_f!==undefined?_f:undefined})});if(error)throw error;if(isBrowser()&&!((_a=credentials.options)===null||_a===undefined?undefined:_a.skipBrowserRedirect)){window.location.assign(data2===null||data2===undefined?undefined:data2.url)}return this._returnResult({data:{provider:credentials.provider,url:data2===null||data2===undefined?undefined:data2.url,flowId},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:{provider:credentials.provider,url:null,flowId},error})}throw error}}async linkIdentityIdToken(credentials){return await this._useSession(async(result2)=>{var _a;try{const{error:sessionError,data:{session}}=result2;if(sessionError)throw sessionError;const{options,provider,token,access_token,nonce}=credentials;const res=await _request(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(_a=session===null||session===undefined?undefined:session.access_token)!==null&&_a!==undefined?_a:undefined,body:{provider,id_token:token,access_token,nonce,link_identity:true,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken}},xform:_sessionResponse});const{data:data2,error}=res;if(error){return this._returnResult({data:{user:null,session:null},error})}else if(!data2||!data2.session||!data2.user){return this._returnResult({data:{user:null,session:null},error:new AuthInvalidTokenResponseError})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers("USER_UPDATED",data2.session)}return this._returnResult({data:data2,error})}catch(error){await removePKCEVerifier(this.storage,this.storageKey,null);if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}})}async unlinkIdentity(identity){try{return await this._useSession(async(result2)=>{var _a,_b;const{data:data2,error}=result2;if(error){throw error}return await _request(this.fetch,"DELETE",`${this.url}/user/identities/${identity.identity_id}`,{headers:this.headers,jwt:(_b=(_a=data2.session)===null||_a===undefined?undefined:_a.access_token)!==null&&_b!==undefined?_b:undefined})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _refreshAccessToken(refreshToken){const debugName=`#_refreshAccessToken()`;this._debug(debugName,"begin");try{const startedAt=Date.now();return await retryable(async(attempt)=>{if(attempt>0){await sleep(200*Math.pow(2,attempt-1))}this._debug(debugName,"refreshing attempt",attempt);return await _request(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:refreshToken},headers:this.headers,xform:_sessionResponse})},(attempt,error)=>{const nextBackOffInterval=200*Math.pow(2,attempt);return error&&isAuthRetryableFetchError(error)&&Date.now()+nextBackOffInterval-startedAt<AUTO_REFRESH_TICK_DURATION_MS})}catch(error){this._debug(debugName,"error",error);if(isAuthError(error)){return this._returnResult({data:{session:null,user:null},error})}throw error}finally{this._debug(debugName,"end")}}_isValidSession(maybeSession){const isValidSession=typeof maybeSession==="object"&&maybeSession!==null&&"access_token"in maybeSession&&"refresh_token"in maybeSession&&"expires_at"in maybeSession;return isValidSession}async _handleProviderSignIn(provider,options){const{url,flowId}=await this._getUrlForProvider(`${this.url}/authorize`,provider,{redirectTo:options.redirectTo,scopes:options.scopes,queryParams:options.queryParams});this._debug("#_handleProviderSignIn()","provider",provider,"options",options,"url",url);if(isBrowser()&&!options.skipBrowserRedirect){window.location.assign(url)}return{data:{provider,url,flowId},error:null}}async _recoverAndRefresh(){var _a,_b;const debugName="#_recoverAndRefresh()";this._debug(debugName,"begin");try{const currentSession=await getItemAsync(this.storage,this.storageKey);if(currentSession&&this.userStorage){let maybeUser=await getItemAsync(this.userStorage,this.storageKey+"-user");if(!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!maybeUser){maybeUser={user:currentSession.user};await setItemAsync(this.userStorage,this.storageKey+"-user",maybeUser)}currentSession.user=(_a=maybeUser===null||maybeUser===undefined?undefined:maybeUser.user)!==null&&_a!==undefined?_a:userNotAvailableProxy()}else if(currentSession&&!currentSession.user){if(!currentSession.user){const separateUser=await getItemAsync(this.storage,this.storageKey+"-user");if(separateUser&&(separateUser===null||separateUser===undefined?undefined:separateUser.user)){currentSession.user=separateUser.user;await removeItemAsync(this.storage,this.storageKey+"-user");await setItemAsync(this.storage,this.storageKey,currentSession)}else{currentSession.user=userNotAvailableProxy()}}}this._debug(debugName,"session from storage",currentSession);if(!this._isValidSession(currentSession)){this._debug(debugName,"session is not valid");if(currentSession!==null){await this._removeSession()}return}const expiresWithMargin=((_b=currentSession.expires_at)!==null&&_b!==undefined?_b:Infinity)*1000-Date.now()<EXPIRY_MARGIN_MS;this._debug(debugName,`session has${expiresWithMargin?"":" not"} expired with margin of ${EXPIRY_MARGIN_MS}s`);if(expiresWithMargin){if(this.autoRefreshToken&&currentSession.refresh_token){const{error}=await this._callRefreshToken(currentSession.refresh_token);if(error){if(isAuthRefreshDiscardedError(error)){this._debug(debugName,"refresh discarded by commit guard",error)}else{this._debug(debugName,"refresh failed",error)}}}}else if(currentSession.user&&currentSession.user.__isUserNotAvailableProxy===true){try{const{data:data2,error:userError}=await this._getUser(currentSession.access_token);if(!userError&&(data2===null||data2===undefined?undefined:data2.user)){currentSession.user=data2.user;await this._saveSession(currentSession);await this._notifyAllSubscribers("SIGNED_IN",currentSession)}else{this._debug(debugName,"could not get user data, skipping SIGNED_IN notification")}}catch(getUserError){console.error("Error getting user data:",getUserError);this._debug(debugName,"error getting user data, skipping SIGNED_IN notification",getUserError)}}else{await this._notifyAllSubscribers("SIGNED_IN",currentSession)}}catch(err){this._debug(debugName,"error",err);if(isAuthRetryableFetchError(err)){console.warn(err)}else{console.error(err)}return}finally{this._debug(debugName,"end")}}async _callRefreshToken(refreshToken){var _a,_b;if(!refreshToken){throw new AuthSessionMissingError}if(this.refreshingDeferred){return this.refreshingDeferred.promise}if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===refreshToken&&Date.now()<this.lastRefreshFailure.expiresAt){this._debug("#_callRefreshToken()","returning cached failure (cooldown active)");return this.lastRefreshFailure.result}const debugName=`#_callRefreshToken()`;this._debug(debugName,"begin");try{this.refreshingDeferred=new Deferred;this.refreshingDeferred.promise.then(undefined,()=>{});const storedAtStart=await getItemAsync(this.storage,this.storageKey);const{data:data2,error}=await this._refreshAccessToken(refreshToken);if(error)throw error;if(!data2.session)throw new AuthSessionMissingError;const storedAfter=await getItemAsync(this.storage,this.storageKey);const storageChangedUnderUs=storedAtStart!==null&&(storedAfter===null||storedAfter.refresh_token!==storedAtStart.refresh_token);if(storageChangedUnderUs){this._debug(debugName,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:storedAfter?"replaced":"cleared"});const discarded={data:null,error:new AuthRefreshDiscardedError};this.refreshingDeferred.resolve(discarded);return discarded}const epochBeforeSave=this._sessionRemovalEpoch;await this._saveSession(data2.session);if(this._sessionRemovalEpoch!==epochBeforeSave){this._debug(debugName,"commit guard (post-save): _removeSession ran during _saveSession, undoing write");await removeItemAsync(this.storage,this.storageKey);if(this.userStorage){await removeItemAsync(this.userStorage,this.storageKey+"-user")}const discarded={data:null,error:new AuthRefreshDiscardedError};this.refreshingDeferred.resolve(discarded);return discarded}await this._notifyAllSubscribers("TOKEN_REFRESHED",data2.session);const result2={data:data2.session,error:null};this.lastRefreshFailure=null;this.refreshingDeferred.resolve(result2);return result2}catch(error){this._debug(debugName,"error",error);if(isAuthError(error)){const result2={data:null,error};if(!isAuthRetryableFetchError(error)){const storedNow=await getItemAsync(this.storage,this.storageKey);const accessTokenStillValid=!!((storedNow===null||storedNow===undefined?undefined:storedNow.expires_at)&&storedNow.expires_at*1000>Date.now());if(accessTokenStillValid){this._debug(debugName,"proactive refresh failed, access token still valid — preserving session")}else{await this._removeSession()}}this.lastRefreshFailure={refreshToken,result:result2,expiresAt:Date.now()+REFRESH_FAILURE_COOLDOWN_MS};(_a=this.refreshingDeferred)===null||_a===undefined||_a.resolve(result2);return result2}(_b=this.refreshingDeferred)===null||_b===undefined||_b.reject(error);throw error}finally{this.refreshingDeferred=null;this._debug(debugName,"end")}}async _notifyAllSubscribers(event,session,broadcast=true){if(this._pendingInitNotifications!==null&&broadcast){this._pendingInitNotifications.push({event,session,broadcast});return}const debugName=`#_notifyAllSubscribers(${event})`;this._debug(debugName,"begin",session,`broadcast = ${broadcast}`);try{if(this.broadcastChannel&&broadcast){this.broadcastChannel.postMessage({event,session})}const errors=[];const promises=Array.from(this.stateChangeEmitters.values()).map(async(x)=>{try{await x.callback(event,session)}catch(e){errors.push(e)}});await Promise.all(promises);if(errors.length>0){for(let i=0;i<errors.length;i+=1){console.error(errors[i])}throw errors[0]}}finally{this._debug(debugName,"end")}}async _saveSession(session){this._debug("#_saveSession()",session);this.suppressGetSessionWarning=true;const sessionToProcess=Object.assign({},session);const userIsProxy=sessionToProcess.user&&sessionToProcess.user.__isUserNotAvailableProxy===true;if(this.userStorage){if(!userIsProxy&&sessionToProcess.user){await setItemAsync(this.userStorage,this.storageKey+"-user",{user:sessionToProcess.user})}else if(userIsProxy){}const mainSessionData=Object.assign({},sessionToProcess);delete mainSessionData.user;const clonedMainSessionData=deepClone(mainSessionData);await setItemAsync(this.storage,this.storageKey,clonedMainSessionData)}else{const clonedSession=deepClone(sessionToProcess);await setItemAsync(this.storage,this.storageKey,clonedSession)}}async _removeSession(){this._sessionRemovalEpoch+=1;this._debug("#_removeSession()");this.lastRefreshFailure=null;this.suppressGetSessionWarning=false;await removeItemAsync(this.storage,this.storageKey);await removeAllPKCEVerifiers(this.storage,this.storageKey);await removeItemAsync(this.storage,this.storageKey+"-user");if(this.userStorage){await removeItemAsync(this.userStorage,this.storageKey+"-user")}await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const callback=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{if(callback&&isBrowser()&&(window===null||window===undefined?undefined:window.removeEventListener)){window.removeEventListener("visibilitychange",callback)}}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh();this._debug("#_startAutoRefresh()");const ticker=setInterval(()=>this._autoRefreshTokenTick(),AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=ticker;if(ticker&&typeof ticker==="object"&&typeof ticker.unref==="function"){ticker.unref()}else if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer==="function"){Deno.unrefTimer(ticker)}const timeout=setTimeout(async()=>{await this.initializePromise;await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=timeout;if(timeout&&typeof timeout==="object"&&typeof timeout.unref==="function"){timeout.unref()}else if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer==="function"){Deno.unrefTimer(timeout)}}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const ticker=this.autoRefreshTicker;this.autoRefreshTicker=null;if(ticker){clearInterval(ticker)}const timeout=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null;if(timeout){clearTimeout(timeout)}}async startAutoRefresh(){this._removeVisibilityChangedCallback();await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback();await this._stopAutoRefresh()}async dispose(){var _a;this._removeVisibilityChangedCallback();await this._stopAutoRefresh();(_a=this.broadcastChannel)===null||_a===undefined||_a.close();this.broadcastChannel=null;this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");if(this.lock!=null){try{await this._acquireLock(0,async()=>{try{const now=Date.now();try{return await this._useSession(async(result2)=>{const{data:{session}}=result2;if(!session||!session.refresh_token||!session.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const expiresInTicks=Math.floor((session.expires_at*1000-now)/AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);if(expiresInTicks<=AUTO_REFRESH_TICK_THRESHOLD){await this._callRefreshToken(session.refresh_token)}})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof LockAcquireTimeoutError){this._debug("auto refresh token tick lock not available")}else{throw e}}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const now=Date.now();try{await this._useSession(async(result2)=>{const{data:{session}}=result2;if(!session||!session.refresh_token||!session.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const expiresInTicks=Math.floor((session.expires_at*1000-now)/AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);if(expiresInTicks<=AUTO_REFRESH_TICK_THRESHOLD){await this._callRefreshToken(session.refresh_token)}})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){this._debug("#_handleVisibilityChange()");if(!isBrowser()||!(window===null||window===undefined?undefined:window.addEventListener)){if(this.autoRefreshToken){this.startAutoRefresh()}return false}try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(false)}catch(error){this._debug("#visibilityChangedCallback","error",error)}};window===null||window===undefined||window.addEventListener("visibilitychange",this.visibilityChangedCallback);await this._onVisibilityChanged(true)}catch(error){console.error("_handleVisibilityChange",error)}}async _onVisibilityChanged(calledFromInitialize){const methodName=`#_onVisibilityChanged(${calledFromInitialize})`;this._debug(methodName,"visibilityState",document.visibilityState);if(document.visibilityState==="visible"){if(this.autoRefreshToken){this._startAutoRefresh()}if(!calledFromInitialize){await this.initializePromise;if(this.lock!=null){await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(methodName,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()})}else{if(document.visibilityState!=="visible"){this._debug(methodName,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}}else if(document.visibilityState==="hidden"){if(this.autoRefreshToken){this._stopAutoRefresh()}}}async _getUrlForProvider(url,provider,options){let redirectTo=options===null||options===undefined?undefined:options.redirectTo;let codeChallenge=null;let codeChallengeMethod=null;let flowId=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod();redirectTo=this._maybeAppendFlowIdToRedirect(redirectTo,flowId)}const urlParams=[`provider=${encodeURIComponent(provider)}`];if(redirectTo){urlParams.push(`redirect_to=${encodeURIComponent(redirectTo)}`)}if(options===null||options===undefined?undefined:options.scopes){urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`)}if(codeChallenge!=null&&codeChallengeMethod!=null){const flowParams=new URLSearchParams({code_challenge:`${encodeURIComponent(codeChallenge)}`,code_challenge_method:`${encodeURIComponent(codeChallengeMethod)}`});urlParams.push(flowParams.toString())}if(options===null||options===undefined?undefined:options.queryParams){const query=new URLSearchParams(options.queryParams);urlParams.push(query.toString())}if(options===null||options===undefined?undefined:options.skipBrowserRedirect){urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`)}return{url:`${url}?${urlParams.join("&")}`,flowId}}_maybeAppendFlowIdToRedirect(redirectTo,flowId){if(!redirectTo||!flowId||!this.experimental.appendPkceFlowIdToRedirects){return redirectTo!==null&&redirectTo!==undefined?redirectTo:undefined}return appendFlowIdToRedirectTo(redirectTo,flowId)}async _getCodeChallengeAndMethod(isPasswordRecovery=false){return getCodeChallengeAndMethod(this.storage,this.storageKey,isPasswordRecovery,(evictedFlowId)=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",evictedFlowId))}async _unenroll(params){try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}return await _request(this.fetch,"DELETE",`${this.url}/factors/${params.factorId}`,{headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _enroll(params){try{return await this._useSession(async(result2)=>{var _a,_b;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const body=Object.assign({friendly_name:params.friendlyName,factor_type:params.factorType},params.factorType==="phone"?{phone:params.phone}:params.factorType==="totp"?{issuer:params.issuer}:{});const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors`,{body,headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}if(params.factorType==="totp"&&data2.type==="totp"&&((_b=data2===null||data2===undefined?undefined:data2.totp)===null||_b===undefined?undefined:_b.qr_code)){data2.totp.qr_code=`data:image/svg+xml;utf-8,${data2.totp.qr_code}`}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _verify(params){const run=async()=>{try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const body=Object.assign({challenge_id:params.challengeId},"webauthn"in params?{webauthn:Object.assign(Object.assign({},params.webauthn),{credential_response:params.webauthn.type==="create"?serializeCredentialCreationResponse(params.webauthn.credential_response):serializeCredentialRequestResponse(params.webauthn.credential_response)})}:{code:params.code});const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors/${params.factorId}/verify`,{body,headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1000)+data2.expires_in},data2));await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",data2);return this._returnResult({data:data2,error})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}};if(this.lock!=null){return this._acquireLock(this.lockAcquireTimeout,run)}return run()}async _challenge(params){const run=async()=>{try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const response2=await _request(this.fetch,"POST",`${this.url}/factors/${params.factorId}/challenge`,{body:params,headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(response2.error){return response2}const{data:data2}=response2;if(data2.type!=="webauthn"){return{data:data2,error:null}}switch(data2.webauthn.type){case"create":return{data:Object.assign(Object.assign({},data2),{webauthn:Object.assign(Object.assign({},data2.webauthn),{credential_options:Object.assign(Object.assign({},data2.webauthn.credential_options),{publicKey:deserializeCredentialCreationOptions(data2.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},data2),{webauthn:Object.assign(Object.assign({},data2.webauthn),{credential_options:Object.assign(Object.assign({},data2.webauthn.credential_options),{publicKey:deserializeCredentialRequestOptions(data2.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}};if(this.lock!=null){return this._acquireLock(this.lockAcquireTimeout,run)}return run()}async _challengeAndVerify(params){const{data:challengeData,error:challengeError}=await this._challenge({factorId:params.factorId});if(challengeError){return this._returnResult({data:null,error:challengeError})}return await this._verify({factorId:params.factorId,challengeId:challengeData.id,code:params.code})}async _listFactors(){var _a;const{data:{user},error:userError}=await this.getUser();if(userError){return{data:null,error:userError}}const data2={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(const factor of(_a=user===null||user===undefined?undefined:user.factors)!==null&&_a!==undefined?_a:[]){data2.all.push(factor);if(factor.status==="verified"&&factor.factor_type in data2&&Array.isArray(data2[factor.factor_type])){data2[factor.factor_type].push(factor)}}return{data:data2,error:null}}async _getAuthenticatorAssuranceLevel(jwt){var _a,_b,_c,_d;if(jwt){try{const{payload:payload2}=decodeJWT(jwt);let currentLevel2=null;if(payload2.aal){currentLevel2=payload2.aal}let nextLevel2=currentLevel2;const{data:{user},error:userError}=await this.getUser(jwt);if(userError){return this._returnResult({data:null,error:userError})}const verifiedFactors2=(_b=(_a=user===null||user===undefined?undefined:user.factors)===null||_a===undefined?undefined:_a.filter((factor)=>factor.status==="verified"))!==null&&_b!==undefined?_b:[];if(verifiedFactors2.length>0){nextLevel2="aal2"}const currentAuthenticationMethods2=payload2.amr||[];return{data:{currentLevel:currentLevel2,nextLevel:nextLevel2,currentAuthenticationMethods:currentAuthenticationMethods2},error:null}}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}const{data:{session},error:sessionError}=await this.getSession();if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null}}const{payload}=decodeJWT(session.access_token);let currentLevel=null;if(payload.aal){currentLevel=payload.aal}let nextLevel=currentLevel;const verifiedFactors=(_d=(_c=session.user.factors)===null||_c===undefined?undefined:_c.filter((factor)=>factor.status==="verified"))!==null&&_d!==undefined?_d:[];if(verifiedFactors.length>0){nextLevel="aal2"}const currentAuthenticationMethods=payload.amr||[];return{data:{currentLevel,nextLevel,currentAuthenticationMethods},error:null}}async _getRecoveryCodesStatus(){assertRecoveryCodesExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _generateRecoveryCodes(params){assertRecoveryCodesExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:(params===null||params===undefined?undefined:params.friendlyName)?{friendly_name:params.friendlyName}:undefined,headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _verifyRecoveryCode(params){assertRecoveryCodesExperimentalEnabled(this.experimental);const run=async()=>{try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:params.code},headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}const session=Object.assign({expires_at:expiresAt(data2.expires_in)},data2);await this._saveSession(session);await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",session);return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}};if(this.lock!=null){return this._acquireLock(this.lockAcquireTimeout,run)}return run()}async _regenerateRecoveryCodes(){assertRecoveryCodesExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _unenrollRecoveryCodes(){assertRecoveryCodesExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _getAuthorizationDetails(authorizationId){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}return await _request(this.fetch,"GET",`${this.url}/oauth/authorizations/${authorizationId}`,{headers:this.headers,jwt:session.access_token,xform:(data2)=>({data:data2,error:null})})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _approveAuthorization(authorizationId,options){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const response2=await _request(this.fetch,"POST",`${this.url}/oauth/authorizations/${authorizationId}/consent`,{headers:this.headers,jwt:session.access_token,body:{action:"approve"},xform:(data2)=>({data:data2,error:null})});if(response2.data&&response2.data.redirect_url){if(isBrowser()&&!(options===null||options===undefined?undefined:options.skipBrowserRedirect)){window.location.assign(response2.data.redirect_url)}}return response2})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _denyAuthorization(authorizationId,options){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const response2=await _request(this.fetch,"POST",`${this.url}/oauth/authorizations/${authorizationId}/consent`,{headers:this.headers,jwt:session.access_token,body:{action:"deny"},xform:(data2)=>({data:data2,error:null})});if(response2.data&&response2.data.redirect_url){if(isBrowser()&&!(options===null||options===undefined?undefined:options.skipBrowserRedirect)){window.location.assign(response2.data.redirect_url)}}return response2})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _listOAuthGrants(){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}return await _request(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:session.access_token,xform:(data2)=>({data:data2,error:null})})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _revokeOAuthGrant(options){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}await _request(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:session.access_token,query:{client_id:options.clientId},noResolveJson:true});return{data:{},error:null}})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async fetchJwk(kid,jwks={keys:[]}){let jwk=jwks.keys.find((key)=>key.kid===kid);if(jwk){return jwk}const now=Date.now();jwk=this.jwks.keys.find((key)=>key.kid===kid);if(jwk&&this.jwks_cached_at+JWKS_TTL>now){return jwk}const{data:data2,error}=await _request(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(error){throw error}if(!data2.keys||data2.keys.length===0){return null}this.jwks=data2;this.jwks_cached_at=now;jwk=data2.keys.find((key)=>key.kid===kid);if(!jwk){return null}return jwk}async getClaims(jwt,options={}){try{let token=jwt;if(!token){const{data:data2,error}=await this.getSession();if(error||!data2.session){return this._returnResult({data:null,error})}token=data2.session.access_token}const{header,payload,signature,raw:{header:rawHeader,payload:rawPayload}}=decodeJWT(token);if(!(options===null||options===undefined?undefined:options.allowExpired)){try{validateExp(payload.exp)}catch(e){throw new AuthInvalidJwtError(e instanceof Error?e.message:"JWT validation failed")}}const signingKey=!header.alg||header.alg.startsWith("HS")||!header.kid||!(("crypto"in globalThis)&&("subtle"in globalThis.crypto))?null:await this.fetchJwk(header.kid,(options===null||options===undefined?undefined:options.keys)?{keys:options.keys}:options===null||options===undefined?undefined:options.jwks);if(!signingKey){const{error}=await this.getUser(token);if(error){throw error}return{data:{claims:payload,header,signature},error:null}}const algorithm=getAlgorithm(header.alg);const publicKey=await crypto.subtle.importKey("jwk",signingKey,algorithm,true,["verify"]);const isValid=await crypto.subtle.verify(algorithm,publicKey,signature,stringToUint8Array(`${rawHeader}.${rawPayload}`));if(!isValid){throw new AuthInvalidJwtError("Invalid JWT signature")}return{data:{claims:payload,header,signature},error:null}}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async signInWithPasskey(credentials){var _a,_b,_c;assertPasskeyExperimentalEnabled(this.experimental);try{if(!browserSupportsWebAuthn()){return this._returnResult({data:null,error:new AuthUnknownError("Browser does not support WebAuthn",null)})}const{data:options,error:optionsError}=await this._startPasskeyAuthentication({options:{captchaToken:(_a=credentials===null||credentials===undefined?undefined:credentials.options)===null||_a===undefined?undefined:_a.captchaToken}});if(optionsError||!options){return this._returnResult({data:null,error:optionsError})}const publicKeyOptions=deserializeCredentialRequestOptions(options.options);const signal=(_c=(_b=credentials===null||credentials===undefined?undefined:credentials.options)===null||_b===undefined?undefined:_b.signal)!==null&&_c!==undefined?_c:webAuthnAbortService.createNewAbortSignal();const{data:credential,error:credentialError}=await getCredential({publicKey:publicKeyOptions,signal});if(credentialError||!credential){return this._returnResult({data:null,error:credentialError!==null&&credentialError!==undefined?credentialError:new AuthUnknownError("WebAuthn ceremony failed",null)})}const serialized=serializeCredentialRequestResponse(credential);return this._verifyPasskeyAuthentication({challengeId:options.challenge_id,credential:serialized})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async registerPasskey(credentials){var _a,_b;assertPasskeyExperimentalEnabled(this.experimental);try{if(!browserSupportsWebAuthn()){return this._returnResult({data:null,error:new AuthUnknownError("Browser does not support WebAuthn",null)})}const{data:options,error:optionsError}=await this._startPasskeyRegistration();if(optionsError||!options){return this._returnResult({data:null,error:optionsError})}const publicKeyOptions=deserializeCredentialCreationOptions(options.options);const signal=(_b=(_a=credentials===null||credentials===undefined?undefined:credentials.options)===null||_a===undefined?undefined:_a.signal)!==null&&_b!==undefined?_b:webAuthnAbortService.createNewAbortSignal();const{data:credential,error:credentialError}=await createCredential({publicKey:publicKeyOptions,signal});if(credentialError||!credential){return this._returnResult({data:null,error:credentialError!==null&&credentialError!==undefined?credentialError:new AuthUnknownError("WebAuthn ceremony failed",null)})}const serialized=serializeCredentialCreationResponse(credential);return this._verifyPasskeyRegistration({challengeId:options.challenge_id,credential:serialized})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _startPasskeyRegistration(){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:session.access_token,body:{}});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _verifyPasskeyRegistration(params){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:session.access_token,body:{challenge_id:params.challengeId,credential:params.credential}});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _startPasskeyAuthentication(params){var _a;assertPasskeyExperimentalEnabled(this.experimental);try{const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(_a=params===null||params===undefined?undefined:params.options)===null||_a===undefined?undefined:_a.captchaToken}}});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _verifyPasskeyAuthentication(params){assertPasskeyExperimentalEnabled(this.experimental);try{const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:params.challengeId,credential:params.credential},xform:_sessionResponse});if(error){return this._returnResult({data:null,error})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers("SIGNED_IN",data2.session)}return this._returnResult({data:data2,error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _listPasskeys(){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{data:data2,error}=await _request(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:session.access_token,xform:(data3)=>({data:data3,error:null})});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _updatePasskey(params){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{data:data2,error}=await _request(this.fetch,"PATCH",`${this.url}/passkeys/${params.passkeyId}`,{headers:this.headers,jwt:session.access_token,body:{friendly_name:params.friendlyName}});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _deletePasskey(params){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{error}=await _request(this.fetch,"DELETE",`${this.url}/passkeys/${params.passkeyId}`,{headers:this.headers,jwt:session.access_token,noResolveJson:true});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:null,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}}var DEFAULT_OPTIONS,GLOBAL_JWKS,deprecatedLockWarned=false,GoTrueClient_default;var init_GoTrueClient=__esm(()=>{init_GoTrueAdminApi();init_constants();init_errors();init_fetch();init_helpers();init_locks();init_base64url();init_webauthn();polyfillGlobalThis();DEFAULT_OPTIONS={url:GOTRUE_URL,storageKey:STORAGE_KEY,autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,headers:DEFAULT_HEADERS,flowType:"implicit",debug:false,hasCustomAuthorizationHeader:false,throwOnError:false,lockAcquireTimeout:5000,skipAutoInitialize:false,experimental:{}};GLOBAL_JWKS={};GoTrueClient.nextInstanceID={};GoTrueClient_default=GoTrueClient});var init_AuthAdminApi=__esm(()=>{init_GoTrueAdminApi()});var AuthClient,AuthClient_default;var init_AuthClient=__esm(()=>{init_GoTrueClient();AuthClient=GoTrueClient_default;AuthClient_default=AuthClient});var init_module=__esm(()=>{init_GoTrueAdminApi();init_GoTrueClient();init_AuthAdminApi();init_AuthClient();init_locks();init_types();init_errors()});var exports_auth_provider={};__export(exports_auth_provider,{AuthClient:()=>AuthClient_default});var init_auth_provider=__esm(()=>{init_module()});var fileValidationReasons={invalid_metadata:"File metadata must contain only the supported fields.",invalid_name:"File name must be 1–255 characters, with no reserved names, path separators, control characters or trailing spaces/dots.",invalid_path:"File path must contain safe relative folder names and cannot start with .os.",invalid_storage:"File storage must be local or remote.",invalid_media_type:"The media type must use a value such as text/markdown or application/json.",invalid_size:"File size must be a non-negative safe integer byte count.",invalid_request_key:"File request key must contain 1–256 characters, with no surrounding whitespace or control characters.",invalid_enrichment_name:"The enrichment name must be a filename without folders, such as read.md. Names such as original and original.pdf are reserved.",invalid_enrichment_request:"The save request has invalid content or metadata.",invalid_replacement:"To replace an enrichment, pass its current SHA-256 value as replace.",invalid_bytes:"File content must contain byte chunks.",original_changed:"The selected file changed while OS was reading it. Wait for it to finish saving, then try again."};var localStorageReasons={local_storage_legacy:`OS found an older local file storage layout: the internal metadata folder is still named .oddington-files.
19
19
 
20
20
  Stop any OS routines using this workspace, then rename .oddington-files to .os in the same directory and rerun your command. Keep the folder’s contents intact.`,local_storage_ambiguous:"OS found both .oddington-files and .os metadata folders in local file storage and could not safely choose one. Reconcile their metadata before continuing; do not overwrite either folder. Your stored files have been left in place.",local_storage_unrecognized:"OS could not open its local file storage because the folder contains files but has no recognized metadata. The storage folder needs to be checked before continuing. Your stored files have been left in place.",local_storage_tracked:"OS could not use its local file storage because it contains Git-tracked files. Local file storage must be outside tracked repository content. Your stored files have been left in place."};function parseFileErrorDetail(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const v=value;if(typeof v.reason!=="string")return;if(Object.hasOwn(fileValidationReasons,v.reason)||Object.hasOwn(localStorageReasons,v.reason))return Object.keys(v).length===1?{reason:v.reason}:undefined;if(v.reason!=="size_mismatch"&&v.reason!=="size_limit")return;const count=v.reason==="size_mismatch"?"expectedBytes":"limitBytes";if(Object.keys(v).some((key)=>!["reason",count,"receivedBytes","receivedAtLeast"].includes(key))||!Number.isSafeInteger(v[count])||v[count]<0||!Number.isSafeInteger(v.receivedBytes)||v.receivedBytes<0||v.receivedAtLeast!==undefined&&v.receivedAtLeast!==true)return;return{reason:v.reason,[count]:v[count],receivedBytes:v.receivedBytes,...v.receivedAtLeast?{receivedAtLeast:true}:{}}}function fileErrorExplanation(detail){if(detail.reason==="size_mismatch")return`The request declared ${detail.expectedBytes} bytes, but contained ${detail.receivedAtLeast?"at least ":""}${detail.receivedBytes} bytes.`;if(detail.reason==="size_limit")return`The file content exceeds the ${fileSizeLabel(detail.limitBytes)} limit; received ${detail.receivedAtLeast?"at least ":""}${fileSizeLabel(detail.receivedBytes)}.`;return Object.hasOwn(localStorageReasons,detail.reason)?localStorageReasons[detail.reason]:fileValidationReasons[detail.reason]}function fileSizeLabel(bytes){for(const[unit,size]of[["GiB",1024**3],["MiB",1024**2],["KiB",1024]])if(bytes>=size&&bytes%size===0)return`${bytes/size} ${unit}`;return`${bytes} bytes`}function fileErrorDetailForCode(code,detail){const parsed=parseFileErrorDetail(detail);if(!parsed)return;const storage=Object.hasOwn(localStorageReasons,parsed.reason);if(storage?code==="unavailable":["invalid_input","request_too_large"].includes(code))return parsed}var FILE_CAPACITY_MESSAGE="OS reached its file-processing limit. Try again in a moment. "+"If this keeps happening with a large batch, split the files into smaller groups.";var FILE_INTEGRITY_MESSAGE="OS could not verify this File against its saved record. Try again. "+"If the problem continues, add the original file again.";function fileErrorMessage(error){const detail=fileErrorDetailForCode(error.code,error.detail);if(detail){const enrichment=["invalid_enrichment_name","invalid_enrichment_request","invalid_replacement"].includes(detail.reason);return`${enrichment?`Couldn’t save the file’s enrichment.
21
- `:""}${fileErrorExplanation(detail)}`}switch(error.code){case"invalid_input":return"The file request is invalid.";case"unsupported_context":return"This environment does not support this file operation.";case"unauthenticated":return"Sign in to OS before accessing files.";case"access_denied":return"You don’t have access to this file operation.";case"not_found":return"This file isn’t available in this workspace.";case"request_too_large":return"The file request exceeds the size limit.";case"conflict":return"The saved file or enrichment doesn’t match this request. Reload it before trying again.";case"local_only":return"This file is stored on a computer and isn’t available through remote storage.";case"integrity":return FILE_INTEGRITY_MESSAGE;case"capacity":return FILE_CAPACITY_MESSAGE;case"method_not_allowed":return"This request uses an unsupported file operation.";case"unavailable":return`OS couldn’t complete the file operation.${error.retryable?" Try again.":""}`}}class FileOperationError extends Error{code;status;retryable;detail;constructor(code,status,retryable=false,detail){const safe=fileErrorDetailForCode(code,detail);super(fileErrorMessage({code,retryable,detail:safe}));this.code=code;this.status=status;this.retryable=retryable;if(safe)this.detail=Object.freeze(safe);if(safe&&Object.hasOwn(localStorageReasons,safe.reason))this.retryable=false}}var FILE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var FILE_ORIGINAL_MAX_BYTES=5*1024**3;function parseFileDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const f=value;if(Object.keys(f).sort().join(",")!=="enrichments,id,mediaType,name,path,sha256,size"||typeof f.id!=="string"||!FILE_ID_PATTERN.test(f.id)||!safeFileName(f.name)||!safeFilePath(f.path)||!Number.isSafeInteger(f.size)||f.size<0||f.size>FILE_ORIGINAL_MAX_BYTES||typeof f.sha256!=="string"||!/^[0-9a-f]{64}$/.test(f.sha256)||!f.enrichments||typeof f.enrichments!=="object"||Array.isArray(f.enrichments)||!isCanonicalOriginalMediaType(f.mediaType))return invalid();for(const[name,descriptor]of Object.entries(f.enrichments)){if(!safeEnrichmentName(name))return invalid();parseEnrichmentDescriptor(descriptor)}if(new TextEncoder().encode(JSON.stringify(f)).byteLength>16*1024)return invalid();return f}function parseEnrichmentDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).sort().join(",")!=="mediaType,sha256,size"||!["application/octet-stream","text/plain","text/markdown","application/json"].includes(d.mediaType)||!Number.isSafeInteger(d.size)||d.size<0||d.size>16*1024*1024||typeof d.sha256!=="string"||!/^[0-9a-f]{64}$/.test(d.sha256))return invalid();return d}function safeEnrichmentName(value){return safeFileName(value)&&!/^original(?:\.|$)/i.test(value)}function parseFileEnrichMetadata(value,maxBytes){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).some((key)=>!["name","size","mediaType","replace"].includes(key)))return invalid();if(!safeEnrichmentName(d.name))return invalid("invalid_enrichment_name");if(!Number.isSafeInteger(d.size)||d.size<0)return invalid("invalid_size");if(d.mediaType!==undefined&&(typeof d.mediaType!=="string"||d.mediaType.length>255||/[\u0000-\u001f\u007f]/.test(d.mediaType)))return invalid("invalid_media_type");if(d.replace!==undefined&&(typeof d.replace!=="string"||!/^[0-9a-f]{64}$/.test(d.replace)))return invalid("invalid_replacement");if(d.size>maxBytes)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:maxBytes,receivedBytes:d.size});return d}function safeFileName(value){return typeof value==="string"&&value.length>0&&value.length<=255&&value===value.trim()&&value!=="."&&value!==".."&&!/[\u0000-\u001f\u007f-\u009f/\\:*?"<>|]/u.test(value)&&!/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(value)&&!/[. ]$/.test(value)&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value)}function safeFilePath(value){return typeof value==="string"&&value.length<=1024&&value.split("/").every(safeFileName)}function safeManagedFilePath(value){return safeFilePath(value)&&value.split("/")[0].toLowerCase()!==".os"}function declaredOriginalMediaType(value){if(typeof value!=="string"||value.length>255||/[\u0000-\u001f\u007f-\u009f]/.test(value))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_media_type"});const normalized=value.split(";",1)[0].trim().toLowerCase();const token="[a-z0-9!#$%&'+.^_`|~-]+";if(!new RegExp(`^${token}/${token}$`).test(normalized))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_media_type"});return normalized}function isCanonicalOriginalMediaType(value){try{return declaredOriginalMediaType(value)===value}catch{return false}}function parseFileCreateMetadata(value,maxBytes){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const input=value;if(Object.keys(input).some((key)=>!["name","path","storage","mediaType","size","requestKey"].includes(key)))return invalid();const path=input.path===undefined?"Files":input.path;if(!safeFileName(input.name))return invalid("invalid_name");if(!safeManagedFilePath(path))return invalid("invalid_path");if(input.storage!==undefined&&input.storage!=="remote"&&input.storage!=="local")return invalid("invalid_storage");const mediaType=input.mediaType===undefined?"application/octet-stream":declaredOriginalMediaType(input.mediaType);if(!Number.isSafeInteger(input.size)||input.size<0)return invalid("invalid_size");if(input.size>maxBytes)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:maxBytes,receivedBytes:input.size});if(typeof input.requestKey!=="string"||input.requestKey.length<1||input.requestKey.length>256||input.requestKey!==input.requestKey.trim()||/[\u0000-\u001f\u007f]/.test(input.requestKey))return invalid("invalid_request_key");return{name:input.name,path,...input.storage?{storage:input.storage}:{},mediaType,size:input.size,requestKey:input.requestKey}}class AppRoutineContractError extends Error{code;constructor(code){super(code);this.code=code}}var propertyName=/^[a-z][A-Za-z0-9]*(?![\s\S])/;var stepId=/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/;var routineName=/^[a-z0-9][a-z0-9-]{0,62}(?![\s\S])/;function isAppRoutineName(value){return typeof value==="string"&&routineName.test(value)}var owns=(value,key)=>Object.hasOwn(value,key);var invalidContract=()=>{throw new AppRoutineContractError("invalid_contract")};var invalidValue=()=>{throw new AppRoutineContractError("invalid_value")};function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null)}function fields(value,required,optional=[]){return required.every((key)=>owns(value,key))&&Object.keys(value).every((key)=>required.includes(key)||optional.includes(key))}function denseArray(value){return Array.isArray(value)&&Object.keys(value).length===value.length&&Array.from({length:value.length},(_,index)=>owns(value,String(index))).every(Boolean)}function parseAppRoutineContract(value){let properties=0;function schema(value2,depth=1){if(depth>8||!record(value2))return invalidContract();switch(value2.type){case"object":{if(!fields(value2,["type","properties","additionalProperties"],["required"])||value2.additionalProperties!==false||!record(value2.properties))return invalidContract();const entries=Object.entries(value2.properties);properties+=entries.length;if(properties>64||entries.some(([key])=>!propertyName.test(key)))return invalidContract();let required;if(owns(value2,"required")){if(!denseArray(value2.required)||value2.required.some((key)=>typeof key!=="string"||!owns(value2.properties,key))||new Set(value2.required).size!==value2.required.length)return invalidContract();required=[...value2.required]}return{type:"object",properties:Object.fromEntries(entries.map(([key,child])=>[key,schema(child,depth+1)])),...required===undefined?{}:{required},additionalProperties:false}}case"array":if(!fields(value2,["type","items"],["maxItems"])||owns(value2,"maxItems")&&(!Number.isSafeInteger(value2.maxItems)||value2.maxItems<1))return invalidContract();return{type:"array",items:schema(value2.items,depth+1),...owns(value2,"maxItems")?{maxItems:value2.maxItems}:{}};case"boolean":if(!fields(value2,["type"]))return invalidContract();return{type:value2.type};case"file":if(!fields(value2,["type"],["storage","path"])||owns(value2,"storage")&&value2.storage!=="local"&&value2.storage!=="remote"||owns(value2,"path")&&!safeManagedFilePath(value2.path))return invalidContract();return{type:"file",...owns(value2,"storage")?{storage:value2.storage}:{},...owns(value2,"path")?{path:value2.path}:{}};case"string":if(!fields(value2,["type"],["maxLength"])||owns(value2,"maxLength")&&(!Number.isSafeInteger(value2.maxLength)||value2.maxLength<0||value2.maxLength>4096))return invalidContract();return{type:"string",...owns(value2,"maxLength")?{maxLength:value2.maxLength}:{}};case"integer":case"number":{const validNumber=value2.type==="integer"?Number.isSafeInteger:Number.isFinite;if(!fields(value2,["type"],["minimum","maximum"])||owns(value2,"minimum")&&!validNumber(value2.minimum)||owns(value2,"maximum")&&!validNumber(value2.maximum)||owns(value2,"minimum")&&owns(value2,"maximum")&&value2.minimum>value2.maximum)return invalidContract();return{type:value2.type,...owns(value2,"minimum")?{minimum:value2.minimum}:{},...owns(value2,"maximum")?{maximum:value2.maximum}:{}}}default:return invalidContract()}}if(!record(value)||!fields(value,["routine","input","steps"],["result"])||!isAppRoutineName(value.routine)||!denseArray(value.steps)||value.steps.length<1||value.steps.length>64)return invalidContract();const input=schema(value.input);const result=owns(value,"result")?schema(value.result):undefined;const ids=new Set;const steps=value.steps.map((step)=>{if(!record(step)||!fields(step,["id"],["summary"])||typeof step.id!=="string"||!stepId.test(step.id)||ids.has(step.id))return invalidContract();ids.add(step.id);return{id:step.id,...owns(step,"summary")?{summary:schema(step.summary)}:{}}});return{routine:value.routine,input,steps,...result===undefined?{}:{result}}}function jsonData(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!record(value)&&!denseArray(value))return invalidValue();if(ancestors.has(value))return invalidValue();ancestors.add(value);for(const child of Object.values(value))jsonData(child,ancestors);ancestors.delete(value)}function validateRoutineSchemaValue(schema,value,rejected){const type=(value2)=>value2===null?"null":Array.isArray(value2)?"array":["object","boolean","string","number"].includes(typeof value2)?typeof value2:"other";function check(schema2,value2,path){const fail=(reason,extra={})=>{rejected?.({reason,path:path.length<=256?path:"$",expected:schema2.type,received:type(value2),...extra});return invalidValue()};switch(schema2.type){case"object":if(!record(value2))return fail("wrong_type");for(const key of schema2.required??[])if(!owns(value2,key))return fail("missing_field",{path:`${path}.${key}`.length<=256?`${path}.${key}`:"$",expected:schema2.properties[key].type,received:"missing"});if(Object.keys(value2).some((key)=>!owns(schema2.properties,key)))return fail("unexpected_field");for(const[key,child]of Object.entries(value2))check(schema2.properties[key],child,`${path}.${key}`);return;case"array":if(!denseArray(value2))return fail("wrong_type");if(schema2.maxItems!==undefined&&value2.length>schema2.maxItems)return fail("out_of_bounds",{constraint:"maxItems",limit:schema2.maxItems});value2.forEach((child,index)=>check(schema2.items,child,`${path}[${index}]`));return;case"boolean":if(typeof value2!=="boolean")return fail("wrong_type");return;case"string":if(typeof value2!=="string")return fail("wrong_type");if(Array.from(value2).length>(schema2.maxLength??4096))return fail("out_of_bounds",{constraint:"maxLength",limit:schema2.maxLength??4096});return;case"integer":case"number":if(typeof value2!=="number"||!(schema2.type==="integer"?Number.isSafeInteger(value2):Number.isFinite(value2)))return fail("wrong_type");if(schema2.minimum!==undefined&&value2<schema2.minimum)return fail("out_of_bounds",{constraint:"minimum",limit:schema2.minimum});if(schema2.maximum!==undefined&&value2>schema2.maximum)return fail("out_of_bounds",{constraint:"maximum",limit:schema2.maximum});return;case"file":{let file;try{jsonData(value2);file=parseFileDescriptor(value2)}catch{return fail("invalid_file")}if(schema2.path!==undefined&&file.path!==schema2.path)return fail("invalid_file")}}}check(schema,value,"$")}function validRecordRef(value){return typeof value==="string"&&value.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(value)}function validDropboxRootPath(value){return value===""||typeof value==="string"&&value.length<=2048&&value.startsWith("/")&&!/[\\\x00-\x1f\x7f]/.test(value)&&value.slice(1).split("/").every((segment)=>segment.length>0&&segment.trim()===segment&&segment!=="."&&segment!=="..")}function validMicrosoftId(value){return typeof value==="string"&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)}function validMicrosoftMailbox(value){return typeof value==="string"&&value.length<=254&&/^[^\s@/?#\\\x00-\x1f\x7f]+@[^\s@/?#\\\x00-\x1f\x7f]+\.[^\s@/?#\\\x00-\x1f\x7f]+$/.test(value)}function sharePointHost(value){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.sharepoint\.com$/.test(value)}function canonicalSharePointSiteUrl(value){if(typeof value!=="string"||value.length>2048||/[\s\\?#\x00-\x1f\x7f]/.test(value)||!/^https:\/\/[^/:@]+(?:\/|$)/i.test(value))return;try{const url=new URL(value);if(url.protocol!=="https:"||!sharePointHost(url.hostname)||url.username||url.password||url.port)return;const rawPath=value.replace(/^https:\/\/[^/]+/i,"")||"/";const path=rawPath.endsWith("/")?rawPath.slice(0,-1):rawPath;const segments=path.slice(1).split("/");if(path&&segments.some((segment)=>!segment))return;const encoded=path?segments.map((segment)=>{const decoded=decodeURIComponent(segment);if(decoded==="."||decoded===".."||/[/%\\?#\x00-\x1f\x7f]/.test(decoded))throw new Error;return encodeURIComponent(decoded)}).join("/"):"";const canonical=`https://${url.hostname}/${encoded}`;return canonical.length<=2048?canonical:undefined}catch{return}}function validSharePointSiteId(value,siteUrl){if(typeof value!=="string"||value.length>512)return false;const[host,collection,site,extra]=value.split(",");return extra===undefined&&host===new URL(siteUrl).hostname&&validMicrosoftId(collection)&&validMicrosoftId(site)}function validGoogleScopes(value){return Array.isArray(value)&&value.length>0&&value.length<=32&&value.every((scope)=>typeof scope==="string"&&scope.length<=256&&/^(https:\/\/www\.googleapis\.com\/auth\/[A-Za-z0-9._-]+|https:\/\/mail\.google\.com\/|openid|email|profile)$/.test(scope))&&new Set(value).size===value.length}var DROPBOX_FILE_SCOPES=["account_info.read","files.metadata.read","files.content.read","files.content.write"];function validDropboxFileScopes(value){return Array.isArray(value)&&value.length===DROPBOX_FILE_SCOPES.length&&new Set(value).size===value.length&&DROPBOX_FILE_SCOPES.every((scope)=>value.includes(scope))}function validDataRepositoryName(value){return typeof value==="string"&&/^[a-z0-9][a-z0-9._-]{0,127}$/.test(value)&&!value.includes("..")}class InboxContractError extends Error{constructor(message){super(message);this.name="InboxContractError"}}var INBOX_PUBLICATION_ITEM_BYTES=1024*1024;var INBOX_PUBLICATION_REQUEST_BYTES=INBOX_PUBLICATION_ITEM_BYTES+4096;var publicationAdvice="Trim the content, or attach long reports, data, and supporting materials as files instead. Then try again.";var INBOX_PUBLICATION_TOO_LARGE=`Your Inbox item failed to publish. Its content exceeds the 1 MB limit. ${publicationAdvice}`;class InboxPublicationSizeError extends InboxContractError{kind;bytes;constructor(kind,bytes){const label=kind==="ask"?"Ask":"Digest";const size=Math.ceil(bytes/INBOX_PUBLICATION_ITEM_BYTES*100)/100;super(`Your ${label} failed to publish. Its content is ${size} MB, which exceeds the 1 MB limit. ${publicationAdvice}`);this.kind=kind;this.bytes=bytes;this.name="InboxPublicationSizeError"}}function enforcePublicationSize(value){const bytes=new TextEncoder().encode(JSON.stringify(value)).byteLength;if(bytes>INBOX_PUBLICATION_ITEM_BYTES)throw new InboxPublicationSizeError(value.kind,bytes);return value}function fail(message){throw new InboxContractError(message)}function object(value,label){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))fail(`${label} must be a plain object`);return value}function keys(value,allowed,label){for(const key of Reflect.ownKeys(value)){if(typeof key!=="string"||!allowed.includes(key))fail(`${label} does not support ${String(key)}`);const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!("value"in descriptor))fail(`${label} must contain only JSON data`)}}function text(value,label){if(typeof value!=="string"||!value.trim())fail(`${label} must be nonempty text`);return value}function id(value,label){const result=text(value,label);if(result!==result.trim())fail(`${label} cannot have surrounding whitespace`);return result}function array(value,label){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype||Reflect.ownKeys(value).length!==value.length+1)fail(`${label} must be a dense array`);for(let index=0;index<value.length;index+=1){const descriptor=Object.getOwnPropertyDescriptor(value,String(index));if(!descriptor?.enumerable||!("value"in descriptor))fail(`${label} must contain only JSON data`)}return value}function distinctIds(value,label,nonempty=true){const result=array(value,label).map((entry)=>id(entry,label));if(nonempty&&!result.length)fail(`${label} must not be empty`);if(new Set(result).size!==result.length)fail(`${label} contains duplicate IDs`);return result}var memberEmail=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function personReference(value,label){const result=id(value,label);return memberEmail.test(result)?result.toLowerCase():result}function distinctPeople(value,label,nonempty=true){const result=array(value,label).map((entry)=>personReference(entry,label));if(nonempty&&!result.length)fail(`${label} must not be empty`);if(new Set(result).size!==result.length)fail(`${label} contains duplicate IDs`);return result}function serializable(value,ancestors=new Set){if(value===null||typeof value==="boolean"||typeof value==="string")return value;if(typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object")fail("Input must be losslessly serializable JSON");if(ancestors.has(value))fail("Input cannot contain cycles");ancestors.add(value);try{if(Array.isArray(value)){array(value,"JSON array");return value.map((entry)=>serializable(entry,ancestors))}const source=object(value,"JSON input");keys(source,Object.keys(source),"JSON input");return Object.fromEntries(Object.entries(source).map(([key,entry])=>[key,serializable(entry,ancestors)]))}finally{ancestors.delete(value)}}function natural(value,label,minimum=0){if(!Number.isSafeInteger(value)||value<minimum)fail(`${label} must be an integer >= ${minimum}`);return value}function validateInboxFile(value){const v=object(serializable(value),"Inbox file");keys(v,["id","name","mediaType","size","sha256"],"Inbox file");const fileId=id(v.id,"Inbox file ID"),name=id(v.name,"filename"),mediaType=id(v.mediaType,"media type");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(fileId)||/[\x00-\x1f\x7f/\\]/.test(name)||!isCanonicalOriginalMediaType(mediaType)||typeof v.sha256!=="string"||!/^[0-9a-f]{64}$/.test(v.sha256))fail("Invalid Inbox file identity or metadata");const size=natural(v.size,"file size");if(size>FILE_ORIGINAL_MAX_BYTES)fail("File exceeds supported size");return{id:fileId,name,mediaType,size,sha256:v.sha256}}function validateQualifiedRecordRef(value){const r=object(value,"Record reference");keys(r,["repository","ref"],"Record reference");if(!validDataRepositoryName(r.repository)||!validRecordRef(r.ref))fail("Invalid qualified Record reference");return{repository:r.repository,ref:r.ref}}function validateBlock(value){const b=object(serializable(value),"Block");if(b.kind==="rich-text"){keys(b,["kind","markdown"],"Rich text Block");return{kind:"rich-text",markdown:text(b.markdown,"Markdown")}}if(b.kind==="asks"){keys(b,["kind","problem","asks"],"Asks Block");const asks=distinctIds(b.asks,"Ask IDs");if(asks.some((ask)=>!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(ask)))fail("Invalid Ask ID");return{kind:"asks",problem:text(b.problem,"problem"),asks}}if(!["record","records","files"].includes(b.kind))fail("Unknown Block kind");keys(b,["kind","label","initiallyExpanded",...b.kind==="record"?["record"]:b.kind==="records"?["records"]:["files"]],"Block");const label=text(b.label,"Block label");if(b.initiallyExpanded!==undefined&&typeof b.initiallyExpanded!=="boolean")fail("Invalid initiallyExpanded");const expanded=b.initiallyExpanded===undefined?{}:{initiallyExpanded:b.initiallyExpanded};if(b.kind==="record")return{kind:"record",label,record:validateQualifiedRecordRef(b.record),...expanded};if(b.kind==="records"){const records=array(b.records,"records").map(validateQualifiedRecordRef);if(!records.length||new Set(records.map((r)=>JSON.stringify([r.repository,r.ref]))).size!==records.length)fail("Empty or duplicate records");return{kind:"records",label,records,...expanded}}const files=array(b.files,"files").map(validateInboxFile);if(!files.length||new Set(files.map((file)=>file.id)).size!==files.length)fail("Empty or duplicate files");return{kind:"files",label,files,...expanded}}function richTextBlock(value){return validateBlock({...value,kind:"rich-text"})}function recordBlock(value){return validateBlock({...value,kind:"record"})}function recordsBlock(value){return validateBlock({...value,kind:"records"})}function fileBlock(value){const input=object(serializable(value),"Files Block");const files=array(input.files,"files").map((entry)=>{const descriptor=object(entry,"File");if(!(("path"in descriptor)||("enrichments"in descriptor)))return validateInboxFile(descriptor);let file;try{file=parseFileDescriptor(descriptor)}catch{return fail("Invalid shared File descriptor")}const{id:id2,name,mediaType,size,sha256}=file;return{id:id2,name,mediaType,size,sha256}});return validateBlock({...input,kind:"files",files})}function asksBlock(value){return validateBlock({...value,kind:"asks"})}function selection(value){const input=object(value,"selection");keys(input,["source"],"selection");return validateResponseDefinition({type:"selection",source:input.source})}function validateAuthoredSource(value){const source=object(value,"response definition");keys(source,["type","options","suggestions","search"],"response definition");if(source.type!=="authored")fail("Expected authored options");const options=array(source.options,"options").map((entry)=>{const option=object(entry,"choice");keys(option,["value","label","description","note"],"choice");let note;if(option.note!==undefined){const declaration=object(option.note,"choice note");keys(declaration,["placeholder"],"choice note");note={placeholder:text(declaration.placeholder,"note placeholder")}}return{value:id(option.value,"choice value"),label:text(option.label,"choice label"),...option.description===undefined?{}:{description:text(option.description,"choice description")},...note?{note}:{}}});if(!options.length)fail("Choices require at least one option");if(new Set(options.map((option)=>option.value)).size!==options.length)fail("Duplicate choice value");if(Object.hasOwn(source,"search")||Object.hasOwn(source,"suggestions")){const labels=object(source.search,"choice search");keys(labels,["triggerLabel","placeholder","emptyLabel"],"choice search");const search={triggerLabel:text(labels.triggerLabel,"search trigger label"),placeholder:text(labels.placeholder,"search placeholder"),emptyLabel:text(labels.emptyLabel,"search empty label")};const suggestions=array(source.suggestions,"suggestions").map((value2)=>id(value2,"suggestion value"));if(suggestions.length>8||new Set(suggestions).size!==suggestions.length||suggestions.some((value2)=>!options.some((option)=>option.value===value2)))fail("Search permits at most eight unique published suggestions");return{type:"authored",options,suggestions,search}}if(options.length>9)fail("Choices require one to nine options");return{type:"authored",options}}function validateRecordReference(value){const row=object(value,"Record reference");keys(row,["repository","ref"],"Record reference");const repository=id(row.repository,"repository"),ref=id(row.ref,"Record reference");if(!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(repository)||/\.\.|\/\//.test(repository)||ref.length>512||!/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(ref))fail("Invalid Record identity");return{repository,ref}}function validateRecordSource(value){const source=object(value,"Record selection");keys(source,["type","collection","refPrefix","where","display","suggestions"],"Record selection");if(source.type!=="records")fail("Expected Record options");const collection=object(source.collection,"collection");keys(collection,["repository","name"],"collection");const repository=validateRecordReference({repository:collection.repository,ref:"records/example"}).repository;const name=id(collection.name,"collection name");if(!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(name))fail("Invalid collection name");const refPrefix=source.refPrefix===undefined?undefined:id(source.refPrefix,"Record reference prefix");if(refPrefix!==undefined&&(!refPrefix.endsWith("/")||refPrefix.length>512||!/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(refPrefix)))fail("Invalid Record reference prefix");const where=object(source.where??{},"Record filter");const fieldName=(name2)=>/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2)&&!["constructor","prototype"].includes(name2);for(const[name2,value2]of Object.entries(where)){if(!fieldName(name2)||!(value2===null||["string","number","boolean"].includes(typeof value2))||typeof value2==="number"&&!Number.isFinite(value2))fail("Record filters require scalar equality")}const display=object(source.display,"Record display");keys(display,["labelFields"],"Record display");const labelFields=distinctIds(display.labelFields,"label fields");if(labelFields.length>2||labelFields.some((name2)=>!fieldName(name2)))fail("Select one or two scalar label fields");const suggestions=array(source.suggestions??[],"suggestions").map((value2)=>{const entry=object(value2,"suggestion");keys(entry,["record","reason"],"suggestion");const record2=validateRecordReference(entry.record);if(record2.repository!==repository)fail("Suggestion belongs to another repository");return{record:record2,...entry.reason===undefined?{}:{reason:text(entry.reason,"suggestion reason")}}});if(suggestions.length>8||new Set(suggestions.map((entry)=>entry.record.ref)).size!==suggestions.length)fail("Record selection permits at most eight unique suggestions");return{type:"records",collection:{repository,name},...refPrefix?{refPrefix}:{},where:{...where},display:{labelFields},suggestions}}function validateResponseDefinition(value){const definition=object(value,"response definition");keys(definition,["type","source"],"response definition");if(definition.type!=="selection")fail("Expected a selection definition");const source=object(definition.source,"option source");switch(source.type){case"authored":return{type:"selection",source:validateAuthoredSource(source)};case"records":return{type:"selection",source:validateRecordSource(source)};default:return fail("Unsupported option source")}}function handlerReference(value){const source=object(value,"handler reference");keys(source,["id","input"],"handler reference");return{id:id(source.id,"handler ID"),input:serializable(source.input)}}function defineHandler(value){const source=object(value,"handler");keys(source,["id","results","run"],"handler");const stable=(value2)=>typeof value2==="string"&&/^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);if(!stable(source.id))fail("Handler ID must be stable");const results=source.results===undefined?undefined:distinctIds(source.results,"handler results",false);if(results&&(results.length>64||results.some((result)=>!stable(result))))fail("Handler results must be stable IDs");if(typeof source.run!=="function")fail("Handler requires a run function");return Object.freeze({id:value.id,...results===undefined?{}:{results:Object.freeze(results.sort())},run:value.run})}function respond(handler,input){defineHandler(handler);return handlerReference({id:handler.id,input})}function question(value){const source=object(value,"question");keys(source,["id","to","allowedResponders","prompt","instructions","response","handler"],"question");const to=personReference(source.to,"question assignee");const allowedResponders=source.allowedResponders===undefined?[to]:distinctPeople(source.allowedResponders,"allowed responders");if(!allowedResponders.includes(to))fail("Allowed responders must include the assignee");return{id:id(source.id,"question ID"),to,allowedResponders,prompt:text(source.prompt,"question prompt"),...source.instructions===undefined?{}:{instructions:text(source.instructions,"instructions")},response:validateResponseDefinition(source.response),...Object.hasOwn(source,"handler")?{handler:handlerReference(source.handler)}:{}}}function presentation(source){const views=source.views===undefined?[]:array(source.views,"views").map((entry)=>{const view=object(entry,"view");keys(view,["id","view","input"],"view");return{id:id(view.id,"view ID"),view:id(view.view,"view name"),input:serializable(view.input)}});if(new Set(views.map((view)=>view.id)).size!==views.length)fail("Duplicate view ID");const body=source.body===undefined?[]:array(source.body,"body").map(validateBlock);return{title:text(source.title,"title"),description:text(source.description,"description"),views,body}}function validatePublication(value){const source=object(value,"publication");if(source.kind!=="ask"&&source.kind!=="digest")fail("Publication requires an explicit kind");keys(source,["kind","title","description","recipients","views","body","notifyImmediately",...source.kind==="ask"?["questions","tags","recordRefs"]:[]],"publication");if(source.notifyImmediately!==undefined&&typeof source.notifyImmediately!=="boolean")fail("notifyImmediately must be a boolean");const itemPresentation={...presentation(source),...source.notifyImmediately===undefined?{}:{notifyImmediately:source.notifyImmediately}};const linkedAsks=(itemPresentation.body??[]).flatMap((block)=>block.kind==="asks"?block.asks:[]);if(new Set(linkedAsks).size!==linkedAsks.length)fail("Ask belongs to more than one problem");if(source.kind==="digest")return{kind:"digest",...itemPresentation,recipients:distinctPeople(source.recipients,"digest recipients")};if(itemPresentation.body?.some((block)=>block.kind==="asks"))fail("Asks Blocks belong to Digests");const questions=array(source.questions===undefined?[]:source.questions,"questions").map((value2)=>question(value2));if(new Set(questions.map((entry)=>entry.id)).size!==questions.length)fail("Duplicate question ID");const extra=source.recipients===undefined?[]:distinctPeople(source.recipients,"recipients",false);if(!questions.length&&!extra.length)fail("Ask requires at least one recipient");const tags=array(source.tags===undefined?[]:source.tags,"Ask tags").map((value2)=>{const tag=text(value2,"Ask tag");if(new TextEncoder().encode(tag).byteLength>64)fail("Ask tag exceeds 64 UTF-8 bytes");return tag});if(tags.length>32||new Set(tags).size!==tags.length)fail("Ask tags exceed bounds or contain duplicates");const recordRefs=array(source.recordRefs===undefined?[]:source.recordRefs,"Ask Record references").map((value2)=>{const row=object(value2,"Ask Record reference");keys(row,["repository","id"],"Ask Record reference");const{repository,ref}=validateRecordReference({repository:row.repository,ref:row.id});return{repository,id:ref}});if(new Set(recordRefs.map((ref)=>JSON.stringify([ref.repository,ref.id]))).size!==recordRefs.length)fail("Ask Record references contain duplicates");return{kind:"ask",...itemPresentation,questions,tags,recordRefs,recipients:[...new Set([...extra,...questions.flatMap((entry)=>[entry.to,...entry.allowedResponders])])]}}function continueAsk(value){const source=object(value,"continueAsk");keys(source,[],"continueAsk");return{type:"continue"}}function resolution(value){const source=object(value,"resolution");keys(source,["outcome","evidence"],"resolution");return{outcome:text(source.outcome,"outcome"),...source.evidence===undefined?{}:{evidence:array(source.evidence,"evidence").map((entry)=>serializable(entry))}}}function resolveAsk(value){return{type:"resolve",...resolution(value)}}function validateResolution(value){const source=object(value,"published resolution");keys(source,["expectedRevision","outcome","evidence"],"published resolution");if(!Number.isSafeInteger(source.expectedRevision)||source.expectedRevision<1)fail("Expected revision must be a positive integer");return{expectedRevision:source.expectedRevision,...resolution({outcome:source.outcome,...source.evidence===undefined?{}:{evidence:source.evidence}})}}function publicationRequestKey(value){const options=object(value,"publication options");keys(options,["requestKey"],"publication options");return id(options.requestKey,"publication request key")}function createInboxPublisher(transport){return{async publishAsk(value,options){const source=object(value,"ask");keys(source,["title","description","recipients","views","body","questions","notifyImmediately","tags","recordRefs"],"ask");const result=await transport.publish({requestKey:publicationRequestKey(options),item:enforcePublicationSize(validatePublication({...source,kind:"ask"}))});id(result.id,"published ask ID");if(!("revision"in result)||!Number.isSafeInteger(result.revision)||result.revision!==1)fail("Initial ask publication must return revision 1");return{id:result.id,revision:result.revision}},async publishDigest(value,options){const source=object(value,"digest");keys(source,["title","description","recipients","views","body","notifyImmediately"],"digest");const result=await transport.publish({requestKey:publicationRequestKey(options),item:enforcePublicationSize(validatePublication({...source,kind:"digest"}))});return{id:id(result.id,"published digest ID")}},async publishResolution(askId,value){await transport.resolve({askId:id(askId,"ask ID"),resolution:validateResolution(value)})}}}var ROUTINE_DECLARATION_SCHEMA="https://schemas.oddington.ai/routine/v1.json";var ROUTINE_SOURCE_LIMITS={files:20000,bytes:256*1024*1024,declarationBytes:64*1024};var invalid=(field)=>{throw new Error(`Invalid routine declaration: ${field}`)};var object2=(value,fields2,field)=>{if(!value||typeof value!=="object"||Array.isArray(value)||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||!fields2.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))invalid(field);return value};var routineAlias=(value)=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(value);var list=(value,field,allowed,qualified=false)=>{if(value===undefined)return[];if(!Array.isArray(value)||value.length>64||value.some((item)=>!(routineAlias(item)||qualified&&typeof item==="string"&&item.split("/").length===2&&item.split("/").every(routineAlias))||allowed&&!allowed.includes(item))||new Set(value).size!==value.length)invalid(field);return[...value].sort()};function routineAssetPattern(value){return typeof value==="string"&&value.length<=512&&!value.startsWith("/")&&!value.includes("\\")&&!value.includes(":")&&value.split("/").every((part)=>!!part&&part!=="."&&part!==".."&&/^[a-zA-Z0-9_.*-]+$/.test(part))}function parseRoutineDeclaration(value){const v=object2(value,["$schema","access","runtime","retry","assets"],"fields");if(v.$schema!==ROUTINE_DECLARATION_SCHEMA)invalid("$schema");const access=object2(v.access===undefined?{}:v.access,["repositories","connections","ai","files","publish"],"access");if(Object.hasOwn(access,"ai")&&access.ai!==true)invalid("access.ai");const rawRepositories=access.repositories===undefined?{}:access.repositories;const repositories=object2(rawRepositories,rawRepositories&&typeof rawRepositories==="object"?Object.keys(rawRepositories):[],"access.repositories");if(Object.keys(repositories).length>64)invalid("access.repositories");const grants={};for(const key of Object.keys(repositories).sort()){if(!routineAlias(key)||!["read","write"].includes(repositories[key]))invalid(`access.repositories.${key}`);grants[key]=repositories[key]}if(access.files!==undefined&&!["read","read-write"].includes(access.files))invalid("access.files");const runtime=object2(v.runtime===undefined?{}:v.runtime,["features","resources","maxDuration"],"runtime");if(runtime.features!==undefined&&(!Array.isArray(runtime.features)||runtime.features.length!==0))invalid("runtime.features");if(runtime.resources!==undefined&&runtime.resources!=="standard")invalid("runtime.resources");if(runtime.maxDuration!==undefined&&!["15m","60m"].includes(runtime.maxDuration))invalid("runtime.maxDuration");const retry=object2(v.retry===undefined?{}:v.retry,["maxAttempts"],"retry");if(retry.maxAttempts!==undefined&&retry.maxAttempts!==1)invalid("retry.maxAttempts");const assets=v.assets===undefined?[]:v.assets;if(!Array.isArray(assets)||assets.length>64||assets.some((item)=>!routineAssetPattern(item))||new Set(assets).size!==assets.length)invalid("assets");return{$schema:ROUTINE_DECLARATION_SCHEMA,access:{repositories:grants,connections:list(access.connections,"access.connections",undefined,true),...access.ai===true?{ai:true}:{},...access.files===undefined?{}:{files:access.files},publish:list(access.publish,"access.publish",["asks","digests"])},runtime:{features:[],resources:"standard",maxDuration:runtime.maxDuration??"60m"},retry:{maxAttempts:1},assets:[...assets].sort()}}var LOCAL_ROUTINE_VALUE_BYTES=256*1024;function hasLocalRoutineFileInput(schema){if(schema.type==="file")return schema.storage==="local";if(schema.type==="array")return hasLocalRoutineFileInput(schema.items);return schema.type==="object"&&Object.values(schema.properties).some(hasLocalRoutineFileInput)}function nextRoutineScheduleOccurrence(schedule,after){const{CronExpressionParser}=require_CronExpressionParser();const fields2=typeof schedule.cron==="string"?schedule.cron.trim().split(/\s+/):[];if(fields2.length!==5||fields2.some((field)=>!/^[\d*,/A-Za-z-]+$/.test(field))||fields2.some((field)=>/[A-Za-z]/.test(field)&&!/^(?:[A-Za-z]{3}|[\d*,/-])+$/.test(field))||typeof schedule.timezone!=="string"||!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)*$/.test(schedule.timezone)||!Number.isFinite(after.getTime()))throw new Error("Invalid routine schedule");new Intl.DateTimeFormat("en",{timeZone:schedule.timezone});const endDate=new Date(after);endDate.setUTCFullYear(endDate.getUTCFullYear()+8);endDate.setUTCDate(endDate.getUTCDate()+2);const expression=CronExpressionParser.parse(fields2.join(" "),{currentDate:after,endDate,tz:schedule.timezone});const next=expression.next().toDate();if(!(next.getTime()>after.getTime())||next>endDate)throw new Error("Invalid routine schedule occurrence");return next}var invalid2=()=>{throw new AppRoutineContractError("invalid_value")};var invalidContract2=()=>{throw new AppRoutineContractError("invalid_contract")};var routineTitle=(value)=>typeof value==="string"&&value.trim().length>0&&value.length<=256;function freezeRoutineMetadata(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))freezeRoutineMetadata(child);Object.freeze(value)}return value}function assertRoutineJson(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!value||typeof value!=="object"||ancestors.has(value))return invalid2();const array2=Array.isArray(value);if(!array2&&Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)return invalid2();const keys2=Reflect.ownKeys(value);if(array2&&(keys2.length!==value.length+1||!Array.from({length:value.length},(_,index)=>Object.hasOwn(value,index)).every(Boolean)))return invalid2();ancestors.add(value);for(const key of keys2){if(array2&&key==="length")continue;if(typeof key!=="string")return invalid2();const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!Object.hasOwn(descriptor,"value"))return invalid2();assertRoutineJson(descriptor.value,ancestors)}ancestors.delete(value)}function assertRoutineFields(value,allowed){if(!value||typeof value!=="object"||Object.getPrototypeOf(value)!==Object.prototype||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||allowed&&!allowed.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))return invalidContract2()}function parseRoutineAccess(value){try{if(value!==undefined)assertRoutineJson(value);assertRoutineFields(value??{},["repositories","connections","ai","files","publish"]);const access=value;const names=access?.connections??[];if(!Array.isArray(names)||names.length>64||new Set(names).size!==names.length||names.some((name)=>typeof name!=="string"||name.split("/").length!==2||name.split("/").some((part)=>!isAppRoutineName(part))))return invalidContract2();const parsed=parseRoutineDeclaration({$schema:ROUTINE_DECLARATION_SCHEMA,access:{...access,connections:[]}}).access;return freezeRoutineMetadata({...parsed,connections:[...names]})}catch{return invalidContract2()}}function routineScheduleMetadata(value,input,hasDefault){try{assertRoutineFields(value,["cron","timezone"]);assertRoutineJson(value);if(!hasDefault||hasLocalRoutineFileInput(input))return invalidContract2();const schedule={cron:value.cron,timezone:value.timezone};nextRoutineScheduleOccurrence(schedule,new Date("2000-01-01T00:00:00Z"));return freezeRoutineMetadata(schedule)}catch{return invalidContract2()}}function parseRoutineAIOutputIssue(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const v=value;if(["invalid_json","invalid_response","empty_text","structured_output_limit"].includes(String(v.reason)))return Object.keys(v).join(",")==="reason"?{reason:v.reason}:undefined;if(!["missing_field","unexpected_field","wrong_type","out_of_bounds","invalid_file"].includes(String(v.reason))||typeof v.path!=="string"||v.path.length>256||!/^\$(?:\.[a-z][A-Za-z0-9]*|\[(?:0|[1-9][0-9]*)\])*$/.test(v.path)||!["object","array","boolean","string","integer","number","file"].includes(String(v.expected))||!["missing","null","object","array","boolean","string","number","other"].includes(String(v.received))||Object.keys(v).some((key)=>!["reason","path","expected","received","constraint","limit"].includes(key)))return;if(v.reason==="out_of_bounds"){if(!["maxLength","maxItems","minimum","maximum"].includes(String(v.constraint))||typeof v.limit!=="number"||!Number.isFinite(v.limit))return}else if(Object.hasOwn(v,"constraint")||Object.hasOwn(v,"limit"))return;return{reason:v.reason,path:v.path,expected:v.expected,received:v.received,...v.reason==="out_of_bounds"?{constraint:v.constraint,limit:v.limit}:{}}}function routineAIOutputMessage(issue){if(issue.reason==="structured_output_limit")return"AI couldn’t produce an answer matching the requested format within its submission limit.";if(issue.reason==="invalid_json")return"AI replied, but its answer could not be read as JSON.";if(issue.reason==="invalid_response")return"AI returned a response OS could not read.";if(issue.reason==="empty_text")return"AI returned an empty answer.";const field=issue.path==="$"?"response":issue.path.slice(issue.path.startsWith("$.")?2:1);const expected={object:"an object",array:"a list",boolean:"true or false",string:"text",integer:"a whole number",number:"a number",file:"a File"}[issue.expected];const received={missing:"a missing field",null:"null",object:"an object",array:"a list",boolean:"true or false",string:"text",number:"a number",other:"an unsupported value"}[issue.received];if(issue.reason==="missing_field")return`AI response is missing a required field.
21
+ `:""}${fileErrorExplanation(detail)}`}switch(error.code){case"invalid_input":return"The file request is invalid.";case"unsupported_context":return"This environment does not support this file operation.";case"unauthenticated":return"Sign in to OS before accessing files.";case"access_denied":return"You don’t have access to this file operation.";case"not_found":return"This file isn’t available in this workspace.";case"request_too_large":return"The file request exceeds the size limit.";case"conflict":return"The saved file or enrichment doesn’t match this request. Reload it before trying again.";case"local_only":return"This file is stored on a computer and isn’t available through remote storage.";case"integrity":return FILE_INTEGRITY_MESSAGE;case"capacity":return FILE_CAPACITY_MESSAGE;case"method_not_allowed":return"This request uses an unsupported file operation.";case"unavailable":return`OS couldn’t complete the file operation.${error.retryable?" Try again.":""}`}}class FileOperationError extends Error{code;status;retryable;detail;constructor(code,status,retryable=false,detail){const safe=fileErrorDetailForCode(code,detail);super(fileErrorMessage({code,retryable,detail:safe}));this.code=code;this.status=status;this.retryable=retryable;if(safe)this.detail=Object.freeze(safe);if(safe&&Object.hasOwn(localStorageReasons,safe.reason))this.retryable=false}}var FILE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var FILE_ORIGINAL_MAX_BYTES=5*1024**3;function parseFileDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const f=value;if(Object.keys(f).sort().join(",")!=="enrichments,id,mediaType,name,path,sha256,size"||typeof f.id!=="string"||!FILE_ID_PATTERN.test(f.id)||!safeFileName(f.name)||!safeFilePath(f.path)||!Number.isSafeInteger(f.size)||f.size<0||f.size>FILE_ORIGINAL_MAX_BYTES||typeof f.sha256!=="string"||!/^[0-9a-f]{64}$/.test(f.sha256)||!f.enrichments||typeof f.enrichments!=="object"||Array.isArray(f.enrichments)||!isCanonicalOriginalMediaType(f.mediaType))return invalid();for(const[name,descriptor]of Object.entries(f.enrichments)){if(!safeEnrichmentName(name))return invalid();parseEnrichmentDescriptor(descriptor)}if(new TextEncoder().encode(JSON.stringify(f)).byteLength>16*1024)return invalid();return f}function parseEnrichmentDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).sort().join(",")!=="mediaType,sha256,size"||!["application/octet-stream","text/plain","text/markdown","application/json"].includes(d.mediaType)||!Number.isSafeInteger(d.size)||d.size<0||d.size>16*1024*1024||typeof d.sha256!=="string"||!/^[0-9a-f]{64}$/.test(d.sha256))return invalid();return d}function safeEnrichmentName(value){return safeFileName(value)&&!/^original(?:\.|$)/i.test(value)}function parseFileEnrichMetadata(value,maxBytes){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).some((key)=>!["name","size","mediaType","replace"].includes(key)))return invalid();if(!safeEnrichmentName(d.name))return invalid("invalid_enrichment_name");if(!Number.isSafeInteger(d.size)||d.size<0)return invalid("invalid_size");if(d.mediaType!==undefined&&(typeof d.mediaType!=="string"||d.mediaType.length>255||/[\u0000-\u001f\u007f]/.test(d.mediaType)))return invalid("invalid_media_type");if(d.replace!==undefined&&(typeof d.replace!=="string"||!/^[0-9a-f]{64}$/.test(d.replace)))return invalid("invalid_replacement");if(d.size>maxBytes)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:maxBytes,receivedBytes:d.size});return d}function safeFileName(value){return typeof value==="string"&&value.length>0&&value.length<=255&&value===value.trim()&&value!=="."&&value!==".."&&!/[\u0000-\u001f\u007f-\u009f/\\:*?"<>|]/u.test(value)&&!/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(value)&&!/[. ]$/.test(value)&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value)}function safeFilePath(value){return typeof value==="string"&&value.length<=1024&&value.split("/").every(safeFileName)}function safeManagedFilePath(value){return safeFilePath(value)&&value.split("/")[0].toLowerCase()!==".os"}function declaredOriginalMediaType(value){if(typeof value!=="string"||value.length>255||/[\u0000-\u001f\u007f-\u009f]/.test(value))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_media_type"});const normalized=value.split(";",1)[0].trim().toLowerCase();const token="[a-z0-9!#$%&'+.^_`|~-]+";if(!new RegExp(`^${token}/${token}$`).test(normalized))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_media_type"});return normalized}function isCanonicalOriginalMediaType(value){try{return declaredOriginalMediaType(value)===value}catch{return false}}function parseFileUpdate(value){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const input=value,update={};if(!Object.keys(input).length||Object.keys(input).some((key)=>!["name","path","mediaType"].includes(key)))return invalid();if(Object.hasOwn(input,"name")){if(!safeFileName(input.name))return invalid("invalid_name");update.name=input.name}if(Object.hasOwn(input,"path")){if(!safeManagedFilePath(input.path))return invalid("invalid_path");update.path=input.path}if(Object.hasOwn(input,"mediaType"))update.mediaType=declaredOriginalMediaType(input.mediaType);return update}function parseFileCreateMetadata(value,maxBytes){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const input=value;if(Object.keys(input).some((key)=>!["name","path","storage","mediaType","size","requestKey"].includes(key)))return invalid();const path=input.path===undefined?"Files":input.path;if(!safeFileName(input.name))return invalid("invalid_name");if(!safeManagedFilePath(path))return invalid("invalid_path");if(input.storage!==undefined&&input.storage!=="remote"&&input.storage!=="local")return invalid("invalid_storage");const mediaType=input.mediaType===undefined?"application/octet-stream":declaredOriginalMediaType(input.mediaType);if(!Number.isSafeInteger(input.size)||input.size<0)return invalid("invalid_size");if(input.size>maxBytes)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:maxBytes,receivedBytes:input.size});if(typeof input.requestKey!=="string"||input.requestKey.length<1||input.requestKey.length>256||input.requestKey!==input.requestKey.trim()||/[\u0000-\u001f\u007f]/.test(input.requestKey))return invalid("invalid_request_key");return{name:input.name,path,...input.storage?{storage:input.storage}:{},mediaType,size:input.size,requestKey:input.requestKey}}class AppRoutineContractError extends Error{code;constructor(code){super(code);this.code=code}}var propertyName=/^[a-z][A-Za-z0-9]*(?![\s\S])/;var stepId=/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/;var routineName=/^[a-z0-9][a-z0-9-]{0,62}(?![\s\S])/;function isAppRoutineName(value){return typeof value==="string"&&routineName.test(value)}var owns=(value,key)=>Object.hasOwn(value,key);var invalidContract=()=>{throw new AppRoutineContractError("invalid_contract")};var invalidValue=()=>{throw new AppRoutineContractError("invalid_value")};function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null)}function fields(value,required,optional=[]){return required.every((key)=>owns(value,key))&&Object.keys(value).every((key)=>required.includes(key)||optional.includes(key))}function denseArray(value){return Array.isArray(value)&&Object.keys(value).length===value.length&&Array.from({length:value.length},(_,index)=>owns(value,String(index))).every(Boolean)}function parseAppRoutineContract(value){let properties=0;function schema(value2,depth=1){if(depth>8||!record(value2))return invalidContract();switch(value2.type){case"object":{if(!fields(value2,["type","properties","additionalProperties"],["required"])||value2.additionalProperties!==false||!record(value2.properties))return invalidContract();const entries=Object.entries(value2.properties);properties+=entries.length;if(properties>64||entries.some(([key])=>!propertyName.test(key)))return invalidContract();let required;if(owns(value2,"required")){if(!denseArray(value2.required)||value2.required.some((key)=>typeof key!=="string"||!owns(value2.properties,key))||new Set(value2.required).size!==value2.required.length)return invalidContract();required=[...value2.required]}return{type:"object",properties:Object.fromEntries(entries.map(([key,child])=>[key,schema(child,depth+1)])),...required===undefined?{}:{required},additionalProperties:false}}case"array":if(!fields(value2,["type","items"],["maxItems"])||owns(value2,"maxItems")&&(!Number.isSafeInteger(value2.maxItems)||value2.maxItems<1))return invalidContract();return{type:"array",items:schema(value2.items,depth+1),...owns(value2,"maxItems")?{maxItems:value2.maxItems}:{}};case"boolean":if(!fields(value2,["type"]))return invalidContract();return{type:value2.type};case"file":if(!fields(value2,["type"],["storage","path"])||owns(value2,"storage")&&value2.storage!=="local"&&value2.storage!=="remote"||owns(value2,"path")&&!safeManagedFilePath(value2.path))return invalidContract();return{type:"file",...owns(value2,"storage")?{storage:value2.storage}:{},...owns(value2,"path")?{path:value2.path}:{}};case"string":if(!fields(value2,["type"],["maxLength"])||owns(value2,"maxLength")&&(!Number.isSafeInteger(value2.maxLength)||value2.maxLength<0||value2.maxLength>4096))return invalidContract();return{type:"string",...owns(value2,"maxLength")?{maxLength:value2.maxLength}:{}};case"integer":case"number":{const validNumber=value2.type==="integer"?Number.isSafeInteger:Number.isFinite;if(!fields(value2,["type"],["minimum","maximum"])||owns(value2,"minimum")&&!validNumber(value2.minimum)||owns(value2,"maximum")&&!validNumber(value2.maximum)||owns(value2,"minimum")&&owns(value2,"maximum")&&value2.minimum>value2.maximum)return invalidContract();return{type:value2.type,...owns(value2,"minimum")?{minimum:value2.minimum}:{},...owns(value2,"maximum")?{maximum:value2.maximum}:{}}}default:return invalidContract()}}if(!record(value)||!fields(value,["routine","input","steps"],["result"])||!isAppRoutineName(value.routine)||!denseArray(value.steps)||value.steps.length<1||value.steps.length>64)return invalidContract();const input=schema(value.input);const result=owns(value,"result")?schema(value.result):undefined;const ids=new Set;const steps=value.steps.map((step)=>{if(!record(step)||!fields(step,["id"],["summary"])||typeof step.id!=="string"||!stepId.test(step.id)||ids.has(step.id))return invalidContract();ids.add(step.id);return{id:step.id,...owns(step,"summary")?{summary:schema(step.summary)}:{}}});return{routine:value.routine,input,steps,...result===undefined?{}:{result}}}function jsonData(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!record(value)&&!denseArray(value))return invalidValue();if(ancestors.has(value))return invalidValue();ancestors.add(value);for(const child of Object.values(value))jsonData(child,ancestors);ancestors.delete(value)}function validateRoutineSchemaValue(schema,value,rejected){const type=(value2)=>value2===null?"null":Array.isArray(value2)?"array":["object","boolean","string","number"].includes(typeof value2)?typeof value2:"other";function check(schema2,value2,path){const fail=(reason,extra={})=>{rejected?.({reason,path:path.length<=256?path:"$",expected:schema2.type,received:type(value2),...extra});return invalidValue()};switch(schema2.type){case"object":if(!record(value2))return fail("wrong_type");for(const key of schema2.required??[])if(!owns(value2,key))return fail("missing_field",{path:`${path}.${key}`.length<=256?`${path}.${key}`:"$",expected:schema2.properties[key].type,received:"missing"});if(Object.keys(value2).some((key)=>!owns(schema2.properties,key)))return fail("unexpected_field");for(const[key,child]of Object.entries(value2))check(schema2.properties[key],child,`${path}.${key}`);return;case"array":if(!denseArray(value2))return fail("wrong_type");if(schema2.maxItems!==undefined&&value2.length>schema2.maxItems)return fail("out_of_bounds",{constraint:"maxItems",limit:schema2.maxItems});value2.forEach((child,index)=>check(schema2.items,child,`${path}[${index}]`));return;case"boolean":if(typeof value2!=="boolean")return fail("wrong_type");return;case"string":if(typeof value2!=="string")return fail("wrong_type");if(Array.from(value2).length>(schema2.maxLength??4096))return fail("out_of_bounds",{constraint:"maxLength",limit:schema2.maxLength??4096});return;case"integer":case"number":if(typeof value2!=="number"||!(schema2.type==="integer"?Number.isSafeInteger(value2):Number.isFinite(value2)))return fail("wrong_type");if(schema2.minimum!==undefined&&value2<schema2.minimum)return fail("out_of_bounds",{constraint:"minimum",limit:schema2.minimum});if(schema2.maximum!==undefined&&value2>schema2.maximum)return fail("out_of_bounds",{constraint:"maximum",limit:schema2.maximum});return;case"file":{let file;try{jsonData(value2);file=parseFileDescriptor(value2)}catch{return fail("invalid_file")}if(schema2.path!==undefined&&file.path!==schema2.path)return fail("invalid_file")}}}check(schema,value,"$")}function validRecordRef(value){return typeof value==="string"&&value.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(value)}function validDropboxRootPath(value){return value===""||typeof value==="string"&&value.length<=2048&&value.startsWith("/")&&!/[\\\x00-\x1f\x7f]/.test(value)&&value.slice(1).split("/").every((segment)=>segment.length>0&&segment.trim()===segment&&segment!=="."&&segment!=="..")}function validMicrosoftId(value){return typeof value==="string"&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)}function validMicrosoftMailbox(value){return typeof value==="string"&&value.length<=254&&/^[^\s@/?#\\\x00-\x1f\x7f]+@[^\s@/?#\\\x00-\x1f\x7f]+\.[^\s@/?#\\\x00-\x1f\x7f]+$/.test(value)}function sharePointHost(value){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.sharepoint\.com$/.test(value)}function canonicalSharePointSiteUrl(value){if(typeof value!=="string"||value.length>2048||/[\s\\?#\x00-\x1f\x7f]/.test(value)||!/^https:\/\/[^/:@]+(?:\/|$)/i.test(value))return;try{const url=new URL(value);if(url.protocol!=="https:"||!sharePointHost(url.hostname)||url.username||url.password||url.port)return;const rawPath=value.replace(/^https:\/\/[^/]+/i,"")||"/";const path=rawPath.endsWith("/")?rawPath.slice(0,-1):rawPath;const segments=path.slice(1).split("/");if(path&&segments.some((segment)=>!segment))return;const encoded=path?segments.map((segment)=>{const decoded=decodeURIComponent(segment);if(decoded==="."||decoded===".."||/[/%\\?#\x00-\x1f\x7f]/.test(decoded))throw new Error;return encodeURIComponent(decoded)}).join("/"):"";const canonical=`https://${url.hostname}/${encoded}`;return canonical.length<=2048?canonical:undefined}catch{return}}function validSharePointSiteId(value,siteUrl){if(typeof value!=="string"||value.length>512)return false;const[host,collection,site,extra]=value.split(",");return extra===undefined&&host===new URL(siteUrl).hostname&&validMicrosoftId(collection)&&validMicrosoftId(site)}function validGoogleScopes(value){return Array.isArray(value)&&value.length>0&&value.length<=32&&value.every((scope)=>typeof scope==="string"&&scope.length<=256&&/^(https:\/\/www\.googleapis\.com\/auth\/[A-Za-z0-9._-]+|https:\/\/mail\.google\.com\/|openid|email|profile)$/.test(scope))&&new Set(value).size===value.length}var DROPBOX_FILE_SCOPES=["account_info.read","files.metadata.read","files.content.read","files.content.write"];function validDropboxFileScopes(value){return Array.isArray(value)&&value.length===DROPBOX_FILE_SCOPES.length&&new Set(value).size===value.length&&DROPBOX_FILE_SCOPES.every((scope)=>value.includes(scope))}function validDataRepositoryName(value){return typeof value==="string"&&/^[a-z0-9][a-z0-9._-]{0,127}$/.test(value)&&!value.includes("..")}class InboxContractError extends Error{constructor(message){super(message);this.name="InboxContractError"}}var INBOX_PUBLICATION_ITEM_BYTES=1024*1024;var INBOX_PUBLICATION_REQUEST_BYTES=INBOX_PUBLICATION_ITEM_BYTES+4096;var publicationAdvice="Trim the content, or attach long reports, data, and supporting materials as files instead. Then try again.";var INBOX_PUBLICATION_TOO_LARGE=`Your Inbox item failed to publish. Its content exceeds the 1 MB limit. ${publicationAdvice}`;class InboxPublicationSizeError extends InboxContractError{kind;bytes;constructor(kind,bytes){const label=kind==="ask"?"Ask":"Digest";const size=Math.ceil(bytes/INBOX_PUBLICATION_ITEM_BYTES*100)/100;super(`Your ${label} failed to publish. Its content is ${size} MB, which exceeds the 1 MB limit. ${publicationAdvice}`);this.kind=kind;this.bytes=bytes;this.name="InboxPublicationSizeError"}}function enforcePublicationSize(value){const bytes=new TextEncoder().encode(JSON.stringify(value)).byteLength;if(bytes>INBOX_PUBLICATION_ITEM_BYTES)throw new InboxPublicationSizeError(value.kind,bytes);return value}function fail(message){throw new InboxContractError(message)}function object(value,label){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))fail(`${label} must be a plain object`);return value}function keys(value,allowed,label){for(const key of Reflect.ownKeys(value)){if(typeof key!=="string"||!allowed.includes(key))fail(`${label} does not support ${String(key)}`);const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!("value"in descriptor))fail(`${label} must contain only JSON data`)}}function text(value,label){if(typeof value!=="string"||!value.trim())fail(`${label} must be nonempty text`);return value}function id(value,label){const result=text(value,label);if(result!==result.trim())fail(`${label} cannot have surrounding whitespace`);return result}function array(value,label){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype||Reflect.ownKeys(value).length!==value.length+1)fail(`${label} must be a dense array`);for(let index=0;index<value.length;index+=1){const descriptor=Object.getOwnPropertyDescriptor(value,String(index));if(!descriptor?.enumerable||!("value"in descriptor))fail(`${label} must contain only JSON data`)}return value}function distinctIds(value,label,nonempty=true){const result=array(value,label).map((entry)=>id(entry,label));if(nonempty&&!result.length)fail(`${label} must not be empty`);if(new Set(result).size!==result.length)fail(`${label} contains duplicate IDs`);return result}var memberEmail=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function personReference(value,label){const result=id(value,label);return memberEmail.test(result)?result.toLowerCase():result}function distinctPeople(value,label,nonempty=true){const result=array(value,label).map((entry)=>personReference(entry,label));if(nonempty&&!result.length)fail(`${label} must not be empty`);if(new Set(result).size!==result.length)fail(`${label} contains duplicate IDs`);return result}function serializable(value,ancestors=new Set){if(value===null||typeof value==="boolean"||typeof value==="string")return value;if(typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object")fail("Input must be losslessly serializable JSON");if(ancestors.has(value))fail("Input cannot contain cycles");ancestors.add(value);try{if(Array.isArray(value)){array(value,"JSON array");return value.map((entry)=>serializable(entry,ancestors))}const source=object(value,"JSON input");keys(source,Object.keys(source),"JSON input");return Object.fromEntries(Object.entries(source).map(([key,entry])=>[key,serializable(entry,ancestors)]))}finally{ancestors.delete(value)}}function natural(value,label,minimum=0){if(!Number.isSafeInteger(value)||value<minimum)fail(`${label} must be an integer >= ${minimum}`);return value}function validateInboxFile(value){const v=object(serializable(value),"Inbox file");keys(v,["id","name","mediaType","size","sha256"],"Inbox file");const fileId=id(v.id,"Inbox file ID"),name=id(v.name,"filename"),mediaType=id(v.mediaType,"media type");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(fileId)||/[\x00-\x1f\x7f/\\]/.test(name)||!isCanonicalOriginalMediaType(mediaType)||typeof v.sha256!=="string"||!/^[0-9a-f]{64}$/.test(v.sha256))fail("Invalid Inbox file identity or metadata");const size=natural(v.size,"file size");if(size>FILE_ORIGINAL_MAX_BYTES)fail("File exceeds supported size");return{id:fileId,name,mediaType,size,sha256:v.sha256}}function validateQualifiedRecordRef(value){const r=object(value,"Record reference");keys(r,["repository","ref"],"Record reference");if(!validDataRepositoryName(r.repository)||!validRecordRef(r.ref))fail("Invalid qualified Record reference");return{repository:r.repository,ref:r.ref}}function validateBlock(value){const b=object(serializable(value),"Block");if(b.kind==="rich-text"){keys(b,["kind","markdown"],"Rich text Block");return{kind:"rich-text",markdown:text(b.markdown,"Markdown")}}if(b.kind==="asks"){keys(b,["kind","problem","asks"],"Asks Block");const asks=distinctIds(b.asks,"Ask IDs");if(asks.some((ask)=>!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(ask)))fail("Invalid Ask ID");return{kind:"asks",problem:text(b.problem,"problem"),asks}}if(!["record","records","files"].includes(b.kind))fail("Unknown Block kind");keys(b,["kind","label","initiallyExpanded",...b.kind==="record"?["record"]:b.kind==="records"?["records"]:["files"]],"Block");const label=text(b.label,"Block label");if(b.initiallyExpanded!==undefined&&typeof b.initiallyExpanded!=="boolean")fail("Invalid initiallyExpanded");const expanded=b.initiallyExpanded===undefined?{}:{initiallyExpanded:b.initiallyExpanded};if(b.kind==="record")return{kind:"record",label,record:validateQualifiedRecordRef(b.record),...expanded};if(b.kind==="records"){const records=array(b.records,"records").map(validateQualifiedRecordRef);if(!records.length||new Set(records.map((r)=>JSON.stringify([r.repository,r.ref]))).size!==records.length)fail("Empty or duplicate records");return{kind:"records",label,records,...expanded}}const files=array(b.files,"files").map(validateInboxFile);if(!files.length||new Set(files.map((file)=>file.id)).size!==files.length)fail("Empty or duplicate files");return{kind:"files",label,files,...expanded}}function richTextBlock(value){return validateBlock({...value,kind:"rich-text"})}function recordBlock(value){return validateBlock({...value,kind:"record"})}function recordsBlock(value){return validateBlock({...value,kind:"records"})}function fileBlock(value){const input=object(serializable(value),"Files Block");const files=array(input.files,"files").map((entry)=>{const descriptor=object(entry,"File");if(!(("path"in descriptor)||("enrichments"in descriptor)))return validateInboxFile(descriptor);let file;try{file=parseFileDescriptor(descriptor)}catch{return fail("Invalid shared File descriptor")}const{id:id2,name,mediaType,size,sha256}=file;return{id:id2,name,mediaType,size,sha256}});return validateBlock({...input,kind:"files",files})}function asksBlock(value){return validateBlock({...value,kind:"asks"})}function selection(value){const input=object(value,"selection");keys(input,["source"],"selection");return validateResponseDefinition({type:"selection",source:input.source})}function validateAuthoredSource(value){const source=object(value,"response definition");keys(source,["type","options","suggestions","search"],"response definition");if(source.type!=="authored")fail("Expected authored options");const options=array(source.options,"options").map((entry)=>{const option=object(entry,"choice");keys(option,["value","label","description","note"],"choice");let note;if(option.note!==undefined){const declaration=object(option.note,"choice note");keys(declaration,["placeholder"],"choice note");note={placeholder:text(declaration.placeholder,"note placeholder")}}return{value:id(option.value,"choice value"),label:text(option.label,"choice label"),...option.description===undefined?{}:{description:text(option.description,"choice description")},...note?{note}:{}}});if(!options.length)fail("Choices require at least one option");if(new Set(options.map((option)=>option.value)).size!==options.length)fail("Duplicate choice value");if(Object.hasOwn(source,"search")||Object.hasOwn(source,"suggestions")){const labels=object(source.search,"choice search");keys(labels,["triggerLabel","placeholder","emptyLabel"],"choice search");const search={triggerLabel:text(labels.triggerLabel,"search trigger label"),placeholder:text(labels.placeholder,"search placeholder"),emptyLabel:text(labels.emptyLabel,"search empty label")};const suggestions=array(source.suggestions,"suggestions").map((value2)=>id(value2,"suggestion value"));if(suggestions.length>8||new Set(suggestions).size!==suggestions.length||suggestions.some((value2)=>!options.some((option)=>option.value===value2)))fail("Search permits at most eight unique published suggestions");return{type:"authored",options,suggestions,search}}if(options.length>9)fail("Choices require one to nine options");return{type:"authored",options}}function validateRecordReference(value){const row=object(value,"Record reference");keys(row,["repository","ref"],"Record reference");const repository=id(row.repository,"repository"),ref=id(row.ref,"Record reference");if(!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(repository)||/\.\.|\/\//.test(repository)||ref.length>512||!/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(ref))fail("Invalid Record identity");return{repository,ref}}function validateRecordSource(value){const source=object(value,"Record selection");keys(source,["type","collection","refPrefix","where","display","suggestions"],"Record selection");if(source.type!=="records")fail("Expected Record options");const collection=object(source.collection,"collection");keys(collection,["repository","name"],"collection");const repository=validateRecordReference({repository:collection.repository,ref:"records/example"}).repository;const name=id(collection.name,"collection name");if(!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(name))fail("Invalid collection name");const refPrefix=source.refPrefix===undefined?undefined:id(source.refPrefix,"Record reference prefix");if(refPrefix!==undefined&&(!refPrefix.endsWith("/")||refPrefix.length>512||!/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(refPrefix)))fail("Invalid Record reference prefix");const where=object(source.where??{},"Record filter");const fieldName=(name2)=>/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2)&&!["constructor","prototype"].includes(name2);for(const[name2,value2]of Object.entries(where)){if(!fieldName(name2)||!(value2===null||["string","number","boolean"].includes(typeof value2))||typeof value2==="number"&&!Number.isFinite(value2))fail("Record filters require scalar equality")}const display=object(source.display,"Record display");keys(display,["labelFields"],"Record display");const labelFields=distinctIds(display.labelFields,"label fields");if(labelFields.length>2||labelFields.some((name2)=>!fieldName(name2)))fail("Select one or two scalar label fields");const suggestions=array(source.suggestions??[],"suggestions").map((value2)=>{const entry=object(value2,"suggestion");keys(entry,["record","reason"],"suggestion");const record2=validateRecordReference(entry.record);if(record2.repository!==repository)fail("Suggestion belongs to another repository");return{record:record2,...entry.reason===undefined?{}:{reason:text(entry.reason,"suggestion reason")}}});if(suggestions.length>8||new Set(suggestions.map((entry)=>entry.record.ref)).size!==suggestions.length)fail("Record selection permits at most eight unique suggestions");return{type:"records",collection:{repository,name},...refPrefix?{refPrefix}:{},where:{...where},display:{labelFields},suggestions}}function validateResponseDefinition(value){const definition=object(value,"response definition");keys(definition,["type","source"],"response definition");if(definition.type!=="selection")fail("Expected a selection definition");const source=object(definition.source,"option source");switch(source.type){case"authored":return{type:"selection",source:validateAuthoredSource(source)};case"records":return{type:"selection",source:validateRecordSource(source)};default:return fail("Unsupported option source")}}function handlerReference(value){const source=object(value,"handler reference");keys(source,["id","input"],"handler reference");return{id:id(source.id,"handler ID"),input:serializable(source.input)}}function defineHandler(value){const source=object(value,"handler");keys(source,["id","results","run"],"handler");const stable=(value2)=>typeof value2==="string"&&/^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);if(!stable(source.id))fail("Handler ID must be stable");const results=source.results===undefined?undefined:distinctIds(source.results,"handler results",false);if(results&&(results.length>64||results.some((result)=>!stable(result))))fail("Handler results must be stable IDs");if(typeof source.run!=="function")fail("Handler requires a run function");return Object.freeze({id:value.id,...results===undefined?{}:{results:Object.freeze(results.sort())},run:value.run})}function respond(handler,input){defineHandler(handler);return handlerReference({id:handler.id,input})}function question(value){const source=object(value,"question");keys(source,["id","to","allowedResponders","prompt","instructions","response","handler"],"question");const to=personReference(source.to,"question assignee");const allowedResponders=source.allowedResponders===undefined?[to]:distinctPeople(source.allowedResponders,"allowed responders");if(!allowedResponders.includes(to))fail("Allowed responders must include the assignee");return{id:id(source.id,"question ID"),to,allowedResponders,prompt:text(source.prompt,"question prompt"),...source.instructions===undefined?{}:{instructions:text(source.instructions,"instructions")},response:validateResponseDefinition(source.response),...Object.hasOwn(source,"handler")?{handler:handlerReference(source.handler)}:{}}}function presentation(source){const views=source.views===undefined?[]:array(source.views,"views").map((entry)=>{const view=object(entry,"view");keys(view,["id","view","input"],"view");return{id:id(view.id,"view ID"),view:id(view.view,"view name"),input:serializable(view.input)}});if(new Set(views.map((view)=>view.id)).size!==views.length)fail("Duplicate view ID");const body=source.body===undefined?[]:array(source.body,"body").map(validateBlock);return{title:text(source.title,"title"),description:text(source.description,"description"),views,body}}function validatePublication(value){const source=object(value,"publication");if(source.kind!=="ask"&&source.kind!=="digest")fail("Publication requires an explicit kind");keys(source,["kind","title","description","recipients","views","body","notifyImmediately",...source.kind==="ask"?["questions","tags","recordRefs"]:[]],"publication");if(source.notifyImmediately!==undefined&&typeof source.notifyImmediately!=="boolean")fail("notifyImmediately must be a boolean");const itemPresentation={...presentation(source),...source.notifyImmediately===undefined?{}:{notifyImmediately:source.notifyImmediately}};const linkedAsks=(itemPresentation.body??[]).flatMap((block)=>block.kind==="asks"?block.asks:[]);if(new Set(linkedAsks).size!==linkedAsks.length)fail("Ask belongs to more than one problem");if(source.kind==="digest")return{kind:"digest",...itemPresentation,recipients:distinctPeople(source.recipients,"digest recipients")};if(itemPresentation.body?.some((block)=>block.kind==="asks"))fail("Asks Blocks belong to Digests");const questions=array(source.questions===undefined?[]:source.questions,"questions").map((value2)=>question(value2));if(new Set(questions.map((entry)=>entry.id)).size!==questions.length)fail("Duplicate question ID");const extra=source.recipients===undefined?[]:distinctPeople(source.recipients,"recipients",false);if(!questions.length&&!extra.length)fail("Ask requires at least one recipient");const tags=array(source.tags===undefined?[]:source.tags,"Ask tags").map((value2)=>{const tag=text(value2,"Ask tag");if(new TextEncoder().encode(tag).byteLength>64)fail("Ask tag exceeds 64 UTF-8 bytes");return tag});if(tags.length>32||new Set(tags).size!==tags.length)fail("Ask tags exceed bounds or contain duplicates");const recordRefs=array(source.recordRefs===undefined?[]:source.recordRefs,"Ask Record references").map((value2)=>{const row=object(value2,"Ask Record reference");keys(row,["repository","id"],"Ask Record reference");const{repository,ref}=validateRecordReference({repository:row.repository,ref:row.id});return{repository,id:ref}});if(new Set(recordRefs.map((ref)=>JSON.stringify([ref.repository,ref.id]))).size!==recordRefs.length)fail("Ask Record references contain duplicates");return{kind:"ask",...itemPresentation,questions,tags,recordRefs,recipients:[...new Set([...extra,...questions.flatMap((entry)=>[entry.to,...entry.allowedResponders])])]}}function continueAsk(value){const source=object(value,"continueAsk");keys(source,[],"continueAsk");return{type:"continue"}}function resolution(value){const source=object(value,"resolution");keys(source,["outcome","evidence"],"resolution");return{outcome:text(source.outcome,"outcome"),...source.evidence===undefined?{}:{evidence:array(source.evidence,"evidence").map((entry)=>serializable(entry))}}}function resolveAsk(value){return{type:"resolve",...resolution(value)}}function validateResolution(value){const source=object(value,"published resolution");keys(source,["expectedRevision","outcome","evidence"],"published resolution");if(!Number.isSafeInteger(source.expectedRevision)||source.expectedRevision<1)fail("Expected revision must be a positive integer");return{expectedRevision:source.expectedRevision,...resolution({outcome:source.outcome,...source.evidence===undefined?{}:{evidence:source.evidence}})}}function publicationRequestKey(value){const options=object(value,"publication options");keys(options,["requestKey"],"publication options");return id(options.requestKey,"publication request key")}function createInboxPublisher(transport){return{async publishAsk(value,options){const source=object(value,"ask");keys(source,["title","description","recipients","views","body","questions","notifyImmediately","tags","recordRefs"],"ask");const result=await transport.publish({requestKey:publicationRequestKey(options),item:enforcePublicationSize(validatePublication({...source,kind:"ask"}))});id(result.id,"published ask ID");if(!("revision"in result)||!Number.isSafeInteger(result.revision)||result.revision!==1)fail("Initial ask publication must return revision 1");return{id:result.id,revision:result.revision}},async publishDigest(value,options){const source=object(value,"digest");keys(source,["title","description","recipients","views","body","notifyImmediately"],"digest");const result=await transport.publish({requestKey:publicationRequestKey(options),item:enforcePublicationSize(validatePublication({...source,kind:"digest"}))});return{id:id(result.id,"published digest ID")}},async publishResolution(askId,value){await transport.resolve({askId:id(askId,"ask ID"),resolution:validateResolution(value)})}}}var ROUTINE_DECLARATION_SCHEMA="https://schemas.oddington.ai/routine/v1.json";var ROUTINE_SOURCE_LIMITS={files:20000,bytes:256*1024*1024,declarationBytes:64*1024};var invalid=(field)=>{throw new Error(`Invalid routine declaration: ${field}`)};var object2=(value,fields2,field)=>{if(!value||typeof value!=="object"||Array.isArray(value)||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||!fields2.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))invalid(field);return value};var routineAlias=(value)=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(value);var list=(value,field,allowed,qualified=false)=>{if(value===undefined)return[];if(!Array.isArray(value)||value.length>64||value.some((item)=>!(routineAlias(item)||qualified&&typeof item==="string"&&item.split("/").length===2&&item.split("/").every(routineAlias))||allowed&&!allowed.includes(item))||new Set(value).size!==value.length)invalid(field);return[...value].sort()};function routineAssetPattern(value){return typeof value==="string"&&value.length<=512&&!value.startsWith("/")&&!value.includes("\\")&&!value.includes(":")&&value.split("/").every((part)=>!!part&&part!=="."&&part!==".."&&/^[a-zA-Z0-9_.*-]+$/.test(part))}function parseRoutineDeclaration(value){const v=object2(value,["$schema","access","runtime","retry","assets"],"fields");if(v.$schema!==ROUTINE_DECLARATION_SCHEMA)invalid("$schema");const access=object2(v.access===undefined?{}:v.access,["repositories","connections","ai","files","publish"],"access");if(Object.hasOwn(access,"ai")&&access.ai!==true)invalid("access.ai");const rawRepositories=access.repositories===undefined?{}:access.repositories;const repositories=object2(rawRepositories,rawRepositories&&typeof rawRepositories==="object"?Object.keys(rawRepositories):[],"access.repositories");if(Object.keys(repositories).length>64)invalid("access.repositories");const grants={};for(const key of Object.keys(repositories).sort()){if(!routineAlias(key)||!["read","write"].includes(repositories[key]))invalid(`access.repositories.${key}`);grants[key]=repositories[key]}if(access.files!==undefined&&!["read","read-write"].includes(access.files))invalid("access.files");const runtime=object2(v.runtime===undefined?{}:v.runtime,["features","resources","maxDuration"],"runtime");if(runtime.features!==undefined&&(!Array.isArray(runtime.features)||runtime.features.length!==0))invalid("runtime.features");if(runtime.resources!==undefined&&runtime.resources!=="standard")invalid("runtime.resources");if(runtime.maxDuration!==undefined&&!["15m","60m"].includes(runtime.maxDuration))invalid("runtime.maxDuration");const retry=object2(v.retry===undefined?{}:v.retry,["maxAttempts"],"retry");if(retry.maxAttempts!==undefined&&retry.maxAttempts!==1)invalid("retry.maxAttempts");const assets=v.assets===undefined?[]:v.assets;if(!Array.isArray(assets)||assets.length>64||assets.some((item)=>!routineAssetPattern(item))||new Set(assets).size!==assets.length)invalid("assets");return{$schema:ROUTINE_DECLARATION_SCHEMA,access:{repositories:grants,connections:list(access.connections,"access.connections",undefined,true),...access.ai===true?{ai:true}:{},...access.files===undefined?{}:{files:access.files},publish:list(access.publish,"access.publish",["asks","digests"])},runtime:{features:[],resources:"standard",maxDuration:runtime.maxDuration??"60m"},retry:{maxAttempts:1},assets:[...assets].sort()}}var LOCAL_ROUTINE_VALUE_BYTES=256*1024;function hasLocalRoutineFileInput(schema){if(schema.type==="file")return schema.storage==="local";if(schema.type==="array")return hasLocalRoutineFileInput(schema.items);return schema.type==="object"&&Object.values(schema.properties).some(hasLocalRoutineFileInput)}function nextRoutineScheduleOccurrence(schedule,after){const{CronExpressionParser}=require_CronExpressionParser();const fields2=typeof schedule.cron==="string"?schedule.cron.trim().split(/\s+/):[];if(fields2.length!==5||fields2.some((field)=>!/^[\d*,/A-Za-z-]+$/.test(field))||fields2.some((field)=>/[A-Za-z]/.test(field)&&!/^(?:[A-Za-z]{3}|[\d*,/-])+$/.test(field))||typeof schedule.timezone!=="string"||!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)*$/.test(schedule.timezone)||!Number.isFinite(after.getTime()))throw new Error("Invalid routine schedule");new Intl.DateTimeFormat("en",{timeZone:schedule.timezone});const endDate=new Date(after);endDate.setUTCFullYear(endDate.getUTCFullYear()+8);endDate.setUTCDate(endDate.getUTCDate()+2);const expression=CronExpressionParser.parse(fields2.join(" "),{currentDate:after,endDate,tz:schedule.timezone});const next=expression.next().toDate();if(!(next.getTime()>after.getTime())||next>endDate)throw new Error("Invalid routine schedule occurrence");return next}var invalid2=()=>{throw new AppRoutineContractError("invalid_value")};var invalidContract2=()=>{throw new AppRoutineContractError("invalid_contract")};var routineTitle=(value)=>typeof value==="string"&&value.trim().length>0&&value.length<=256;function freezeRoutineMetadata(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))freezeRoutineMetadata(child);Object.freeze(value)}return value}function assertRoutineJson(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!value||typeof value!=="object"||ancestors.has(value))return invalid2();const array2=Array.isArray(value);if(!array2&&Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)return invalid2();const keys2=Reflect.ownKeys(value);if(array2&&(keys2.length!==value.length+1||!Array.from({length:value.length},(_,index)=>Object.hasOwn(value,index)).every(Boolean)))return invalid2();ancestors.add(value);for(const key of keys2){if(array2&&key==="length")continue;if(typeof key!=="string")return invalid2();const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!Object.hasOwn(descriptor,"value"))return invalid2();assertRoutineJson(descriptor.value,ancestors)}ancestors.delete(value)}function assertRoutineFields(value,allowed){if(!value||typeof value!=="object"||Object.getPrototypeOf(value)!==Object.prototype||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||allowed&&!allowed.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))return invalidContract2()}function parseRoutineAccess(value){try{if(value!==undefined)assertRoutineJson(value);assertRoutineFields(value??{},["repositories","connections","ai","files","publish"]);const access=value;const names=access?.connections??[];if(!Array.isArray(names)||names.length>64||new Set(names).size!==names.length||names.some((name)=>typeof name!=="string"||name.split("/").length!==2||name.split("/").some((part)=>!isAppRoutineName(part))))return invalidContract2();const parsed=parseRoutineDeclaration({$schema:ROUTINE_DECLARATION_SCHEMA,access:{...access,connections:[]}}).access;return freezeRoutineMetadata({...parsed,connections:[...names]})}catch{return invalidContract2()}}function routineScheduleMetadata(value,input,hasDefault){try{assertRoutineFields(value,["cron","timezone"]);assertRoutineJson(value);if(!hasDefault||hasLocalRoutineFileInput(input))return invalidContract2();const schedule={cron:value.cron,timezone:value.timezone};nextRoutineScheduleOccurrence(schedule,new Date("2000-01-01T00:00:00Z"));return freezeRoutineMetadata(schedule)}catch{return invalidContract2()}}function parseRoutineAIOutputIssue(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const v=value;if(["invalid_json","invalid_response","empty_text","structured_output_limit"].includes(String(v.reason)))return Object.keys(v).join(",")==="reason"?{reason:v.reason}:undefined;if(!["missing_field","unexpected_field","wrong_type","out_of_bounds","invalid_file"].includes(String(v.reason))||typeof v.path!=="string"||v.path.length>256||!/^\$(?:\.[a-z][A-Za-z0-9]*|\[(?:0|[1-9][0-9]*)\])*$/.test(v.path)||!["object","array","boolean","string","integer","number","file"].includes(String(v.expected))||!["missing","null","object","array","boolean","string","number","other"].includes(String(v.received))||Object.keys(v).some((key)=>!["reason","path","expected","received","constraint","limit"].includes(key)))return;if(v.reason==="out_of_bounds"){if(!["maxLength","maxItems","minimum","maximum"].includes(String(v.constraint))||typeof v.limit!=="number"||!Number.isFinite(v.limit))return}else if(Object.hasOwn(v,"constraint")||Object.hasOwn(v,"limit"))return;return{reason:v.reason,path:v.path,expected:v.expected,received:v.received,...v.reason==="out_of_bounds"?{constraint:v.constraint,limit:v.limit}:{}}}function routineAIOutputMessage(issue){if(issue.reason==="structured_output_limit")return"AI couldn’t produce an answer matching the requested format within its submission limit.";if(issue.reason==="invalid_json")return"AI replied, but its answer could not be read as JSON.";if(issue.reason==="invalid_response")return"AI returned a response OS could not read.";if(issue.reason==="empty_text")return"AI returned an empty answer.";const field=issue.path==="$"?"response":issue.path.slice(issue.path.startsWith("$.")?2:1);const expected={object:"an object",array:"a list",boolean:"true or false",string:"text",integer:"a whole number",number:"a number",file:"a File"}[issue.expected];const received={missing:"a missing field",null:"null",object:"an object",array:"a list",boolean:"true or false",string:"text",number:"a number",other:"an unsupported value"}[issue.received];if(issue.reason==="missing_field")return`AI response is missing a required field.
22
22
  ${field}: expected ${expected}; the field was missing.`;if(issue.reason==="unexpected_field")return`AI response includes an unexpected field.
23
23
  ${field}: only the fields declared by the routine are allowed.`;if(issue.reason==="invalid_file")return`AI response contains an invalid File.
24
24
  ${field}: expected a valid File matching the routine's requirements.`;if(issue.reason==="out_of_bounds"){const constraint={maxLength:`at most ${issue.limit} characters`,maxItems:`at most ${issue.limit} items`,minimum:`a value of at least ${issue.limit}`,maximum:`a value of at most ${issue.limit}`}[issue.constraint];return`AI response is outside a permitted limit.
@@ -33,7 +33,7 @@ Set tools to true or false.`;case"tools_require_file":return`The AI request is i
33
33
  Using tools requires a File input.`;case"unsupported_media_type":return`AI couldn’t read this file.
34
34
  Its media type is ${detail.mediaType}, which this input path doesn’t support.
35
35
 
36
- Check the file’s stored media type before retrying. The model was not called.`}switch(code){case"access_denied":return"This routine doesn’t currently have permission to use AI.";case"capability_unavailable":return"AI is unavailable in this execution environment.";case"invalid_input":return"The AI request is invalid. Check its input, instructions and schema.";case"unsupported_file":return"AI couldn’t read this file in the requested format.";case"file_unavailable":return"AI couldn’t read or verify the file.";case"input_too_large":return"The AI input exceeds the size limit for this execution path.";case"output_too_large":return"The AI response exceeds the size limit for this execution path.";case"provider_failure":return"AI couldn’t complete the request. No more specific reason was recorded.";case"invalid_output":return"AI returned an answer OS could not accept.";case"cancelled":return"The AI operation was stopped before it completed."}}var ROUTINE_AI_VALUE_BYTES=256*1024;var ROUTINE_AI_RESULT_BYTES=6*ROUTINE_AI_VALUE_BYTES+1024;var ROUTINE_AI_EVIDENCE_BYTES=4*1024;var ROUTINE_AI_ERROR_CODES=["access_denied","capability_unavailable","invalid_input","unsupported_file","file_unavailable","input_too_large","output_too_large","provider_failure","invalid_output","cancelled"];class AIError extends Error{code;detail;constructor(code,options={}){const detail=parseRoutineAIErrorDetail(code,options.detail);super(routineAIErrorMessage(code,detail));this.code=code;this.name="AIError";if(detail)this.detail=Object.freeze(detail);if(code==="invalid_output"&&typeof options.text==="string"&&new TextEncoder().encode(options.text).byteLength<=ROUTINE_AI_VALUE_BYTES)Object.defineProperty(this,"text",{value:options.text})}}function parseRoutineAIError(value){try{const v=capture(value,"invalid_output","output_too_large",ROUTINE_AI_RESULT_BYTES);assertRoutineFields(v,["code","detail","text"]);if(!ROUTINE_AI_ERROR_CODES.includes(v.code))throw new Error;const detail=parseRoutineAIErrorDetail(v.code,v.detail);if(Object.hasOwn(v,"detail")&&!detail||Object.hasOwn(v,"text")&&(typeof v.text!=="string"||new TextEncoder().encode(v.text).byteLength>ROUTINE_AI_VALUE_BYTES)||v.code!=="invalid_output"&&Object.hasOwn(v,"text"))throw new Error;return new AIError(v.code,{detail,...v.text===undefined?{}:{text:v.text}})}catch{throw new AIError("invalid_output")}}function capture(value,invalid3,oversized,limit=ROUTINE_AI_VALUE_BYTES){try{assertRoutineJson(value);const encoded=JSON.stringify(value);if(new TextEncoder().encode(encoded).byteLength>limit)throw new AIError(oversized);return freezeRoutineMetadata(JSON.parse(encoded))}catch(error){if(error instanceof AIError)throw error;throw new AIError(invalid3)}}function parseRoutineAIRequest(value){const v=capture(value,"invalid_input","input_too_large");try{assertRoutineFields(v,v.kind==="generateObject"?["kind","instructions","input","schema","tools"]:["kind","instructions","input","tools"]);if(!["generateText","generateObject"].includes(v.kind)||typeof v.instructions!=="string"||!v.instructions.trim())throw new Error;const input=typeof v.input==="string"?v.input:parseFileDescriptor(v.input);if(Object.hasOwn(v,"tools")&&typeof v.tools!=="boolean")throw new AIError("invalid_input",{detail:{reason:"invalid_tools"}});if(v.tools===true&&typeof input==="string")throw new AIError("invalid_input",{detail:{reason:"tools_require_file"}});const tools=v.tools===true?{tools:true}:{};if(v.kind==="generateText")return freezeRoutineMetadata({kind:v.kind,instructions:v.instructions,input,...tools});const schema=parseAppRoutineContract({routine:"ai",input:v.schema,steps:[{id:"generate"}]}).input;return freezeRoutineMetadata({kind:v.kind,instructions:v.instructions,input,schema,...tools})}catch(error){if(error instanceof AIError)throw error;throw new AIError("invalid_input")}}function parseRoutineAIResult(request,value){let v;try{v=capture(value,"invalid_output","output_too_large",request.kind==="generateText"?ROUTINE_AI_RESULT_BYTES:ROUTINE_AI_VALUE_BYTES);assertRoutineFields(v,request.kind==="generateText"?["text"]:["object"]);if(request.kind==="generateText"){if(typeof v.text!=="string")throw new Error;return acceptText(request,v.text)}if(!Object.hasOwn(v,"object"))throw new Error}catch(error){if(error instanceof AIError)throw error;throw new AIError("invalid_output",{detail:{reason:"invalid_response"}})}validateObject(request.schema,v.object);return freezeRoutineMetadata({object:v.object})}function validateObject(schema,object3,text2){let detail={reason:"invalid_response"};try{validateRoutineSchemaValue(schema,object3,(issue)=>{detail=issue})}catch{throw new AIError("invalid_output",{...text2===undefined?{}:{text:text2},detail})}}function acceptText(request,text2){if(new TextEncoder().encode(text2).byteLength>ROUTINE_AI_VALUE_BYTES)throw new AIError("output_too_large");if(request.kind==="generateText"){if(!text2.trim())throw new AIError("invalid_output",{text:text2,detail:{reason:"empty_text"}});return freezeRoutineMetadata({text:text2})}let object3;const trimmed=text2.trim();const fenced=/^(`{3,}|~{3,})(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/i.exec(trimmed);try{object3=JSON.parse(fenced?fenced[2]:text2)}catch{throw new AIError("invalid_output",{text:text2,detail:{reason:"invalid_json"}})}validateObject(request.schema,object3,text2);return capture({object:object3},"invalid_output","output_too_large")}var ROUTINE_STEP_SUMMARY_BYTES=256*1024;var ROUTINE_STEP_OUTPUT_BYTES=1024*1024;function parseRoutineStepOutputDetail(value){const invalid3=()=>{throw new AppRoutineContractError("invalid_value")};assertRoutineFields(value,["step","sizeBytes","limitBytes","summaryBytes","dataBytes"]);const{step,sizeBytes,limitBytes,summaryBytes,dataBytes}=value;if(!isAppRoutineName(step)||![sizeBytes,limitBytes,summaryBytes,dataBytes].every((bytes)=>Number.isSafeInteger(bytes)&&bytes>0)||sizeBytes!==summaryBytes+dataBytes||limitBytes!==(summaryBytes>ROUTINE_STEP_SUMMARY_BYTES?ROUTINE_STEP_SUMMARY_BYTES:ROUTINE_STEP_OUTPUT_BYTES)||(limitBytes===ROUTINE_STEP_SUMMARY_BYTES?summaryBytes:sizeBytes)<=limitBytes)return invalid3();return freezeRoutineMetadata({step,sizeBytes,limitBytes,summaryBytes,dataBytes})}function routineStepOutputMessage(value){const detail=parseRoutineStepOutputDetail(value);const size=`${(detail.sizeBytes/(1024*1024)).toFixed(1)} MB`;const bound=detail.limitBytes===ROUTINE_STEP_SUMMARY_BYTES?`, including ${(detail.summaryBytes/1024).toFixed(1)} KB of summary. Each step's summary can return up to 256 KB.`:". Each step can return up to 1 MB across its summary and data.";return`Step ${detail.step} returned ${size} of output${bound} Return fewer fields or process a smaller batch, then try again.`}class RoutineStepOutputError extends Error{code="step_output_too_large";detail;constructor(detail){const captured=parseRoutineStepOutputDetail(detail);super(routineStepOutputMessage(captured));this.detail=captured;Object.freeze(this)}}function captureRoutineStepOutput(step,summary,data){assertRoutineJson(summary);assertRoutineJson(data);const summaryJson=JSON.stringify(summary),dataJson=JSON.stringify(data);const summaryBytes=new TextEncoder().encode(summaryJson).byteLength;const dataBytes=new TextEncoder().encode(dataJson).byteLength;const sizeBytes=summaryBytes+dataBytes;const limitBytes=summaryBytes>ROUTINE_STEP_SUMMARY_BYTES?ROUTINE_STEP_SUMMARY_BYTES:ROUTINE_STEP_OUTPUT_BYTES;if(summaryBytes>ROUTINE_STEP_SUMMARY_BYTES||sizeBytes>ROUTINE_STEP_OUTPUT_BYTES)throw new RoutineStepOutputError({step,sizeBytes,limitBytes,summaryBytes,dataBytes});return freezeRoutineMetadata({summary:JSON.parse(summaryJson),data:JSON.parse(dataJson)})}function captureRetainedStepOutput(step,value){const hasSummary=Object.hasOwn(value,"summary"),hasData=Object.hasOwn(value,"data");if(hasSummary&&hasData)return captureRoutineStepOutput(step,value.summary,value.data);for(const key of["summary","data"])if(Object.hasOwn(value,key)){assertRoutineJson(value[key]);const bytes=new TextEncoder().encode(JSON.stringify(value[key])).byteLength;if(bytes>(key==="summary"?ROUTINE_STEP_SUMMARY_BYTES:ROUTINE_STEP_OUTPUT_BYTES))throw new AppRoutineContractError("invalid_value")}return freezeRoutineMetadata(JSON.parse(JSON.stringify(value)))}var LIMIT=256*1024;var invalid3=()=>{throw new AppRoutineContractError("invalid_value")};var invalidContract3=()=>{throw new AppRoutineContractError("invalid_contract")};var empty={type:"object",properties:{},required:[],additionalProperties:false};function captureJson(value,maximum=LIMIT){assertRoutineJson(value);const encoded=JSON.stringify(value);if(maximum!==null&&new TextEncoder().encode(encoded).byteLength>maximum)return invalid3();return freezeRoutineMetadata(JSON.parse(encoded))}function capture2(schema,value){const captured=captureJson(value);validateRoutineSchemaValue(schema,captured);return captured}var schemas=new WeakMap;function nestedSchema(value){const metadata=schemaMetadata(value);if(Object.hasOwn(metadata,"default"))return invalidContract3();return metadata.schema}function schemaMetadata(value){if(!value||typeof value!=="object")return invalidContract3();const registered=schemas.get(value);if(registered)return registered;try{assertRoutineJson(value)}catch{return invalidContract3()}return{schema:parseAppRoutineContract({routine:"definition",input:value,steps:[{id:"inspect"}]}).input}}function declaration(value,defaults){try{assertRoutineJson(value)}catch{return invalidContract3()}const parsed=freezeRoutineMetadata(parseAppRoutineContract({routine:"definition",input:value,steps:[{id:"inspect"}]}).input);const captured=defaults?capture2(parsed,defaults.value):undefined;const builder=Object.defineProperty({...parsed},"default",{value:(value2)=>declaration(parsed,{value:value2})});schemas.set(builder,{schema:parsed,...defaults?{default:captured}:{}});return Object.freeze(builder)}var schema={object(properties){return declaration({type:"object",properties:Object.fromEntries(Object.entries(properties).map(([key,value])=>[key,nestedSchema(value)])),required:Object.keys(properties),additionalProperties:false})},array(items,options={}){assertRoutineFields(options,["maxItems"]);return declaration({type:"array",items:nestedSchema(items),...options})},string(options={}){return declaration({type:"string",...options})},integer(options={}){return declaration({type:"integer",...options})},number(options={}){return declaration({type:"number",...options})},boolean(){return declaration({type:"boolean"})}};var file=(options={})=>{assertRoutineFields(options,["storage","path"]);return declaration({type:"file",...options})};var defineResponse=(value)=>defineHandler(value);var definitions=new WeakMap;var defineRoutine=(definition)=>{assertRoutineFields(definition,["id","title","schedule","input","steps","result","access","responses","run"]);if(!isAppRoutineName(definition.id)||definition.title!==undefined&&!routineTitle(definition.title)||typeof definition.run!=="function")return invalidContract3();const input=definition.input===undefined?{schema:empty,default:{}}:schemaMetadata(definition.input);const schedule=definition.schedule===undefined?undefined:routineScheduleMetadata(definition.schedule,input.schema,Object.hasOwn(input,"default"));const result=definition.result===undefined?undefined:schemaMetadata(definition.result).schema;const access=parseRoutineAccess(definition.access);assertRoutineFields(definition.steps??{});const executable=Object.fromEntries(Object.entries(definition.steps??{}).map(([id2,step])=>{assertRoutineFields(step,["title","run"]);if(!routineTitle(step.title)||typeof step.run!=="function")return invalidContract3();return[id2,Object.freeze({title:step.title,run:step.run})]}));const steps=Object.entries(executable).map(([id2,step])=>({id:id2,title:step.title}));parseAppRoutineContract({routine:definition.id,input:input.schema,steps:steps.length?steps.map(({id:id2})=>({id:id2})):[{id:"inspect"}],...result?{result}:{}});const responses=[];const ids=new Set;if(definition.responses!==undefined){if(!Array.isArray(definition.responses)||definition.responses.length>64||Reflect.ownKeys(definition.responses).length!==definition.responses.length+1)return invalidContract3();for(let index=0;index<definition.responses.length;index++){const descriptor=Object.getOwnPropertyDescriptor(definition.responses,String(index));if(!descriptor||!Object.hasOwn(descriptor,"value"))return invalidContract3();const response=descriptor.value;assertRoutineFields(response,["id","results","run"]);if(!isAppRoutineName(response.id)||ids.has(response.id))return invalidContract3();ids.add(response.id);if(response.results!==undefined){try{assertRoutineJson(response.results)}catch{return invalidContract3()}}try{responses.push(defineHandler(response))}catch{return invalidContract3()}}}const contract=freezeRoutineMetadata({id:definition.id,...definition.title===undefined?{}:{title:definition.title},...schedule===undefined?{}:{schedule},input:input.schema,...Object.hasOwn(input,"default")?{inputDefault:input.default}:{},access,responses:responses.map(({id:id2})=>({id:id2})),steps,...result?{result}:{}});const captured=Object.freeze({...definition,...schedule===undefined?{}:{schedule},access,steps:Object.freeze(executable),responses:Object.freeze(responses.map((handler)=>defineHandler({...handler,async run(context,runtime){let active=true;const capabilities=runtime?createCapabilityRuntime(contract,runtime,()=>active,"Response"):undefined;try{return await handler.run(context,capabilities?.os)}catch(error){active=false;throw error}finally{try{await capabilities?.drain()}finally{active=false}}}}))),...definition.input===undefined?{}:{input:declaration(input.schema,Object.hasOwn(input,"default")?{value:input.default}:undefined)},...result===undefined?{}:{result:declaration(result)},run:(input2,os)=>executeRoutineDefinition(captured,input2,os)});definitions.set(captured,{contract,steps:executable,run:definition.run});return captured};function inspectRoutineDefinition(definition){if(!definition||typeof definition!=="object")return invalidContract3();const registered=definitions.get(definition);if(!registered)return invalidContract3();return registered.contract}function captureRoutineInput(definition,input){const contract=inspectRoutineDefinition(definition);return capture2(contract.input,input===undefined&&Object.hasOwn(contract,"inputDefault")?contract.inputDefault:input)}function createCapabilityRuntime(contract,runtime,current,owner){const aiWork=new Set;const generate=(kind,value)=>{const operation=(async()=>{if(!current()||contract.access.ai!==true)throw new AIError("access_denied");if(!runtime.ai)throw new AIError("capability_unavailable");let request;try{assertRoutineFields(value,kind==="generateObject"?["instructions","input","schema","tools"]:["instructions","input","tools"]);request=parseRoutineAIRequest({kind,instructions:value.instructions,input:value.input,...kind==="generateObject"?{schema:schemaMetadata(value.schema).schema}:{},...value.tools===undefined?{}:{tools:value.tools}})}catch(error){if(error instanceof AIError)throw error;throw new AIError("invalid_input")}const result=await runtime.ai[kind](request);if(!current())throw new AIError("access_denied");return parseRoutineAIResult(request,result)})();aiWork.add(operation);operation.then(()=>aiWork.delete(operation),()=>aiWork.delete(operation));return operation};const guarded=(value,receiver)=>typeof value==="function"?(...args)=>{if(!current())throw new Error(`${owner} authority ended`);return guarded(Reflect.apply(value,receiver,args))}:value&&typeof value==="object"&&!(value instanceof Promise)?new Proxy({...value},{get(_target,key){return guarded(Reflect.get(value,key,value),value)}}):value;const validateHandlers=(value)=>{for(const question2 of value.questions??[])if(question2.handler&&!contract.responses.some((handler)=>handler.id===question2.handler.id))return invalid3();return value};const os=Object.freeze({...guarded({data:runtime.data,files:runtime.files,ai:{generateText:(value)=>generate("generateText",value),generateObject:(value)=>generate("generateObject",value)},connections:{...runtime.connections,get:async(identity)=>{if(!current()||!contract.access.connections?.includes(identity))throw new Error("Connection unavailable");const value=await runtime.connections.get(identity);if(!current())throw new Error(`${owner} authority ended`);return value}},inbox:{...runtime.inbox,publishAsk:(value,options)=>runtime.inbox.publishAsk(validateHandlers(value),options)}})});return{os,guarded,async drain(){while(aiWork.size)await Promise.allSettled([...aiWork])}}}async function executeRoutineDefinition(definition,input,runtime){const captured=captureRoutineInput(definition,input);const{contract,steps,run}=definitions.get(definition);let active=true,accepting=true,broken=false;let outputFailure;let work=Promise.resolve();const capabilities=createCapabilityRuntime(contract,runtime,()=>active&&!broken,"Run");const called=new Set;const reached=new Set;let activeStep;const progress=new Map;const os=Object.freeze({...capabilities.os,...capabilities.guarded({run:freezeRoutineMetadata({id:runtime.run.id,async progress(value){assertRoutineFields(value,["completed","total"]);const{completed,total}=value;const prior=activeStep?progress.get(activeStep):undefined;if(!active||broken||!activeStep||!Number.isSafeInteger(completed)||!Number.isSafeInteger(total)||completed<1||completed>total||prior&&(prior.total!==total||completed<=prior.completed))return invalid3();const accepted=freezeRoutineMetadata({step:activeStep,completed,total});await runtime.run.progress(accepted);progress.set(activeStep,accepted)}}),...runtime.artifact?{artifact:runtime.artifact}:{}}),step(id2,...input2){let saved;try{if(!active||!accepting||broken||!Object.hasOwn(steps,id2)||called.has(id2)||input2.length>1)return invalid3();if(input2.length)saved=captureJson(input2[0],null);called.add(id2)}catch(error){broken=true;return Promise.reject(error)}const next=work.then(async()=>{if(broken)return invalid3();reached.add(id2);try{await runtime.step(id2,{status:"running"});activeStep=id2;const output=await steps[id2].run(saved,os);assertRoutineFields(output,["summary","data"]);if(!Object.hasOwn(output,"summary")||!Object.hasOwn(output,"data"))return invalid3();const{summary,data}=captureRoutineStepOutput(id2,output.summary,output.data);await runtime.step(id2,{status:"completed",summary,data});activeStep=undefined;return freezeRoutineMetadata({summary,data})}catch(error){if(error instanceof RoutineStepOutputError)outputFailure??=error;broken=true;activeStep=undefined;await runtime.step(id2,{status:"failed"});throw error}});work=next.then(()=>{},()=>{broken=true});return next}});let result,failure;try{result=await run(captured,os)}catch(error){failure=error;broken=true}accepting=false;await work;await capabilities.drain();active=false;try{for(const step of contract.steps)if(!reached.has(step.id))await runtime.step(step.id,{status:"skipped"})}catch(error){throw outputFailure??error}if(broken)throw outputFailure??failure??new AppRoutineContractError("invalid_value");if(contract.result!==undefined)return capture2(contract.result,result);if(result!==undefined)return invalid3();return}var fieldProblems=["unknown","missing","invalid","source_schema"];var reasons={unknown:"unknown_field",missing:"missing_field",invalid:"invalid_value",source_schema:"source_schema_mismatch"};var expectationKinds={string:"a string",integer:"a safe integer",number:"a finite number",boolean:"a boolean",date:"a date in YYYY-MM-DD format",const:"the constant declared in the schema",datetime:"a UTC date and time in YYYY-MM-DDTHH:mm:ss.sssZ format, for example 2026-09-15T14:30:00.000Z",enum:"one of the choices declared in the schema",link:"a link to an existing record of an allowed type",object:"an object matching the schema",map:"a map matching the schema"};function expectationText(expected){if(!Object.hasOwn(expectationKinds,expected.type)||typeof expected.many!=="boolean"||typeof expected.nullable!=="boolean"||expected.decimalPlaces!==undefined&&(expected.type!=="number"||!Number.isInteger(expected.decimalPlaces)||expected.decimalPlaces<0||expected.decimalPlaces>6)||expected.format!==undefined&&(expected.type!=="date"||expected.format!=="month"))return;const scalar=expected.type==="number"&&expected.decimalPlaces!==undefined?`a finite number with at most ${expected.decimalPlaces} decimal places`:expected.type==="date"&&expected.format==="month"?"a date in YYYY-MM format":expectationKinds[expected.type];return`${expected.many?"Expected a list. Each item must be":"Expected"} ${scalar}.${expected.nullable?" The field may also be null.":""}`}function parseExpectation(text2){if(!text2)return;const parts=/^Expected (a list\. Each item must be )?(.+?)\.( The field may also be null\.)?$/.exec(text2);if(!parts)return;const number=/^a finite number with at most ([0-6]) decimal places$/.exec(parts[2]);const month=parts[2]==="a date in YYYY-MM format";const kind=number?"number":month?"date":Object.keys(expectationKinds).find((kind2)=>expectationKinds[kind2]===parts[2]);if(!kind)return;const expected={type:kind,many:!!parts[1],nullable:!!parts[3],...number?{decimalPlaces:Number(number[1])}:{},...month?{format:"month"}:{}};return expectationText(expected)===text2?expected:undefined}function parseDataValidationDetail(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const v=value;if(Object.keys(v).some((key)=>!["record","field","reason","schemaFile","expected"].includes(key))||typeof v.record!=="string"||typeof v.field!=="string")return;const problem=fieldProblems.find((problem2)=>reasons[problem2]===v.reason);if(!problem||v.schemaFile!==undefined&&typeof v.schemaFile!=="string")return;let expected;if(Object.hasOwn(v,"expected")){if(!v.expected||typeof v.expected!=="object"||Array.isArray(v.expected))return;const e=v.expected;if(Object.keys(e).some((key)=>!["type","many","nullable","decimalPlaces","format"].includes(key)))return;expected={...e};if(!expectationText(expected))return}if(problem==="unknown"&&expected||problem==="source_schema"&&(v.field!=="media_type"||expected?.type!=="string"||expected.many||expected.nullable))return;if(!recordFieldMessage(v.record,v.field,problem,v.schemaFile,expected))return;return{record:v.record,field:v.field,reason:reasons[problem],...typeof v.schemaFile==="string"?{schemaFile:v.schemaFile}:{},...expected?{expected}:{}}}function recordFieldDetail(record2,field,problem,schemaFile,expectation){const expected=problem==="source_schema"?{type:"string",many:false,nullable:false}:expectation;return parseDataValidationDetail({record:record2,field,reason:reasons[problem],...schemaFile?{schemaFile}:{},...expected?{expected}:{}})}function recordFieldMessage(record2,field,problem,schemaPath,expected){if(!validRecordRef(record2)||!/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(field))return;if(schemaPath!==undefined&&(schemaPath.length>256||!/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*\/_schema\.yaml$/.test(schemaPath)||schemaPath.split("/").some((part)=>[".","..",".git","routines"].includes(part))))return;const prefix=`Record "${record2}" isn't valid.`;const schema2=schemaPath?`"${schemaPath}"`:"the collection schema";if(problem==="source_schema")return field==="media_type"?`${prefix} This repository's Source schema${schemaPath?` ${schema2}`:""} doesn't include "media_type". The OS SDK uses "media_type" for file Sources. Update the Source schema in this repository to include this field.`:undefined;if(problem==="unknown")return`${prefix} The record contains "${field}", but ${schema2} doesn't define that field. Check that the record and ${schemaPath?"that file":"the collection schema"} use the same field name.`;if(problem==="missing")return`${prefix} The record is missing required field "${field}". Add it as defined in ${schema2}.`;const expectation=expected?expectationText(expected):undefined;if(expected&&!expectation)return;return`${prefix} The record has an invalid value for field "${field}".${expectation?` ${expectation}`:""} Check its definition in ${schema2}.`}function safeRecordFieldMessage(value){if(typeof value!=="string"||value.length>1200)return;const parts=/^Record "([^"]+)" isn't valid\. (.+)$/.exec(value);if(!parts)return;const schemaPath=/"([^"]+\/_schema\.yaml)"/.exec(value)?.[1];const field=[...parts[2].matchAll(/"([^"]+)"/g)].map((match)=>match[1]).find((part)=>part!==schemaPath);if(!field)return;const expected=parseExpectation(/\. (Expected .+) Check its definition in /.exec(value)?.[1]);return fieldProblems.map((problem)=>recordFieldMessage(parts[1],field,problem,schemaPath,expected)).find((message)=>message===value)}function dataValidationMessageFacts(error){if(error.code==="invalid_change"){const detail=parseDataValidationDetail(error.detail);if(detail){const problem=fieldProblems.find((problem2)=>reasons[problem2]===detail.reason);return{detail,message:recordFieldMessage(detail.record,detail.field,problem,detail.schemaFile,detail.expected)}}}const message=error.code==="invalid_change"?safeRecordFieldMessage(error.message):undefined;return message?{message}:{}}function explainDataValidation(error,message,detail){Object.assign(error,dataValidationMessageFacts({code:error.code,message:typeof message==="string"?message:"",detail}));return error}function dataPublicationFailureMessage(detail){if(detail.preflight==="dirty_repository")return`Data repository ${detail.repository} has existing changes. No Record files were changed.`+` Use os data push ${detail.repository} or stash those Data changes with Git, then run the routine again.`;return(detail.state==="commit"?`Data commit ${detail.commit} remains in your checkout; its push is unconfirmed.`:detail.state==="files"?"Your Record files were applied, but Git could not create their commit.":"Data publication needs Git preparation. No Record files were changed.")+` Review git status and your branch and destination, then use os data push ${detail.repository}. Do not rerun the routine to recover this publication.`}var localDataPath=(value,repository)=>typeof value==="string"&&value.length<=1024&&value.startsWith(`${repository}/`)&&!value.includes("\\")&&!/[\x00-\x1f\x7f]/.test(value)&&value.split("/").every((part)=>!!part&&part!=="."&&part!=="..");var localDataFile=(value,repository)=>{if(!value||typeof value!=="object"||Array.isArray(value))return false;const row=value;return Object.keys(row).sort().join(",")==="action,path"&&["created","updated","deleted"].includes(String(row.action))&&localDataPath(row.path,repository)};function parseDataFailureDetail(value){const invalid4=()=>{throw new Error("Invalid local Data failure detail")};if(!value||typeof value!=="object"||Array.isArray(value))return invalid4();const row=value;if(Object.keys(row).sort().join(",")!=="cause,code,files,nextAction,operation,repository"||!["local_data_read_failed","local_data_write_failed","local_data_write_partial"].includes(String(row.code))||!["read","write"].includes(String(row.operation))||typeof row.repository!=="string"||!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(row.repository)||row.repository.includes("//")||row.repository.includes("..")||!["fix_failed_file_then_rerun","review_resolve_then_rerun"].includes(String(row.nextAction)))return invalid4();const repository=row.repository;if(!row.cause||typeof row.cause!=="object"||Array.isArray(row.cause))return invalid4();const cause=row.cause;if(!["code,message","code,message,path"].includes(Object.keys(cause).sort().join(","))||!["schema_validation_failed","invalid_record","unsafe_record","stale_record","path_conflict","filesystem_unavailable"].includes(String(cause.code))||typeof cause.message!=="string"||!cause.message||cause.message.length>512||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(cause.message)||cause.path!==undefined&&!localDataPath(cause.path,repository))return invalid4();if(!row.files||typeof row.files!=="object"||Array.isArray(row.files))return invalid4();const files=row.files;if(Object.keys(files).some((key)=>!["state","saved","failed","notAttempted","savedOmitted","notAttemptedOmitted"].includes(key))||!["none","partial"].includes(String(files.state))||!Array.isArray(files.saved)||files.saved.length>128||!files.saved.every((item)=>localDataFile(item,repository))||files.failed!==undefined&&!localDataFile(files.failed,repository)||!Array.isArray(files.notAttempted)||files.notAttempted.length>128||!files.notAttempted.every((item)=>localDataFile(item,repository)))return invalid4();for(const key of["savedOmitted","notAttemptedOmitted"])if(files[key]!==undefined&&(!Number.isSafeInteger(files[key])||Number(files[key])<1||Number(files[key])>1e4))return invalid4();if(row.operation==="read"&&(row.code!=="local_data_read_failed"||files.state!=="none"||files.saved.length||files.failed!==undefined||files.notAttempted.length)||row.operation==="write"&&row.code==="local_data_read_failed"||row.code==="local_data_write_partial"&&(files.state!=="partial"||!files.saved.length)||row.code!=="local_data_write_partial"&&files.state==="partial")return invalid4();return structuredClone(value)}function parseDataOperationDetail(value){const validation=parseDataValidationDetail(value);if(validation)return validation;if(value&&typeof value==="object"&&!Array.isArray(value)&&value.code==="record_limit_exceeded"){const row=value;if(Object.keys(row).sort().join(",")!=="code,collections,maxRecords"||!Number.isSafeInteger(row.maxRecords)||Number(row.maxRecords)<1||!Array.isArray(row.collections)||!row.collections.length||row.collections.length>16||!row.collections.every((name)=>typeof name==="string"&&name.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(name))||new Set(row.collections).size!==row.collections.length)throw new Error("Invalid Data operation detail");return structuredClone(value)}if(value&&typeof value==="object"&&!Array.isArray(value)&&value.code==="local_data_publication_failed"){const row=value;if(Object.keys(row).sort().join(",")!==(row.state==="commit"?"code,commit,repository,state":Object.hasOwn(row,"preflight")?"code,preflight,repository,state":"code,repository,state")||Object.hasOwn(row,"preflight")&&(row.state!=="unapplied"||row.preflight!=="dirty_repository")||typeof row.repository!=="string"||!/^[a-z0-9][a-z0-9._-]{0,127}$/.test(row.repository)||row.repository.includes("..")||!["unapplied","files","commit"].includes(String(row.state))||row.state==="commit"&&(typeof row.commit!=="string"||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(row.commit)))throw new Error("Invalid Data publication detail");return structuredClone(value)}return parseDataFailureDetail(value)}function dataRecordLimitMessage(detail){const scope=detail.collections.length===1?` from ${detail.collections[0]}`:` across ${detail.collections.join(", ")}`;return`The routine tried to load more than ${detail.maxRecords.toLocaleString("en-US")} matching Records${scope}. `+"Narrow the query or increase maxRecords."}function dataErrorMessage(code,effect){if(effect==="uncertain")return"We couldn’t confirm whether your changes were saved.";if(code==="unavailable"&&effect==="unapplied")return"Your changes could not be saved.";if(code==="apply_pending")return effect==="applied"?"Your changes were saved, but confirmation is still pending.":effect==="unapplied"?"Your changes have not been saved yet.":"We couldn’t confirm whether your changes were saved.";const message={context_unavailable:"Data access is not available in this context.",unauthenticated:"Sign in to access this data.",access_denied:"You do not have permission to access this data.",invalid_query:"The data request is not valid.",request_too_large:"The data request is too large.",capacity:"The data service has reached its limit. Try again later.",unavailable:"We couldn’t complete your request.",invalid_change:"These changes are not valid.",conflict:"The data changed before the operation finished.",apply_pending:""};return message[code]+(effect==="unapplied"?" No changes were saved.":effect==="applied"?" Your changes were saved.":"")}class DataOperationError extends Error{code;retryable;effect;component;detail;constructor(code,retryable=false,effect,component,detail){const parsed=detail===undefined?undefined:parseDataOperationDetail(detail);if(parsed&&("reason"in parsed?code!=="invalid_change":parsed.code==="record_limit_exceeded"&&code!=="capacity"))throw new Error("Invalid Data operation detail");super(parsed&&"code"in parsed&&parsed.code==="local_data_publication_failed"?dataPublicationFailureMessage(parsed):code==="capacity"&&parsed&&("code"in parsed)&&parsed.code==="record_limit_exceeded"?dataRecordLimitMessage(parsed):dataErrorMessage(code,effect));this.code=code;this.retryable=retryable;this.effect=effect;this.component=component;this.detail=detail;this.name="DataOperationError";if(parsed!==undefined)this.detail=parsed}}var invalid4=()=>{throw new DataOperationError("invalid_query")};var dataText=(value)=>typeof value==="string"&&!/[\u0000\uD800-\uDFFF]/u.test(value);var dataVersion=(value)=>dataText(value)&&value.length>0&&new TextEncoder().encode(value).length<=1024&&!/[\u0000-\u001f\u007f-\u009f]/.test(value)&&!/^[0-9a-f]{40}$/i.test(value);function dataProperties(value){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))return invalid4();const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(value).some((key)=>typeof key!=="string"||!descriptors[key]?.enumerable||!Object.hasOwn(descriptors[key],"value")))return invalid4();return descriptors}function dataArray(value){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)return invalid4();const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(value).length!==value.length+1)return invalid4();const result=[];for(let index=0;index<value.length;index++){const descriptor=descriptors[index];if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value"))return invalid4();result.push(descriptor.value)}return result}var invalid5=()=>{throw new DataOperationError("invalid_query")};function captureRecordsSearchInput(query,options){if(!dataText(query))return invalid5();const length=[...query.trim()].length;if(length<1||length>256)return invalid5();if(options===undefined)return{query};const descriptors=dataProperties(options);if(Object.keys(descriptors).some((key)=>!["collections","limit"].includes(key)))return invalid5();const captured={};if(Object.hasOwn(descriptors,"collections")){const supplied=descriptors.collections.value;if(!Array.isArray(supplied)||supplied.length<1||supplied.length>16||Reflect.ownKeys(supplied).length!==supplied.length+1)return invalid5();const collections=[];for(let index=0;index<supplied.length;index++){const descriptor=Object.getOwnPropertyDescriptor(supplied,String(index));if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value")||!dataText(descriptor.value))return invalid5();collections.push(descriptor.value)}if(new Set(collections).size!==collections.length)return invalid5();captured.collections=collections}if(Object.hasOwn(descriptors,"limit")){const supplied=descriptors.limit.value;if(!Number.isInteger(supplied)||supplied<1||supplied>100)return invalid5();captured.limit=supplied}return{query,options:captured}}function captureRecordsReadRefs(value){if(!Array.isArray(value)||value.length<1||value.length>100)throw new DataOperationError("invalid_query");const refs=dataArray(value);if(!refs.every((ref)=>validRecordRef(ref)&&!/[\r\n]/.test(ref))||new Set(refs).size!==refs.length)throw new DataOperationError("invalid_query");return refs}function captureRecordsReadOptions(value){if(value===undefined)return{};try{dataProperties(value)}catch{throw new DataOperationError("invalid_query")}if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value))||Reflect.ownKeys(value).some((key)=>key!=="body"&&key!=="timeline")||Object.values(value).some((option)=>option!==true))throw new DataOperationError("invalid_query");return{...Object.hasOwn(value,"body")?{body:true}:{},...Object.hasOwn(value,"timeline")?{timeline:true}:{}}}function capture3(value,ancestors=new Set,depth=0){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object"||ancestors.has(value)||depth>32)throw new DataOperationError("invalid_query");ancestors.add(value);try{if(Array.isArray(value))return dataArray(value).map((item)=>capture3(item,ancestors,depth+1));return Object.fromEntries(Object.entries(dataProperties(value)).map(([key,descriptor])=>[key,capture3(descriptor.value,ancestors,depth+1)]))}finally{ancestors.delete(value)}}function captureRecordsQuery(query){return capture3(query)}function captureRecordsAll(query,options){const invalid6=()=>{throw new DataOperationError("invalid_query")};try{const properties=dataProperties(options),maxRecords=properties.maxRecords?.value;if(Object.keys(properties).join(",")!=="maxRecords"||!Number.isSafeInteger(maxRecords)||maxRecords<1)return invalid6();const detached=capture3(query);const selections=dataProperties(detached);if(Object.keys(selections).length<1||Object.keys(selections).length>16)return invalid6();for(const selection2 of Object.values(selections)){const fields2=dataProperties(selection2.value);if(fields2.$&&Object.hasOwn(dataProperties(fields2.$.value),"after"))return invalid6()}return{query:detached,maxRecords}}catch{return invalid6()}}function validRecordBody(value){return typeof value==="string"&&value===new TextDecoder("utf-8",{ignoreBOM:true}).decode(new TextEncoder().encode(value))}var RECORD_BODY_READ_BYTES=8*1024*1024;var fail2=()=>{throw new DataOperationError("invalid_change",false,"unapplied")};function mapping(value){try{dataProperties(value);return value}catch{return fail2()}}var validSignalKey=(value)=>typeof value==="string"&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(value);var validSignalText=(value)=>typeof value==="string"&&!!value.trim()&&!/[\r\n\u0000\uD800-\uDFFF]/u.test(value);function validSignalInstant(value){if(typeof value!=="string")return false;const match=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?Z$/.exec(value);if(!match)return false;const normalized=`${match[1]}.${(match[2]??"").padEnd(3,"0").slice(0,3)}Z`;return Number.isFinite(Date.parse(normalized))&&new Date(normalized).toISOString()===normalized}var positive=(value)=>Number.isSafeInteger(value)&&Number(value)>0;function references(value,compact){if(value===undefined&&compact)return[];if(!Array.isArray(value))return fail2();let items;try{items=dataArray(value)}catch{return fail2()}return items.map((item)=>{const row=mapping(item),keys2=Object.keys(row).sort().join(",");if(compact){if(keys2==="record"&&validRecordRef(row.record))return{type:"record",ref:row.record};if(keys2==="ask"&&positive(row.ask))return{type:"ask",number:row.ask};if(keys2==="signal"){const signal=mapping(row.signal);if(Object.keys(signal).sort().join(",")==="number,record"&&validRecordRef(signal.record)&&positive(signal.number))return{type:"signal",record:signal.record,number:signal.number}}}else{if(keys2==="ref,type"&&row.type==="record"&&validRecordRef(row.ref))return{type:"record",ref:row.ref};if(keys2==="number,type"&&row.type==="ask"&&positive(row.number))return{type:"ask",number:row.number};if(keys2==="number,record,type"&&row.type==="signal"&&validRecordRef(row.record)&&positive(row.number))return{type:"signal",record:row.record,number:row.number}}return fail2()})}function captureSignal(value,acceptedAt){const row=mapping(value),compact=acceptedAt!==undefined;if(Object.keys(row).some((key)=>!["key","label","status","reason","related",...compact?[]:["asOf"]].includes(key))||!validSignalKey(row.key)||!validSignalText(row.label)||!validSignalText(row.status)||row.reason!==undefined&&(typeof row.reason!=="string"||/[\r\n\u0000\uD800-\uDFFF]/u.test(row.reason))||!validSignalInstant(acceptedAt??row.asOf))return fail2();return{key:row.key,label:row.label,status:row.status,...row.reason?{reason:row.reason}:{},related:references(row.related,compact),asOf:acceptedAt??row.asOf}}function captureTimeline(value,compact=false){const row=mapping(value);if(Object.keys(row).some((key)=>!["when","event","activity","related"].includes(key))||!validSignalInstant(row.when)||!validSignalText(row.activity)||row.event!==undefined&&!validSignalKey(row.event))return fail2();return{when:row.when,...row.event!==undefined?{event:row.event}:{},activity:row.activity,related:references(row.related,compact)}}function captureRecordSignal(value){const row=mapping(value),{number,...assessment}=row;if(!positive(number))return fail2();return{number,...captureSignal(assessment)}}function captureRecordSignals(value){if(!Array.isArray(value))return fail2();const rows=dataArray(value).map(captureRecordSignal);if(new Set(rows.map((row)=>row.key)).size!==rows.length||new Set(rows.map((row)=>row.number)).size!==rows.length)return fail2();return rows}var DATA_REQUEST_LIMIT=256*1024;var LOCAL_DATA_CHANGE_REQUEST_LIMIT=32*1024*1024;var invalidChange=()=>{throw new DataOperationError("invalid_change",false,"unapplied")};function mapping2(value){try{dataProperties(value);return value}catch{return invalidChange()}}function captureDataTables(value){const row=mapping2(value);const result={};if(Object.hasOwn(row,"signals")){if(!Array.isArray(row.signals)||!row.signals.length||row.signals.length>1e4)return invalidChange();try{result.signals=dataArray(row.signals).map((value2)=>captureSignal(value2))}catch{return invalidChange()}if(new Set(result.signals.map((value2)=>value2.key)).size!==result.signals.length)return invalidChange()}if(Object.hasOwn(row,"timeline")){if(!Array.isArray(row.timeline)||!row.timeline.length||row.timeline.length>1e4)return invalidChange();try{result.timeline=dataArray(row.timeline).map((value2)=>captureTimeline(value2))}catch{return invalidChange()}}return result}function captureDataChangeOptions(value){if(value===undefined)return{};const options=mapping2(value);if(Object.keys(options).some((key)=>!["summary","source"].includes(key)))return invalidChange();const line=(value2)=>{if(!dataText(value2)||!value2.trim().length||[...value2].length>120||/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value2))return invalidChange();return value2};const captured={};if(Object.hasOwn(options,"summary"))captured.summary=line(options.summary);if(Object.hasOwn(options,"source")){const source=mapping2(options.source);if(Object.keys(source).sort().join(",")!=="id,kind"||source.kind!=="app"&&source.kind!=="routine")return invalidChange();captured.source={kind:source.kind,id:line(source.id)}}return captured}function captureValue(value,ancestors=new Set,depth=0){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object"||ancestors.has(value)||depth>32)return invalidChange();ancestors.add(value);try{if(Array.isArray(value)){if(value.length>1e5||Object.keys(value).length!==value.length||Object.getOwnPropertySymbols(value).length)return invalidChange();return Array.from(value,(item)=>captureValue(item,ancestors,depth+1))}return Object.fromEntries(Object.entries(mapping2(value)).map(([key,item])=>{if(["__proto__","constructor","prototype"].includes(key))return invalidChange();return[key,captureValue(item,ancestors,depth+1)]}))}finally{ancestors.delete(value)}}function captureDataDelete(record2){const identity=mapping2(record2);if(!validRecordRef(identity.$ref)||typeof identity.$version!=="string"||!identity.$version.length||identity.$version.length>512)return invalidChange();return{ref:identity.$ref,expectedVersion:identity.$version}}function captureDataUpdate(record2,set){if(!validRecordRef(record2))return invalidChange();const input=mapping2(set);const{$body,...fields2}=input;const body=Object.hasOwn(input,"$body");if(body&&!validRecordBody($body)||!Object.keys(fields2).length&&!body||Object.keys(fields2).some((key)=>key.startsWith("$")||["id","type"].includes(key)))return invalidChange();return{ref:record2,set:captureValue(fields2),...body?{body:$body}:{}}}function captureIdentities(value,update,allowEmpty=true){if(!Array.isArray(value)||!allowEmpty&&!value.length||value.length>1e4)return invalidChange();const captured=value.map((item)=>{const row=mapping2(item);if(Object.keys(row).filter((key)=>!update||!["body","expectedVersion","signals","timeline"].includes(key)).sort().join(",")!==(update?"ref,set":"expectedVersion,ref"))return invalidChange();const identity={$ref:row.ref,$version:row.expectedVersion};if(update&&Object.keys(mapping2(row.set)).some((key)=>key.startsWith("$")))return invalidChange();if(!update)return captureDataDelete(identity);const tables=captureDataTables(row);const captured2=Object.keys(mapping2(row.set)).length||Object.hasOwn(row,"body")?captureDataUpdate(row.ref,{...mapping2(row.set),...Object.hasOwn(row,"body")?{$body:row.body}:{}}):validRecordRef(row.ref)&&Object.keys(tables).length?{ref:row.ref,set:{}}:invalidChange();return{...captured2,...tables,...Object.hasOwn(row,"expectedVersion")?{expectedVersion:captureDataDelete(identity).expectedVersion}:{}}});if(new Set(captured.map((item)=>item.ref)).size!==captured.length)return invalidChange();return captured}function captureDataUpdates(value,allowEmpty=false){return captureIdentities(value,true,allowEmpty)}function captureDataCreate(value){const row=mapping2(value);if(!validRecordRef(row.$ref)||Object.keys(row).some((key)=>key.startsWith("$")&&!["$ref","$filing","$body"].includes(key)))return invalidChange();const{$ref:ref,$filing,$body,...fields2}=row;const body=Object.hasOwn(row,"$body");if(body&&!validRecordBody($body))return invalidChange();let filing;if($filing!==undefined){const components=mapping2($filing);if(Object.entries(components).some(([name,value2])=>!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)||["constructor","prototype"].includes(name)||typeof value2!=="string"||!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value2)))return invalidChange();filing={...components}}return{ref,fields:captureValue(fields2),...filing?{filing}:{},...body?{body:$body}:{}}}function captureDataChanges(updatesValue,createsValue=[],deletesValue=[]){const updates=captureDataUpdates(updatesValue,true);if(!Array.isArray(createsValue)||createsValue.length>1e4)return invalidChange();const creates=createsValue.map((item)=>{const row=mapping2(item);if(Object.keys(row).some((key)=>!["ref","fields","filing","body","signals","timeline"].includes(key))||!Object.hasOwn(row,"ref")||!Object.hasOwn(row,"fields"))return invalidChange();const fields2=mapping2(row.fields);if(Object.keys(fields2).some((key)=>key.startsWith("$")))return invalidChange();return{...captureDataCreate({...fields2,$ref:row.ref,...Object.hasOwn(row,"filing")?{$filing:row.filing}:{},...Object.hasOwn(row,"body")?{$body:row.body}:{}}),...captureDataTables(row)}});const deletes=captureIdentities(deletesValue,false);const refs=[...updates,...creates,...deletes].map((item)=>item.ref);if(!refs.length||refs.length>1e4||new Set(refs).size!==refs.length)return invalidChange();return{updates,creates,deletes}}function checkDataRequestSize(input,limit=DATA_REQUEST_LIMIT){if(new TextEncoder().encode(JSON.stringify(input)).byteLength>limit)throw new DataOperationError("request_too_large",false,"unapplied")}function dataTransportError(status,value){const failures={400:["invalid_query","invalid_change"],401:["unauthenticated"],403:["access_denied"],409:["conflict","apply_pending"],413:["request_too_large"],429:["capacity"],503:["unavailable","apply_pending"]};const error=value&&typeof value==="object"&&"error"in value?value.error:undefined;const row=error&&typeof error==="object"?error:undefined;const code=failures[status]?.find((allowed)=>allowed===row?.code)??"unavailable";const effect=["unapplied","uncertain","applied"].includes(String(row?.effect))?row.effect:undefined;let detail;try{detail=row?.detail===undefined?undefined:parseDataOperationDetail(row.detail)}catch{}if(detail&&"reason"in detail&&code!=="invalid_change")detail=undefined;return explainDataValidation(new DataOperationError(code,typeof row?.retryable==="boolean"?row.retryable:["capacity","unavailable","apply_pending"].includes(code),code==="conflict"?"unapplied":effect,code==="invalid_change"&&typeof row?.component==="string"&&/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(row.component)?row.component:undefined,detail),row?.message,row?.detail)}var AUTH_ORIGIN="https://auth.oddington.ai";function oddingtonOrigin(environment=process.env){const value=environment.OS_ORIGIN??AUTH_ORIGIN;const url=new URL(value);if(url.protocol!=="https:"&&url.hostname!=="127.0.0.1")throw new Error("OS_ORIGIN must use HTTPS");return url.origin}var nodeRequest;var nodeReadable;if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){({request:nodeRequest}=await import("node:http"));({Readable:nodeReadable}=await import("node:stream"))}function privateRoutineRequest(environment=typeof __OS_BROWSER__!=="undefined"&&__OS_BROWSER__?{}:typeof process==="undefined"?{}:process.env){if(typeof __OS_BROWSER__!=="undefined"&&__OS_BROWSER__)return;const prepared=["OS_ROUTINE_LOCAL","OS_ROUTINE_LOCAL_SOCKET","OS_ROUTINE_LOCAL_TOKEN"].some((key)=>environment[key]!==undefined);const managed=["OS_FILES_SOCKET","OS_FILES_TOKEN"].some((key)=>environment[key]!==undefined);if(!prepared&&!managed)return;const socket=prepared?environment.OS_ROUTINE_LOCAL_SOCKET:environment.OS_FILES_SOCKET;const token=prepared?environment.OS_ROUTINE_LOCAL_TOKEN:environment.OS_FILES_TOKEN;const request=localRoutineRequest(prepared?environment:{OS_ROUTINE_LOCAL:"1",OS_ROUTINE_LOCAL_SOCKET:socket,OS_ROUTINE_LOCAL_TOKEN:token});const isCurrent=()=>prepared?environment.OS_ROUTINE_LOCAL==="1"&&environment.OS_ROUTINE_LOCAL_SOCKET===socket&&environment.OS_ROUTINE_LOCAL_TOKEN===token:environment.OS_FILES_SOCKET===socket&&environment.OS_FILES_TOKEN===token;if(!nodeRequest||!nodeReadable)throw new Error("Files transport unavailable");const httpRequest=nodeRequest,Readable=nodeReadable;const files=async(suffix,init,signal)=>{if(!isCurrent())throw new FileOperationError("unsupported_context",400);const tcp=/^tcp:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(socket);const endpoint=tcp?{hostname:"127.0.0.1",port:Number(tcp[1])}:{socketPath:socket};const id2=crypto.randomUUID();if(init.body instanceof ReadableStream||suffix===""&&init.method==="POST"){await new Promise((resolve,reject)=>{const check=httpRequest({...endpoint,path:"/files/check-create",method:"POST",timeout:30000,signal,agent:false,headers:{...Object.fromEntries(new Headers(init.headers)),authorization:`Bearer ${token}`,"x-os-files-suffix":encodeURIComponent(suffix),"x-os-files-method":init.method??"GET"}},(response)=>{const bytes=Buffer.alloc(16384);let size=0;response.on("data",(chunk)=>{size+=chunk.length;if(size>16384)response.destroy(new Error("File operation start response exceeded 16 KiB."));else bytes.set(chunk,size-chunk.length)});response.once("error",reject);response.once("end",()=>{if(response.statusCode===204){resolve();return}try{const value=JSON.parse(bytes.subarray(0,size).toString());const code=value?.error?.code;const status=response.statusCode??503;if(["invalid_input","request_too_large","unsupported_context","access_denied","capacity","unavailable"].includes(code))reject(new FileOperationError(code,status,code==="capacity"||code==="unavailable",parseFileErrorDetail(value?.error?.detail)));else reject(new FileOperationError("unavailable",503,true))}catch{reject(new FileOperationError("unavailable",503,true))}})});check.once("error",()=>reject(new FileOperationError("unavailable",503,true)));check.once("timeout",()=>check.destroy(new Error("The file create check did not finish in time.")));check.end()});if(!isCurrent())throw new FileOperationError("unsupported_context",400)}let cancellation;const cancelCall=()=>cancellation??=new Promise((resolve,reject)=>{const cancel=httpRequest({...endpoint,path:"/files/cancel",method:"POST",timeout:30000,headers:{authorization:`Bearer ${token}`,"x-os-files-call":id2}},(response)=>{response.resume();response.once("end",resolve);response.once("error",reject)});cancel.once("error",reject);cancel.once("timeout",()=>cancel.destroy(new Error("Files cancellation stalled")));cancel.end()});let pumping=Promise.resolve();let sourceReader;const result=new Promise((resolve,reject)=>{const call=httpRequest({...endpoint,path:"/files/stream",method:"POST",headers:{...Object.fromEntries(new Headers(init.headers)),authorization:`Bearer ${token}`,"x-os-files-call":id2,"x-os-files-suffix":encodeURIComponent(suffix),"x-os-files-method":init.method??"GET"},signal,timeout:30000,agent:false},async(response)=>{try{call.setTimeout(0);if((response.statusCode??503)>=400){await sourceReader?.cancel().catch(()=>{});call.end()}await pumping;if(!isCurrent()){response.destroy();reject(new FileOperationError("unsupported_context",400));return}const headers=new Headers;for(const[key,value]of Object.entries(response.headers))if(value!==undefined)headers.set(key,Array.isArray(value)?value.join(", "):value);const source=Readable.toWeb(response,{strategy:{highWaterMark:65536,size:(chunk)=>chunk.byteLength}});const reader=source.getReader();if(response.statusCode===204){const timer=setTimeout(()=>response.destroy(new Error("Files completion stalled")),30000);try{if(!(await reader.read()).done)throw new FileOperationError("unavailable",503,true);if(!isCurrent())throw new FileOperationError("unsupported_context",400);resolve(new Response(null,{status:204,headers}))}finally{clearTimeout(timer);reader.releaseLock()}return}let closed=false;const body=new ReadableStream({async pull(controller){let timer;try{if(!isCurrent())throw new FileOperationError("unsupported_context",400);timer=setTimeout(()=>response.destroy(new Error("Files delivery stalled")),30000);const next=await reader.read();if(closed)return;if(next.done){closed=true;reader.releaseLock();controller.close()}else controller.enqueue(next.value)}catch(error){closed=true;controller.error(error);await cancelCall().catch(()=>{});response.socket?.destroy();response.destroy();await reader.cancel(error).catch(()=>{});reader.releaseLock()}finally{clearTimeout(timer)}},async cancel(reason){closed=true;await cancelCall().catch(()=>{});response.socket?.destroy();response.destroy();call.destroy();await reader.cancel(reason).catch(()=>{});reader.releaseLock()}},{highWaterMark:0});resolve(new Response(body,{status:response.statusCode??503,headers}))}catch(error){response.destroy();reject(error instanceof FileOperationError?error:new FileOperationError("unavailable",503,true))}});call.on("error",(error)=>{cancelCall().catch(()=>{});reject(error instanceof FileOperationError?error:new FileOperationError("unavailable",503,true))});call.on("timeout",()=>call.destroy(new Error("Files I/O stalled")));call.on("information",()=>call.setTimeout(30000));if(init.body instanceof ReadableStream){call.flushHeaders();const reader=sourceReader=init.body.getReader();const abort=()=>{reader.cancel(signal.reason).catch(()=>{})};signal.addEventListener("abort",abort,{once:true});call.once("close",abort);pumping=(async()=>{try{for(;;){const next=await reader.read();if(next.done)break;if(!(next.value instanceof Uint8Array))throw new FileOperationError("invalid_input",400);if(!isCurrent())throw new FileOperationError("unsupported_context",400);for(let offset=0;offset<next.value.byteLength;offset+=262144){if(call.destroyed)throw new Error("Files parent disconnected");await new Promise((done,fail3)=>{const closed=()=>fail3(new Error("Files parent disconnected"));call.once("close",closed);call.write(next.value.subarray(offset,offset+262144),(error)=>{call.removeListener("close",closed);error?fail3(error):done()})})}}call.end()}catch(error){call.destroy(error instanceof Error?error:new Error("Files transport failed"))}finally{await reader.cancel().catch(()=>{});signal.removeEventListener("abort",abort);call.removeListener("close",abort);reader.releaseLock()}})()}else call.end(init.body===undefined?undefined:Buffer.from(init.body))});try{return await result}finally{await pumping}};return{request,files,isCurrent,identity:`private:${socket}`}}function localRoutineRequest(environment=typeof __OS_BROWSER__!=="undefined"&&__OS_BROWSER__?{}:typeof process==="undefined"?{}:process.env){if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){const{OS_ROUTINE_LOCAL:mode,OS_ROUTINE_LOCAL_SOCKET:socket,OS_ROUTINE_LOCAL_TOKEN:token}=environment;if(mode===undefined&&socket===undefined&&token===undefined)return;if(mode!=="1"||!socket||!token||!/^[0-9a-f]{64}$/.test(token))throw new Error("Preparation transport unavailable; nothing can publish");const tcp=/^tcp:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(socket);const endpoint=tcp&&tcp[0]===socket&&Number(tcp[1])<=65535?{hostname:"127.0.0.1",port:Number(tcp[1])}:socket.startsWith("/")&&!socket.startsWith("//")&&!socket.includes("\x00")?{socketPath:socket}:undefined;if(!endpoint)throw new Error("Preparation transport unavailable; nothing can publish");return async(operation,input)=>{const{request}=await import("node:http");return await new Promise((resolve,reject)=>{const call=request({...endpoint,path:`/${operation}`,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${token}`},timeout:operation==="ai/generate"?125000:120000},(response)=>{const limit=operation==="ai/generate"?ROUTINE_AI_RESULT_BYTES:33554432;const bytes=Buffer.alloc(limit);let size=0;response.on("data",(chunk)=>{size+=chunk.length;if(size>limit){response.destroy();reject(operation==="ai/generate"?new AIError("output_too_large"):new Error("Local result exceeds supported size"))}else bytes.set(chunk,size-chunk.length)});response.on("error",(error)=>reject(operation==="ai/generate"?new AIError("capability_unavailable"):error));response.on("end",()=>{try{const result=JSON.parse(bytes.subarray(0,size).toString());if(response.statusCode!==200){if(operation==="ai/generate")throw parseRoutineAIError(result.error);if(operation==="files/request"){const error=result.error;const status=response.statusCode??503;const codes=["invalid_input","unsupported_context","unauthenticated","access_denied","not_found","request_too_large","conflict","local_only","integrity","unavailable","capacity","method_not_allowed"];if(error?.code&&codes.includes(error.code))throw new FileOperationError(error.code,status,error.code==="capacity"||error.code==="unavailable",parseFileErrorDetail(error.detail));throw new FileOperationError("unavailable",503,true)}if(operation==="data/query"){throw dataTransportError(response.statusCode??0,result)}throw new Error(typeof result.error==="string"?result.error:"Preparation failed")}resolve(result)}catch(error){reject(operation==="ai/generate"&&!(error instanceof AIError)?new AIError("invalid_output"):error)}})});call.on("error",()=>reject(operation==="ai/generate"?new AIError("capability_unavailable"):operation==="data/query"?dataTransportError(503,{error:{code:"unavailable"}}):new Error("Preparation transport unavailable; nothing was published")));call.on("timeout",()=>call.destroy(new Error("Preparation timed out")));call.end(JSON.stringify(input))})}}}var installed;var ended=false;function routineTransport(){if(ended||installed&&!installed.isCurrent())throw new Error("Routine authority ended");return installed}var memberContext;var memberLifetime;var retainedContext;function installMemberContext(resolve,retained=resolve){memberLifetime?.abort();memberLifetime=new AbortController;memberContext=resolve;retainedContext=retained;return()=>{if(memberContext===resolve){memberLifetime?.abort();memberContext=undefined;retainedContext=undefined}}}async function resolveAppContext(retained=false){const host=memberContext;if(!host)throw new Error("App context unavailable.");const context=await(retained?retainedContext:host)();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now()||context.kind!=="local"&&(typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))){throw new Error("App context unavailable.")}return context}async function resolveSnapshotContext(){try{if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__)throw new Error;const context=await resolveAppContext();if(context.kind==="local"||!context.memberId||!context.binding||context.endpoint!==globalThis.location.origin||context.endpoint!==`https://${context.workspace}.oddington.ai`)throw new Error;const host=memberContext;const retained=context.snapshot;const isCurrent=()=>host===memberContext&&(retained?retained.isCurrent():context.isCurrent()&&context.expiresAt>Date.now());return{workspace:context.workspace,endpoint:context.endpoint,memberId:context.memberId,binding:context.binding,get expiresAt(){return retained?.credentials().expiresAt??context.expiresAt},get headers(){return{authorization:`Bearer ${retained?.credentials().accessToken??context.accessToken}`}},signal:context.signal?AbortSignal.any([context.signal,memberLifetime.signal]):memberLifetime.signal,isCurrent,...retained?{subscribe:retained.subscribe,async refresh(){try{const next=await resolveAppContext();if(!isCurrent()||next.kind==="local"||next.binding!==context.binding||next.memberId!==context.memberId||next.workspace!==context.workspace||next.endpoint!==context.endpoint)throw new Error}catch{throw new DataOperationError(isCurrent()?"unavailable":"context_unavailable",isCurrent())}}}:{}}}catch{throw new DataOperationError("context_unavailable")}}async function resolveDataContext(){try{if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){const installed2=routineTransport();if(installed2)return{local:installed2.request};const local=localRoutineRequest();if(local)return{local};const managed=privateRoutineRequest();if(managed)return{local:managed.request}}const host=memberContext;if(host!==undefined){const context=await host();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now())throw new Error;if(context.kind==="local")return{local:context.requestData};if(!context||!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now()||typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))throw new Error;return checked(context.workspace,context.endpoint,{authorization:`Bearer ${context.accessToken}`})}if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){const environment=typeof process==="undefined"?undefined:process.env;if(!environment||!/^[0-9a-f]{64}$/.test(environment.OS_ROUTINE_RUN??""))throw new Error;return checked(environment.OS_ROUTINE_WORKSPACE,oddingtonOrigin(environment),{"x-os-run":environment.OS_ROUTINE_RUN})}throw new Error}catch{throw new DataOperationError("context_unavailable")}}async function resolveFilesContext(){try{const environment=typeof __OS_BROWSER__!=="undefined"&&__OS_BROWSER__?{}:typeof process==="undefined"?{}:process.env;if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){const installed2=routineTransport();if(installed2)return{url:"private:installed",headers:{},isCurrent:installed2.isCurrent,local:installed2.request,localFiles:installed2.files,signal:undefined};const local=privateRoutineRequest(environment);if(local)return{url:local.identity,headers:{},isCurrent:local.isCurrent,local:local.request,localFiles:local.files,signal:undefined}}const host=memberContext;if(host){const context=await host();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now())throw new Error;if(context.kind==="local")return{url:`private:app:${context.workspace}/${context.memberId}`,headers:{},isCurrent:context.isCurrent,signal:context.signal,local:undefined,localFiles:context.requestFiles};if(!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now()||typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))throw new Error;return{...filesContext(context.workspace,context.endpoint,{authorization:`Bearer ${context.accessToken}`}),isCurrent:context.isCurrent,local:undefined,localFiles:undefined,signal:undefined}}if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){if(!/^[0-9a-f]{64}$/.test(environment.OS_ROUTINE_RUN??""))throw new Error;const workspace=environment.OS_ROUTINE_WORKSPACE;return{...filesContext(workspace,`https://${workspace}.oddington.ai`,{"x-os-run":environment.OS_ROUTINE_RUN}),local:undefined,localFiles:undefined,signal:undefined}}throw new Error}catch{throw new FileOperationError("unsupported_context",400)}}function filesContext(workspace,endpoint,headers){if(!workspace||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(workspace)||workspace.length>63||["auth","www","api","os"].includes(workspace)||endpoint!==`https://${workspace}.oddington.ai`)throw new Error;return{url:`${endpoint}/api/files`,headers:{...headers,"x-os-workspace":workspace},isCurrent:()=>true}}function checked(workspace,endpoint,headers){if(!workspace||!/^[a-z0-9][a-z0-9-]{0,127}$/.test(workspace))throw new Error;const origin=new URL(endpoint);if(origin.protocol!=="https:"||origin.username||origin.password||origin.search||origin.hash||origin.pathname!=="/")throw new Error;return{url:`${origin.origin}/api/data`,headers:{...headers,"x-os-workspace":workspace}}}var invalid6=()=>{throw new DataOperationError("invalid_query")};var unavailable=()=>{throw new DataOperationError("unavailable")};var text2=(value)=>typeof value==="string"&&value.length>0;function capture4(value,ancestors=new Set,depth=0){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object"||ancestors.has(value)||depth>32)return invalid6();ancestors.add(value);try{if(Array.isArray(value))return dataArray(value).map((item)=>capture4(item,ancestors,depth+1));return Object.fromEntries(Object.entries(dataProperties(value)).map(([key,descriptor])=>[key,capture4(descriptor.value,ancestors,depth+1)]))}finally{ancestors.delete(value)}}function recordPagination(queryRecords){function pages(query){const captured=capture4(query);const names=Object.keys(dataProperties(captured));for(const name of names){const selection2=dataProperties(captured[name]);if(Object.hasOwn(selection2,"$")){const options=dataProperties(selection2.$.value);if(Object.hasOwn(options,"after"))return invalid6()}}return iterate();async function*iterate(){const state=new Map(names.map((name)=>[name,{seen:new Set,count:undefined,next:undefined}]));let active=names,version;do{const request=Object.fromEntries(active.map((name)=>{const selection2=captured[name];const next=state.get(name).next;return[name,next===undefined?selection2:{...selection2,$:{...selection2.$,after:next}}]}));const response=await queryRecords(request);let page;try{page=capture4(response);const keys2=Object.keys(dataProperties(page));if(keys2.length!==active.length+1||keys2.some((key)=>key!=="$meta"&&!active.includes(key)))unavailable();const meta=page.$meta;if(Object.keys(dataProperties(meta)).sort().join(",")!=="collections,version"||!text2(meta.version))unavailable();version=meta.version;const collectionKeys=Object.keys(dataProperties(meta.collections));if(collectionKeys.some((key)=>!active.includes(key)))unavailable();for(const name of active){const records=dataArray(page[name]);const metadata=Object.hasOwn(meta.collections,name)?meta.collections[name]:{};if(Object.keys(dataProperties(metadata)).some((key)=>key!=="count"&&key!=="next")||Object.hasOwn(metadata,"next")&&!text2(metadata.next))unavailable();for(const record2 of records){dataProperties(record2);const row=record2;if(!validRecordRef(row.$ref)||!text2(row.$version))unavailable()}const current=state.get(name);if(captured[name].$?.count===true){if(!Number.isSafeInteger(metadata.count)||metadata.count<0)unavailable();current.count=metadata.count}else if(Object.hasOwn(metadata,"count"))unavailable();if(metadata.next!==undefined){if(current.seen.has(metadata.next))unavailable();current.seen.add(metadata.next)}current.next=metadata.next}}catch{return unavailable()}const collections=Object.fromEntries(names.map((name)=>{const current=state.get(name);return[name,{...current.count===undefined?{}:{count:current.count},...current.next===undefined?{}:{next:current.next}}]}));const output=Object.fromEntries(names.map((name)=>[name,active.includes(name)?page[name]:[]]));active=active.filter((name)=>state.get(name).next!==undefined);yield{...output,$meta:{version,collections}}}while(active.length)}}return{pages}}var FRAGMENT=/^(?:[a-zA-Z0-9._~!$&'()*+,;=:@/?-]|%[0-9a-fA-F]{2})+(?![\s\S])/;function parseRecordLink(value){if(typeof value!=="string")return;const separator=value.indexOf("#");const ref=separator<0?value:value.slice(0,separator);if(!validRecordRef(ref))return;if(separator<0)return{ref};const fragment=value.slice(separator+1);return FRAGMENT.test(fragment)?{ref,fragment}:undefined}function parseStoredRecordLink(value){return typeof value==="string"&&value.startsWith("[[")&&value.endsWith("]]")?parseRecordLink(value.slice(2,-2)):undefined}class RecordValidationError extends Error{path;constructor(message,path){super(message);this.path=path;this.name="RecordValidationError"}}class RecordFieldValidationError extends RecordValidationError{problem;field;expected;detail;constructor(problem,field,expected){super(`${problem} record field: ${field}`);this.problem=problem;this.field=field;this.expected=expected}atRecord(ref,schemaPath,fileSource=false){const problem=fileSource&&this.problem==="unknown"&&this.field==="media_type"?"source_schema":this.problem;this.message=recordFieldMessage(ref,this.field,problem,schemaPath,this.expected)??recordFieldMessage(ref,this.field,this.problem)??this.message;this.detail=recordFieldDetail(ref,this.field,problem,schemaPath,this.expected)??recordFieldDetail(ref,this.field,this.problem,undefined,this.expected);Object.assign(this,dataValidationMessageFacts({code:"invalid_change",message:this.message,detail:this.detail}));return this}}function fieldExpectation(field){return{type:field.kind,many:field.many,nullable:field.nullable,...field.kind==="number"&&field.precision!==undefined?{decimalPlaces:field.precision}:{},...field.kind==="date"&&field.format?{format:field.format}:{}}}var NAME=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fail3(message){throw new RecordValidationError(message)}function validateRecordText(value){if(/[\u0000\uD800-\uDFFF]/u.test(value))fail3("Record text must contain Unicode scalar values excluding U+0000")}function object3(value){if(!value||typeof value!=="object"||Array.isArray(value))fail3("Expected a field mapping");return value}function keys2(row,allowed,required){if(Object.keys(row).some((key)=>!allowed.includes(key))||required.some((key)=>!Object.hasOwn(row,key)))fail3("Unsupported or missing schema/record fields")}function valueDefinition(value,depth,native,named=false){if(depth>8)fail3("Invalid field definitions");const row={...object3(value)};const legacyMany=["enum_list","links","list"].includes(String(row.kind));if(legacyMany&&row.many!==undefined&&row.many!==true)fail3("Conflicting cardinality");if(Object.hasOwn(row,"inline")){if(row.kind!=="list"||typeof row.inline!=="boolean"||Object.hasOwn(row,"style"))fail3("Unsupported or conflicting inline style");if(row.inline)row.style="inline";delete row.inline}switch(row.kind){case"bool":row.kind="boolean";break;case"constant":row.kind="const";break;case"enum_list":row.kind="enum";row.many=true;break;case"links":row.kind="link";row.many=true;break;case"month":if(row.format!==undefined&&row.format!=="month")fail3("Conflicting date format");row.kind="date";row.format="month";break;case"list":{if(Object.hasOwn(row,"items")&&Object.hasOwn(row,"fields"))fail3("Conflicting list definitions");const nested=Object.hasOwn(row,"items")?row.items:row.fields;row.kind=nested===undefined?"string":"object";row.many=true;if(Object.hasOwn(row,"items"))delete row.items;if(nested!==undefined)row.fields=nested;break}case"map":if(Object.hasOwn(row,"keys")||Object.hasOwn(row,"values")){if(Object.hasOwn(row,"key")||Object.hasOwn(row,"value")||row.keys!=="YYYY-MM"||row.values!=="number")fail3("Unsupported or conflicting map definitions");row.key={kind:"date",format:"month"};row.value={kind:"number",...Object.hasOwn(row,"precision")?{precision:row.precision}:{}};delete row.keys;delete row.values;delete row.precision}break}if(row.nullable!==undefined&&typeof row.nullable!=="boolean")fail3("Invalid nullability");if(row.many!==undefined&&typeof row.many!=="boolean")fail3("Invalid cardinality");if(["description","term"].some((key)=>row[key]!==undefined&&typeof row[key]!=="string"))fail3("Invalid field documentation");const base={nullable:row.nullable===true,many:row.many===true,...native&&row.nullable===true?{optional:true}:{},...typeof row.description==="string"?{description:row.description}:{},...typeof row.term==="string"?{term:row.term}:{},...row.style==="inline"?{style:"inline"}:{}};if(row.style!==undefined&&(row.style!=="inline"||!base.many))fail3("Unsupported storage style");const common=["kind","nullable","many","style","description","term",...named?["name"]:[]];const check=(owned=[])=>keys2(row,[...common,...owned],["kind",...owned]);switch(row.kind){case"string":case"integer":case"boolean":case"datetime":check();return{...base,kind:row.kind};case"number":keys2(row,[...common,"precision"],["kind"]);if(row.precision!==undefined&&(!Number.isInteger(row.precision)||Number(row.precision)<0||Number(row.precision)>6))fail3("Unsupported decimal precision");return{...base,kind:"number",...row.precision!==undefined?{precision:row.precision}:{}};case"date":keys2(row,[...common,"format"],["kind"]);if(row.format!==undefined&&row.format!=="month")fail3("Unsupported date format");return{...base,kind:"date",...row.format==="month"?{format:"month"}:{}};case"const":check(["value"]);if(base.many||!["string","number","boolean"].includes(typeof row.value)||typeof row.value==="number"&&!Number.isFinite(row.value))fail3("Invalid constant");return{...base,kind:"const",value:row.value};case"enum":case"link":{const property=row.kind==="enum"?"values":"to";check([property]);const list2=row.kind==="link"&&typeof row.to==="string"?[row.to]:row[property];if(!Array.isArray(list2)||!list2.length||list2.length>1e5||new Set(list2).size!==list2.length||list2.some((item)=>typeof item!=="string"||!item||row.kind==="link"&&!NAME.test(item)))fail3("Invalid enum/link definition");return row.kind==="enum"?{...base,kind:"enum",values:list2}:{...base,kind:"link",to:list2}}case"object":check(["fields"]);return{...base,kind:"object",fields:fields2(row.fields,depth+1,native)};case"map":{check(["key","value"]);const key=valueDefinition(row.key,depth+1,native),value2=valueDefinition(row.value,depth+1,native);if(!["string","integer","date","enum"].includes(key.kind)||key.nullable||key.many)fail3("Unsupported map key definition");return{...base,kind:"map",key,value:value2}}default:return fail3("Unsupported field kind")}}function fields2(value,depth=0,native=false){if(depth>8||!Array.isArray(value)||!value.length||value.length>256)fail3("Invalid field definitions");const names=new Set;return value.map((definition)=>{const row=object3(definition);if(typeof row.name!=="string"||!NAME.test(row.name)||["constructor","prototype"].includes(row.name)||names.has(row.name))fail3("Invalid or duplicate field name");names.add(row.name);return{name:row.name,...valueDefinition(row,depth,native,true)}})}function validateRecordFields(value,definitions2,resolveLink,canonical=false){const row=object3(value);for(const[key,entry]of Object.entries(row)){validateRecordText(key);if(typeof entry==="string")validateRecordText(entry)}for(const name of Object.keys(row))if(!definitions2.some((field)=>field.name===name))throw new RecordFieldValidationError("unknown",name);for(const field of definitions2)if(!field.optional&&!Object.hasOwn(row,field.name))throw new RecordFieldValidationError("missing",field.name,fieldExpectation(field));for(const field of definitions2){const value2=row[field.name];if(!Object.hasOwn(row,field.name)&&field.optional)continue;if(value2===null&&field.nullable)continue;if(field.many){if(!Array.isArray(value2)||value2.length>1e5||["enum","link"].includes(field.kind)&&new Set(value2).size!==value2.length)throw new RecordFieldValidationError("invalid",field.name,fieldExpectation(field));try{for(const entry of value2)validateRecordFields({[field.name]:entry},[{...field,many:false,nullable:false}],resolveLink,canonical)}catch(error){if(error instanceof RecordFieldValidationError&&error.field===field.name)error.expected=fieldExpectation(field);throw error}continue}let valid=false;switch(field.kind){case"const":valid=value2===field.value;break;case"string":valid=typeof value2==="string";break;case"integer":valid=Number.isSafeInteger(value2);break;case"number":{valid=typeof value2==="number"&&Number.isFinite(value2);if(valid&&field.precision!==undefined){const scaled=value2*10**field.precision;valid=Number.isSafeInteger(Math.round(scaled))&&Math.abs(scaled-Math.round(scaled))<=Math.min(0.0000001,Number.EPSILON*Math.max(1,Math.abs(scaled))*4)}break}case"boolean":valid=typeof value2==="boolean";break;case"datetime":valid=typeof value2==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value2)&&Number.isFinite(Date.parse(value2))&&new Date(value2).toISOString()===value2;break;case"date":{const day=typeof value2==="string"&&field.format==="month"?`${value2}-01`:value2;valid=typeof value2==="string"&&(field.format==="month"?/^\d{4}-\d{2}$/.test(value2):/^\d{4}-\d{2}-\d{2}$/.test(value2))&&typeof day==="string"&&Number.isFinite(Date.parse(day))&&new Date(day).toISOString().slice(0,10)===day;break}case"enum":valid=typeof value2==="string"&&field.values.includes(value2);break;case"link":{const link=(canonical?parseRecordLink:parseStoredRecordLink)(value2);valid=!!link&&(!resolveLink||field.to.includes(resolveLink(link.ref,field.to)??""));break}case"object":if(!value2||typeof value2!=="object"||Array.isArray(value2))break;validateRecordFields(value2,field.fields,resolveLink,canonical);valid=true;break;case"map":{if(!value2||typeof value2!=="object"||Array.isArray(value2))break;const entries=Object.entries(value2);if(entries.length>1e5)fail3("Record map is too large");for(const[key,entry]of entries){if(["<<","__proto__","constructor","prototype"].includes(key))fail3("Unsupported record map key");const keyValue=field.key.kind==="integer"?Number(key):key;if(field.key.kind==="integer"&&String(keyValue)!==key)fail3("Invalid integer map key");validateRecordFields({key:keyValue},[{...field.key,name:"key"}],resolveLink,canonical);validateRecordFields({value:entry},[{...field.value,name:"value"}],resolveLink,canonical)}valid=true;break}}if(!valid)throw new RecordFieldValidationError("invalid",field.name,fieldExpectation(field))}}var boundOperators=["$gt","$gte","$lt","$lte"];var compare=(a,b)=>a<b?-1:a>b?1:0;var fail4=(message)=>{throw new RecordValidationError(`Invalid Records query: ${message}`)};function mapping3(value){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))return fail4("expected a mapping");return value}function publicDefinition(field){const{optional:_optional,style:_style,...definition}=field;if(definition.kind==="object")return{...definition,fields:definition.fields.map(publicField)};if(definition.kind==="map")return{...definition,key:publicDefinition(definition.key),value:publicDefinition(definition.value)};return structuredClone(definition)}function publicField(field){return{...publicDefinition(field),name:field.name}}function scalarField(name,schema2){if(name==="$ref")return{name,kind:"string",nullable:false,many:false};const field=schema2.fields.find((field2)=>field2.name===name);if(!field||field.many||field.kind==="object"||field.kind==="map")return fail4(`ineligible scalar field: ${name}`);return field}function conditionValue(value,field){if(field.kind==="link"||field.name==="$ref"){if(value!==null&&!(field.kind==="link"?parseRecordLink(value):validRecordRef(value)))return fail4(`invalid reference: ${field.name}`)}validateRecordFields({[field.name]:field.kind==="link"&&typeof value==="string"?`[[${value}]]`:value},[{...field,optional:false}]);return value}function queryEntries(query){const entries=Object.entries(mapping3(query));preflightSelections(entries);return entries}function preflightSelections(entries){if(entries.length<1||entries.length>16)return fail4("expected 1–16 collections");let nodes=0;const visit=(value,depth)=>{if(++nodes>256)return fail4("too many selection nodes");const selection2=mapping3(value);for(const[name,nested]of Object.entries(selection2)){if(name==="$")continue;if(depth>=4)return fail4("too many link levels");visit(nested,depth+1)}};for(const[,value]of entries)visit(value,0)}function selectionTree(value,schema2,collectionsByType,depth=0,many=false){const selection2=mapping3(value);const options=Object.hasOwn(selection2,"$")?mapping3(selection2.$):{};const allowed=depth===0?["where","fields","order","limit","count","after"]:many?["where","fields","order","limit"]:["where","fields"];allowed.push("timeline");if(Object.keys(options).some((key)=>!allowed.includes(key)))return fail4("unsupported option");const fields3=Object.hasOwn(options,"fields")?options.fields:schema2.fields.map((field)=>field.name);if(!Array.isArray(fields3)||fields3.some((name)=>typeof name!=="string"||!["$ref","$version"].includes(name)&&!schema2.fields.some((field)=>field.name===name))||new Set(fields3).size!==fields3.length)return fail4("invalid projection");const conditions=[];const signalConditions=[];if(Object.hasOwn(options,"timeline")&&options.timeline!==true)return fail4("invalid timeline option");if(Object.hasOwn(options,"where"))for(const[name,condition]of Object.entries(mapping3(options.where))){if(name==="$signals"){for(const[key,signalCondition]of Object.entries(mapping3(condition))){if(!validSignalKey(key))return fail4("invalid Signal key");if(typeof signalCondition==="string"){if(!validSignalText(signalCondition))return fail4("invalid Signal status");signalConditions.push([key,[signalCondition]])}else{const expression=mapping3(signalCondition);if(Object.keys(expression).length!==1)return fail4("invalid Signal condition");if(Object.hasOwn(expression,"$exists")&&expression.$exists===false)signalConditions.push([key,false]);else if(Object.hasOwn(expression,"$in")&&Array.isArray(expression.$in)&&expression.$in.length>=1&&expression.$in.length<=100&&expression.$in.every(validSignalText)&&new Set(expression.$in).size===expression.$in.length)signalConditions.push([key,[...expression.$in]]);else return fail4("invalid Signal condition")}}continue}const field=scalarField(name,schema2);let values=[condition];if(condition!==null&&typeof condition==="object"){const expression=mapping3(condition);if(!Object.hasOwn(expression,"$in")){const keys3=Object.keys(expression);if(keys3.length===0||keys3.some((key)=>!boundOperators.includes(key))||Object.hasOwn(expression,"$gt")&&Object.hasOwn(expression,"$gte")||Object.hasOwn(expression,"$lt")&&Object.hasOwn(expression,"$lte"))return fail4("invalid bounds");if(field.name==="$ref"||!["integer","number","date","datetime"].includes(field.kind))return fail4(`ineligible range field: ${name}`);const bounds=boundOperators.filter((operator)=>Object.hasOwn(expression,operator)).map((operator)=>{const value2=expression[operator];if(value2===null)return fail4("null bound");return[operator,conditionValue(value2,field)]});conditions.push([name,{bounds}]);continue}if(Object.keys(expression).length!==1||!Object.hasOwn(expression,"$in")||!Array.isArray(expression.$in)||expression.$in.length<1||expression.$in.length>100)return fail4("invalid $in");values=expression.$in}const checked2=values.map((value2)=>conditionValue(value2,field));if(new Set(checked2).size!==checked2.length)return fail4("duplicate $in value");conditions.push([name,checked2])}let order={field:"$ref",direction:"asc"};if(Object.hasOwn(options,"order")){const entries=Object.entries(mapping3(options.order));if(entries.length!==1)return fail4("order requires one field");const[name,direction]=entries[0];scalarField(name,schema2);if(direction!=="asc"&&direction!=="desc")return fail4("invalid order direction");order={field:name,direction}}const limit=Object.hasOwn(options,"limit")?options.limit:100;if(typeof limit!=="number"||!Number.isInteger(limit)||limit<1||limit>(depth===0?500:100))return fail4("invalid limit");if(Object.hasOwn(options,"count")&&typeof options.count!=="boolean")return fail4("invalid count");if(Object.hasOwn(options,"after")&&(typeof options.after!=="string"||options.after.length===0))return fail4("invalid cursor");const links=[];for(const[name,nested]of Object.entries(selection2)){if(name==="$")continue;const field=schema2.fields.find((field2)=>field2.name===name);if(!field||field.kind!=="link")return fail4(`ineligible link field: ${name}`);if(depth>=4)return fail4("too many link levels");const targets=new Map(field.to.flatMap((type)=>{const targets2=collectionsByType.get(type)??fail4(`unknown link target type: ${type}`);return targets2.map((target)=>[target.name,selectionTree(nested,target.schema,collectionsByType,depth+1,field.many)])}));links.push({name,many:field.many,targets})}return{fields:fields3,conditions,...signalConditions.length?{signalConditions}:{},...options.timeline===true?{timeline:true}:{},order,limit,count:options.count===true,...Object.hasOwn(options,"after")?{after:options.after}:{},explicitOrder:Object.hasOwn(options,"order"),explicitLimit:Object.hasOwn(options,"limit"),links}}function selectionBinding(selection2,top=true,many=false){return{fields:selection2.fields,conditions:[...selection2.conditions].sort(([a],[b])=>compare(a,b)),...selection2.signalConditions?{signalConditions:[...selection2.signalConditions].sort(([a],[b])=>compare(a,b))}:{},...selection2.timeline?{timeline:true}:{},order:top||many&&selection2.explicitOrder?selection2.order:null,limit:top||many&&selection2.explicitLimit?selection2.limit:null,count:selection2.count,links:[...selection2.links].sort((a,b)=>compare(a.name,b.name)).map((link)=>({name:link.name,many:link.many,targets:[...link.targets].sort(([a],[b])=>compare(a,b)).map(([collection,nested])=>[collection,selectionBinding(nested,false,link.many)])}))}}function planIndexQuery(query,catalogue){const entries=queryEntries(query);const collections=new Map(catalogue.map((collection)=>[collection.name,collection]));const byType=new Map;for(const collection of catalogue){const targets=byType.get(collection.schema.type)??[];targets.push(collection);byType.set(collection.schema.type,targets)}return entries.map(([name,value])=>{const target=collections.get(name)??fail4(`unknown collection: ${name}`);return{name,selection:selectionTree(value,target.schema,byType)}})}function indexSelectionBinding(context,collection,selection2){return JSON.stringify({...context,collection,selection:selectionBinding(selection2)})}function cursorPosition(value,binding,limit){let payload;try{payload=mapping3(value)}catch{return fail4("invalid cursor")}const{position,ref}=payload;if(Object.keys(payload).length!==4||payload.format!==1||payload.binding!==binding||typeof position!=="number"||!Number.isSafeInteger(position)||position<=0||position%limit!==0||typeof ref!=="string"||!validRecordRef(ref))return fail4("incompatible cursor");return{position,ref}}var invalid7=()=>{throw new DataOperationError("unavailable",true)};var object4=(value)=>{if(!value||typeof value!=="object"||Array.isArray(value))return invalid7();return value};var keys3=(value,expected)=>Object.keys(value).sort().join(",")===expected;var hash=(value)=>typeof value==="string"&&/^[0-9a-f]{40}$/.test(value);var time=(value)=>typeof value==="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value)&&Number.isFinite(Date.parse(value));var sorted=(values)=>values.every((value,i)=>i===0||values[i-1]<value);function json(value){if(value===null||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value)||dataText(value))return;if(Array.isArray(value)){for(const item of value)json(item);return}for(const[key,item]of Object.entries(object4(value))){if(!dataText(key))return invalid7();json(item)}}function stable(value){if(Array.isArray(value))return`[${value.map(stable).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([key,item])=>`${JSON.stringify(key)}:${stable(item)}`).join(",")}}`;return JSON.stringify(value)}var slot=(values,field)=>Object.hasOwn(values,field)?{present:true,value:values[field]}:{present:false};function apply(book,event){const records=book.get(event.collection),prior=records.get(event.ref);if(event.kind==="create"){if(prior)return invalid7();records.set(event.ref,structuredClone(event.values))}else if(event.kind==="delete"){if(!prior||stable(prior)!==stable(event.values))return invalid7();records.delete(event.ref)}else if(event.kind==="rename"){const before=records.get(event.previousRef);if(!before||prior)return invalid7();records.delete(event.previousRef);records.set(event.ref,before)}else if(event.kind==="update"){if(!prior||stable(slot(prior,event.field))!==stable(event.before)||stable(event.before)===stable(event.after))return invalid7();if(event.after.present)Object.defineProperty(prior,event.field,{value:structuredClone(event.after.value),enumerable:true,configurable:true,writable:true});else delete prior[event.field]}}function validateSnapshotHistory(input,collections,version){const row=object4(input),selections=object4(row.fields);if(!keys3(row,"commits,fields,through")||!hash(row.through)||version!==`current-${row.through}`||!Array.isArray(row.commits)||!row.commits.length||!Object.keys(selections).length||!sorted(Object.keys(selections)))return invalid7();const book=new Map;for(const[collection,selection2]of Object.entries(selections)){const selected=object4(selection2),fields3=selected.fields;if(!Object.hasOwn(collections,collection)||!keys3(selected,"fields")||!Array.isArray(fields3)||!fields3.length||fields3.some((field)=>typeof field!=="string"||!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field))||!sorted(fields3))return invalid7();book.set(collection,new Map)}const history=row,seen=new Set;let parent=null;for(const group of history.commits){if(!keys3(object4(group),"authoredAt,commit,committedAt,events,firstParent")||!hash(group.commit)||seen.has(group.commit)||group.firstParent!==parent||!time(group.authoredAt)||!time(group.committedAt)||!Array.isArray(group.events))return invalid7();seen.add(group.commit);parent=group.commit;let previous;const created=new Set;for(const event of group.events){object4(event);if(!book.has(event.collection)||!validRecordRef(event.ref)||!event.ref.startsWith(`${event.collection}/`))return invalid7();const fields3=history.fields[event.collection].fields;if(event.kind==="create"||event.kind==="delete"){if(!keys3(event,"collection,kind,ref,values")||Object.keys(object4(event.values)).some((field)=>!fields3.includes(field)))return invalid7();json(event.values);if(event.kind==="create")created.add(event.ref)}else if(event.kind==="rename"){if(!keys3(event,"collection,kind,previousRef,ref")||!validRecordRef(event.previousRef)||!event.previousRef.startsWith(`${event.collection}/`)||event.previousRef===event.ref)return invalid7()}else if(event.kind==="update"){if(!keys3(event,"after,before,collection,field,kind,ref")||!fields3.includes(event.field)||created.has(event.ref))return invalid7();for(const value of[event.before,event.after]){object4(value);if(value.present===false?!keys3(value,"present"):value.present!==true||!keys3(value,"present,value"))return invalid7();if(value.present)json(value.value)}}else return invalid7();const order=[event.kind==="delete"?0:1,event.ref,event.kind==="update"?1:0,event.kind==="update"?event.field:""];if(previous){const index=order.findIndex((value,i)=>value!==previous[i]);if(index===-1||order[index]<previous[index])return invalid7()}previous=order;apply(book,event)}const refs=new Set;for(const records of book.values())for(const ref of records.keys()){if(refs.has(ref))return invalid7();refs.add(ref)}}if(parent!==history.through)return invalid7();for(const[collection,records]of book){const expected=collections[collection].map((record2)=>[record2.$ref,Object.fromEntries(history.fields[collection].fields.filter((field)=>Object.hasOwn(record2,field)).map((field)=>[field,record2[field]]))]);if(stable([...records].sort(([a],[b])=>a<b?-1:1))!==stable(expected))return invalid7()}return history}function captureHistoryInput(input,operation){const properties=dataProperties(input),row=Object.fromEntries(Object.entries(properties).map(([key,property])=>[key,property.value]));if(Object.keys(row).some((key)=>!(operation==="records"?["collection","at"]:["collection","ref","field"]).includes(key))||typeof row.collection!=="string"||operation==="records"&&!time(row.at)||Object.hasOwn(row,"ref")&&!validRecordRef(row.ref)||Object.hasOwn(row,"field")&&typeof row.field!=="string")throw new DataOperationError("invalid_query");return row}function readSnapshotHistory(history,input,operation){if(!history||!Object.hasOwn(history.fields,input.collection)||input.field!==undefined&&!history.fields[input.collection].fields.includes(input.field))throw new DataOperationError("invalid_query");if(operation==="changes")return structuredClone(history.commits.flatMap(({firstParent:_parent,...group})=>{const events=group.events.filter((event)=>event.collection===input.collection&&(input.ref===undefined||event.ref===input.ref)&&(input.field===undefined||event.kind==="update"&&event.field===input.field));return events.length?[{...group,events}]:[]}));let index=history.commits.length-1;while(index>=0&&Date.parse(history.commits[index].committedAt)>Date.parse(input.at))index--;const book=new Map([[input.collection,new Map]]);let selected=false;for(let i=0;i<=index;i++)for(const event of history.commits[i].events)if(event.collection===input.collection){selected=true;apply(book,event)}return{commit:selected?history.commits[index].commit:null,records:[...book.get(input.collection)].sort(([a],[b])=>a<b?-1:1).map(([$ref,values])=>({$ref,values}))}}var snapshotCollection=(catalogue,ref)=>catalogue.filter((c)=>ref.startsWith(`${c.name}/`)).sort((a,b)=>b.name.length-a.name.length)[0];var invalid8=()=>{throw new DataOperationError("unavailable",true)};var object5=(value)=>{if(!value||typeof value!=="object"||Array.isArray(value))return invalid8();return value};function stable2(value){if(Array.isArray(value))return`[${value.map(stable2).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([key,entry])=>`${JSON.stringify(key)}:${stable2(entry)}`).join(",")}}`;return JSON.stringify(value)}function schemaText(value){if(typeof value==="string"&&!dataText(value))return invalid8();if(value&&typeof value==="object")for(const[key,entry]of Object.entries(value)){if(!dataText(key))return invalid8();schemaText(entry)}}function validateSnapshotEnvelope(input,repository,name,bodies=[],timelines=[]){try{const row=object5(input);const legacy=row.format==="data-snapshot.v1";if(!["collections,format,name,repository,schemas,version","collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(","))||!legacy&&row.format!=="data-snapshot.v2"||legacy&&timelines.length>0||row.repository!==repository||row.name!==name||!dataVersion(row.version))return invalid8();const schemas2=object5(row.schemas),collections=object5(row.collections);schemaText(schemas2);const names=Object.keys(collections);for(const subset of[bodies,timelines])if(new Set(subset).size!==subset.length||subset.some((name2)=>!names.includes(name2)))return invalid8();if(!names.length||names.join("\x00")!==[...names].sort().join("\x00")||Object.keys(schemas2).join("\x00")!==names.join("\x00"))return invalid8();const catalogue=names.map((name2)=>{const schema2=object5(schemas2[name2]);if(!validRecordRef(`${name2}/example`)||schema2.name!==name2||typeof schema2.type!=="string"||!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type)||schema2.description!==undefined&&!dataText(schema2.description)||Object.keys(schema2).some((key)=>!["name","type","description","fields"].includes(key)))return invalid8();const definitions2=fields2(schema2.fields,0,true);if(stable2(definitions2.map(publicField))!==stable2(schema2.fields))return invalid8();return{name:name2,schema:{type:schema2.type,fields:definitions2,...schema2.description===undefined?{}:{description:schema2.description}}}});const types=new Map;for(const collection of catalogue){const records=collections[collection.name];if(!Array.isArray(records))return invalid8();let previous="";for(const record2 of records){const value=object5(record2);if(!validRecordRef(value.$ref)||snapshotCollection(catalogue,value.$ref)?.name!==collection.name||value.$ref<=previous||types.has(value.$ref)||typeof value.$version!=="string"||!/^record-v1:[0-9a-f]{64}$/.test(value.$version))return invalid8();types.set(value.$ref,collection.schema.type);previous=value.$ref}}for(const collection of catalogue)for(const record2 of collections[collection.name]){const{$ref:_ref,$version:_version,$body,$signals,$timeline,...values}=record2;if(legacy){if(Object.hasOwn(record2,"$signals")||Object.hasOwn(record2,"$timeline"))return invalid8()}else{captureRecordSignals($signals);if(timelines.includes(collection.name)){if(!Array.isArray($timeline))return invalid8();$timeline.forEach((value)=>captureTimeline(value))}else if(Object.hasOwn(record2,"$timeline"))return invalid8()}if(Object.hasOwn(record2,"$body")&&(!bodies.includes(collection.name)||typeof $body!=="string"))return invalid8();validateRecordFields(values,collection.schema.fields,(ref,targets)=>{return types.get(ref)??targets[0]},true)}const normalized=legacy?Object.fromEntries(Object.entries(collections).map(([collection,records])=>[collection,records.map((record2)=>({...record2,$signals:[]}))])):collections;return{format:"data-snapshot.v2",repository,name,version:row.version,bodyCollections:[...bodies],timelineCollections:[...timelines],catalogue,collections:normalized,...Object.hasOwn(row,"history")?{history:validateSnapshotHistory(row.history,normalized,row.version)}:{}}}catch{return invalid8()}}var compare2=(a,b)=>a<b?-1:a>b?1:0;var fail5=(message)=>{throw new RecordValidationError(`Invalid Records query: ${message}`)};function continuation(value,binding,matching,limit){const{position,ref}=cursorPosition(value,binding,limit);if(position>=matching.length||ref!==matching[position-1]?.$ref)return fail5("incompatible cursor");return position}function matches(record2,selection2){return(selection2.signalConditions??[]).every(([key,statuses])=>{if(!Array.isArray(record2.$signals))return fail5("Signals are unavailable");const signal=record2.$signals?.find((row)=>row.key===key);return statuses===false?signal===undefined:signal!==undefined&&statuses.includes(signal.status)})&&selection2.conditions.every(([field,condition])=>{if(!Object.hasOwn(record2,field))return false;const value=record2[field];if(Array.isArray(condition))return condition.some((candidate)=>candidate===value);if(value===null)return false;return condition.bounds.every(([operator,bound])=>{const result=typeof value==="number"&&typeof bound==="number"?value-bound:compare2(value,bound);switch(operator){case"$gt":return result>0;case"$gte":return result>=0;case"$lt":return result<0;case"$lte":return result<=0}})})}function ordered(a,b,{field,direction}){const left=a[field],right=b[field];const missingLeft=left===null||left===undefined,missingRight=right===null||right===undefined;let result=0;if(missingLeft!==missingRight)return missingLeft?1:-1;if(!missingLeft&&!missingRight){result=typeof left==="number"&&typeof right==="number"?left-right:typeof left==="boolean"&&typeof right==="boolean"?Number(left)-Number(right):compare2(left,right);if(direction==="desc")result=-result}return result||compare2(a.$ref,b.$ref)}function*evaluateRecordsQuery(query,catalogue,context,maxRecords,cloneValue,bodyCollections=[]){const{version}=context;const selections=planIndexQuery(query,catalogue);const scanned=new Map;for(const{name}of selections)scanned.set(name,yield{operation:"scan",collection:name});if(maxRecords!==undefined){const total=selections.reduce((sum,{name,selection:selection2})=>sum+scanned.get(name).filter((record2)=>matches(record2,selection2)).length,0);if(total>maxRecords)throw new DataOperationError("capacity",false,undefined,undefined,{code:"record_limit_exceeded",maxRecords,collections:selections.map((row)=>row.name)})}let occurrences=0;function*expand(record2,collection,selection2,fragment){if(++occurrences>2000)return fail5("too many returned Record occurrences");const result=Object.fromEntries(["$ref","$version",...selection2.fields.filter((field)=>!["$ref","$version"].includes(field))].filter((field)=>Object.hasOwn(record2,field)).map((field)=>[field,cloneValue(record2[field])]));if(Object.hasOwn(record2,"$signals"))result.$signals=cloneValue(record2.$signals);if(selection2.timeline){if(!Array.isArray(record2.$timeline))return fail5("Timeline is unavailable");result.$timeline=cloneValue(record2.$timeline)}if(bodyCollections.includes(collection)&&typeof record2.$body==="string")result.$body=record2.$body;if(fragment!==undefined)result.$fragment=fragment;for(const link of selection2.links){if(!Object.hasOwn(record2,link.name))continue;const value=record2[link.name];let expanded;if(value===null)expanded=null;else{const refs=link.many?value:[value];let matching=[];for(const value2 of refs){const{ref,fragment:fragment2}=parseRecordLink(value2)??fail5("invalid stored link");const target=yield{operation:"lookup",ref};if(!target)return fail5("unresolved stored link");const nested=link.targets.get(target.collection)??fail5("incompatible stored link");if(matches(target.record,nested))matching.push({record:target.record,collection:target.collection,selection:nested,fragment:fragment2})}const options=link.targets.values().next().value;if(options.explicitOrder)matching.sort((a,b)=>ordered(a.record,b.record,options.order));if(link.many&&!options.explicitLimit&&matching.length>100)return fail5("too many matching linked Records");if(options.explicitLimit)matching=matching.slice(0,options.limit);const records=[];for(const{record:record3,collection:collection2,selection:selection3,fragment:fragment2}of matching)records.push(yield*expand(record3,collection2,selection3,fragment2));expanded=link.many?records:records[0]??null}Object.defineProperty(result,link.name,{value:expanded,enumerable:true,writable:true,configurable:true})}return result}const metadata={version,collections:{}};const results=[];for(const{name,selection:selection2}of selections){const matching=scanned.get(name).filter((record2)=>matches(record2,selection2)).sort((a,b)=>ordered(a,b,selection2.order));const binding=indexSelectionBinding(context,name,selection2);const start=selection2.after===undefined?0:continuation(yield{operation:"open",token:selection2.after},binding,matching,selection2.limit);const end=maxRecords===undefined?Math.min(start+selection2.limit,matching.length):matching.length;const records=[];for(let index=start;index<end;index++){if(maxRecords!==undefined&&(index-start)%selection2.limit===0)occurrences=0;records.push(yield*expand(matching[index],name,selection2))}const page=selection2.count?{count:matching.length}:{};if(maxRecords===undefined&&end<matching.length){const token=yield{operation:"seal",payload:{format:1,binding,position:end,ref:matching[end-1].$ref}};if(typeof token!=="string"||token.length===0)return fail5("invalid sealed cursor");page.next=token}if(Object.keys(page).length)Object.defineProperty(metadata.collections,name,{value:page,enumerable:true,writable:true,configurable:true});results.push([name,records])}return{...Object.fromEntries(results),$meta:metadata}}var snapshotAcquisitionType="application/vnd.os.data-snapshot.v2+json";var snapshotAcquisitionFormat="data-snapshot-acquisition.v2";var snapshotPairHeader="Snapshot-Pair";var validSnapshotPairToken=(value)=>typeof value==="string"&&/^snapshot-pair-v1:[0-9a-f]{64}$/.test(value);var snapshotArtifactHeader="Snapshot-Artifact";var validSnapshotArtifactToken=(value)=>typeof value==="string"&&/^snapshot-artifact-v1:[0-9a-f]{64}$/.test(value);var snapshotUpdatesProtocol="os.data-snapshot.updates.v1";var snapshotUpdatesCredentialPrefix="os.member.";var snapshotUpdateHint="update";var invalid9=()=>{throw new DataOperationError("unavailable",true)};var object6=(v)=>v&&typeof v==="object"&&!Array.isArray(v)?v:invalid9();var uuid=(v)=>typeof v==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v);var time2=(v)=>typeof v==="string"&&Number.isFinite(Date.parse(v));var recordVersion=(v)=>typeof v==="string"&&/^record-v1:[0-9a-f]{64}$/.test(v);var keys4=(v,allowed)=>Object.keys(v).every((k)=>allowed.includes(k));function validateAcquisition(input,repository,name){const row=object6(input),snapshot=object6(row.snapshot);if(Object.keys(row).sort().join(",")!=="changes,format,snapshot"||row.format!==snapshotAcquisitionFormat||!keys4(snapshot,["id","name","refreshedAt","repository","version","collections","bodies","timelines"])||!uuid(snapshot.id)||snapshot.repository!==repository||snapshot.name!==name||!dataVersion(snapshot.version)||!time2(snapshot.refreshedAt)||!Array.isArray(snapshot.collections)||!snapshot.collections.length||!snapshot.collections.every((c)=>typeof c==="string"&&validRecordRef(`${c}/example`))||snapshot.collections.join("\x00")!==[...new Set(snapshot.collections)].sort().join("\x00")||!Array.isArray(row.changes))return invalid9();const bodies=snapshot.bodies===undefined?[]:snapshot.bodies;const timelines=snapshot.timelines===undefined?[]:snapshot.timelines;for(const subset of[bodies,timelines])if(!Array.isArray(subset)||subset.some((c)=>!snapshot.collections.includes(c))||subset.join("\x00")!==[...new Set(subset)].sort().join("\x00"))return invalid9();return{snapshot:{...snapshot,bodies,timelines},changes:validateSnapshotChanges(row.changes,snapshot.collections)}}function validateSnapshotChanges(input,collections){try{if(!Array.isArray(input))return invalid9();const ids=new Set;let unpublished=false;for(const value of input){const c=object6(value),effect=object6(c.effect);if(!keys4(c,["id","version","ref","recordVersion","effect","updatedAt","person","source","publication"])||!uuid(c.id)||ids.has(c.id)||!dataVersion(c.version)||!validRecordRef(c.ref)||!collections.some((name)=>c.ref.startsWith(`${name}/`))||!recordVersion(c.recordVersion)||!time2(c.updatedAt))return invalid9();ids.add(c.id);if(c.person!==undefined){const person=object6(c.person);if(!keys4(person,["id","name","email"])||!uuid(person.id)||person.name!==undefined&&!dataText(person.name)||person.email!==undefined&&!dataText(person.email))return invalid9()}if(c.source!==undefined){const source=object6(c.source);if(Object.keys(source).sort().join(",")!=="id,kind"||source.kind!=="app"&&source.kind!=="routine"||!dataText(source.id))return invalid9()}if(c.publication!==undefined){const publication=object6(c.publication);if(unpublished||Object.keys(publication).sort().join(",")!=="commit,time"||typeof publication.commit!=="string"||!/^[0-9a-f]{40}$/.test(publication.commit)||!time2(publication.time))return invalid9()}else unpublished=true;if(effect.kind==="set"){if(Object.keys(effect).sort().join(",")!=="field,kind,value"||!dataText(effect.field)||effect.field.startsWith("$")||["id","type","__proto__","constructor","prototype"].includes(effect.field))return invalid9()}else if(effect.kind==="link"||effect.kind==="unlink"){if(!keys4(effect,["kind","field","refs",...effect.kind==="link"?["remove"]:[]])||!dataText(effect.field)||effect.field.startsWith("$")||["id","type","__proto__","constructor","prototype"].includes(effect.field)||!Array.isArray(effect.refs)||!effect.refs.length||effect.refs.length>1e5||effect.refs.some((ref)=>!validRecordRef(ref))||new Set(effect.refs).size!==effect.refs.length)return invalid9();if(effect.remove!==undefined&&(!Array.isArray(effect.remove)||!effect.remove.length||effect.remove.length>1e5||effect.remove.some((ref)=>!validRecordRef(ref))||new Set(effect.remove).size!==effect.remove.length))return invalid9()}else if(effect.kind==="signal"){if(Object.keys(effect).sort().join(",")!=="key,kind,value")return invalid9();const value2=object6(effect.value);if(!keys4(value2,["label","status","reason","related","asOf","number"]))return invalid9();const{number,...assessment}=value2;captureSignal({...assessment,key:effect.key});if(c.publication||Object.hasOwn(value2,"number"))captureRecordSignal({...value2,key:effect.key})}else if(effect.kind==="timeline"){if(Object.keys(effect).sort().join(",")!=="entry,kind")return invalid9();captureTimeline(effect.entry)}else if(effect.kind==="create"||effect.kind==="delete"){if(!keys4(effect,["fields","kind","signals","timeline"]))return invalid9();object6(effect.fields);if(Object.hasOwn(effect,"signals"))captureRecordSignals(effect.signals);if(Object.hasOwn(effect,"timeline")){if(!Array.isArray(effect.timeline))return invalid9();effect.timeline.forEach((value2)=>captureTimeline(value2))}}else return invalid9()}return input}catch{return invalid9()}}function materializeSnapshot(envelope,changes,version){try{if(!changes.length)return envelope;const rows=new Map(Object.values(envelope.collections).flat().map((r)=>[r.$ref,structuredClone(r)]));for(const c of changes){const schema2=snapshotCollection(envelope.catalogue,c.ref);if(!schema2)return invalid9();const effect=c.effect;const definitions2="field"in effect?schema2.schema.fields.filter((f)=>f.name===effect.field):schema2.schema.fields;if("field"in effect&&!definitions2.length)return invalid9();let values;if(effect.kind==="link"||effect.kind==="unlink"){const field=definitions2[0];if(field.kind!=="link"||!field.many&&effect.kind==="link"&&effect.refs.length!==1)return invalid9();const targets=[...effect.refs,...effect.kind==="link"?effect.remove??[]:[]];for(const ref of targets)validateRecordFields({[effect.field]:field.many?[ref]:ref},definitions2,(_ref,allowed)=>allowed[0],true);values={[effect.field]:field.many?effect.refs:effect.refs[0]}}else values=effect.kind==="set"?{[effect.field]:effect.value}:("fields"in effect)?effect.fields:{};if(effect.kind!=="signal"&&effect.kind!=="timeline")validateRecordFields(values,definitions2,(_ref,targets)=>targets[0],true);if(!c.publication)continue;const prior=rows.get(c.ref);if(effect.kind==="set"){if(!prior)return invalid9();rows.set(c.ref,{...prior,[effect.field]:effect.value,$version:c.recordVersion})}else if(effect.kind==="link"||effect.kind==="unlink"){if(!prior)return invalid9();const field=definitions2[0];const current=prior[effect.field];const value=field.many?effect.kind==="link"?[...new Set([...Array.isArray(current)?current:[],...effect.refs])].filter((ref)=>!effect.remove?.includes(String(ref))):(Array.isArray(current)?current:[]).filter((ref)=>!effect.refs.includes(String(ref))):effect.kind==="link"?effect.remove?.includes(effect.refs[0])?null:effect.refs[0]:effect.refs.includes(String(current))?null:current;rows.set(c.ref,{...prior,[effect.field]:value,$version:c.recordVersion})}else if(effect.kind==="signal"){if(!prior||!effect.value.number)return invalid9();const signal=captureRecordSignal({...effect.value,key:effect.key});const signals=captureRecordSignals(prior.$signals);const index=signals.findIndex((row)=>row.key===effect.key);if(index<0)signals.push(signal);else signals[index]=signal;rows.set(c.ref,{...prior,$signals:captureRecordSignals(signals),$version:c.recordVersion})}else if(effect.kind==="timeline"){if(!prior)return invalid9();rows.set(c.ref,{...prior,$version:c.recordVersion,...envelope.timelineCollections.includes(schema2.name)?{$timeline:[...prior.$timeline,effect.entry]}:{}})}else if(effect.kind==="create"){if(prior)return invalid9();rows.set(c.ref,{...effect.fields,$ref:c.ref,$version:c.recordVersion,$signals:effect.signals??[],...envelope.timelineCollections.includes(schema2.name)?{$timeline:effect.timeline??[]}:{}})}else{if(!prior)return invalid9();rows.delete(c.ref)}}const materialized=validateSnapshotEnvelope({format:envelope.format,repository:envelope.repository,name:envelope.name,version,schemas:Object.fromEntries(envelope.catalogue.map((c)=>[c.name,{name:c.name,type:c.schema.type,...c.schema.description===undefined?{}:{description:c.schema.description},fields:c.schema.fields.map(publicField)}])),collections:Object.fromEntries(envelope.catalogue.map((c)=>[c.name,[...rows.values()].filter((r)=>snapshotCollection(envelope.catalogue,r.$ref)?.name===c.name).sort((a,b)=>a.$ref<b.$ref?-1:1)]))},envelope.repository,envelope.name,envelope.bodyCollections,envelope.timelineCollections);return{...materialized,...envelope.history?{history:envelope.history}:{}}}catch{return invalid9()}}function applySnapshotMutation(envelope,prior,mutation,installation){const rejected=()=>{throw new DataOperationError("unavailable")};let changes=prior;if(mutation.kind==="discard"){changes=prior.filter((c)=>!mutation.selected.some((s)=>s.id===c.id&&s.version===c.version))}else{const accepted=validateSnapshotChanges(mutation.changes,installation.catalogue.map((c)=>c.name));const ids=new Set(accepted.map((c)=>c.id));changes=[...prior.filter((c)=>mutation.kind==="publish"?!mutation.selected.some((s)=>s.id===c.id&&s.version===c.version):!ids.has(c.id)),...accepted.filter((c)=>mutation.kind!=="publish"||!prior.some((p)=>p.id===c.id&&p.version!==c.version))];changes=[...changes.filter((c)=>c.publication),...changes.filter((c)=>!c.publication)];if(mutation.kind==="publish"){if(accepted.some((c)=>!c.publication)||!Array.isArray(mutation.effects))return rejected();const effects=mutation.effects.map((e)=>{const source=accepted.find((c)=>c.ref===e.ref);if(!source||snapshotCollection(envelope.catalogue,e.ref)?.name!==e.collection||!["set","signal","timeline","create","delete"].includes(e.effect.kind))return rejected();return{...source,id:crypto.randomUUID(),recordVersion:e.version,effect:e.effect}});validateSnapshotChanges(effects,installation.catalogue.map((c)=>c.name));if(mutation.records!==undefined){materializeSnapshot(envelope,[...accepted,...effects].map(({publication:_publication,...c})=>c),envelope.version);if(!Array.isArray(mutation.records)||new Set(mutation.records.map((r)=>r.$ref)).size!==mutation.records.length)return rejected();const refs=new Set(mutation.records.map((r)=>r.$ref));const selected=[...accepted,...prior.filter((c)=>mutation.selected.some((s)=>s.id===c.id&&s.version===c.version))];if(selected.some((c)=>c.effect.kind!=="delete"&&!refs.has(c.ref)))return rejected();if(accepted.some((c)=>!mutation.effects.some((e)=>e.ref===c.ref&&("field"in c.effect?"field"in e.effect&&e.effect.field===c.effect.field:c.effect.kind==="signal"?e.effect.kind==="signal"&&e.effect.key===c.effect.key:e.effect.kind===c.effect.kind))))return rejected();if(mutation.effects.some((e)=>!accepted.some((c)=>c.ref===e.ref)||snapshotCollection(envelope.catalogue,e.ref)?.name!==e.collection||!["set","signal","timeline","create","delete"].includes(e.effect.kind)||e.effect.kind!=="delete"&&!mutation.records.some((r)=>r.$ref===e.ref&&r.$version===e.version)))return rejected();const rows=new Map(Object.values(envelope.collections).flat().map((r)=>[r.$ref,r]));for(const e of mutation.effects)if(e.effect.kind==="delete")rows.delete(e.ref);for(const record2 of mutation.records){const collection=snapshotCollection(envelope.catalogue,record2.$ref)?.name;if(!collection)return rejected();const{$body,$timeline,...fields3}=record2;rows.set(record2.$ref,{...fields3,...envelope.bodyCollections?.includes(collection)&&$body!==undefined?{$body}:{},...envelope.timelineCollections.includes(collection)?{$timeline}:{}})}envelope=validateSnapshotEnvelope({format:envelope.format,repository:envelope.repository,name:envelope.name,version:`snapshot-${crypto.randomUUID()}`,schemas:Object.fromEntries(envelope.catalogue.map((c)=>[c.name,{name:c.name,type:c.schema.type,...c.schema.description===undefined?{}:{description:c.schema.description},fields:c.schema.fields.map(publicField)}])),collections:Object.fromEntries(envelope.catalogue.map((c)=>[c.name,[...rows.values()].filter((r)=>snapshotCollection(envelope.catalogue,r.$ref)?.name===c.name).sort((a,b)=>a.$ref<b.$ref?-1:1)]))},envelope.repository,envelope.name,envelope.bodyCollections,envelope.timelineCollections);return{envelope,changes}}if(!accepted.length||!mutation.effects.length)return rejected();envelope=materializeSnapshot(envelope,effects,`snapshot-${crypto.randomUUID()}`)}else{if(!accepted.length||accepted.some((c)=>c.publication))return rejected();materializeSnapshot(envelope,accepted,envelope.version)}}return{envelope,changes}}var unavailable2=()=>{throw new DataOperationError("unavailable",true)};function request(value){return new Promise((resolve,reject)=>{value.onsuccess=()=>resolve(value.result);value.onerror=()=>reject(new DataOperationError("unavailable",true))})}function completed(transaction){const done=new Promise((resolve,reject)=>{transaction.oncomplete=()=>resolve();transaction.onabort=transaction.onerror=()=>reject(new DataOperationError("unavailable",true))});done.catch(()=>{});return done}function encode(bytes){return btoa(Array.from(bytes,(byte)=>String.fromCharCode(byte)).join(""))}async function openSnapshotStore(){const opening=indexedDB.open("oddington.data.snapshots.v2",2);opening.onupgradeneeded=()=>{opening.result.createObjectStore("bases");if(opening.transaction.objectStoreNames.contains("current"))return;opening.result.createObjectStore("current");opening.result.createObjectStore("changes");const records=opening.result.createObjectStore("records",{keyPath:["installation","ref"]});records.createIndex("collection",["installation","collection"])};const database=await request(opening);database.onversionchange=()=>database.close();return{close(){database.close()},async current(partition){const transaction=database.transaction(["current","records","changes","bases"],"readonly"),done=completed(transaction);const value=await request(transaction.objectStore("current").get(partition));if(!value){await done;return}if(value.format!=="data-snapshot.v2"||!Array.isArray(value.timelineCollections)||value.partition!==partition||!value.id||!value.snapshotId||value.pairToken!==""&&!validSnapshotPairToken(value.pairToken)||!validSnapshotArtifactToken(value.artifactToken)||!value.version||!Array.isArray(value.catalogue)||!value.counts||!(value.cursorKey instanceof Uint8Array)||value.cursorKey.length!==32){await done;return}const changes=await request(transaction.objectStore("changes").get(value.id));let complete=!!await request(transaction.objectStore("bases").getKey(value.artifactToken))&&Array.isArray(changes)&&changes.length===value.changeCount;for(const collection of value.catalogue){const count=await request(transaction.objectStore("records").index("collection").count([value.id,collection.name]));if(count!==value.counts[collection.name])complete=false}await done;return complete?value:undefined},async base(installation){const transaction=database.transaction("bases","readonly"),done=completed(transaction);const base=await request(transaction.objectStore("bases").get(installation.artifactToken));await done;return base},async install(partition,pairToken,envelope,changes,assertCurrent,snapshotId,artifact,unchangedRecords){const installation={id:crypto.randomUUID(),partition,pairToken,version:envelope.version,artifactToken:artifact.token,snapshotId,repository:envelope.repository,name:envelope.name,format:envelope.format,bodyCollections:envelope.bodyCollections,timelineCollections:envelope.timelineCollections,catalogue:envelope.catalogue,changeCount:changes.length,cursorKey:unchangedRecords?.cursorKey??crypto.getRandomValues(new Uint8Array(32)),...unchangedRecords?{queryIdentity:unchangedRecords.queryIdentity??unchangedRecords.id}:{},counts:Object.fromEntries(Object.entries(envelope.collections).map(([name,rows])=>[name,rows.length]))};const transaction=database.transaction(["current","records","changes","bases"],"readwrite"),done=completed(transaction);try{assertCurrent();transaction.objectStore("bases").put(artifact.base,artifact.token);const records=transaction.objectStore("records");for(const[collection,rows]of Object.entries(envelope.collections))for(const record2 of rows)records.put({installation:installation.id,collection,ref:record2.$ref,record:record2});await request(transaction.objectStore("changes").put(changes,installation.id));await request(transaction.objectStore("current").put(installation,partition));assertCurrent();await done;assertCurrent();return installation}catch(error){try{transaction.abort()}catch{}await done.catch(()=>{});throw error}},async invalidate(installation){const transaction=database.transaction(["current","changes"],"readwrite"),done=completed(transaction);transaction.objectStore("changes").delete(installation.id);const current=await request(transaction.objectStore("current").get(installation.partition));if(current?.id===installation.id)transaction.objectStore("current").delete(installation.partition);await done},async mutate(installation,mutation,assertCurrent){const transaction=database.transaction(["current","records","changes"],"readwrite"),done=completed(transaction);try{assertCurrent();const records=transaction.objectStore("records"),collections={};const prior=await request(transaction.objectStore("changes").get(installation.id));if(!prior||prior.length!==installation.changeCount)return unavailable2();for(const c of installation.catalogue){const rows=await request(records.index("collection").getAll([installation.id,c.name]));if(rows.length!==installation.counts[c.name])return unavailable2();collections[c.name]=rows.map((r)=>r.record)}const{envelope,changes}=applySnapshotMutation({format:"data-snapshot.v2",repository:installation.repository,name:installation.name,version:installation.version,bodyCollections:installation.bodyCollections,timelineCollections:installation.timelineCollections,catalogue:installation.catalogue,collections},prior,mutation,installation);const id2=crypto.randomUUID();const next={...installation,id:id2,pairToken:"",version:envelope.version,queryIdentity:mutation.kind==="publish"?id2:installation.queryIdentity??installation.id,changeCount:changes.length,counts:Object.fromEntries(Object.entries(envelope.collections).map(([name,rows])=>[name,rows.length]))};for(const[collection,rows]of Object.entries(envelope.collections))for(const record2 of rows)records.put({installation:id2,collection,ref:record2.$ref,record:record2});transaction.objectStore("changes").put(changes,id2);const current=await request(transaction.objectStore("current").get(installation.partition));if(current?.id===installation.id)transaction.objectStore("current").put(next,installation.partition);assertCurrent();await done;assertCurrent();return next}catch(error){try{transaction.abort()}catch{}await done.catch(()=>{});throw error}},async read(installation,ref){const transaction=database.transaction("records","readonly"),done=completed(transaction);const row=await request(transaction.objectStore("records").get([installation.id,ref]));const collection=snapshotCollection(installation.catalogue,ref).name;const count=await request(transaction.objectStore("records").index("collection").count([installation.id,collection]));await done;if(count!==installation.counts[collection])return unavailable2();return row?.record??null},async changes(installation){const transaction=database.transaction("changes","readonly"),done=completed(transaction);const rows=await request(transaction.objectStore("changes").get(installation.id));await done;if(!rows||rows.length!==installation.changeCount)return unavailable2();return rows},async query(installation,query,maxRecords,body){const key=await crypto.subtle.importKey("raw",installation.cursorKey,"AES-GCM",false,["encrypt","decrypt"]);let transaction,done;const records=()=>{if(!transaction){transaction=database.transaction("records","readonly");done=completed(transaction)}return transaction.objectStore("records")};const finish=async()=>{await done;transaction=undefined;done=undefined};const evaluation=evaluateRecordsQuery(query,installation.catalogue,{workspaceId:installation.partition,repository:installation.partition,identity:installation.queryIdentity??installation.id,version:installation.version},maxRecords,(value)=>value,body?installation.bodyCollections:undefined);try{let step=evaluation.next();while(!step.done){const work=step.value;let value;if(work.operation==="scan"){const rows=await request(records().index("collection").getAll([installation.id,work.collection]));if(rows.length!==installation.counts[work.collection])return unavailable2();value=rows.map((row)=>row.record)}else if(work.operation==="lookup"){const row=await request(records().get([installation.id,work.ref]));value=row&&{record:row.record,collection:row.collection}}else{await finish();if(work.operation==="seal"){const iv=crypto.getRandomValues(new Uint8Array(12));const sealed=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv},key,new TextEncoder().encode(JSON.stringify(work.payload))));value=encode(new Uint8Array([...iv,...sealed]))}else{try{const bytes=Uint8Array.from(atob(work.token),(c)=>c.charCodeAt(0));const opened=await crypto.subtle.decrypt({name:"AES-GCM",iv:bytes.slice(0,12)},key,bytes.slice(12));value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(opened))}catch{throw new DataOperationError("invalid_query")}}}step=evaluation.next(value)}await finish();return step.value}catch(error){try{transaction?.abort()}catch{}await done?.catch(()=>{});throw error}}}}function unavailable3(){throw new DataOperationError("unavailable",true)}function stable3(value){if(Array.isArray(value))return`[${value.map(stable3).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>`${JSON.stringify(k)}:${stable3(v)}`).join(",")}}`;return JSON.stringify(value)}var facts=(changes,records=false)=>stable3(changes.filter((c)=>!records||c.publication).map((c)=>records?{id:c.id,version:c.version,recordVersion:c.recordVersion,effect:c.effect,publication:c.publication}:c).sort((a,b)=>a.id.localeCompare(b.id)));function snapshotDifference(before,after){return{records:facts(before,true)!==facts(after,true),changes:facts(before)!==facts(after)}}async function acquireSnapshot(store,partition,url,headers,repository,snapshot,assertCurrent,signal,prior){const candidate=prior===null?undefined:prior??await store.current(partition);const cached=candidate?.format==="data-snapshot.v2"&&validSnapshotArtifactToken(candidate.artifactToken)&&(candidate.pairToken===""||validSnapshotPairToken(candidate.pairToken))?candidate:undefined;let base=cached?await store.base(cached):undefined;if(base?.format!=="data-snapshot.v2")base=undefined;const reusable=base?cached:undefined;assertCurrent();for(let attempt=0;attempt<3;attempt++){const response=await fetch(url,{method:"GET",redirect:"error",cache:"no-store",signal,headers:{...headers,accept:snapshotAcquisitionType,...reusable?.pairToken?{[snapshotPairHeader]:reusable.pairToken}:{}}});assertCurrent();if(response.status===409){await response.body?.cancel();continue}const pairToken=response.headers.get(snapshotPairHeader),artifactToken=response.headers.get(snapshotArtifactHeader);if(response.status===204){if(!reusable||pairToken!==reusable.pairToken||artifactToken!==reusable.artifactToken)unavailable3();return{installation:reusable,update:{records:false,changes:false}}}if(!response.ok)throw dataTransportError(response.status,await response.json().catch(()=>{return}));if(response.status!==200||!validSnapshotPairToken(pairToken)||!validSnapshotArtifactToken(artifactToken)||response.headers.get("content-type")?.split(";")[0]!=="application/json")unavailable3();const acquired=validateAcquisition(await response.json(),repository,snapshot);assertCurrent();if(!reusable||reusable.artifactToken!==artifactToken){const artifact=await fetch(url,{method:"GET",redirect:"error",cache:"no-store",signal,headers:{...headers,accept:"application/gzip",[snapshotPairHeader]:pairToken}});assertCurrent();if(artifact.status===409){await artifact.body?.cancel();continue}if(!artifact.ok)throw dataTransportError(artifact.status,await artifact.json().catch(()=>{return}));if(artifact.status!==200||artifact.headers.get(snapshotPairHeader)!==pairToken||artifact.headers.get(snapshotArtifactHeader)!==artifactToken||!artifact.body||artifact.headers.get("content-type")?.split(";")[0]!=="application/gzip")unavailable3();const bytes=await new Response(artifact.body.pipeThrough(new DecompressionStream("gzip"))).arrayBuffer();base=validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)),repository,snapshot,acquired.snapshot.bodies,acquired.snapshot.timelines)}if(!base||base.version!==acquired.snapshot.version||(base.bodyCollections??[]).join("\x00")!==acquired.snapshot.bodies.join("\x00")||base.timelineCollections.join("\x00")!==acquired.snapshot.timelines.join("\x00")||base.catalogue.map((c)=>c.name).join("\x00")!==acquired.snapshot.collections.join("\x00")||reusable?.artifactToken===artifactToken&&reusable.snapshotId!==acquired.snapshot.id)unavailable3();const update=reusable?snapshotDifference(await store.changes(reusable),acquired.changes):{records:true,changes:true};update.records||=reusable?.artifactToken!==artifactToken;const published=acquired.changes.filter((c)=>c.publication);let version=base.version;if(reusable&&!update.records)version=reusable.version;else if(published.length){const digest=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify([base.version,published]))));version=`snapshot-${Array.from(digest,(byte)=>byte.toString(16).padStart(2,"0")).join("")}`}const materialized=materializeSnapshot(base,acquired.changes,version);assertCurrent();const installation=await store.install(partition,pairToken,materialized,acquired.changes,assertCurrent,acquired.snapshot.id,{token:artifactToken,base},update.records?undefined:reusable);return{installation,update}}unavailable3()}function snapshotListeners(url,authority,assertCurrent,invalidate,reconcile,connect){const listeners=new Set;let session,socket;let retry,expiry;let stopAuthority,stopCredentials;let delay=250;const stop=()=>{session?.abort();session=undefined;const prior=socket;socket=undefined;prior?.close();clearTimeout(retry);clearTimeout(expiry);retry=expiry=undefined;stopAuthority?.();stopAuthority=undefined;stopCredentials?.();stopCredentials=undefined};const current=()=>{try{assertCurrent();return true}catch{stop();return false}};const notify=(update)=>{if(!update.records&&!update.changes||!current())return;for(const listener of[...listeners]){if(!current())break;if(listeners.has(listener)){try{listener({...update})}catch{}}}};const start=()=>{if(!listeners.size||!current())return;const owned=new AbortController;session=owned;let dirty=false,running=false;const lostAuthority=()=>{invalidate();stop()};authority.signal.addEventListener("abort",lostAuthority,{once:true});stopAuthority=()=>authority.signal.removeEventListener("abort",lostAuthority);const armExpiry=()=>{clearTimeout(expiry);expiry=setTimeout(()=>{if(authority.refresh)restart();else lostAuthority()},Math.min(2147483647,Math.max(0,authority.expiresAt-Date.now())))};const later=()=>{retry=setTimeout(open,delay);delay=Math.min(30000,delay*2)};const reconnect=(connection)=>{if(session!==owned||!connection||socket!==connection)return;socket=undefined;connection.close();later()};const refresh=()=>{dirty=true;if(running)return;running=true;(async()=>{try{while(dirty&&session===owned&&current()){dirty=false;const update=await reconcile(owned.signal);if(session===owned&&current()){delay=250;notify(update)}}}catch(error){if(session!==owned)return;if(error instanceof DataOperationError&&["context_unavailable","unauthenticated","access_denied","not_found"].includes(error.code))lostAuthority();else reconnect(socket)}finally{running=false}})()};let opening=0;const open=()=>{retry=undefined;if(session!==owned||!current())return;if(authority.expiresAt<=Date.now()&&authority.refresh){const attempt=++opening;authority.refresh().then(()=>{if(session===owned&&opening===attempt&&current()&&authority.expiresAt>Date.now())open()}).catch(()=>{if(session===owned)current()});return}armExpiry();try{const connection=connect(url.replace(/^http/,"ws")+"/updates",[snapshotUpdatesProtocol,snapshotUpdatesCredentialPrefix+authority.headers.authorization.slice("Bearer ".length)]);socket=connection;connection.addEventListener("open",()=>{if(socket===connection&&session===owned)refresh()});connection.addEventListener("message",(event)=>{if(socket===connection&&session===owned&&event.data===snapshotUpdateHint)refresh()});connection.addEventListener("close",()=>reconnect(connection));connection.addEventListener("error",()=>reconnect(connection))}catch{if(session===owned)later()}};const restart=()=>{if(session!==owned||!current())return;const attempt=++opening;clearTimeout(retry);clearTimeout(expiry);const prior=socket;socket=undefined;prior?.close();Promise.resolve().then(()=>{if(session===owned&&opening===attempt)open()})};stopCredentials=authority.subscribe?.(restart);open()};return{notify,stop,subscribe(listener){assertCurrent();if(typeof listener!=="function")throw new DataOperationError("invalid_query");const owned=(update)=>listener(update);listeners.add(owned);if(listeners.size===1)start();return()=>{listeners.delete(owned);if(!listeners.size)stop()}}}}var invalidChange2=()=>{throw new DataOperationError("invalid_change",false,"unapplied")};var unsafe=(key)=>key.startsWith("$")||["__proto__","constructor","prototype"].includes(key);function capture5(value,depth=0){if(depth>32)return invalidChange2();if(Array.isArray(value))return dataArray(value).map((v)=>capture5(v,depth+1));if(value&&typeof value==="object")return Object.fromEntries(Object.entries(dataProperties(value)).map(([key,d])=>{if(unsafe(key))return invalidChange2();return[key,capture5(d.value,depth+1)]}));if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;return invalidChange2()}function captureTransaction(callback,installation){let active=true;const operations=[];try{if(typeof callback!=="function")return invalidChange2();const tx=new Proxy(Object.create(null),{get(_target,name){if(typeof name!=="string"||unsafe(name)||!installation.catalogue.some((c)=>c.name===name))return invalidChange2();return new Proxy(Object.create(null),{get(_target2,id2){const ref=`${name}/${String(id2)}`;if(typeof id2!=="string"||!validRecordRef(ref)||snapshotCollection(installation.catalogue,ref)?.name!==name)return invalidChange2();const schema2=installation.catalogue.find((c)=>c.name===name).schema;const builder=Object.fromEntries(["create","update","link","unlink","delete","setSignal","appendTimeline"].map((kind)=>[kind,(...args)=>{if(!active||args.length!==(kind==="delete"?0:1)||operations.length>=1e4)return invalidChange2();let table;if(kind==="setSignal"){const{asOf:_time,...signal}=captureSignal(args[0],new Date().toISOString());table={kind:"signal",ref,signal}}else if(kind==="appendTimeline")table={kind:"timeline",ref,entry:captureTimeline(args[0],true)};let fields3;if(kind!=="delete"&&!table){dataProperties(args[0]);fields3=capture5(args[0]);if(!Object.keys(fields3).length||Object.keys(fields3).some((key)=>unsafe(key)||kind!=="create"&&["id","type"].includes(key)))return invalidChange2();const definitions2=kind==="create"?schema2.fields:schema2.fields.filter((f)=>Object.hasOwn(fields3,f.name));if(kind==="link"||kind==="unlink"){for(const[key,value]of Object.entries(fields3)){const field=definitions2.find((f)=>f.name===key);const refs=typeof value==="string"?[value]:value;if(field?.kind!=="link"||!Array.isArray(refs)||!refs.length||!field.many&&refs.length!==1||refs.some((ref2)=>!validRecordRef(ref2))||new Set(refs).size!==refs.length)return invalidChange2();fields3[key]=field.many?refs:refs[0]}}validateRecordFields(fields3,definitions2,(ref2)=>snapshotCollection(installation.catalogue,ref2)?.schema.type,true);fields3=captureDataCreate({...fields3,$ref:ref}).fields}const prior=operations.filter((op)=>op.ref===ref);if(kind==="delete"&&prior.length||prior.some((op)=>op.kind==="delete")||kind==="create"&&prior.length)return invalidChange2();operations.push(table??{kind,ref,...fields3?{fields:fields3}:{}});return builder}]));return builder}})}});const result=callback(tx);if(result&&typeof result.then==="function"){Promise.resolve(result).catch(()=>{});return invalidChange2()}if(!operations.length)return invalidChange2();return operations}catch(error){if(error instanceof DataOperationError&&error.code==="invalid_change")throw error;return invalidChange2()}finally{active=false}}function captureSelection(input){try{const selected=dataArray(input).map((value)=>{const row=dataProperties(value),id2=row.id?.value,version=row.version?.value;if(typeof id2!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id2)||!dataVersion(version))return invalidChange2();return{id:id2,version}});if(!selected.length||selected.length>1e4||new Set(selected.map((c)=>c.id)).size!==selected.length)return invalidChange2();return selected}catch{return invalidChange2()}}var invalid10=()=>{throw new DataOperationError("invalid_query")};function captureSnapshotAll(query,options){const properties=dataProperties(options);if(Object.keys(properties).some((key)=>!["maxRecords","body","timeline"].includes(key))||properties.body&&properties.body.value!==true||properties.timeline&&properties.timeline.value!==true)return invalid10();return{...captureRecordsAll(query,{maxRecords:properties.maxRecords?.value}),body:properties.body?.value===true,timeline:properties.timeline?.value===true}}var safeName=(value)=>typeof value==="string"&&/^[a-z0-9][a-z0-9._-]{0,127}$/.test(value)&&!value.includes("..");function createSnapshotInitializer(resolve=resolveSnapshotContext,open=openSnapshotStore,connect=(url,protocols)=>new WebSocket(url,protocols)){const pending=new WeakMap;return async function initialize(input){const properties=dataProperties(input);const repository=properties.repository?.value,snapshot=properties.snapshot?.value;if(Object.keys(properties).sort().join(",")!=="repository,snapshot"||!safeName(repository)||!safeName(snapshot))return invalid10();const authority=await resolve();let invalidated=false;let stopLive;const assertCurrent=()=>{if(invalidated||authority.signal.aborted||!authority.isCurrent()||!authority.refresh&&authority.expiresAt<=Date.now()){invalidated=true;stopLive?.();throw new DataOperationError("context_unavailable")}};const assertAccess=()=>{assertCurrent();if(authority.expiresAt<=Date.now())throw new DataOperationError("unavailable",true)};const ensureAccess=async()=>{assertCurrent();if(authority.expiresAt<=Date.now())await authority.refresh?.();assertAccess()};assertCurrent();const partition=JSON.stringify([authority.endpoint,authority.memberId,authority.workspace,repository,snapshot]);let work=pending.get(authority.binding);if(!work){work=new Map;pending.set(authority.binding,work)}const url=`${authority.endpoint}/api/data/snapshots/${repository}/${snapshot}`;let cached;try{const store=await open();try{cached=await store.current(partition)}finally{store.close()}assertAccess();if(cached&&(cached.format!=="data-snapshot.v2"||!Array.isArray(cached.timelineCollections)||cached.repository!==repository||cached.name!==snapshot||!validSnapshotArtifactToken(cached.artifactToken)||cached.pairToken!==""&&!validSnapshotPairToken(cached.pairToken)))cached=undefined}catch(error){assertCurrent();if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}let installation;if(cached)installation=cached;else{let installing=work.get(partition);if(!installing){installing=(async()=>{const store=await open();try{return(await acquireSnapshot(store,partition,url,authority.headers,repository,snapshot,assertAccess,authority.signal,null)).installation}finally{store.close()}})();work.set(partition,installing);installing.finally(()=>{if(work.get(partition)===installing)work.delete(partition)}).catch(()=>{})}try{installation=await installing;assertAccess()}catch(error){assertCurrent();if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}}let tail=Promise.resolve(),writes=Promise.resolve();const serial=(work2)=>{const result=tail.then(work2);tail=result.catch(()=>{});return result};const write=(work2)=>{const result=serial(work2);writes=result.catch(()=>{});return result};const reconcile=(signal)=>serial(async()=>{await ensureAccess();const headers=authority.headers;const fenced=()=>{assertAccess();if(signal.aborted||headers.authorization!==authority.headers.authorization)throw new DataOperationError("unavailable",true)};fenced();const store=await open();try{const next=await acquireSnapshot(store,partition,url,headers,repository,snapshot,fenced,AbortSignal.any([signal,authority.signal]),installation);fenced();installation=next.installation;return next.update}finally{store.close()}});let initialRefresh;const live=snapshotListeners(url,authority,assertCurrent,()=>{invalidated=true},(signal)=>initialRefresh?initialRefresh.then(()=>({records:false,changes:false})):reconcile(signal),connect);stopLive=live.stop;if(cached){const refresh=reconcile(authority.signal);initialRefresh=refresh;refresh.then(live.notify).catch((error)=>{if(error instanceof DataOperationError&&["context_unavailable","unauthenticated","access_denied","not_found"].includes(error.code)){invalidated=true;live.stop()}}).finally(()=>{if(initialRefresh===refresh)initialRefresh=undefined})}const publications=new Map;const mutate=async(kind,payload,selected,publication)=>{await ensureAccess();if(publication?.complete)return[];const body={snapshotId:installation.snapshotId,...payload};checkDataRequestSize(body,2*1024*1024);let dispatched=false,applied=false;let store;try{store=await open();assertAccess();dispatched=true;const response=await fetch(`${authority.endpoint}/api/data/snapshots/${repository}/${snapshot}/changes/${kind}`,{method:"POST",redirect:"error",cache:"no-store",headers:{...authority.headers,"content-type":"application/json"},body:JSON.stringify(body)});if(!response.ok)throw dataTransportError(response.status,await response.json());applied=true;const value=await response.json();let mutation;if(kind==="discard"){if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length)throw new Error;mutation={kind,selected}}else if(kind==="transact")mutation={kind,changes:value};else{if(!value||!["changes,effects","changes,effects,records"].includes(Object.keys(value).sort().join(","))||!Array.isArray(value.changes)||value.changes.length>selected.length||value.changes.some((c)=>!selected.some((s)=>s.id===c.id&&s.version===c.version))||!Object.hasOwn(value,"records")&&value.changes.length!==selected.length)throw new Error;mutation={kind,selected,changes:value.changes,effects:value.effects,...Object.hasOwn(value,"records")?{records:value.records}:{}}}const before=await store.changes(installation);installation=await store.mutate(installation,mutation,assertAccess);assertAccess();const update=snapshotDifference(before,await store.changes(installation));if(kind==="publish")update.records=true;assertAccess();if(publication)publication.complete=true;live.notify(update);assertAccess();return structuredClone(mutation.changes??[])}catch(error){const failure=error instanceof DataOperationError?error:new DataOperationError("unavailable");const effect=applied?"applied":dispatched?failure.effect??"uncertain":"unapplied";if(effect!=="unapplied"&&(kind!=="publish"||effect==="applied")){invalidated=true;live.stop();await store?.invalidate(installation).catch(()=>{})}throw new DataOperationError(failure.code,effect==="uncertain"?kind==="publish":effect==="applied"?false:failure.retryable,effect,failure.component,failure.detail)}finally{store?.close()}};const query=async(query2,maxRecords,body=false,timeline=false)=>{const pinned=installation;await ensureAccess();const captured=captureRecordsQuery(query2);checkDataRequestSize({repository,operation:maxRecords===undefined?"records.query":"records.all",query:captured,...maxRecords===undefined?{}:{maxRecords}});let store;try{const selections=planIndexQuery(captured,pinned.catalogue);const checkTimeline=(collection,selection2)=>{if((timeline||selection2.timeline)&&!pinned.timelineCollections.includes(collection))return invalid10();for(const link of selection2.links)for(const[name,nested]of link.targets)checkTimeline(name,nested)};for(const{name,selection:selection2}of selections)checkTimeline(name,selection2);if(timeline){const include=(selection2)=>{selection2.$={...selection2.$,timeline:true};for(const[key,nested]of Object.entries(selection2))if(key!=="$")include(nested)};for(const selection2 of Object.values(captured))include(selection2)}store=await open();assertAccess();const result=await store.query(pinned,captured,maxRecords,body);assertAccess();return result}catch(error){assertAccess();if(error instanceof DataOperationError)throw error;if(error instanceof RecordValidationError)throw new DataOperationError("invalid_query");throw new DataOperationError("unavailable",true)}finally{store?.close()}};const localRead=async(operation)=>{await ensureAccess();let store;try{store=await open();assertAccess();const value=await operation(store);assertAccess();return value}catch(error){assertAccess();if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}finally{store?.close()}};const queryRecords=async(input2)=>{const captured=captureRecordsQuery(input2);return writes.then(()=>query(captured))};const transact=(callback)=>{try{assertCurrent();const operations=captureTransaction(callback,installation);return write(()=>mutate("transact",{operations}))}catch(error){return Promise.reject(error)}};const historyRead=(input2,operation)=>{const captured=captureHistoryInput(input2,operation);return writes.then(()=>{const pinned=installation;return localRead(async(store)=>{const base=await store.base(pinned);if(!base)throw new DataOperationError("unavailable",true);return readSnapshotHistory(base.history,captured,operation)})})};const history={records:async(input2)=>await historyRead(input2,"records"),changes:async(input2)=>await historyRead(input2,"changes")};return{subscribe:live.subscribe,transact,history,changes:{list:()=>writes.then(()=>{const pinned=installation;return localRead((store)=>store.changes(pinned))}),discard:async(input2)=>{const selected=captureSelection(input2);await write(()=>mutate("discard",{selected},selected))},publish:async(input2,options)=>{const selected=captureSelection(input2);const metadata=captureDataChangeOptions(options);if(metadata.source)return invalidChange2();const key=JSON.stringify([selected.slice().sort((a,b)=>a.id.localeCompare(b.id)),metadata]);let publication=publications.get(key);if(!publication){publication={id:crypto.randomUUID()};publications.set(key,publication)}await write(()=>mutate("publish",{selected,...metadata,publicationId:publication.id},selected,publication))}},records:{read:async(ref,...extra)=>{if(typeof ref!=="string"||extra.length>1)return Promise.reject(new DataOperationError("invalid_query"));const{body,timeline}=captureRecordsReadOptions(extra[0]);const[captured]=captureRecordsReadRefs([ref]);if(!snapshotCollection(installation.catalogue,captured))return Promise.reject(new DataOperationError("invalid_query"));return writes.then(()=>{const pinned=installation;return localRead(async(store)=>{if(timeline&&!pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue,captured).name))return invalid10();const record2=await store.read(pinned,captured);if(!record2)return record2;const{$body,$timeline,...structured}=record2;return{...structured,...body&&$body!==undefined?{$body}:{},...timeline?{$timeline}:{}}})})},query:queryRecords,...recordPagination(queryRecords),all:async(input2,options)=>{const captured=captureSnapshotAll(input2,options);return writes.then(()=>query(captured.query,captured.maxRecords,captured.body,captured.timeline))}}}}}var initializeSnapshot=createSnapshotInitializer();var genericData={init:initializeSnapshot,repository(repository){async function send(input){const context=await resolveDataContext();const envelope={repository,...input};const changing="operation"in input&&["changes.validate","changes.apply","changes.publish"].includes(String(input.operation));checkDataRequestSize(envelope,"local"in context&&changing?LOCAL_DATA_CHANGE_REQUEST_LIMIT:DATA_REQUEST_LIMIT);if("local"in context)return await context.local("data/query",envelope);try{const response=await fetch(context.url,{method:"POST",redirect:"error",cache:"no-store",headers:{"content-type":"application/json",...context.headers},body:JSON.stringify(envelope)});const result=await response.json();if(!response.ok){throw dataTransportError(response.status,result)}return result}catch(error){if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}}async function read(input,options){const refs=captureRecordsReadRefs(typeof input==="string"?[input]:input);const captured=captureRecordsReadOptions(options);const result=await send({operation:"records.read",refs,...options===undefined?{}:{options:captured}});return typeof input==="string"?result.records[0]:result}const queryRecords=(query)=>send({operation:"records.query",query});return{collections:{list:()=>send({operation:"collections.list"}),schema:(name)=>send({operation:"collections.schema",name})},records:{read,query:queryRecords,...recordPagination(queryRecords),all:async(query,options)=>send({operation:"records.all",...captureRecordsAll(query,options)}),search:async(query,options)=>send({operation:"records.search",...captureRecordsSearchInput(query,options)})},changes(options){const metadata=captureDataChangeOptions(options);let updates=[],creates=[],deletes=[],applyId;let method;let pending,confirmed;const assertMutable=()=>{if(applyId)throw new DataOperationError("invalid_change",false,"unapplied")};const snapshot=(nextUpdates=updates,nextCreates=creates,nextDeletes=deletes)=>{const{updates:updates2,creates:creates2,deletes:deletes2}=captureDataChanges(nextUpdates,nextCreates,nextDeletes);const input={...metadata,updates:updates2,...creates2.length?{creates:creates2}:{},...deletes2.length?{deletes:deletes2}:{}};checkDataRequestSize({repository,operation:"changes.apply",...input,applyId:applyId??"00000000-0000-4000-8000-000000000000"},LOCAL_DATA_CHANGE_REQUEST_LIMIT);return input};const write=(operation)=>{if(method&&method!==operation)return Promise.reject(new DataOperationError("invalid_change",false,"unapplied"));if(confirmed)return Promise.resolve(structuredClone(confirmed));if(!pending){let captured;try{captured=snapshot()}catch(error){return Promise.reject(error)}method=operation;applyId??=routineTransport()?.key("data")??crypto.randomUUID();pending=send({operation,...captured,applyId}).then((result)=>{confirmed=structuredClone(result);return result}).catch((error)=>{if(error instanceof DataOperationError&&error.effect!==undefined)throw error;if(error instanceof DataOperationError)throw explainDataValidation(new DataOperationError(error.code,error.retryable,error.effect??(["unavailable","apply_pending"].includes(error.code)?"uncertain":"unapplied"),error.component,error.detail),error.message,error.detail);throw new DataOperationError("unavailable",true,"uncertain")}).finally(()=>{pending=undefined})}return pending.then((result)=>structuredClone(result))};const authorTable=(ref,patch)=>{assertMutable();if(!validRecordRef(ref))throw new DataOperationError("invalid_change",false,"unapplied");const nextUpdates=structuredClone(updates),nextCreates=structuredClone(creates);const creation=nextCreates.find((row)=>row.ref===ref);let target=creation??nextUpdates.find((row)=>row.ref===ref);if(!target){target={ref,set:{}};nextUpdates.push(target)}if(patch.signals)target.signals=[...target.signals??[],...patch.signals];if(patch.timeline)target.timeline=[...target.timeline??[],...patch.timeline];snapshot(nextUpdates,nextCreates,deletes);updates=nextUpdates;creates=nextCreates};return{create(record2){assertMutable();const next=[...creates,captureDataCreate(record2)];snapshot(updates,next,deletes);creates=next},update(record2,set){assertMutable();const edit=captureDataUpdate(record2,set),prior=updates.find((row)=>row.ref===record2);const next=prior&&!Object.keys(prior.set).length&&prior.body===undefined?updates.map((row)=>row===prior?{...prior,...edit}:row):[...updates,edit];snapshot(next,creates,deletes);updates=next},setSignal(ref,input){authorTable(ref,{signals:[captureSignal(input,new Date().toISOString())]})},appendTimeline(ref,input){authorTable(ref,{timeline:[captureTimeline(input,true)]})},delete(record2){assertMutable();const next=[...deletes,captureDataDelete(record2)];snapshot(updates,creates,next);deletes=next},async validate(){await send({operation:"changes.validate",...snapshot()})},apply:()=>write("changes.apply"),publish:()=>write("changes.publish")}}}}};var data=genericData;async function hostedContent(url,init,parent,upstream=fetch,check=async()=>{},failure){const delivery=new AbortController;const abort=()=>delivery.abort(parent.reason);parent.addEventListener("abort",abort,{once:true});if(parent.aborted)abort();const detach=()=>parent.removeEventListener("abort",abort);try{const response=await upstream(url,{...init,signal:delivery.signal});try{await check();if(delivery.signal.aborted)throw failure?.()??new FileOperationError("unavailable",503,true)}catch(error){response.body?.cancel().catch(()=>{});throw error}if(!response.body){detach();return response}const source=response.body;let reader;let settled=false;let output;const cancel=async(reason)=>{if(settled)return;settled=true;detach();delivery.signal.removeEventListener("abort",stop);delivery.abort(reason);try{await(reader?reader.cancel(reason):source.cancel(reason))}catch(error){if(error!==delivery.signal.reason&&!(error instanceof Error&&error.name==="AbortError"))throw error}finally{reader?.releaseLock()}};const stop=()=>{if(settled)return;const error=failure?.()??delivery.signal.reason;cancel(error).catch(()=>{});output.error(error)};const body=new ReadableStream({start(controller){output=controller;delivery.signal.addEventListener("abort",stop,{once:true});if(delivery.signal.aborted)stop()},async pull(controller){try{await check();if(settled)return;reader??=source.getReader();const{done,value}=await reader.read();await check();if(settled)return;if(done){settled=true;detach();delivery.signal.removeEventListener("abort",stop);reader.releaseLock();controller.close()}else controller.enqueue(value)}catch(error){if(settled)return;controller.error(failure?.()??error);await cancel(error).catch(()=>{})}},cancel},{highWaterMark:0});const wrapped=new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers});for(const key of["url","redirected","type"])Object.defineProperty(wrapped,key,{value:response[key]});return wrapped}catch(error){detach();delivery.abort(error);throw error}}var MAX_BYTES=16*1024*1024;var PART_BYTES=8*1024*1024;var METADATA_BYTES=4096;var RESULT_BYTES=16*1024;var CONTROL_RESULT_BYTES=128*1024;var TIMEOUT_MS=30000;var MAX_ACTIVE=4;var ATTEMPTS=2;var active=0;var waiters=[];var invalid11=()=>new FileOperationError("invalid_input",400);var unavailable4=()=>new FileOperationError("unavailable",503,true);var failures={400:["invalid_input","unsupported_context"],401:["unauthenticated"],403:["access_denied"],404:["not_found"],405:["method_not_allowed"],409:["conflict","local_only"],413:["request_too_large"],429:["capacity"],503:["integrity","unavailable"]};function heldSlot(){let held=true;return()=>{if(!held)return;held=false;for(;;){const waiter=waiters.shift();if(!waiter){active--;return}if(!waiter.waiting)continue;waiter.waiting=false;waiter.signal?.removeEventListener("abort",waiter.abort);waiter.resolve(heldSlot());return}}}async function acquireSlot(signal){if(signal?.aborted)throw unavailable4();if(active<MAX_ACTIVE){active++;return heldSlot()}return new Promise((resolve,reject)=>{const waiter={signal,waiting:true,resolve,reject,abort(){if(!waiter.waiting)return;waiter.waiting=false;const index=waiters.indexOf(waiter);if(index!==-1)waiters.splice(index,1);reject(unavailable4())}};waiters.push(waiter);signal?.addEventListener("abort",waiter.abort,{once:true});if(signal?.aborted)waiter.abort()})}async function boundedBytes(stream,limit,signal){if(!stream)return new Uint8Array;const reader=stream.getReader();const bytes=new Uint8Array(limit);let size=0;const cancel=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",cancel,{once:true});if(signal?.aborted)cancel();try{for(;;){const{done,value}=await reader.read();if(signal?.aborted)throw unavailable4();if(done)break;if(!(value instanceof Uint8Array))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_bytes"});size+=value.byteLength;if(size>limit)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:limit,receivedBytes:size,receivedAtLeast:true});bytes.set(value,size-value.byteLength)}}catch(error){cancel();throw error}finally{signal?.removeEventListener("abort",cancel);reader.releaseLock()}return bytes.slice(0,size)}async function timed(work,parent,timeout=TIMEOUT_MS){const controller=new AbortController;let timer;let abort;const expiry=new Promise((_,reject)=>{abort=()=>{controller.abort();reject(unavailable4())};timer=setTimeout(abort,timeout);parent?.addEventListener("abort",abort,{once:true});if(parent?.aborted)abort()});try{return await Promise.race([work(controller.signal),expiry])}finally{clearTimeout(timer);parent?.removeEventListener("abort",abort)}}async function result(response,maximum=RESULT_BYTES){try{const bytes=await boundedBytes(response.body,maximum);return JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))}catch{throw unavailable4()}}async function send(suffix,init,descriptor,initial,parent){const original=initial;const checkCurrent=(context=original)=>{if(parent?.aborted)throw unavailable4();if(!original.isCurrent()||context.url!==original.url)throw new FileOperationError("unsupported_context",400)};for(let attempt=0;attempt<ATTEMPTS;attempt++){checkCurrent();const context=await resolveFilesContext();checkCurrent(context);try{const response=context.localFiles?await context.localFiles(suffix,init,parent):await(async()=>{const url=`${context.url}${suffix}`;const request2={...init,signal:parent,headers:{...context.headers,...init.headers},redirect:"error",cache:"no-store"};return descriptor?fetch(url,request2):hostedContent(url,request2,parent)})();if(!response.ok){const value2=await result(response);const error=value2&&typeof value2==="object"&&"error"in value2?value2.error:undefined;const received=error&&typeof error==="object"&&"code"in error?error.code:undefined;const code=failures[response.status]?.find((code2)=>code2===received);throw code?new FileOperationError(code,response.status,code==="capacity"||code==="unavailable",parseFileErrorDetail(error?.detail)):unavailable4()}if(response.status!==200){response.body?.cancel().catch(()=>{});throw unavailable4()}try{checkCurrent()}catch(error){response.body?.cancel().catch(()=>{});throw error}if(!descriptor)return response;const value=await result(response,descriptor==="control"?CONTROL_RESULT_BYTES:RESULT_BYTES);if(descriptor==="control"){checkCurrent();return value}let parsed;if(descriptor==="enrichment"){if(!value||typeof value!=="object"||Array.isArray(value))throw unavailable4();const{name,...metadata}=value;if(!safeEnrichmentName(name))throw unavailable4();parsed={name,...parseEnrichmentDescriptor(metadata)}}else parsed=parseFileDescriptor(value);checkCurrent();return parsed}catch(error){const failure=error instanceof FileOperationError?error:unavailable4();if(init.body instanceof ReadableStream||!failure.retryable||attempt+1===ATTEMPTS)throw failure}}throw unavailable4()}function idPath(id2){if(typeof id2!=="string"||!FILE_ID_PATTERN.test(id2))throw invalid11();return`/${id2}`}async function multipartCreate(input,metadata,exchange,release,upload,expectedSha256){const route=upload?`${idPath(upload.file.id)}/upload/multipart`:"/multipart";let ticket;let reader;let chunk,offset=0;const receipts=[];const pending=new Set;const request2=(work,timeout=TIMEOUT_MS)=>timed((signal)=>{const task=work(signal);pending.add(task);task.then(()=>pending.delete(task),()=>pending.delete(task));return task},undefined,timeout);const control=(body)=>({method:"POST",headers:{"content-type":"application/json",...ticket?{"x-os-transfer":ticket}:{}},body:JSON.stringify(body)});try{const startRequest=control(upload?.file??metadata);if(expectedSha256)startRequest.headers["x-os-original-sha256"]=expectedSha256;const start=await request2((signal)=>exchange(`${route}/start`,startRequest,"control",signal));if(!start||typeof start!=="object"||Array.isArray(start))throw unavailable4();const session=start;if(Object.keys(session).sort().join(",")!=="partBytes,ticket"||session.partBytes!==PART_BYTES||typeof session.ticket!=="string"||!session.ticket||session.ticket.length>64*1024)throw unavailable4();ticket=session.ticket;if(input.file instanceof ReadableStream)reader=input.file.getReader();let lastProgress=Date.now();const next=async()=>{try{if(Date.now()-lastProgress>=TIMEOUT_MS)throw unavailable4();const value=await request2(()=>reader.read(),Math.max(1,TIMEOUT_MS-(Date.now()-lastProgress)));if(value.value?.byteLength)lastProgress=Date.now();return value}catch(error){await reader.cancel(error).catch(()=>{});throw error}};for(let sent=0,partNumber=1;sent<metadata.size||metadata.size===0&&partNumber===1;partNumber++){const length=Math.min(PART_BYTES,metadata.size-sent);let part;if(input.file instanceof Uint8Array)part=new Uint8Array(input.file.subarray(sent,sent+length));else if(input.file instanceof Blob){const slice=input.file.slice(sent,sent+length);part=new Uint8Array(await request2(()=>slice.arrayBuffer()))}else{part=new Uint8Array(length);let filled=0;while(filled<length){if(!chunk||offset===chunk.byteLength){chunk=undefined;offset=0;const value2=await next();if(value2.done)throw invalid11();if(!(value2.value instanceof Uint8Array))throw invalid11();chunk=value2.value;if(chunk.byteLength>metadata.size-sent-filled)throw invalid11()}const take=Math.min(length-filled,chunk.byteLength-offset);part.set(chunk.subarray(offset,offset+take),filled);filled+=take;offset+=take;if(offset===chunk.byteLength){chunk=undefined;offset=0}}}if(part.byteLength!==length)throw invalid11();if(reader&&sent+length===metadata.size){lastProgress=Date.now();for(;;){const value2=await next();if(value2.done)break;if(!(value2.value instanceof Uint8Array)||value2.value.byteLength)throw invalid11()}}const value=await request2((signal)=>exchange(`${route}/part`,{method:"POST",headers:{"content-type":"application/octet-stream","x-os-transfer":ticket,"x-os-part":String(partNumber)},body:part.buffer},"control",signal));part=undefined;const receipt=value;if(!receipt||typeof receipt!=="object"||Object.keys(receipt).sort().join(",")!=="etag,partNumber"||receipt.partNumber!==partNumber||typeof receipt.etag!=="string"||!receipt.etag||receipt.etag.length>256||/[\u0000-\u001f\u007f]/.test(receipt.etag))throw unavailable4();receipts.push({partNumber,etag:receipt.etag});sent+=length;lastProgress=Date.now()}if(upload)for(const name of Object.keys(upload.file.enrichments)){const bytes=await request2(()=>upload.enrichment(name));if(bytes.byteLength!==upload.file.enrichments[name].size||bytes.byteLength>MAX_BYTES)throw invalid11();await request2((signal)=>exchange(`${route}/enrichments/${encodeURIComponent(name)}`,{method:"POST",headers:{"content-type":"application/octet-stream","x-os-transfer":ticket},body:bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)},"control",signal))}await upload?.beforeComplete();const completion=control({parts:receipts});if(new TextEncoder().encode(completion.body).byteLength>128*1024)throw unavailable4();const completed2=parseFileDescriptor(await request2((signal)=>exchange(`${route}/complete`,completion,true,signal),TIMEOUT_MS+Math.ceil(metadata.size/(1024*1024))*1000));if(!upload){const acknowledged=await request2((signal)=>exchange(`${route}/acknowledge`,control(completed2),"control",signal));if(!acknowledged||typeof acknowledged!=="object"||Object.keys(acknowledged).join(",")!=="acknowledged"||acknowledged.acknowledged!==true)throw unavailable4()}return completed2}catch(error){if(reader)await reader.cancel(error).catch(()=>{});if(ticket)await request2((signal)=>exchange(`${route}/abort`,control({}),"control",signal)).catch(()=>{});throw error instanceof FileOperationError?error:unavailable4()}finally{chunk=undefined;reader?.releaseLock();if(pending.size)Promise.allSettled([...pending]).then(release);else release()}}async function operation(work,initial,parent){const context=initial??await resolveFilesContext();const signal=context.signal&&parent?AbortSignal.any([context.signal,parent]):context.signal??parent;const release=await acquireSlot(signal);const execute=async(signal2)=>{try{return await work(context,signal2)}finally{release()}};if(context.localFiles)return execute(signal??new AbortController().signal);return timed(execute,signal).catch((error)=>{throw error instanceof FileOperationError?error:unavailable4()})}function contentPath(id2,name){const path=idPath(id2);if(name===undefined)return`${path}/content`;if(!safeEnrichmentName(name))throw invalid11();return`${path}/enrichments/${encodeURIComponent(name)}/content`}async function read(id2,names){const context=await resolveFilesContext();idPath(id2);if(names===undefined||typeof names==="string"){const path=contentPath(id2,names);return operation((context2,signal)=>send(path,{method:"GET"},false,context2,signal),context)}if(!Array.isArray(names))throw invalid11();const distinct=[];const seen=new Set;for(const name of names){if(typeof name!=="string"||!safeEnrichmentName(name))throw invalid11();if(seen.has(name))continue;if(seen.size===16)throw invalid11();seen.add(name);distinct.push(name)}const paths=distinct.map((name)=>contentPath(id2,name));return timed(async(parent)=>{const responses={};try{for(let i=0;i<paths.length;i++){const response=await operation((context2,signal)=>send(paths[i],{method:"GET"},false,context2,signal),context,parent);Object.defineProperty(responses,distinct[i],{value:response,enumerable:true})}if(!context.isCurrent())throw new FileOperationError("unsupported_context",400);return responses}catch(error){for(const response of Object.values(responses))response.body?.cancel().catch(()=>{});throw error}})}var files={async upload(id2){return operation(async(context,signal)=>{const file2=await send(`${idPath(id2)}/upload`,{method:"POST"},true,context,signal);if(file2.id!==id2)throw unavailable4();return file2})},async create(input,options){const context=await resolveFilesContext();if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some((key)=>!["file","size","path","name","storage","mediaType"].includes(key))||options!==undefined&&(!options||typeof options!=="object"||Array.isArray(options)||Object.keys(options).some((key)=>key!=="requestKey")))throw invalid11();const blob=input.file instanceof Blob;const array2=input.file instanceof Uint8Array;const stream=input.file instanceof ReadableStream;if(!blob&&!array2&&!stream)throw invalid11();const intrinsic=blob?input.file.size:array2?input.file.byteLength:undefined;if(intrinsic!==undefined&&input.size!==undefined&&input.size!==intrinsic){if(!Number.isSafeInteger(input.size)||input.size<0)throw new FileOperationError("invalid_input",400,false,{reason:"invalid_size"});throw new FileOperationError("invalid_input",400,false,{reason:"size_mismatch",expectedBytes:input.size,receivedBytes:intrinsic})}let name=input.name;if(name===undefined&&blob&&"name"in input.file&&typeof input.file.name==="string"){name=typeof globalThis.File!=="undefined"&&input.file instanceof globalThis.File?input.file.name:input.file.name.split(/[\\/]/).at(-1)}const mediaType=declaredOriginalMediaType(input.mediaType===undefined?blob&&input.file.type?input.file.type:"application/octet-stream":input.mediaType);const metadata=parseFileCreateMetadata({name,size:intrinsic??input.size,path:input.path,storage:input.storage,mediaType,requestKey:options?.requestKey===undefined?routineTransport()?.key("files")??crypto.randomUUID():options.requestKey},FILE_ORIGINAL_MAX_BYTES);if(!context.local&&!context.localFiles&&metadata.storage==="local")throw new FileOperationError("unsupported_context",400);const header=encodeURIComponent(JSON.stringify(metadata));if(new TextEncoder().encode(header).byteLength>METADATA_BYTES)throw invalid11();const release=await acquireSlot(context.signal);if(context.localFiles&&!routineTransport()&&metadata.size>MAX_BYTES){try{const signal=context.signal??new AbortController().signal;const file2=input.file;let offset=0;const body=file2 instanceof Blob?context.signal?file2:file2.stream():file2 instanceof ReadableStream?file2:new ReadableStream({pull(controller){if(offset===file2.byteLength){controller.close();return}const end=Math.min(offset+256*1024,file2.byteLength);controller.enqueue(file2.subarray(offset,end));offset=end}},{highWaterMark:0});return await send("",{method:"POST",headers:{"content-type":"application/octet-stream","x-os-file":header},body},true,context,signal)}finally{release()}}if(metadata.size>MAX_BYTES)return multipartCreate(input,metadata,(suffix,init,kind,signal)=>kind===true?send(suffix,init,true,context,signal):send(suffix,init,"control",context,signal),release);return timed(async(signal)=>{try{const bytes=array2?new Uint8Array(input.file):await boundedBytes(blob?input.file.stream():input.file,metadata.size,signal);if(bytes.byteLength!==metadata.size)throw new FileOperationError("invalid_input",400,false,{reason:"size_mismatch",expectedBytes:metadata.size,receivedBytes:bytes.byteLength});if(signal.aborted)throw unavailable4();return await send("",{method:"POST",headers:{"content-type":"application/octet-stream","x-os-file":header},body:bytes.buffer},true,context,signal)}finally{release()}},context.signal).catch((error)=>{throw error instanceof FileOperationError?error:unavailable4()})},async enrich(input){const context=await resolveFilesContext();if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some((key)=>!["file","name","content","mediaType","replace"].includes(key))||typeof input.content!=="string"&&!(input.content instanceof Uint8Array))throw invalid11();const path=`${idPath(input.file)}/enrichments`;if(typeof input.content==="string"?input.content.length>MAX_BYTES:input.content.byteLength>MAX_BYTES)throw new FileOperationError("request_too_large",413);return operation(async(context2,signal)=>{let bytes;if(typeof input.content==="string"){const buffer=new Uint8Array(Math.min(MAX_BYTES,input.content.length*3));const encoded=new TextEncoder().encodeInto(input.content,buffer);if(encoded.read!==input.content.length)throw new FileOperationError("request_too_large",413);bytes=buffer.slice(0,encoded.written)}else bytes=new Uint8Array(input.content);const metadata=parseFileEnrichMetadata({name:input.name,size:bytes.byteLength,...input.mediaType===undefined?{}:{mediaType:input.mediaType},...input.replace===undefined?{}:{replace:input.replace}},MAX_BYTES);const header=encodeURIComponent(JSON.stringify(metadata));if(new TextEncoder().encode(header).byteLength>METADATA_BYTES)throw invalid11();const result2=await send(path,{method:"POST",headers:{"content-type":"application/octet-stream","x-os-enrichment":header},body:bytes.buffer},"enrichment",context2,signal);if(result2.name!==metadata.name)throw unavailable4();return result2},context)},async get(id2){return operation((context,signal)=>send(idPath(id2),{method:"GET"},true,context,signal))},read};var ROUTINE_CONNECTION_CREDENTIALS_ENV="OS_ROUTINE_CONNECTION_CREDENTIALS";function parseRoutineConnectionNames(value){if(!Array.isArray(value)||value.some((name)=>typeof name!=="string"||!/^(gmail|airtable|dropbox|outlook|sharepoint)\/[a-z0-9][a-z0-9-]{0,62}$/.test(name))||new Set(value).size!==value.length)throw new Error("Invalid routine connections");return value}var connectionUuid=(v)=>typeof v==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(v);function runtimeConnection(lease){switch(lease.provider){case"outlook":return{id:`outlook/${lease.name}`,provider:lease.provider,name:lease.name,mailboxEmail:lease.mailboxEmail,accessToken:lease.accessToken,expiresAt:lease.expiresAt};case"sharepoint":return{id:`sharepoint/${lease.name}`,provider:lease.provider,name:lease.name,siteId:lease.siteId,siteUrl:lease.siteUrl,accessToken:lease.accessToken,expiresAt:lease.expiresAt};case"gmail":return{id:`gmail/${lease.name}`,provider:lease.provider,name:lease.name,accountEmail:lease.accountEmail,scopes:[...lease.scopes],accessToken:lease.accessToken,expiresAt:lease.expiresAt};case"airtable":return{id:`airtable/${lease.name}`,provider:lease.provider,name:lease.name,baseId:lease.baseId,accessToken:lease.accessToken,runExpiresAt:lease.runExpiresAt};case"dropbox":return{id:`dropbox/${lease.name}`,provider:lease.provider,name:lease.name,accountId:lease.accountId,access:lease.access,rootPath:lease.rootPath,scopes:[...lease.scopes],accessToken:lease.accessToken,expiresAt:lease.expiresAt}}}function parseConnectionLease(raw,now=Date.now()){const v=raw;if(!v||typeof v!=="object"||Array.isArray(v)||!connectionUuid(v.connectionId)||!connectionUuid(v.runId)||typeof v.name!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(v.name)||typeof v.accessToken!=="string"||!/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(v.accessToken))throw new Error("Invalid connection credential");if(v.provider==="outlook"||v.provider==="sharepoint"){const targetValid=v.provider==="outlook"?Object.keys(v).sort().join(",")==="accessToken,connectionId,expiresAt,mailboxEmail,name,provider,runId"&&validMicrosoftMailbox(v.mailboxEmail):Object.keys(v).sort().join(",")==="accessToken,connectionId,expiresAt,name,provider,runId,siteId,siteUrl"&&typeof v.siteUrl==="string"&&canonicalSharePointSiteUrl(v.siteUrl)===v.siteUrl&&validSharePointSiteId(v.siteId,v.siteUrl);if(!targetValid||typeof v.expiresAt!=="string"||!Number.isFinite(Date.parse(v.expiresAt))||Date.parse(v.expiresAt)<=now||Date.parse(v.expiresAt)>now+3600000)throw new Error("Invalid connection credential");return v}if(v.provider==="gmail"){if(Object.keys(v).sort().join(",")!=="accessToken,accountEmail,connectionId,expiresAt,name,provider,runId,scopes"||typeof v.accountEmail!=="string"||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.accountEmail)||!validGoogleScopes(v.scopes)||typeof v.expiresAt!=="string"||!Number.isFinite(Date.parse(v.expiresAt))||Date.parse(v.expiresAt)<=now||Date.parse(v.expiresAt)>now+3600000)throw new Error("Invalid connection credential");return v}if(v.provider==="airtable"&&Object.keys(v).sort().join(",")==="accessToken,baseId,connectionId,name,provider,runExpiresAt,runId"&&typeof v.baseId==="string"&&/^app[A-Za-z0-9]+$/.test(v.baseId)&&typeof v.runExpiresAt==="string"&&Number.isFinite(Date.parse(v.runExpiresAt))&&Date.parse(v.runExpiresAt)>now&&Date.parse(v.runExpiresAt)<=now+15*60000)return v;if(v.provider==="dropbox"&&Object.keys(v).sort().join(",")==="access,accessToken,accountId,connectionId,expiresAt,name,provider,rootPath,runId,scopes"&&typeof v.accountId==="string"&&/^dbid:[A-Za-z0-9_-]{1,128}$/.test(v.accountId)&&v.access==="full_dropbox"&&validDropboxRootPath(v.rootPath)&&validDropboxFileScopes(v.scopes)&&typeof v.expiresAt==="string"&&Number.isFinite(Date.parse(v.expiresAt))&&Date.parse(v.expiresAt)>now&&Date.parse(v.expiresAt)<=now+14400000)return v;throw new Error("Invalid connection credential")}class AirtableOperationError extends Error{effect;receipts;constructor(message,effect="unapplied",receipts=[]){super(message);this.effect=effect;this.receipts=receipts;this.name="AirtableOperationError"}}var recordId=(v)=>typeof v==="string"&&/^rec[A-Za-z0-9]+$/.test(v);var tableId=(v)=>typeof v==="string"&&/^tbl[A-Za-z0-9]+$/.test(v);function fail6(message){throw new AirtableOperationError(message)}function object7(v){if(!v||typeof v!=="object"||Array.isArray(v)||![null,Object.prototype].includes(Object.getPrototypeOf(v)))fail6("Invalid Airtable data");return v}function keys5(v,allowed,required=allowed){if(Object.keys(v).some((k)=>!allowed.includes(k))||required.some((k)=>!Object.hasOwn(v,k)))fail6("Invalid Airtable input")}function text3(v){return typeof v==="string"&&v.length>0&&v.length<=1024}function fields3(v,nonempty=false){const result2=object7(v);if(nonempty&&!Object.keys(result2).length||Object.keys(result2).some((k)=>!text3(k)))fail6("Invalid Airtable fields");try{return serializable(result2)}catch{return fail6("Invalid Airtable fields")}}function record2(v){const r=object7(v);if(!recordId(r.id)||r.createdTime!==undefined&&(typeof r.createdTime!=="string"||!Number.isFinite(Date.parse(r.createdTime))))fail6("Malformed Airtable record");return{id:r.id,...r.createdTime===undefined?{}:{createdTime:r.createdTime},fields:fields3(r.fields)}}function equal(a,b){if(a===b)return true;if(!a||!b||typeof a!=="object"||typeof b!=="object"||Array.isArray(a)!==Array.isArray(b))return false;const left=Object.keys(a),right=Object.keys(b);return left.length===right.length&&left.every((k)=>Object.hasOwn(b,k)&&equal(a[k],b[k]))}function createConnections(transport){return{async get(){throw new Error("Connection unavailable")},airtable(name){if(typeof name!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name))fail6("Invalid Airtable connection name");const call=(operation2,input)=>transport(name,operation2,input);return{tables:{list:async()=>await call("tables.list",{})},records:{list:async(input)=>await call("records.list",input),get:async(input)=>await call("records.get",input),create:async(input)=>await call("records.create",input),update:async(input)=>await call("records.update",input),delete:async(input)=>await call("records.delete",input)}}}}}async function executeAirtableOperation(authority,operation2,raw,options={}){const{name,baseId,accessToken}=authority;if(!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)||!/^app[A-Za-z0-9]+$/.test(baseId)||!/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(accessToken))fail6("Airtable connection unavailable");let input;try{input=object7(serializable(raw))}catch{return fail6("Invalid Airtable input")}const mutation=["records.create","records.update","records.delete"].includes(operation2);const receipt=(ids2)=>({provider:"airtable",connection:`airtable/${name}`,baseId,table:input.table,operation:operation2.slice(8),records:ids2.map((id2)=>({id:id2}))});async function request2(path2,init={},write=false){let response;try{response=await(options.fetch??fetch)(`https://api.airtable.com/v0/${path2}`,{...init,headers:{authorization:`Bearer ${accessToken}`,"content-type":"application/json"},redirect:"manual",signal:options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})}catch{throw new AirtableOperationError("Airtable request acknowledgment unavailable",write?"uncertain":"unapplied")}if(!response.ok){await response.body?.cancel().catch(()=>{});throw new AirtableOperationError("Airtable request rejected",write&&(response.status>=500||response.status===408||response.status<400)?"uncertain":"unapplied")}try{if(!response.headers.get("content-type")?.toLowerCase().includes("application/json"))throw new Error;const value=object7(await response.json());const safe=serializable(value);if(Object.hasOwn(value,"error")||JSON.stringify(safe).includes(accessToken))throw new Error;return value}catch{throw new AirtableOperationError("Malformed Airtable acknowledgment",write?"uncertain":"unapplied")}}if(operation2==="tables.list"){keys5(input,[]);const tables=[],seen=new Set;let offset;do{const query2=new URLSearchParams(offset?{offset}:{});const page=await request2(`meta/bases/${baseId}/tables?${query2}`);if(!Array.isArray(page.tables))fail6("Malformed Airtable tables");for(const value of page.tables){const t=object7(value);if(!tableId(t.id)||!text3(t.name)||!text3(t.primaryFieldId)||!Array.isArray(t.fields)||tables.some((existing)=>existing.id===t.id))fail6("Malformed Airtable table");const metadata=t.fields.map((value2)=>{const f=object7(value2);if(typeof f.id!=="string"||!/^fld[A-Za-z0-9]+$/.test(f.id)||!text3(f.name)||!text3(f.type))fail6("Malformed Airtable field");return{id:f.id,name:f.name,type:f.type,...f.options===undefined?{}:{options:serializable(f.options)}}});if(!metadata.some((f)=>f.id===t.primaryFieldId)||new Set(metadata.map((f)=>f.id)).size!==metadata.length)fail6("Malformed Airtable fields");tables.push({id:t.id,name:t.name,primaryFieldId:t.primaryFieldId,fields:metadata})}offset=nextOffset(page.offset,seen)}while(offset);return tables}if(!text3(input.table)||input.table==="."||input.table==="..")fail6("Invalid Airtable table");if(mutation&&!tableId(input.table))fail6("Airtable writes require a stable table ID");const path=`${baseId}/${encodeURIComponent(input.table)}`;if(operation2==="records.get"){keys5(input,["table","id"]);if(!recordId(input.id))fail6("Invalid Airtable record ID");const result3=record2(await request2(`${path}/${input.id}`));if(result3.id!==input.id)fail6("Malformed Airtable record");return result3}if(operation2==="records.list"){keys5(input,["table","fields"],["table"]);if(input.fields!==undefined&&(!Array.isArray(input.fields)||!input.fields.length||input.fields.some((f)=>!text3(f))||new Set(input.fields).size!==input.fields.length))fail6("Invalid Airtable field selection");const records2=[],ids2=new Set,seen=new Set;let offset;do{const query2=new URLSearchParams;for(const field of input.fields??[])query2.append("fields[]",field);if(offset)query2.set("offset",offset);const page=await request2(`${path}?${query2}`);if(!Array.isArray(page.records))fail6("Malformed Airtable records");for(const value of page.records){const r=record2(value);if(ids2.has(r.id))fail6("Malformed Airtable pagination");ids2.add(r.id);records2.push(r)}offset=nextOffset(page.offset,seen)}while(offset);return records2}if(!mutation)fail6("Unsupported Airtable operation");keys5(input,["table","records"]);if(!Array.isArray(input.records)||!input.records.length||input.records.length>10)fail6("Invalid Airtable batch");const kind=operation2.slice(8),ids=new Set;const records=input.records.map((value)=>{const r=object7(value);keys5(r,kind==="create"?["fields"]:kind==="update"?["id","expected","set"]:["id","expected"]);if(kind==="create")return{fields:fields3(r.fields,true)};if(!recordId(r.id)||ids.has(r.id))fail6("Invalid Airtable batch record ID");ids.add(r.id);const set=kind==="update"?fields3(r.set,true):undefined;if(set&&Object.values(set).some((value2)=>value2===null))fail6("Airtable guard null cannot be an update value");return{id:r.id,expected:fields3(r.expected),...set?{set}:{}}});for(const r of records){if(!("id"in r))continue;const current=record2(await request2(`${path}/${r.id}`));if(current.id!==r.id)fail6("Malformed Airtable record");for(const[key,value]of Object.entries(r.expected)){if(value===null?Object.hasOwn(current.fields,key):!Object.hasOwn(current.fields,key)||!equal(current.fields[key],value))fail6("Airtable reviewed values are stale")}}await options.beforeMutation?.();const query=new URLSearchParams;if(kind==="delete")for(const id2 of ids)query.append("records[]",id2);const result2=await request2(`${path}${kind==="delete"?`?${query}`:""}`,{method:kind==="create"?"POST":kind==="update"?"PATCH":"DELETE",...kind==="delete"?{}:{body:JSON.stringify({records:records.map((r)=>("id"in r)?{id:r.id,fields:r.set}:r)})}},true);const acknowledged=[],returned=[];try{if(!Array.isArray(result2.records))throw new Error;for(const value of result2.records){const r=object7(value);if(!recordId(r.id)||acknowledged.includes(r.id)||kind!=="create"&&!ids.has(r.id)||kind==="delete"&&r.deleted!==true)throw new Error;acknowledged.push(r.id);if(kind!=="delete")returned.push(record2(r))}if(acknowledged.length!==records.length)throw new Error}catch{throw new AirtableOperationError("Incomplete Airtable mutation acknowledgment",acknowledged.length?"partial":"uncertain",acknowledged.length?[receipt(acknowledged)]:[])}return{receipt:receipt(acknowledged),...kind==="delete"?{}:{records:returned}}}function nextOffset(value,seen){if(value===undefined)return;if(!text3(value)||seen.has(value))fail6("Malformed Airtable pagination");seen.add(value);return value}var MANAGED_CONNECTION_CAPABILITY_ENV="OS_MANAGED_CONNECTION_CAPABILITY";function managedConnections(capability){const endpoint=new URL(capability.endpoint);if(endpoint.protocol!=="http:"||endpoint.hostname!=="127.0.0.1"||!endpoint.port||endpoint.pathname!=="/"||endpoint.search||endpoint.hash||endpoint.username||endpoint.password||!/^[0-9a-f-]{36}$/.test(capability.token))throw new AirtableOperationError("Airtable capability unavailable");const transport=async(name,operation2,input)=>{let safeInput;try{safeInput=serializable(input)}catch{safeInput=null}try{const response=await fetch(new URL("airtable",endpoint),{method:"POST",redirect:"error",headers:{authorization:`Bearer ${capability.token}`,"content-type":"application/json"},body:JSON.stringify({name,operation:operation2,input:safeInput}),signal:AbortSignal.timeout(125000)});const value=await response.json();if(!response.ok)throw new AirtableOperationError("Airtable operation failed; the execution retains its evidence",value.effect==="partial"||value.effect==="uncertain"?value.effect:"unapplied",value.receipts??[]);return value}catch(error){if(error instanceof AirtableOperationError)throw error;throw new AirtableOperationError("Airtable parent acknowledgment unavailable",["records.create","records.update","records.delete"].includes(operation2)?"uncertain":"unapplied")}};return createConnections(transport)}var observer;function observeLocalRoutineEffects(value){observer=value}async function reportLocalRoutineEffect(value){await observer?.(value)}var identityPattern=/^(gmail|airtable|dropbox|outlook|sharepoint)\/([a-z0-9][a-z0-9-]{0,62})$/;var workspacePattern=/^[a-z0-9][a-z0-9-]{0,62}$/;var providerNames={gmail:"Gmail",airtable:"Airtable",dropbox:"Dropbox",outlook:"Outlook",sharepoint:"SharePoint"};function parseConnectionFailureDetail(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Connection failure");const detail=value;if(!["identity","identity,workspace"].includes(Object.keys(detail).sort().join(","))||typeof detail.identity!=="string"||!identityPattern.test(detail.identity)||detail.workspace!==undefined&&(typeof detail.workspace!=="string"||!workspacePattern.test(detail.workspace)))throw new Error("Invalid Connection failure");return{identity:detail.identity,...detail.workspace===undefined?{}:{workspace:detail.workspace}}}function connectionFailureMessage(value){const detail=parseConnectionFailureDetail(value);const[,provider,name]=identityPattern.exec(detail.identity);const first=`Couldn’t use ${providerNames[provider]??provider} connection ${name}.`;return detail.workspace?`${first}
36
+ Check the file’s stored media type before retrying. The model was not called.`}switch(code){case"access_denied":return"This routine doesn’t currently have permission to use AI.";case"capability_unavailable":return"AI is unavailable in this execution environment.";case"invalid_input":return"The AI request is invalid. Check its input, instructions and schema.";case"unsupported_file":return"AI couldn’t read this file in the requested format.";case"file_unavailable":return"AI couldn’t read or verify the file.";case"input_too_large":return"The AI input exceeds the size limit for this execution path.";case"output_too_large":return"The AI response exceeds the size limit for this execution path.";case"provider_failure":return"AI couldn’t complete the request. No more specific reason was recorded.";case"invalid_output":return"AI returned an answer OS could not accept.";case"cancelled":return"The AI operation was stopped before it completed."}}var ROUTINE_AI_VALUE_BYTES=256*1024;var ROUTINE_AI_RESULT_BYTES=6*ROUTINE_AI_VALUE_BYTES+1024;var ROUTINE_AI_EVIDENCE_BYTES=4*1024;var ROUTINE_AI_ERROR_CODES=["access_denied","capability_unavailable","invalid_input","unsupported_file","file_unavailable","input_too_large","output_too_large","provider_failure","invalid_output","cancelled"];class AIError extends Error{code;detail;constructor(code,options={}){const detail=parseRoutineAIErrorDetail(code,options.detail);super(routineAIErrorMessage(code,detail));this.code=code;this.name="AIError";if(detail)this.detail=Object.freeze(detail);if(code==="invalid_output"&&typeof options.text==="string"&&new TextEncoder().encode(options.text).byteLength<=ROUTINE_AI_VALUE_BYTES)Object.defineProperty(this,"text",{value:options.text})}}function parseRoutineAIError(value){try{const v=capture(value,"invalid_output","output_too_large",ROUTINE_AI_RESULT_BYTES);assertRoutineFields(v,["code","detail","text"]);if(!ROUTINE_AI_ERROR_CODES.includes(v.code))throw new Error;const detail=parseRoutineAIErrorDetail(v.code,v.detail);if(Object.hasOwn(v,"detail")&&!detail||Object.hasOwn(v,"text")&&(typeof v.text!=="string"||new TextEncoder().encode(v.text).byteLength>ROUTINE_AI_VALUE_BYTES)||v.code!=="invalid_output"&&Object.hasOwn(v,"text"))throw new Error;return new AIError(v.code,{detail,...v.text===undefined?{}:{text:v.text}})}catch{throw new AIError("invalid_output")}}function capture(value,invalid3,oversized,limit=ROUTINE_AI_VALUE_BYTES){try{assertRoutineJson(value);const encoded=JSON.stringify(value);if(new TextEncoder().encode(encoded).byteLength>limit)throw new AIError(oversized);return freezeRoutineMetadata(JSON.parse(encoded))}catch(error){if(error instanceof AIError)throw error;throw new AIError(invalid3)}}function parseRoutineAIRequest(value){const v=capture(value,"invalid_input","input_too_large");try{assertRoutineFields(v,v.kind==="generateObject"?["kind","instructions","input","schema","tools"]:["kind","instructions","input","tools"]);if(!["generateText","generateObject"].includes(v.kind)||typeof v.instructions!=="string"||!v.instructions.trim())throw new Error;const input=typeof v.input==="string"?v.input:parseFileDescriptor(v.input);if(Object.hasOwn(v,"tools")&&typeof v.tools!=="boolean")throw new AIError("invalid_input",{detail:{reason:"invalid_tools"}});if(v.tools===true&&typeof input==="string")throw new AIError("invalid_input",{detail:{reason:"tools_require_file"}});const tools=v.tools===true?{tools:true}:{};if(v.kind==="generateText")return freezeRoutineMetadata({kind:v.kind,instructions:v.instructions,input,...tools});const schema=parseAppRoutineContract({routine:"ai",input:v.schema,steps:[{id:"generate"}]}).input;return freezeRoutineMetadata({kind:v.kind,instructions:v.instructions,input,schema,...tools})}catch(error){if(error instanceof AIError)throw error;throw new AIError("invalid_input")}}function parseRoutineAIResult(request,value){let v;try{v=capture(value,"invalid_output","output_too_large",request.kind==="generateText"?ROUTINE_AI_RESULT_BYTES:ROUTINE_AI_VALUE_BYTES);assertRoutineFields(v,request.kind==="generateText"?["text"]:["object"]);if(request.kind==="generateText"){if(typeof v.text!=="string")throw new Error;return acceptText(request,v.text)}if(!Object.hasOwn(v,"object"))throw new Error}catch(error){if(error instanceof AIError)throw error;throw new AIError("invalid_output",{detail:{reason:"invalid_response"}})}validateObject(request.schema,v.object);return freezeRoutineMetadata({object:v.object})}function validateObject(schema,object3,text2){let detail={reason:"invalid_response"};try{validateRoutineSchemaValue(schema,object3,(issue)=>{detail=issue})}catch{throw new AIError("invalid_output",{...text2===undefined?{}:{text:text2},detail})}}function acceptText(request,text2){if(new TextEncoder().encode(text2).byteLength>ROUTINE_AI_VALUE_BYTES)throw new AIError("output_too_large");if(request.kind==="generateText"){if(!text2.trim())throw new AIError("invalid_output",{text:text2,detail:{reason:"empty_text"}});return freezeRoutineMetadata({text:text2})}let object3;const trimmed=text2.trim();const fenced=/^(`{3,}|~{3,})(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/i.exec(trimmed);try{object3=JSON.parse(fenced?fenced[2]:text2)}catch{throw new AIError("invalid_output",{text:text2,detail:{reason:"invalid_json"}})}validateObject(request.schema,object3,text2);return capture({object:object3},"invalid_output","output_too_large")}var ROUTINE_STEP_SUMMARY_BYTES=256*1024;var ROUTINE_STEP_OUTPUT_BYTES=1024*1024;function parseRoutineStepOutputDetail(value){const invalid3=()=>{throw new AppRoutineContractError("invalid_value")};assertRoutineFields(value,["step","sizeBytes","limitBytes","summaryBytes","dataBytes"]);const{step,sizeBytes,limitBytes,summaryBytes,dataBytes}=value;if(!isAppRoutineName(step)||![sizeBytes,limitBytes,summaryBytes,dataBytes].every((bytes)=>Number.isSafeInteger(bytes)&&bytes>0)||sizeBytes!==summaryBytes+dataBytes||limitBytes!==(summaryBytes>ROUTINE_STEP_SUMMARY_BYTES?ROUTINE_STEP_SUMMARY_BYTES:ROUTINE_STEP_OUTPUT_BYTES)||(limitBytes===ROUTINE_STEP_SUMMARY_BYTES?summaryBytes:sizeBytes)<=limitBytes)return invalid3();return freezeRoutineMetadata({step,sizeBytes,limitBytes,summaryBytes,dataBytes})}function routineStepOutputMessage(value){const detail=parseRoutineStepOutputDetail(value);const size=`${(detail.sizeBytes/(1024*1024)).toFixed(1)} MB`;const bound=detail.limitBytes===ROUTINE_STEP_SUMMARY_BYTES?`, including ${(detail.summaryBytes/1024).toFixed(1)} KB of summary. Each step's summary can return up to 256 KB.`:". Each step can return up to 1 MB across its summary and data.";return`Step ${detail.step} returned ${size} of output${bound} Return fewer fields or process a smaller batch, then try again.`}class RoutineStepOutputError extends Error{code="step_output_too_large";detail;constructor(detail){const captured=parseRoutineStepOutputDetail(detail);super(routineStepOutputMessage(captured));this.detail=captured;Object.freeze(this)}}function captureRoutineStepOutput(step,summary,data){assertRoutineJson(summary);assertRoutineJson(data);const summaryJson=JSON.stringify(summary),dataJson=JSON.stringify(data);const summaryBytes=new TextEncoder().encode(summaryJson).byteLength;const dataBytes=new TextEncoder().encode(dataJson).byteLength;const sizeBytes=summaryBytes+dataBytes;const limitBytes=summaryBytes>ROUTINE_STEP_SUMMARY_BYTES?ROUTINE_STEP_SUMMARY_BYTES:ROUTINE_STEP_OUTPUT_BYTES;if(summaryBytes>ROUTINE_STEP_SUMMARY_BYTES||sizeBytes>ROUTINE_STEP_OUTPUT_BYTES)throw new RoutineStepOutputError({step,sizeBytes,limitBytes,summaryBytes,dataBytes});return freezeRoutineMetadata({summary:JSON.parse(summaryJson),data:JSON.parse(dataJson)})}function captureRetainedStepOutput(step,value){const hasSummary=Object.hasOwn(value,"summary"),hasData=Object.hasOwn(value,"data");if(hasSummary&&hasData)return captureRoutineStepOutput(step,value.summary,value.data);for(const key of["summary","data"])if(Object.hasOwn(value,key)){assertRoutineJson(value[key]);const bytes=new TextEncoder().encode(JSON.stringify(value[key])).byteLength;if(bytes>(key==="summary"?ROUTINE_STEP_SUMMARY_BYTES:ROUTINE_STEP_OUTPUT_BYTES))throw new AppRoutineContractError("invalid_value")}return freezeRoutineMetadata(JSON.parse(JSON.stringify(value)))}var LIMIT=256*1024;var invalid3=()=>{throw new AppRoutineContractError("invalid_value")};var invalidContract3=()=>{throw new AppRoutineContractError("invalid_contract")};var empty={type:"object",properties:{},required:[],additionalProperties:false};function captureJson(value,maximum=LIMIT){assertRoutineJson(value);const encoded=JSON.stringify(value);if(maximum!==null&&new TextEncoder().encode(encoded).byteLength>maximum)return invalid3();return freezeRoutineMetadata(JSON.parse(encoded))}function capture2(schema,value){const captured=captureJson(value);validateRoutineSchemaValue(schema,captured);return captured}var schemas=new WeakMap;function nestedSchema(value){const metadata=schemaMetadata(value);if(Object.hasOwn(metadata,"default"))return invalidContract3();return metadata.schema}function schemaMetadata(value){if(!value||typeof value!=="object")return invalidContract3();const registered=schemas.get(value);if(registered)return registered;try{assertRoutineJson(value)}catch{return invalidContract3()}return{schema:parseAppRoutineContract({routine:"definition",input:value,steps:[{id:"inspect"}]}).input}}function declaration(value,defaults){try{assertRoutineJson(value)}catch{return invalidContract3()}const parsed=freezeRoutineMetadata(parseAppRoutineContract({routine:"definition",input:value,steps:[{id:"inspect"}]}).input);const captured=defaults?capture2(parsed,defaults.value):undefined;const builder=Object.defineProperty({...parsed},"default",{value:(value2)=>declaration(parsed,{value:value2})});schemas.set(builder,{schema:parsed,...defaults?{default:captured}:{}});return Object.freeze(builder)}var schema={object(properties){return declaration({type:"object",properties:Object.fromEntries(Object.entries(properties).map(([key,value])=>[key,nestedSchema(value)])),required:Object.keys(properties),additionalProperties:false})},array(items,options={}){assertRoutineFields(options,["maxItems"]);return declaration({type:"array",items:nestedSchema(items),...options})},string(options={}){return declaration({type:"string",...options})},integer(options={}){return declaration({type:"integer",...options})},number(options={}){return declaration({type:"number",...options})},boolean(){return declaration({type:"boolean"})}};var file=(options={})=>{assertRoutineFields(options,["storage","path"]);return declaration({type:"file",...options})};var defineResponse=(value)=>defineHandler(value);var definitions=new WeakMap;var defineRoutine=(definition)=>{assertRoutineFields(definition,["id","title","schedule","input","steps","result","access","responses","run"]);if(!isAppRoutineName(definition.id)||definition.title!==undefined&&!routineTitle(definition.title)||typeof definition.run!=="function")return invalidContract3();const input=definition.input===undefined?{schema:empty,default:{}}:schemaMetadata(definition.input);const schedule=definition.schedule===undefined?undefined:routineScheduleMetadata(definition.schedule,input.schema,Object.hasOwn(input,"default"));const result=definition.result===undefined?undefined:schemaMetadata(definition.result).schema;const access=parseRoutineAccess(definition.access);assertRoutineFields(definition.steps??{});const executable=Object.fromEntries(Object.entries(definition.steps??{}).map(([id2,step])=>{assertRoutineFields(step,["title","run"]);if(!routineTitle(step.title)||typeof step.run!=="function")return invalidContract3();return[id2,Object.freeze({title:step.title,run:step.run})]}));const steps=Object.entries(executable).map(([id2,step])=>({id:id2,title:step.title}));parseAppRoutineContract({routine:definition.id,input:input.schema,steps:steps.length?steps.map(({id:id2})=>({id:id2})):[{id:"inspect"}],...result?{result}:{}});const responses=[];const ids=new Set;if(definition.responses!==undefined){if(!Array.isArray(definition.responses)||definition.responses.length>64||Reflect.ownKeys(definition.responses).length!==definition.responses.length+1)return invalidContract3();for(let index=0;index<definition.responses.length;index++){const descriptor=Object.getOwnPropertyDescriptor(definition.responses,String(index));if(!descriptor||!Object.hasOwn(descriptor,"value"))return invalidContract3();const response=descriptor.value;assertRoutineFields(response,["id","results","run"]);if(!isAppRoutineName(response.id)||ids.has(response.id))return invalidContract3();ids.add(response.id);if(response.results!==undefined){try{assertRoutineJson(response.results)}catch{return invalidContract3()}}try{responses.push(defineHandler(response))}catch{return invalidContract3()}}}const contract=freezeRoutineMetadata({id:definition.id,...definition.title===undefined?{}:{title:definition.title},...schedule===undefined?{}:{schedule},input:input.schema,...Object.hasOwn(input,"default")?{inputDefault:input.default}:{},access,responses:responses.map(({id:id2})=>({id:id2})),steps,...result?{result}:{}});const captured=Object.freeze({...definition,...schedule===undefined?{}:{schedule},access,steps:Object.freeze(executable),responses:Object.freeze(responses.map((handler)=>defineHandler({...handler,async run(context,runtime){let active=true;const capabilities=runtime?createCapabilityRuntime(contract,runtime,()=>active,"Response"):undefined;try{return await handler.run(context,capabilities?.os)}catch(error){active=false;throw error}finally{try{await capabilities?.drain()}finally{active=false}}}}))),...definition.input===undefined?{}:{input:declaration(input.schema,Object.hasOwn(input,"default")?{value:input.default}:undefined)},...result===undefined?{}:{result:declaration(result)},run:(input2,os)=>executeRoutineDefinition(captured,input2,os)});definitions.set(captured,{contract,steps:executable,run:definition.run});return captured};function inspectRoutineDefinition(definition){if(!definition||typeof definition!=="object")return invalidContract3();const registered=definitions.get(definition);if(!registered)return invalidContract3();return registered.contract}function captureRoutineInput(definition,input){const contract=inspectRoutineDefinition(definition);return capture2(contract.input,input===undefined&&Object.hasOwn(contract,"inputDefault")?contract.inputDefault:input)}function createCapabilityRuntime(contract,runtime,current,owner){const aiWork=new Set;const generate=(kind,value)=>{const operation=(async()=>{if(!current()||contract.access.ai!==true)throw new AIError("access_denied");if(!runtime.ai)throw new AIError("capability_unavailable");let request;try{assertRoutineFields(value,kind==="generateObject"?["instructions","input","schema","tools"]:["instructions","input","tools"]);request=parseRoutineAIRequest({kind,instructions:value.instructions,input:value.input,...kind==="generateObject"?{schema:schemaMetadata(value.schema).schema}:{},...value.tools===undefined?{}:{tools:value.tools}})}catch(error){if(error instanceof AIError)throw error;throw new AIError("invalid_input")}const result=await runtime.ai[kind](request);if(!current())throw new AIError("access_denied");return parseRoutineAIResult(request,result)})();aiWork.add(operation);operation.then(()=>aiWork.delete(operation),()=>aiWork.delete(operation));return operation};const guarded=(value,receiver)=>typeof value==="function"?(...args)=>{if(!current())throw new Error(`${owner} authority ended`);return guarded(Reflect.apply(value,receiver,args))}:value&&typeof value==="object"&&!(value instanceof Promise)?new Proxy({...value},{get(_target,key){return guarded(Reflect.get(value,key,value),value)}}):value;const validateHandlers=(value)=>{for(const question2 of value.questions??[])if(question2.handler&&!contract.responses.some((handler)=>handler.id===question2.handler.id))return invalid3();return value};const os=Object.freeze({...guarded({data:runtime.data,files:runtime.files,ai:{generateText:(value)=>generate("generateText",value),generateObject:(value)=>generate("generateObject",value)},connections:{...runtime.connections,get:async(identity)=>{if(!current()||!contract.access.connections?.includes(identity))throw new Error("Connection unavailable");const value=await runtime.connections.get(identity);if(!current())throw new Error(`${owner} authority ended`);return value}},inbox:{...runtime.inbox,publishAsk:(value,options)=>runtime.inbox.publishAsk(validateHandlers(value),options)}})});return{os,guarded,async drain(){while(aiWork.size)await Promise.allSettled([...aiWork])}}}async function executeRoutineDefinition(definition,input,runtime){const captured=captureRoutineInput(definition,input);const{contract,steps,run}=definitions.get(definition);let active=true,accepting=true,broken=false;let outputFailure;let work=Promise.resolve();const capabilities=createCapabilityRuntime(contract,runtime,()=>active&&!broken,"Run");const called=new Set;const reached=new Set;let activeStep;const progress=new Map;const os=Object.freeze({...capabilities.os,...capabilities.guarded({run:freezeRoutineMetadata({id:runtime.run.id,async progress(value){assertRoutineFields(value,["completed","total"]);const{completed,total}=value;const prior=activeStep?progress.get(activeStep):undefined;if(!active||broken||!activeStep||!Number.isSafeInteger(completed)||!Number.isSafeInteger(total)||completed<1||completed>total||prior&&(prior.total!==total||completed<=prior.completed))return invalid3();const accepted=freezeRoutineMetadata({step:activeStep,completed,total});await runtime.run.progress(accepted);progress.set(activeStep,accepted)}}),...runtime.artifact?{artifact:runtime.artifact}:{}}),step(id2,...input2){let saved;try{if(!active||!accepting||broken||!Object.hasOwn(steps,id2)||called.has(id2)||input2.length>1)return invalid3();if(input2.length)saved=captureJson(input2[0],null);called.add(id2)}catch(error){broken=true;return Promise.reject(error)}const next=work.then(async()=>{if(broken)return invalid3();reached.add(id2);try{await runtime.step(id2,{status:"running"});activeStep=id2;const output=await steps[id2].run(saved,os);assertRoutineFields(output,["summary","data"]);if(!Object.hasOwn(output,"summary")||!Object.hasOwn(output,"data"))return invalid3();const{summary,data}=captureRoutineStepOutput(id2,output.summary,output.data);await runtime.step(id2,{status:"completed",summary,data});activeStep=undefined;return freezeRoutineMetadata({summary,data})}catch(error){if(error instanceof RoutineStepOutputError)outputFailure??=error;broken=true;activeStep=undefined;await runtime.step(id2,{status:"failed"});throw error}});work=next.then(()=>{},()=>{broken=true});return next}});let result,failure;try{result=await run(captured,os)}catch(error){failure=error;broken=true}accepting=false;await work;await capabilities.drain();active=false;try{for(const step of contract.steps)if(!reached.has(step.id))await runtime.step(step.id,{status:"skipped"})}catch(error){throw outputFailure??error}if(broken)throw outputFailure??failure??new AppRoutineContractError("invalid_value");if(contract.result!==undefined)return capture2(contract.result,result);if(result!==undefined)return invalid3();return}var fieldProblems=["unknown","missing","invalid","source_schema"];var reasons={unknown:"unknown_field",missing:"missing_field",invalid:"invalid_value",source_schema:"source_schema_mismatch"};var expectationKinds={string:"a string",integer:"a safe integer",number:"a finite number",boolean:"a boolean",date:"a date in YYYY-MM-DD format",const:"the constant declared in the schema",datetime:"a UTC date and time in YYYY-MM-DDTHH:mm:ss.sssZ format, for example 2026-09-15T14:30:00.000Z",enum:"one of the choices declared in the schema",link:"a link to an existing record of an allowed type",object:"an object matching the schema",map:"a map matching the schema"};function expectationText(expected){if(!Object.hasOwn(expectationKinds,expected.type)||typeof expected.many!=="boolean"||typeof expected.nullable!=="boolean"||expected.decimalPlaces!==undefined&&(expected.type!=="number"||!Number.isInteger(expected.decimalPlaces)||expected.decimalPlaces<0||expected.decimalPlaces>6)||expected.format!==undefined&&(expected.type!=="date"||expected.format!=="month"))return;const scalar=expected.type==="number"&&expected.decimalPlaces!==undefined?`a finite number with at most ${expected.decimalPlaces} decimal places`:expected.type==="date"&&expected.format==="month"?"a date in YYYY-MM format":expectationKinds[expected.type];return`${expected.many?"Expected a list. Each item must be":"Expected"} ${scalar}.${expected.nullable?" The field may also be null.":""}`}function parseExpectation(text2){if(!text2)return;const parts=/^Expected (a list\. Each item must be )?(.+?)\.( The field may also be null\.)?$/.exec(text2);if(!parts)return;const number=/^a finite number with at most ([0-6]) decimal places$/.exec(parts[2]);const month=parts[2]==="a date in YYYY-MM format";const kind=number?"number":month?"date":Object.keys(expectationKinds).find((kind2)=>expectationKinds[kind2]===parts[2]);if(!kind)return;const expected={type:kind,many:!!parts[1],nullable:!!parts[3],...number?{decimalPlaces:Number(number[1])}:{},...month?{format:"month"}:{}};return expectationText(expected)===text2?expected:undefined}function parseDataValidationDetail(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const v=value;if(Object.keys(v).some((key)=>!["record","field","reason","schemaFile","expected"].includes(key))||typeof v.record!=="string"||typeof v.field!=="string")return;const problem=fieldProblems.find((problem2)=>reasons[problem2]===v.reason);if(!problem||v.schemaFile!==undefined&&typeof v.schemaFile!=="string")return;let expected;if(Object.hasOwn(v,"expected")){if(!v.expected||typeof v.expected!=="object"||Array.isArray(v.expected))return;const e=v.expected;if(Object.keys(e).some((key)=>!["type","many","nullable","decimalPlaces","format"].includes(key)))return;expected={...e};if(!expectationText(expected))return}if(problem==="unknown"&&expected||problem==="source_schema"&&(v.field!=="media_type"||expected?.type!=="string"||expected.many||expected.nullable))return;if(!recordFieldMessage(v.record,v.field,problem,v.schemaFile,expected))return;return{record:v.record,field:v.field,reason:reasons[problem],...typeof v.schemaFile==="string"?{schemaFile:v.schemaFile}:{},...expected?{expected}:{}}}function recordFieldDetail(record2,field,problem,schemaFile,expectation){const expected=problem==="source_schema"?{type:"string",many:false,nullable:false}:expectation;return parseDataValidationDetail({record:record2,field,reason:reasons[problem],...schemaFile?{schemaFile}:{},...expected?{expected}:{}})}function recordFieldMessage(record2,field,problem,schemaPath,expected){if(!validRecordRef(record2)||!/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(field))return;if(schemaPath!==undefined&&(schemaPath.length>256||!/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*\/_schema\.yaml$/.test(schemaPath)||schemaPath.split("/").some((part)=>[".","..",".git","routines"].includes(part))))return;const prefix=`Record "${record2}" isn't valid.`;const schema2=schemaPath?`"${schemaPath}"`:"the collection schema";if(problem==="source_schema")return field==="media_type"?`${prefix} This repository's Source schema${schemaPath?` ${schema2}`:""} doesn't include "media_type". The OS SDK uses "media_type" for file Sources. Update the Source schema in this repository to include this field.`:undefined;if(problem==="unknown")return`${prefix} The record contains "${field}", but ${schema2} doesn't define that field. Check that the record and ${schemaPath?"that file":"the collection schema"} use the same field name.`;if(problem==="missing")return`${prefix} The record is missing required field "${field}". Add it as defined in ${schema2}.`;const expectation=expected?expectationText(expected):undefined;if(expected&&!expectation)return;return`${prefix} The record has an invalid value for field "${field}".${expectation?` ${expectation}`:""} Check its definition in ${schema2}.`}function safeRecordFieldMessage(value){if(typeof value!=="string"||value.length>1200)return;const parts=/^Record "([^"]+)" isn't valid\. (.+)$/.exec(value);if(!parts)return;const schemaPath=/"([^"]+\/_schema\.yaml)"/.exec(value)?.[1];const field=[...parts[2].matchAll(/"([^"]+)"/g)].map((match)=>match[1]).find((part)=>part!==schemaPath);if(!field)return;const expected=parseExpectation(/\. (Expected .+) Check its definition in /.exec(value)?.[1]);return fieldProblems.map((problem)=>recordFieldMessage(parts[1],field,problem,schemaPath,expected)).find((message)=>message===value)}function dataValidationMessageFacts(error){if(error.code==="invalid_change"){const detail=parseDataValidationDetail(error.detail);if(detail){const problem=fieldProblems.find((problem2)=>reasons[problem2]===detail.reason);return{detail,message:recordFieldMessage(detail.record,detail.field,problem,detail.schemaFile,detail.expected)}}}const message=error.code==="invalid_change"?safeRecordFieldMessage(error.message):undefined;return message?{message}:{}}function explainDataValidation(error,message,detail){Object.assign(error,dataValidationMessageFacts({code:error.code,message:typeof message==="string"?message:"",detail}));return error}function dataPublicationFailureMessage(detail){if(detail.preflight==="dirty_repository")return`Data repository ${detail.repository} has existing changes. No Record files were changed.`+` Use os data push ${detail.repository} or stash those Data changes with Git, then run the routine again.`;return(detail.state==="commit"?`Data commit ${detail.commit} remains in your checkout; its push is unconfirmed.`:detail.state==="files"?"Your Record files were applied, but Git could not create their commit.":"Data publication needs Git preparation. No Record files were changed.")+` Review git status and your branch and destination, then use os data push ${detail.repository}. Do not rerun the routine to recover this publication.`}var localDataPath=(value,repository)=>typeof value==="string"&&value.length<=1024&&value.startsWith(`${repository}/`)&&!value.includes("\\")&&!/[\x00-\x1f\x7f]/.test(value)&&value.split("/").every((part)=>!!part&&part!=="."&&part!=="..");var localDataFile=(value,repository)=>{if(!value||typeof value!=="object"||Array.isArray(value))return false;const row=value;return Object.keys(row).sort().join(",")==="action,path"&&["created","updated","deleted"].includes(String(row.action))&&localDataPath(row.path,repository)};function parseDataFailureDetail(value){const invalid4=()=>{throw new Error("Invalid local Data failure detail")};if(!value||typeof value!=="object"||Array.isArray(value))return invalid4();const row=value;if(Object.keys(row).sort().join(",")!=="cause,code,files,nextAction,operation,repository"||!["local_data_read_failed","local_data_write_failed","local_data_write_partial"].includes(String(row.code))||!["read","write"].includes(String(row.operation))||typeof row.repository!=="string"||!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(row.repository)||row.repository.includes("//")||row.repository.includes("..")||!["fix_failed_file_then_rerun","review_resolve_then_rerun"].includes(String(row.nextAction)))return invalid4();const repository=row.repository;if(!row.cause||typeof row.cause!=="object"||Array.isArray(row.cause))return invalid4();const cause=row.cause;if(!["code,message","code,message,path"].includes(Object.keys(cause).sort().join(","))||!["schema_validation_failed","invalid_record","unsafe_record","stale_record","path_conflict","filesystem_unavailable"].includes(String(cause.code))||typeof cause.message!=="string"||!cause.message||cause.message.length>512||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(cause.message)||cause.path!==undefined&&!localDataPath(cause.path,repository))return invalid4();if(!row.files||typeof row.files!=="object"||Array.isArray(row.files))return invalid4();const files=row.files;if(Object.keys(files).some((key)=>!["state","saved","failed","notAttempted","savedOmitted","notAttemptedOmitted"].includes(key))||!["none","partial"].includes(String(files.state))||!Array.isArray(files.saved)||files.saved.length>128||!files.saved.every((item)=>localDataFile(item,repository))||files.failed!==undefined&&!localDataFile(files.failed,repository)||!Array.isArray(files.notAttempted)||files.notAttempted.length>128||!files.notAttempted.every((item)=>localDataFile(item,repository)))return invalid4();for(const key of["savedOmitted","notAttemptedOmitted"])if(files[key]!==undefined&&(!Number.isSafeInteger(files[key])||Number(files[key])<1||Number(files[key])>1e4))return invalid4();if(row.operation==="read"&&(row.code!=="local_data_read_failed"||files.state!=="none"||files.saved.length||files.failed!==undefined||files.notAttempted.length)||row.operation==="write"&&row.code==="local_data_read_failed"||row.code==="local_data_write_partial"&&(files.state!=="partial"||!files.saved.length)||row.code!=="local_data_write_partial"&&files.state==="partial")return invalid4();return structuredClone(value)}function parseDataOperationDetail(value){const validation=parseDataValidationDetail(value);if(validation)return validation;if(value&&typeof value==="object"&&!Array.isArray(value)&&value.code==="record_limit_exceeded"){const row=value;if(Object.keys(row).sort().join(",")!=="code,collections,maxRecords"||!Number.isSafeInteger(row.maxRecords)||Number(row.maxRecords)<1||!Array.isArray(row.collections)||!row.collections.length||row.collections.length>16||!row.collections.every((name)=>typeof name==="string"&&name.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(name))||new Set(row.collections).size!==row.collections.length)throw new Error("Invalid Data operation detail");return structuredClone(value)}if(value&&typeof value==="object"&&!Array.isArray(value)&&value.code==="local_data_publication_failed"){const row=value;if(Object.keys(row).sort().join(",")!==(row.state==="commit"?"code,commit,repository,state":Object.hasOwn(row,"preflight")?"code,preflight,repository,state":"code,repository,state")||Object.hasOwn(row,"preflight")&&(row.state!=="unapplied"||row.preflight!=="dirty_repository")||typeof row.repository!=="string"||!/^[a-z0-9][a-z0-9._-]{0,127}$/.test(row.repository)||row.repository.includes("..")||!["unapplied","files","commit"].includes(String(row.state))||row.state==="commit"&&(typeof row.commit!=="string"||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(row.commit)))throw new Error("Invalid Data publication detail");return structuredClone(value)}return parseDataFailureDetail(value)}function dataRecordLimitMessage(detail){const scope=detail.collections.length===1?` from ${detail.collections[0]}`:` across ${detail.collections.join(", ")}`;return`The routine tried to load more than ${detail.maxRecords.toLocaleString("en-US")} matching Records${scope}. `+"Narrow the query or increase maxRecords."}function dataErrorMessage(code,effect){if(effect==="uncertain")return"We couldn’t confirm whether your changes were saved.";if(code==="unavailable"&&effect==="unapplied")return"Your changes could not be saved.";if(code==="apply_pending")return effect==="applied"?"Your changes were saved, but confirmation is still pending.":effect==="unapplied"?"Your changes have not been saved yet.":"We couldn’t confirm whether your changes were saved.";const message={context_unavailable:"Data access is not available in this context.",unauthenticated:"Sign in to access this data.",access_denied:"You do not have permission to access this data.",invalid_query:"The data request is not valid.",request_too_large:"The data request is too large.",capacity:"The data service has reached its limit. Try again later.",unavailable:"We couldn’t complete your request.",invalid_change:"These changes are not valid.",conflict:"The data changed before the operation finished.",apply_pending:""};return message[code]+(effect==="unapplied"?" No changes were saved.":effect==="applied"?" Your changes were saved.":"")}class DataOperationError extends Error{code;retryable;effect;component;detail;constructor(code,retryable=false,effect,component,detail){const parsed=detail===undefined?undefined:parseDataOperationDetail(detail);if(parsed&&("reason"in parsed?code!=="invalid_change":parsed.code==="record_limit_exceeded"&&code!=="capacity"))throw new Error("Invalid Data operation detail");super(parsed&&"code"in parsed&&parsed.code==="local_data_publication_failed"?dataPublicationFailureMessage(parsed):code==="capacity"&&parsed&&("code"in parsed)&&parsed.code==="record_limit_exceeded"?dataRecordLimitMessage(parsed):dataErrorMessage(code,effect));this.code=code;this.retryable=retryable;this.effect=effect;this.component=component;this.detail=detail;this.name="DataOperationError";if(parsed!==undefined)this.detail=parsed}}var invalid4=()=>{throw new DataOperationError("invalid_query")};var dataText=(value)=>typeof value==="string"&&!/[\u0000\uD800-\uDFFF]/u.test(value);var dataVersion=(value)=>dataText(value)&&value.length>0&&new TextEncoder().encode(value).length<=1024&&!/[\u0000-\u001f\u007f-\u009f]/.test(value)&&!/^[0-9a-f]{40}$/i.test(value);function dataProperties(value){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))return invalid4();const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(value).some((key)=>typeof key!=="string"||!descriptors[key]?.enumerable||!Object.hasOwn(descriptors[key],"value")))return invalid4();return descriptors}function dataArray(value){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)return invalid4();const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(value).length!==value.length+1)return invalid4();const result=[];for(let index=0;index<value.length;index++){const descriptor=descriptors[index];if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value"))return invalid4();result.push(descriptor.value)}return result}var invalid5=()=>{throw new DataOperationError("invalid_query")};function captureRecordsSearchInput(query,options){if(!dataText(query))return invalid5();const length=[...query.trim()].length;if(length<1||length>256)return invalid5();if(options===undefined)return{query};const descriptors=dataProperties(options);if(Object.keys(descriptors).some((key)=>!["collections","limit"].includes(key)))return invalid5();const captured={};if(Object.hasOwn(descriptors,"collections")){const supplied=descriptors.collections.value;if(!Array.isArray(supplied)||supplied.length<1||supplied.length>16||Reflect.ownKeys(supplied).length!==supplied.length+1)return invalid5();const collections=[];for(let index=0;index<supplied.length;index++){const descriptor=Object.getOwnPropertyDescriptor(supplied,String(index));if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value")||!dataText(descriptor.value))return invalid5();collections.push(descriptor.value)}if(new Set(collections).size!==collections.length)return invalid5();captured.collections=collections}if(Object.hasOwn(descriptors,"limit")){const supplied=descriptors.limit.value;if(!Number.isInteger(supplied)||supplied<1||supplied>100)return invalid5();captured.limit=supplied}return{query,options:captured}}function captureRecordsReadRefs(value){if(!Array.isArray(value)||value.length<1||value.length>100)throw new DataOperationError("invalid_query");const refs=dataArray(value);if(!refs.every((ref)=>validRecordRef(ref)&&!/[\r\n]/.test(ref))||new Set(refs).size!==refs.length)throw new DataOperationError("invalid_query");return refs}function captureRecordsReadOptions(value){if(value===undefined)return{};try{dataProperties(value)}catch{throw new DataOperationError("invalid_query")}if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value))||Reflect.ownKeys(value).some((key)=>key!=="body"&&key!=="timeline")||Object.values(value).some((option)=>option!==true))throw new DataOperationError("invalid_query");return{...Object.hasOwn(value,"body")?{body:true}:{},...Object.hasOwn(value,"timeline")?{timeline:true}:{}}}function capture3(value,ancestors=new Set,depth=0){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object"||ancestors.has(value)||depth>32)throw new DataOperationError("invalid_query");ancestors.add(value);try{if(Array.isArray(value))return dataArray(value).map((item)=>capture3(item,ancestors,depth+1));return Object.fromEntries(Object.entries(dataProperties(value)).map(([key,descriptor])=>[key,capture3(descriptor.value,ancestors,depth+1)]))}finally{ancestors.delete(value)}}function captureRecordsQuery(query){return capture3(query)}function captureRecordsAll(query,options){const invalid6=()=>{throw new DataOperationError("invalid_query")};try{const properties=dataProperties(options),maxRecords=properties.maxRecords?.value;if(Object.keys(properties).join(",")!=="maxRecords"||!Number.isSafeInteger(maxRecords)||maxRecords<1)return invalid6();const detached=capture3(query);const selections=dataProperties(detached);if(Object.keys(selections).length<1||Object.keys(selections).length>16)return invalid6();for(const selection2 of Object.values(selections)){const fields2=dataProperties(selection2.value);if(fields2.$&&Object.hasOwn(dataProperties(fields2.$.value),"after"))return invalid6()}return{query:detached,maxRecords}}catch{return invalid6()}}function validRecordBody(value){return typeof value==="string"&&value===new TextDecoder("utf-8",{ignoreBOM:true}).decode(new TextEncoder().encode(value))}var RECORD_BODY_READ_BYTES=8*1024*1024;var fail2=()=>{throw new DataOperationError("invalid_change",false,"unapplied")};function mapping(value){try{dataProperties(value);return value}catch{return fail2()}}var validSignalKey=(value)=>typeof value==="string"&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(value);var validSignalText=(value)=>typeof value==="string"&&!!value.trim()&&!/[\r\n\u0000\uD800-\uDFFF]/u.test(value);function validSignalInstant(value){if(typeof value!=="string")return false;const match=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?Z$/.exec(value);if(!match)return false;const normalized=`${match[1]}.${(match[2]??"").padEnd(3,"0").slice(0,3)}Z`;return Number.isFinite(Date.parse(normalized))&&new Date(normalized).toISOString()===normalized}var positive=(value)=>Number.isSafeInteger(value)&&Number(value)>0;function references(value,compact){if(value===undefined&&compact)return[];if(!Array.isArray(value))return fail2();let items;try{items=dataArray(value)}catch{return fail2()}return items.map((item)=>{const row=mapping(item),keys2=Object.keys(row).sort().join(",");if(compact){if(keys2==="record"&&validRecordRef(row.record))return{type:"record",ref:row.record};if(keys2==="ask"&&positive(row.ask))return{type:"ask",number:row.ask};if(keys2==="signal"){const signal=mapping(row.signal);if(Object.keys(signal).sort().join(",")==="number,record"&&validRecordRef(signal.record)&&positive(signal.number))return{type:"signal",record:signal.record,number:signal.number}}}else{if(keys2==="ref,type"&&row.type==="record"&&validRecordRef(row.ref))return{type:"record",ref:row.ref};if(keys2==="number,type"&&row.type==="ask"&&positive(row.number))return{type:"ask",number:row.number};if(keys2==="number,record,type"&&row.type==="signal"&&validRecordRef(row.record)&&positive(row.number))return{type:"signal",record:row.record,number:row.number}}return fail2()})}function captureSignal(value,acceptedAt){const row=mapping(value),compact=acceptedAt!==undefined;if(Object.keys(row).some((key)=>!["key","label","status","reason","related",...compact?[]:["asOf"]].includes(key))||!validSignalKey(row.key)||!validSignalText(row.label)||!validSignalText(row.status)||row.reason!==undefined&&(typeof row.reason!=="string"||/[\r\n\u0000\uD800-\uDFFF]/u.test(row.reason))||!validSignalInstant(acceptedAt??row.asOf))return fail2();return{key:row.key,label:row.label,status:row.status,...row.reason?{reason:row.reason}:{},related:references(row.related,compact),asOf:acceptedAt??row.asOf}}function captureTimeline(value,compact=false){const row=mapping(value);if(Object.keys(row).some((key)=>!["when","event","activity","related"].includes(key))||!validSignalInstant(row.when)||!validSignalText(row.activity)||row.event!==undefined&&!validSignalKey(row.event))return fail2();return{when:row.when,...row.event!==undefined?{event:row.event}:{},activity:row.activity,related:references(row.related,compact)}}function captureRecordSignal(value){const row=mapping(value),{number,...assessment}=row;if(!positive(number))return fail2();return{number,...captureSignal(assessment)}}function captureRecordSignals(value){if(!Array.isArray(value))return fail2();const rows=dataArray(value).map(captureRecordSignal);if(new Set(rows.map((row)=>row.key)).size!==rows.length||new Set(rows.map((row)=>row.number)).size!==rows.length)return fail2();return rows}var DATA_REQUEST_LIMIT=256*1024;var LOCAL_DATA_CHANGE_REQUEST_LIMIT=32*1024*1024;var invalidChange=()=>{throw new DataOperationError("invalid_change",false,"unapplied")};function mapping2(value){try{dataProperties(value);return value}catch{return invalidChange()}}function captureDataTables(value){const row=mapping2(value);const result={};if(Object.hasOwn(row,"signals")){if(!Array.isArray(row.signals)||!row.signals.length||row.signals.length>1e4)return invalidChange();try{result.signals=dataArray(row.signals).map((value2)=>captureSignal(value2))}catch{return invalidChange()}if(new Set(result.signals.map((value2)=>value2.key)).size!==result.signals.length)return invalidChange()}if(Object.hasOwn(row,"timeline")){if(!Array.isArray(row.timeline)||!row.timeline.length||row.timeline.length>1e4)return invalidChange();try{result.timeline=dataArray(row.timeline).map((value2)=>captureTimeline(value2))}catch{return invalidChange()}}return result}function captureDataChangeOptions(value){if(value===undefined)return{};const options=mapping2(value);if(Object.keys(options).some((key)=>!["summary","source"].includes(key)))return invalidChange();const line=(value2)=>{if(!dataText(value2)||!value2.trim().length||[...value2].length>120||/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value2))return invalidChange();return value2};const captured={};if(Object.hasOwn(options,"summary"))captured.summary=line(options.summary);if(Object.hasOwn(options,"source")){const source=mapping2(options.source);if(Object.keys(source).sort().join(",")!=="id,kind"||source.kind!=="app"&&source.kind!=="routine")return invalidChange();captured.source={kind:source.kind,id:line(source.id)}}return captured}function captureValue(value,ancestors=new Set,depth=0){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object"||ancestors.has(value)||depth>32)return invalidChange();ancestors.add(value);try{if(Array.isArray(value)){if(value.length>1e5||Object.keys(value).length!==value.length||Object.getOwnPropertySymbols(value).length)return invalidChange();return Array.from(value,(item)=>captureValue(item,ancestors,depth+1))}return Object.fromEntries(Object.entries(mapping2(value)).map(([key,item])=>{if(["__proto__","constructor","prototype"].includes(key))return invalidChange();return[key,captureValue(item,ancestors,depth+1)]}))}finally{ancestors.delete(value)}}function captureDataDelete(record2){const identity=mapping2(record2);if(!validRecordRef(identity.$ref)||typeof identity.$version!=="string"||!identity.$version.length||identity.$version.length>512)return invalidChange();return{ref:identity.$ref,expectedVersion:identity.$version}}function captureDataUpdate(record2,set){if(!validRecordRef(record2))return invalidChange();const input=mapping2(set);const{$body,...fields2}=input;const body=Object.hasOwn(input,"$body");if(body&&!validRecordBody($body)||!Object.keys(fields2).length&&!body||Object.keys(fields2).some((key)=>key.startsWith("$")||["id","type"].includes(key)))return invalidChange();return{ref:record2,set:captureValue(fields2),...body?{body:$body}:{}}}function captureIdentities(value,update,allowEmpty=true){if(!Array.isArray(value)||!allowEmpty&&!value.length||value.length>1e4)return invalidChange();const captured=value.map((item)=>{const row=mapping2(item);if(Object.keys(row).filter((key)=>!update||!["body","expectedVersion","signals","timeline"].includes(key)).sort().join(",")!==(update?"ref,set":"expectedVersion,ref"))return invalidChange();const identity={$ref:row.ref,$version:row.expectedVersion};if(update&&Object.keys(mapping2(row.set)).some((key)=>key.startsWith("$")))return invalidChange();if(!update)return captureDataDelete(identity);const tables=captureDataTables(row);const captured2=Object.keys(mapping2(row.set)).length||Object.hasOwn(row,"body")?captureDataUpdate(row.ref,{...mapping2(row.set),...Object.hasOwn(row,"body")?{$body:row.body}:{}}):validRecordRef(row.ref)&&Object.keys(tables).length?{ref:row.ref,set:{}}:invalidChange();return{...captured2,...tables,...Object.hasOwn(row,"expectedVersion")?{expectedVersion:captureDataDelete(identity).expectedVersion}:{}}});if(new Set(captured.map((item)=>item.ref)).size!==captured.length)return invalidChange();return captured}function captureDataUpdates(value,allowEmpty=false){return captureIdentities(value,true,allowEmpty)}function captureDataCreate(value){const row=mapping2(value);if(!validRecordRef(row.$ref)||Object.keys(row).some((key)=>key.startsWith("$")&&!["$ref","$filing","$body"].includes(key)))return invalidChange();const{$ref:ref,$filing,$body,...fields2}=row;const body=Object.hasOwn(row,"$body");if(body&&!validRecordBody($body))return invalidChange();let filing;if($filing!==undefined){const components=mapping2($filing);if(Object.entries(components).some(([name,value2])=>!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)||["constructor","prototype"].includes(name)||typeof value2!=="string"||!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value2)))return invalidChange();filing={...components}}return{ref,fields:captureValue(fields2),...filing?{filing}:{},...body?{body:$body}:{}}}function captureDataChanges(updatesValue,createsValue=[],deletesValue=[]){const updates=captureDataUpdates(updatesValue,true);if(!Array.isArray(createsValue)||createsValue.length>1e4)return invalidChange();const creates=createsValue.map((item)=>{const row=mapping2(item);if(Object.keys(row).some((key)=>!["ref","fields","filing","body","signals","timeline"].includes(key))||!Object.hasOwn(row,"ref")||!Object.hasOwn(row,"fields"))return invalidChange();const fields2=mapping2(row.fields);if(Object.keys(fields2).some((key)=>key.startsWith("$")))return invalidChange();return{...captureDataCreate({...fields2,$ref:row.ref,...Object.hasOwn(row,"filing")?{$filing:row.filing}:{},...Object.hasOwn(row,"body")?{$body:row.body}:{}}),...captureDataTables(row)}});const deletes=captureIdentities(deletesValue,false);const refs=[...updates,...creates,...deletes].map((item)=>item.ref);if(!refs.length||refs.length>1e4||new Set(refs).size!==refs.length)return invalidChange();return{updates,creates,deletes}}function checkDataRequestSize(input,limit=DATA_REQUEST_LIMIT){if(new TextEncoder().encode(JSON.stringify(input)).byteLength>limit)throw new DataOperationError("request_too_large",false,"unapplied")}function dataTransportError(status,value){const failures={400:["invalid_query","invalid_change"],401:["unauthenticated"],403:["access_denied"],409:["conflict","apply_pending"],413:["request_too_large"],429:["capacity"],503:["unavailable","apply_pending"]};const error=value&&typeof value==="object"&&"error"in value?value.error:undefined;const row=error&&typeof error==="object"?error:undefined;const code=failures[status]?.find((allowed)=>allowed===row?.code)??"unavailable";const effect=["unapplied","uncertain","applied"].includes(String(row?.effect))?row.effect:undefined;let detail;try{detail=row?.detail===undefined?undefined:parseDataOperationDetail(row.detail)}catch{}if(detail&&"reason"in detail&&code!=="invalid_change")detail=undefined;return explainDataValidation(new DataOperationError(code,typeof row?.retryable==="boolean"?row.retryable:["capacity","unavailable","apply_pending"].includes(code),code==="conflict"?"unapplied":effect,code==="invalid_change"&&typeof row?.component==="string"&&/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(row.component)?row.component:undefined,detail),row?.message,row?.detail)}var AUTH_ORIGIN="https://auth.oddington.ai";function oddingtonOrigin(environment=process.env){const value=environment.OS_ORIGIN??AUTH_ORIGIN;const url=new URL(value);if(url.protocol!=="https:"&&url.hostname!=="127.0.0.1")throw new Error("OS_ORIGIN must use HTTPS");return url.origin}var nodeRequest;var nodeReadable;if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){({request:nodeRequest}=await import("node:http"));({Readable:nodeReadable}=await import("node:stream"))}function privateRoutineRequest(environment=typeof __OS_BROWSER__!=="undefined"&&__OS_BROWSER__?{}:typeof process==="undefined"?{}:process.env){if(typeof __OS_BROWSER__!=="undefined"&&__OS_BROWSER__)return;const prepared=["OS_ROUTINE_LOCAL","OS_ROUTINE_LOCAL_SOCKET","OS_ROUTINE_LOCAL_TOKEN"].some((key)=>environment[key]!==undefined);const managed=["OS_FILES_SOCKET","OS_FILES_TOKEN"].some((key)=>environment[key]!==undefined);if(!prepared&&!managed)return;const socket=prepared?environment.OS_ROUTINE_LOCAL_SOCKET:environment.OS_FILES_SOCKET;const token=prepared?environment.OS_ROUTINE_LOCAL_TOKEN:environment.OS_FILES_TOKEN;const request=localRoutineRequest(prepared?environment:{OS_ROUTINE_LOCAL:"1",OS_ROUTINE_LOCAL_SOCKET:socket,OS_ROUTINE_LOCAL_TOKEN:token});const isCurrent=()=>prepared?environment.OS_ROUTINE_LOCAL==="1"&&environment.OS_ROUTINE_LOCAL_SOCKET===socket&&environment.OS_ROUTINE_LOCAL_TOKEN===token:environment.OS_FILES_SOCKET===socket&&environment.OS_FILES_TOKEN===token;if(!nodeRequest||!nodeReadable)throw new Error("Files transport unavailable");const httpRequest=nodeRequest,Readable=nodeReadable;const files=async(suffix,init,signal)=>{if(!isCurrent())throw new FileOperationError("unsupported_context",400);const tcp=/^tcp:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(socket);const endpoint=tcp?{hostname:"127.0.0.1",port:Number(tcp[1])}:{socketPath:socket};const id2=crypto.randomUUID();if(init.body instanceof ReadableStream||suffix===""&&init.method==="POST"){await new Promise((resolve,reject)=>{const check=httpRequest({...endpoint,path:"/files/check-create",method:"POST",timeout:30000,signal,agent:false,headers:{...Object.fromEntries(new Headers(init.headers)),authorization:`Bearer ${token}`,"x-os-files-suffix":encodeURIComponent(suffix),"x-os-files-method":init.method??"GET"}},(response)=>{const bytes=Buffer.alloc(16384);let size=0;response.on("data",(chunk)=>{size+=chunk.length;if(size>16384)response.destroy(new Error("File operation start response exceeded 16 KiB."));else bytes.set(chunk,size-chunk.length)});response.once("error",reject);response.once("end",()=>{if(response.statusCode===204){resolve();return}try{const value=JSON.parse(bytes.subarray(0,size).toString());const code=value?.error?.code;const status=response.statusCode??503;if(["invalid_input","request_too_large","unsupported_context","access_denied","capacity","unavailable"].includes(code))reject(new FileOperationError(code,status,code==="capacity"||code==="unavailable",parseFileErrorDetail(value?.error?.detail)));else reject(new FileOperationError("unavailable",503,true))}catch{reject(new FileOperationError("unavailable",503,true))}})});check.once("error",()=>reject(new FileOperationError("unavailable",503,true)));check.once("timeout",()=>check.destroy(new Error("The file create check did not finish in time.")));check.end()});if(!isCurrent())throw new FileOperationError("unsupported_context",400)}let cancellation;const cancelCall=()=>cancellation??=new Promise((resolve,reject)=>{const cancel=httpRequest({...endpoint,path:"/files/cancel",method:"POST",timeout:30000,headers:{authorization:`Bearer ${token}`,"x-os-files-call":id2}},(response)=>{response.resume();response.once("end",resolve);response.once("error",reject)});cancel.once("error",reject);cancel.once("timeout",()=>cancel.destroy(new Error("Files cancellation stalled")));cancel.end()});let pumping=Promise.resolve();let sourceReader;const result=new Promise((resolve,reject)=>{const call=httpRequest({...endpoint,path:"/files/stream",method:"POST",headers:{...Object.fromEntries(new Headers(init.headers)),authorization:`Bearer ${token}`,"x-os-files-call":id2,"x-os-files-suffix":encodeURIComponent(suffix),"x-os-files-method":init.method??"GET"},signal,timeout:30000,agent:false},async(response)=>{try{call.setTimeout(0);if((response.statusCode??503)>=400){await sourceReader?.cancel().catch(()=>{});call.end()}await pumping;if(!isCurrent()){response.destroy();reject(new FileOperationError("unsupported_context",400));return}const headers=new Headers;for(const[key,value]of Object.entries(response.headers))if(value!==undefined)headers.set(key,Array.isArray(value)?value.join(", "):value);const source=Readable.toWeb(response,{strategy:{highWaterMark:65536,size:(chunk)=>chunk.byteLength}});const reader=source.getReader();if(response.statusCode===204){const timer=setTimeout(()=>response.destroy(new Error("Files completion stalled")),30000);try{if(!(await reader.read()).done)throw new FileOperationError("unavailable",503,true);if(!isCurrent())throw new FileOperationError("unsupported_context",400);resolve(new Response(null,{status:204,headers}))}finally{clearTimeout(timer);reader.releaseLock()}return}let closed=false;const body=new ReadableStream({async pull(controller){let timer;try{if(!isCurrent())throw new FileOperationError("unsupported_context",400);timer=setTimeout(()=>response.destroy(new Error("Files delivery stalled")),30000);const next=await reader.read();if(closed)return;if(next.done){closed=true;reader.releaseLock();controller.close()}else controller.enqueue(next.value)}catch(error){closed=true;controller.error(error);await cancelCall().catch(()=>{});response.socket?.destroy();response.destroy();await reader.cancel(error).catch(()=>{});reader.releaseLock()}finally{clearTimeout(timer)}},async cancel(reason){closed=true;await cancelCall().catch(()=>{});response.socket?.destroy();response.destroy();call.destroy();await reader.cancel(reason).catch(()=>{});reader.releaseLock()}},{highWaterMark:0});resolve(new Response(body,{status:response.statusCode??503,headers}))}catch(error){response.destroy();reject(error instanceof FileOperationError?error:new FileOperationError("unavailable",503,true))}});call.on("error",(error)=>{cancelCall().catch(()=>{});reject(error instanceof FileOperationError?error:new FileOperationError("unavailable",503,true))});call.on("timeout",()=>call.destroy(new Error("Files I/O stalled")));call.on("information",()=>call.setTimeout(30000));if(init.body instanceof ReadableStream){call.flushHeaders();const reader=sourceReader=init.body.getReader();const abort=()=>{reader.cancel(signal.reason).catch(()=>{})};signal.addEventListener("abort",abort,{once:true});call.once("close",abort);pumping=(async()=>{try{for(;;){const next=await reader.read();if(next.done)break;if(!(next.value instanceof Uint8Array))throw new FileOperationError("invalid_input",400);if(!isCurrent())throw new FileOperationError("unsupported_context",400);for(let offset=0;offset<next.value.byteLength;offset+=262144){if(call.destroyed)throw new Error("Files parent disconnected");await new Promise((done,fail3)=>{const closed=()=>fail3(new Error("Files parent disconnected"));call.once("close",closed);call.write(next.value.subarray(offset,offset+262144),(error)=>{call.removeListener("close",closed);error?fail3(error):done()})})}}call.end()}catch(error){call.destroy(error instanceof Error?error:new Error("Files transport failed"))}finally{await reader.cancel().catch(()=>{});signal.removeEventListener("abort",abort);call.removeListener("close",abort);reader.releaseLock()}})()}else call.end(init.body===undefined?undefined:Buffer.from(init.body))});try{return await result}finally{await pumping}};return{request,files,isCurrent,identity:`private:${socket}`}}function localRoutineRequest(environment=typeof __OS_BROWSER__!=="undefined"&&__OS_BROWSER__?{}:typeof process==="undefined"?{}:process.env){if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){const{OS_ROUTINE_LOCAL:mode,OS_ROUTINE_LOCAL_SOCKET:socket,OS_ROUTINE_LOCAL_TOKEN:token}=environment;if(mode===undefined&&socket===undefined&&token===undefined)return;if(mode!=="1"||!socket||!token||!/^[0-9a-f]{64}$/.test(token))throw new Error("Preparation transport unavailable; nothing can publish");const tcp=/^tcp:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(socket);const endpoint=tcp&&tcp[0]===socket&&Number(tcp[1])<=65535?{hostname:"127.0.0.1",port:Number(tcp[1])}:socket.startsWith("/")&&!socket.startsWith("//")&&!socket.includes("\x00")?{socketPath:socket}:undefined;if(!endpoint)throw new Error("Preparation transport unavailable; nothing can publish");return async(operation,input)=>{const{request}=await import("node:http");return await new Promise((resolve,reject)=>{const call=request({...endpoint,path:`/${operation}`,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${token}`},timeout:operation==="ai/generate"?125000:120000},(response)=>{const limit=operation==="ai/generate"?ROUTINE_AI_RESULT_BYTES:33554432;const bytes=Buffer.alloc(limit);let size=0;response.on("data",(chunk)=>{size+=chunk.length;if(size>limit){response.destroy();reject(operation==="ai/generate"?new AIError("output_too_large"):new Error("Local result exceeds supported size"))}else bytes.set(chunk,size-chunk.length)});response.on("error",(error)=>reject(operation==="ai/generate"?new AIError("capability_unavailable"):error));response.on("end",()=>{try{const result=JSON.parse(bytes.subarray(0,size).toString());if(response.statusCode!==200){if(operation==="ai/generate")throw parseRoutineAIError(result.error);if(operation==="files/request"){const error=result.error;const status=response.statusCode??503;const codes=["invalid_input","unsupported_context","unauthenticated","access_denied","not_found","request_too_large","conflict","local_only","integrity","unavailable","capacity","method_not_allowed"];if(error?.code&&codes.includes(error.code))throw new FileOperationError(error.code,status,error.code==="capacity"||error.code==="unavailable",parseFileErrorDetail(error.detail));throw new FileOperationError("unavailable",503,true)}if(operation==="data/query"){throw dataTransportError(response.statusCode??0,result)}throw new Error(typeof result.error==="string"?result.error:"Preparation failed")}resolve(result)}catch(error){reject(operation==="ai/generate"&&!(error instanceof AIError)?new AIError("invalid_output"):error)}})});call.on("error",()=>reject(operation==="ai/generate"?new AIError("capability_unavailable"):operation==="data/query"?dataTransportError(503,{error:{code:"unavailable"}}):new Error("Preparation transport unavailable; nothing was published")));call.on("timeout",()=>call.destroy(new Error("Preparation timed out")));call.end(JSON.stringify(input))})}}}var installed;var ended=false;function routineTransport(){if(ended||installed&&!installed.isCurrent())throw new Error("Routine authority ended");return installed}var memberContext;var memberLifetime;var retainedContext;function installMemberContext(resolve,retained=resolve){memberLifetime?.abort();memberLifetime=new AbortController;memberContext=resolve;retainedContext=retained;return()=>{if(memberContext===resolve){memberLifetime?.abort();memberContext=undefined;retainedContext=undefined}}}async function resolveAppContext(retained=false){const host=memberContext;if(!host)throw new Error("App context unavailable.");const context=await(retained?retainedContext:host)();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now()||context.kind!=="local"&&(typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))){throw new Error("App context unavailable.")}return context}async function resolveSnapshotContext(){try{if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__)throw new Error;const context=await resolveAppContext();if(context.kind==="local"||!context.memberId||!context.binding||context.endpoint!==globalThis.location.origin||context.endpoint!==`https://${context.workspace}.oddington.ai`)throw new Error;const host=memberContext;const retained=context.snapshot;const isCurrent=()=>host===memberContext&&(retained?retained.isCurrent():context.isCurrent()&&context.expiresAt>Date.now());return{workspace:context.workspace,endpoint:context.endpoint,memberId:context.memberId,binding:context.binding,get expiresAt(){return retained?.credentials().expiresAt??context.expiresAt},get headers(){return{authorization:`Bearer ${retained?.credentials().accessToken??context.accessToken}`}},signal:context.signal?AbortSignal.any([context.signal,memberLifetime.signal]):memberLifetime.signal,isCurrent,...retained?{subscribe:retained.subscribe,async refresh(){try{const next=await resolveAppContext();if(!isCurrent()||next.kind==="local"||next.binding!==context.binding||next.memberId!==context.memberId||next.workspace!==context.workspace||next.endpoint!==context.endpoint)throw new Error}catch{throw new DataOperationError(isCurrent()?"unavailable":"context_unavailable",isCurrent())}}}:{}}}catch{throw new DataOperationError("context_unavailable")}}async function resolveDataContext(){try{if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){const installed2=routineTransport();if(installed2)return{local:installed2.request};const local=localRoutineRequest();if(local)return{local};const managed=privateRoutineRequest();if(managed)return{local:managed.request}}const host=memberContext;if(host!==undefined){const context=await host();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now())throw new Error;if(context.kind==="local")return{local:context.requestData};if(!context||!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now()||typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))throw new Error;return checked(context.workspace,context.endpoint,{authorization:`Bearer ${context.accessToken}`})}if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){const environment=typeof process==="undefined"?undefined:process.env;if(!environment||!/^[0-9a-f]{64}$/.test(environment.OS_ROUTINE_RUN??""))throw new Error;return checked(environment.OS_ROUTINE_WORKSPACE,oddingtonOrigin(environment),{"x-os-run":environment.OS_ROUTINE_RUN})}throw new Error}catch{throw new DataOperationError("context_unavailable")}}async function resolveFilesContext(){try{const environment=typeof __OS_BROWSER__!=="undefined"&&__OS_BROWSER__?{}:typeof process==="undefined"?{}:process.env;if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){const installed2=routineTransport();if(installed2)return{url:"private:installed",headers:{},isCurrent:installed2.isCurrent,local:installed2.request,localFiles:installed2.files,signal:undefined};const local=privateRoutineRequest(environment);if(local)return{url:local.identity,headers:{},isCurrent:local.isCurrent,local:local.request,localFiles:local.files,signal:undefined}}const host=memberContext;if(host){const context=await host();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now())throw new Error;if(context.kind==="local")return{url:`private:app:${context.workspace}/${context.memberId}`,headers:{},isCurrent:context.isCurrent,signal:context.signal,local:undefined,localFiles:context.requestFiles};if(!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now()||typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))throw new Error;return{...filesContext(context.workspace,context.endpoint,{authorization:`Bearer ${context.accessToken}`}),isCurrent:context.isCurrent,local:undefined,localFiles:undefined,signal:undefined}}if(typeof __OS_BROWSER__==="undefined"||!__OS_BROWSER__){if(!/^[0-9a-f]{64}$/.test(environment.OS_ROUTINE_RUN??""))throw new Error;const workspace=environment.OS_ROUTINE_WORKSPACE;return{...filesContext(workspace,`https://${workspace}.oddington.ai`,{"x-os-run":environment.OS_ROUTINE_RUN}),local:undefined,localFiles:undefined,signal:undefined}}throw new Error}catch{throw new FileOperationError("unsupported_context",400)}}function filesContext(workspace,endpoint,headers){if(!workspace||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(workspace)||workspace.length>63||["auth","www","api","os"].includes(workspace)||endpoint!==`https://${workspace}.oddington.ai`)throw new Error;return{url:`${endpoint}/api/files`,headers:{...headers,"x-os-workspace":workspace},isCurrent:()=>true}}function checked(workspace,endpoint,headers){if(!workspace||!/^[a-z0-9][a-z0-9-]{0,127}$/.test(workspace))throw new Error;const origin=new URL(endpoint);if(origin.protocol!=="https:"||origin.username||origin.password||origin.search||origin.hash||origin.pathname!=="/")throw new Error;return{url:`${origin.origin}/api/data`,headers:{...headers,"x-os-workspace":workspace}}}var invalid6=()=>{throw new DataOperationError("invalid_query")};var unavailable=()=>{throw new DataOperationError("unavailable")};var text2=(value)=>typeof value==="string"&&value.length>0;function capture4(value,ancestors=new Set,depth=0){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object"||ancestors.has(value)||depth>32)return invalid6();ancestors.add(value);try{if(Array.isArray(value))return dataArray(value).map((item)=>capture4(item,ancestors,depth+1));return Object.fromEntries(Object.entries(dataProperties(value)).map(([key,descriptor])=>[key,capture4(descriptor.value,ancestors,depth+1)]))}finally{ancestors.delete(value)}}function recordPagination(queryRecords){function pages(query){const captured=capture4(query);const names=Object.keys(dataProperties(captured));for(const name of names){const selection2=dataProperties(captured[name]);if(Object.hasOwn(selection2,"$")){const options=dataProperties(selection2.$.value);if(Object.hasOwn(options,"after"))return invalid6()}}return iterate();async function*iterate(){const state=new Map(names.map((name)=>[name,{seen:new Set,count:undefined,next:undefined}]));let active=names,version;do{const request=Object.fromEntries(active.map((name)=>{const selection2=captured[name];const next=state.get(name).next;return[name,next===undefined?selection2:{...selection2,$:{...selection2.$,after:next}}]}));const response=await queryRecords(request);let page;try{page=capture4(response);const keys2=Object.keys(dataProperties(page));if(keys2.length!==active.length+1||keys2.some((key)=>key!=="$meta"&&!active.includes(key)))unavailable();const meta=page.$meta;if(Object.keys(dataProperties(meta)).sort().join(",")!=="collections,version"||!text2(meta.version))unavailable();version=meta.version;const collectionKeys=Object.keys(dataProperties(meta.collections));if(collectionKeys.some((key)=>!active.includes(key)))unavailable();for(const name of active){const records=dataArray(page[name]);const metadata=Object.hasOwn(meta.collections,name)?meta.collections[name]:{};if(Object.keys(dataProperties(metadata)).some((key)=>key!=="count"&&key!=="next")||Object.hasOwn(metadata,"next")&&!text2(metadata.next))unavailable();for(const record2 of records){dataProperties(record2);const row=record2;if(!validRecordRef(row.$ref)||!text2(row.$version))unavailable()}const current=state.get(name);if(captured[name].$?.count===true){if(!Number.isSafeInteger(metadata.count)||metadata.count<0)unavailable();current.count=metadata.count}else if(Object.hasOwn(metadata,"count"))unavailable();if(metadata.next!==undefined){if(current.seen.has(metadata.next))unavailable();current.seen.add(metadata.next)}current.next=metadata.next}}catch{return unavailable()}const collections=Object.fromEntries(names.map((name)=>{const current=state.get(name);return[name,{...current.count===undefined?{}:{count:current.count},...current.next===undefined?{}:{next:current.next}}]}));const output=Object.fromEntries(names.map((name)=>[name,active.includes(name)?page[name]:[]]));active=active.filter((name)=>state.get(name).next!==undefined);yield{...output,$meta:{version,collections}}}while(active.length)}}return{pages}}var FRAGMENT=/^(?:[a-zA-Z0-9._~!$&'()*+,;=:@/?-]|%[0-9a-fA-F]{2})+(?![\s\S])/;function parseRecordLink(value){if(typeof value!=="string")return;const separator=value.indexOf("#");const ref=separator<0?value:value.slice(0,separator);if(!validRecordRef(ref))return;if(separator<0)return{ref};const fragment=value.slice(separator+1);return FRAGMENT.test(fragment)?{ref,fragment}:undefined}function parseStoredRecordLink(value){return typeof value==="string"&&value.startsWith("[[")&&value.endsWith("]]")?parseRecordLink(value.slice(2,-2)):undefined}class RecordValidationError extends Error{path;constructor(message,path){super(message);this.path=path;this.name="RecordValidationError"}}class RecordFieldValidationError extends RecordValidationError{problem;field;expected;detail;constructor(problem,field,expected){super(`${problem} record field: ${field}`);this.problem=problem;this.field=field;this.expected=expected}atRecord(ref,schemaPath,fileSource=false){const problem=fileSource&&this.problem==="unknown"&&this.field==="media_type"?"source_schema":this.problem;this.message=recordFieldMessage(ref,this.field,problem,schemaPath,this.expected)??recordFieldMessage(ref,this.field,this.problem)??this.message;this.detail=recordFieldDetail(ref,this.field,problem,schemaPath,this.expected)??recordFieldDetail(ref,this.field,this.problem,undefined,this.expected);Object.assign(this,dataValidationMessageFacts({code:"invalid_change",message:this.message,detail:this.detail}));return this}}function fieldExpectation(field){return{type:field.kind,many:field.many,nullable:field.nullable,...field.kind==="number"&&field.precision!==undefined?{decimalPlaces:field.precision}:{},...field.kind==="date"&&field.format?{format:field.format}:{}}}var NAME=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fail3(message){throw new RecordValidationError(message)}function validateRecordText(value){if(/[\u0000\uD800-\uDFFF]/u.test(value))fail3("Record text must contain Unicode scalar values excluding U+0000")}function object3(value){if(!value||typeof value!=="object"||Array.isArray(value))fail3("Expected a field mapping");return value}function keys2(row,allowed,required){if(Object.keys(row).some((key)=>!allowed.includes(key))||required.some((key)=>!Object.hasOwn(row,key)))fail3("Unsupported or missing schema/record fields")}function valueDefinition(value,depth,native,named=false){if(depth>8)fail3("Invalid field definitions");const row={...object3(value)};const legacyMany=["enum_list","links","list"].includes(String(row.kind));if(legacyMany&&row.many!==undefined&&row.many!==true)fail3("Conflicting cardinality");if(Object.hasOwn(row,"inline")){if(row.kind!=="list"||typeof row.inline!=="boolean"||Object.hasOwn(row,"style"))fail3("Unsupported or conflicting inline style");if(row.inline)row.style="inline";delete row.inline}switch(row.kind){case"bool":row.kind="boolean";break;case"constant":row.kind="const";break;case"enum_list":row.kind="enum";row.many=true;break;case"links":row.kind="link";row.many=true;break;case"month":if(row.format!==undefined&&row.format!=="month")fail3("Conflicting date format");row.kind="date";row.format="month";break;case"list":{if(Object.hasOwn(row,"items")&&Object.hasOwn(row,"fields"))fail3("Conflicting list definitions");const nested=Object.hasOwn(row,"items")?row.items:row.fields;row.kind=nested===undefined?"string":"object";row.many=true;if(Object.hasOwn(row,"items"))delete row.items;if(nested!==undefined)row.fields=nested;break}case"map":if(Object.hasOwn(row,"keys")||Object.hasOwn(row,"values")){if(Object.hasOwn(row,"key")||Object.hasOwn(row,"value")||row.keys!=="YYYY-MM"||row.values!=="number")fail3("Unsupported or conflicting map definitions");row.key={kind:"date",format:"month"};row.value={kind:"number",...Object.hasOwn(row,"precision")?{precision:row.precision}:{}};delete row.keys;delete row.values;delete row.precision}break}if(row.nullable!==undefined&&typeof row.nullable!=="boolean")fail3("Invalid nullability");if(row.many!==undefined&&typeof row.many!=="boolean")fail3("Invalid cardinality");if(["description","term"].some((key)=>row[key]!==undefined&&typeof row[key]!=="string"))fail3("Invalid field documentation");const base={nullable:row.nullable===true,many:row.many===true,...native&&row.nullable===true?{optional:true}:{},...typeof row.description==="string"?{description:row.description}:{},...typeof row.term==="string"?{term:row.term}:{},...row.style==="inline"?{style:"inline"}:{}};if(row.style!==undefined&&(row.style!=="inline"||!base.many))fail3("Unsupported storage style");const common=["kind","nullable","many","style","description","term",...named?["name"]:[]];const check=(owned=[])=>keys2(row,[...common,...owned],["kind",...owned]);switch(row.kind){case"string":case"integer":case"boolean":case"datetime":check();return{...base,kind:row.kind};case"number":keys2(row,[...common,"precision"],["kind"]);if(row.precision!==undefined&&(!Number.isInteger(row.precision)||Number(row.precision)<0||Number(row.precision)>6))fail3("Unsupported decimal precision");return{...base,kind:"number",...row.precision!==undefined?{precision:row.precision}:{}};case"date":keys2(row,[...common,"format"],["kind"]);if(row.format!==undefined&&row.format!=="month")fail3("Unsupported date format");return{...base,kind:"date",...row.format==="month"?{format:"month"}:{}};case"const":check(["value"]);if(base.many||!["string","number","boolean"].includes(typeof row.value)||typeof row.value==="number"&&!Number.isFinite(row.value))fail3("Invalid constant");return{...base,kind:"const",value:row.value};case"enum":case"link":{const property=row.kind==="enum"?"values":"to";check([property]);const list2=row.kind==="link"&&typeof row.to==="string"?[row.to]:row[property];if(!Array.isArray(list2)||!list2.length||list2.length>1e5||new Set(list2).size!==list2.length||list2.some((item)=>typeof item!=="string"||!item||row.kind==="link"&&!NAME.test(item)))fail3("Invalid enum/link definition");return row.kind==="enum"?{...base,kind:"enum",values:list2}:{...base,kind:"link",to:list2}}case"object":check(["fields"]);return{...base,kind:"object",fields:fields2(row.fields,depth+1,native)};case"map":{check(["key","value"]);const key=valueDefinition(row.key,depth+1,native),value2=valueDefinition(row.value,depth+1,native);if(!["string","integer","date","enum"].includes(key.kind)||key.nullable||key.many)fail3("Unsupported map key definition");return{...base,kind:"map",key,value:value2}}default:return fail3("Unsupported field kind")}}function fields2(value,depth=0,native=false){if(depth>8||!Array.isArray(value)||!value.length||value.length>256)fail3("Invalid field definitions");const names=new Set;return value.map((definition)=>{const row=object3(definition);if(typeof row.name!=="string"||!NAME.test(row.name)||["constructor","prototype"].includes(row.name)||names.has(row.name))fail3("Invalid or duplicate field name");names.add(row.name);return{name:row.name,...valueDefinition(row,depth,native,true)}})}function validateRecordFields(value,definitions2,resolveLink,canonical=false){const row=object3(value);for(const[key,entry]of Object.entries(row)){validateRecordText(key);if(typeof entry==="string")validateRecordText(entry)}for(const name of Object.keys(row))if(!definitions2.some((field)=>field.name===name))throw new RecordFieldValidationError("unknown",name);for(const field of definitions2)if(!field.optional&&!Object.hasOwn(row,field.name))throw new RecordFieldValidationError("missing",field.name,fieldExpectation(field));for(const field of definitions2){const value2=row[field.name];if(!Object.hasOwn(row,field.name)&&field.optional)continue;if(value2===null&&field.nullable)continue;if(field.many){if(!Array.isArray(value2)||value2.length>1e5||["enum","link"].includes(field.kind)&&new Set(value2).size!==value2.length)throw new RecordFieldValidationError("invalid",field.name,fieldExpectation(field));try{for(const entry of value2)validateRecordFields({[field.name]:entry},[{...field,many:false,nullable:false}],resolveLink,canonical)}catch(error){if(error instanceof RecordFieldValidationError&&error.field===field.name)error.expected=fieldExpectation(field);throw error}continue}let valid=false;switch(field.kind){case"const":valid=value2===field.value;break;case"string":valid=typeof value2==="string";break;case"integer":valid=Number.isSafeInteger(value2);break;case"number":{valid=typeof value2==="number"&&Number.isFinite(value2);if(valid&&field.precision!==undefined){const scaled=value2*10**field.precision;valid=Number.isSafeInteger(Math.round(scaled))&&Math.abs(scaled-Math.round(scaled))<=Math.min(0.0000001,Number.EPSILON*Math.max(1,Math.abs(scaled))*4)}break}case"boolean":valid=typeof value2==="boolean";break;case"datetime":valid=typeof value2==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value2)&&Number.isFinite(Date.parse(value2))&&new Date(value2).toISOString()===value2;break;case"date":{const day=typeof value2==="string"&&field.format==="month"?`${value2}-01`:value2;valid=typeof value2==="string"&&(field.format==="month"?/^\d{4}-\d{2}$/.test(value2):/^\d{4}-\d{2}-\d{2}$/.test(value2))&&typeof day==="string"&&Number.isFinite(Date.parse(day))&&new Date(day).toISOString().slice(0,10)===day;break}case"enum":valid=typeof value2==="string"&&field.values.includes(value2);break;case"link":{const link=(canonical?parseRecordLink:parseStoredRecordLink)(value2);valid=!!link&&(!resolveLink||field.to.includes(resolveLink(link.ref,field.to)??""));break}case"object":if(!value2||typeof value2!=="object"||Array.isArray(value2))break;validateRecordFields(value2,field.fields,resolveLink,canonical);valid=true;break;case"map":{if(!value2||typeof value2!=="object"||Array.isArray(value2))break;const entries=Object.entries(value2);if(entries.length>1e5)fail3("Record map is too large");for(const[key,entry]of entries){if(["<<","__proto__","constructor","prototype"].includes(key))fail3("Unsupported record map key");const keyValue=field.key.kind==="integer"?Number(key):key;if(field.key.kind==="integer"&&String(keyValue)!==key)fail3("Invalid integer map key");validateRecordFields({key:keyValue},[{...field.key,name:"key"}],resolveLink,canonical);validateRecordFields({value:entry},[{...field.value,name:"value"}],resolveLink,canonical)}valid=true;break}}if(!valid)throw new RecordFieldValidationError("invalid",field.name,fieldExpectation(field))}}var boundOperators=["$gt","$gte","$lt","$lte"];var compare=(a,b)=>a<b?-1:a>b?1:0;var fail4=(message)=>{throw new RecordValidationError(`Invalid Records query: ${message}`)};function mapping3(value){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))return fail4("expected a mapping");return value}function publicDefinition(field){const{optional:_optional,style:_style,...definition}=field;if(definition.kind==="object")return{...definition,fields:definition.fields.map(publicField)};if(definition.kind==="map")return{...definition,key:publicDefinition(definition.key),value:publicDefinition(definition.value)};return structuredClone(definition)}function publicField(field){return{...publicDefinition(field),name:field.name}}function scalarField(name,schema2){if(name==="$ref")return{name,kind:"string",nullable:false,many:false};const field=schema2.fields.find((field2)=>field2.name===name);if(!field||field.many||field.kind==="object"||field.kind==="map")return fail4(`ineligible scalar field: ${name}`);return field}function conditionValue(value,field){if(field.kind==="link"||field.name==="$ref"){if(value!==null&&!(field.kind==="link"?parseRecordLink(value):validRecordRef(value)))return fail4(`invalid reference: ${field.name}`)}validateRecordFields({[field.name]:field.kind==="link"&&typeof value==="string"?`[[${value}]]`:value},[{...field,optional:false}]);return value}function queryEntries(query){const entries=Object.entries(mapping3(query));preflightSelections(entries);return entries}function preflightSelections(entries){if(entries.length<1||entries.length>16)return fail4("expected 1–16 collections");let nodes=0;const visit=(value,depth)=>{if(++nodes>256)return fail4("too many selection nodes");const selection2=mapping3(value);for(const[name,nested]of Object.entries(selection2)){if(name==="$")continue;if(depth>=4)return fail4("too many link levels");visit(nested,depth+1)}};for(const[,value]of entries)visit(value,0)}function selectionTree(value,schema2,collectionsByType,depth=0,many=false){const selection2=mapping3(value);const options=Object.hasOwn(selection2,"$")?mapping3(selection2.$):{};const allowed=depth===0?["where","fields","order","limit","count","after"]:many?["where","fields","order","limit"]:["where","fields"];allowed.push("timeline");if(Object.keys(options).some((key)=>!allowed.includes(key)))return fail4("unsupported option");const fields3=Object.hasOwn(options,"fields")?options.fields:schema2.fields.map((field)=>field.name);if(!Array.isArray(fields3)||fields3.some((name)=>typeof name!=="string"||!["$ref","$version"].includes(name)&&!schema2.fields.some((field)=>field.name===name))||new Set(fields3).size!==fields3.length)return fail4("invalid projection");const conditions=[];const signalConditions=[];if(Object.hasOwn(options,"timeline")&&options.timeline!==true)return fail4("invalid timeline option");if(Object.hasOwn(options,"where"))for(const[name,condition]of Object.entries(mapping3(options.where))){if(name==="$signals"){for(const[key,signalCondition]of Object.entries(mapping3(condition))){if(!validSignalKey(key))return fail4("invalid Signal key");if(typeof signalCondition==="string"){if(!validSignalText(signalCondition))return fail4("invalid Signal status");signalConditions.push([key,[signalCondition]])}else{const expression=mapping3(signalCondition);if(Object.keys(expression).length!==1)return fail4("invalid Signal condition");if(Object.hasOwn(expression,"$exists")&&expression.$exists===false)signalConditions.push([key,false]);else if(Object.hasOwn(expression,"$in")&&Array.isArray(expression.$in)&&expression.$in.length>=1&&expression.$in.length<=100&&expression.$in.every(validSignalText)&&new Set(expression.$in).size===expression.$in.length)signalConditions.push([key,[...expression.$in]]);else return fail4("invalid Signal condition")}}continue}const field=scalarField(name,schema2);let values=[condition];if(condition!==null&&typeof condition==="object"){const expression=mapping3(condition);if(!Object.hasOwn(expression,"$in")){const keys3=Object.keys(expression);if(keys3.length===0||keys3.some((key)=>!boundOperators.includes(key))||Object.hasOwn(expression,"$gt")&&Object.hasOwn(expression,"$gte")||Object.hasOwn(expression,"$lt")&&Object.hasOwn(expression,"$lte"))return fail4("invalid bounds");if(field.name==="$ref"||!["integer","number","date","datetime"].includes(field.kind))return fail4(`ineligible range field: ${name}`);const bounds=boundOperators.filter((operator)=>Object.hasOwn(expression,operator)).map((operator)=>{const value2=expression[operator];if(value2===null)return fail4("null bound");return[operator,conditionValue(value2,field)]});conditions.push([name,{bounds}]);continue}if(Object.keys(expression).length!==1||!Object.hasOwn(expression,"$in")||!Array.isArray(expression.$in)||expression.$in.length<1||expression.$in.length>100)return fail4("invalid $in");values=expression.$in}const checked2=values.map((value2)=>conditionValue(value2,field));if(new Set(checked2).size!==checked2.length)return fail4("duplicate $in value");conditions.push([name,checked2])}let order={field:"$ref",direction:"asc"};if(Object.hasOwn(options,"order")){const entries=Object.entries(mapping3(options.order));if(entries.length!==1)return fail4("order requires one field");const[name,direction]=entries[0];scalarField(name,schema2);if(direction!=="asc"&&direction!=="desc")return fail4("invalid order direction");order={field:name,direction}}const limit=Object.hasOwn(options,"limit")?options.limit:100;if(typeof limit!=="number"||!Number.isInteger(limit)||limit<1||limit>(depth===0?500:100))return fail4("invalid limit");if(Object.hasOwn(options,"count")&&typeof options.count!=="boolean")return fail4("invalid count");if(Object.hasOwn(options,"after")&&(typeof options.after!=="string"||options.after.length===0))return fail4("invalid cursor");const links=[];for(const[name,nested]of Object.entries(selection2)){if(name==="$")continue;const field=schema2.fields.find((field2)=>field2.name===name);if(!field||field.kind!=="link")return fail4(`ineligible link field: ${name}`);if(depth>=4)return fail4("too many link levels");const targets=new Map(field.to.flatMap((type)=>{const targets2=collectionsByType.get(type)??fail4(`unknown link target type: ${type}`);return targets2.map((target)=>[target.name,selectionTree(nested,target.schema,collectionsByType,depth+1,field.many)])}));links.push({name,many:field.many,targets})}return{fields:fields3,conditions,...signalConditions.length?{signalConditions}:{},...options.timeline===true?{timeline:true}:{},order,limit,count:options.count===true,...Object.hasOwn(options,"after")?{after:options.after}:{},explicitOrder:Object.hasOwn(options,"order"),explicitLimit:Object.hasOwn(options,"limit"),links}}function selectionBinding(selection2,top=true,many=false){return{fields:selection2.fields,conditions:[...selection2.conditions].sort(([a],[b])=>compare(a,b)),...selection2.signalConditions?{signalConditions:[...selection2.signalConditions].sort(([a],[b])=>compare(a,b))}:{},...selection2.timeline?{timeline:true}:{},order:top||many&&selection2.explicitOrder?selection2.order:null,limit:top||many&&selection2.explicitLimit?selection2.limit:null,count:selection2.count,links:[...selection2.links].sort((a,b)=>compare(a.name,b.name)).map((link)=>({name:link.name,many:link.many,targets:[...link.targets].sort(([a],[b])=>compare(a,b)).map(([collection,nested])=>[collection,selectionBinding(nested,false,link.many)])}))}}function planIndexQuery(query,catalogue){const entries=queryEntries(query);const collections=new Map(catalogue.map((collection)=>[collection.name,collection]));const byType=new Map;for(const collection of catalogue){const targets=byType.get(collection.schema.type)??[];targets.push(collection);byType.set(collection.schema.type,targets)}return entries.map(([name,value])=>{const target=collections.get(name)??fail4(`unknown collection: ${name}`);return{name,selection:selectionTree(value,target.schema,byType)}})}function indexSelectionBinding(context,collection,selection2){return JSON.stringify({...context,collection,selection:selectionBinding(selection2)})}function cursorPosition(value,binding,limit){let payload;try{payload=mapping3(value)}catch{return fail4("invalid cursor")}const{position,ref}=payload;if(Object.keys(payload).length!==4||payload.format!==1||payload.binding!==binding||typeof position!=="number"||!Number.isSafeInteger(position)||position<=0||position%limit!==0||typeof ref!=="string"||!validRecordRef(ref))return fail4("incompatible cursor");return{position,ref}}var invalid7=()=>{throw new DataOperationError("unavailable",true)};var object4=(value)=>{if(!value||typeof value!=="object"||Array.isArray(value))return invalid7();return value};var keys3=(value,expected)=>Object.keys(value).sort().join(",")===expected;var hash=(value)=>typeof value==="string"&&/^[0-9a-f]{40}$/.test(value);var time=(value)=>typeof value==="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value)&&Number.isFinite(Date.parse(value));var sorted=(values)=>values.every((value,i)=>i===0||values[i-1]<value);function json(value){if(value===null||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value)||dataText(value))return;if(Array.isArray(value)){for(const item of value)json(item);return}for(const[key,item]of Object.entries(object4(value))){if(!dataText(key))return invalid7();json(item)}}function stable(value){if(Array.isArray(value))return`[${value.map(stable).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([key,item])=>`${JSON.stringify(key)}:${stable(item)}`).join(",")}}`;return JSON.stringify(value)}var slot=(values,field)=>Object.hasOwn(values,field)?{present:true,value:values[field]}:{present:false};function apply(book,event){const records=book.get(event.collection),prior=records.get(event.ref);if(event.kind==="create"){if(prior)return invalid7();records.set(event.ref,structuredClone(event.values))}else if(event.kind==="delete"){if(!prior||stable(prior)!==stable(event.values))return invalid7();records.delete(event.ref)}else if(event.kind==="rename"){const before=records.get(event.previousRef);if(!before||prior)return invalid7();records.delete(event.previousRef);records.set(event.ref,before)}else if(event.kind==="update"){if(!prior||stable(slot(prior,event.field))!==stable(event.before)||stable(event.before)===stable(event.after))return invalid7();if(event.after.present)Object.defineProperty(prior,event.field,{value:structuredClone(event.after.value),enumerable:true,configurable:true,writable:true});else delete prior[event.field]}}function validateSnapshotHistory(input,collections,version){const row=object4(input),selections=object4(row.fields);if(!keys3(row,"commits,fields,through")||!hash(row.through)||version!==`current-${row.through}`||!Array.isArray(row.commits)||!row.commits.length||!Object.keys(selections).length||!sorted(Object.keys(selections)))return invalid7();const book=new Map;for(const[collection,selection2]of Object.entries(selections)){const selected=object4(selection2),fields3=selected.fields;if(!Object.hasOwn(collections,collection)||!keys3(selected,"fields")||!Array.isArray(fields3)||!fields3.length||fields3.some((field)=>typeof field!=="string"||!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field))||!sorted(fields3))return invalid7();book.set(collection,new Map)}const history=row,seen=new Set;let parent=null;for(const group of history.commits){if(!keys3(object4(group),"authoredAt,commit,committedAt,events,firstParent")||!hash(group.commit)||seen.has(group.commit)||group.firstParent!==parent||!time(group.authoredAt)||!time(group.committedAt)||!Array.isArray(group.events))return invalid7();seen.add(group.commit);parent=group.commit;let previous;const created=new Set;for(const event of group.events){object4(event);if(!book.has(event.collection)||!validRecordRef(event.ref)||!event.ref.startsWith(`${event.collection}/`))return invalid7();const fields3=history.fields[event.collection].fields;if(event.kind==="create"||event.kind==="delete"){if(!keys3(event,"collection,kind,ref,values")||Object.keys(object4(event.values)).some((field)=>!fields3.includes(field)))return invalid7();json(event.values);if(event.kind==="create")created.add(event.ref)}else if(event.kind==="rename"){if(!keys3(event,"collection,kind,previousRef,ref")||!validRecordRef(event.previousRef)||!event.previousRef.startsWith(`${event.collection}/`)||event.previousRef===event.ref)return invalid7()}else if(event.kind==="update"){if(!keys3(event,"after,before,collection,field,kind,ref")||!fields3.includes(event.field)||created.has(event.ref))return invalid7();for(const value of[event.before,event.after]){object4(value);if(value.present===false?!keys3(value,"present"):value.present!==true||!keys3(value,"present,value"))return invalid7();if(value.present)json(value.value)}}else return invalid7();const order=[event.kind==="delete"?0:1,event.ref,event.kind==="update"?1:0,event.kind==="update"?event.field:""];if(previous){const index=order.findIndex((value,i)=>value!==previous[i]);if(index===-1||order[index]<previous[index])return invalid7()}previous=order;apply(book,event)}const refs=new Set;for(const records of book.values())for(const ref of records.keys()){if(refs.has(ref))return invalid7();refs.add(ref)}}if(parent!==history.through)return invalid7();for(const[collection,records]of book){const expected=collections[collection].map((record2)=>[record2.$ref,Object.fromEntries(history.fields[collection].fields.filter((field)=>Object.hasOwn(record2,field)).map((field)=>[field,record2[field]]))]);if(stable([...records].sort(([a],[b])=>a<b?-1:1))!==stable(expected))return invalid7()}return history}function captureHistoryInput(input,operation){const properties=dataProperties(input),row=Object.fromEntries(Object.entries(properties).map(([key,property])=>[key,property.value]));if(Object.keys(row).some((key)=>!(operation==="records"?["collection","at"]:["collection","ref","field"]).includes(key))||typeof row.collection!=="string"||operation==="records"&&!time(row.at)||Object.hasOwn(row,"ref")&&!validRecordRef(row.ref)||Object.hasOwn(row,"field")&&typeof row.field!=="string")throw new DataOperationError("invalid_query");return row}function readSnapshotHistory(history,input,operation){if(!history||!Object.hasOwn(history.fields,input.collection)||input.field!==undefined&&!history.fields[input.collection].fields.includes(input.field))throw new DataOperationError("invalid_query");if(operation==="changes")return structuredClone(history.commits.flatMap(({firstParent:_parent,...group})=>{const events=group.events.filter((event)=>event.collection===input.collection&&(input.ref===undefined||event.ref===input.ref)&&(input.field===undefined||event.kind==="update"&&event.field===input.field));return events.length?[{...group,events}]:[]}));let index=history.commits.length-1;while(index>=0&&Date.parse(history.commits[index].committedAt)>Date.parse(input.at))index--;const book=new Map([[input.collection,new Map]]);let selected=false;for(let i=0;i<=index;i++)for(const event of history.commits[i].events)if(event.collection===input.collection){selected=true;apply(book,event)}return{commit:selected?history.commits[index].commit:null,records:[...book.get(input.collection)].sort(([a],[b])=>a<b?-1:1).map(([$ref,values])=>({$ref,values}))}}var snapshotCollection=(catalogue,ref)=>catalogue.filter((c)=>ref.startsWith(`${c.name}/`)).sort((a,b)=>b.name.length-a.name.length)[0];var invalid8=()=>{throw new DataOperationError("unavailable",true)};var object5=(value)=>{if(!value||typeof value!=="object"||Array.isArray(value))return invalid8();return value};function stable2(value){if(Array.isArray(value))return`[${value.map(stable2).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([key,entry])=>`${JSON.stringify(key)}:${stable2(entry)}`).join(",")}}`;return JSON.stringify(value)}function schemaText(value){if(typeof value==="string"&&!dataText(value))return invalid8();if(value&&typeof value==="object")for(const[key,entry]of Object.entries(value)){if(!dataText(key))return invalid8();schemaText(entry)}}function validateSnapshotEnvelope(input,repository,name,bodies=[],timelines=[]){try{const row=object5(input);const legacy=row.format==="data-snapshot.v1";if(!["collections,format,name,repository,schemas,version","collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(","))||!legacy&&row.format!=="data-snapshot.v2"||legacy&&timelines.length>0||row.repository!==repository||row.name!==name||!dataVersion(row.version))return invalid8();const schemas2=object5(row.schemas),collections=object5(row.collections);schemaText(schemas2);const names=Object.keys(collections);for(const subset of[bodies,timelines])if(new Set(subset).size!==subset.length||subset.some((name2)=>!names.includes(name2)))return invalid8();if(!names.length||names.join("\x00")!==[...names].sort().join("\x00")||Object.keys(schemas2).join("\x00")!==names.join("\x00"))return invalid8();const catalogue=names.map((name2)=>{const schema2=object5(schemas2[name2]);if(!validRecordRef(`${name2}/example`)||schema2.name!==name2||typeof schema2.type!=="string"||!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type)||schema2.description!==undefined&&!dataText(schema2.description)||Object.keys(schema2).some((key)=>!["name","type","description","fields"].includes(key)))return invalid8();const definitions2=fields2(schema2.fields,0,true);if(stable2(definitions2.map(publicField))!==stable2(schema2.fields))return invalid8();return{name:name2,schema:{type:schema2.type,fields:definitions2,...schema2.description===undefined?{}:{description:schema2.description}}}});const types=new Map;for(const collection of catalogue){const records=collections[collection.name];if(!Array.isArray(records))return invalid8();let previous="";for(const record2 of records){const value=object5(record2);if(!validRecordRef(value.$ref)||snapshotCollection(catalogue,value.$ref)?.name!==collection.name||value.$ref<=previous||types.has(value.$ref)||typeof value.$version!=="string"||!/^record-v1:[0-9a-f]{64}$/.test(value.$version))return invalid8();types.set(value.$ref,collection.schema.type);previous=value.$ref}}for(const collection of catalogue)for(const record2 of collections[collection.name]){const{$ref:_ref,$version:_version,$body,$signals,$timeline,...values}=record2;if(legacy){if(Object.hasOwn(record2,"$signals")||Object.hasOwn(record2,"$timeline"))return invalid8()}else{captureRecordSignals($signals);if(timelines.includes(collection.name)){if(!Array.isArray($timeline))return invalid8();$timeline.forEach((value)=>captureTimeline(value))}else if(Object.hasOwn(record2,"$timeline"))return invalid8()}if(Object.hasOwn(record2,"$body")&&(!bodies.includes(collection.name)||typeof $body!=="string"))return invalid8();validateRecordFields(values,collection.schema.fields,(ref,targets)=>{return types.get(ref)??targets[0]},true)}const normalized=legacy?Object.fromEntries(Object.entries(collections).map(([collection,records])=>[collection,records.map((record2)=>({...record2,$signals:[]}))])):collections;return{format:"data-snapshot.v2",repository,name,version:row.version,bodyCollections:[...bodies],timelineCollections:[...timelines],catalogue,collections:normalized,...Object.hasOwn(row,"history")?{history:validateSnapshotHistory(row.history,normalized,row.version)}:{}}}catch{return invalid8()}}var compare2=(a,b)=>a<b?-1:a>b?1:0;var fail5=(message)=>{throw new RecordValidationError(`Invalid Records query: ${message}`)};function continuation(value,binding,matching,limit){const{position,ref}=cursorPosition(value,binding,limit);if(position>=matching.length||ref!==matching[position-1]?.$ref)return fail5("incompatible cursor");return position}function matches(record2,selection2){return(selection2.signalConditions??[]).every(([key,statuses])=>{if(!Array.isArray(record2.$signals))return fail5("Signals are unavailable");const signal=record2.$signals?.find((row)=>row.key===key);return statuses===false?signal===undefined:signal!==undefined&&statuses.includes(signal.status)})&&selection2.conditions.every(([field,condition])=>{if(!Object.hasOwn(record2,field))return false;const value=record2[field];if(Array.isArray(condition))return condition.some((candidate)=>candidate===value);if(value===null)return false;return condition.bounds.every(([operator,bound])=>{const result=typeof value==="number"&&typeof bound==="number"?value-bound:compare2(value,bound);switch(operator){case"$gt":return result>0;case"$gte":return result>=0;case"$lt":return result<0;case"$lte":return result<=0}})})}function ordered(a,b,{field,direction}){const left=a[field],right=b[field];const missingLeft=left===null||left===undefined,missingRight=right===null||right===undefined;let result=0;if(missingLeft!==missingRight)return missingLeft?1:-1;if(!missingLeft&&!missingRight){result=typeof left==="number"&&typeof right==="number"?left-right:typeof left==="boolean"&&typeof right==="boolean"?Number(left)-Number(right):compare2(left,right);if(direction==="desc")result=-result}return result||compare2(a.$ref,b.$ref)}function*evaluateRecordsQuery(query,catalogue,context,maxRecords,cloneValue,bodyCollections=[]){const{version}=context;const selections=planIndexQuery(query,catalogue);const scanned=new Map;for(const{name}of selections)scanned.set(name,yield{operation:"scan",collection:name});if(maxRecords!==undefined){const total=selections.reduce((sum,{name,selection:selection2})=>sum+scanned.get(name).filter((record2)=>matches(record2,selection2)).length,0);if(total>maxRecords)throw new DataOperationError("capacity",false,undefined,undefined,{code:"record_limit_exceeded",maxRecords,collections:selections.map((row)=>row.name)})}let occurrences=0;function*expand(record2,collection,selection2,fragment){if(++occurrences>2000)return fail5("too many returned Record occurrences");const result=Object.fromEntries(["$ref","$version",...selection2.fields.filter((field)=>!["$ref","$version"].includes(field))].filter((field)=>Object.hasOwn(record2,field)).map((field)=>[field,cloneValue(record2[field])]));if(Object.hasOwn(record2,"$signals"))result.$signals=cloneValue(record2.$signals);if(selection2.timeline){if(!Array.isArray(record2.$timeline))return fail5("Timeline is unavailable");result.$timeline=cloneValue(record2.$timeline)}if(bodyCollections.includes(collection)&&typeof record2.$body==="string")result.$body=record2.$body;if(fragment!==undefined)result.$fragment=fragment;for(const link of selection2.links){if(!Object.hasOwn(record2,link.name))continue;const value=record2[link.name];let expanded;if(value===null)expanded=null;else{const refs=link.many?value:[value];let matching=[];for(const value2 of refs){const{ref,fragment:fragment2}=parseRecordLink(value2)??fail5("invalid stored link");const target=yield{operation:"lookup",ref};if(!target)return fail5("unresolved stored link");const nested=link.targets.get(target.collection)??fail5("incompatible stored link");if(matches(target.record,nested))matching.push({record:target.record,collection:target.collection,selection:nested,fragment:fragment2})}const options=link.targets.values().next().value;if(options.explicitOrder)matching.sort((a,b)=>ordered(a.record,b.record,options.order));if(link.many&&!options.explicitLimit&&matching.length>100)return fail5("too many matching linked Records");if(options.explicitLimit)matching=matching.slice(0,options.limit);const records=[];for(const{record:record3,collection:collection2,selection:selection3,fragment:fragment2}of matching)records.push(yield*expand(record3,collection2,selection3,fragment2));expanded=link.many?records:records[0]??null}Object.defineProperty(result,link.name,{value:expanded,enumerable:true,writable:true,configurable:true})}return result}const metadata={version,collections:{}};const results=[];for(const{name,selection:selection2}of selections){const matching=scanned.get(name).filter((record2)=>matches(record2,selection2)).sort((a,b)=>ordered(a,b,selection2.order));const binding=indexSelectionBinding(context,name,selection2);const start=selection2.after===undefined?0:continuation(yield{operation:"open",token:selection2.after},binding,matching,selection2.limit);const end=maxRecords===undefined?Math.min(start+selection2.limit,matching.length):matching.length;const records=[];for(let index=start;index<end;index++){if(maxRecords!==undefined&&(index-start)%selection2.limit===0)occurrences=0;records.push(yield*expand(matching[index],name,selection2))}const page=selection2.count?{count:matching.length}:{};if(maxRecords===undefined&&end<matching.length){const token=yield{operation:"seal",payload:{format:1,binding,position:end,ref:matching[end-1].$ref}};if(typeof token!=="string"||token.length===0)return fail5("invalid sealed cursor");page.next=token}if(Object.keys(page).length)Object.defineProperty(metadata.collections,name,{value:page,enumerable:true,writable:true,configurable:true});results.push([name,records])}return{...Object.fromEntries(results),$meta:metadata}}var snapshotAcquisitionType="application/vnd.os.data-snapshot.v2+json";var snapshotAcquisitionFormat="data-snapshot-acquisition.v2";var snapshotPairHeader="Snapshot-Pair";var validSnapshotPairToken=(value)=>typeof value==="string"&&/^snapshot-pair-v1:[0-9a-f]{64}$/.test(value);var snapshotArtifactHeader="Snapshot-Artifact";var validSnapshotArtifactToken=(value)=>typeof value==="string"&&/^snapshot-artifact-v1:[0-9a-f]{64}$/.test(value);var snapshotUpdatesProtocol="os.data-snapshot.updates.v1";var snapshotUpdatesCredentialPrefix="os.member.";var snapshotUpdateHint="update";var invalid9=()=>{throw new DataOperationError("unavailable",true)};var object6=(v)=>v&&typeof v==="object"&&!Array.isArray(v)?v:invalid9();var uuid=(v)=>typeof v==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v);var time2=(v)=>typeof v==="string"&&Number.isFinite(Date.parse(v));var recordVersion=(v)=>typeof v==="string"&&/^record-v1:[0-9a-f]{64}$/.test(v);var keys4=(v,allowed)=>Object.keys(v).every((k)=>allowed.includes(k));function validateAcquisition(input,repository,name){const row=object6(input),snapshot=object6(row.snapshot);if(Object.keys(row).sort().join(",")!=="changes,format,snapshot"||row.format!==snapshotAcquisitionFormat||!keys4(snapshot,["id","name","refreshedAt","repository","version","collections","bodies","timelines"])||!uuid(snapshot.id)||snapshot.repository!==repository||snapshot.name!==name||!dataVersion(snapshot.version)||!time2(snapshot.refreshedAt)||!Array.isArray(snapshot.collections)||!snapshot.collections.length||!snapshot.collections.every((c)=>typeof c==="string"&&validRecordRef(`${c}/example`))||snapshot.collections.join("\x00")!==[...new Set(snapshot.collections)].sort().join("\x00")||!Array.isArray(row.changes))return invalid9();const bodies=snapshot.bodies===undefined?[]:snapshot.bodies;const timelines=snapshot.timelines===undefined?[]:snapshot.timelines;for(const subset of[bodies,timelines])if(!Array.isArray(subset)||subset.some((c)=>!snapshot.collections.includes(c))||subset.join("\x00")!==[...new Set(subset)].sort().join("\x00"))return invalid9();return{snapshot:{...snapshot,bodies,timelines},changes:validateSnapshotChanges(row.changes,snapshot.collections)}}function validateSnapshotChanges(input,collections){try{if(!Array.isArray(input))return invalid9();const ids=new Set;let unpublished=false;for(const value of input){const c=object6(value),effect=object6(c.effect);if(!keys4(c,["id","version","ref","recordVersion","effect","updatedAt","person","source","publication"])||!uuid(c.id)||ids.has(c.id)||!dataVersion(c.version)||!validRecordRef(c.ref)||!collections.some((name)=>c.ref.startsWith(`${name}/`))||!recordVersion(c.recordVersion)||!time2(c.updatedAt))return invalid9();ids.add(c.id);if(c.person!==undefined){const person=object6(c.person);if(!keys4(person,["id","name","email"])||!uuid(person.id)||person.name!==undefined&&!dataText(person.name)||person.email!==undefined&&!dataText(person.email))return invalid9()}if(c.source!==undefined){const source=object6(c.source);if(Object.keys(source).sort().join(",")!=="id,kind"||source.kind!=="app"&&source.kind!=="routine"||!dataText(source.id))return invalid9()}if(c.publication!==undefined){const publication=object6(c.publication);if(unpublished||Object.keys(publication).sort().join(",")!=="commit,time"||typeof publication.commit!=="string"||!/^[0-9a-f]{40}$/.test(publication.commit)||!time2(publication.time))return invalid9()}else unpublished=true;if(effect.kind==="set"){if(Object.keys(effect).sort().join(",")!=="field,kind,value"||!dataText(effect.field)||effect.field.startsWith("$")||["id","type","__proto__","constructor","prototype"].includes(effect.field))return invalid9()}else if(effect.kind==="link"||effect.kind==="unlink"){if(!keys4(effect,["kind","field","refs",...effect.kind==="link"?["remove"]:[]])||!dataText(effect.field)||effect.field.startsWith("$")||["id","type","__proto__","constructor","prototype"].includes(effect.field)||!Array.isArray(effect.refs)||!effect.refs.length||effect.refs.length>1e5||effect.refs.some((ref)=>!validRecordRef(ref))||new Set(effect.refs).size!==effect.refs.length)return invalid9();if(effect.remove!==undefined&&(!Array.isArray(effect.remove)||!effect.remove.length||effect.remove.length>1e5||effect.remove.some((ref)=>!validRecordRef(ref))||new Set(effect.remove).size!==effect.remove.length))return invalid9()}else if(effect.kind==="signal"){if(Object.keys(effect).sort().join(",")!=="key,kind,value")return invalid9();const value2=object6(effect.value);if(!keys4(value2,["label","status","reason","related","asOf","number"]))return invalid9();const{number,...assessment}=value2;captureSignal({...assessment,key:effect.key});if(c.publication||Object.hasOwn(value2,"number"))captureRecordSignal({...value2,key:effect.key})}else if(effect.kind==="timeline"){if(Object.keys(effect).sort().join(",")!=="entry,kind")return invalid9();captureTimeline(effect.entry)}else if(effect.kind==="create"||effect.kind==="delete"){if(!keys4(effect,["fields","kind","signals","timeline"]))return invalid9();object6(effect.fields);if(Object.hasOwn(effect,"signals"))captureRecordSignals(effect.signals);if(Object.hasOwn(effect,"timeline")){if(!Array.isArray(effect.timeline))return invalid9();effect.timeline.forEach((value2)=>captureTimeline(value2))}}else return invalid9()}return input}catch{return invalid9()}}function materializeSnapshot(envelope,changes,version){try{if(!changes.length)return envelope;const rows=new Map(Object.values(envelope.collections).flat().map((r)=>[r.$ref,structuredClone(r)]));for(const c of changes){const schema2=snapshotCollection(envelope.catalogue,c.ref);if(!schema2)return invalid9();const effect=c.effect;const definitions2="field"in effect?schema2.schema.fields.filter((f)=>f.name===effect.field):schema2.schema.fields;if("field"in effect&&!definitions2.length)return invalid9();let values;if(effect.kind==="link"||effect.kind==="unlink"){const field=definitions2[0];if(field.kind!=="link"||!field.many&&effect.kind==="link"&&effect.refs.length!==1)return invalid9();const targets=[...effect.refs,...effect.kind==="link"?effect.remove??[]:[]];for(const ref of targets)validateRecordFields({[effect.field]:field.many?[ref]:ref},definitions2,(_ref,allowed)=>allowed[0],true);values={[effect.field]:field.many?effect.refs:effect.refs[0]}}else values=effect.kind==="set"?{[effect.field]:effect.value}:("fields"in effect)?effect.fields:{};if(effect.kind!=="signal"&&effect.kind!=="timeline")validateRecordFields(values,definitions2,(_ref,targets)=>targets[0],true);if(!c.publication)continue;const prior=rows.get(c.ref);if(effect.kind==="set"){if(!prior)return invalid9();rows.set(c.ref,{...prior,[effect.field]:effect.value,$version:c.recordVersion})}else if(effect.kind==="link"||effect.kind==="unlink"){if(!prior)return invalid9();const field=definitions2[0];const current=prior[effect.field];const value=field.many?effect.kind==="link"?[...new Set([...Array.isArray(current)?current:[],...effect.refs])].filter((ref)=>!effect.remove?.includes(String(ref))):(Array.isArray(current)?current:[]).filter((ref)=>!effect.refs.includes(String(ref))):effect.kind==="link"?effect.remove?.includes(effect.refs[0])?null:effect.refs[0]:effect.refs.includes(String(current))?null:current;rows.set(c.ref,{...prior,[effect.field]:value,$version:c.recordVersion})}else if(effect.kind==="signal"){if(!prior||!effect.value.number)return invalid9();const signal=captureRecordSignal({...effect.value,key:effect.key});const signals=captureRecordSignals(prior.$signals);const index=signals.findIndex((row)=>row.key===effect.key);if(index<0)signals.push(signal);else signals[index]=signal;rows.set(c.ref,{...prior,$signals:captureRecordSignals(signals),$version:c.recordVersion})}else if(effect.kind==="timeline"){if(!prior)return invalid9();rows.set(c.ref,{...prior,$version:c.recordVersion,...envelope.timelineCollections.includes(schema2.name)?{$timeline:[...prior.$timeline,effect.entry]}:{}})}else if(effect.kind==="create"){if(prior)return invalid9();rows.set(c.ref,{...effect.fields,$ref:c.ref,$version:c.recordVersion,$signals:effect.signals??[],...envelope.timelineCollections.includes(schema2.name)?{$timeline:effect.timeline??[]}:{}})}else{if(!prior)return invalid9();rows.delete(c.ref)}}const materialized=validateSnapshotEnvelope({format:envelope.format,repository:envelope.repository,name:envelope.name,version,schemas:Object.fromEntries(envelope.catalogue.map((c)=>[c.name,{name:c.name,type:c.schema.type,...c.schema.description===undefined?{}:{description:c.schema.description},fields:c.schema.fields.map(publicField)}])),collections:Object.fromEntries(envelope.catalogue.map((c)=>[c.name,[...rows.values()].filter((r)=>snapshotCollection(envelope.catalogue,r.$ref)?.name===c.name).sort((a,b)=>a.$ref<b.$ref?-1:1)]))},envelope.repository,envelope.name,envelope.bodyCollections,envelope.timelineCollections);return{...materialized,...envelope.history?{history:envelope.history}:{}}}catch{return invalid9()}}function applySnapshotMutation(envelope,prior,mutation,installation){const rejected=()=>{throw new DataOperationError("unavailable")};let changes=prior;if(mutation.kind==="discard"){changes=prior.filter((c)=>!mutation.selected.some((s)=>s.id===c.id&&s.version===c.version))}else{const accepted=validateSnapshotChanges(mutation.changes,installation.catalogue.map((c)=>c.name));const ids=new Set(accepted.map((c)=>c.id));changes=[...prior.filter((c)=>mutation.kind==="publish"?!mutation.selected.some((s)=>s.id===c.id&&s.version===c.version):!ids.has(c.id)),...accepted.filter((c)=>mutation.kind!=="publish"||!prior.some((p)=>p.id===c.id&&p.version!==c.version))];changes=[...changes.filter((c)=>c.publication),...changes.filter((c)=>!c.publication)];if(mutation.kind==="publish"){if(accepted.some((c)=>!c.publication)||!Array.isArray(mutation.effects))return rejected();const effects=mutation.effects.map((e)=>{const source=accepted.find((c)=>c.ref===e.ref);if(!source||snapshotCollection(envelope.catalogue,e.ref)?.name!==e.collection||!["set","signal","timeline","create","delete"].includes(e.effect.kind))return rejected();return{...source,id:crypto.randomUUID(),recordVersion:e.version,effect:e.effect}});validateSnapshotChanges(effects,installation.catalogue.map((c)=>c.name));if(mutation.records!==undefined){materializeSnapshot(envelope,[...accepted,...effects].map(({publication:_publication,...c})=>c),envelope.version);if(!Array.isArray(mutation.records)||new Set(mutation.records.map((r)=>r.$ref)).size!==mutation.records.length)return rejected();const refs=new Set(mutation.records.map((r)=>r.$ref));const selected=[...accepted,...prior.filter((c)=>mutation.selected.some((s)=>s.id===c.id&&s.version===c.version))];if(selected.some((c)=>c.effect.kind!=="delete"&&!refs.has(c.ref)))return rejected();if(accepted.some((c)=>!mutation.effects.some((e)=>e.ref===c.ref&&("field"in c.effect?"field"in e.effect&&e.effect.field===c.effect.field:c.effect.kind==="signal"?e.effect.kind==="signal"&&e.effect.key===c.effect.key:e.effect.kind===c.effect.kind))))return rejected();if(mutation.effects.some((e)=>!accepted.some((c)=>c.ref===e.ref)||snapshotCollection(envelope.catalogue,e.ref)?.name!==e.collection||!["set","signal","timeline","create","delete"].includes(e.effect.kind)||e.effect.kind!=="delete"&&!mutation.records.some((r)=>r.$ref===e.ref&&r.$version===e.version)))return rejected();const rows=new Map(Object.values(envelope.collections).flat().map((r)=>[r.$ref,r]));for(const e of mutation.effects)if(e.effect.kind==="delete")rows.delete(e.ref);for(const record2 of mutation.records){const collection=snapshotCollection(envelope.catalogue,record2.$ref)?.name;if(!collection)return rejected();const{$body,$timeline,...fields3}=record2;rows.set(record2.$ref,{...fields3,...envelope.bodyCollections?.includes(collection)&&$body!==undefined?{$body}:{},...envelope.timelineCollections.includes(collection)?{$timeline}:{}})}envelope=validateSnapshotEnvelope({format:envelope.format,repository:envelope.repository,name:envelope.name,version:`snapshot-${crypto.randomUUID()}`,schemas:Object.fromEntries(envelope.catalogue.map((c)=>[c.name,{name:c.name,type:c.schema.type,...c.schema.description===undefined?{}:{description:c.schema.description},fields:c.schema.fields.map(publicField)}])),collections:Object.fromEntries(envelope.catalogue.map((c)=>[c.name,[...rows.values()].filter((r)=>snapshotCollection(envelope.catalogue,r.$ref)?.name===c.name).sort((a,b)=>a.$ref<b.$ref?-1:1)]))},envelope.repository,envelope.name,envelope.bodyCollections,envelope.timelineCollections);return{envelope,changes}}if(!accepted.length||!mutation.effects.length)return rejected();envelope=materializeSnapshot(envelope,effects,`snapshot-${crypto.randomUUID()}`)}else{if(!accepted.length||accepted.some((c)=>c.publication))return rejected();materializeSnapshot(envelope,accepted,envelope.version)}}return{envelope,changes}}var unavailable2=()=>{throw new DataOperationError("unavailable",true)};function request(value){return new Promise((resolve,reject)=>{value.onsuccess=()=>resolve(value.result);value.onerror=()=>reject(new DataOperationError("unavailable",true))})}function completed(transaction){const done=new Promise((resolve,reject)=>{transaction.oncomplete=()=>resolve();transaction.onabort=transaction.onerror=()=>reject(new DataOperationError("unavailable",true))});done.catch(()=>{});return done}function encode(bytes){return btoa(Array.from(bytes,(byte)=>String.fromCharCode(byte)).join(""))}async function openSnapshotStore(){const opening=indexedDB.open("oddington.data.snapshots.v2",2);opening.onupgradeneeded=()=>{opening.result.createObjectStore("bases");if(opening.transaction.objectStoreNames.contains("current"))return;opening.result.createObjectStore("current");opening.result.createObjectStore("changes");const records=opening.result.createObjectStore("records",{keyPath:["installation","ref"]});records.createIndex("collection",["installation","collection"])};const database=await request(opening);database.onversionchange=()=>database.close();return{close(){database.close()},async current(partition){const transaction=database.transaction(["current","records","changes","bases"],"readonly"),done=completed(transaction);const value=await request(transaction.objectStore("current").get(partition));if(!value){await done;return}if(value.format!=="data-snapshot.v2"||!Array.isArray(value.timelineCollections)||value.partition!==partition||!value.id||!value.snapshotId||value.pairToken!==""&&!validSnapshotPairToken(value.pairToken)||!validSnapshotArtifactToken(value.artifactToken)||!value.version||!Array.isArray(value.catalogue)||!value.counts||!(value.cursorKey instanceof Uint8Array)||value.cursorKey.length!==32){await done;return}const changes=await request(transaction.objectStore("changes").get(value.id));let complete=!!await request(transaction.objectStore("bases").getKey(value.artifactToken))&&Array.isArray(changes)&&changes.length===value.changeCount;for(const collection of value.catalogue){const count=await request(transaction.objectStore("records").index("collection").count([value.id,collection.name]));if(count!==value.counts[collection.name])complete=false}await done;return complete?value:undefined},async base(installation){const transaction=database.transaction("bases","readonly"),done=completed(transaction);const base=await request(transaction.objectStore("bases").get(installation.artifactToken));await done;return base},async install(partition,pairToken,envelope,changes,assertCurrent,snapshotId,artifact,unchangedRecords){const installation={id:crypto.randomUUID(),partition,pairToken,version:envelope.version,artifactToken:artifact.token,snapshotId,repository:envelope.repository,name:envelope.name,format:envelope.format,bodyCollections:envelope.bodyCollections,timelineCollections:envelope.timelineCollections,catalogue:envelope.catalogue,changeCount:changes.length,cursorKey:unchangedRecords?.cursorKey??crypto.getRandomValues(new Uint8Array(32)),...unchangedRecords?{queryIdentity:unchangedRecords.queryIdentity??unchangedRecords.id}:{},counts:Object.fromEntries(Object.entries(envelope.collections).map(([name,rows])=>[name,rows.length]))};const transaction=database.transaction(["current","records","changes","bases"],"readwrite"),done=completed(transaction);try{assertCurrent();transaction.objectStore("bases").put(artifact.base,artifact.token);const records=transaction.objectStore("records");for(const[collection,rows]of Object.entries(envelope.collections))for(const record2 of rows)records.put({installation:installation.id,collection,ref:record2.$ref,record:record2});await request(transaction.objectStore("changes").put(changes,installation.id));await request(transaction.objectStore("current").put(installation,partition));assertCurrent();await done;assertCurrent();return installation}catch(error){try{transaction.abort()}catch{}await done.catch(()=>{});throw error}},async invalidate(installation){const transaction=database.transaction(["current","changes"],"readwrite"),done=completed(transaction);transaction.objectStore("changes").delete(installation.id);const current=await request(transaction.objectStore("current").get(installation.partition));if(current?.id===installation.id)transaction.objectStore("current").delete(installation.partition);await done},async mutate(installation,mutation,assertCurrent){const transaction=database.transaction(["current","records","changes"],"readwrite"),done=completed(transaction);try{assertCurrent();const records=transaction.objectStore("records"),collections={};const prior=await request(transaction.objectStore("changes").get(installation.id));if(!prior||prior.length!==installation.changeCount)return unavailable2();for(const c of installation.catalogue){const rows=await request(records.index("collection").getAll([installation.id,c.name]));if(rows.length!==installation.counts[c.name])return unavailable2();collections[c.name]=rows.map((r)=>r.record)}const{envelope,changes}=applySnapshotMutation({format:"data-snapshot.v2",repository:installation.repository,name:installation.name,version:installation.version,bodyCollections:installation.bodyCollections,timelineCollections:installation.timelineCollections,catalogue:installation.catalogue,collections},prior,mutation,installation);const id2=crypto.randomUUID();const next={...installation,id:id2,pairToken:"",version:envelope.version,queryIdentity:mutation.kind==="publish"?id2:installation.queryIdentity??installation.id,changeCount:changes.length,counts:Object.fromEntries(Object.entries(envelope.collections).map(([name,rows])=>[name,rows.length]))};for(const[collection,rows]of Object.entries(envelope.collections))for(const record2 of rows)records.put({installation:id2,collection,ref:record2.$ref,record:record2});transaction.objectStore("changes").put(changes,id2);const current=await request(transaction.objectStore("current").get(installation.partition));if(current?.id===installation.id)transaction.objectStore("current").put(next,installation.partition);assertCurrent();await done;assertCurrent();return next}catch(error){try{transaction.abort()}catch{}await done.catch(()=>{});throw error}},async read(installation,ref){const transaction=database.transaction("records","readonly"),done=completed(transaction);const row=await request(transaction.objectStore("records").get([installation.id,ref]));const collection=snapshotCollection(installation.catalogue,ref).name;const count=await request(transaction.objectStore("records").index("collection").count([installation.id,collection]));await done;if(count!==installation.counts[collection])return unavailable2();return row?.record??null},async changes(installation){const transaction=database.transaction("changes","readonly"),done=completed(transaction);const rows=await request(transaction.objectStore("changes").get(installation.id));await done;if(!rows||rows.length!==installation.changeCount)return unavailable2();return rows},async query(installation,query,maxRecords,body){const key=await crypto.subtle.importKey("raw",installation.cursorKey,"AES-GCM",false,["encrypt","decrypt"]);let transaction,done;const records=()=>{if(!transaction){transaction=database.transaction("records","readonly");done=completed(transaction)}return transaction.objectStore("records")};const finish=async()=>{await done;transaction=undefined;done=undefined};const evaluation=evaluateRecordsQuery(query,installation.catalogue,{workspaceId:installation.partition,repository:installation.partition,identity:installation.queryIdentity??installation.id,version:installation.version},maxRecords,(value)=>value,body?installation.bodyCollections:undefined);try{let step=evaluation.next();while(!step.done){const work=step.value;let value;if(work.operation==="scan"){const rows=await request(records().index("collection").getAll([installation.id,work.collection]));if(rows.length!==installation.counts[work.collection])return unavailable2();value=rows.map((row)=>row.record)}else if(work.operation==="lookup"){const row=await request(records().get([installation.id,work.ref]));value=row&&{record:row.record,collection:row.collection}}else{await finish();if(work.operation==="seal"){const iv=crypto.getRandomValues(new Uint8Array(12));const sealed=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv},key,new TextEncoder().encode(JSON.stringify(work.payload))));value=encode(new Uint8Array([...iv,...sealed]))}else{try{const bytes=Uint8Array.from(atob(work.token),(c)=>c.charCodeAt(0));const opened=await crypto.subtle.decrypt({name:"AES-GCM",iv:bytes.slice(0,12)},key,bytes.slice(12));value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(opened))}catch{throw new DataOperationError("invalid_query")}}}step=evaluation.next(value)}await finish();return step.value}catch(error){try{transaction?.abort()}catch{}await done?.catch(()=>{});throw error}}}}function unavailable3(){throw new DataOperationError("unavailable",true)}function stable3(value){if(Array.isArray(value))return`[${value.map(stable3).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>`${JSON.stringify(k)}:${stable3(v)}`).join(",")}}`;return JSON.stringify(value)}var facts=(changes,records=false)=>stable3(changes.filter((c)=>!records||c.publication).map((c)=>records?{id:c.id,version:c.version,recordVersion:c.recordVersion,effect:c.effect,publication:c.publication}:c).sort((a,b)=>a.id.localeCompare(b.id)));function snapshotDifference(before,after){return{records:facts(before,true)!==facts(after,true),changes:facts(before)!==facts(after)}}async function acquireSnapshot(store,partition,url,headers,repository,snapshot,assertCurrent,signal,prior){const candidate=prior===null?undefined:prior??await store.current(partition);const cached=candidate?.format==="data-snapshot.v2"&&validSnapshotArtifactToken(candidate.artifactToken)&&(candidate.pairToken===""||validSnapshotPairToken(candidate.pairToken))?candidate:undefined;let base=cached?await store.base(cached):undefined;if(base?.format!=="data-snapshot.v2")base=undefined;const reusable=base?cached:undefined;assertCurrent();for(let attempt=0;attempt<3;attempt++){const response=await fetch(url,{method:"GET",redirect:"error",cache:"no-store",signal,headers:{...headers,accept:snapshotAcquisitionType,...reusable?.pairToken?{[snapshotPairHeader]:reusable.pairToken}:{}}});assertCurrent();if(response.status===409){await response.body?.cancel();continue}const pairToken=response.headers.get(snapshotPairHeader),artifactToken=response.headers.get(snapshotArtifactHeader);if(response.status===204){if(!reusable||pairToken!==reusable.pairToken||artifactToken!==reusable.artifactToken)unavailable3();return{installation:reusable,update:{records:false,changes:false}}}if(!response.ok)throw dataTransportError(response.status,await response.json().catch(()=>{return}));if(response.status!==200||!validSnapshotPairToken(pairToken)||!validSnapshotArtifactToken(artifactToken)||response.headers.get("content-type")?.split(";")[0]!=="application/json")unavailable3();const acquired=validateAcquisition(await response.json(),repository,snapshot);assertCurrent();if(!reusable||reusable.artifactToken!==artifactToken){const artifact=await fetch(url,{method:"GET",redirect:"error",cache:"no-store",signal,headers:{...headers,accept:"application/gzip",[snapshotPairHeader]:pairToken}});assertCurrent();if(artifact.status===409){await artifact.body?.cancel();continue}if(!artifact.ok)throw dataTransportError(artifact.status,await artifact.json().catch(()=>{return}));if(artifact.status!==200||artifact.headers.get(snapshotPairHeader)!==pairToken||artifact.headers.get(snapshotArtifactHeader)!==artifactToken||!artifact.body||artifact.headers.get("content-type")?.split(";")[0]!=="application/gzip")unavailable3();const bytes=await new Response(artifact.body.pipeThrough(new DecompressionStream("gzip"))).arrayBuffer();base=validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)),repository,snapshot,acquired.snapshot.bodies,acquired.snapshot.timelines)}if(!base||base.version!==acquired.snapshot.version||(base.bodyCollections??[]).join("\x00")!==acquired.snapshot.bodies.join("\x00")||base.timelineCollections.join("\x00")!==acquired.snapshot.timelines.join("\x00")||base.catalogue.map((c)=>c.name).join("\x00")!==acquired.snapshot.collections.join("\x00")||reusable?.artifactToken===artifactToken&&reusable.snapshotId!==acquired.snapshot.id)unavailable3();const update=reusable?snapshotDifference(await store.changes(reusable),acquired.changes):{records:true,changes:true};update.records||=reusable?.artifactToken!==artifactToken;const published=acquired.changes.filter((c)=>c.publication);let version=base.version;if(reusable&&!update.records)version=reusable.version;else if(published.length){const digest=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify([base.version,published]))));version=`snapshot-${Array.from(digest,(byte)=>byte.toString(16).padStart(2,"0")).join("")}`}const materialized=materializeSnapshot(base,acquired.changes,version);assertCurrent();const installation=await store.install(partition,pairToken,materialized,acquired.changes,assertCurrent,acquired.snapshot.id,{token:artifactToken,base},update.records?undefined:reusable);return{installation,update}}unavailable3()}function snapshotListeners(url,authority,assertCurrent,invalidate,reconcile,connect){const listeners=new Set;let session,socket;let retry,expiry;let stopAuthority,stopCredentials;let delay=250;const stop=()=>{session?.abort();session=undefined;const prior=socket;socket=undefined;prior?.close();clearTimeout(retry);clearTimeout(expiry);retry=expiry=undefined;stopAuthority?.();stopAuthority=undefined;stopCredentials?.();stopCredentials=undefined};const current=()=>{try{assertCurrent();return true}catch{stop();return false}};const notify=(update)=>{if(!update.records&&!update.changes||!current())return;for(const listener of[...listeners]){if(!current())break;if(listeners.has(listener)){try{listener({...update})}catch{}}}};const start=()=>{if(!listeners.size||!current())return;const owned=new AbortController;session=owned;let dirty=false,running=false;const lostAuthority=()=>{invalidate();stop()};authority.signal.addEventListener("abort",lostAuthority,{once:true});stopAuthority=()=>authority.signal.removeEventListener("abort",lostAuthority);const armExpiry=()=>{clearTimeout(expiry);expiry=setTimeout(()=>{if(authority.refresh)restart();else lostAuthority()},Math.min(2147483647,Math.max(0,authority.expiresAt-Date.now())))};const later=()=>{retry=setTimeout(open,delay);delay=Math.min(30000,delay*2)};const reconnect=(connection)=>{if(session!==owned||!connection||socket!==connection)return;socket=undefined;connection.close();later()};const refresh=()=>{dirty=true;if(running)return;running=true;(async()=>{try{while(dirty&&session===owned&&current()){dirty=false;const update=await reconcile(owned.signal);if(session===owned&&current()){delay=250;notify(update)}}}catch(error){if(session!==owned)return;if(error instanceof DataOperationError&&["context_unavailable","unauthenticated","access_denied","not_found"].includes(error.code))lostAuthority();else reconnect(socket)}finally{running=false}})()};let opening=0;const open=()=>{retry=undefined;if(session!==owned||!current())return;if(authority.expiresAt<=Date.now()&&authority.refresh){const attempt=++opening;authority.refresh().then(()=>{if(session===owned&&opening===attempt&&current()&&authority.expiresAt>Date.now())open()}).catch(()=>{if(session===owned)current()});return}armExpiry();try{const connection=connect(url.replace(/^http/,"ws")+"/updates",[snapshotUpdatesProtocol,snapshotUpdatesCredentialPrefix+authority.headers.authorization.slice("Bearer ".length)]);socket=connection;connection.addEventListener("open",()=>{if(socket===connection&&session===owned)refresh()});connection.addEventListener("message",(event)=>{if(socket===connection&&session===owned&&event.data===snapshotUpdateHint)refresh()});connection.addEventListener("close",()=>reconnect(connection));connection.addEventListener("error",()=>reconnect(connection))}catch{if(session===owned)later()}};const restart=()=>{if(session!==owned||!current())return;const attempt=++opening;clearTimeout(retry);clearTimeout(expiry);const prior=socket;socket=undefined;prior?.close();Promise.resolve().then(()=>{if(session===owned&&opening===attempt)open()})};stopCredentials=authority.subscribe?.(restart);open()};return{notify,stop,subscribe(listener){assertCurrent();if(typeof listener!=="function")throw new DataOperationError("invalid_query");const owned=(update)=>listener(update);listeners.add(owned);if(listeners.size===1)start();return()=>{listeners.delete(owned);if(!listeners.size)stop()}}}}var invalidChange2=()=>{throw new DataOperationError("invalid_change",false,"unapplied")};var unsafe=(key)=>key.startsWith("$")||["__proto__","constructor","prototype"].includes(key);function capture5(value,depth=0){if(depth>32)return invalidChange2();if(Array.isArray(value))return dataArray(value).map((v)=>capture5(v,depth+1));if(value&&typeof value==="object")return Object.fromEntries(Object.entries(dataProperties(value)).map(([key,d])=>{if(unsafe(key))return invalidChange2();return[key,capture5(d.value,depth+1)]}));if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;return invalidChange2()}function captureTransaction(callback,installation){let active=true;const operations=[];try{if(typeof callback!=="function")return invalidChange2();const tx=new Proxy(Object.create(null),{get(_target,name){if(typeof name!=="string"||unsafe(name)||!installation.catalogue.some((c)=>c.name===name))return invalidChange2();return new Proxy(Object.create(null),{get(_target2,id2){const ref=`${name}/${String(id2)}`;if(typeof id2!=="string"||!validRecordRef(ref)||snapshotCollection(installation.catalogue,ref)?.name!==name)return invalidChange2();const schema2=installation.catalogue.find((c)=>c.name===name).schema;const builder=Object.fromEntries(["create","update","link","unlink","delete","setSignal","appendTimeline"].map((kind)=>[kind,(...args)=>{if(!active||args.length!==(kind==="delete"?0:1)||operations.length>=1e4)return invalidChange2();let table;if(kind==="setSignal"){const{asOf:_time,...signal}=captureSignal(args[0],new Date().toISOString());table={kind:"signal",ref,signal}}else if(kind==="appendTimeline")table={kind:"timeline",ref,entry:captureTimeline(args[0],true)};let fields3;if(kind!=="delete"&&!table){dataProperties(args[0]);fields3=capture5(args[0]);if(!Object.keys(fields3).length||Object.keys(fields3).some((key)=>unsafe(key)||kind!=="create"&&["id","type"].includes(key)))return invalidChange2();const definitions2=kind==="create"?schema2.fields:schema2.fields.filter((f)=>Object.hasOwn(fields3,f.name));if(kind==="link"||kind==="unlink"){for(const[key,value]of Object.entries(fields3)){const field=definitions2.find((f)=>f.name===key);const refs=typeof value==="string"?[value]:value;if(field?.kind!=="link"||!Array.isArray(refs)||!refs.length||!field.many&&refs.length!==1||refs.some((ref2)=>!validRecordRef(ref2))||new Set(refs).size!==refs.length)return invalidChange2();fields3[key]=field.many?refs:refs[0]}}validateRecordFields(fields3,definitions2,(ref2)=>snapshotCollection(installation.catalogue,ref2)?.schema.type,true);fields3=captureDataCreate({...fields3,$ref:ref}).fields}const prior=operations.filter((op)=>op.ref===ref);if(kind==="delete"&&prior.length||prior.some((op)=>op.kind==="delete")||kind==="create"&&prior.length)return invalidChange2();operations.push(table??{kind,ref,...fields3?{fields:fields3}:{}});return builder}]));return builder}})}});const result=callback(tx);if(result&&typeof result.then==="function"){Promise.resolve(result).catch(()=>{});return invalidChange2()}if(!operations.length)return invalidChange2();return operations}catch(error){if(error instanceof DataOperationError&&error.code==="invalid_change")throw error;return invalidChange2()}finally{active=false}}function captureSelection(input){try{const selected=dataArray(input).map((value)=>{const row=dataProperties(value),id2=row.id?.value,version=row.version?.value;if(typeof id2!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id2)||!dataVersion(version))return invalidChange2();return{id:id2,version}});if(!selected.length||selected.length>1e4||new Set(selected.map((c)=>c.id)).size!==selected.length)return invalidChange2();return selected}catch{return invalidChange2()}}var invalid10=()=>{throw new DataOperationError("invalid_query")};function captureSnapshotAll(query,options){const properties=dataProperties(options);if(Object.keys(properties).some((key)=>!["maxRecords","body","timeline"].includes(key))||properties.body&&properties.body.value!==true||properties.timeline&&properties.timeline.value!==true)return invalid10();return{...captureRecordsAll(query,{maxRecords:properties.maxRecords?.value}),body:properties.body?.value===true,timeline:properties.timeline?.value===true}}var safeName=(value)=>typeof value==="string"&&/^[a-z0-9][a-z0-9._-]{0,127}$/.test(value)&&!value.includes("..");function createSnapshotInitializer(resolve=resolveSnapshotContext,open=openSnapshotStore,connect=(url,protocols)=>new WebSocket(url,protocols)){const pending=new WeakMap;return async function initialize(input){const properties=dataProperties(input);const repository=properties.repository?.value,snapshot=properties.snapshot?.value;if(Object.keys(properties).sort().join(",")!=="repository,snapshot"||!safeName(repository)||!safeName(snapshot))return invalid10();const authority=await resolve();let invalidated=false;let stopLive;const assertCurrent=()=>{if(invalidated||authority.signal.aborted||!authority.isCurrent()||!authority.refresh&&authority.expiresAt<=Date.now()){invalidated=true;stopLive?.();throw new DataOperationError("context_unavailable")}};const assertAccess=()=>{assertCurrent();if(authority.expiresAt<=Date.now())throw new DataOperationError("unavailable",true)};const ensureAccess=async()=>{assertCurrent();if(authority.expiresAt<=Date.now())await authority.refresh?.();assertAccess()};assertCurrent();const partition=JSON.stringify([authority.endpoint,authority.memberId,authority.workspace,repository,snapshot]);let work=pending.get(authority.binding);if(!work){work=new Map;pending.set(authority.binding,work)}const url=`${authority.endpoint}/api/data/snapshots/${repository}/${snapshot}`;let cached;try{const store=await open();try{cached=await store.current(partition)}finally{store.close()}assertAccess();if(cached&&(cached.format!=="data-snapshot.v2"||!Array.isArray(cached.timelineCollections)||cached.repository!==repository||cached.name!==snapshot||!validSnapshotArtifactToken(cached.artifactToken)||cached.pairToken!==""&&!validSnapshotPairToken(cached.pairToken)))cached=undefined}catch(error){assertCurrent();if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}let installation;if(cached)installation=cached;else{let installing=work.get(partition);if(!installing){installing=(async()=>{const store=await open();try{return(await acquireSnapshot(store,partition,url,authority.headers,repository,snapshot,assertAccess,authority.signal,null)).installation}finally{store.close()}})();work.set(partition,installing);installing.finally(()=>{if(work.get(partition)===installing)work.delete(partition)}).catch(()=>{})}try{installation=await installing;assertAccess()}catch(error){assertCurrent();if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}}let tail=Promise.resolve(),writes=Promise.resolve();const serial=(work2)=>{const result=tail.then(work2);tail=result.catch(()=>{});return result};const write=(work2)=>{const result=serial(work2);writes=result.catch(()=>{});return result};const reconcile=(signal)=>serial(async()=>{await ensureAccess();const headers=authority.headers;const fenced=()=>{assertAccess();if(signal.aborted||headers.authorization!==authority.headers.authorization)throw new DataOperationError("unavailable",true)};fenced();const store=await open();try{const next=await acquireSnapshot(store,partition,url,headers,repository,snapshot,fenced,AbortSignal.any([signal,authority.signal]),installation);fenced();installation=next.installation;return next.update}finally{store.close()}});let initialRefresh;const live=snapshotListeners(url,authority,assertCurrent,()=>{invalidated=true},(signal)=>initialRefresh?initialRefresh.then(()=>({records:false,changes:false})):reconcile(signal),connect);stopLive=live.stop;if(cached){const refresh=reconcile(authority.signal);initialRefresh=refresh;refresh.then(live.notify).catch((error)=>{if(error instanceof DataOperationError&&["context_unavailable","unauthenticated","access_denied","not_found"].includes(error.code)){invalidated=true;live.stop()}}).finally(()=>{if(initialRefresh===refresh)initialRefresh=undefined})}const publications=new Map;const mutate=async(kind,payload,selected,publication)=>{await ensureAccess();if(publication?.complete)return[];const body={snapshotId:installation.snapshotId,...payload};checkDataRequestSize(body,2*1024*1024);let dispatched=false,applied=false;let store;try{store=await open();assertAccess();dispatched=true;const response=await fetch(`${authority.endpoint}/api/data/snapshots/${repository}/${snapshot}/changes/${kind}`,{method:"POST",redirect:"error",cache:"no-store",headers:{...authority.headers,"content-type":"application/json"},body:JSON.stringify(body)});if(!response.ok)throw dataTransportError(response.status,await response.json());applied=true;const value=await response.json();let mutation;if(kind==="discard"){if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length)throw new Error;mutation={kind,selected}}else if(kind==="transact")mutation={kind,changes:value};else{if(!value||!["changes,effects","changes,effects,records"].includes(Object.keys(value).sort().join(","))||!Array.isArray(value.changes)||value.changes.length>selected.length||value.changes.some((c)=>!selected.some((s)=>s.id===c.id&&s.version===c.version))||!Object.hasOwn(value,"records")&&value.changes.length!==selected.length)throw new Error;mutation={kind,selected,changes:value.changes,effects:value.effects,...Object.hasOwn(value,"records")?{records:value.records}:{}}}const before=await store.changes(installation);installation=await store.mutate(installation,mutation,assertAccess);assertAccess();const update=snapshotDifference(before,await store.changes(installation));if(kind==="publish")update.records=true;assertAccess();if(publication)publication.complete=true;live.notify(update);assertAccess();return structuredClone(mutation.changes??[])}catch(error){const failure=error instanceof DataOperationError?error:new DataOperationError("unavailable");const effect=applied?"applied":dispatched?failure.effect??"uncertain":"unapplied";if(effect!=="unapplied"&&(kind!=="publish"||effect==="applied")){invalidated=true;live.stop();await store?.invalidate(installation).catch(()=>{})}throw new DataOperationError(failure.code,effect==="uncertain"?kind==="publish":effect==="applied"?false:failure.retryable,effect,failure.component,failure.detail)}finally{store?.close()}};const query=async(query2,maxRecords,body=false,timeline=false)=>{const pinned=installation;await ensureAccess();const captured=captureRecordsQuery(query2);checkDataRequestSize({repository,operation:maxRecords===undefined?"records.query":"records.all",query:captured,...maxRecords===undefined?{}:{maxRecords}});let store;try{const selections=planIndexQuery(captured,pinned.catalogue);const checkTimeline=(collection,selection2)=>{if((timeline||selection2.timeline)&&!pinned.timelineCollections.includes(collection))return invalid10();for(const link of selection2.links)for(const[name,nested]of link.targets)checkTimeline(name,nested)};for(const{name,selection:selection2}of selections)checkTimeline(name,selection2);if(timeline){const include=(selection2)=>{selection2.$={...selection2.$,timeline:true};for(const[key,nested]of Object.entries(selection2))if(key!=="$")include(nested)};for(const selection2 of Object.values(captured))include(selection2)}store=await open();assertAccess();const result=await store.query(pinned,captured,maxRecords,body);assertAccess();return result}catch(error){assertAccess();if(error instanceof DataOperationError)throw error;if(error instanceof RecordValidationError)throw new DataOperationError("invalid_query");throw new DataOperationError("unavailable",true)}finally{store?.close()}};const localRead=async(operation)=>{await ensureAccess();let store;try{store=await open();assertAccess();const value=await operation(store);assertAccess();return value}catch(error){assertAccess();if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}finally{store?.close()}};const queryRecords=async(input2)=>{const captured=captureRecordsQuery(input2);return writes.then(()=>query(captured))};const transact=(callback)=>{try{assertCurrent();const operations=captureTransaction(callback,installation);return write(()=>mutate("transact",{operations}))}catch(error){return Promise.reject(error)}};const historyRead=(input2,operation)=>{const captured=captureHistoryInput(input2,operation);return writes.then(()=>{const pinned=installation;return localRead(async(store)=>{const base=await store.base(pinned);if(!base)throw new DataOperationError("unavailable",true);return readSnapshotHistory(base.history,captured,operation)})})};const history={records:async(input2)=>await historyRead(input2,"records"),changes:async(input2)=>await historyRead(input2,"changes")};return{subscribe:live.subscribe,transact,history,changes:{list:()=>writes.then(()=>{const pinned=installation;return localRead((store)=>store.changes(pinned))}),discard:async(input2)=>{const selected=captureSelection(input2);await write(()=>mutate("discard",{selected},selected))},publish:async(input2,options)=>{const selected=captureSelection(input2);const metadata=captureDataChangeOptions(options);if(metadata.source)return invalidChange2();const key=JSON.stringify([selected.slice().sort((a,b)=>a.id.localeCompare(b.id)),metadata]);let publication=publications.get(key);if(!publication){publication={id:crypto.randomUUID()};publications.set(key,publication)}await write(()=>mutate("publish",{selected,...metadata,publicationId:publication.id},selected,publication))}},records:{read:async(ref,...extra)=>{if(typeof ref!=="string"||extra.length>1)return Promise.reject(new DataOperationError("invalid_query"));const{body,timeline}=captureRecordsReadOptions(extra[0]);const[captured]=captureRecordsReadRefs([ref]);if(!snapshotCollection(installation.catalogue,captured))return Promise.reject(new DataOperationError("invalid_query"));return writes.then(()=>{const pinned=installation;return localRead(async(store)=>{if(timeline&&!pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue,captured).name))return invalid10();const record2=await store.read(pinned,captured);if(!record2)return record2;const{$body,$timeline,...structured}=record2;return{...structured,...body&&$body!==undefined?{$body}:{},...timeline?{$timeline}:{}}})})},query:queryRecords,...recordPagination(queryRecords),all:async(input2,options)=>{const captured=captureSnapshotAll(input2,options);return writes.then(()=>query(captured.query,captured.maxRecords,captured.body,captured.timeline))}}}}}var initializeSnapshot=createSnapshotInitializer();var genericData={init:initializeSnapshot,repository(repository){async function send(input){const context=await resolveDataContext();const envelope={repository,...input};const changing="operation"in input&&["changes.validate","changes.apply","changes.publish"].includes(String(input.operation));checkDataRequestSize(envelope,"local"in context&&changing?LOCAL_DATA_CHANGE_REQUEST_LIMIT:DATA_REQUEST_LIMIT);if("local"in context)return await context.local("data/query",envelope);try{const response=await fetch(context.url,{method:"POST",redirect:"error",cache:"no-store",headers:{"content-type":"application/json",...context.headers},body:JSON.stringify(envelope)});const result=await response.json();if(!response.ok){throw dataTransportError(response.status,result)}return result}catch(error){if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}}async function read(input,options){const refs=captureRecordsReadRefs(typeof input==="string"?[input]:input);const captured=captureRecordsReadOptions(options);const result=await send({operation:"records.read",refs,...options===undefined?{}:{options:captured}});return typeof input==="string"?result.records[0]:result}const queryRecords=(query)=>send({operation:"records.query",query});return{collections:{list:()=>send({operation:"collections.list"}),schema:(name)=>send({operation:"collections.schema",name})},records:{read,query:queryRecords,...recordPagination(queryRecords),all:async(query,options)=>send({operation:"records.all",...captureRecordsAll(query,options)}),search:async(query,options)=>send({operation:"records.search",...captureRecordsSearchInput(query,options)})},changes(options){const metadata=captureDataChangeOptions(options);let updates=[],creates=[],deletes=[],applyId;let method;let pending,confirmed;const assertMutable=()=>{if(applyId)throw new DataOperationError("invalid_change",false,"unapplied")};const snapshot=(nextUpdates=updates,nextCreates=creates,nextDeletes=deletes)=>{const{updates:updates2,creates:creates2,deletes:deletes2}=captureDataChanges(nextUpdates,nextCreates,nextDeletes);const input={...metadata,updates:updates2,...creates2.length?{creates:creates2}:{},...deletes2.length?{deletes:deletes2}:{}};checkDataRequestSize({repository,operation:"changes.apply",...input,applyId:applyId??"00000000-0000-4000-8000-000000000000"},LOCAL_DATA_CHANGE_REQUEST_LIMIT);return input};const write=(operation)=>{if(method&&method!==operation)return Promise.reject(new DataOperationError("invalid_change",false,"unapplied"));if(confirmed)return Promise.resolve(structuredClone(confirmed));if(!pending){let captured;try{captured=snapshot()}catch(error){return Promise.reject(error)}method=operation;applyId??=routineTransport()?.key("data")??crypto.randomUUID();pending=send({operation,...captured,applyId}).then((result)=>{confirmed=structuredClone(result);return result}).catch((error)=>{if(error instanceof DataOperationError&&error.effect!==undefined)throw error;if(error instanceof DataOperationError)throw explainDataValidation(new DataOperationError(error.code,error.retryable,error.effect??(["unavailable","apply_pending"].includes(error.code)?"uncertain":"unapplied"),error.component,error.detail),error.message,error.detail);throw new DataOperationError("unavailable",true,"uncertain")}).finally(()=>{pending=undefined})}return pending.then((result)=>structuredClone(result))};const authorTable=(ref,patch)=>{assertMutable();if(!validRecordRef(ref))throw new DataOperationError("invalid_change",false,"unapplied");const nextUpdates=structuredClone(updates),nextCreates=structuredClone(creates);const creation=nextCreates.find((row)=>row.ref===ref);let target=creation??nextUpdates.find((row)=>row.ref===ref);if(!target){target={ref,set:{}};nextUpdates.push(target)}if(patch.signals)target.signals=[...target.signals??[],...patch.signals];if(patch.timeline)target.timeline=[...target.timeline??[],...patch.timeline];snapshot(nextUpdates,nextCreates,deletes);updates=nextUpdates;creates=nextCreates};return{create(record2){assertMutable();const next=[...creates,captureDataCreate(record2)];snapshot(updates,next,deletes);creates=next},update(record2,set){assertMutable();const edit=captureDataUpdate(record2,set),prior=updates.find((row)=>row.ref===record2);const next=prior&&!Object.keys(prior.set).length&&prior.body===undefined?updates.map((row)=>row===prior?{...prior,...edit}:row):[...updates,edit];snapshot(next,creates,deletes);updates=next},setSignal(ref,input){authorTable(ref,{signals:[captureSignal(input,new Date().toISOString())]})},appendTimeline(ref,input){authorTable(ref,{timeline:[captureTimeline(input,true)]})},delete(record2){assertMutable();const next=[...deletes,captureDataDelete(record2)];snapshot(updates,creates,next);deletes=next},async validate(){await send({operation:"changes.validate",...snapshot()})},apply:()=>write("changes.apply"),publish:()=>write("changes.publish")}}}}};var data=genericData;async function hostedContent(url,init,parent,upstream=fetch,check=async()=>{},failure){const delivery=new AbortController;const abort=()=>delivery.abort(parent.reason);parent.addEventListener("abort",abort,{once:true});if(parent.aborted)abort();const detach=()=>parent.removeEventListener("abort",abort);try{const response=await upstream(url,{...init,signal:delivery.signal});try{await check();if(delivery.signal.aborted)throw failure?.()??new FileOperationError("unavailable",503,true)}catch(error){response.body?.cancel().catch(()=>{});throw error}if(!response.body){detach();return response}const source=response.body;let reader;let settled=false;let output;const cancel=async(reason)=>{if(settled)return;settled=true;detach();delivery.signal.removeEventListener("abort",stop);delivery.abort(reason);try{await(reader?reader.cancel(reason):source.cancel(reason))}catch(error){if(error!==delivery.signal.reason&&!(error instanceof Error&&error.name==="AbortError"))throw error}finally{reader?.releaseLock()}};const stop=()=>{if(settled)return;const error=failure?.()??delivery.signal.reason;cancel(error).catch(()=>{});output.error(error)};const body=new ReadableStream({start(controller){output=controller;delivery.signal.addEventListener("abort",stop,{once:true});if(delivery.signal.aborted)stop()},async pull(controller){try{await check();if(settled)return;reader??=source.getReader();const{done,value}=await reader.read();await check();if(settled)return;if(done){settled=true;detach();delivery.signal.removeEventListener("abort",stop);reader.releaseLock();controller.close()}else controller.enqueue(value)}catch(error){if(settled)return;controller.error(failure?.()??error);await cancel(error).catch(()=>{})}},cancel},{highWaterMark:0});const wrapped=new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers});for(const key of["url","redirected","type"])Object.defineProperty(wrapped,key,{value:response[key]});return wrapped}catch(error){detach();delivery.abort(error);throw error}}var MAX_BYTES=16*1024*1024;var PART_BYTES=8*1024*1024;var METADATA_BYTES=4096;var RESULT_BYTES=16*1024;var CONTROL_RESULT_BYTES=128*1024;var TIMEOUT_MS=30000;var MAX_ACTIVE=4;var ATTEMPTS=2;var active=0;var waiters=[];var invalid11=()=>new FileOperationError("invalid_input",400);var unavailable4=()=>new FileOperationError("unavailable",503,true);var failures={400:["invalid_input","unsupported_context"],401:["unauthenticated"],403:["access_denied"],404:["not_found"],405:["method_not_allowed"],409:["conflict","local_only"],413:["request_too_large"],429:["capacity"],503:["integrity","unavailable"]};function heldSlot(){let held=true;return()=>{if(!held)return;held=false;for(;;){const waiter=waiters.shift();if(!waiter){active--;return}if(!waiter.waiting)continue;waiter.waiting=false;waiter.signal?.removeEventListener("abort",waiter.abort);waiter.resolve(heldSlot());return}}}async function acquireSlot(signal){if(signal?.aborted)throw unavailable4();if(active<MAX_ACTIVE){active++;return heldSlot()}return new Promise((resolve,reject)=>{const waiter={signal,waiting:true,resolve,reject,abort(){if(!waiter.waiting)return;waiter.waiting=false;const index=waiters.indexOf(waiter);if(index!==-1)waiters.splice(index,1);reject(unavailable4())}};waiters.push(waiter);signal?.addEventListener("abort",waiter.abort,{once:true});if(signal?.aborted)waiter.abort()})}async function boundedBytes(stream,limit,signal){if(!stream)return new Uint8Array;const reader=stream.getReader();const bytes=new Uint8Array(limit);let size=0;const cancel=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",cancel,{once:true});if(signal?.aborted)cancel();try{for(;;){const{done,value}=await reader.read();if(signal?.aborted)throw unavailable4();if(done)break;if(!(value instanceof Uint8Array))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_bytes"});size+=value.byteLength;if(size>limit)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:limit,receivedBytes:size,receivedAtLeast:true});bytes.set(value,size-value.byteLength)}}catch(error){cancel();throw error}finally{signal?.removeEventListener("abort",cancel);reader.releaseLock()}return bytes.slice(0,size)}async function timed(work,parent,timeout=TIMEOUT_MS){const controller=new AbortController;let timer;let abort;const expiry=new Promise((_,reject)=>{abort=()=>{controller.abort();reject(unavailable4())};timer=setTimeout(abort,timeout);parent?.addEventListener("abort",abort,{once:true});if(parent?.aborted)abort()});try{return await Promise.race([work(controller.signal),expiry])}finally{clearTimeout(timer);parent?.removeEventListener("abort",abort)}}async function result(response,maximum=RESULT_BYTES){try{const bytes=await boundedBytes(response.body,maximum);return JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))}catch{throw unavailable4()}}async function send(suffix,init,descriptor,initial,parent){const original=initial;const checkCurrent=(context=original)=>{if(parent?.aborted)throw unavailable4();if(!original.isCurrent()||context.url!==original.url)throw new FileOperationError("unsupported_context",400)};for(let attempt=0;attempt<ATTEMPTS;attempt++){checkCurrent();const context=await resolveFilesContext();checkCurrent(context);try{const response=context.localFiles?await context.localFiles(suffix,init,parent):await(async()=>{const url=`${context.url}${suffix}`;const request2={...init,signal:parent,headers:{...context.headers,...init.headers},redirect:"error",cache:"no-store"};return descriptor?fetch(url,request2):hostedContent(url,request2,parent)})();if(!response.ok){const value2=await result(response);const error=value2&&typeof value2==="object"&&"error"in value2?value2.error:undefined;const received=error&&typeof error==="object"&&"code"in error?error.code:undefined;const code=failures[response.status]?.find((code2)=>code2===received);throw code?new FileOperationError(code,response.status,code==="capacity"||code==="unavailable",parseFileErrorDetail(error?.detail)):unavailable4()}if(response.status!==200){response.body?.cancel().catch(()=>{});throw unavailable4()}try{checkCurrent()}catch(error){response.body?.cancel().catch(()=>{});throw error}if(!descriptor)return response;const value=await result(response,descriptor==="control"?CONTROL_RESULT_BYTES:RESULT_BYTES);if(descriptor==="control"){checkCurrent();return value}let parsed;if(descriptor==="enrichment"){if(!value||typeof value!=="object"||Array.isArray(value))throw unavailable4();const{name,...metadata}=value;if(!safeEnrichmentName(name))throw unavailable4();parsed={name,...parseEnrichmentDescriptor(metadata)}}else parsed=parseFileDescriptor(value);checkCurrent();return parsed}catch(error){const failure=error instanceof FileOperationError?error:unavailable4();if(init.body instanceof ReadableStream||!failure.retryable||attempt+1===ATTEMPTS)throw failure}}throw unavailable4()}function idPath(id2){if(typeof id2!=="string"||!FILE_ID_PATTERN.test(id2))throw invalid11();return`/${id2}`}async function multipartCreate(input,metadata,exchange,release,upload,expectedSha256){const route=upload?`${idPath(upload.file.id)}/upload/multipart`:"/multipart";let ticket;let reader;let chunk,offset=0;const receipts=[];const pending=new Set;const request2=(work,timeout=TIMEOUT_MS)=>timed((signal)=>{const task=work(signal);pending.add(task);task.then(()=>pending.delete(task),()=>pending.delete(task));return task},undefined,timeout);const control=(body)=>({method:"POST",headers:{"content-type":"application/json",...ticket?{"x-os-transfer":ticket}:{}},body:JSON.stringify(body)});try{const startRequest=control(upload?.file??metadata);if(expectedSha256)startRequest.headers["x-os-original-sha256"]=expectedSha256;const start=await request2((signal)=>exchange(`${route}/start`,startRequest,"control",signal));if(!start||typeof start!=="object"||Array.isArray(start))throw unavailable4();const session=start;if(Object.keys(session).sort().join(",")!=="partBytes,ticket"||session.partBytes!==PART_BYTES||typeof session.ticket!=="string"||!session.ticket||session.ticket.length>64*1024)throw unavailable4();ticket=session.ticket;if(input.file instanceof ReadableStream)reader=input.file.getReader();let lastProgress=Date.now();const next=async()=>{try{if(Date.now()-lastProgress>=TIMEOUT_MS)throw unavailable4();const value=await request2(()=>reader.read(),Math.max(1,TIMEOUT_MS-(Date.now()-lastProgress)));if(value.value?.byteLength)lastProgress=Date.now();return value}catch(error){await reader.cancel(error).catch(()=>{});throw error}};for(let sent=0,partNumber=1;sent<metadata.size||metadata.size===0&&partNumber===1;partNumber++){const length=Math.min(PART_BYTES,metadata.size-sent);let part;if(input.file instanceof Uint8Array)part=new Uint8Array(input.file.subarray(sent,sent+length));else if(input.file instanceof Blob){const slice=input.file.slice(sent,sent+length);part=new Uint8Array(await request2(()=>slice.arrayBuffer()))}else{part=new Uint8Array(length);let filled=0;while(filled<length){if(!chunk||offset===chunk.byteLength){chunk=undefined;offset=0;const value2=await next();if(value2.done)throw invalid11();if(!(value2.value instanceof Uint8Array))throw invalid11();chunk=value2.value;if(chunk.byteLength>metadata.size-sent-filled)throw invalid11()}const take=Math.min(length-filled,chunk.byteLength-offset);part.set(chunk.subarray(offset,offset+take),filled);filled+=take;offset+=take;if(offset===chunk.byteLength){chunk=undefined;offset=0}}}if(part.byteLength!==length)throw invalid11();if(reader&&sent+length===metadata.size){lastProgress=Date.now();for(;;){const value2=await next();if(value2.done)break;if(!(value2.value instanceof Uint8Array)||value2.value.byteLength)throw invalid11()}}const value=await request2((signal)=>exchange(`${route}/part`,{method:"POST",headers:{"content-type":"application/octet-stream","x-os-transfer":ticket,"x-os-part":String(partNumber)},body:part.buffer},"control",signal));part=undefined;const receipt=value;if(!receipt||typeof receipt!=="object"||Object.keys(receipt).sort().join(",")!=="etag,partNumber"||receipt.partNumber!==partNumber||typeof receipt.etag!=="string"||!receipt.etag||receipt.etag.length>256||/[\u0000-\u001f\u007f]/.test(receipt.etag))throw unavailable4();receipts.push({partNumber,etag:receipt.etag});sent+=length;lastProgress=Date.now()}if(upload)for(const name of Object.keys(upload.file.enrichments)){const bytes=await request2(()=>upload.enrichment(name));if(bytes.byteLength!==upload.file.enrichments[name].size||bytes.byteLength>MAX_BYTES)throw invalid11();await request2((signal)=>exchange(`${route}/enrichments/${encodeURIComponent(name)}`,{method:"POST",headers:{"content-type":"application/octet-stream","x-os-transfer":ticket},body:bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)},"control",signal))}await upload?.beforeComplete();const completion=control({parts:receipts});if(new TextEncoder().encode(completion.body).byteLength>128*1024)throw unavailable4();const completed2=parseFileDescriptor(await request2((signal)=>exchange(`${route}/complete`,completion,true,signal),TIMEOUT_MS+Math.ceil(metadata.size/(1024*1024))*1000));if(!upload){const acknowledged=await request2((signal)=>exchange(`${route}/acknowledge`,control(completed2),"control",signal));if(!acknowledged||typeof acknowledged!=="object"||Object.keys(acknowledged).join(",")!=="acknowledged"||acknowledged.acknowledged!==true)throw unavailable4()}return completed2}catch(error){if(reader)await reader.cancel(error).catch(()=>{});if(ticket)await request2((signal)=>exchange(`${route}/abort`,control({}),"control",signal)).catch(()=>{});throw error instanceof FileOperationError?error:unavailable4()}finally{chunk=undefined;reader?.releaseLock();if(pending.size)Promise.allSettled([...pending]).then(release);else release()}}async function operation(work,initial,parent){const context=initial??await resolveFilesContext();const signal=context.signal&&parent?AbortSignal.any([context.signal,parent]):context.signal??parent;const release=await acquireSlot(signal);const execute=async(signal2)=>{try{return await work(context,signal2)}finally{release()}};if(context.localFiles)return execute(signal??new AbortController().signal);return timed(execute,signal).catch((error)=>{throw error instanceof FileOperationError?error:unavailable4()})}function contentPath(id2,name){const path=idPath(id2);if(name===undefined)return`${path}/content`;if(!safeEnrichmentName(name))throw invalid11();return`${path}/enrichments/${encodeURIComponent(name)}/content`}async function read(id2,names){const context=await resolveFilesContext();idPath(id2);if(names===undefined||typeof names==="string"){const path=contentPath(id2,names);return operation((context2,signal)=>send(path,{method:"GET"},false,context2,signal),context)}if(!Array.isArray(names))throw invalid11();const distinct=[];const seen=new Set;for(const name of names){if(typeof name!=="string"||!safeEnrichmentName(name))throw invalid11();if(seen.has(name))continue;if(seen.size===16)throw invalid11();seen.add(name);distinct.push(name)}const paths=distinct.map((name)=>contentPath(id2,name));return timed(async(parent)=>{const responses={};try{for(let i=0;i<paths.length;i++){const response=await operation((context2,signal)=>send(paths[i],{method:"GET"},false,context2,signal),context,parent);Object.defineProperty(responses,distinct[i],{value:response,enumerable:true})}if(!context.isCurrent())throw new FileOperationError("unsupported_context",400);return responses}catch(error){for(const response of Object.values(responses))response.body?.cancel().catch(()=>{});throw error}})}var files={async update(id2,changes){const path=idPath(id2),body=JSON.stringify(parseFileUpdate(changes));return operation(async(context,signal)=>{const file2=await send(path,{method:"PATCH",headers:{"content-type":"application/json"},body},true,context,signal);if(file2.id!==id2)throw unavailable4();return file2})},async upload(id2){return operation(async(context,signal)=>{const file2=await send(`${idPath(id2)}/upload`,{method:"POST"},true,context,signal);if(file2.id!==id2)throw unavailable4();return file2})},async create(input,options){const context=await resolveFilesContext();if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some((key)=>!["file","size","path","name","storage","mediaType"].includes(key))||options!==undefined&&(!options||typeof options!=="object"||Array.isArray(options)||Object.keys(options).some((key)=>key!=="requestKey")))throw invalid11();const blob=input.file instanceof Blob;const array2=input.file instanceof Uint8Array;const stream=input.file instanceof ReadableStream;if(!blob&&!array2&&!stream)throw invalid11();const intrinsic=blob?input.file.size:array2?input.file.byteLength:undefined;if(intrinsic!==undefined&&input.size!==undefined&&input.size!==intrinsic){if(!Number.isSafeInteger(input.size)||input.size<0)throw new FileOperationError("invalid_input",400,false,{reason:"invalid_size"});throw new FileOperationError("invalid_input",400,false,{reason:"size_mismatch",expectedBytes:input.size,receivedBytes:intrinsic})}let name=input.name;if(name===undefined&&blob&&"name"in input.file&&typeof input.file.name==="string"){name=typeof globalThis.File!=="undefined"&&input.file instanceof globalThis.File?input.file.name:input.file.name.split(/[\\/]/).at(-1)}const mediaType=declaredOriginalMediaType(input.mediaType===undefined?blob&&input.file.type?input.file.type:"application/octet-stream":input.mediaType);const metadata=parseFileCreateMetadata({name,size:intrinsic??input.size,path:input.path,storage:input.storage,mediaType,requestKey:options?.requestKey===undefined?routineTransport()?.key("files")??crypto.randomUUID():options.requestKey},FILE_ORIGINAL_MAX_BYTES);if(!context.local&&!context.localFiles&&metadata.storage==="local")throw new FileOperationError("unsupported_context",400);const header=encodeURIComponent(JSON.stringify(metadata));if(new TextEncoder().encode(header).byteLength>METADATA_BYTES)throw invalid11();const release=await acquireSlot(context.signal);if(context.localFiles&&!routineTransport()&&metadata.size>MAX_BYTES){try{const signal=context.signal??new AbortController().signal;const file2=input.file;let offset=0;const body=file2 instanceof Blob?context.signal?file2:file2.stream():file2 instanceof ReadableStream?file2:new ReadableStream({pull(controller){if(offset===file2.byteLength){controller.close();return}const end=Math.min(offset+256*1024,file2.byteLength);controller.enqueue(file2.subarray(offset,end));offset=end}},{highWaterMark:0});return await send("",{method:"POST",headers:{"content-type":"application/octet-stream","x-os-file":header},body},true,context,signal)}finally{release()}}if(metadata.size>MAX_BYTES)return multipartCreate(input,metadata,(suffix,init,kind,signal)=>kind===true?send(suffix,init,true,context,signal):send(suffix,init,"control",context,signal),release);return timed(async(signal)=>{try{const bytes=array2?new Uint8Array(input.file):await boundedBytes(blob?input.file.stream():input.file,metadata.size,signal);if(bytes.byteLength!==metadata.size)throw new FileOperationError("invalid_input",400,false,{reason:"size_mismatch",expectedBytes:metadata.size,receivedBytes:bytes.byteLength});if(signal.aborted)throw unavailable4();return await send("",{method:"POST",headers:{"content-type":"application/octet-stream","x-os-file":header},body:bytes.buffer},true,context,signal)}finally{release()}},context.signal).catch((error)=>{throw error instanceof FileOperationError?error:unavailable4()})},async enrich(input){const context=await resolveFilesContext();if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some((key)=>!["file","name","content","mediaType","replace"].includes(key))||typeof input.content!=="string"&&!(input.content instanceof Uint8Array))throw invalid11();const path=`${idPath(input.file)}/enrichments`;if(typeof input.content==="string"?input.content.length>MAX_BYTES:input.content.byteLength>MAX_BYTES)throw new FileOperationError("request_too_large",413);return operation(async(context2,signal)=>{let bytes;if(typeof input.content==="string"){const buffer=new Uint8Array(Math.min(MAX_BYTES,input.content.length*3));const encoded=new TextEncoder().encodeInto(input.content,buffer);if(encoded.read!==input.content.length)throw new FileOperationError("request_too_large",413);bytes=buffer.slice(0,encoded.written)}else bytes=new Uint8Array(input.content);const metadata=parseFileEnrichMetadata({name:input.name,size:bytes.byteLength,...input.mediaType===undefined?{}:{mediaType:input.mediaType},...input.replace===undefined?{}:{replace:input.replace}},MAX_BYTES);const header=encodeURIComponent(JSON.stringify(metadata));if(new TextEncoder().encode(header).byteLength>METADATA_BYTES)throw invalid11();const result2=await send(path,{method:"POST",headers:{"content-type":"application/octet-stream","x-os-enrichment":header},body:bytes.buffer},"enrichment",context2,signal);if(result2.name!==metadata.name)throw unavailable4();return result2},context)},async get(id2){return operation((context,signal)=>send(idPath(id2),{method:"GET"},true,context,signal))},read};var ROUTINE_CONNECTION_CREDENTIALS_ENV="OS_ROUTINE_CONNECTION_CREDENTIALS";function parseRoutineConnectionNames(value){if(!Array.isArray(value)||value.some((name)=>typeof name!=="string"||!/^(gmail|airtable|dropbox|outlook|sharepoint)\/[a-z0-9][a-z0-9-]{0,62}$/.test(name))||new Set(value).size!==value.length)throw new Error("Invalid routine connections");return value}var connectionUuid=(v)=>typeof v==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(v);function runtimeConnection(lease){switch(lease.provider){case"outlook":return{id:`outlook/${lease.name}`,provider:lease.provider,name:lease.name,mailboxEmail:lease.mailboxEmail,accessToken:lease.accessToken,expiresAt:lease.expiresAt};case"sharepoint":return{id:`sharepoint/${lease.name}`,provider:lease.provider,name:lease.name,siteId:lease.siteId,siteUrl:lease.siteUrl,accessToken:lease.accessToken,expiresAt:lease.expiresAt};case"gmail":return{id:`gmail/${lease.name}`,provider:lease.provider,name:lease.name,accountEmail:lease.accountEmail,scopes:[...lease.scopes],accessToken:lease.accessToken,expiresAt:lease.expiresAt};case"airtable":return{id:`airtable/${lease.name}`,provider:lease.provider,name:lease.name,baseId:lease.baseId,accessToken:lease.accessToken,runExpiresAt:lease.runExpiresAt};case"dropbox":return{id:`dropbox/${lease.name}`,provider:lease.provider,name:lease.name,accountId:lease.accountId,access:lease.access,rootPath:lease.rootPath,scopes:[...lease.scopes],accessToken:lease.accessToken,expiresAt:lease.expiresAt}}}function parseConnectionLease(raw,now=Date.now()){const v=raw;if(!v||typeof v!=="object"||Array.isArray(v)||!connectionUuid(v.connectionId)||!connectionUuid(v.runId)||typeof v.name!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(v.name)||typeof v.accessToken!=="string"||!/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(v.accessToken))throw new Error("Invalid connection credential");if(v.provider==="outlook"||v.provider==="sharepoint"){const targetValid=v.provider==="outlook"?Object.keys(v).sort().join(",")==="accessToken,connectionId,expiresAt,mailboxEmail,name,provider,runId"&&validMicrosoftMailbox(v.mailboxEmail):Object.keys(v).sort().join(",")==="accessToken,connectionId,expiresAt,name,provider,runId,siteId,siteUrl"&&typeof v.siteUrl==="string"&&canonicalSharePointSiteUrl(v.siteUrl)===v.siteUrl&&validSharePointSiteId(v.siteId,v.siteUrl);if(!targetValid||typeof v.expiresAt!=="string"||!Number.isFinite(Date.parse(v.expiresAt))||Date.parse(v.expiresAt)<=now||Date.parse(v.expiresAt)>now+3600000)throw new Error("Invalid connection credential");return v}if(v.provider==="gmail"){if(Object.keys(v).sort().join(",")!=="accessToken,accountEmail,connectionId,expiresAt,name,provider,runId,scopes"||typeof v.accountEmail!=="string"||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.accountEmail)||!validGoogleScopes(v.scopes)||typeof v.expiresAt!=="string"||!Number.isFinite(Date.parse(v.expiresAt))||Date.parse(v.expiresAt)<=now||Date.parse(v.expiresAt)>now+3600000)throw new Error("Invalid connection credential");return v}if(v.provider==="airtable"&&Object.keys(v).sort().join(",")==="accessToken,baseId,connectionId,name,provider,runExpiresAt,runId"&&typeof v.baseId==="string"&&/^app[A-Za-z0-9]+$/.test(v.baseId)&&typeof v.runExpiresAt==="string"&&Number.isFinite(Date.parse(v.runExpiresAt))&&Date.parse(v.runExpiresAt)>now&&Date.parse(v.runExpiresAt)<=now+15*60000)return v;if(v.provider==="dropbox"&&Object.keys(v).sort().join(",")==="access,accessToken,accountId,connectionId,expiresAt,name,provider,rootPath,runId,scopes"&&typeof v.accountId==="string"&&/^dbid:[A-Za-z0-9_-]{1,128}$/.test(v.accountId)&&v.access==="full_dropbox"&&validDropboxRootPath(v.rootPath)&&validDropboxFileScopes(v.scopes)&&typeof v.expiresAt==="string"&&Number.isFinite(Date.parse(v.expiresAt))&&Date.parse(v.expiresAt)>now&&Date.parse(v.expiresAt)<=now+14400000)return v;throw new Error("Invalid connection credential")}class AirtableOperationError extends Error{effect;receipts;constructor(message,effect="unapplied",receipts=[]){super(message);this.effect=effect;this.receipts=receipts;this.name="AirtableOperationError"}}var recordId=(v)=>typeof v==="string"&&/^rec[A-Za-z0-9]+$/.test(v);var tableId=(v)=>typeof v==="string"&&/^tbl[A-Za-z0-9]+$/.test(v);function fail6(message){throw new AirtableOperationError(message)}function object7(v){if(!v||typeof v!=="object"||Array.isArray(v)||![null,Object.prototype].includes(Object.getPrototypeOf(v)))fail6("Invalid Airtable data");return v}function keys5(v,allowed,required=allowed){if(Object.keys(v).some((k)=>!allowed.includes(k))||required.some((k)=>!Object.hasOwn(v,k)))fail6("Invalid Airtable input")}function text3(v){return typeof v==="string"&&v.length>0&&v.length<=1024}function fields3(v,nonempty=false){const result2=object7(v);if(nonempty&&!Object.keys(result2).length||Object.keys(result2).some((k)=>!text3(k)))fail6("Invalid Airtable fields");try{return serializable(result2)}catch{return fail6("Invalid Airtable fields")}}function record2(v){const r=object7(v);if(!recordId(r.id)||r.createdTime!==undefined&&(typeof r.createdTime!=="string"||!Number.isFinite(Date.parse(r.createdTime))))fail6("Malformed Airtable record");return{id:r.id,...r.createdTime===undefined?{}:{createdTime:r.createdTime},fields:fields3(r.fields)}}function equal(a,b){if(a===b)return true;if(!a||!b||typeof a!=="object"||typeof b!=="object"||Array.isArray(a)!==Array.isArray(b))return false;const left=Object.keys(a),right=Object.keys(b);return left.length===right.length&&left.every((k)=>Object.hasOwn(b,k)&&equal(a[k],b[k]))}function createConnections(transport){return{async get(){throw new Error("Connection unavailable")},airtable(name){if(typeof name!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name))fail6("Invalid Airtable connection name");const call=(operation2,input)=>transport(name,operation2,input);return{tables:{list:async()=>await call("tables.list",{})},records:{list:async(input)=>await call("records.list",input),get:async(input)=>await call("records.get",input),create:async(input)=>await call("records.create",input),update:async(input)=>await call("records.update",input),delete:async(input)=>await call("records.delete",input)}}}}}async function executeAirtableOperation(authority,operation2,raw,options={}){const{name,baseId,accessToken}=authority;if(!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)||!/^app[A-Za-z0-9]+$/.test(baseId)||!/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(accessToken))fail6("Airtable connection unavailable");let input;try{input=object7(serializable(raw))}catch{return fail6("Invalid Airtable input")}const mutation=["records.create","records.update","records.delete"].includes(operation2);const receipt=(ids2)=>({provider:"airtable",connection:`airtable/${name}`,baseId,table:input.table,operation:operation2.slice(8),records:ids2.map((id2)=>({id:id2}))});async function request2(path2,init={},write=false){let response;try{response=await(options.fetch??fetch)(`https://api.airtable.com/v0/${path2}`,{...init,headers:{authorization:`Bearer ${accessToken}`,"content-type":"application/json"},redirect:"manual",signal:options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})}catch{throw new AirtableOperationError("Airtable request acknowledgment unavailable",write?"uncertain":"unapplied")}if(!response.ok){await response.body?.cancel().catch(()=>{});throw new AirtableOperationError("Airtable request rejected",write&&(response.status>=500||response.status===408||response.status<400)?"uncertain":"unapplied")}try{if(!response.headers.get("content-type")?.toLowerCase().includes("application/json"))throw new Error;const value=object7(await response.json());const safe=serializable(value);if(Object.hasOwn(value,"error")||JSON.stringify(safe).includes(accessToken))throw new Error;return value}catch{throw new AirtableOperationError("Malformed Airtable acknowledgment",write?"uncertain":"unapplied")}}if(operation2==="tables.list"){keys5(input,[]);const tables=[],seen=new Set;let offset;do{const query2=new URLSearchParams(offset?{offset}:{});const page=await request2(`meta/bases/${baseId}/tables?${query2}`);if(!Array.isArray(page.tables))fail6("Malformed Airtable tables");for(const value of page.tables){const t=object7(value);if(!tableId(t.id)||!text3(t.name)||!text3(t.primaryFieldId)||!Array.isArray(t.fields)||tables.some((existing)=>existing.id===t.id))fail6("Malformed Airtable table");const metadata=t.fields.map((value2)=>{const f=object7(value2);if(typeof f.id!=="string"||!/^fld[A-Za-z0-9]+$/.test(f.id)||!text3(f.name)||!text3(f.type))fail6("Malformed Airtable field");return{id:f.id,name:f.name,type:f.type,...f.options===undefined?{}:{options:serializable(f.options)}}});if(!metadata.some((f)=>f.id===t.primaryFieldId)||new Set(metadata.map((f)=>f.id)).size!==metadata.length)fail6("Malformed Airtable fields");tables.push({id:t.id,name:t.name,primaryFieldId:t.primaryFieldId,fields:metadata})}offset=nextOffset(page.offset,seen)}while(offset);return tables}if(!text3(input.table)||input.table==="."||input.table==="..")fail6("Invalid Airtable table");if(mutation&&!tableId(input.table))fail6("Airtable writes require a stable table ID");const path=`${baseId}/${encodeURIComponent(input.table)}`;if(operation2==="records.get"){keys5(input,["table","id"]);if(!recordId(input.id))fail6("Invalid Airtable record ID");const result3=record2(await request2(`${path}/${input.id}`));if(result3.id!==input.id)fail6("Malformed Airtable record");return result3}if(operation2==="records.list"){keys5(input,["table","fields"],["table"]);if(input.fields!==undefined&&(!Array.isArray(input.fields)||!input.fields.length||input.fields.some((f)=>!text3(f))||new Set(input.fields).size!==input.fields.length))fail6("Invalid Airtable field selection");const records2=[],ids2=new Set,seen=new Set;let offset;do{const query2=new URLSearchParams;for(const field of input.fields??[])query2.append("fields[]",field);if(offset)query2.set("offset",offset);const page=await request2(`${path}?${query2}`);if(!Array.isArray(page.records))fail6("Malformed Airtable records");for(const value of page.records){const r=record2(value);if(ids2.has(r.id))fail6("Malformed Airtable pagination");ids2.add(r.id);records2.push(r)}offset=nextOffset(page.offset,seen)}while(offset);return records2}if(!mutation)fail6("Unsupported Airtable operation");keys5(input,["table","records"]);if(!Array.isArray(input.records)||!input.records.length||input.records.length>10)fail6("Invalid Airtable batch");const kind=operation2.slice(8),ids=new Set;const records=input.records.map((value)=>{const r=object7(value);keys5(r,kind==="create"?["fields"]:kind==="update"?["id","expected","set"]:["id","expected"]);if(kind==="create")return{fields:fields3(r.fields,true)};if(!recordId(r.id)||ids.has(r.id))fail6("Invalid Airtable batch record ID");ids.add(r.id);const set=kind==="update"?fields3(r.set,true):undefined;if(set&&Object.values(set).some((value2)=>value2===null))fail6("Airtable guard null cannot be an update value");return{id:r.id,expected:fields3(r.expected),...set?{set}:{}}});for(const r of records){if(!("id"in r))continue;const current=record2(await request2(`${path}/${r.id}`));if(current.id!==r.id)fail6("Malformed Airtable record");for(const[key,value]of Object.entries(r.expected)){if(value===null?Object.hasOwn(current.fields,key):!Object.hasOwn(current.fields,key)||!equal(current.fields[key],value))fail6("Airtable reviewed values are stale")}}await options.beforeMutation?.();const query=new URLSearchParams;if(kind==="delete")for(const id2 of ids)query.append("records[]",id2);const result2=await request2(`${path}${kind==="delete"?`?${query}`:""}`,{method:kind==="create"?"POST":kind==="update"?"PATCH":"DELETE",...kind==="delete"?{}:{body:JSON.stringify({records:records.map((r)=>("id"in r)?{id:r.id,fields:r.set}:r)})}},true);const acknowledged=[],returned=[];try{if(!Array.isArray(result2.records))throw new Error;for(const value of result2.records){const r=object7(value);if(!recordId(r.id)||acknowledged.includes(r.id)||kind!=="create"&&!ids.has(r.id)||kind==="delete"&&r.deleted!==true)throw new Error;acknowledged.push(r.id);if(kind!=="delete")returned.push(record2(r))}if(acknowledged.length!==records.length)throw new Error}catch{throw new AirtableOperationError("Incomplete Airtable mutation acknowledgment",acknowledged.length?"partial":"uncertain",acknowledged.length?[receipt(acknowledged)]:[])}return{receipt:receipt(acknowledged),...kind==="delete"?{}:{records:returned}}}function nextOffset(value,seen){if(value===undefined)return;if(!text3(value)||seen.has(value))fail6("Malformed Airtable pagination");seen.add(value);return value}var MANAGED_CONNECTION_CAPABILITY_ENV="OS_MANAGED_CONNECTION_CAPABILITY";function managedConnections(capability){const endpoint=new URL(capability.endpoint);if(endpoint.protocol!=="http:"||endpoint.hostname!=="127.0.0.1"||!endpoint.port||endpoint.pathname!=="/"||endpoint.search||endpoint.hash||endpoint.username||endpoint.password||!/^[0-9a-f-]{36}$/.test(capability.token))throw new AirtableOperationError("Airtable capability unavailable");const transport=async(name,operation2,input)=>{let safeInput;try{safeInput=serializable(input)}catch{safeInput=null}try{const response=await fetch(new URL("airtable",endpoint),{method:"POST",redirect:"error",headers:{authorization:`Bearer ${capability.token}`,"content-type":"application/json"},body:JSON.stringify({name,operation:operation2,input:safeInput}),signal:AbortSignal.timeout(125000)});const value=await response.json();if(!response.ok)throw new AirtableOperationError("Airtable operation failed; the execution retains its evidence",value.effect==="partial"||value.effect==="uncertain"?value.effect:"unapplied",value.receipts??[]);return value}catch(error){if(error instanceof AirtableOperationError)throw error;throw new AirtableOperationError("Airtable parent acknowledgment unavailable",["records.create","records.update","records.delete"].includes(operation2)?"uncertain":"unapplied")}};return createConnections(transport)}var observer;function observeLocalRoutineEffects(value){observer=value}async function reportLocalRoutineEffect(value){await observer?.(value)}var identityPattern=/^(gmail|airtable|dropbox|outlook|sharepoint)\/([a-z0-9][a-z0-9-]{0,62})$/;var workspacePattern=/^[a-z0-9][a-z0-9-]{0,62}$/;var providerNames={gmail:"Gmail",airtable:"Airtable",dropbox:"Dropbox",outlook:"Outlook",sharepoint:"SharePoint"};function parseConnectionFailureDetail(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Connection failure");const detail=value;if(!["identity","identity,workspace"].includes(Object.keys(detail).sort().join(","))||typeof detail.identity!=="string"||!identityPattern.test(detail.identity)||detail.workspace!==undefined&&(typeof detail.workspace!=="string"||!workspacePattern.test(detail.workspace)))throw new Error("Invalid Connection failure");return{identity:detail.identity,...detail.workspace===undefined?{}:{workspace:detail.workspace}}}function connectionFailureMessage(value){const detail=parseConnectionFailureDetail(value);const[,provider,name]=identityPattern.exec(detail.identity);const first=`Couldn’t use ${providerNames[provider]??provider} connection ${name}.`;return detail.workspace?`${first}
37
37
 
38
38
  Check it with:
39
39
  os connection test --workspace ${detail.workspace} --connection ${detail.identity}`:`${first}