@auth-craft/aws-cf-stack 1.10.1 → 1.10.2

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.
@@ -184,7 +184,7 @@ Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let
184
184
  RETURNING *`,[e.provider,e.externalId,e.userId,e.externalUsername??null,e.externalEmail??null,e.externalPhone??null,e.externalName??null,e.externalAvatarUrl??null,e.metadata?JSON.stringify(e.metadata):null]);return T(this.toEntity(t[0]))}catch(t){let n=t;return n.code==="23505"?S(O.UniqueConstraintViolation({field:"provider link"})):n.code==="23503"?S(O.ForeignKeyViolation({field:"userId"})):S(O.DatabaseQueryError({query:"create provider"}))}}async update(e,t,n){try{let s=[],i=[],o=1;return n.externalUsername!==void 0&&(s.push(`external_username = $${o++}`),i.push(n.externalUsername??null)),n.externalEmail!==void 0&&(s.push(`external_email = $${o++}`),i.push(n.externalEmail??null)),n.externalPhone!==void 0&&(s.push(`external_phone = $${o++}`),i.push(n.externalPhone??null)),n.externalName!==void 0&&(s.push(`external_name = $${o++}`),i.push(n.externalName??null)),n.externalAvatarUrl!==void 0&&(s.push(`external_avatar_url = $${o++}`),i.push(n.externalAvatarUrl??null)),n.metadata!==void 0&&(s.push(`metadata = $${o++}`),i.push(n.metadata?JSON.stringify(n.metadata):null)),s.length===0?T(void 0):(i.push(e,t),await this.pool.query(`UPDATE user_providers SET ${s.join(", ")} WHERE provider = $${o++} AND external_id = $${o}`,i),T(void 0))}catch{return S(O.DatabaseQueryError({query:"update provider"}))}}async remove(e,t){try{return await this.pool.query("DELETE FROM user_providers WHERE provider = $1 AND external_id = $2",[e,t]),T(void 0)}catch{return S(O.DatabaseQueryError({query:"remove provider"}))}}toEntity(e){let t={userId:e.user_id,provider:e.provider,externalId:e.external_id,createdAt:new Date(e.created_at)};return e.external_username&&(t.externalUsername=e.external_username),e.external_email&&(t.externalEmail=e.external_email),e.external_phone&&(t.externalPhone=e.external_phone),e.external_name&&(t.externalName=e.external_name),e.external_avatar_url&&(t.externalAvatarUrl=e.external_avatar_url),e.metadata&&(t.metadata=e.metadata),t}};var zd=class{pool;constructor(e){this.pool=e}async get(e,t){try{let{rows:n}=await this.pool.query("SELECT * FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,t]);return n.length===0?T(null):T(this.toEntity(n[0]))}catch{return S(O.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let{rows:t}=await this.pool.query(`INSERT INTO user_tenant_profiles (
185
185
  tenant_id, user_id, contact_email, contact_phone, display_name, display_name_source, given_name, family_name, avatar_url, locale, job_title, bio, metadata
186
186
  ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
187
- RETURNING *`,[e.tenantId,e.userId,e.contactEmail??null,e.contactPhone??null,e.displayName??null,e.displayNameSource??null,e.givenName??null,e.familyName??null,e.avatarUrl??null,e.locale??null,e.jobTitle??null,e.bio??null,e.metadata?JSON.stringify(e.metadata):null]);return T(this.toEntity(t[0]))}catch(t){console.error("[DEBUG] user_tenant_profiles insert error:",t);let n=t;return n.code==="23505"?S(O.UniqueConstraintViolation({field:"tenant profile"})):n.code==="23503"?S(O.ForeignKeyViolation({field:"userId"})):S(O.DatabaseQueryError({query:"create user tenant profile"}))}}async update(e,t,n){try{let s=["updated_at = NOW()"],i=[],o=1,a=[["contactEmail","contact_email"],["contactPhone","contact_phone"],["displayName","display_name"],["displayNameSource","display_name_source"],["givenName","given_name"],["familyName","family_name"],["avatarUrl","avatar_url"],["locale","locale"],["jobTitle","job_title"],["bio","bio"]];for(let[c,u]of a)n[c]!==void 0&&(s.push(`${u} = $${o++}`),i.push(n[c]??null));return n.metadata!==void 0&&(s.push(`metadata = $${o++}`),i.push(n.metadata?JSON.stringify(n.metadata):null)),i.length===0?T(void 0):(i.push(e,t),await this.pool.query(`UPDATE user_tenant_profiles SET ${s.join(", ")} WHERE tenant_id = $${o++} AND user_id = $${o}`,i),T(void 0))}catch{return S(O.DatabaseQueryError({query:"update user tenant profile"}))}}async remove(e,t){try{return await this.pool.query("DELETE FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,t]),T(void 0)}catch{return S(O.DatabaseQueryError({query:"remove user tenant profile"}))}}toEntity(e){let t={tenantId:e.tenant_id,userId:e.user_id,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)};return e.contact_email&&(t.contactEmail=e.contact_email),e.contact_phone&&(t.contactPhone=e.contact_phone),e.display_name&&(t.displayName=e.display_name),e.display_name_source&&(t.displayNameSource=e.display_name_source),e.given_name&&(t.givenName=e.given_name),e.family_name&&(t.familyName=e.family_name),e.avatar_url&&(t.avatarUrl=e.avatar_url),e.locale&&(t.locale=e.locale),e.job_title&&(t.jobTitle=e.job_title),e.bio&&(t.bio=e.bio),e.metadata&&(t.metadata=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata),t}};var ow=class{name="database-postgresql";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;userAuths;tenants;tenantMembers;tenantInvites;userTenantProfiles;queries;pool;constructor(e){this.pool=e,this.users=new Wd(e),this.userAuths=new Gd(e),this.sessions=new Ld(e),this.identities=new kd(e),this.credentials=new Pd(e),this.challenges=new Od(e),this.userProviders=new jd(e),this.userMfaAuthenticators=new qd(e),this.tenants=new Hd(e),this.tenantMembers=new Fd(e),this.tenantInvites=new Ud(e),this.userTenantProfiles=new zd(e),this.queries={tenantInvites:new Md(e),tenantMembers:new $d(e),tenants:new Bd(e)}}async initialize(){}async health(){try{let e=await this.pool.connect();return await e.query("SELECT 1"),e.release(),!0}catch{return!1}}async cleanup(){await this.pool.end()}};function jL(r){let e=new lE(r);return new ow(e)}var rne={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function zL(r={}){let e={...rne,...r},n=(()=>{if(r.customRegex)return r.customRegex;let s="[a-zA-Z0-9_\\-]";e.allowDots?(s+="+",s=`(${s}\\.?)+`):s+="+",e.allowPlusAddressing&&(s=`${s}(\\+[a-zA-Z0-9_\\-]+)?`);let i=e.requireTLD?"[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.[a-zA-Z]{2,}":"[a-zA-Z0-9][a-zA-Z0-9\\-\\.]*";return new RegExp(`^${s}@${i}$`)})();return{name:"email-identity",version:"1.0.0",identityType:"email",normalize(s){return s.toLowerCase().trim()},validate(s){if(!s||s.trim().length===0)return S([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(s.length>254)return S([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(s))return S([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(s.includes(".."))return S([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let i=s.split("@");if(i.length!==2)return S([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[o,a]=i;return!o||o.length>64?S([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?S([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):T()}}}var NT=Ae(aT(),1),wQ=Ae(Kt(),1);function oe(r){return r.getTime()}function W(r){return new Date(r)}function pQ(r){return Math.floor(r/1e3)}function Ee(){return Date.now()}function vm(r){return r instanceof Date?pQ(r.getTime()):pQ(r)}function uO(r){return r<Date.now()}function Ds(r){return r?oe(r):null}function Mr(r){return r==null?null:W(r)}function Ur(r){let e={};for(let[t,n]of Object.entries(r))n!=null&&(e[t]=n);return e}function Os(r){let e=[],t=[],n={},s={},i=0;for(let[c,u]of Object.entries(r)){if(c==="PK"||c==="SK")continue;let l=`#${c}`;if(n[l]=c,u==null)t.push(l);else{let d=`:val${i}`;e.push(`${l} = ${d}`),s[d]=u,i++}}let o=[];return e.length>0&&o.push(`SET ${e.join(", ")}`),t.length>0&&o.push(`REMOVE ${t.join(", ")}`),{UpdateExpression:o.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:s}}function lO(r="PK"){return`attribute_not_exists(${r})`}var lr={INVITE_MEMBERS:1,REMOVE_MEMBERS:2,VIEW_MEMBERS:4,CHANGE_MEMBER_PERMISSION:8,UPDATE_MEMBER_PROFILE:16,UPDATE_MEMBER_STATUS:32,VIEW_ACCOUNTS:64,UPDATE_ACCOUNT_PROFILE:128,UPDATE_ACCOUNT_STATUS:256,RESET_ACCOUNT_CREDENTIALS:512,REMOVE_ACCOUNTS:1024},Pwe=lr.VIEW_ACCOUNTS|lr.UPDATE_ACCOUNT_PROFILE|lr.UPDATE_ACCOUNT_STATUS|lr.RESET_ACCOUNT_CREDENTIALS|lr.REMOVE_ACCOUNTS;var mQ={[lr.INVITE_MEMBERS]:"tenant.member.invite",[lr.REMOVE_MEMBERS]:"tenant.member.remove",[lr.VIEW_MEMBERS]:"tenant.member.view",[lr.CHANGE_MEMBER_PERMISSION]:"tenant.member.permission",[lr.UPDATE_MEMBER_PROFILE]:"tenant.member.profile.update",[lr.UPDATE_MEMBER_STATUS]:"tenant.member.status.update",[lr.VIEW_ACCOUNTS]:"account.view",[lr.UPDATE_ACCOUNT_PROFILE]:"account.profile.update",[lr.UPDATE_ACCOUNT_STATUS]:"account.status.update",[lr.RESET_ACCOUNT_CREDENTIALS]:"account.credentials.reset",[lr.REMOVE_ACCOUNTS]:"account.remove"},kwe=Object.fromEntries(Object.entries(mQ).map(([r,e])=>[e,Number(r)]));var dO={SYSTEM:"system",DEFAULT:"org"};var fO={USER:"USR"},ge={USER:`${fO.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},ut={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},dr="#",P={USER_PK:r=>`${ge.USER}${r}`,USER_AUTH_SK:()=>ut.AUTH,USER_PROFILE_SK:()=>ut.PROFILE,USER_MFA_SK:r=>`${ut.MFA}${r}`,USER_MFA_WITH_ID_SK:(r,e)=>`${ut.MFA}${r}${dr}${e}`,TENANT_MEMBER_PK:r=>`${ge.TENANT}${r}`,TENANT_MEMBER_SK:r=>`${ge.USER}${r}`,TENANT_OWNER_MARKER_SK:()=>ut.OWNER,TENANT_PK:r=>`${ge.TENANT}${r}`,TENANT_SK:()=>ut.METADATA,INVITE_PK:r=>`${ge.INVITE}${r}`,INVITE_SK:()=>ut.METADATA,TENANT_PROFILE_PK:r=>`${ge.TENANT}${r}`,TENANT_PROFILE_SK:r=>`${ut.TENANT_PROFILE}${ge.USER}${r}`,SESSION_PK:r=>`${ge.SESSION}${r}`,SESSION_METADATA_SK:()=>ut.METADATA,SESSION_SK:()=>ut.METADATA,PROVIDER_SK:(r,e)=>`${ut.PROVIDER}${r}${dr}${e}`,PROVIDER_PK:(r,e)=>`${ge.PROVIDER}${r}${dr}${e}`,PROVIDER_METADATA_SK:()=>ut.METADATA,CHALLENGE_PK:r=>`${ge.CHALLENGE}${r}`,CHALLENGE_SK:()=>ut.METADATA,IDENTITY_PK:(r,e)=>`${ge.IDENTITY}${r}#${e}`,IDENTITY_SK:()=>ut.METADATA,CREDENTIAL_PK:r=>`${ge.CREDENTIAL}${r}`,CREDENTIAL_SK:()=>ut.METADATA,CREDENTIAL_TYPE_PREFIX:r=>`${ge.CREDENTIAL}${r}#`,CREDENTIAL_USER_SK:(r,e)=>`${ge.CREDENTIAL}${r}#${e}`,USER_INDEX_PK:r=>`${ge.USER}${r}`,USER_INDEX_SK:(r,e)=>`${ge.IDENTITY}${r}#${e}`},ye={userId:r=>r.slice(ge.USER.length),sessionId:r=>r.slice(ge.SESSION.length),providerPKInfo:r=>{let e=r.slice(ge.PROVIDER.length),t=e.indexOf("#");if(t===-1)return null;let n=e.slice(0,t),s=e.slice(t+1);return{provider:n,externalId:s}},providerInfo:r=>{let e=r.slice(ut.PROVIDER.length),t=e.indexOf(dr);if(t===-1)return null;let n=e.slice(0,t),s=e.slice(t+1);return{provider:n,externalId:s}},mfaSKInfo:r=>{let e=r.slice(ut.MFA.length),t=e.indexOf(dr);if(t===-1)return{method:e};let n=e.slice(0,t),s=e.slice(t+1);return{method:n,id:s}},tenantId:r=>r.slice(ge.TENANT.length),tenantMemberUserId:r=>r.slice(ge.USER.length),challengeIdFromPK:r=>r.slice(ge.CHALLENGE.length),inviteId:r=>r.slice(ge.INVITE.length),tenantProfileUserId:r=>r.slice(ut.TENANT_PROFILE.length+ge.USER.length),identityPKInfo:r=>{let e=r.slice(ge.IDENTITY.length),t=e.indexOf("#");if(t===-1)return null;let n=e.slice(0,t),s=e.slice(t+1);return{type:n,value:s}},credentialId:r=>r.slice(ge.CREDENTIAL.length),credentialTypeFromUserSK:r=>{let e=r.slice(ge.CREDENTIAL.length),t=e.indexOf("#");return t===-1?"":e.slice(0,t)},userIndexSKInfo:r=>{let e=r.slice(ge.IDENTITY.length),t=e.indexOf("#");if(t===-1)return null;let n=e.slice(0,t),s=e.slice(t+1);return{type:n,value:s}}};var Pe={ACTIVE_SESSION_PK:r=>`${ge.USER}${r}`,ACTIVE_SESSION_SK:(r,e)=>`${r}${dr}${e}`,USER_SESSION_PK:r=>`${ge.USER}${r}`,USER_SESSION_SK:(r,e)=>`${r}${dr}${e}`,USER_STATUS_PK:r=>{let e=r===Bs.ACTIVE?"ACTIVE":"INACTIVE";return`${fO.USER}${dr}${e}`},USER_STATUS_SK:r=>r,USER_PROVIDER_PK:r=>`${ge.USER}${r}`,USER_PROVIDER_SK:(r,e)=>`${ut.PROVIDER}${r}${dr}${e}`,INVITE_TENANT_PK:r=>`${ge.TENANT}${r}`,INVITE_TENANT_SK:(r,e,t)=>`${r}${dr}${e}${dr}${t}`,INVITE_TENANT_STATUS_PREFIX:r=>`${r}${dr}`,USER_TENANT_PK:r=>`${ge.USER}${r}`,USER_TENANT_SK:(r,e,t,n)=>`${r}${dr}${e??"ROOT"}${dr}${t}${dr}${n}`},p={PK:"PK",SK:"SK",TTL:"TTL",ACTIVE_SESSION_PK:"activeSessionPk",ACTIVE_SESSION_SK:"activeSessionSk",USER_SESSION_PK:"userSessionPk",USER_SESSION_SK:"userSessionSk",USER_STATUS_PK:"userStatusPk",USER_STATUS_SK:"userStatusSk",USER_PROVIDER_PK:"userProviderPk",USER_PROVIDER_SK:"userProviderSk",USER_ID:"userId",TENANT_ID:"tenantId",TENANT_TYPE:"tenantType",AUDIENCE:"audience",PURPOSE:"purpose",CHALLENGE_STATUS:"challengeStatus",PHASE:"phase",ALLOWED_METHODS:"allowedMethods",METHOD:"method",IDENTITY_TYPE:"identityType",IDENTITY_VALUE:"identityValue",CODE_HASH:"codeHash",ATTEMPTS:"attempts",MAX_ATTEMPTS:"maxAttempts",METADATA:"metadata",FLOW_KEY:"flowKey",EXPIRES_AT:"expiresAt",CREATED_AT:"createdAt",TOKEN_ID:"tokenId",PREVIOUS_TOKEN_ID:"previousTokenId",ROTATED_AT:"rotatedAt",LAST_USED_AT:"lastUsedAt",REVOKED_AT:"revokedAt",ROLE:"role",ROLES:"roles",PERM:"perm",AUTH_PERM:"authPerm",IS_OWNER:"isOwner",DEVICE_LABEL:"deviceLabel",COUNTRY:"country",CITY:"city",IDENTITY_USER_PK:"identityUserPk",IDENTITY_USER_SK:"identityUserSk",LOGIN_ENABLED:"loginEnabled",VERIFIED_AT:"verifiedAt",GUARDS:"guards",PENDING_VERIFICATION:"pendingVerification",UPDATED_AT:"updatedAt",CREDENTIAL_USER_PK:"credentialUserPk",CREDENTIAL_USER_SK:"credentialUserSk",CREDENTIAL_VALUE:"value",INVITE_STATUS:"inviteStatus",INVITE_TOKEN:"inviteToken",INVITED_BY_ID:"invitedById",INVITED_BY_INFO:"invitedByInfo",INVITEE_USER_ID:"inviteeUserId",INVITEE_EMAIL:"inviteeEmail",INVITEE_PHONE:"inviteePhone",ACCEPTED_AT:"acceptedAt",DECLINED_AT:"declinedAt",INVITE_TENANT_PK:"inviteTenantPk",INVITE_TENANT_SK:"inviteTenantSk",INVITE_TOKEN_GSI:"inviteTokenGsi",INVITEE_EMAIL_GSI:"inviteeEmailGsi",INVITEE_EMAIL_TENANT_SK:"inviteeEmailTenantSk",INVITEE_PHONE_GSI:"inviteePhoneGsi",INVITEE_PHONE_TENANT_SK:"inviteePhoneTenantSk",USER_TENANT_PK:"userTenantPk",USER_TENANT_SK:"userTenantSk",DISPLAY_NAME:"displayName",AVATAR_URL:"avatarUrl",TITLE:"title",BIO:"bio"},bT={sessionSK:(r,e)=>`${r instanceof Date?r.getTime():r}${dr}${e}`,extractCreatedAt:r=>{let e=r.indexOf(dr),t=e===-1?r:r.slice(0,e);return Number(t)}};var Se={ACTIVE_SESSIONS:"GSI_ActiveSessions",USER_SESSIONS:"GSI_UserSessions",USERS_BY_STATUS:"GSI_UsersByStatus",USER_PROVIDERS:"GSI_UserProviders",USER_IDENTITIES:"GSI_UserIdentities",USER_CREDENTIALS:"GSI_UserCredentials",TENANT_INVITES:"GSI_TenantInvites",INVITE_TOKEN:"GSI_InviteToken",INVITEE_EMAIL:"GSI_InviteeEmail",INVITEE_PHONE:"GSI_InviteePhone",USER_TENANTS:"GSI_UserTenants"},gt="S",Lwe={partitionKey:{name:"PK",type:gt},sortKey:{name:"SK",type:gt},ttlAttribute:"TTL",globalSecondaryIndexes:[{indexName:Se.ACTIVE_SESSIONS,partitionKey:{name:"activeSessionPk",type:gt},sortKey:{name:"activeSessionSk",type:gt},projection:{type:"KEYS_ONLY"}},{indexName:Se.USER_SESSIONS,partitionKey:{name:"userSessionPk",type:gt},sortKey:{name:"userSessionSk",type:gt},projection:{type:"KEYS_ONLY"}},{indexName:Se.USERS_BY_STATUS,partitionKey:{name:"userStatusPk",type:gt},sortKey:{name:"userStatusSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["displayName","createdAt"]}},{indexName:Se.USER_PROVIDERS,partitionKey:{name:"userProviderPk",type:gt},sortKey:{name:"userProviderSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["userId","externalEmail","externalName","createdAt"]}},{indexName:Se.USER_IDENTITIES,partitionKey:{name:"identityUserPk",type:gt},sortKey:{name:"identityUserSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["loginEnabled","verifiedAt","createdAt"]}},{indexName:Se.USER_CREDENTIALS,partitionKey:{name:"credentialUserPk",type:gt},sortKey:{name:"credentialUserSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["revokedAt","createdAt"]}},{indexName:Se.USER_TENANTS,partitionKey:{name:"userTenantPk",type:gt},sortKey:{name:"userTenantSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["userStatus","role","roles","perm","authPerm","isOwner","createdAt","updatedAt"]}},{indexName:Se.TENANT_INVITES,partitionKey:{name:"inviteTenantPk",type:gt},sortKey:{name:"inviteTenantSk",type:gt},projection:{type:"ALL"}},{indexName:Se.INVITE_TOKEN,partitionKey:{name:"inviteTokenGsi",type:gt},projection:{type:"KEYS_ONLY"}},{indexName:Se.INVITEE_EMAIL,partitionKey:{name:"inviteeEmailGsi",type:gt},sortKey:{name:"inviteeEmailTenantSk",type:gt},projection:{type:"ALL"}},{indexName:Se.INVITEE_PHONE,partitionKey:{name:"inviteePhoneGsi",type:gt},sortKey:{name:"inviteePhoneTenantSk",type:gt},projection:{type:"ALL"}}]};var mo=Ae(Kt(),1);function ql(r){if(typeof r=="object"&&r!==null&&"name"in r){let{name:e}=r;return typeof e=="string"?e:void 0}}function Je(r){return ql(r)==="ConditionalCheckFailedException"}function Mwe(r){let e=ql(r),t=r instanceof Error?r.message:typeof r=="string"?r:void 0;return[e,t].filter(Boolean).join(": ")||String(r)}function hQ(r,e){console.error(`[repo-plugin-dynamodb] ${r} failed \u2014 ${Mwe(e)}`)}function V(r,e){return hQ(r,e),O.DatabaseQueryError({query:r})}function Ir(r,e){return hQ(r,e),O.UnknownError({message:r})}var Dm=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return At()}async get(e){try{let t=await this.docClient.send(new mo.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.CHALLENGE_PK(e),[p.SK]:P.CHALLENGE_SK()}}));if(!t.Item)return T(null);let n=this.unmarshall(t.Item);return uO(oe(n.expiresAt))?T(null):T(n)}catch(t){return S(V("get challenge",t))}}async create(e){try{let t=Ee(),n=e.id||this.generateChallengeId(),s={...e,id:n,createdAt:W(t)},i=oe(e.expiresAt),o=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new mo.PutCommand({TableName:this.tableName,Item:this.marshall(s,o)})),T(s)}catch(t){return S(V("create challenge",t))}}async update(e,t){try{let n=[],s={},i={};return t.method!==void 0&&(n.push("#method = :method"),s["#method"]=p.METHOD,i[":method"]=t.method),t.phase!==void 0&&(n.push("#phase = :phase"),s["#phase"]=p.PHASE,i[":phase"]=t.phase),t.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),s["#codeHash"]=p.CODE_HASH,i[":codeHash"]=t.codeHash),t.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),s["#challengeStatus"]=p.CHALLENGE_STATUS,i[":challengeStatus"]=t.status),n.length===0?T(void 0):(await this.docClient.send(new mo.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.CHALLENGE_PK(e),[p.SK]:P.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:i})),T(void 0))}catch(n){return S(V("update challenge",n))}}async incrementAttempts(e,t){let n={":zero":0,":inc":1},s;t!==void 0&&(s="attribute_not_exists(#attempts) OR #attempts < :max",n[":max"]=t);try{let o=(await this.docClient.send(new mo.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.CHALLENGE_PK(e),[p.SK]:P.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...s?{ConditionExpression:s}:{},ExpressionAttributeNames:{"#attempts":p.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[p.ATTEMPTS]??0;return T(o)}catch(i){return Je(i)?S(O.AttemptsExceeded()):S(V("increment challenge attempts",i))}}async remove(e){try{return await this.docClient.send(new mo.DeleteCommand({TableName:this.tableName,Key:{[p.PK]:P.CHALLENGE_PK(e),[p.SK]:P.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":p.PK}})),T(void 0)}catch(t){return Je(t)?T(void 0):S(V("remove challenge",t))}}marshall(e,t){let n={[p.PK]:P.CHALLENGE_PK(e.id),[p.SK]:P.CHALLENGE_SK(),[p.USER_ID]:e.userId,[p.PURPOSE]:e.purpose,[p.CHALLENGE_STATUS]:e.status,[p.EXPIRES_AT]:oe(e.expiresAt),[p.CREATED_AT]:oe(e.createdAt),[p.TTL]:t};return e.tenantId&&(n[p.TENANT_ID]=e.tenantId),e.phase&&(n[p.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[p.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[p.METHOD]=e.method),e.codeHash&&(n[p.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[p.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[p.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[p.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[p.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[p.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[p.COUNTRY]=e.country),e.city&&(n[p.CITY]=e.city),e.metadata&&(n[p.METADATA]=e.metadata),e.flowKey&&(n[p.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:ye.challengeIdFromPK(e[p.PK]),userId:e[p.USER_ID],purpose:e[p.PURPOSE],status:e[p.CHALLENGE_STATUS],expiresAt:W(e[p.EXPIRES_AT]),createdAt:W(e[p.CREATED_AT])};return e[p.TENANT_ID]&&(n.tenantId=e[p.TENANT_ID]),e[p.PHASE]&&(n.phase=e[p.PHASE]),e[p.ALLOWED_METHODS]&&(n.allowedMethods=e[p.ALLOWED_METHODS]),e[p.METHOD]&&(n.method=e[p.METHOD]),e[p.CODE_HASH]&&(n.codeHash=e[p.CODE_HASH]),e[p.ATTEMPTS]!==void 0&&(n.attempts=e[p.ATTEMPTS]),e[p.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[p.MAX_ATTEMPTS]),e[p.IDENTITY_TYPE]&&(n.identityType=e[p.IDENTITY_TYPE]),e[p.IDENTITY_VALUE]&&(n.identityValue=e[p.IDENTITY_VALUE]),e[p.DEVICE_LABEL]&&(n.deviceLabel=e[p.DEVICE_LABEL]),e[p.COUNTRY]&&(n.country=e[p.COUNTRY]),e[p.CITY]&&(n.city=e[p.CITY]),e[p.METADATA]&&(n.metadata=e[p.METADATA]),e[p.FLOW_KEY]&&(n.flowKey=e[p.FLOW_KEY]),n}};var $r=Ae(Kt(),1);var Om=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return At()}async get(e){try{let t=await this.docClient.send(new $r.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.CREDENTIAL_PK(e),[p.SK]:P.CREDENTIAL_SK()}}));return t.Item?T(this.unmarshall(t.Item)):T(null)}catch(t){return S(V("get credential",t))}}async getByUserIdAndType(e,t){try{let n=await this.docClient.send(new $r.QueryCommand({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${p.CREDENTIAL_USER_PK} = :userPk AND begins_with(${p.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":P.USER_PK(e),":typePrefix":P.CREDENTIAL_TYPE_PREFIX(t)},Limit:1}));if(!n.Items||n.Items.length===0)return T(null);let s=n.Items[0];if(!s)return T(null);let i=ye.credentialId(s[p.PK]);return this.get(i)}catch(n){return S(V("get credential by user and type",n))}}async getByUserId(e){try{let t=await this.docClient.send(new $r.QueryCommand({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${p.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":P.USER_PK(e)}}));if(!t.Items||t.Items.length===0)return T([]);let n=t.Items.map(o=>ye.credentialId(o[p.PK])),s=await this.batchGet(n);if(s.ok===!1)return S(s.errors,s.meta);if(!s.data)return T([]);let i=s.data.filter(o=>o!==null);return T(i)}catch(t){return S(V("get credentials by user",t))}}async create(e){try{let t=Ee(),n=this.generateCredentialId(),s={revokedAt:null,lastUsedAt:null,...e,id:n,createdAt:new Date(t),updatedAt:new Date(t)};return await this.docClient.send(new $r.PutCommand({TableName:this.tableName,Item:this.marshall(s),ConditionExpression:`attribute_not_exists(${p.PK})`})),T(s)}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"credential"})):S(V("create credential",t))}}async update(e,t){try{let n=Ee(),s=[],i={},o={};return s.push(`#${p.UPDATED_AT} = :updatedAt`),i[`#${p.UPDATED_AT}`]=p.UPDATED_AT,o[":updatedAt"]=n,t.value!==void 0&&(s.push(`#${p.CREDENTIAL_VALUE} = :value`),i[`#${p.CREDENTIAL_VALUE}`]=p.CREDENTIAL_VALUE,o[":value"]=t.value),t.data!==void 0&&(s.push(`#${p.METADATA} = :data`),i[`#${p.METADATA}`]=p.METADATA,o[":data"]=t.data),t.revokedAt!==void 0&&(s.push(`#${p.REVOKED_AT} = :revokedAt`),i[`#${p.REVOKED_AT}`]=p.REVOKED_AT,o[":revokedAt"]=t.revokedAt?oe(t.revokedAt):null),t.lastUsedAt!==void 0&&(s.push(`#${p.LAST_USED_AT} = :lastUsedAt`),i[`#${p.LAST_USED_AT}`]=p.LAST_USED_AT,o[":lastUsedAt"]=t.lastUsedAt?oe(t.lastUsedAt):null),await this.docClient.send(new $r.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.CREDENTIAL_PK(e),[p.SK]:P.CREDENTIAL_SK()},UpdateExpression:`SET ${s.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"credential",id:e})):S(V("update credential",n))}}async remove(e){try{return await this.docClient.send(new $r.DeleteCommand({TableName:this.tableName,Key:{[p.PK]:P.CREDENTIAL_PK(e),[p.SK]:P.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(t){return Je(t)?S(O.NotFound({entity:"credential",id:e})):S(V("delete credential",t))}}async hasType(e,t){try{let n=await this.docClient.send(new $r.QueryCommand({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${p.CREDENTIAL_USER_PK} = :userPk AND begins_with(${p.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":P.USER_PK(e),":typePrefix":P.CREDENTIAL_TYPE_PREFIX(t)},Select:"COUNT",Limit:1}));return T((n.Count||0)>0)}catch(n){return S(V("check credential type",n))}}async countByUserId(e){try{let t=await this.docClient.send(new $r.QueryCommand({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${p.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":P.USER_PK(e)},Select:"COUNT"}));return T(t.Count||0)}catch(t){return S(V("count credentials",t))}}async batchGet(e){if(e.length===0)return T([]);try{let t=[];for(let s=0;s<e.length;s+=100)t.push(e.slice(s,s+100));let n=[];for(let s of t){let o=(await this.docClient.send(new $r.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:s.map(c=>({[p.PK]:P.CREDENTIAL_PK(c),[p.SK]:P.CREDENTIAL_SK()}))}}}))).Responses?.[this.tableName]||[],a=new Map;for(let c of o){let u=this.unmarshall(c);a.set(u.id,u)}for(let c of s)n.push(a.get(c)||null)}return T(n)}catch(t){return S(V("batch get credentials",t))}}marshall(e){let t={[p.PK]:P.CREDENTIAL_PK(e.id),[p.SK]:P.CREDENTIAL_SK(),[p.CREDENTIAL_USER_PK]:P.USER_PK(e.userId),[p.CREDENTIAL_USER_SK]:P.CREDENTIAL_USER_SK(e.type,e.id),[p.USER_ID]:e.userId,[p.CREDENTIAL_VALUE]:e.value,[p.METADATA]:e.data,[p.REVOKED_AT]:e.revokedAt?oe(e.revokedAt):null,[p.CREATED_AT]:oe(e.createdAt),[p.UPDATED_AT]:oe(e.updatedAt)};return e.lastUsedAt&&(t[p.LAST_USED_AT]=oe(e.lastUsedAt)),t}unmarshall(e){let t=ye.credentialId(e[p.PK]),n=ye.credentialTypeFromUserSK(e[p.CREDENTIAL_USER_SK]);return{id:t,userId:e[p.USER_ID],type:n,value:e[p.CREDENTIAL_VALUE],data:e[p.METADATA]||{},revokedAt:Mr(e[p.REVOKED_AT]),createdAt:W(e[p.CREATED_AT]),updatedAt:W(e[p.UPDATED_AT]),lastUsedAt:Mr(e[p.LAST_USED_AT])}}};var Zr=Ae(Kt(),1);function pO(r){return{failedAttempts:r.failedAttempts,lastFailedAt:Ds(r.lastFailedAt),lockedUntil:Ds(r.lockedUntil)}}function EQ(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))e[t]={failedAttempts:n.failedAttempts??0,lastFailedAt:Mr(n.lastFailedAt),lockedUntil:Mr(n.lockedUntil)};return e}function gQ(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))n&&(e[t]=pO(n));return e}var Pm=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e,t){try{let n=await this.docClient.send(new Zr.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.IDENTITY_PK(e,t),[p.SK]:P.IDENTITY_SK()}}));if(!n.Item)return T(null);let s=this.unmarshall(n.Item);return T(s)}catch(n){return S(V("get identity",n))}}async getByUserId(e){try{let t=await this.docClient.send(new Zr.QueryCommand({TableName:this.tableName,IndexName:Se.USER_IDENTITIES,KeyConditionExpression:`${p.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":P.USER_INDEX_PK(e)}})),n=[];for(let s of t.Items||[]){let i=this.unmarshall(s);i!==null&&n.push(i)}return T(n)}catch(t){return S(V("get identities by userId",t))}}async create(e){try{let t=Ee(),n={...e,createdAt:W(t),updatedAt:W(t)};return await this.docClient.send(new Zr.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),T(n)}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"identity"})):S(V("create identity",t))}}async update(e,t,n){try{let s=[],i=[],o={},a={};if(n.loginEnabled!==void 0&&(s.push("#loginEnabled = :loginEnabled"),o["#loginEnabled"]=p.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let u=Ds(n.verifiedAt);u===null?(i.push("#verifiedAt"),o["#verifiedAt"]=p.VERIFIED_AT):(s.push("#verifiedAt = :verifiedAt"),o["#verifiedAt"]=p.VERIFIED_AT,a[":verifiedAt"]=u)}n.guards!==void 0&&(s.push("#guards = :guards"),o["#guards"]=p.GUARDS,a[":guards"]=gQ(n.guards)),n.pendingVerification!==void 0&&(o["#pendingVerification"]=p.PENDING_VERIFICATION,n.pendingVerification===null?i.push("#pendingVerification"):(s.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Ur({...n.pendingVerification,expiresAt:oe(n.pendingVerification.expiresAt),resendAvailableAt:Ds(n.pendingVerification.resendAvailableAt)}))),s.push("#updatedAt = :updatedAt"),o["#updatedAt"]=p.UPDATED_AT,a[":updatedAt"]=Ee();let c=[];return s.length>0&&c.push(`SET ${s.join(", ")}`),i.length>0&&c.push(`REMOVE ${i.join(", ")}`),await this.docClient.send(new Zr.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.IDENTITY_PK(e,t),[p.SK]:P.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:o,ExpressionAttributeValues:a})),T(void 0)}catch(s){return S(V("update identity",s))}}async remove(e,t){try{return await this.docClient.send(new Zr.DeleteCommand({TableName:this.tableName,Key:{[p.PK]:P.IDENTITY_PK(e,t),[p.SK]:P.IDENTITY_SK()}})),T(void 0)}catch(n){return S(V("remove identity",n))}}async updateGuard(e,t,n,s){let i={[p.PK]:P.IDENTITY_PK(e,t),[p.SK]:P.IDENTITY_SK()};try{return await this.docClient.send(new Zr.UpdateCommand({TableName:this.tableName,Key:i,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":p.GUARDS,"#guardKey":n,"#updatedAt":p.UPDATED_AT},ExpressionAttributeValues:{":guard":pO(s),":updatedAt":Ee()}})),T(void 0)}catch(o){if(Je(o))try{return await this.docClient.send(new Zr.UpdateCommand({TableName:this.tableName,Key:i,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":p.GUARDS,"#updatedAt":p.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:pO(s)},":updatedAt":Ee()}})),T(void 0)}catch(a){return S(V("update guard",a))}return S(V("update guard",o))}}async batchGet(e){try{if(e.length===0)return T([]);let n=(await this.docClient.send(new Zr.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:e.map(({type:o,value:a})=>({[p.PK]:P.IDENTITY_PK(o,a),[p.SK]:P.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],s=new Map;for(let o of n){let a=this.unmarshall(o);if(a!==null){let c=`${a.type}#${a.value}`;s.set(c,a)}}let i=e.map(({type:o,value:a})=>{let c=`${o}#${a}`;return s.get(c)||null});return T(i)}catch(t){return S(V("batch get identities",t))}}marshall(e){let t={[p.PK]:P.IDENTITY_PK(e.type,e.value),[p.SK]:P.IDENTITY_SK(),[p.IDENTITY_USER_PK]:P.USER_INDEX_PK(e.userId),[p.IDENTITY_USER_SK]:P.USER_INDEX_SK(e.type,e.value),[p.USER_ID]:e.userId,[p.LOGIN_ENABLED]:e.loginEnabled,[p.CREATED_AT]:oe(e.createdAt),[p.UPDATED_AT]:oe(e.updatedAt)},n=Ds(e.verifiedAt);return n!==null&&(t[p.VERIFIED_AT]=n),t[p.GUARDS]=gQ(e.guards),e.pendingVerification&&(t[p.PENDING_VERIFICATION]=Ur({...e.pendingVerification,expiresAt:oe(e.pendingVerification.expiresAt),resendAvailableAt:Ds(e.pendingVerification.resendAvailableAt)})),t}unmarshall(e){let t=ye.identityPKInfo(e[p.PK]);if(!t){let n=e[p.IDENTITY_USER_SK]?ye.userIndexSKInfo(e[p.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[p.USER_ID],loginEnabled:e[p.LOGIN_ENABLED],verifiedAt:Mr(e[p.VERIFIED_AT]),guards:EQ(e[p.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[p.PENDING_VERIFICATION]),createdAt:W(e[p.CREATED_AT]),updatedAt:W(e[p.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[p.PK],GSI1SK:e[p.IDENTITY_USER_SK]}),null)}return{type:t.type,value:t.value,userId:e[p.USER_ID],loginEnabled:e[p.LOGIN_ENABLED],verifiedAt:Mr(e[p.VERIFIED_AT]),guards:EQ(e[p.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[p.PENDING_VERIFICATION]),createdAt:W(e[p.CREATED_AT]),updatedAt:W(e[p.UPDATED_AT])}}unmarshallPendingVerification(e){if(!e||typeof e!="object")return null;let t=e;return{challengeId:t.challengeId,purpose:t.purpose,channel:t.channel,expiresAt:W(t.expiresAt),resendAvailableAt:Mr(t.resendAvailableAt)}}};var yQ=Ae(Kt(),1);var km=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}async createEmailVerificationRegistration(e){try{let t=Ee(),n=At(),s=oe(e.challenge.expiresAt),i=Math.floor((s+this.ttlGracePeriod)/1e3);return await this.docClient.send(new yQ.TransactWriteCommand({TransactItems:[this.putItem(this.marshallProfile(e,t)),this.putItem(this.marshallUserAuth(e,t)),this.putItem(this.marshallIdentity(e,t)),this.putItem(this.marshallCredential(e,n,t)),this.putItem(this.marshallChallenge(e,t,i))]})),T(void 0)}catch(t){return ql(t)==="TransactionCanceledException"||Je(t)?S(O.UniqueConstraintViolation({field:"registration"})):S(V("create email verification registration transaction",t))}}putItem(e){return{Put:{TableName:this.tableName,Item:Ur(e),ConditionExpression:`attribute_not_exists(${p.PK})`}}}marshallProfile(e,t){let n=e.profile.status,s={[p.PK]:P.USER_PK(e.profile.id),[p.SK]:P.USER_PROFILE_SK(),userStatus:n,[p.CREATED_AT]:t,[p.UPDATED_AT]:t,[p.USER_STATUS_PK]:Pe.USER_STATUS_PK(n),[p.USER_STATUS_SK]:Pe.USER_STATUS_SK(e.profile.id)};return e.profile.contactEmail&&(s.contactEmail=e.profile.contactEmail),e.profile.contactPhone&&(s.contactPhone=e.profile.contactPhone),e.profile.username&&(s.username=e.profile.username),e.profile.displayName&&(s.displayName=e.profile.displayName),e.profile.givenName&&(s.givenName=e.profile.givenName),e.profile.familyName&&(s.familyName=e.profile.familyName),e.profile.avatarUrl&&(s.avatarUrl=e.profile.avatarUrl),e.profile.locale&&(s.locale=e.profile.locale),e.profile.metadata&&(s.metadata=JSON.stringify(e.profile.metadata)),s}marshallUserAuth(e,t){return{[p.PK]:P.USER_PK(e.userAuth.userId),[p.SK]:P.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[p.CREATED_AT]:t,[p.UPDATED_AT]:t}}marshallIdentity(e,t){let n=e.identity,s={[p.PK]:P.IDENTITY_PK(n.type,n.value),[p.SK]:P.IDENTITY_SK(),[p.IDENTITY_USER_PK]:P.USER_INDEX_PK(n.userId),[p.IDENTITY_USER_SK]:P.USER_INDEX_SK(n.type,n.value),[p.USER_ID]:n.userId,[p.LOGIN_ENABLED]:n.loginEnabled,[p.CREATED_AT]:t,[p.UPDATED_AT]:t,[p.PENDING_VERIFICATION]:Ur({...n.pendingVerification,expiresAt:oe(n.pendingVerification.expiresAt),resendAvailableAt:Ds(n.pendingVerification.resendAvailableAt)})},i=Ds(n.verifiedAt);return i!==null&&(s[p.VERIFIED_AT]=i),s[p.GUARDS]=n.guards??{},s}marshallCredential(e,t,n){let s=e.credential,i={[p.PK]:P.CREDENTIAL_PK(t),[p.SK]:P.CREDENTIAL_SK(),[p.CREDENTIAL_USER_PK]:P.USER_PK(s.userId),[p.CREDENTIAL_USER_SK]:P.CREDENTIAL_USER_SK(s.type,t),[p.USER_ID]:s.userId,[p.CREDENTIAL_VALUE]:s.value,[p.METADATA]:s.data,[p.REVOKED_AT]:s.revokedAt?oe(s.revokedAt):null,[p.CREATED_AT]:n,[p.UPDATED_AT]:n};return s.lastUsedAt&&(i[p.LAST_USED_AT]=oe(s.lastUsedAt)),i}marshallChallenge(e,t,n){let s=e.challenge,i={[p.PK]:P.CHALLENGE_PK(s.id),[p.SK]:P.CHALLENGE_SK(),[p.USER_ID]:s.userId,[p.PURPOSE]:s.purpose,[p.CHALLENGE_STATUS]:s.status,[p.EXPIRES_AT]:oe(s.expiresAt),[p.CREATED_AT]:t,[p.TTL]:n};return s.tenantId&&(i[p.TENANT_ID]=s.tenantId),s.phase&&(i[p.PHASE]=s.phase),s.allowedMethods&&s.allowedMethods.length>0&&(i[p.ALLOWED_METHODS]=s.allowedMethods),s.method&&(i[p.METHOD]=s.method),s.codeHash&&(i[p.CODE_HASH]=s.codeHash),s.attempts!==void 0&&(i[p.ATTEMPTS]=s.attempts),s.maxAttempts!==void 0&&(i[p.MAX_ATTEMPTS]=s.maxAttempts),s.identityType&&(i[p.IDENTITY_TYPE]=s.identityType),s.identityValue&&(i[p.IDENTITY_VALUE]=s.identityValue),s.deviceLabel&&(i[p.DEVICE_LABEL]=s.deviceLabel),s.country&&(i[p.COUNTRY]=s.country),s.city&&(i[p.CITY]=s.city),s.metadata&&(i[p.METADATA]=s.metadata),s.flowKey&&(i[p.FLOW_KEY]=s.flowKey),i}};var TQ=Ae(aT(),1),kt=Ae(Kt(),1);var AQ=Ae(Kt(),1),SQ=100,_Q=5;function Uwe(r){return new Promise(e=>setTimeout(e,r))}async function Wl(r,e,t){if(t.length===0)return[];let n=[];for(let s=0;s<t.length;s+=SQ){let i=t.slice(s,s+SQ),o=0;for(;i.length>0;){let a=await r.send(new AQ.BatchGetCommand({RequestItems:{[e]:{Keys:i}}})),c=a.Responses?.[e];c&&n.push(...c);let u=a.UnprocessedKeys?.[e]?.Keys;if(!u||u.length===0)break;if(o+=1,o>_Q)throw new Error(`BatchGet left ${u.length} unprocessed keys after ${_Q} retries`);i=u,await Uwe(2**o*25)}}return n}var Lm=class{docClient;tableName;ttlGracePeriod;constructor(e){let t=e.client||new TQ.DynamoDBClient({});this.docClient=e.docClient||kt.DynamoDBDocumentClient.from(t),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return At()}generateTokenId(){return At()}async get(e){try{let t=await this.docClient.send(new kt.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()}}));return t.Item?T(this.unmarshall(t.Item)):T(null)}catch(t){return S(V("get session",t))}}async create(e){try{let t=Ee(),n=e.id||this.generateSessionId(),s=e.tokenId||this.generateTokenId(),i={...e,id:n,tokenId:s,revokedAt:null,createdAt:new Date(t),lastUsedAt:new Date(t)},o=vm(oe(e.expiresAt)+this.ttlGracePeriod),a=bT.sessionSK(t,n);return await this.docClient.send(new kt.PutCommand({TableName:this.tableName,Item:this.marshall(i,o,a)})),T(i)}catch(t){return S(V("create session",t))}}async update(e,t){try{let n=[],s={},i={};if(t.tokenId!==void 0&&(n.push(`#${p.TOKEN_ID} = :tokenId`),s[`#${p.TOKEN_ID}`]=p.TOKEN_ID,i[":tokenId"]=t.tokenId),t.expiresAt!==void 0){n.push(`#${p.EXPIRES_AT} = :expiresAt`),s[`#${p.EXPIRES_AT}`]=p.EXPIRES_AT,i[":expiresAt"]=oe(t.expiresAt);let o=vm(oe(t.expiresAt)+this.ttlGracePeriod);n.push(`#${p.TTL} = :ttl`),s[`#${p.TTL}`]=p.TTL,i[":ttl"]=o}return t.lastUsedAt!==void 0&&(n.push(`#${p.LAST_USED_AT} = :lastUsedAt`),s[`#${p.LAST_USED_AT}`]=p.LAST_USED_AT,i[":lastUsedAt"]=oe(t.lastUsedAt)),t.metadata!==void 0&&(n.push(`#${p.METADATA} = :metadata`),s[`#${p.METADATA}`]=p.METADATA,i[":metadata"]=t.metadata),t.previousTokenId!==void 0&&(n.push(`#${p.PREVIOUS_TOKEN_ID} = :previousTokenId`),s[`#${p.PREVIOUS_TOKEN_ID}`]=p.PREVIOUS_TOKEN_ID,i[":previousTokenId"]=t.previousTokenId),t.rotatedAt!==void 0&&(n.push(`#${p.ROTATED_AT} = :rotatedAt`),s[`#${p.ROTATED_AT}`]=p.ROTATED_AT,i[":rotatedAt"]=t.rotatedAt),n.length===0?T():(await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:i})),T())}catch(n){return S(V("update session",n))}}async rotateToken(e,t,n){try{let s=vm(oe(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET #${p.TOKEN_ID} = :tokenId, #${p.PREVIOUS_TOKEN_ID} = :previousTokenId, #${p.ROTATED_AT} = :rotatedAt, #${p.EXPIRES_AT} = :expiresAt, #${p.LAST_USED_AT} = :lastUsedAt, #${p.TTL} = :ttl`,ConditionExpression:`#${p.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${p.TOKEN_ID}`]:p.TOKEN_ID,[`#${p.PREVIOUS_TOKEN_ID}`]:p.PREVIOUS_TOKEN_ID,[`#${p.ROTATED_AT}`]:p.ROTATED_AT,[`#${p.EXPIRES_AT}`]:p.EXPIRES_AT,[`#${p.LAST_USED_AT}`]:p.LAST_USED_AT,[`#${p.TTL}`]:p.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":oe(n.expiresAt),":lastUsedAt":oe(n.lastUsedAt),":ttl":s,":expectedCurrentTokenId":t}})),T(!0)}catch(s){return Je(s)?T(!1):S(V("rotate session token",s))}}async switchTenant(e,t){try{let n=[`#${p.TENANT_ID} = :tenantId`,`#${p.TOKEN_ID} = :tokenId`,`#${p.LAST_USED_AT} = :lastUsedAt`],s=[],i={[`#${p.TENANT_ID}`]:p.TENANT_ID,[`#${p.TOKEN_ID}`]:p.TOKEN_ID,[`#${p.LAST_USED_AT}`]:p.LAST_USED_AT},o={":tenantId":t.tenantId,":tokenId":t.tokenId,":lastUsedAt":Ee()};i[`#${p.TENANT_TYPE}`]=p.TENANT_TYPE,t.tenantType!==void 0?(n.push(`#${p.TENANT_TYPE} = :tenantType`),o[":tenantType"]=t.tenantType):s.push(`#${p.TENANT_TYPE}`),i[`#${p.PERM}`]=p.PERM,t.perms!==void 0?(n.push(`#${p.PERM} = :perms`),o[":perms"]=JSON.stringify(t.perms)):s.push(`#${p.PERM}`),i[`#${p.ROLES}`]=p.ROLES,t.roles!==void 0?(n.push(`#${p.ROLES} = :roles`),o[":roles"]=t.roles):s.push(`#${p.ROLES}`),i["#revokedAt"]=p.REVOKED_AT;let a=`SET ${n.join(", ")}${s.length>0?` REMOVE ${s.join(", ")}`:""}`;return await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:i,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${p.PK}) AND attribute_not_exists(#revokedAt)`})),T()}catch(n){return Je(n)?S(O.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):S(V("switch tenant",n))}}async revoke(e){try{return await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET #${p.REVOKED_AT} = :revokedAt REMOVE #${p.ACTIVE_SESSION_PK}, #${p.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${p.REVOKED_AT}`]:p.REVOKED_AT,[`#${p.ACTIVE_SESSION_PK}`]:p.ACTIVE_SESSION_PK,[`#${p.ACTIVE_SESSION_SK}`]:p.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":oe(new Date)},ConditionExpression:`attribute_exists(${p.PK})`})),T()}catch(t){return Je(t)?T():S(V("revoke session",t))}}async revokeByIdAndUserId(e,t){try{return await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET #${p.REVOKED_AT} = :revokedAt REMOVE #${p.ACTIVE_SESSION_PK}, #${p.ACTIVE_SESSION_SK}`,ConditionExpression:`#${p.USER_ID} = :userId AND attribute_not_exists(#${p.REVOKED_AT})`,ExpressionAttributeNames:{[`#${p.REVOKED_AT}`]:p.REVOKED_AT,[`#${p.USER_ID}`]:p.USER_ID,[`#${p.ACTIVE_SESSION_PK}`]:p.ACTIVE_SESSION_PK,[`#${p.ACTIVE_SESSION_SK}`]:p.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":oe(new Date),":userId":t}})),T()}catch(n){return Je(n)?T():S(V("revoke session by user",n))}}async findByUserId(e,t){try{let n=Math.min(t?.limit||50,100),s;if(t?.cursor)try{s=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))}catch{return S(O.DatabaseQueryError({query:"invalid pagination cursor"}))}let i=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.USER_SESSIONS,KeyConditionExpression:`${p.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":P.USER_PK(e)},Limit:n,ExclusiveStartKey:s,ScanIndexForward:!1}));if(!i.Items||i.Items.length===0){let h={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!t?.cursor,cursor:null};return T([],{pagination:h})}let a=i.Items.map(h=>ye.sessionId(h[p.PK])).map(h=>({[p.PK]:P.SESSION_PK(h),[p.SK]:P.SESSION_SK()})),u=(await Wl(this.docClient,this.tableName,a)).map(h=>this.unmarshall(h)),l=!!i.LastEvaluatedKey,d=l?Buffer.from(JSON.stringify(i.LastEvaluatedKey)).toString("base64url"):null,f={type:"cursor",limit:n,count:u.length,hasNext:l,hasPrev:!!t?.cursor,cursor:d};return T(u,{pagination:f})}catch(n){return S(V("find sessions by user",n))}}async findActiveByUserId(e,t){try{let n=Math.min(t?.limit||50,100),s;if(t?.cursor)try{s=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))}catch{return S(O.DatabaseQueryError({query:"invalid pagination cursor"}))}let i=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${p.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Pe.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:s,ScanIndexForward:!1}));if(!i.Items||i.Items.length===0){let h={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!t?.cursor,cursor:null};return T([],{pagination:h})}let a=i.Items.map(h=>ye.sessionId(h[p.PK])).map(h=>({[p.PK]:P.SESSION_PK(h),[p.SK]:P.SESSION_SK()})),u=(await Wl(this.docClient,this.tableName,a)).map(h=>this.unmarshall(h)),l=!!i.LastEvaluatedKey,d=l?Buffer.from(JSON.stringify(i.LastEvaluatedKey)).toString("base64url"):null,f={type:"cursor",limit:n,count:u.length,hasNext:l,hasPrev:!!t?.cursor,cursor:d};return T(u,{pagination:f})}catch(n){return S(V("find active sessions by user",n))}}async getActiveSessionsForLimit(e){try{let t=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${p.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Pe.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!t.Items||t.Items.length===0)return T([]);let n=t.Items.map(s=>{let i=ye.sessionId(s[p.PK]),o=bT.extractCreatedAt(s[p.ACTIVE_SESSION_SK]);return{id:i,createdAt:new Date(o)}});return T(n)}catch(t){return S(V("get active sessions for limit",t))}}async revokeSessionsByIds(e,t){if(e.length===0)return 0;let n=oe(new Date),s=await Promise.allSettled(e.map(o=>this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(o),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET #${p.REVOKED_AT} = :revokedAt REMOVE #${p.ACTIVE_SESSION_PK}, #${p.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${p.REVOKED_AT}`]:p.REVOKED_AT,[`#${p.ACTIVE_SESSION_PK}`]:p.ACTIVE_SESSION_PK,[`#${p.ACTIVE_SESSION_SK}`]:p.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),i=0;for(let o of s)o.status==="fulfilled"?i+=1:console.error(`[session-repo] ${t}: session revoke failed (may remain active):`,{name:ql(o.reason)});return i}async revokeAllByUserId(e,t){try{let n=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${p.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Pe.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return T(0);let s=n.Items.map(o=>ye.sessionId(o[p.PK])).filter(o=>!t||o!==t),i=await this.revokeSessionsByIds(s,"revokeAllByUserId");return T(i)}catch(n){return S(V("revoke all sessions by user",n))}}async revokeBatch(e){try{let t=await this.revokeSessionsByIds(e,"revokeBatch");return T(t)}catch(t){return S(V("revoke batch sessions",t))}}async countByUserId(e){try{let t=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${p.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Pe.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return T(t.Count||0)}catch(t){return S(V("count active sessions by user",t))}}async isTokenActive(e,t){try{let n=await this.docClient.send(new kt.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(t),[p.SK]:P.SESSION_SK()},ProjectionExpression:`${p.TOKEN_ID}, ${p.REVOKED_AT}, ${p.EXPIRES_AT}`}));if(!n.Item)return T(!1);let s=n.Item,i=s[p.TOKEN_ID]===e&&!s[p.REVOKED_AT]&&W(s[p.EXPIRES_AT])>new Date;return T(i)}catch(n){return S(V("check token active",n))}}marshall(e,t,n){let s={[p.PK]:P.SESSION_PK(e.id),[p.SK]:P.SESSION_SK(),[p.USER_SESSION_PK]:P.USER_PK(e.userId),[p.USER_SESSION_SK]:n,...!e.revokedAt&&{[p.ACTIVE_SESSION_PK]:Pe.ACTIVE_SESSION_PK(e.userId),[p.ACTIVE_SESSION_SK]:n},[p.USER_ID]:e.userId,[p.TOKEN_ID]:e.tokenId,[p.EXPIRES_AT]:oe(e.expiresAt),[p.CREATED_AT]:oe(e.createdAt),[p.LAST_USED_AT]:oe(e.lastUsedAt),[p.TTL]:t};return e.tenantId&&(s[p.TENANT_ID]=e.tenantId),e.tenantType&&(s[p.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(s[p.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(s[p.ROLES]=e.roles),e.deviceLabel&&(s[p.DEVICE_LABEL]=e.deviceLabel),e.country&&(s[p.COUNTRY]=e.country),e.city&&(s[p.CITY]=e.city),e.metadata&&(s[p.METADATA]=e.metadata),e.revokedAt&&(s[p.REVOKED_AT]=oe(e.revokedAt)),e.previousTokenId&&(s[p.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(s[p.ROTATED_AT]=e.rotatedAt),s}unmarshall(e){let n={id:ye.sessionId(e[p.PK]),userId:e[p.USER_ID],tokenId:e[p.TOKEN_ID],expiresAt:W(e[p.EXPIRES_AT]),createdAt:W(e[p.CREATED_AT]),lastUsedAt:W(e[p.LAST_USED_AT]),revokedAt:e[p.REVOKED_AT]?W(e[p.REVOKED_AT]):null};return e[p.TENANT_ID]&&(n.tenantId=e[p.TENANT_ID]),e[p.TENANT_TYPE]&&(n.tenantType=e[p.TENANT_TYPE]),e[p.PERM]!==void 0&&(n.perms=JSON.parse(e[p.PERM])),e[p.ROLES]!==void 0&&(n.roles=e[p.ROLES]),e[p.DEVICE_LABEL]&&(n.deviceLabel=e[p.DEVICE_LABEL]),e[p.COUNTRY]&&(n.country=e[p.COUNTRY]),e[p.CITY]&&(n.city=e[p.CITY]),e[p.METADATA]&&(n.metadata=e[p.METADATA]),e[p.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[p.PREVIOUS_TOKEN_ID]),e[p.ROTATED_AT]!==void 0&&(n.rotatedAt=e[p.ROTATED_AT]),n}};var IQ=Ae(Kt(),1);var Mm=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,t){try{let n=Math.min(t?.limit||50,100),s={"#pk":p.INVITE_TENANT_PK},i={":pk":Pe.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:s,ExpressionAttributeValues:i,ScanIndexForward:!1,Limit:n};t?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))),t?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",s["#sk"]=p.INVITE_TENANT_SK,i[":statusPrefix"]=Pe.INVITE_TENANT_STATUS_PREFIX(t.status));let a=await this.docClient.send(new IQ.QueryCommand(o)),c=(a.Items||[]).map(d=>this.toListItem(d)),u=!!a.LastEvaluatedKey,l=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return tt(c,{limit:n,hasNext:u,cursor:l,prevCursor:t?.cursor??null})}catch(n){return S(V("listByTenant query",n))}}toListItem(e){let t=ye.inviteId(e.PK),n={id:e.invitedById};e.invitedByInfo&&(e.invitedByInfo.name&&(n.name=e.invitedByInfo.name),e.invitedByInfo.email&&(n.email=e.invitedByInfo.email),e.invitedByInfo.jobTitle&&(n.jobTitle=e.invitedByInfo.jobTitle));let s={id:t,tenantId:e.tenantId,invitedBy:n,status:e.inviteStatus,expiresAt:W(e.expiresAt),createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};return e.inviteeUserId&&(s.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(s.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(s.inviteePhone=e.inviteePhone),e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm),e.displayName&&(s.displayName=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.jobTitle&&(s.jobTitle=e.jobTitle),e.acceptedAt&&(s.acceptedAt=W(e.acceptedAt)),e.declinedAt&&(s.declinedAt=W(e.declinedAt)),e.revokedAt&&(s.revokedAt=W(e.revokedAt)),s}};var br=Ae(Kt(),1);var $we=10080*60*1e3,Um=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:ye.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:W(e.expiresAt),createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};e.inviteeUserId&&(n.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(n.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(n.inviteePhone=e.inviteePhone),e.roles!==void 0&&(n.roles=e.roles);let s=e[p.PERM];return s!==void 0&&(n.perms=JSON.parse(s)),e.authPerm!==void 0&&(n.authPerm=e.authPerm),e.displayName&&(n.displayName=e.displayName),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.jobTitle&&(n.jobTitle=e.jobTitle),e.acceptedAt&&(n.acceptedAt=W(e.acceptedAt)),e.declinedAt&&(n.declinedAt=W(e.declinedAt)),e.revokedAt&&(n.revokedAt=W(e.revokedAt)),n}generateInviteId(){return At()}async getById(e){try{let t=await this.docClient.send(new br.GetCommand({TableName:this.tableName,Key:{PK:P.INVITE_PK(e),SK:P.INVITE_SK()}}));return t.Item?T(this.mapItemToEntity(t.Item)):T(null)}catch(t){return S(V("getById invite",t))}}async getByToken(e){try{let n=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":p.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return T(null);let s=n[0],i=await this.docClient.send(new br.GetCommand({TableName:this.tableName,Key:{PK:s.PK,SK:s.SK}}));return i.Item?T(this.mapItemToEntity(i.Item)):T(null)}catch(t){return S(V("getByToken invite",t))}}async create(e){try{let t=Ee(),n=oe(e.expiresAt),s=Math.floor((n+$we)/1e3),i={PK:P.INVITE_PK(e.id),SK:P.INVITE_SK(),[p.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[p.INVITED_BY_ID]:e.invitedById,[p.INVITE_STATUS]:e.status,[p.INVITE_TOKEN]:e.inviteToken,[p.EXPIRES_AT]:n,[p.CREATED_AT]:t,[p.UPDATED_AT]:t,[p.TTL]:s,[p.INVITE_TENANT_PK]:Pe.INVITE_TENANT_PK(e.tenantId),[p.INVITE_TENANT_SK]:Pe.INVITE_TENANT_SK(e.status,t,e.id),[p.INVITE_TOKEN_GSI]:e.inviteToken},o={};e.invitedByName&&(o.name=e.invitedByName),e.invitedByEmail&&(o.email=e.invitedByEmail),e.invitedByJobTitle&&(o.jobTitle=e.invitedByJobTitle),Object.keys(o).length>0&&(i[p.INVITED_BY_INFO]=o),e.inviteeUserId&&(i[p.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(i[p.INVITEE_EMAIL]=e.inviteeEmail,i[p.INVITEE_EMAIL_GSI]=e.inviteeEmail,i[p.INVITEE_EMAIL_TENANT_SK]=`${ge.TENANT}${e.tenantId}`),e.inviteePhone&&(i[p.INVITEE_PHONE]=e.inviteePhone,i[p.INVITEE_PHONE_GSI]=e.inviteePhone,i[p.INVITEE_PHONE_TENANT_SK]=`${ge.TENANT}${e.tenantId}`),e.roles!==void 0&&(i[p.ROLES]=e.roles),e.perms!==void 0&&(i[p.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(i[p.AUTH_PERM]=e.authPerm),e.displayName&&(i[p.DISPLAY_NAME]=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.jobTitle&&(i.jobTitle=e.jobTitle),await this.docClient.send(new br.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK)"}));let a={id:e.id,tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.status,inviteToken:e.inviteToken,expiresAt:e.expiresAt,createdAt:W(t),updatedAt:W(t)};return e.inviteeUserId&&(a.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(a.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(a.inviteePhone=e.inviteePhone),e.roles!==void 0&&(a.roles=e.roles),e.perms!==void 0&&(a.perms=e.perms),e.authPerm!==void 0&&(a.authPerm=e.authPerm),e.displayName&&(a.displayName=e.displayName),e.givenName&&(a.givenName=e.givenName),e.familyName&&(a.familyName=e.familyName),e.jobTitle&&(a.jobTitle=e.jobTitle),T(a)}catch(t){return t.name==="ConditionalCheckFailedException"?S(O.UniqueConstraintViolation({field:"invite id"})):S(Ir("create invite",t))}}async updateStatus(e,t){try{let n=Ee(),s=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],i={"#inviteStatus":p.INVITE_STATUS,"#inviteTenantSk":p.INVITE_TENANT_SK,"#updatedAt":p.UPDATED_AT},o={":inviteStatus":t.status,":inviteTenantSk":Pe.INVITE_TENANT_SK(t.status,n,e),":updatedAt":n};t.acceptedAt&&(s.push("#acceptedAt = :acceptedAt"),i["#acceptedAt"]=p.ACCEPTED_AT,o[":acceptedAt"]=oe(t.acceptedAt)),t.declinedAt&&(s.push("#declinedAt = :declinedAt"),i["#declinedAt"]=p.DECLINED_AT,o[":declinedAt"]=oe(t.declinedAt)),t.revokedAt&&(s.push("#revokedAt = :revokedAt"),i["#revokedAt"]=p.REVOKED_AT,o[":revokedAt"]=oe(t.revokedAt));let a=[];t.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),i["#inviteTokenGsi"]=p.INVITE_TOKEN_GSI,i["#inviteeEmailGsi"]=p.INVITEE_EMAIL_GSI,i["#inviteeEmailTenantSk"]=p.INVITEE_EMAIL_TENANT_SK,i["#inviteePhoneGsi"]=p.INVITEE_PHONE_GSI,i["#inviteePhoneTenantSk"]=p.INVITEE_PHONE_TENANT_SK);let c=`SET ${s.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new br.UpdateCommand({TableName:this.tableName,Key:{PK:P.INVITE_PK(e),SK:P.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:i,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"TenantInvite",id:e})):S(Ir("updateStatus invite",n))}}async findByTenantAndEmail(e,t){try{let s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":p.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":p.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":t,":tenantSk":`${ge.TENANT}${e}`},Limit:1}))).Items;return!s||s.length===0?T(null):T(this.mapItemToEntity(s[0]))}catch(n){return S(V("findByTenantAndEmail",n))}}async findByTenantAndPhone(e,t){try{let s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":p.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":p.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":t,":tenantSk":`${ge.TENANT}${e}`},Limit:1}))).Items;return!s||s.length===0?T(null):T(this.mapItemToEntity(s[0]))}catch(n){return S(V("findByTenantAndPhone",n))}}async findByTenantAndUserId(e,t){try{let s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":p.INVITE_TENANT_PK,"#sk":p.INVITE_TENANT_SK,"#inviteeUserId":p.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":Pe.INVITE_TENANT_PK(e),":pendingPrefix":Pe.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":t},Limit:1}))).Items;return!s||s.length===0?T(null):T(this.mapItemToEntity(s[0]))}catch(n){return S(V("findByTenantAndUserId",n))}}async listByTenant(e,t){try{let n=Math.min(t?.limit||50,100),s={"#pk":p.INVITE_TENANT_PK},i={":pk":Pe.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:s,ExpressionAttributeValues:i,ScanIndexForward:!1,Limit:n};t?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))),t?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",s["#sk"]=p.INVITE_TENANT_SK,i[":statusPrefix"]=Pe.INVITE_TENANT_STATUS_PREFIX(t.status));let a=await this.docClient.send(new br.QueryCommand(o)),c=(a.Items||[]).map(d=>this.mapItemToEntity(d)),u=!!a.LastEvaluatedKey,l=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return tt(c,{limit:n,hasNext:u,cursor:l,prevCursor:t?.cursor??null})}catch(n){return S(V("listByTenant",n))}}async findPendingByEmail(e){try{let t=Ee(),s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":p.INVITEE_EMAIL_GSI,"#expiresAt":p.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":t}}))).Items||[];if(s.length===0)return T([]);let i=s.map(c=>({PK:c.PK,SK:c.SK})),a=(await Wl(this.docClient,this.tableName,i)).map(c=>this.mapItemToEntity(c));return T(a)}catch(t){return S(V("findPendingByEmail",t))}}async findPendingByPhone(e){try{let t=Ee(),s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":p.INVITEE_PHONE_GSI,"#expiresAt":p.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":t}}))).Items||[];if(s.length===0)return T([]);let i=s.map(c=>({PK:c.PK,SK:c.SK})),a=(await Wl(this.docClient,this.tableName,i)).map(c=>this.mapItemToEntity(c));return T(a)}catch(t){return S(V("findPendingByPhone",t))}}async countPendingByTenant(e){try{let t=await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":p.INVITE_TENANT_PK,"#sk":p.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":Pe.INVITE_TENANT_PK(e),":pendingPrefix":Pe.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return T(t.Count??0)}catch(t){return S(V("countPendingByTenant",t))}}async expireOld(e){return T(0)}};var bQ=Ae(Kt(),1);var $m=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,t){try{let n=Math.min(t?.limit||50,100),s={TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":P.TENANT_MEMBER_PK(e)}};t?.cursor&&(s.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8")));let o=(await this.docClient.send(new bQ.QueryCommand(s))).Items||[],a=[],c=new Map;for(let h of o){let g=h.SK;if(g.startsWith(ut.TENANT_PROFILE)){let A=ye.tenantProfileUserId(g);c.set(A,h)}else g.startsWith(ge.USER)&&a.push(h)}a.sort((h,g)=>g.createdAt-h.createdAt);let u=a.slice(0,n),l=a.length>n,d=u.map(h=>{let g=ye.tenantMemberUserId(h.SK),A=c.get(g);return this.toListItem(h,e,g,A)}),f=l&&u.length>0?Buffer.from(JSON.stringify({PK:u[u.length-1].PK,SK:u[u.length-1].SK})).toString("base64url"):null;return tt(d,{limit:n,hasNext:l,cursor:f,prevCursor:t?.cursor??null})}catch(n){return S(V("listByTenant query",n))}}toListItem(e,t,n,s){let i={tenantId:t,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};if(e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),s){let o={tenantId:t,userId:n,createdAt:W(s.createdAt),updatedAt:W(s.updatedAt)};s.contactEmail&&(o.contactEmail=s.contactEmail),s.contactPhone&&(o.contactPhone=s.contactPhone),s.displayName&&(o.displayName=s.displayName),s.displayNameSource&&(o.displayNameSource=s.displayNameSource),s.givenName&&(o.givenName=s.givenName),s.familyName&&(o.familyName=s.familyName),s.avatarUrl&&(o.avatarUrl=s.avatarUrl),s.locale&&(o.locale=s.locale),s.jobTitle&&(o.jobTitle=s.jobTitle),s.bio&&(o.bio=s.bio),s.metadata&&(o.metadata=JSON.parse(s.metadata)),i.tenantProfile=o}return i}};var wr=Ae(Kt(),1);var Fm=class{tableName;docClient;constructor(e,t){this.tableName=t,this.docClient=wr.DynamoDBDocumentClient.from(e)}mapItemToEntity(e){let t=ye.tenantId(e.PK),n=ye.tenantMemberUserId(e.SK),s={tenantId:t,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};return e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm),s}async get(e,t){try{let n=await this.docClient.send(new wr.GetCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_MEMBER_SK(t)}}));if(!n.Item)return T(null);let s=this.mapItemToEntity(n.Item);return T(s)}catch(n){return S(V("get",n))}}async create(e){try{let t=Ee(),n=e.isOwner?void 0:e.authPerm,s=Ur({PK:P.TENANT_MEMBER_PK(e.tenantId),SK:P.TENANT_MEMBER_SK(e.userId),userStatus:e.status,roles:e.roles,perms:e.perms!==void 0?JSON.stringify(e.perms):void 0,authPerm:n,isOwner:e.isOwner,createdAt:t,updatedAt:t,userTenantPk:Pe.USER_TENANT_PK(e.userId),userTenantSk:Pe.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,t,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new wr.TransactWriteCommand({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:P.TENANT_MEMBER_PK(e.tenantId),SK:P.TENANT_OWNER_MARKER_SK(),createdAt:t},ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}},{Put:{TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}}]})):await this.docClient.send(new wr.PutCommand({TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(void 0)}catch(t){return t.name==="TransactionCanceledException"?t.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?S(O.UniqueConstraintViolation({field:"tenant owner"})):S(O.UniqueConstraintViolation({field:"tenant member"})):t.name==="ConditionalCheckFailedException"?S(O.UniqueConstraintViolation({field:"tenant member"})):S(Ir("create tenant member",t))}}async updatePermissions(e,t,n){try{let s={...n,updatedAt:Ee()},{UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=Os(s);return await this.docClient.send(new wr.UpdateCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_MEMBER_SK(t)},UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(s){return s.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"TenantMember",id:`${e}:${t}`})):S(Ir("updatePermissions tenant member",s))}}async updateStatus(e,t,n){try{return await this.docClient.send(new wr.UpdateCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_MEMBER_SK(t)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":Ee()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(s){return s.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"TenantMember",id:`${e}:${t}`})):S(Ir("updateStatus tenant member",s))}}async listByTenant(e,t){try{let n=Math.min(t?.limit||50,100),s={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":P.TENANT_MEMBER_PK(e),":skPrefix":ge.USER},Limit:n};t?.cursor&&(s.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8")));let i=await this.docClient.send(new wr.QueryCommand(s)),o=(i.Items||[]).map(u=>this.mapItemToEntity(u)),a=!!i.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(i.LastEvaluatedKey)).toString("base64url"):null;return tt(o,{limit:n,hasNext:a,cursor:c,prevCursor:t?.cursor??null})}catch(n){return S(V("listByTenant",n))}}async hasOwner(e){try{let t=await this.docClient.send(new wr.GetCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_OWNER_MARKER_SK()}}));return T(!!t.Item)}catch(t){return S(V("hasOwner",t))}}async remove(e,t){try{return await this.docClient.send(new wr.DeleteCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_MEMBER_SK(t)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"TenantMember",id:`${e}:${t}`})):S(Ir("remove tenant member",n))}}};var wT=Ae(Kt(),1);var Bm=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByUser(e,t){try{let n=Math.min(t?.limit??50,100),s=t?.tenantType??dO.DEFAULT,i=t?.parentTenantId,o=i?`${s}#${i}#`:`${s}#`,a={TableName:this.tableName,IndexName:Se.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":Pe.USER_TENANT_PK(e),":skPrefix":o},ScanIndexForward:!1,Limit:n};t?.cursor&&(a.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8")));let c=await this.docClient.send(new wT.QueryCommand(a)),u=c.Items??[],l=await this.fetchProfileMap(e,u),d=u.map(g=>this.toListItem(g,e,l)),f=!!c.LastEvaluatedKey,h=f?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return tt(d,{limit:n,hasNext:f,cursor:h,prevCursor:t?.cursor??null})}catch(n){return S(V("listByUser query",n))}}async fetchProfileMap(e,t){let n=new Map;if(t.length===0)return n;let s=t.map(o=>({PK:P.TENANT_PROFILE_PK(ye.tenantId(o.PK)),SK:P.TENANT_PROFILE_SK(e)})),i=await this.docClient.send(new wT.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:s}}}));for(let o of i.Responses?.[this.tableName]??[]){let a=o,c=ye.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,t,n){let s=ye.tenantId(e.PK),i={tenantId:s,userId:t,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm);let o=n.get(s);return o&&(o.contactEmail&&(i.contactEmail=o.contactEmail),o.contactPhone&&(i.contactPhone=o.contactPhone),o.displayName&&(i.displayName=o.displayName),o.displayNameSource&&(i.displayNameSource=o.displayNameSource),o.givenName&&(i.givenName=o.givenName),o.familyName&&(i.familyName=o.familyName),o.avatarUrl&&(i.avatarUrl=o.avatarUrl),o.locale&&(i.locale=o.locale),o.jobTitle&&(i.jobTitle=o.jobTitle),o.bio&&(i.bio=o.bio),o.metadata&&(i.metadata=JSON.parse(o.metadata))),i}};var Sa=Ae(Kt(),1);var Km=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return At()}toEntity(e){let n={id:ye.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let t=await this.docClient.send(new Sa.GetCommand({TableName:this.tableName,Key:{PK:P.TENANT_PK(e),SK:P.TENANT_SK()}}));return t.Item?T(this.toEntity(t.Item)):T(null)}catch(t){return S(V("get tenant",t))}}async create(e){try{let t=e.id??this.generateTenantId(),n=Ee(),s=Ur({PK:P.TENANT_PK(t),SK:P.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new Sa.PutCommand({TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(void 0)}catch(t){return t.name==="ConditionalCheckFailedException"?S(O.UniqueConstraintViolation({field:"tenant"})):S(Ir("create tenant",t))}}async update(e,t){try{let n={updatedAt:Ee()};t.type!==void 0&&(n.tenantType=t.type),t.ownerId!==void 0&&(n.ownerId=t.ownerId),t.parentTenantId!==void 0&&(n.parentTenantId=t.parentTenantId===null?void 0:t.parentTenantId);let{UpdateExpression:s,ExpressionAttributeNames:i,ExpressionAttributeValues:o}=Os(n);return await this.docClient.send(new Sa.UpdateCommand({TableName:this.tableName,Key:{PK:P.TENANT_PK(e),SK:P.TENANT_SK()},UpdateExpression:s,ExpressionAttributeNames:i,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"Tenant",id:e})):S(Ir("update tenant",n))}}async delete(e){try{return await this.docClient.send(new Sa.DeleteCommand({TableName:this.tableName,Key:{PK:P.TENANT_PK(e),SK:P.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(t){return t.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"Tenant",id:e})):S(Ir("delete tenant",t))}}async list(){return S(O.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return S(O.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return S(O.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};var Ps=Ae(Kt(),1);var Vm=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let t=await this.docClient.send(new Ps.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()}}));return t.Item?T(this.unmarshall(t.Item,e)):T(null)}catch(t){return S(V("get user auth",t))}}async create(e){try{let t=Ee(),n={...e,createdAt:new Date(t),updatedAt:new Date(t)};return await this.docClient.send(new Ps.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${p.PK})`})),T(n)}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"userAuth"})):S(V("create user auth",t))}}async updateStatus(e,t){try{let n=Ee();return await this.docClient.send(new Ps.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${p.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${p.UPDATED_AT}`]:p.UPDATED_AT},ExpressionAttributeValues:{":userStatus":t,":updatedAt":n},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userAuth",id:e})):S(V("update user auth status",n))}}async updateMfaRequired(e,t){try{let n=Ee();return await this.docClient.send(new Ps.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${p.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${p.UPDATED_AT}`]:p.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":t,":updatedAt":n},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userAuth",id:e})):S(V("update mfa required",n))}}async updateMfaMethods(e,t){try{let n=Ee();return await this.docClient.send(new Ps.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${p.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${p.UPDATED_AT}`]:p.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":t,":updatedAt":n},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userAuth",id:e})):S(V("update mfa methods",n))}}async updateMfaSettings(e,t){try{let n=Ee();return await this.docClient.send(new Ps.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${p.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${p.UPDATED_AT}`]:p.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":t.mfaRequired,":mfaMethods":t.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userAuth",id:e})):S(V("update mfa settings",n))}}async remove(e){try{return await this.docClient.send(new Ps.DeleteCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()}})),T(void 0)}catch(t){return S(V("remove user auth",t))}}marshall(e){return{[p.PK]:P.USER_PK(e.userId),[p.SK]:P.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[p.CREATED_AT]:oe(e.createdAt),[p.UPDATED_AT]:oe(e.updatedAt)}}unmarshall(e,t){return{userId:t,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:W(e[p.CREATED_AT]),updatedAt:W(e[p.UPDATED_AT])}}};var Fr=Ae(Kt(),1);function jl(r,e){return e?P.USER_MFA_WITH_ID_SK(r,e):P.USER_MFA_SK(r)}var Hm=class{client;tableName;docClient;constructor(e,t){this.client=e,this.tableName=t,this.docClient=Fr.DynamoDBDocumentClient.from(e)}toDynamoDBItem(e){let t={PK:P.USER_PK(e.userId),SK:jl(e.method,e.id),method:e.method,data:JSON.stringify(e.data),createdAt:Date.now(),failedAttempts:0};return e.label&&(t.label=e.label),e.verifiedAt&&(t.verifiedAt=e.verifiedAt.getTime()),e.metadata&&(t.metadata=JSON.stringify(e.metadata)),t}fromDynamoDBItem(e,t){let n=ye.mfaSKInfo(e.SK),s={userId:t,method:e.method,data:JSON.parse(e.data),createdAt:W(e.createdAt),verifiedAt:Mr(e.verifiedAt)??null};return n?.id&&(s.id=n.id),e.label&&(s.label=e.label),e.failedAttempts!==void 0&&(s.failedAttempts=e.failedAttempts),e.lastFailedAt!==void 0&&(s.lastFailedAt=Mr(e.lastFailedAt)),e.lockedUntil!==void 0&&(s.lockedUntil=Mr(e.lockedUntil)),e.lastUsedAt!==void 0&&(s.lastUsedAt=Mr(e.lastUsedAt)),e.metadata&&(s.metadata=JSON.parse(e.metadata)),s}async get(e,t,n){try{let s=jl(t,n),i=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:s}}));return i.Item?T(this.fromDynamoDBItem(i.Item,e)):T(null)}catch(s){return S(V("get MFA authenticator",s))}}async findByUserId(e){try{let t={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":P.USER_PK(e),":skPrefix":ut.MFA}},i=((await this.docClient.send(new Fr.QueryCommand(t))).Items??[]).map(o=>this.fromDynamoDBItem(o,e));return T(i)}catch(t){return S(V("find MFA authenticators by user",t))}}async findByUserIdAndMethod(e,t){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":P.USER_PK(e),":skPrefix":`${ut.MFA}${t}`}},o=((await this.docClient.send(new Fr.QueryCommand(n))).Items??[]).filter(a=>a.method===t).map(a=>this.fromDynamoDBItem(a,e));return T(o)}catch(n){return S(V("find MFA authenticators by method",n))}}async create(e){try{let t={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(t.id=At());let n=this.toDynamoDBItem(t);return await this.docClient.send(new Fr.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(this.fromDynamoDBItem(n,e.userId))}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"MFA authenticator"})):S(V("create MFA authenticator",t))}}async update(e,t,n,s){try{let i=jl(t,n),o=[],a={},c={};if(s.label!==void 0&&(o.push("#label = :label"),a["#label"]="label",c[":label"]=s.label),s.data!==void 0&&(o.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(s.data)),s.verifiedAt!==void 0&&(o.push("#verifiedAt = :verifiedAt"),a["#verifiedAt"]="verifiedAt",c[":verifiedAt"]=s.verifiedAt instanceof Date?s.verifiedAt.getTime():s.verifiedAt===null?void 0:s.verifiedAt),s.lastUsedAt!==void 0&&(o.push("#lastUsedAt = :lastUsedAt"),a["#lastUsedAt"]="lastUsedAt",c[":lastUsedAt"]=s.lastUsedAt instanceof Date?s.lastUsedAt.getTime():s.lastUsedAt===null?void 0:s.lastUsedAt),s.failedAttempts!==void 0&&(o.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=s.failedAttempts),s.lastFailedAt!==void 0&&(o.push("#lastFailedAt = :lastFailedAt"),a["#lastFailedAt"]="lastFailedAt",c[":lastFailedAt"]=s.lastFailedAt instanceof Date?s.lastFailedAt.getTime():s.lastFailedAt===null?void 0:s.lastFailedAt),s.lockedUntil!==void 0&&(o.push("#lockedUntil = :lockedUntil"),a["#lockedUntil"]="lockedUntil",c[":lockedUntil"]=s.lockedUntil instanceof Date?s.lockedUntil.getTime():s.lockedUntil===null?void 0:s.lockedUntil),s.metadata!==void 0&&(o.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(s.metadata)),o.length===0)return T(void 0);let u={TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:i},UpdateExpression:`SET ${o.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new Fr.UpdateCommand(u)),T(void 0)}catch(i){return S(V("update MFA authenticator",i))}}async remove(e,t,n){try{let s=jl(t,n);return await this.docClient.send(new Fr.DeleteCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:s}})),T(void 0)}catch(s){return S(V("remove MFA authenticator",s))}}async incrementFailedAttempts(e,t,n,s,i){try{let o=jl(t,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],u={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},l={":zero":0,":inc":1,":lastFailedAt":a};i!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),u["#lockedUntil"]="lockedUntil",l[":lockedUntil"]=a+i*60*1e3,l[":maxAttempts"]=s);let d={TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:o},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:u,ExpressionAttributeValues:l};return await this.docClient.send(new Fr.UpdateCommand(d)),T(void 0)}catch(o){return S(V("increment failed attempts",o))}}async resetFailedAttempts(e,t,n){try{let s=jl(t,n),i={TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:s},UpdateExpression:"SET #failedAttempts = :zero REMOVE #lastFailedAt, #lockedUntil",ExpressionAttributeNames:{"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt","#lockedUntil":"lockedUntil"},ExpressionAttributeValues:{":zero":0}};return await this.docClient.send(new Fr.UpdateCommand(i)),T(void 0)}catch(s){return S(V("reset failed attempts",s))}}async unlock(e,t,n){return this.resetFailedAttempts(e,t,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};var en=Ae(Kt(),1);var Gm=class{tableName;docClient;constructor(e,t){this.tableName=t,this.docClient=en.DynamoDBDocumentClient.from(e)}generateUserId(){return At()}async getById(e){try{let t=await this.docClient.send(new en.GetCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:P.USER_PROFILE_SK()}}));if(!t.Item)return T(null);let n=t.Item;if(n.deletedAt)return T(null);let i={id:ye.userId(n.PK),status:n.userStatus,createdAt:W(n.createdAt),updatedAt:W(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:W(n.deletedAt)},...n.contactEmail!==void 0&&{contactEmail:n.contactEmail},...n.contactPhone!==void 0&&{contactPhone:n.contactPhone},...n.username!==void 0&&{username:n.username},...n.displayName!==void 0&&{displayName:n.displayName},...n.givenName!==void 0&&{givenName:n.givenName},...n.familyName!==void 0&&{familyName:n.familyName},...n.avatarUrl!==void 0&&{avatarUrl:n.avatarUrl},...n.locale!==void 0&&{locale:n.locale},...n.metadata!==void 0&&{metadata:JSON.parse(n.metadata)}};return T(i)}catch(t){return S(V("getById user",t))}}async create(e){try{let t=Ee(),n=e.id||this.generateUserId(),s=e.status||"pending",i={PK:P.USER_PK(n),SK:P.USER_PROFILE_SK(),userStatus:s,createdAt:t,updatedAt:t};e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.username&&(i.username=e.username),e.displayName&&(i.displayName=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.metadata&&(i.metadata=JSON.stringify(e.metadata)),i[p.USER_STATUS_PK]=Pe.USER_STATUS_PK(s),i[p.USER_STATUS_SK]=Pe.USER_STATUS_SK(n),await this.docClient.send(new en.PutCommand({TableName:this.tableName,Item:Ur(i),ConditionExpression:lO("PK")}));let o={id:n,status:s,createdAt:W(t),updatedAt:W(t),...e.contactEmail&&{contactEmail:e.contactEmail},...e.contactPhone&&{contactPhone:e.contactPhone},...e.username&&{username:e.username},...e.displayName&&{displayName:e.displayName},...e.givenName&&{givenName:e.givenName},...e.familyName&&{familyName:e.familyName},...e.avatarUrl&&{avatarUrl:e.avatarUrl},...e.locale&&{locale:e.locale},...e.metadata&&{metadata:e.metadata}};return T(o)}catch(t){return S(V("create user",t))}}async updateProfile(e,t){try{let n=Ee(),s={};if(t.contactEmail!==void 0&&(s.contactEmail=t.contactEmail),t.contactPhone!==void 0&&(s.contactPhone=t.contactPhone),t.displayName!==void 0&&(s.displayName=t.displayName),t.givenName!==void 0&&(s.givenName=t.givenName),t.familyName!==void 0&&(s.familyName=t.familyName),t.avatarUrl!==void 0&&(s.avatarUrl=t.avatarUrl),t.locale!==void 0&&(s.locale=t.locale),t.metadata!==void 0&&(s.metadata=JSON.stringify(t.metadata)),Object.keys(s).length===0)return T(void 0);s.updatedAt=n;let i=Os(s);return await this.docClient.send(new en.UpdateCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:P.USER_PROFILE_SK()},UpdateExpression:i.UpdateExpression,ExpressionAttributeNames:i.ExpressionAttributeNames,ExpressionAttributeValues:i.ExpressionAttributeValues})),T(void 0)}catch(n){return S(V("updateProfile",n))}}async getByStatus(e,t){try{let n=Math.min(t?.limit||50,100),s;if(t?.cursor)try{s=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))}catch{return S(O.DatabaseQueryError({query:"invalid pagination cursor"}))}let i=Pe.USER_STATUS_PK(e),o=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:Se.USERS_BY_STATUS,KeyConditionExpression:`${p.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":i},Limit:n,ExclusiveStartKey:s})),a=[];if(o.Items&&o.Items.length>0)for(let l of o.Items){let d=ye.userId(l.PK);a.push(d)}let c=!!o.LastEvaluatedKey,u=c?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return T(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!t?.cursor,cursor:u}})}catch(n){return S(V("get users by status",n))}}async countByStatus(e){try{let t=Pe.USER_STATUS_PK(e),n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:Se.USERS_BY_STATUS,KeyConditionExpression:`${p.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":t},Select:"COUNT"}));return T(n.Count||0)}catch(t){return S(V("count users by status",t))}}async syncAuthStatus(e,t){try{let n=Ee(),s=`SET userStatus = :userStatus, #${p.UPDATED_AT} = :updatedAt, #${p.USER_STATUS_PK} = :statusPk, #${p.USER_STATUS_SK} = :statusSk`,i={":userStatus":t,":updatedAt":n,":statusPk":Pe.USER_STATUS_PK(t),":statusSk":Pe.USER_STATUS_SK(e)};return t===Bs.DELETED?(s+=", deletedAt = :deletedAt",i[":deletedAt"]=n):s+=" REMOVE deletedAt",await this.docClient.send(new en.UpdateCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:P.USER_PROFILE_SK()},UpdateExpression:s,ExpressionAttributeNames:{[`#${p.UPDATED_AT}`]:p.UPDATED_AT,[`#${p.USER_STATUS_PK}`]:p.USER_STATUS_PK,[`#${p.USER_STATUS_SK}`]:p.USER_STATUS_SK},ExpressionAttributeValues:i,ConditionExpression:"attribute_exists(PK)"})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userProfile",id:e})):S(V("sync auth status",n))}}async remove(e){try{return await this.docClient.send(new en.DeleteCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:P.USER_PROFILE_SK()}})),T(void 0)}catch(t){return S(V("remove user profile",t))}}};var Wn=Ae(Kt(),1);var qm=class{tableName;docClient;constructor(e,t){this.tableName=t,this.docClient=Wn.DynamoDBDocumentClient.from(e)}mapItemToUserProviderLink(e){let t=ye.providerPKInfo(e.PK);if(!t)throw new Error(`Invalid provider PK: ${e.PK}`);let n={userId:e.userId,provider:t.provider,externalId:t.externalId,createdAt:W(e.createdAt)};if(e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata)try{n.metadata=JSON.parse(e.metadata)}catch{}return n}mapUserProviderLinkToItem(e){let t=Ee(),n={PK:P.PROVIDER_PK(e.provider,e.externalId),SK:P.PROVIDER_METADATA_SK(),userProviderPk:P.USER_PK(e.userId),userProviderSk:P.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?oe(e.createdAt):t};return e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),Ur(n)}async findByProviderAndExternalId(e,t){try{let n=await this.docClient.send(new Wn.GetCommand({TableName:this.tableName,Key:{PK:P.PROVIDER_PK(e,t),SK:P.PROVIDER_METADATA_SK()}}));return n.Item?T(this.mapItemToUserProviderLink(n.Item)):T(null)}catch(n){return S(V("find provider by external id",n))}}async findByUserId(e){try{let t=await this.docClient.send(new Wn.QueryCommand({TableName:this.tableName,IndexName:Se.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":p.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":P.USER_PK(e)}}));return!t.Items||t.Items.length===0?T([]):T(t.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch(t){return S(V("find providers by user id",t))}}async create(e){try{let t={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(t);return await this.docClient.send(new Wn.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),T(this.mapItemToUserProviderLink(n))}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):S(V("create user provider",t))}}async update(e,t,n){try{let s={};if(n.externalUsername!==void 0&&(s.externalUsername=n.externalUsername),n.externalEmail!==void 0&&(s.externalEmail=n.externalEmail),n.externalPhone!==void 0&&(s.externalPhone=n.externalPhone),n.externalName!==void 0&&(s.externalName=n.externalName),n.externalAvatarUrl!==void 0&&(s.externalAvatarUrl=n.externalAvatarUrl),n.metadata!==void 0&&(s.metadata=JSON.stringify(n.metadata)),Object.keys(s).length===0)return T(void 0);let{UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=Os(s);return await this.docClient.send(new Wn.UpdateCommand({TableName:this.tableName,Key:{PK:P.PROVIDER_PK(e,t),SK:P.PROVIDER_METADATA_SK()},UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a})),T(void 0)}catch(s){return S(V("update user provider",s))}}async remove(e,t){try{return await this.docClient.send(new Wn.DeleteCommand({TableName:this.tableName,Key:{PK:P.PROVIDER_PK(e,t),SK:P.PROVIDER_METADATA_SK()}})),T(void 0)}catch(n){return S(V("delete user provider",n))}}};var _a=Ae(Kt(),1);var Wm=class{docClient;tableName;constructor(e,t){this.docClient=e,this.tableName=t}mapItemToEntity(e){let t=ye.tenantId(e.PK),n=ye.tenantProfileUserId(e.SK),s={tenantId:t,userId:n,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};return e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.displayName&&(s.displayName=e.displayName),e.displayNameSource&&(s.displayNameSource=e.displayNameSource),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.avatarUrl&&(s.avatarUrl=e.avatarUrl),e.locale&&(s.locale=e.locale),e.jobTitle&&(s.jobTitle=e.jobTitle),e.bio&&(s.bio=e.bio),e.metadata&&(s.metadata=JSON.parse(e.metadata)),s}async get(e,t){try{let n=await this.docClient.send(new _a.GetCommand({TableName:this.tableName,Key:{PK:P.TENANT_PROFILE_PK(e),SK:P.TENANT_PROFILE_SK(t)}}));return n.Item?T(this.mapItemToEntity(n.Item)):T(null)}catch(n){return S(V("get user tenant profile",n))}}async create(e){try{let t=Ee(),n={PK:P.TENANT_PROFILE_PK(e.tenantId),SK:P.TENANT_PROFILE_SK(e.userId),createdAt:t,updatedAt:t};e.contactEmail&&(n.contactEmail=e.contactEmail),e.contactPhone&&(n.contactPhone=e.contactPhone),e.displayName&&(n.displayName=e.displayName),e.displayNameSource&&(n.displayNameSource=e.displayNameSource),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.locale&&(n.locale=e.locale),e.jobTitle&&(n.jobTitle=e.jobTitle),e.bio&&(n.bio=e.bio),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),await this.docClient.send(new _a.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let s={tenantId:e.tenantId,userId:e.userId,createdAt:W(t),updatedAt:W(t)};return e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.displayName&&(s.displayName=e.displayName),e.displayNameSource&&(s.displayNameSource=e.displayNameSource),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.avatarUrl&&(s.avatarUrl=e.avatarUrl),e.locale&&(s.locale=e.locale),e.jobTitle&&(s.jobTitle=e.jobTitle),e.bio&&(s.bio=e.bio),e.metadata&&(s.metadata=e.metadata),T(s)}catch(t){return t.name==="ConditionalCheckFailedException"?S(O.UniqueConstraintViolation({field:"user tenant profile"})):S(Ir("create user tenant profile",t))}}async update(e,t,n){try{let s={updatedAt:Ee()};n.contactEmail!==void 0&&(s.contactEmail=n.contactEmail),n.contactPhone!==void 0&&(s.contactPhone=n.contactPhone),n.displayName!==void 0&&(s.displayName=n.displayName),n.displayNameSource!==void 0&&(s.displayNameSource=n.displayNameSource),n.givenName!==void 0&&(s.givenName=n.givenName),n.familyName!==void 0&&(s.familyName=n.familyName),n.avatarUrl!==void 0&&(s.avatarUrl=n.avatarUrl),n.locale!==void 0&&(s.locale=n.locale),n.jobTitle!==void 0&&(s.jobTitle=n.jobTitle),n.bio!==void 0&&(s.bio=n.bio),n.metadata!==void 0&&(s.metadata=n.metadata?JSON.stringify(n.metadata):null);let{UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=Os(s);return await this.docClient.send(new _a.UpdateCommand({TableName:this.tableName,Key:{PK:P.TENANT_PROFILE_PK(e),SK:P.TENANT_PROFILE_SK(t)},UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(s){return s.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"UserTenantProfile",id:`${e}:${t}`})):S(Ir("update user tenant profile",s))}}async remove(e,t){try{return await this.docClient.send(new _a.DeleteCommand({TableName:this.tableName,Key:{PK:P.TENANT_PROFILE_PK(e),SK:P.TENANT_PROFILE_SK(t)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"UserTenantProfile",id:`${e}:${t}`})):S(Ir("remove user tenant profile",n))}}};var xT=class{name="database-dynamodb";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;registration;userAuths;tenantMembers;tenantInvites;userTenantProfiles;tenants;queries;client;tableName;constructor(e){this.tableName=e.tableName,this.client=e.client||new NT.DynamoDBClient(e.clientConfig||{});let t=wQ.DynamoDBDocumentClient.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new Gm(this.client,this.tableName),this.sessions=new Lm({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new qm(this.client,this.tableName),this.userMfaAuthenticators=new Hm(this.client,this.tableName),this.challenges=new Dm({docClient:t,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new Pm({docClient:t,tableName:this.tableName}),this.credentials=new Om({docClient:t,tableName:this.tableName}),this.registration=new km({docClient:t,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new Vm({docClient:t,tableName:this.tableName}),this.tenantMembers=new Fm(this.client,this.tableName),this.tenantInvites=new Um({docClient:t,tableName:this.tableName}),this.userTenantProfiles=new Wm(t,this.tableName),this.tenants=new Km({docClient:t,tableName:this.tableName}),this.queries={tenantInvites:new Mm({docClient:t,tableName:this.tableName}),tenantMembers:new $m({docClient:t,tableName:this.tableName}),tenants:new Bm({docClient:t,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new NT.DescribeTableCommand({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};JO();var QO=1,zY=2,JY=3,QY="auth-craft:internal";async function Txe(r){let e=r.replace(/^0x/,""),t=XY(e),n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),s=new Uint8Array(n.length+t.length);s.set(n),s.set(t,n.length);let i=`-----BEGIN PRIVATE KEY-----
187
+ RETURNING *`,[e.tenantId,e.userId,e.contactEmail??null,e.contactPhone??null,e.displayName??null,e.displayNameSource??null,e.givenName??null,e.familyName??null,e.avatarUrl??null,e.locale??null,e.jobTitle??null,e.bio??null,e.metadata?JSON.stringify(e.metadata):null]);return T(this.toEntity(t[0]))}catch(t){console.error("[DEBUG] user_tenant_profiles insert error:",t);let n=t;return n.code==="23505"?S(O.UniqueConstraintViolation({field:"tenant profile"})):n.code==="23503"?S(O.ForeignKeyViolation({field:"userId"})):S(O.DatabaseQueryError({query:"create user tenant profile"}))}}async update(e,t,n){try{let s=["updated_at = NOW()"],i=[],o=1,a=[["contactEmail","contact_email"],["contactPhone","contact_phone"],["displayName","display_name"],["displayNameSource","display_name_source"],["givenName","given_name"],["familyName","family_name"],["avatarUrl","avatar_url"],["locale","locale"],["jobTitle","job_title"],["bio","bio"]];for(let[c,u]of a)n[c]!==void 0&&(s.push(`${u} = $${o++}`),i.push(n[c]??null));return n.metadata!==void 0&&(s.push(`metadata = $${o++}`),i.push(n.metadata?JSON.stringify(n.metadata):null)),i.length===0?T(void 0):(i.push(e,t),await this.pool.query(`UPDATE user_tenant_profiles SET ${s.join(", ")} WHERE tenant_id = $${o++} AND user_id = $${o}`,i),T(void 0))}catch{return S(O.DatabaseQueryError({query:"update user tenant profile"}))}}async remove(e,t){try{return await this.pool.query("DELETE FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,t]),T(void 0)}catch{return S(O.DatabaseQueryError({query:"remove user tenant profile"}))}}toEntity(e){let t={tenantId:e.tenant_id,userId:e.user_id,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)};return e.contact_email&&(t.contactEmail=e.contact_email),e.contact_phone&&(t.contactPhone=e.contact_phone),e.display_name&&(t.displayName=e.display_name),e.display_name_source&&(t.displayNameSource=e.display_name_source),e.given_name&&(t.givenName=e.given_name),e.family_name&&(t.familyName=e.family_name),e.avatar_url&&(t.avatarUrl=e.avatar_url),e.locale&&(t.locale=e.locale),e.job_title&&(t.jobTitle=e.job_title),e.bio&&(t.bio=e.bio),e.metadata&&(t.metadata=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata),t}};var ow=class{name="database-postgresql";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;userAuths;tenants;tenantMembers;tenantInvites;userTenantProfiles;queries;pool;constructor(e){this.pool=e,this.users=new Wd(e),this.userAuths=new Gd(e),this.sessions=new Ld(e),this.identities=new kd(e),this.credentials=new Pd(e),this.challenges=new Od(e),this.userProviders=new jd(e),this.userMfaAuthenticators=new qd(e),this.tenants=new Hd(e),this.tenantMembers=new Fd(e),this.tenantInvites=new Ud(e),this.userTenantProfiles=new zd(e),this.queries={tenantInvites:new Md(e),tenantMembers:new $d(e),tenants:new Bd(e)}}async initialize(){}async health(){try{let e=await this.pool.connect();return await e.query("SELECT 1"),e.release(),!0}catch{return!1}}async cleanup(){await this.pool.end()}};function jL(r){let e=new lE(r);return new ow(e)}var rne={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function zL(r={}){let e={...rne,...r},n=(()=>{if(r.customRegex)return r.customRegex;let s="[a-zA-Z0-9_\\-]";e.allowDots?(s+="+",s=`(${s}\\.?)+`):s+="+",e.allowPlusAddressing&&(s=`${s}(\\+[a-zA-Z0-9_\\-]+)?`);let i=e.requireTLD?"(?:[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}":"[a-zA-Z0-9][a-zA-Z0-9\\-\\.]*";return new RegExp(`^${s}@${i}$`)})();return{name:"email-identity",version:"1.0.0",identityType:"email",normalize(s){return s.toLowerCase().trim()},validate(s){if(!s||s.trim().length===0)return S([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(s.length>254)return S([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(s))return S([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(s.includes(".."))return S([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let i=s.split("@");if(i.length!==2)return S([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[o,a]=i;return!o||o.length>64?S([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?S([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):T()}}}var NT=Ae(aT(),1),wQ=Ae(Kt(),1);function oe(r){return r.getTime()}function W(r){return new Date(r)}function pQ(r){return Math.floor(r/1e3)}function Ee(){return Date.now()}function vm(r){return r instanceof Date?pQ(r.getTime()):pQ(r)}function uO(r){return r<Date.now()}function Ds(r){return r?oe(r):null}function Mr(r){return r==null?null:W(r)}function Ur(r){let e={};for(let[t,n]of Object.entries(r))n!=null&&(e[t]=n);return e}function Os(r){let e=[],t=[],n={},s={},i=0;for(let[c,u]of Object.entries(r)){if(c==="PK"||c==="SK")continue;let l=`#${c}`;if(n[l]=c,u==null)t.push(l);else{let d=`:val${i}`;e.push(`${l} = ${d}`),s[d]=u,i++}}let o=[];return e.length>0&&o.push(`SET ${e.join(", ")}`),t.length>0&&o.push(`REMOVE ${t.join(", ")}`),{UpdateExpression:o.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:s}}function lO(r="PK"){return`attribute_not_exists(${r})`}var lr={INVITE_MEMBERS:1,REMOVE_MEMBERS:2,VIEW_MEMBERS:4,CHANGE_MEMBER_PERMISSION:8,UPDATE_MEMBER_PROFILE:16,UPDATE_MEMBER_STATUS:32,VIEW_ACCOUNTS:64,UPDATE_ACCOUNT_PROFILE:128,UPDATE_ACCOUNT_STATUS:256,RESET_ACCOUNT_CREDENTIALS:512,REMOVE_ACCOUNTS:1024},Pwe=lr.VIEW_ACCOUNTS|lr.UPDATE_ACCOUNT_PROFILE|lr.UPDATE_ACCOUNT_STATUS|lr.RESET_ACCOUNT_CREDENTIALS|lr.REMOVE_ACCOUNTS;var mQ={[lr.INVITE_MEMBERS]:"tenant.member.invite",[lr.REMOVE_MEMBERS]:"tenant.member.remove",[lr.VIEW_MEMBERS]:"tenant.member.view",[lr.CHANGE_MEMBER_PERMISSION]:"tenant.member.permission",[lr.UPDATE_MEMBER_PROFILE]:"tenant.member.profile.update",[lr.UPDATE_MEMBER_STATUS]:"tenant.member.status.update",[lr.VIEW_ACCOUNTS]:"account.view",[lr.UPDATE_ACCOUNT_PROFILE]:"account.profile.update",[lr.UPDATE_ACCOUNT_STATUS]:"account.status.update",[lr.RESET_ACCOUNT_CREDENTIALS]:"account.credentials.reset",[lr.REMOVE_ACCOUNTS]:"account.remove"},kwe=Object.fromEntries(Object.entries(mQ).map(([r,e])=>[e,Number(r)]));var dO={SYSTEM:"system",DEFAULT:"org"};var fO={USER:"USR"},ge={USER:`${fO.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},ut={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},dr="#",P={USER_PK:r=>`${ge.USER}${r}`,USER_AUTH_SK:()=>ut.AUTH,USER_PROFILE_SK:()=>ut.PROFILE,USER_MFA_SK:r=>`${ut.MFA}${r}`,USER_MFA_WITH_ID_SK:(r,e)=>`${ut.MFA}${r}${dr}${e}`,TENANT_MEMBER_PK:r=>`${ge.TENANT}${r}`,TENANT_MEMBER_SK:r=>`${ge.USER}${r}`,TENANT_OWNER_MARKER_SK:()=>ut.OWNER,TENANT_PK:r=>`${ge.TENANT}${r}`,TENANT_SK:()=>ut.METADATA,INVITE_PK:r=>`${ge.INVITE}${r}`,INVITE_SK:()=>ut.METADATA,TENANT_PROFILE_PK:r=>`${ge.TENANT}${r}`,TENANT_PROFILE_SK:r=>`${ut.TENANT_PROFILE}${ge.USER}${r}`,SESSION_PK:r=>`${ge.SESSION}${r}`,SESSION_METADATA_SK:()=>ut.METADATA,SESSION_SK:()=>ut.METADATA,PROVIDER_SK:(r,e)=>`${ut.PROVIDER}${r}${dr}${e}`,PROVIDER_PK:(r,e)=>`${ge.PROVIDER}${r}${dr}${e}`,PROVIDER_METADATA_SK:()=>ut.METADATA,CHALLENGE_PK:r=>`${ge.CHALLENGE}${r}`,CHALLENGE_SK:()=>ut.METADATA,IDENTITY_PK:(r,e)=>`${ge.IDENTITY}${r}#${e}`,IDENTITY_SK:()=>ut.METADATA,CREDENTIAL_PK:r=>`${ge.CREDENTIAL}${r}`,CREDENTIAL_SK:()=>ut.METADATA,CREDENTIAL_TYPE_PREFIX:r=>`${ge.CREDENTIAL}${r}#`,CREDENTIAL_USER_SK:(r,e)=>`${ge.CREDENTIAL}${r}#${e}`,USER_INDEX_PK:r=>`${ge.USER}${r}`,USER_INDEX_SK:(r,e)=>`${ge.IDENTITY}${r}#${e}`},ye={userId:r=>r.slice(ge.USER.length),sessionId:r=>r.slice(ge.SESSION.length),providerPKInfo:r=>{let e=r.slice(ge.PROVIDER.length),t=e.indexOf("#");if(t===-1)return null;let n=e.slice(0,t),s=e.slice(t+1);return{provider:n,externalId:s}},providerInfo:r=>{let e=r.slice(ut.PROVIDER.length),t=e.indexOf(dr);if(t===-1)return null;let n=e.slice(0,t),s=e.slice(t+1);return{provider:n,externalId:s}},mfaSKInfo:r=>{let e=r.slice(ut.MFA.length),t=e.indexOf(dr);if(t===-1)return{method:e};let n=e.slice(0,t),s=e.slice(t+1);return{method:n,id:s}},tenantId:r=>r.slice(ge.TENANT.length),tenantMemberUserId:r=>r.slice(ge.USER.length),challengeIdFromPK:r=>r.slice(ge.CHALLENGE.length),inviteId:r=>r.slice(ge.INVITE.length),tenantProfileUserId:r=>r.slice(ut.TENANT_PROFILE.length+ge.USER.length),identityPKInfo:r=>{let e=r.slice(ge.IDENTITY.length),t=e.indexOf("#");if(t===-1)return null;let n=e.slice(0,t),s=e.slice(t+1);return{type:n,value:s}},credentialId:r=>r.slice(ge.CREDENTIAL.length),credentialTypeFromUserSK:r=>{let e=r.slice(ge.CREDENTIAL.length),t=e.indexOf("#");return t===-1?"":e.slice(0,t)},userIndexSKInfo:r=>{let e=r.slice(ge.IDENTITY.length),t=e.indexOf("#");if(t===-1)return null;let n=e.slice(0,t),s=e.slice(t+1);return{type:n,value:s}}};var Pe={ACTIVE_SESSION_PK:r=>`${ge.USER}${r}`,ACTIVE_SESSION_SK:(r,e)=>`${r}${dr}${e}`,USER_SESSION_PK:r=>`${ge.USER}${r}`,USER_SESSION_SK:(r,e)=>`${r}${dr}${e}`,USER_STATUS_PK:r=>{let e=r===Bs.ACTIVE?"ACTIVE":"INACTIVE";return`${fO.USER}${dr}${e}`},USER_STATUS_SK:r=>r,USER_PROVIDER_PK:r=>`${ge.USER}${r}`,USER_PROVIDER_SK:(r,e)=>`${ut.PROVIDER}${r}${dr}${e}`,INVITE_TENANT_PK:r=>`${ge.TENANT}${r}`,INVITE_TENANT_SK:(r,e,t)=>`${r}${dr}${e}${dr}${t}`,INVITE_TENANT_STATUS_PREFIX:r=>`${r}${dr}`,USER_TENANT_PK:r=>`${ge.USER}${r}`,USER_TENANT_SK:(r,e,t,n)=>`${r}${dr}${e??"ROOT"}${dr}${t}${dr}${n}`},p={PK:"PK",SK:"SK",TTL:"TTL",ACTIVE_SESSION_PK:"activeSessionPk",ACTIVE_SESSION_SK:"activeSessionSk",USER_SESSION_PK:"userSessionPk",USER_SESSION_SK:"userSessionSk",USER_STATUS_PK:"userStatusPk",USER_STATUS_SK:"userStatusSk",USER_PROVIDER_PK:"userProviderPk",USER_PROVIDER_SK:"userProviderSk",USER_ID:"userId",TENANT_ID:"tenantId",TENANT_TYPE:"tenantType",AUDIENCE:"audience",PURPOSE:"purpose",CHALLENGE_STATUS:"challengeStatus",PHASE:"phase",ALLOWED_METHODS:"allowedMethods",METHOD:"method",IDENTITY_TYPE:"identityType",IDENTITY_VALUE:"identityValue",CODE_HASH:"codeHash",ATTEMPTS:"attempts",MAX_ATTEMPTS:"maxAttempts",METADATA:"metadata",FLOW_KEY:"flowKey",EXPIRES_AT:"expiresAt",CREATED_AT:"createdAt",TOKEN_ID:"tokenId",PREVIOUS_TOKEN_ID:"previousTokenId",ROTATED_AT:"rotatedAt",LAST_USED_AT:"lastUsedAt",REVOKED_AT:"revokedAt",ROLE:"role",ROLES:"roles",PERM:"perm",AUTH_PERM:"authPerm",IS_OWNER:"isOwner",DEVICE_LABEL:"deviceLabel",COUNTRY:"country",CITY:"city",IDENTITY_USER_PK:"identityUserPk",IDENTITY_USER_SK:"identityUserSk",LOGIN_ENABLED:"loginEnabled",VERIFIED_AT:"verifiedAt",GUARDS:"guards",PENDING_VERIFICATION:"pendingVerification",UPDATED_AT:"updatedAt",CREDENTIAL_USER_PK:"credentialUserPk",CREDENTIAL_USER_SK:"credentialUserSk",CREDENTIAL_VALUE:"value",INVITE_STATUS:"inviteStatus",INVITE_TOKEN:"inviteToken",INVITED_BY_ID:"invitedById",INVITED_BY_INFO:"invitedByInfo",INVITEE_USER_ID:"inviteeUserId",INVITEE_EMAIL:"inviteeEmail",INVITEE_PHONE:"inviteePhone",ACCEPTED_AT:"acceptedAt",DECLINED_AT:"declinedAt",INVITE_TENANT_PK:"inviteTenantPk",INVITE_TENANT_SK:"inviteTenantSk",INVITE_TOKEN_GSI:"inviteTokenGsi",INVITEE_EMAIL_GSI:"inviteeEmailGsi",INVITEE_EMAIL_TENANT_SK:"inviteeEmailTenantSk",INVITEE_PHONE_GSI:"inviteePhoneGsi",INVITEE_PHONE_TENANT_SK:"inviteePhoneTenantSk",USER_TENANT_PK:"userTenantPk",USER_TENANT_SK:"userTenantSk",DISPLAY_NAME:"displayName",AVATAR_URL:"avatarUrl",TITLE:"title",BIO:"bio"},bT={sessionSK:(r,e)=>`${r instanceof Date?r.getTime():r}${dr}${e}`,extractCreatedAt:r=>{let e=r.indexOf(dr),t=e===-1?r:r.slice(0,e);return Number(t)}};var Se={ACTIVE_SESSIONS:"GSI_ActiveSessions",USER_SESSIONS:"GSI_UserSessions",USERS_BY_STATUS:"GSI_UsersByStatus",USER_PROVIDERS:"GSI_UserProviders",USER_IDENTITIES:"GSI_UserIdentities",USER_CREDENTIALS:"GSI_UserCredentials",TENANT_INVITES:"GSI_TenantInvites",INVITE_TOKEN:"GSI_InviteToken",INVITEE_EMAIL:"GSI_InviteeEmail",INVITEE_PHONE:"GSI_InviteePhone",USER_TENANTS:"GSI_UserTenants"},gt="S",Lwe={partitionKey:{name:"PK",type:gt},sortKey:{name:"SK",type:gt},ttlAttribute:"TTL",globalSecondaryIndexes:[{indexName:Se.ACTIVE_SESSIONS,partitionKey:{name:"activeSessionPk",type:gt},sortKey:{name:"activeSessionSk",type:gt},projection:{type:"KEYS_ONLY"}},{indexName:Se.USER_SESSIONS,partitionKey:{name:"userSessionPk",type:gt},sortKey:{name:"userSessionSk",type:gt},projection:{type:"KEYS_ONLY"}},{indexName:Se.USERS_BY_STATUS,partitionKey:{name:"userStatusPk",type:gt},sortKey:{name:"userStatusSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["displayName","createdAt"]}},{indexName:Se.USER_PROVIDERS,partitionKey:{name:"userProviderPk",type:gt},sortKey:{name:"userProviderSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["userId","externalEmail","externalName","createdAt"]}},{indexName:Se.USER_IDENTITIES,partitionKey:{name:"identityUserPk",type:gt},sortKey:{name:"identityUserSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["loginEnabled","verifiedAt","createdAt"]}},{indexName:Se.USER_CREDENTIALS,partitionKey:{name:"credentialUserPk",type:gt},sortKey:{name:"credentialUserSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["revokedAt","createdAt"]}},{indexName:Se.USER_TENANTS,partitionKey:{name:"userTenantPk",type:gt},sortKey:{name:"userTenantSk",type:gt},projection:{type:"INCLUDE",nonKeyAttributes:["userStatus","role","roles","perm","authPerm","isOwner","createdAt","updatedAt"]}},{indexName:Se.TENANT_INVITES,partitionKey:{name:"inviteTenantPk",type:gt},sortKey:{name:"inviteTenantSk",type:gt},projection:{type:"ALL"}},{indexName:Se.INVITE_TOKEN,partitionKey:{name:"inviteTokenGsi",type:gt},projection:{type:"KEYS_ONLY"}},{indexName:Se.INVITEE_EMAIL,partitionKey:{name:"inviteeEmailGsi",type:gt},sortKey:{name:"inviteeEmailTenantSk",type:gt},projection:{type:"ALL"}},{indexName:Se.INVITEE_PHONE,partitionKey:{name:"inviteePhoneGsi",type:gt},sortKey:{name:"inviteePhoneTenantSk",type:gt},projection:{type:"ALL"}}]};var mo=Ae(Kt(),1);function ql(r){if(typeof r=="object"&&r!==null&&"name"in r){let{name:e}=r;return typeof e=="string"?e:void 0}}function Je(r){return ql(r)==="ConditionalCheckFailedException"}function Mwe(r){let e=ql(r),t=r instanceof Error?r.message:typeof r=="string"?r:void 0;return[e,t].filter(Boolean).join(": ")||String(r)}function hQ(r,e){console.error(`[repo-plugin-dynamodb] ${r} failed \u2014 ${Mwe(e)}`)}function V(r,e){return hQ(r,e),O.DatabaseQueryError({query:r})}function Ir(r,e){return hQ(r,e),O.UnknownError({message:r})}var Dm=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return At()}async get(e){try{let t=await this.docClient.send(new mo.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.CHALLENGE_PK(e),[p.SK]:P.CHALLENGE_SK()}}));if(!t.Item)return T(null);let n=this.unmarshall(t.Item);return uO(oe(n.expiresAt))?T(null):T(n)}catch(t){return S(V("get challenge",t))}}async create(e){try{let t=Ee(),n=e.id||this.generateChallengeId(),s={...e,id:n,createdAt:W(t)},i=oe(e.expiresAt),o=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new mo.PutCommand({TableName:this.tableName,Item:this.marshall(s,o)})),T(s)}catch(t){return S(V("create challenge",t))}}async update(e,t){try{let n=[],s={},i={};return t.method!==void 0&&(n.push("#method = :method"),s["#method"]=p.METHOD,i[":method"]=t.method),t.phase!==void 0&&(n.push("#phase = :phase"),s["#phase"]=p.PHASE,i[":phase"]=t.phase),t.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),s["#codeHash"]=p.CODE_HASH,i[":codeHash"]=t.codeHash),t.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),s["#challengeStatus"]=p.CHALLENGE_STATUS,i[":challengeStatus"]=t.status),n.length===0?T(void 0):(await this.docClient.send(new mo.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.CHALLENGE_PK(e),[p.SK]:P.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:i})),T(void 0))}catch(n){return S(V("update challenge",n))}}async incrementAttempts(e,t){let n={":zero":0,":inc":1},s;t!==void 0&&(s="attribute_not_exists(#attempts) OR #attempts < :max",n[":max"]=t);try{let o=(await this.docClient.send(new mo.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.CHALLENGE_PK(e),[p.SK]:P.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...s?{ConditionExpression:s}:{},ExpressionAttributeNames:{"#attempts":p.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[p.ATTEMPTS]??0;return T(o)}catch(i){return Je(i)?S(O.AttemptsExceeded()):S(V("increment challenge attempts",i))}}async remove(e){try{return await this.docClient.send(new mo.DeleteCommand({TableName:this.tableName,Key:{[p.PK]:P.CHALLENGE_PK(e),[p.SK]:P.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":p.PK}})),T(void 0)}catch(t){return Je(t)?T(void 0):S(V("remove challenge",t))}}marshall(e,t){let n={[p.PK]:P.CHALLENGE_PK(e.id),[p.SK]:P.CHALLENGE_SK(),[p.USER_ID]:e.userId,[p.PURPOSE]:e.purpose,[p.CHALLENGE_STATUS]:e.status,[p.EXPIRES_AT]:oe(e.expiresAt),[p.CREATED_AT]:oe(e.createdAt),[p.TTL]:t};return e.tenantId&&(n[p.TENANT_ID]=e.tenantId),e.phase&&(n[p.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[p.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[p.METHOD]=e.method),e.codeHash&&(n[p.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[p.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[p.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[p.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[p.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[p.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[p.COUNTRY]=e.country),e.city&&(n[p.CITY]=e.city),e.metadata&&(n[p.METADATA]=e.metadata),e.flowKey&&(n[p.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:ye.challengeIdFromPK(e[p.PK]),userId:e[p.USER_ID],purpose:e[p.PURPOSE],status:e[p.CHALLENGE_STATUS],expiresAt:W(e[p.EXPIRES_AT]),createdAt:W(e[p.CREATED_AT])};return e[p.TENANT_ID]&&(n.tenantId=e[p.TENANT_ID]),e[p.PHASE]&&(n.phase=e[p.PHASE]),e[p.ALLOWED_METHODS]&&(n.allowedMethods=e[p.ALLOWED_METHODS]),e[p.METHOD]&&(n.method=e[p.METHOD]),e[p.CODE_HASH]&&(n.codeHash=e[p.CODE_HASH]),e[p.ATTEMPTS]!==void 0&&(n.attempts=e[p.ATTEMPTS]),e[p.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[p.MAX_ATTEMPTS]),e[p.IDENTITY_TYPE]&&(n.identityType=e[p.IDENTITY_TYPE]),e[p.IDENTITY_VALUE]&&(n.identityValue=e[p.IDENTITY_VALUE]),e[p.DEVICE_LABEL]&&(n.deviceLabel=e[p.DEVICE_LABEL]),e[p.COUNTRY]&&(n.country=e[p.COUNTRY]),e[p.CITY]&&(n.city=e[p.CITY]),e[p.METADATA]&&(n.metadata=e[p.METADATA]),e[p.FLOW_KEY]&&(n.flowKey=e[p.FLOW_KEY]),n}};var $r=Ae(Kt(),1);var Om=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return At()}async get(e){try{let t=await this.docClient.send(new $r.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.CREDENTIAL_PK(e),[p.SK]:P.CREDENTIAL_SK()}}));return t.Item?T(this.unmarshall(t.Item)):T(null)}catch(t){return S(V("get credential",t))}}async getByUserIdAndType(e,t){try{let n=await this.docClient.send(new $r.QueryCommand({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${p.CREDENTIAL_USER_PK} = :userPk AND begins_with(${p.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":P.USER_PK(e),":typePrefix":P.CREDENTIAL_TYPE_PREFIX(t)},Limit:1}));if(!n.Items||n.Items.length===0)return T(null);let s=n.Items[0];if(!s)return T(null);let i=ye.credentialId(s[p.PK]);return this.get(i)}catch(n){return S(V("get credential by user and type",n))}}async getByUserId(e){try{let t=await this.docClient.send(new $r.QueryCommand({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${p.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":P.USER_PK(e)}}));if(!t.Items||t.Items.length===0)return T([]);let n=t.Items.map(o=>ye.credentialId(o[p.PK])),s=await this.batchGet(n);if(s.ok===!1)return S(s.errors,s.meta);if(!s.data)return T([]);let i=s.data.filter(o=>o!==null);return T(i)}catch(t){return S(V("get credentials by user",t))}}async create(e){try{let t=Ee(),n=this.generateCredentialId(),s={revokedAt:null,lastUsedAt:null,...e,id:n,createdAt:new Date(t),updatedAt:new Date(t)};return await this.docClient.send(new $r.PutCommand({TableName:this.tableName,Item:this.marshall(s),ConditionExpression:`attribute_not_exists(${p.PK})`})),T(s)}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"credential"})):S(V("create credential",t))}}async update(e,t){try{let n=Ee(),s=[],i={},o={};return s.push(`#${p.UPDATED_AT} = :updatedAt`),i[`#${p.UPDATED_AT}`]=p.UPDATED_AT,o[":updatedAt"]=n,t.value!==void 0&&(s.push(`#${p.CREDENTIAL_VALUE} = :value`),i[`#${p.CREDENTIAL_VALUE}`]=p.CREDENTIAL_VALUE,o[":value"]=t.value),t.data!==void 0&&(s.push(`#${p.METADATA} = :data`),i[`#${p.METADATA}`]=p.METADATA,o[":data"]=t.data),t.revokedAt!==void 0&&(s.push(`#${p.REVOKED_AT} = :revokedAt`),i[`#${p.REVOKED_AT}`]=p.REVOKED_AT,o[":revokedAt"]=t.revokedAt?oe(t.revokedAt):null),t.lastUsedAt!==void 0&&(s.push(`#${p.LAST_USED_AT} = :lastUsedAt`),i[`#${p.LAST_USED_AT}`]=p.LAST_USED_AT,o[":lastUsedAt"]=t.lastUsedAt?oe(t.lastUsedAt):null),await this.docClient.send(new $r.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.CREDENTIAL_PK(e),[p.SK]:P.CREDENTIAL_SK()},UpdateExpression:`SET ${s.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"credential",id:e})):S(V("update credential",n))}}async remove(e){try{return await this.docClient.send(new $r.DeleteCommand({TableName:this.tableName,Key:{[p.PK]:P.CREDENTIAL_PK(e),[p.SK]:P.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(t){return Je(t)?S(O.NotFound({entity:"credential",id:e})):S(V("delete credential",t))}}async hasType(e,t){try{let n=await this.docClient.send(new $r.QueryCommand({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${p.CREDENTIAL_USER_PK} = :userPk AND begins_with(${p.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":P.USER_PK(e),":typePrefix":P.CREDENTIAL_TYPE_PREFIX(t)},Select:"COUNT",Limit:1}));return T((n.Count||0)>0)}catch(n){return S(V("check credential type",n))}}async countByUserId(e){try{let t=await this.docClient.send(new $r.QueryCommand({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${p.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":P.USER_PK(e)},Select:"COUNT"}));return T(t.Count||0)}catch(t){return S(V("count credentials",t))}}async batchGet(e){if(e.length===0)return T([]);try{let t=[];for(let s=0;s<e.length;s+=100)t.push(e.slice(s,s+100));let n=[];for(let s of t){let o=(await this.docClient.send(new $r.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:s.map(c=>({[p.PK]:P.CREDENTIAL_PK(c),[p.SK]:P.CREDENTIAL_SK()}))}}}))).Responses?.[this.tableName]||[],a=new Map;for(let c of o){let u=this.unmarshall(c);a.set(u.id,u)}for(let c of s)n.push(a.get(c)||null)}return T(n)}catch(t){return S(V("batch get credentials",t))}}marshall(e){let t={[p.PK]:P.CREDENTIAL_PK(e.id),[p.SK]:P.CREDENTIAL_SK(),[p.CREDENTIAL_USER_PK]:P.USER_PK(e.userId),[p.CREDENTIAL_USER_SK]:P.CREDENTIAL_USER_SK(e.type,e.id),[p.USER_ID]:e.userId,[p.CREDENTIAL_VALUE]:e.value,[p.METADATA]:e.data,[p.REVOKED_AT]:e.revokedAt?oe(e.revokedAt):null,[p.CREATED_AT]:oe(e.createdAt),[p.UPDATED_AT]:oe(e.updatedAt)};return e.lastUsedAt&&(t[p.LAST_USED_AT]=oe(e.lastUsedAt)),t}unmarshall(e){let t=ye.credentialId(e[p.PK]),n=ye.credentialTypeFromUserSK(e[p.CREDENTIAL_USER_SK]);return{id:t,userId:e[p.USER_ID],type:n,value:e[p.CREDENTIAL_VALUE],data:e[p.METADATA]||{},revokedAt:Mr(e[p.REVOKED_AT]),createdAt:W(e[p.CREATED_AT]),updatedAt:W(e[p.UPDATED_AT]),lastUsedAt:Mr(e[p.LAST_USED_AT])}}};var Zr=Ae(Kt(),1);function pO(r){return{failedAttempts:r.failedAttempts,lastFailedAt:Ds(r.lastFailedAt),lockedUntil:Ds(r.lockedUntil)}}function EQ(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))e[t]={failedAttempts:n.failedAttempts??0,lastFailedAt:Mr(n.lastFailedAt),lockedUntil:Mr(n.lockedUntil)};return e}function gQ(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))n&&(e[t]=pO(n));return e}var Pm=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e,t){try{let n=await this.docClient.send(new Zr.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.IDENTITY_PK(e,t),[p.SK]:P.IDENTITY_SK()}}));if(!n.Item)return T(null);let s=this.unmarshall(n.Item);return T(s)}catch(n){return S(V("get identity",n))}}async getByUserId(e){try{let t=await this.docClient.send(new Zr.QueryCommand({TableName:this.tableName,IndexName:Se.USER_IDENTITIES,KeyConditionExpression:`${p.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":P.USER_INDEX_PK(e)}})),n=[];for(let s of t.Items||[]){let i=this.unmarshall(s);i!==null&&n.push(i)}return T(n)}catch(t){return S(V("get identities by userId",t))}}async create(e){try{let t=Ee(),n={...e,createdAt:W(t),updatedAt:W(t)};return await this.docClient.send(new Zr.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),T(n)}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"identity"})):S(V("create identity",t))}}async update(e,t,n){try{let s=[],i=[],o={},a={};if(n.loginEnabled!==void 0&&(s.push("#loginEnabled = :loginEnabled"),o["#loginEnabled"]=p.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let u=Ds(n.verifiedAt);u===null?(i.push("#verifiedAt"),o["#verifiedAt"]=p.VERIFIED_AT):(s.push("#verifiedAt = :verifiedAt"),o["#verifiedAt"]=p.VERIFIED_AT,a[":verifiedAt"]=u)}n.guards!==void 0&&(s.push("#guards = :guards"),o["#guards"]=p.GUARDS,a[":guards"]=gQ(n.guards)),n.pendingVerification!==void 0&&(o["#pendingVerification"]=p.PENDING_VERIFICATION,n.pendingVerification===null?i.push("#pendingVerification"):(s.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Ur({...n.pendingVerification,expiresAt:oe(n.pendingVerification.expiresAt),resendAvailableAt:Ds(n.pendingVerification.resendAvailableAt)}))),s.push("#updatedAt = :updatedAt"),o["#updatedAt"]=p.UPDATED_AT,a[":updatedAt"]=Ee();let c=[];return s.length>0&&c.push(`SET ${s.join(", ")}`),i.length>0&&c.push(`REMOVE ${i.join(", ")}`),await this.docClient.send(new Zr.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.IDENTITY_PK(e,t),[p.SK]:P.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:o,ExpressionAttributeValues:a})),T(void 0)}catch(s){return S(V("update identity",s))}}async remove(e,t){try{return await this.docClient.send(new Zr.DeleteCommand({TableName:this.tableName,Key:{[p.PK]:P.IDENTITY_PK(e,t),[p.SK]:P.IDENTITY_SK()}})),T(void 0)}catch(n){return S(V("remove identity",n))}}async updateGuard(e,t,n,s){let i={[p.PK]:P.IDENTITY_PK(e,t),[p.SK]:P.IDENTITY_SK()};try{return await this.docClient.send(new Zr.UpdateCommand({TableName:this.tableName,Key:i,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":p.GUARDS,"#guardKey":n,"#updatedAt":p.UPDATED_AT},ExpressionAttributeValues:{":guard":pO(s),":updatedAt":Ee()}})),T(void 0)}catch(o){if(Je(o))try{return await this.docClient.send(new Zr.UpdateCommand({TableName:this.tableName,Key:i,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":p.GUARDS,"#updatedAt":p.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:pO(s)},":updatedAt":Ee()}})),T(void 0)}catch(a){return S(V("update guard",a))}return S(V("update guard",o))}}async batchGet(e){try{if(e.length===0)return T([]);let n=(await this.docClient.send(new Zr.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:e.map(({type:o,value:a})=>({[p.PK]:P.IDENTITY_PK(o,a),[p.SK]:P.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],s=new Map;for(let o of n){let a=this.unmarshall(o);if(a!==null){let c=`${a.type}#${a.value}`;s.set(c,a)}}let i=e.map(({type:o,value:a})=>{let c=`${o}#${a}`;return s.get(c)||null});return T(i)}catch(t){return S(V("batch get identities",t))}}marshall(e){let t={[p.PK]:P.IDENTITY_PK(e.type,e.value),[p.SK]:P.IDENTITY_SK(),[p.IDENTITY_USER_PK]:P.USER_INDEX_PK(e.userId),[p.IDENTITY_USER_SK]:P.USER_INDEX_SK(e.type,e.value),[p.USER_ID]:e.userId,[p.LOGIN_ENABLED]:e.loginEnabled,[p.CREATED_AT]:oe(e.createdAt),[p.UPDATED_AT]:oe(e.updatedAt)},n=Ds(e.verifiedAt);return n!==null&&(t[p.VERIFIED_AT]=n),t[p.GUARDS]=gQ(e.guards),e.pendingVerification&&(t[p.PENDING_VERIFICATION]=Ur({...e.pendingVerification,expiresAt:oe(e.pendingVerification.expiresAt),resendAvailableAt:Ds(e.pendingVerification.resendAvailableAt)})),t}unmarshall(e){let t=ye.identityPKInfo(e[p.PK]);if(!t){let n=e[p.IDENTITY_USER_SK]?ye.userIndexSKInfo(e[p.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[p.USER_ID],loginEnabled:e[p.LOGIN_ENABLED],verifiedAt:Mr(e[p.VERIFIED_AT]),guards:EQ(e[p.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[p.PENDING_VERIFICATION]),createdAt:W(e[p.CREATED_AT]),updatedAt:W(e[p.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[p.PK],GSI1SK:e[p.IDENTITY_USER_SK]}),null)}return{type:t.type,value:t.value,userId:e[p.USER_ID],loginEnabled:e[p.LOGIN_ENABLED],verifiedAt:Mr(e[p.VERIFIED_AT]),guards:EQ(e[p.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[p.PENDING_VERIFICATION]),createdAt:W(e[p.CREATED_AT]),updatedAt:W(e[p.UPDATED_AT])}}unmarshallPendingVerification(e){if(!e||typeof e!="object")return null;let t=e;return{challengeId:t.challengeId,purpose:t.purpose,channel:t.channel,expiresAt:W(t.expiresAt),resendAvailableAt:Mr(t.resendAvailableAt)}}};var yQ=Ae(Kt(),1);var km=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}async createEmailVerificationRegistration(e){try{let t=Ee(),n=At(),s=oe(e.challenge.expiresAt),i=Math.floor((s+this.ttlGracePeriod)/1e3);return await this.docClient.send(new yQ.TransactWriteCommand({TransactItems:[this.putItem(this.marshallProfile(e,t)),this.putItem(this.marshallUserAuth(e,t)),this.putItem(this.marshallIdentity(e,t)),this.putItem(this.marshallCredential(e,n,t)),this.putItem(this.marshallChallenge(e,t,i))]})),T(void 0)}catch(t){return ql(t)==="TransactionCanceledException"||Je(t)?S(O.UniqueConstraintViolation({field:"registration"})):S(V("create email verification registration transaction",t))}}putItem(e){return{Put:{TableName:this.tableName,Item:Ur(e),ConditionExpression:`attribute_not_exists(${p.PK})`}}}marshallProfile(e,t){let n=e.profile.status,s={[p.PK]:P.USER_PK(e.profile.id),[p.SK]:P.USER_PROFILE_SK(),userStatus:n,[p.CREATED_AT]:t,[p.UPDATED_AT]:t,[p.USER_STATUS_PK]:Pe.USER_STATUS_PK(n),[p.USER_STATUS_SK]:Pe.USER_STATUS_SK(e.profile.id)};return e.profile.contactEmail&&(s.contactEmail=e.profile.contactEmail),e.profile.contactPhone&&(s.contactPhone=e.profile.contactPhone),e.profile.username&&(s.username=e.profile.username),e.profile.displayName&&(s.displayName=e.profile.displayName),e.profile.givenName&&(s.givenName=e.profile.givenName),e.profile.familyName&&(s.familyName=e.profile.familyName),e.profile.avatarUrl&&(s.avatarUrl=e.profile.avatarUrl),e.profile.locale&&(s.locale=e.profile.locale),e.profile.metadata&&(s.metadata=JSON.stringify(e.profile.metadata)),s}marshallUserAuth(e,t){return{[p.PK]:P.USER_PK(e.userAuth.userId),[p.SK]:P.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[p.CREATED_AT]:t,[p.UPDATED_AT]:t}}marshallIdentity(e,t){let n=e.identity,s={[p.PK]:P.IDENTITY_PK(n.type,n.value),[p.SK]:P.IDENTITY_SK(),[p.IDENTITY_USER_PK]:P.USER_INDEX_PK(n.userId),[p.IDENTITY_USER_SK]:P.USER_INDEX_SK(n.type,n.value),[p.USER_ID]:n.userId,[p.LOGIN_ENABLED]:n.loginEnabled,[p.CREATED_AT]:t,[p.UPDATED_AT]:t,[p.PENDING_VERIFICATION]:Ur({...n.pendingVerification,expiresAt:oe(n.pendingVerification.expiresAt),resendAvailableAt:Ds(n.pendingVerification.resendAvailableAt)})},i=Ds(n.verifiedAt);return i!==null&&(s[p.VERIFIED_AT]=i),s[p.GUARDS]=n.guards??{},s}marshallCredential(e,t,n){let s=e.credential,i={[p.PK]:P.CREDENTIAL_PK(t),[p.SK]:P.CREDENTIAL_SK(),[p.CREDENTIAL_USER_PK]:P.USER_PK(s.userId),[p.CREDENTIAL_USER_SK]:P.CREDENTIAL_USER_SK(s.type,t),[p.USER_ID]:s.userId,[p.CREDENTIAL_VALUE]:s.value,[p.METADATA]:s.data,[p.REVOKED_AT]:s.revokedAt?oe(s.revokedAt):null,[p.CREATED_AT]:n,[p.UPDATED_AT]:n};return s.lastUsedAt&&(i[p.LAST_USED_AT]=oe(s.lastUsedAt)),i}marshallChallenge(e,t,n){let s=e.challenge,i={[p.PK]:P.CHALLENGE_PK(s.id),[p.SK]:P.CHALLENGE_SK(),[p.USER_ID]:s.userId,[p.PURPOSE]:s.purpose,[p.CHALLENGE_STATUS]:s.status,[p.EXPIRES_AT]:oe(s.expiresAt),[p.CREATED_AT]:t,[p.TTL]:n};return s.tenantId&&(i[p.TENANT_ID]=s.tenantId),s.phase&&(i[p.PHASE]=s.phase),s.allowedMethods&&s.allowedMethods.length>0&&(i[p.ALLOWED_METHODS]=s.allowedMethods),s.method&&(i[p.METHOD]=s.method),s.codeHash&&(i[p.CODE_HASH]=s.codeHash),s.attempts!==void 0&&(i[p.ATTEMPTS]=s.attempts),s.maxAttempts!==void 0&&(i[p.MAX_ATTEMPTS]=s.maxAttempts),s.identityType&&(i[p.IDENTITY_TYPE]=s.identityType),s.identityValue&&(i[p.IDENTITY_VALUE]=s.identityValue),s.deviceLabel&&(i[p.DEVICE_LABEL]=s.deviceLabel),s.country&&(i[p.COUNTRY]=s.country),s.city&&(i[p.CITY]=s.city),s.metadata&&(i[p.METADATA]=s.metadata),s.flowKey&&(i[p.FLOW_KEY]=s.flowKey),i}};var TQ=Ae(aT(),1),kt=Ae(Kt(),1);var AQ=Ae(Kt(),1),SQ=100,_Q=5;function Uwe(r){return new Promise(e=>setTimeout(e,r))}async function Wl(r,e,t){if(t.length===0)return[];let n=[];for(let s=0;s<t.length;s+=SQ){let i=t.slice(s,s+SQ),o=0;for(;i.length>0;){let a=await r.send(new AQ.BatchGetCommand({RequestItems:{[e]:{Keys:i}}})),c=a.Responses?.[e];c&&n.push(...c);let u=a.UnprocessedKeys?.[e]?.Keys;if(!u||u.length===0)break;if(o+=1,o>_Q)throw new Error(`BatchGet left ${u.length} unprocessed keys after ${_Q} retries`);i=u,await Uwe(2**o*25)}}return n}var Lm=class{docClient;tableName;ttlGracePeriod;constructor(e){let t=e.client||new TQ.DynamoDBClient({});this.docClient=e.docClient||kt.DynamoDBDocumentClient.from(t),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return At()}generateTokenId(){return At()}async get(e){try{let t=await this.docClient.send(new kt.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()}}));return t.Item?T(this.unmarshall(t.Item)):T(null)}catch(t){return S(V("get session",t))}}async create(e){try{let t=Ee(),n=e.id||this.generateSessionId(),s=e.tokenId||this.generateTokenId(),i={...e,id:n,tokenId:s,revokedAt:null,createdAt:new Date(t),lastUsedAt:new Date(t)},o=vm(oe(e.expiresAt)+this.ttlGracePeriod),a=bT.sessionSK(t,n);return await this.docClient.send(new kt.PutCommand({TableName:this.tableName,Item:this.marshall(i,o,a)})),T(i)}catch(t){return S(V("create session",t))}}async update(e,t){try{let n=[],s={},i={};if(t.tokenId!==void 0&&(n.push(`#${p.TOKEN_ID} = :tokenId`),s[`#${p.TOKEN_ID}`]=p.TOKEN_ID,i[":tokenId"]=t.tokenId),t.expiresAt!==void 0){n.push(`#${p.EXPIRES_AT} = :expiresAt`),s[`#${p.EXPIRES_AT}`]=p.EXPIRES_AT,i[":expiresAt"]=oe(t.expiresAt);let o=vm(oe(t.expiresAt)+this.ttlGracePeriod);n.push(`#${p.TTL} = :ttl`),s[`#${p.TTL}`]=p.TTL,i[":ttl"]=o}return t.lastUsedAt!==void 0&&(n.push(`#${p.LAST_USED_AT} = :lastUsedAt`),s[`#${p.LAST_USED_AT}`]=p.LAST_USED_AT,i[":lastUsedAt"]=oe(t.lastUsedAt)),t.metadata!==void 0&&(n.push(`#${p.METADATA} = :metadata`),s[`#${p.METADATA}`]=p.METADATA,i[":metadata"]=t.metadata),t.previousTokenId!==void 0&&(n.push(`#${p.PREVIOUS_TOKEN_ID} = :previousTokenId`),s[`#${p.PREVIOUS_TOKEN_ID}`]=p.PREVIOUS_TOKEN_ID,i[":previousTokenId"]=t.previousTokenId),t.rotatedAt!==void 0&&(n.push(`#${p.ROTATED_AT} = :rotatedAt`),s[`#${p.ROTATED_AT}`]=p.ROTATED_AT,i[":rotatedAt"]=t.rotatedAt),n.length===0?T():(await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:i})),T())}catch(n){return S(V("update session",n))}}async rotateToken(e,t,n){try{let s=vm(oe(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET #${p.TOKEN_ID} = :tokenId, #${p.PREVIOUS_TOKEN_ID} = :previousTokenId, #${p.ROTATED_AT} = :rotatedAt, #${p.EXPIRES_AT} = :expiresAt, #${p.LAST_USED_AT} = :lastUsedAt, #${p.TTL} = :ttl`,ConditionExpression:`#${p.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${p.TOKEN_ID}`]:p.TOKEN_ID,[`#${p.PREVIOUS_TOKEN_ID}`]:p.PREVIOUS_TOKEN_ID,[`#${p.ROTATED_AT}`]:p.ROTATED_AT,[`#${p.EXPIRES_AT}`]:p.EXPIRES_AT,[`#${p.LAST_USED_AT}`]:p.LAST_USED_AT,[`#${p.TTL}`]:p.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":oe(n.expiresAt),":lastUsedAt":oe(n.lastUsedAt),":ttl":s,":expectedCurrentTokenId":t}})),T(!0)}catch(s){return Je(s)?T(!1):S(V("rotate session token",s))}}async switchTenant(e,t){try{let n=[`#${p.TENANT_ID} = :tenantId`,`#${p.TOKEN_ID} = :tokenId`,`#${p.LAST_USED_AT} = :lastUsedAt`],s=[],i={[`#${p.TENANT_ID}`]:p.TENANT_ID,[`#${p.TOKEN_ID}`]:p.TOKEN_ID,[`#${p.LAST_USED_AT}`]:p.LAST_USED_AT},o={":tenantId":t.tenantId,":tokenId":t.tokenId,":lastUsedAt":Ee()};i[`#${p.TENANT_TYPE}`]=p.TENANT_TYPE,t.tenantType!==void 0?(n.push(`#${p.TENANT_TYPE} = :tenantType`),o[":tenantType"]=t.tenantType):s.push(`#${p.TENANT_TYPE}`),i[`#${p.PERM}`]=p.PERM,t.perms!==void 0?(n.push(`#${p.PERM} = :perms`),o[":perms"]=JSON.stringify(t.perms)):s.push(`#${p.PERM}`),i[`#${p.ROLES}`]=p.ROLES,t.roles!==void 0?(n.push(`#${p.ROLES} = :roles`),o[":roles"]=t.roles):s.push(`#${p.ROLES}`),i["#revokedAt"]=p.REVOKED_AT;let a=`SET ${n.join(", ")}${s.length>0?` REMOVE ${s.join(", ")}`:""}`;return await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:i,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${p.PK}) AND attribute_not_exists(#revokedAt)`})),T()}catch(n){return Je(n)?S(O.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):S(V("switch tenant",n))}}async revoke(e){try{return await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET #${p.REVOKED_AT} = :revokedAt REMOVE #${p.ACTIVE_SESSION_PK}, #${p.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${p.REVOKED_AT}`]:p.REVOKED_AT,[`#${p.ACTIVE_SESSION_PK}`]:p.ACTIVE_SESSION_PK,[`#${p.ACTIVE_SESSION_SK}`]:p.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":oe(new Date)},ConditionExpression:`attribute_exists(${p.PK})`})),T()}catch(t){return Je(t)?T():S(V("revoke session",t))}}async revokeByIdAndUserId(e,t){try{return await this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(e),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET #${p.REVOKED_AT} = :revokedAt REMOVE #${p.ACTIVE_SESSION_PK}, #${p.ACTIVE_SESSION_SK}`,ConditionExpression:`#${p.USER_ID} = :userId AND attribute_not_exists(#${p.REVOKED_AT})`,ExpressionAttributeNames:{[`#${p.REVOKED_AT}`]:p.REVOKED_AT,[`#${p.USER_ID}`]:p.USER_ID,[`#${p.ACTIVE_SESSION_PK}`]:p.ACTIVE_SESSION_PK,[`#${p.ACTIVE_SESSION_SK}`]:p.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":oe(new Date),":userId":t}})),T()}catch(n){return Je(n)?T():S(V("revoke session by user",n))}}async findByUserId(e,t){try{let n=Math.min(t?.limit||50,100),s;if(t?.cursor)try{s=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))}catch{return S(O.DatabaseQueryError({query:"invalid pagination cursor"}))}let i=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.USER_SESSIONS,KeyConditionExpression:`${p.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":P.USER_PK(e)},Limit:n,ExclusiveStartKey:s,ScanIndexForward:!1}));if(!i.Items||i.Items.length===0){let h={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!t?.cursor,cursor:null};return T([],{pagination:h})}let a=i.Items.map(h=>ye.sessionId(h[p.PK])).map(h=>({[p.PK]:P.SESSION_PK(h),[p.SK]:P.SESSION_SK()})),u=(await Wl(this.docClient,this.tableName,a)).map(h=>this.unmarshall(h)),l=!!i.LastEvaluatedKey,d=l?Buffer.from(JSON.stringify(i.LastEvaluatedKey)).toString("base64url"):null,f={type:"cursor",limit:n,count:u.length,hasNext:l,hasPrev:!!t?.cursor,cursor:d};return T(u,{pagination:f})}catch(n){return S(V("find sessions by user",n))}}async findActiveByUserId(e,t){try{let n=Math.min(t?.limit||50,100),s;if(t?.cursor)try{s=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))}catch{return S(O.DatabaseQueryError({query:"invalid pagination cursor"}))}let i=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${p.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Pe.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:s,ScanIndexForward:!1}));if(!i.Items||i.Items.length===0){let h={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!t?.cursor,cursor:null};return T([],{pagination:h})}let a=i.Items.map(h=>ye.sessionId(h[p.PK])).map(h=>({[p.PK]:P.SESSION_PK(h),[p.SK]:P.SESSION_SK()})),u=(await Wl(this.docClient,this.tableName,a)).map(h=>this.unmarshall(h)),l=!!i.LastEvaluatedKey,d=l?Buffer.from(JSON.stringify(i.LastEvaluatedKey)).toString("base64url"):null,f={type:"cursor",limit:n,count:u.length,hasNext:l,hasPrev:!!t?.cursor,cursor:d};return T(u,{pagination:f})}catch(n){return S(V("find active sessions by user",n))}}async getActiveSessionsForLimit(e){try{let t=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${p.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Pe.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!t.Items||t.Items.length===0)return T([]);let n=t.Items.map(s=>{let i=ye.sessionId(s[p.PK]),o=bT.extractCreatedAt(s[p.ACTIVE_SESSION_SK]);return{id:i,createdAt:new Date(o)}});return T(n)}catch(t){return S(V("get active sessions for limit",t))}}async revokeSessionsByIds(e,t){if(e.length===0)return 0;let n=oe(new Date),s=await Promise.allSettled(e.map(o=>this.docClient.send(new kt.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(o),[p.SK]:P.SESSION_SK()},UpdateExpression:`SET #${p.REVOKED_AT} = :revokedAt REMOVE #${p.ACTIVE_SESSION_PK}, #${p.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${p.REVOKED_AT}`]:p.REVOKED_AT,[`#${p.ACTIVE_SESSION_PK}`]:p.ACTIVE_SESSION_PK,[`#${p.ACTIVE_SESSION_SK}`]:p.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),i=0;for(let o of s)o.status==="fulfilled"?i+=1:console.error(`[session-repo] ${t}: session revoke failed (may remain active):`,{name:ql(o.reason)});return i}async revokeAllByUserId(e,t){try{let n=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${p.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Pe.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return T(0);let s=n.Items.map(o=>ye.sessionId(o[p.PK])).filter(o=>!t||o!==t),i=await this.revokeSessionsByIds(s,"revokeAllByUserId");return T(i)}catch(n){return S(V("revoke all sessions by user",n))}}async revokeBatch(e){try{let t=await this.revokeSessionsByIds(e,"revokeBatch");return T(t)}catch(t){return S(V("revoke batch sessions",t))}}async countByUserId(e){try{let t=await this.docClient.send(new kt.QueryCommand({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${p.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Pe.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return T(t.Count||0)}catch(t){return S(V("count active sessions by user",t))}}async isTokenActive(e,t){try{let n=await this.docClient.send(new kt.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.SESSION_PK(t),[p.SK]:P.SESSION_SK()},ProjectionExpression:`${p.TOKEN_ID}, ${p.REVOKED_AT}, ${p.EXPIRES_AT}`}));if(!n.Item)return T(!1);let s=n.Item,i=s[p.TOKEN_ID]===e&&!s[p.REVOKED_AT]&&W(s[p.EXPIRES_AT])>new Date;return T(i)}catch(n){return S(V("check token active",n))}}marshall(e,t,n){let s={[p.PK]:P.SESSION_PK(e.id),[p.SK]:P.SESSION_SK(),[p.USER_SESSION_PK]:P.USER_PK(e.userId),[p.USER_SESSION_SK]:n,...!e.revokedAt&&{[p.ACTIVE_SESSION_PK]:Pe.ACTIVE_SESSION_PK(e.userId),[p.ACTIVE_SESSION_SK]:n},[p.USER_ID]:e.userId,[p.TOKEN_ID]:e.tokenId,[p.EXPIRES_AT]:oe(e.expiresAt),[p.CREATED_AT]:oe(e.createdAt),[p.LAST_USED_AT]:oe(e.lastUsedAt),[p.TTL]:t};return e.tenantId&&(s[p.TENANT_ID]=e.tenantId),e.tenantType&&(s[p.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(s[p.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(s[p.ROLES]=e.roles),e.deviceLabel&&(s[p.DEVICE_LABEL]=e.deviceLabel),e.country&&(s[p.COUNTRY]=e.country),e.city&&(s[p.CITY]=e.city),e.metadata&&(s[p.METADATA]=e.metadata),e.revokedAt&&(s[p.REVOKED_AT]=oe(e.revokedAt)),e.previousTokenId&&(s[p.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(s[p.ROTATED_AT]=e.rotatedAt),s}unmarshall(e){let n={id:ye.sessionId(e[p.PK]),userId:e[p.USER_ID],tokenId:e[p.TOKEN_ID],expiresAt:W(e[p.EXPIRES_AT]),createdAt:W(e[p.CREATED_AT]),lastUsedAt:W(e[p.LAST_USED_AT]),revokedAt:e[p.REVOKED_AT]?W(e[p.REVOKED_AT]):null};return e[p.TENANT_ID]&&(n.tenantId=e[p.TENANT_ID]),e[p.TENANT_TYPE]&&(n.tenantType=e[p.TENANT_TYPE]),e[p.PERM]!==void 0&&(n.perms=JSON.parse(e[p.PERM])),e[p.ROLES]!==void 0&&(n.roles=e[p.ROLES]),e[p.DEVICE_LABEL]&&(n.deviceLabel=e[p.DEVICE_LABEL]),e[p.COUNTRY]&&(n.country=e[p.COUNTRY]),e[p.CITY]&&(n.city=e[p.CITY]),e[p.METADATA]&&(n.metadata=e[p.METADATA]),e[p.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[p.PREVIOUS_TOKEN_ID]),e[p.ROTATED_AT]!==void 0&&(n.rotatedAt=e[p.ROTATED_AT]),n}};var IQ=Ae(Kt(),1);var Mm=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,t){try{let n=Math.min(t?.limit||50,100),s={"#pk":p.INVITE_TENANT_PK},i={":pk":Pe.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:s,ExpressionAttributeValues:i,ScanIndexForward:!1,Limit:n};t?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))),t?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",s["#sk"]=p.INVITE_TENANT_SK,i[":statusPrefix"]=Pe.INVITE_TENANT_STATUS_PREFIX(t.status));let a=await this.docClient.send(new IQ.QueryCommand(o)),c=(a.Items||[]).map(d=>this.toListItem(d)),u=!!a.LastEvaluatedKey,l=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return tt(c,{limit:n,hasNext:u,cursor:l,prevCursor:t?.cursor??null})}catch(n){return S(V("listByTenant query",n))}}toListItem(e){let t=ye.inviteId(e.PK),n={id:e.invitedById};e.invitedByInfo&&(e.invitedByInfo.name&&(n.name=e.invitedByInfo.name),e.invitedByInfo.email&&(n.email=e.invitedByInfo.email),e.invitedByInfo.jobTitle&&(n.jobTitle=e.invitedByInfo.jobTitle));let s={id:t,tenantId:e.tenantId,invitedBy:n,status:e.inviteStatus,expiresAt:W(e.expiresAt),createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};return e.inviteeUserId&&(s.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(s.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(s.inviteePhone=e.inviteePhone),e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm),e.displayName&&(s.displayName=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.jobTitle&&(s.jobTitle=e.jobTitle),e.acceptedAt&&(s.acceptedAt=W(e.acceptedAt)),e.declinedAt&&(s.declinedAt=W(e.declinedAt)),e.revokedAt&&(s.revokedAt=W(e.revokedAt)),s}};var br=Ae(Kt(),1);var $we=10080*60*1e3,Um=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:ye.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:W(e.expiresAt),createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};e.inviteeUserId&&(n.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(n.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(n.inviteePhone=e.inviteePhone),e.roles!==void 0&&(n.roles=e.roles);let s=e[p.PERM];return s!==void 0&&(n.perms=JSON.parse(s)),e.authPerm!==void 0&&(n.authPerm=e.authPerm),e.displayName&&(n.displayName=e.displayName),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.jobTitle&&(n.jobTitle=e.jobTitle),e.acceptedAt&&(n.acceptedAt=W(e.acceptedAt)),e.declinedAt&&(n.declinedAt=W(e.declinedAt)),e.revokedAt&&(n.revokedAt=W(e.revokedAt)),n}generateInviteId(){return At()}async getById(e){try{let t=await this.docClient.send(new br.GetCommand({TableName:this.tableName,Key:{PK:P.INVITE_PK(e),SK:P.INVITE_SK()}}));return t.Item?T(this.mapItemToEntity(t.Item)):T(null)}catch(t){return S(V("getById invite",t))}}async getByToken(e){try{let n=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":p.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return T(null);let s=n[0],i=await this.docClient.send(new br.GetCommand({TableName:this.tableName,Key:{PK:s.PK,SK:s.SK}}));return i.Item?T(this.mapItemToEntity(i.Item)):T(null)}catch(t){return S(V("getByToken invite",t))}}async create(e){try{let t=Ee(),n=oe(e.expiresAt),s=Math.floor((n+$we)/1e3),i={PK:P.INVITE_PK(e.id),SK:P.INVITE_SK(),[p.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[p.INVITED_BY_ID]:e.invitedById,[p.INVITE_STATUS]:e.status,[p.INVITE_TOKEN]:e.inviteToken,[p.EXPIRES_AT]:n,[p.CREATED_AT]:t,[p.UPDATED_AT]:t,[p.TTL]:s,[p.INVITE_TENANT_PK]:Pe.INVITE_TENANT_PK(e.tenantId),[p.INVITE_TENANT_SK]:Pe.INVITE_TENANT_SK(e.status,t,e.id),[p.INVITE_TOKEN_GSI]:e.inviteToken},o={};e.invitedByName&&(o.name=e.invitedByName),e.invitedByEmail&&(o.email=e.invitedByEmail),e.invitedByJobTitle&&(o.jobTitle=e.invitedByJobTitle),Object.keys(o).length>0&&(i[p.INVITED_BY_INFO]=o),e.inviteeUserId&&(i[p.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(i[p.INVITEE_EMAIL]=e.inviteeEmail,i[p.INVITEE_EMAIL_GSI]=e.inviteeEmail,i[p.INVITEE_EMAIL_TENANT_SK]=`${ge.TENANT}${e.tenantId}`),e.inviteePhone&&(i[p.INVITEE_PHONE]=e.inviteePhone,i[p.INVITEE_PHONE_GSI]=e.inviteePhone,i[p.INVITEE_PHONE_TENANT_SK]=`${ge.TENANT}${e.tenantId}`),e.roles!==void 0&&(i[p.ROLES]=e.roles),e.perms!==void 0&&(i[p.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(i[p.AUTH_PERM]=e.authPerm),e.displayName&&(i[p.DISPLAY_NAME]=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.jobTitle&&(i.jobTitle=e.jobTitle),await this.docClient.send(new br.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK)"}));let a={id:e.id,tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.status,inviteToken:e.inviteToken,expiresAt:e.expiresAt,createdAt:W(t),updatedAt:W(t)};return e.inviteeUserId&&(a.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(a.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(a.inviteePhone=e.inviteePhone),e.roles!==void 0&&(a.roles=e.roles),e.perms!==void 0&&(a.perms=e.perms),e.authPerm!==void 0&&(a.authPerm=e.authPerm),e.displayName&&(a.displayName=e.displayName),e.givenName&&(a.givenName=e.givenName),e.familyName&&(a.familyName=e.familyName),e.jobTitle&&(a.jobTitle=e.jobTitle),T(a)}catch(t){return t.name==="ConditionalCheckFailedException"?S(O.UniqueConstraintViolation({field:"invite id"})):S(Ir("create invite",t))}}async updateStatus(e,t){try{let n=Ee(),s=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],i={"#inviteStatus":p.INVITE_STATUS,"#inviteTenantSk":p.INVITE_TENANT_SK,"#updatedAt":p.UPDATED_AT},o={":inviteStatus":t.status,":inviteTenantSk":Pe.INVITE_TENANT_SK(t.status,n,e),":updatedAt":n};t.acceptedAt&&(s.push("#acceptedAt = :acceptedAt"),i["#acceptedAt"]=p.ACCEPTED_AT,o[":acceptedAt"]=oe(t.acceptedAt)),t.declinedAt&&(s.push("#declinedAt = :declinedAt"),i["#declinedAt"]=p.DECLINED_AT,o[":declinedAt"]=oe(t.declinedAt)),t.revokedAt&&(s.push("#revokedAt = :revokedAt"),i["#revokedAt"]=p.REVOKED_AT,o[":revokedAt"]=oe(t.revokedAt));let a=[];t.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),i["#inviteTokenGsi"]=p.INVITE_TOKEN_GSI,i["#inviteeEmailGsi"]=p.INVITEE_EMAIL_GSI,i["#inviteeEmailTenantSk"]=p.INVITEE_EMAIL_TENANT_SK,i["#inviteePhoneGsi"]=p.INVITEE_PHONE_GSI,i["#inviteePhoneTenantSk"]=p.INVITEE_PHONE_TENANT_SK);let c=`SET ${s.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new br.UpdateCommand({TableName:this.tableName,Key:{PK:P.INVITE_PK(e),SK:P.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:i,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"TenantInvite",id:e})):S(Ir("updateStatus invite",n))}}async findByTenantAndEmail(e,t){try{let s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":p.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":p.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":t,":tenantSk":`${ge.TENANT}${e}`},Limit:1}))).Items;return!s||s.length===0?T(null):T(this.mapItemToEntity(s[0]))}catch(n){return S(V("findByTenantAndEmail",n))}}async findByTenantAndPhone(e,t){try{let s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":p.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":p.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":t,":tenantSk":`${ge.TENANT}${e}`},Limit:1}))).Items;return!s||s.length===0?T(null):T(this.mapItemToEntity(s[0]))}catch(n){return S(V("findByTenantAndPhone",n))}}async findByTenantAndUserId(e,t){try{let s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":p.INVITE_TENANT_PK,"#sk":p.INVITE_TENANT_SK,"#inviteeUserId":p.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":Pe.INVITE_TENANT_PK(e),":pendingPrefix":Pe.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":t},Limit:1}))).Items;return!s||s.length===0?T(null):T(this.mapItemToEntity(s[0]))}catch(n){return S(V("findByTenantAndUserId",n))}}async listByTenant(e,t){try{let n=Math.min(t?.limit||50,100),s={"#pk":p.INVITE_TENANT_PK},i={":pk":Pe.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:s,ExpressionAttributeValues:i,ScanIndexForward:!1,Limit:n};t?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))),t?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",s["#sk"]=p.INVITE_TENANT_SK,i[":statusPrefix"]=Pe.INVITE_TENANT_STATUS_PREFIX(t.status));let a=await this.docClient.send(new br.QueryCommand(o)),c=(a.Items||[]).map(d=>this.mapItemToEntity(d)),u=!!a.LastEvaluatedKey,l=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return tt(c,{limit:n,hasNext:u,cursor:l,prevCursor:t?.cursor??null})}catch(n){return S(V("listByTenant",n))}}async findPendingByEmail(e){try{let t=Ee(),s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":p.INVITEE_EMAIL_GSI,"#expiresAt":p.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":t}}))).Items||[];if(s.length===0)return T([]);let i=s.map(c=>({PK:c.PK,SK:c.SK})),a=(await Wl(this.docClient,this.tableName,i)).map(c=>this.mapItemToEntity(c));return T(a)}catch(t){return S(V("findPendingByEmail",t))}}async findPendingByPhone(e){try{let t=Ee(),s=(await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":p.INVITEE_PHONE_GSI,"#expiresAt":p.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":t}}))).Items||[];if(s.length===0)return T([]);let i=s.map(c=>({PK:c.PK,SK:c.SK})),a=(await Wl(this.docClient,this.tableName,i)).map(c=>this.mapItemToEntity(c));return T(a)}catch(t){return S(V("findPendingByPhone",t))}}async countPendingByTenant(e){try{let t=await this.docClient.send(new br.QueryCommand({TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":p.INVITE_TENANT_PK,"#sk":p.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":Pe.INVITE_TENANT_PK(e),":pendingPrefix":Pe.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return T(t.Count??0)}catch(t){return S(V("countPendingByTenant",t))}}async expireOld(e){return T(0)}};var bQ=Ae(Kt(),1);var $m=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,t){try{let n=Math.min(t?.limit||50,100),s={TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":P.TENANT_MEMBER_PK(e)}};t?.cursor&&(s.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8")));let o=(await this.docClient.send(new bQ.QueryCommand(s))).Items||[],a=[],c=new Map;for(let h of o){let g=h.SK;if(g.startsWith(ut.TENANT_PROFILE)){let A=ye.tenantProfileUserId(g);c.set(A,h)}else g.startsWith(ge.USER)&&a.push(h)}a.sort((h,g)=>g.createdAt-h.createdAt);let u=a.slice(0,n),l=a.length>n,d=u.map(h=>{let g=ye.tenantMemberUserId(h.SK),A=c.get(g);return this.toListItem(h,e,g,A)}),f=l&&u.length>0?Buffer.from(JSON.stringify({PK:u[u.length-1].PK,SK:u[u.length-1].SK})).toString("base64url"):null;return tt(d,{limit:n,hasNext:l,cursor:f,prevCursor:t?.cursor??null})}catch(n){return S(V("listByTenant query",n))}}toListItem(e,t,n,s){let i={tenantId:t,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};if(e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),s){let o={tenantId:t,userId:n,createdAt:W(s.createdAt),updatedAt:W(s.updatedAt)};s.contactEmail&&(o.contactEmail=s.contactEmail),s.contactPhone&&(o.contactPhone=s.contactPhone),s.displayName&&(o.displayName=s.displayName),s.displayNameSource&&(o.displayNameSource=s.displayNameSource),s.givenName&&(o.givenName=s.givenName),s.familyName&&(o.familyName=s.familyName),s.avatarUrl&&(o.avatarUrl=s.avatarUrl),s.locale&&(o.locale=s.locale),s.jobTitle&&(o.jobTitle=s.jobTitle),s.bio&&(o.bio=s.bio),s.metadata&&(o.metadata=JSON.parse(s.metadata)),i.tenantProfile=o}return i}};var wr=Ae(Kt(),1);var Fm=class{tableName;docClient;constructor(e,t){this.tableName=t,this.docClient=wr.DynamoDBDocumentClient.from(e)}mapItemToEntity(e){let t=ye.tenantId(e.PK),n=ye.tenantMemberUserId(e.SK),s={tenantId:t,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};return e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm),s}async get(e,t){try{let n=await this.docClient.send(new wr.GetCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_MEMBER_SK(t)}}));if(!n.Item)return T(null);let s=this.mapItemToEntity(n.Item);return T(s)}catch(n){return S(V("get",n))}}async create(e){try{let t=Ee(),n=e.isOwner?void 0:e.authPerm,s=Ur({PK:P.TENANT_MEMBER_PK(e.tenantId),SK:P.TENANT_MEMBER_SK(e.userId),userStatus:e.status,roles:e.roles,perms:e.perms!==void 0?JSON.stringify(e.perms):void 0,authPerm:n,isOwner:e.isOwner,createdAt:t,updatedAt:t,userTenantPk:Pe.USER_TENANT_PK(e.userId),userTenantSk:Pe.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,t,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new wr.TransactWriteCommand({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:P.TENANT_MEMBER_PK(e.tenantId),SK:P.TENANT_OWNER_MARKER_SK(),createdAt:t},ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}},{Put:{TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}}]})):await this.docClient.send(new wr.PutCommand({TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(void 0)}catch(t){return t.name==="TransactionCanceledException"?t.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?S(O.UniqueConstraintViolation({field:"tenant owner"})):S(O.UniqueConstraintViolation({field:"tenant member"})):t.name==="ConditionalCheckFailedException"?S(O.UniqueConstraintViolation({field:"tenant member"})):S(Ir("create tenant member",t))}}async updatePermissions(e,t,n){try{let s={...n,updatedAt:Ee()},{UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=Os(s);return await this.docClient.send(new wr.UpdateCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_MEMBER_SK(t)},UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(s){return s.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"TenantMember",id:`${e}:${t}`})):S(Ir("updatePermissions tenant member",s))}}async updateStatus(e,t,n){try{return await this.docClient.send(new wr.UpdateCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_MEMBER_SK(t)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":Ee()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(s){return s.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"TenantMember",id:`${e}:${t}`})):S(Ir("updateStatus tenant member",s))}}async listByTenant(e,t){try{let n=Math.min(t?.limit||50,100),s={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":P.TENANT_MEMBER_PK(e),":skPrefix":ge.USER},Limit:n};t?.cursor&&(s.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8")));let i=await this.docClient.send(new wr.QueryCommand(s)),o=(i.Items||[]).map(u=>this.mapItemToEntity(u)),a=!!i.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(i.LastEvaluatedKey)).toString("base64url"):null;return tt(o,{limit:n,hasNext:a,cursor:c,prevCursor:t?.cursor??null})}catch(n){return S(V("listByTenant",n))}}async hasOwner(e){try{let t=await this.docClient.send(new wr.GetCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_OWNER_MARKER_SK()}}));return T(!!t.Item)}catch(t){return S(V("hasOwner",t))}}async remove(e,t){try{return await this.docClient.send(new wr.DeleteCommand({TableName:this.tableName,Key:{PK:P.TENANT_MEMBER_PK(e),SK:P.TENANT_MEMBER_SK(t)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"TenantMember",id:`${e}:${t}`})):S(Ir("remove tenant member",n))}}};var wT=Ae(Kt(),1);var Bm=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByUser(e,t){try{let n=Math.min(t?.limit??50,100),s=t?.tenantType??dO.DEFAULT,i=t?.parentTenantId,o=i?`${s}#${i}#`:`${s}#`,a={TableName:this.tableName,IndexName:Se.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":Pe.USER_TENANT_PK(e),":skPrefix":o},ScanIndexForward:!1,Limit:n};t?.cursor&&(a.ExclusiveStartKey=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8")));let c=await this.docClient.send(new wT.QueryCommand(a)),u=c.Items??[],l=await this.fetchProfileMap(e,u),d=u.map(g=>this.toListItem(g,e,l)),f=!!c.LastEvaluatedKey,h=f?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return tt(d,{limit:n,hasNext:f,cursor:h,prevCursor:t?.cursor??null})}catch(n){return S(V("listByUser query",n))}}async fetchProfileMap(e,t){let n=new Map;if(t.length===0)return n;let s=t.map(o=>({PK:P.TENANT_PROFILE_PK(ye.tenantId(o.PK)),SK:P.TENANT_PROFILE_SK(e)})),i=await this.docClient.send(new wT.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:s}}}));for(let o of i.Responses?.[this.tableName]??[]){let a=o,c=ye.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,t,n){let s=ye.tenantId(e.PK),i={tenantId:s,userId:t,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm);let o=n.get(s);return o&&(o.contactEmail&&(i.contactEmail=o.contactEmail),o.contactPhone&&(i.contactPhone=o.contactPhone),o.displayName&&(i.displayName=o.displayName),o.displayNameSource&&(i.displayNameSource=o.displayNameSource),o.givenName&&(i.givenName=o.givenName),o.familyName&&(i.familyName=o.familyName),o.avatarUrl&&(i.avatarUrl=o.avatarUrl),o.locale&&(i.locale=o.locale),o.jobTitle&&(i.jobTitle=o.jobTitle),o.bio&&(i.bio=o.bio),o.metadata&&(i.metadata=JSON.parse(o.metadata))),i}};var Sa=Ae(Kt(),1);var Km=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return At()}toEntity(e){let n={id:ye.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let t=await this.docClient.send(new Sa.GetCommand({TableName:this.tableName,Key:{PK:P.TENANT_PK(e),SK:P.TENANT_SK()}}));return t.Item?T(this.toEntity(t.Item)):T(null)}catch(t){return S(V("get tenant",t))}}async create(e){try{let t=e.id??this.generateTenantId(),n=Ee(),s=Ur({PK:P.TENANT_PK(t),SK:P.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new Sa.PutCommand({TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(void 0)}catch(t){return t.name==="ConditionalCheckFailedException"?S(O.UniqueConstraintViolation({field:"tenant"})):S(Ir("create tenant",t))}}async update(e,t){try{let n={updatedAt:Ee()};t.type!==void 0&&(n.tenantType=t.type),t.ownerId!==void 0&&(n.ownerId=t.ownerId),t.parentTenantId!==void 0&&(n.parentTenantId=t.parentTenantId===null?void 0:t.parentTenantId);let{UpdateExpression:s,ExpressionAttributeNames:i,ExpressionAttributeValues:o}=Os(n);return await this.docClient.send(new Sa.UpdateCommand({TableName:this.tableName,Key:{PK:P.TENANT_PK(e),SK:P.TENANT_SK()},UpdateExpression:s,ExpressionAttributeNames:i,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"Tenant",id:e})):S(Ir("update tenant",n))}}async delete(e){try{return await this.docClient.send(new Sa.DeleteCommand({TableName:this.tableName,Key:{PK:P.TENANT_PK(e),SK:P.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(t){return t.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"Tenant",id:e})):S(Ir("delete tenant",t))}}async list(){return S(O.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return S(O.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return S(O.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};var Ps=Ae(Kt(),1);var Vm=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let t=await this.docClient.send(new Ps.GetCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()}}));return t.Item?T(this.unmarshall(t.Item,e)):T(null)}catch(t){return S(V("get user auth",t))}}async create(e){try{let t=Ee(),n={...e,createdAt:new Date(t),updatedAt:new Date(t)};return await this.docClient.send(new Ps.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${p.PK})`})),T(n)}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"userAuth"})):S(V("create user auth",t))}}async updateStatus(e,t){try{let n=Ee();return await this.docClient.send(new Ps.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${p.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${p.UPDATED_AT}`]:p.UPDATED_AT},ExpressionAttributeValues:{":userStatus":t,":updatedAt":n},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userAuth",id:e})):S(V("update user auth status",n))}}async updateMfaRequired(e,t){try{let n=Ee();return await this.docClient.send(new Ps.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${p.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${p.UPDATED_AT}`]:p.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":t,":updatedAt":n},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userAuth",id:e})):S(V("update mfa required",n))}}async updateMfaMethods(e,t){try{let n=Ee();return await this.docClient.send(new Ps.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${p.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${p.UPDATED_AT}`]:p.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":t,":updatedAt":n},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userAuth",id:e})):S(V("update mfa methods",n))}}async updateMfaSettings(e,t){try{let n=Ee();return await this.docClient.send(new Ps.UpdateCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${p.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${p.UPDATED_AT}`]:p.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":t.mfaRequired,":mfaMethods":t.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${p.PK})`})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userAuth",id:e})):S(V("update mfa settings",n))}}async remove(e){try{return await this.docClient.send(new Ps.DeleteCommand({TableName:this.tableName,Key:{[p.PK]:P.USER_PK(e),[p.SK]:P.USER_AUTH_SK()}})),T(void 0)}catch(t){return S(V("remove user auth",t))}}marshall(e){return{[p.PK]:P.USER_PK(e.userId),[p.SK]:P.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[p.CREATED_AT]:oe(e.createdAt),[p.UPDATED_AT]:oe(e.updatedAt)}}unmarshall(e,t){return{userId:t,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:W(e[p.CREATED_AT]),updatedAt:W(e[p.UPDATED_AT])}}};var Fr=Ae(Kt(),1);function jl(r,e){return e?P.USER_MFA_WITH_ID_SK(r,e):P.USER_MFA_SK(r)}var Hm=class{client;tableName;docClient;constructor(e,t){this.client=e,this.tableName=t,this.docClient=Fr.DynamoDBDocumentClient.from(e)}toDynamoDBItem(e){let t={PK:P.USER_PK(e.userId),SK:jl(e.method,e.id),method:e.method,data:JSON.stringify(e.data),createdAt:Date.now(),failedAttempts:0};return e.label&&(t.label=e.label),e.verifiedAt&&(t.verifiedAt=e.verifiedAt.getTime()),e.metadata&&(t.metadata=JSON.stringify(e.metadata)),t}fromDynamoDBItem(e,t){let n=ye.mfaSKInfo(e.SK),s={userId:t,method:e.method,data:JSON.parse(e.data),createdAt:W(e.createdAt),verifiedAt:Mr(e.verifiedAt)??null};return n?.id&&(s.id=n.id),e.label&&(s.label=e.label),e.failedAttempts!==void 0&&(s.failedAttempts=e.failedAttempts),e.lastFailedAt!==void 0&&(s.lastFailedAt=Mr(e.lastFailedAt)),e.lockedUntil!==void 0&&(s.lockedUntil=Mr(e.lockedUntil)),e.lastUsedAt!==void 0&&(s.lastUsedAt=Mr(e.lastUsedAt)),e.metadata&&(s.metadata=JSON.parse(e.metadata)),s}async get(e,t,n){try{let s=jl(t,n),i=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:s}}));return i.Item?T(this.fromDynamoDBItem(i.Item,e)):T(null)}catch(s){return S(V("get MFA authenticator",s))}}async findByUserId(e){try{let t={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":P.USER_PK(e),":skPrefix":ut.MFA}},i=((await this.docClient.send(new Fr.QueryCommand(t))).Items??[]).map(o=>this.fromDynamoDBItem(o,e));return T(i)}catch(t){return S(V("find MFA authenticators by user",t))}}async findByUserIdAndMethod(e,t){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":P.USER_PK(e),":skPrefix":`${ut.MFA}${t}`}},o=((await this.docClient.send(new Fr.QueryCommand(n))).Items??[]).filter(a=>a.method===t).map(a=>this.fromDynamoDBItem(a,e));return T(o)}catch(n){return S(V("find MFA authenticators by method",n))}}async create(e){try{let t={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(t.id=At());let n=this.toDynamoDBItem(t);return await this.docClient.send(new Fr.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(this.fromDynamoDBItem(n,e.userId))}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"MFA authenticator"})):S(V("create MFA authenticator",t))}}async update(e,t,n,s){try{let i=jl(t,n),o=[],a={},c={};if(s.label!==void 0&&(o.push("#label = :label"),a["#label"]="label",c[":label"]=s.label),s.data!==void 0&&(o.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(s.data)),s.verifiedAt!==void 0&&(o.push("#verifiedAt = :verifiedAt"),a["#verifiedAt"]="verifiedAt",c[":verifiedAt"]=s.verifiedAt instanceof Date?s.verifiedAt.getTime():s.verifiedAt===null?void 0:s.verifiedAt),s.lastUsedAt!==void 0&&(o.push("#lastUsedAt = :lastUsedAt"),a["#lastUsedAt"]="lastUsedAt",c[":lastUsedAt"]=s.lastUsedAt instanceof Date?s.lastUsedAt.getTime():s.lastUsedAt===null?void 0:s.lastUsedAt),s.failedAttempts!==void 0&&(o.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=s.failedAttempts),s.lastFailedAt!==void 0&&(o.push("#lastFailedAt = :lastFailedAt"),a["#lastFailedAt"]="lastFailedAt",c[":lastFailedAt"]=s.lastFailedAt instanceof Date?s.lastFailedAt.getTime():s.lastFailedAt===null?void 0:s.lastFailedAt),s.lockedUntil!==void 0&&(o.push("#lockedUntil = :lockedUntil"),a["#lockedUntil"]="lockedUntil",c[":lockedUntil"]=s.lockedUntil instanceof Date?s.lockedUntil.getTime():s.lockedUntil===null?void 0:s.lockedUntil),s.metadata!==void 0&&(o.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(s.metadata)),o.length===0)return T(void 0);let u={TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:i},UpdateExpression:`SET ${o.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new Fr.UpdateCommand(u)),T(void 0)}catch(i){return S(V("update MFA authenticator",i))}}async remove(e,t,n){try{let s=jl(t,n);return await this.docClient.send(new Fr.DeleteCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:s}})),T(void 0)}catch(s){return S(V("remove MFA authenticator",s))}}async incrementFailedAttempts(e,t,n,s,i){try{let o=jl(t,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],u={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},l={":zero":0,":inc":1,":lastFailedAt":a};i!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),u["#lockedUntil"]="lockedUntil",l[":lockedUntil"]=a+i*60*1e3,l[":maxAttempts"]=s);let d={TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:o},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:u,ExpressionAttributeValues:l};return await this.docClient.send(new Fr.UpdateCommand(d)),T(void 0)}catch(o){return S(V("increment failed attempts",o))}}async resetFailedAttempts(e,t,n){try{let s=jl(t,n),i={TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:s},UpdateExpression:"SET #failedAttempts = :zero REMOVE #lastFailedAt, #lockedUntil",ExpressionAttributeNames:{"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt","#lockedUntil":"lockedUntil"},ExpressionAttributeValues:{":zero":0}};return await this.docClient.send(new Fr.UpdateCommand(i)),T(void 0)}catch(s){return S(V("reset failed attempts",s))}}async unlock(e,t,n){return this.resetFailedAttempts(e,t,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};var en=Ae(Kt(),1);var Gm=class{tableName;docClient;constructor(e,t){this.tableName=t,this.docClient=en.DynamoDBDocumentClient.from(e)}generateUserId(){return At()}async getById(e){try{let t=await this.docClient.send(new en.GetCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:P.USER_PROFILE_SK()}}));if(!t.Item)return T(null);let n=t.Item;if(n.deletedAt)return T(null);let i={id:ye.userId(n.PK),status:n.userStatus,createdAt:W(n.createdAt),updatedAt:W(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:W(n.deletedAt)},...n.contactEmail!==void 0&&{contactEmail:n.contactEmail},...n.contactPhone!==void 0&&{contactPhone:n.contactPhone},...n.username!==void 0&&{username:n.username},...n.displayName!==void 0&&{displayName:n.displayName},...n.givenName!==void 0&&{givenName:n.givenName},...n.familyName!==void 0&&{familyName:n.familyName},...n.avatarUrl!==void 0&&{avatarUrl:n.avatarUrl},...n.locale!==void 0&&{locale:n.locale},...n.metadata!==void 0&&{metadata:JSON.parse(n.metadata)}};return T(i)}catch(t){return S(V("getById user",t))}}async create(e){try{let t=Ee(),n=e.id||this.generateUserId(),s=e.status||"pending",i={PK:P.USER_PK(n),SK:P.USER_PROFILE_SK(),userStatus:s,createdAt:t,updatedAt:t};e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.username&&(i.username=e.username),e.displayName&&(i.displayName=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.metadata&&(i.metadata=JSON.stringify(e.metadata)),i[p.USER_STATUS_PK]=Pe.USER_STATUS_PK(s),i[p.USER_STATUS_SK]=Pe.USER_STATUS_SK(n),await this.docClient.send(new en.PutCommand({TableName:this.tableName,Item:Ur(i),ConditionExpression:lO("PK")}));let o={id:n,status:s,createdAt:W(t),updatedAt:W(t),...e.contactEmail&&{contactEmail:e.contactEmail},...e.contactPhone&&{contactPhone:e.contactPhone},...e.username&&{username:e.username},...e.displayName&&{displayName:e.displayName},...e.givenName&&{givenName:e.givenName},...e.familyName&&{familyName:e.familyName},...e.avatarUrl&&{avatarUrl:e.avatarUrl},...e.locale&&{locale:e.locale},...e.metadata&&{metadata:e.metadata}};return T(o)}catch(t){return S(V("create user",t))}}async updateProfile(e,t){try{let n=Ee(),s={};if(t.contactEmail!==void 0&&(s.contactEmail=t.contactEmail),t.contactPhone!==void 0&&(s.contactPhone=t.contactPhone),t.displayName!==void 0&&(s.displayName=t.displayName),t.givenName!==void 0&&(s.givenName=t.givenName),t.familyName!==void 0&&(s.familyName=t.familyName),t.avatarUrl!==void 0&&(s.avatarUrl=t.avatarUrl),t.locale!==void 0&&(s.locale=t.locale),t.metadata!==void 0&&(s.metadata=JSON.stringify(t.metadata)),Object.keys(s).length===0)return T(void 0);s.updatedAt=n;let i=Os(s);return await this.docClient.send(new en.UpdateCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:P.USER_PROFILE_SK()},UpdateExpression:i.UpdateExpression,ExpressionAttributeNames:i.ExpressionAttributeNames,ExpressionAttributeValues:i.ExpressionAttributeValues})),T(void 0)}catch(n){return S(V("updateProfile",n))}}async getByStatus(e,t){try{let n=Math.min(t?.limit||50,100),s;if(t?.cursor)try{s=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf-8"))}catch{return S(O.DatabaseQueryError({query:"invalid pagination cursor"}))}let i=Pe.USER_STATUS_PK(e),o=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:Se.USERS_BY_STATUS,KeyConditionExpression:`${p.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":i},Limit:n,ExclusiveStartKey:s})),a=[];if(o.Items&&o.Items.length>0)for(let l of o.Items){let d=ye.userId(l.PK);a.push(d)}let c=!!o.LastEvaluatedKey,u=c?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return T(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!t?.cursor,cursor:u}})}catch(n){return S(V("get users by status",n))}}async countByStatus(e){try{let t=Pe.USER_STATUS_PK(e),n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:Se.USERS_BY_STATUS,KeyConditionExpression:`${p.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":t},Select:"COUNT"}));return T(n.Count||0)}catch(t){return S(V("count users by status",t))}}async syncAuthStatus(e,t){try{let n=Ee(),s=`SET userStatus = :userStatus, #${p.UPDATED_AT} = :updatedAt, #${p.USER_STATUS_PK} = :statusPk, #${p.USER_STATUS_SK} = :statusSk`,i={":userStatus":t,":updatedAt":n,":statusPk":Pe.USER_STATUS_PK(t),":statusSk":Pe.USER_STATUS_SK(e)};return t===Bs.DELETED?(s+=", deletedAt = :deletedAt",i[":deletedAt"]=n):s+=" REMOVE deletedAt",await this.docClient.send(new en.UpdateCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:P.USER_PROFILE_SK()},UpdateExpression:s,ExpressionAttributeNames:{[`#${p.UPDATED_AT}`]:p.UPDATED_AT,[`#${p.USER_STATUS_PK}`]:p.USER_STATUS_PK,[`#${p.USER_STATUS_SK}`]:p.USER_STATUS_SK},ExpressionAttributeValues:i,ConditionExpression:"attribute_exists(PK)"})),T(void 0)}catch(n){return Je(n)?S(O.NotFound({entity:"userProfile",id:e})):S(V("sync auth status",n))}}async remove(e){try{return await this.docClient.send(new en.DeleteCommand({TableName:this.tableName,Key:{PK:P.USER_PK(e),SK:P.USER_PROFILE_SK()}})),T(void 0)}catch(t){return S(V("remove user profile",t))}}};var Wn=Ae(Kt(),1);var qm=class{tableName;docClient;constructor(e,t){this.tableName=t,this.docClient=Wn.DynamoDBDocumentClient.from(e)}mapItemToUserProviderLink(e){let t=ye.providerPKInfo(e.PK);if(!t)throw new Error(`Invalid provider PK: ${e.PK}`);let n={userId:e.userId,provider:t.provider,externalId:t.externalId,createdAt:W(e.createdAt)};if(e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata)try{n.metadata=JSON.parse(e.metadata)}catch{}return n}mapUserProviderLinkToItem(e){let t=Ee(),n={PK:P.PROVIDER_PK(e.provider,e.externalId),SK:P.PROVIDER_METADATA_SK(),userProviderPk:P.USER_PK(e.userId),userProviderSk:P.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?oe(e.createdAt):t};return e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),Ur(n)}async findByProviderAndExternalId(e,t){try{let n=await this.docClient.send(new Wn.GetCommand({TableName:this.tableName,Key:{PK:P.PROVIDER_PK(e,t),SK:P.PROVIDER_METADATA_SK()}}));return n.Item?T(this.mapItemToUserProviderLink(n.Item)):T(null)}catch(n){return S(V("find provider by external id",n))}}async findByUserId(e){try{let t=await this.docClient.send(new Wn.QueryCommand({TableName:this.tableName,IndexName:Se.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":p.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":P.USER_PK(e)}}));return!t.Items||t.Items.length===0?T([]):T(t.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch(t){return S(V("find providers by user id",t))}}async create(e){try{let t={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(t);return await this.docClient.send(new Wn.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),T(this.mapItemToUserProviderLink(n))}catch(t){return Je(t)?S(O.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):S(V("create user provider",t))}}async update(e,t,n){try{let s={};if(n.externalUsername!==void 0&&(s.externalUsername=n.externalUsername),n.externalEmail!==void 0&&(s.externalEmail=n.externalEmail),n.externalPhone!==void 0&&(s.externalPhone=n.externalPhone),n.externalName!==void 0&&(s.externalName=n.externalName),n.externalAvatarUrl!==void 0&&(s.externalAvatarUrl=n.externalAvatarUrl),n.metadata!==void 0&&(s.metadata=JSON.stringify(n.metadata)),Object.keys(s).length===0)return T(void 0);let{UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=Os(s);return await this.docClient.send(new Wn.UpdateCommand({TableName:this.tableName,Key:{PK:P.PROVIDER_PK(e,t),SK:P.PROVIDER_METADATA_SK()},UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a})),T(void 0)}catch(s){return S(V("update user provider",s))}}async remove(e,t){try{return await this.docClient.send(new Wn.DeleteCommand({TableName:this.tableName,Key:{PK:P.PROVIDER_PK(e,t),SK:P.PROVIDER_METADATA_SK()}})),T(void 0)}catch(n){return S(V("delete user provider",n))}}};var _a=Ae(Kt(),1);var Wm=class{docClient;tableName;constructor(e,t){this.docClient=e,this.tableName=t}mapItemToEntity(e){let t=ye.tenantId(e.PK),n=ye.tenantProfileUserId(e.SK),s={tenantId:t,userId:n,createdAt:W(e.createdAt),updatedAt:W(e.updatedAt)};return e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.displayName&&(s.displayName=e.displayName),e.displayNameSource&&(s.displayNameSource=e.displayNameSource),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.avatarUrl&&(s.avatarUrl=e.avatarUrl),e.locale&&(s.locale=e.locale),e.jobTitle&&(s.jobTitle=e.jobTitle),e.bio&&(s.bio=e.bio),e.metadata&&(s.metadata=JSON.parse(e.metadata)),s}async get(e,t){try{let n=await this.docClient.send(new _a.GetCommand({TableName:this.tableName,Key:{PK:P.TENANT_PROFILE_PK(e),SK:P.TENANT_PROFILE_SK(t)}}));return n.Item?T(this.mapItemToEntity(n.Item)):T(null)}catch(n){return S(V("get user tenant profile",n))}}async create(e){try{let t=Ee(),n={PK:P.TENANT_PROFILE_PK(e.tenantId),SK:P.TENANT_PROFILE_SK(e.userId),createdAt:t,updatedAt:t};e.contactEmail&&(n.contactEmail=e.contactEmail),e.contactPhone&&(n.contactPhone=e.contactPhone),e.displayName&&(n.displayName=e.displayName),e.displayNameSource&&(n.displayNameSource=e.displayNameSource),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.locale&&(n.locale=e.locale),e.jobTitle&&(n.jobTitle=e.jobTitle),e.bio&&(n.bio=e.bio),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),await this.docClient.send(new _a.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let s={tenantId:e.tenantId,userId:e.userId,createdAt:W(t),updatedAt:W(t)};return e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.displayName&&(s.displayName=e.displayName),e.displayNameSource&&(s.displayNameSource=e.displayNameSource),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.avatarUrl&&(s.avatarUrl=e.avatarUrl),e.locale&&(s.locale=e.locale),e.jobTitle&&(s.jobTitle=e.jobTitle),e.bio&&(s.bio=e.bio),e.metadata&&(s.metadata=e.metadata),T(s)}catch(t){return t.name==="ConditionalCheckFailedException"?S(O.UniqueConstraintViolation({field:"user tenant profile"})):S(Ir("create user tenant profile",t))}}async update(e,t,n){try{let s={updatedAt:Ee()};n.contactEmail!==void 0&&(s.contactEmail=n.contactEmail),n.contactPhone!==void 0&&(s.contactPhone=n.contactPhone),n.displayName!==void 0&&(s.displayName=n.displayName),n.displayNameSource!==void 0&&(s.displayNameSource=n.displayNameSource),n.givenName!==void 0&&(s.givenName=n.givenName),n.familyName!==void 0&&(s.familyName=n.familyName),n.avatarUrl!==void 0&&(s.avatarUrl=n.avatarUrl),n.locale!==void 0&&(s.locale=n.locale),n.jobTitle!==void 0&&(s.jobTitle=n.jobTitle),n.bio!==void 0&&(s.bio=n.bio),n.metadata!==void 0&&(s.metadata=n.metadata?JSON.stringify(n.metadata):null);let{UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=Os(s);return await this.docClient.send(new _a.UpdateCommand({TableName:this.tableName,Key:{PK:P.TENANT_PROFILE_PK(e),SK:P.TENANT_PROFILE_SK(t)},UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(s){return s.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"UserTenantProfile",id:`${e}:${t}`})):S(Ir("update user tenant profile",s))}}async remove(e,t){try{return await this.docClient.send(new _a.DeleteCommand({TableName:this.tableName,Key:{PK:P.TENANT_PROFILE_PK(e),SK:P.TENANT_PROFILE_SK(t)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?S(O.NotFound({entity:"UserTenantProfile",id:`${e}:${t}`})):S(Ir("remove user tenant profile",n))}}};var xT=class{name="database-dynamodb";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;registration;userAuths;tenantMembers;tenantInvites;userTenantProfiles;tenants;queries;client;tableName;constructor(e){this.tableName=e.tableName,this.client=e.client||new NT.DynamoDBClient(e.clientConfig||{});let t=wQ.DynamoDBDocumentClient.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new Gm(this.client,this.tableName),this.sessions=new Lm({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new qm(this.client,this.tableName),this.userMfaAuthenticators=new Hm(this.client,this.tableName),this.challenges=new Dm({docClient:t,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new Pm({docClient:t,tableName:this.tableName}),this.credentials=new Om({docClient:t,tableName:this.tableName}),this.registration=new km({docClient:t,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new Vm({docClient:t,tableName:this.tableName}),this.tenantMembers=new Fm(this.client,this.tableName),this.tenantInvites=new Um({docClient:t,tableName:this.tableName}),this.userTenantProfiles=new Wm(t,this.tableName),this.tenants=new Km({docClient:t,tableName:this.tableName}),this.queries={tenantInvites:new Mm({docClient:t,tableName:this.tableName}),tenantMembers:new $m({docClient:t,tableName:this.tableName}),tenants:new Bm({docClient:t,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new NT.DescribeTableCommand({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};JO();var QO=1,zY=2,JY=3,QY="auth-craft:internal";async function Txe(r){let e=r.replace(/^0x/,""),t=XY(e),n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),s=new Uint8Array(n.length+t.length);s.set(n),s.set(t,n.length);let i=`-----BEGIN PRIVATE KEY-----
188
188
  `+btoa(String.fromCharCode(...s)).match(/.{1,64}/g).join(`
189
189
  `)+`
190
190
  -----END PRIVATE KEY-----`;return mh(i,"EdDSA")}async function Ixe(r){let e=r.replace(/^0x/,""),t=XY(e),n=wxe(t);return Da({kty:"OKP",crv:"Ed25519",x:n},"EdDSA")}async function YO(r,e){if(e==="EdDSA"){let t=r.trim();if(t.startsWith("{"))return Da(JSON.parse(t),e);if(!t.includes(`
@@ -128,7 +128,7 @@ Invalid`)}},FromEmailAddress:"invalid@invalid",Destination:{ToAddresses:["invali
128
128
  </div>
129
129
  </body>
130
130
  </html>
131
- `}};var oc=class t{static createDirectSmtp(e){return new cd(e)}static create(e){return t.createDirectSmtp(e.smtp)}};var f0={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function sT(t={}){let e={...f0,...t},n=(()=>{if(t.customRegex)return t.customRegex;let i="[a-zA-Z0-9_\\-]";e.allowDots?(i+="+",i=`(${i}\\.?)+`):i+="+",e.allowPlusAddressing&&(i=`${i}(\\+[a-zA-Z0-9_\\-]+)?`);let o=e.requireTLD?"[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.[a-zA-Z]{2,}":"[a-zA-Z0-9][a-zA-Z0-9\\-\\.]*";return new RegExp(`^${i}@${o}$`)})();return{name:"email-identity",version:"1.0.0",identityType:"email",normalize(i){return i.toLowerCase().trim()},validate(i){if(!i||i.trim().length===0)return d([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(i.length>254)return d([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(i))return d([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(i.includes(".."))return d([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let o=i.split("@");if(o.length!==2)return d([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[s,a]=o;return!s||s.length>64?d([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?d([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):T()}}}function Lm(t=6){let e="";for(;e.length<t;){let r=new Uint8Array(t);crypto.getRandomValues(r);for(let n=0;n<r.length&&e.length<t;n++){let i=r[n];i>=250||(e+=(i%10).toString())}}return e}function m0(t){return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function Mm(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return m0(r)}var Km="email",ld={EMAIL_SYSTEM_NOT_AVAILABLE:_("MFA_EMAIL_SYSTEM_NOT_AVAILABLE","Email system is not configured"),RECIPIENT_NOT_FOUND:_("MFA_EMAIL_RECIPIENT_NOT_FOUND","No email address on file for this user"),SEND_FAILED:_("MFA_EMAIL_SEND_FAILED","Failed to send the verification email"),USE_CHALLENGE_CODE_HASH:_("MFA_EMAIL_USE_CHALLENGE_CODE_HASH","Email MFA codes are verified against the challenge code hash, not stored credentials")};function h0(t){let[e,r]=t.split("@");return!e||!r?"***":`${e.slice(0,1)}***@${r}`}function aT(t={}){let e=t.codeLength??6,r=t.template??"mfa-email-code";return{name:"email-mfa",version:"1.0.0",method:Km,requiresServerDelivery:!0,async sendCode(n,i){if(!i.plugins.emailSystem)return d(ld.EMAIL_SYSTEM_NOT_AVAILABLE());let o=await i.plugins.database.users.getById(n.userId),s=o.ok&&o.data?o.data.contactEmail:void 0;if(!s)return d(ld.RECIPIENT_NOT_FOUND());let a=Lm(e),c=await Mm(a);return(await i.plugins.emailSystem.send({to:s,template:r,variables:{code:a,purpose:"mfa"}})).ok===!1?d(ld.SEND_FAILED()):T({codeHash:c,maskedRecipient:h0(s)})},async issueChallenge(n){return T({challengeId:`email_${Date.now()}`,methods:n.availableMethods.includes(Km)?[Km]:n.availableMethods,expiresAt:new Date(Date.now()+300*1e3)})},async verify(){return d(ld.USE_CHALLENGE_CODE_HASH())}}}var cT="ABCDEFGHIJKLMNPQRSTUVWXYZ23456789";function ud(t=10,e=10){let r=[];for(let n=0;n<t;n++){let i=new Uint8Array(e);crypto.getRandomValues(i);let o="";for(let s of i)o+=cT[s%cT.length];r.push(o)}return r}function E0(t){return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function dd(t){let e=new TextEncoder().encode(t.toUpperCase().trim()),r=await crypto.subtle.digest("SHA-256",e);return E0(r)}function y0(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function Hm(t,e){let r=await dd(t),n=null;for(let i of e)y0(r,i)&&(n=i);return n}var Fm="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function lT(t){let e=t.toUpperCase().replace(/=+$/u,"").replace(/\s+/gu,""),r=0,n=0,i=[];for(let o of e){let s=Fm.indexOf(o);if(s===-1)throw new Error("Invalid base32 character in TOTP secret");n=n<<5|s,r+=5,r>=8&&(r-=8,i.push(n>>>r&255))}return new Uint8Array(i)}function uT(t){let e=0,r=0,n="";for(let i of t)for(r=r<<8|i,e+=8;e>=5;)e-=5,n+=Fm[r>>>e&31];return e>0&&(n+=Fm[r<<5-e&31]),n}function pd(t=20){let e=new Uint8Array(t);return crypto.getRandomValues(e),uT(e)}function g0(t){let e=new Uint8Array(8),r=t;for(let n=7;n>=0;n--)e[n]=r&255,r=Math.floor(r/256);return e}async function v0(t,e,r){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-1"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",n,g0(e))),o=i[i.length-1]&15;return(((i[o]&127)<<24|(i[o+1]&255)<<16|(i[o+2]&255)<<8|i[o+3]&255)%10**r).toString().padStart(r,"0")}async function fd(t,e,r=Date.now(),n={}){let i=n.period??30,o=n.digits??6,s=n.window??1,a=e.trim();if(a.length!==o||!/^\d+$/u.test(a))return!1;let c=lT(t),l=Math.floor(r/1e3/i),u=!1;for(let p=-s;p<=s;p++){let f=await v0(c,l+p,o);A0(f,a)&&(u=!0)}return u}function A0(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}function dT(t){let e=encodeURIComponent(`${t.issuer}:${t.accountName}`),r=new URLSearchParams({secret:t.secretBase32,issuer:t.issuer,algorithm:"SHA1",digits:String(t.digits??6),period:String(t.period??30)});return`otpauth://totp/${e}?${r.toString()}`}var Vm="totp",T0={USE_VERIFY_WITH_CREDENTIALS:{code:"TOTP_USE_VERIFY_WITH_CREDENTIALS",message:"TOTP verification requires credential data; call verifyWithCredentials()"}};function pT(t={}){let e=t.issuer??"Auth Craft",r=t.backupCodeCount??10,n=t.window??1;return{name:"totp-mfa",version:"1.0.0",method:Vm,requiresServerDelivery:!1,generateSecret(){return pd()},generateBackupCodes(i){return ud(i||r)},async issueChallenge(i){return T({challengeId:`totp_${Date.now()}`,methods:i.availableMethods.includes(Vm)?[Vm]:i.availableMethods,expiresAt:new Date(Date.now()+300*1e3)})},async verify(){return d(T0.USE_VERIFY_WITH_CREDENTIALS)},async setup(i){let o=pd(),s=ud(r),a=await Promise.all(s.map(p=>dd(p))),c=i.data.accountName??i.userId,l=dT({secretBase32:o,accountName:c,issuer:e});return T({secret:o,otpauthUri:l,backupCodes:s,credentialData:{secret:o,backupCodeHashes:a}})},async verifyWithCredentials(i){let o=i.credentialData,s=i.data.code?.trim();if(!s||!o?.secret)return T({verified:!1,data:{}});if(await fd(o.secret,s,Date.now(),{window:n}))return T({verified:!0,data:{}});let c=o.backupCodeHashes??[];if(c.length>0){let l=await Hm(s,c);if(l)return T({verified:!0,data:{usedBackupCodeHash:l}})}return T({verified:!1,data:{}})},async verifyCredential(i,o){let s=i.data.code,a=i.data.secret;if(!s||!a)return T({verified:!1,data:{}});let c=await fd(a,s,Date.now(),{window:n});return T({verified:c,data:{}})}}}var Bm={scopes:["email","public_profile"],apiVersion:"v18.0"};var Zr={INVALID_CODE:_("FACEBOOK_INVALID_CODE","Invalid authorization code"),TOKEN_EXCHANGE_FAILED:_("FACEBOOK_TOKEN_EXCHANGE_FAILED","Failed to exchange code for token"),USER_PROFILE_FAILED:_("FACEBOOK_USER_PROFILE_FAILED","Failed to fetch user profile"),INVALID_TOKEN:_("FACEBOOK_INVALID_TOKEN","Invalid access token"),MISSING_CONFIG:_("FACEBOOK_MISSING_CONFIG","Missing required Facebook OAuth configuration")};function jm(t={}){let{scopes:e=Bm.scopes,apiVersion:r=Bm.apiVersion}=t,n={AUTHORIZATION:`https://www.facebook.com/${r}/dialog/oauth`,TOKEN:`https://graph.facebook.com/${r}/oauth/access_token`,USER_INFO:`https://graph.facebook.com/${r}/me`,DEBUG_TOKEN:`https://graph.facebook.com/${r}/debug_token`};return{name:"facebook-oauth-provider",version:"1.0.0",getAuthorizationUrl(i,o){let s=new URLSearchParams({client_id:i.clientId,redirect_uri:i.redirectUri,scope:(i.scopes??e).join(","),response_type:"code",...o&&{state:o}});return`${n.AUTHORIZATION}?${s.toString()}`},async exchangeCodeForToken(i,o){try{if(!i)return d(Zr.INVALID_CODE());let s=new URLSearchParams({client_id:o.clientId,client_secret:o.clientSecret,code:i,redirect_uri:o.redirectUri}),a=await fetch(`${n.TOKEN}?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return d(Zr.TOKEN_EXCHANGE_FAILED());let c=await a.json();return T({accessToken:c.access_token,...c.expires_in&&{expiresIn:c.expires_in}})}catch(s){return console.error("Facebook token exchange error:",s),d(Zr.TOKEN_EXCHANGE_FAILED())}},async getUserProfile(i){try{if(!i)return d(Zr.INVALID_TOKEN());let o=["id","email","name","first_name","last_name","picture","locale"],s=new URLSearchParams({fields:o.join(","),access_token:i}),a=await fetch(`${n.USER_INFO}?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return d(Zr.USER_PROFILE_FAILED());let c=await a.json(),l={id:c.id,...c.email&&{email:c.email},...c.email&&{emailVerified:!1},...c.name&&{name:c.name},...c.first_name&&{givenName:c.first_name},...c.last_name&&{familyName:c.last_name},...c.picture?.data?.url&&{avatarUrl:c.picture.data.url},...c.locale&&{locale:c.locale},provider:"facebook"};return T(l)}catch(o){return console.error("Facebook user profile error:",o),d(Zr.USER_PROFILE_FAILED())}},async verifyAccessToken(i){try{if(!i)return d(Zr.INVALID_TOKEN());let o=`${t.appId}|${t.appSecret}`,s=new URLSearchParams({input_token:i,access_token:o}),a=await fetch(`${n.DEBUG_TOKEN}?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}});return a.ok?(await a.json()).data.is_valid?this.getUserProfile(i):d(Zr.INVALID_TOKEN()):d(Zr.INVALID_TOKEN())}catch(o){return console.error("Facebook token verification error:",o),d(Zr.INVALID_TOKEN())}}}}var md={scopes:["openid","email","profile"],accessType:"online",includeGrantedScopes:!1},Ji={AUTHORIZATION:"https://accounts.google.com/o/oauth2/v2/auth",TOKEN:"https://oauth2.googleapis.com/token",USER_INFO:"https://www.googleapis.com/oauth2/v2/userinfo",TOKEN_INFO:"https://oauth2.googleapis.com/tokeninfo",REVOKE:"https://oauth2.googleapis.com/revoke"};var tt={INVALID_CODE:_("GOOGLE_INVALID_CODE","Invalid authorization code"),TOKEN_EXCHANGE_FAILED:_("GOOGLE_TOKEN_EXCHANGE_FAILED","Failed to exchange code for token"),USER_PROFILE_FAILED:_("GOOGLE_USER_PROFILE_FAILED","Failed to fetch user profile"),INVALID_TOKEN:_("GOOGLE_INVALID_TOKEN","Invalid access token"),INVALID_CREDENTIAL:_("GOOGLE_INVALID_CREDENTIAL","Invalid ID token or credential"),CREDENTIAL_VERIFICATION_FAILED:_("GOOGLE_CREDENTIAL_VERIFICATION_FAILED","Failed to verify credential"),REFRESH_TOKEN_FAILED:_("GOOGLE_REFRESH_TOKEN_FAILED","Failed to refresh access token"),MISSING_CONFIG:_("GOOGLE_MISSING_CONFIG","Missing required Google OAuth configuration")};function _0(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;if(r){if(r===1)throw new Error("Invalid base64url string");e+=new Array(5-r).join("=")}try{return decodeURIComponent(atob(e).split("").map(n=>`%${`00${n.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""))}catch{throw new Error("Failed to decode base64url")}}function I0(t){try{let e=t.split(".");if(e.length!==3)return null;let r=e[1];if(!r)return null;let n=_0(r);return JSON.parse(n)}catch(e){return console.error("Failed to decode JWT:",e),null}}function Gm(t={}){let{clientId:e,clientSecret:r,redirectUri:n,scopes:i=md.scopes,accessType:o=md.accessType,includeGrantedScopes:s=md.includeGrantedScopes,prompt:a}=t;return{name:"google-oauth-provider",version:"1.0.0",getAuthorizationUrl(c,l){let u=c?.clientId??e,p=c?.redirectUri??n;if(!u||!p)throw new Error("Google OAuth: clientId and redirectUri are required");let f=new URLSearchParams({client_id:u,redirect_uri:p,response_type:"code",scope:(c?.scopes??i).join(" "),access_type:o,...l&&{state:l},...a&&{prompt:a},...s&&{include_granted_scopes:"true"}});return`${Ji.AUTHORIZATION}?${f.toString()}`},async exchangeCodeForToken(c,l){let u=l?.clientId??e,p=l?.clientSecret??r,f=l?.redirectUri??n;try{if(!c)return d(tt.INVALID_CODE());if(!u||!p||!f)return d(tt.MISSING_CONFIG());let m=new URLSearchParams({client_id:u,client_secret:p,code:c,redirect_uri:f,grant_type:"authorization_code"}),E=await fetch(Ji.TOKEN,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:m.toString()});if(!E.ok)return console.error("Google token exchange failed with status:",E.status),d(tt.TOKEN_EXCHANGE_FAILED());let v=await E.json();return T({accessToken:v.access_token,...v.refresh_token&&{refreshToken:v.refresh_token},...v.expires_in&&{expiresIn:v.expires_in}})}catch(m){return console.error("Google token exchange error:",m),d(tt.TOKEN_EXCHANGE_FAILED())}},async getUserProfile(c){try{if(!c)return d(tt.INVALID_TOKEN());let l=await fetch(Ji.USER_INFO,{method:"GET",headers:{Authorization:`Bearer ${c}`,Accept:"application/json"}});if(!l.ok)return console.error("Google user profile failed with status:",l.status),d(tt.USER_PROFILE_FAILED());let u=await l.json(),p={id:u.id,...u.email&&{email:u.email},...u.verified_email!==void 0&&{emailVerified:u.verified_email},...u.name&&{name:u.name},...u.given_name&&{givenName:u.given_name},...u.family_name&&{familyName:u.family_name},...u.picture&&{avatarUrl:u.picture},...u.locale&&{locale:u.locale},provider:"google"};return T(p)}catch(l){return console.error("Google user profile error:",l),d(tt.USER_PROFILE_FAILED())}},async verifyAccessToken(c){try{if(!c)return d(tt.INVALID_TOKEN());let l=await fetch(`${Ji.TOKEN_INFO}?access_token=${c}`,{method:"GET",headers:{Accept:"application/json"}});if(!l.ok)return d(tt.INVALID_TOKEN());let u=await l.json();return parseInt(u.expires_in,10)<=0?d(tt.INVALID_TOKEN()):this.getUserProfile(c)}catch(l){return console.error("Google token verification error:",l),d(tt.INVALID_TOKEN())}},async verifyCredential(c){try{if(!c)return d(tt.INVALID_CREDENTIAL());let l=await fetch(`${Ji.TOKEN_INFO}?id_token=${encodeURIComponent(c)}`,{method:"GET",headers:{Accept:"application/json"}});if(!l.ok)return console.error("Google credential verification failed with status:",l.status),d(tt.INVALID_CREDENTIAL());let u=await l.json();if(!e)return d(tt.MISSING_CONFIG());if(u.aud!==e)return d(tt.INVALID_CREDENTIAL());if(parseInt(u.expires_in,10)<=0)return d(tt.INVALID_CREDENTIAL());let f=u.email_verified==="true",m=I0(c),E={id:u.sub,...u.email&&{email:u.email},...u.email&&{emailVerified:f},...m?.name&&{name:m.name},...m?.given_name&&{givenName:m.given_name},...m?.family_name&&{familyName:m.family_name},...m?.picture&&{avatarUrl:m.picture},...m?.locale&&{locale:m.locale},provider:"google"};return T(E)}catch(l){return console.error("Google credential verification error:",l),d(tt.CREDENTIAL_VERIFICATION_FAILED())}},async refreshAccessToken(c,l){let u=l?.clientId??e,p=l?.clientSecret??r;try{if(!c)return d(tt.INVALID_TOKEN());if(!u||!p)return d(tt.MISSING_CONFIG());let f=new URLSearchParams({client_id:u,client_secret:p,refresh_token:c,grant_type:"refresh_token"}),m=await fetch(Ji.TOKEN,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:f.toString()});if(!m.ok)return console.error("Google refresh token failed with status:",m.status),d(tt.REFRESH_TOKEN_FAILED());let E=await m.json();return T({accessToken:E.access_token,...E.expires_in&&{expiresIn:E.expires_in}})}catch(f){return console.error("Google refresh token error:",f),d(tt.REFRESH_TOKEN_FAILED())}}}}function fT(t={}){let e=new Map,r=t.sweepIntervalMs??6e4,n=0,i;function o(){if(n===0)return;let s=Date.now()-n;for(let[a,c]of e){let l=c.hits.filter(u=>u>s);l.length===0?e.delete(a):c.hits=l}}return r>0&&(i=setInterval(o,r),i.unref?.()),{name:"rate-limiter-memory",version:"1.0.0",async consume(s,a){let{limit:c,windowMs:l}=a;l>n&&(n=l);let u=Date.now(),p=u-l,f=e.get(s)??{hits:[]},m=f.hits.filter(E=>E>p);if(m.length>=c){let E=m[0]??u,v=Math.max(0,E+l-u);return f.hits=m,e.set(s,f),{allowed:!1,remaining:0,retryAfterMs:v,limit:c}}return m.push(u),f.hits=m,e.set(s,f),{allowed:!0,remaining:c-m.length,retryAfterMs:0,limit:c}},async reset(s){e.delete(s)},async cleanup(){i&&clearInterval(i),e.clear()}}}import{DescribeTableCommand as XO,DynamoDBClient as QO}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as ZO}from"@aws-sdk/lib-dynamodb";var te={DatabaseConnectionError:_("DATABASE_CONNECTION_ERROR","Failed to connect to database"),DatabaseQueryError:Q("DATABASE_QUERY_ERROR","Database query execution failed: {query}"),NotFound:Q("REPOSITORY_NOT_FOUND","{entity} with {id} not found"),UniqueConstraintViolation:Q("UNIQUE_CONSTRAINT_VIOLATION","Record with this {field} already exists"),ForeignKeyViolation:Q("FOREIGN_KEY_VIOLATION","Referenced {field} does not exist"),RecordLocked:_("RECORD_LOCKED","Record is currently locked by another operation"),DeadlockDetected:_("DEADLOCK_DETECTED","Transaction deadlock detected"),InvalidData:Q("INVALID_DATA","Invalid data: {reason}"),Timeout:_("REPOSITORY_TIMEOUT","Database operation timed out"),AttemptsExceeded:_("ATTEMPTS_EXCEEDED","Attempt limit reached"),TransactionFailed:Q("TRANSACTION_FAILED","Transaction failed: {reason}"),UnknownError:Q("REPOSITORY_UNKNOWN_ERROR","Unexpected database error: {message}")};function re(t){return t.getTime()}function J(t){return new Date(t)}function mT(t){return Math.floor(t/1e3)}function ae(){return Date.now()}function sc(t){return t instanceof Date?mT(t.getTime()):mT(t)}function $m(t){return t<Date.now()}function Cr(t){return t?re(t):null}function Kt(t){return t==null?null:J(t)}function Ht(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}function Dr(t){let e=[],r=[],n={},i={},o=0;for(let[c,l]of Object.entries(t)){if(c==="PK"||c==="SK")continue;let u=`#${c}`;if(n[u]=c,l==null)r.push(u);else{let p=`:val${o}`;e.push(`${u} = ${p}`),i[p]=l,o++}}let s=[];return e.length>0&&s.push(`SET ${e.join(", ")}`),r.length>0&&s.push(`REMOVE ${r.join(", ")}`),{UpdateExpression:s.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:i}}function qm(t="PK"){return`attribute_not_exists(${t})`}var Wm={USER:"USR"},ce={USER:`${Wm.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},Be={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},Tt="#",U={USER_PK:t=>`${ce.USER}${t}`,USER_AUTH_SK:()=>Be.AUTH,USER_PROFILE_SK:()=>Be.PROFILE,USER_MFA_SK:t=>`${Be.MFA}${t}`,USER_MFA_WITH_ID_SK:(t,e)=>`${Be.MFA}${t}${Tt}${e}`,TENANT_MEMBER_PK:t=>`${ce.TENANT}${t}`,TENANT_MEMBER_SK:t=>`${ce.USER}${t}`,TENANT_OWNER_MARKER_SK:()=>Be.OWNER,TENANT_PK:t=>`${ce.TENANT}${t}`,TENANT_SK:()=>Be.METADATA,INVITE_PK:t=>`${ce.INVITE}${t}`,INVITE_SK:()=>Be.METADATA,TENANT_PROFILE_PK:t=>`${ce.TENANT}${t}`,TENANT_PROFILE_SK:t=>`${Be.TENANT_PROFILE}${ce.USER}${t}`,SESSION_PK:t=>`${ce.SESSION}${t}`,SESSION_METADATA_SK:()=>Be.METADATA,SESSION_SK:()=>Be.METADATA,PROVIDER_SK:(t,e)=>`${Be.PROVIDER}${t}${Tt}${e}`,PROVIDER_PK:(t,e)=>`${ce.PROVIDER}${t}${Tt}${e}`,PROVIDER_METADATA_SK:()=>Be.METADATA,CHALLENGE_PK:t=>`${ce.CHALLENGE}${t}`,CHALLENGE_SK:()=>Be.METADATA,IDENTITY_PK:(t,e)=>`${ce.IDENTITY}${t}#${e}`,IDENTITY_SK:()=>Be.METADATA,CREDENTIAL_PK:t=>`${ce.CREDENTIAL}${t}`,CREDENTIAL_SK:()=>Be.METADATA,CREDENTIAL_TYPE_PREFIX:t=>`${ce.CREDENTIAL}${t}#`,CREDENTIAL_USER_SK:(t,e)=>`${ce.CREDENTIAL}${t}#${e}`,USER_INDEX_PK:t=>`${ce.USER}${t}`,USER_INDEX_SK:(t,e)=>`${ce.IDENTITY}${t}#${e}`},le={userId:t=>t.slice(ce.USER.length),sessionId:t=>t.slice(ce.SESSION.length),providerPKInfo:t=>{let e=t.slice(ce.PROVIDER.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},providerInfo:t=>{let e=t.slice(Be.PROVIDER.length),r=e.indexOf(Tt);if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},mfaSKInfo:t=>{let e=t.slice(Be.MFA.length),r=e.indexOf(Tt);if(r===-1)return{method:e};let n=e.slice(0,r),i=e.slice(r+1);return{method:n,id:i}},tenantId:t=>t.slice(ce.TENANT.length),tenantMemberUserId:t=>t.slice(ce.USER.length),challengeIdFromPK:t=>t.slice(ce.CHALLENGE.length),inviteId:t=>t.slice(ce.INVITE.length),tenantProfileUserId:t=>t.slice(Be.TENANT_PROFILE.length+ce.USER.length),identityPKInfo:t=>{let e=t.slice(ce.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}},credentialId:t=>t.slice(ce.CREDENTIAL.length),credentialTypeFromUserSK:t=>{let e=t.slice(ce.CREDENTIAL.length),r=e.indexOf("#");return r===-1?"":e.slice(0,r)},userIndexSKInfo:t=>{let e=t.slice(ce.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}}};var Ae={ACTIVE_SESSION_PK:t=>`${ce.USER}${t}`,ACTIVE_SESSION_SK:(t,e)=>`${t}${Tt}${e}`,USER_SESSION_PK:t=>`${ce.USER}${t}`,USER_SESSION_SK:(t,e)=>`${t}${Tt}${e}`,USER_STATUS_PK:t=>{let e=t===ye.ACTIVE?"ACTIVE":"INACTIVE";return`${Wm.USER}${Tt}${e}`},USER_STATUS_SK:t=>t,USER_PROVIDER_PK:t=>`${ce.USER}${t}`,USER_PROVIDER_SK:(t,e)=>`${Be.PROVIDER}${t}${Tt}${e}`,INVITE_TENANT_PK:t=>`${ce.TENANT}${t}`,INVITE_TENANT_SK:(t,e,r)=>`${t}${Tt}${e}${Tt}${r}`,INVITE_TENANT_STATUS_PREFIX:t=>`${t}${Tt}`,USER_TENANT_PK:t=>`${ce.USER}${t}`,USER_TENANT_SK:(t,e,r,n)=>`${t}${Tt}${e??"ROOT"}${Tt}${r}${Tt}${n}`},h={PK:"PK",SK:"SK",TTL:"TTL",ACTIVE_SESSION_PK:"activeSessionPk",ACTIVE_SESSION_SK:"activeSessionSk",USER_SESSION_PK:"userSessionPk",USER_SESSION_SK:"userSessionSk",USER_STATUS_PK:"userStatusPk",USER_STATUS_SK:"userStatusSk",USER_PROVIDER_PK:"userProviderPk",USER_PROVIDER_SK:"userProviderSk",USER_ID:"userId",TENANT_ID:"tenantId",TENANT_TYPE:"tenantType",AUDIENCE:"audience",PURPOSE:"purpose",CHALLENGE_STATUS:"challengeStatus",PHASE:"phase",ALLOWED_METHODS:"allowedMethods",METHOD:"method",IDENTITY_TYPE:"identityType",IDENTITY_VALUE:"identityValue",CODE_HASH:"codeHash",ATTEMPTS:"attempts",MAX_ATTEMPTS:"maxAttempts",METADATA:"metadata",FLOW_KEY:"flowKey",EXPIRES_AT:"expiresAt",CREATED_AT:"createdAt",TOKEN_ID:"tokenId",PREVIOUS_TOKEN_ID:"previousTokenId",ROTATED_AT:"rotatedAt",LAST_USED_AT:"lastUsedAt",REVOKED_AT:"revokedAt",ROLE:"role",ROLES:"roles",PERM:"perm",AUTH_PERM:"authPerm",IS_OWNER:"isOwner",DEVICE_LABEL:"deviceLabel",COUNTRY:"country",CITY:"city",IDENTITY_USER_PK:"identityUserPk",IDENTITY_USER_SK:"identityUserSk",LOGIN_ENABLED:"loginEnabled",VERIFIED_AT:"verifiedAt",GUARDS:"guards",PENDING_VERIFICATION:"pendingVerification",UPDATED_AT:"updatedAt",CREDENTIAL_USER_PK:"credentialUserPk",CREDENTIAL_USER_SK:"credentialUserSk",CREDENTIAL_VALUE:"value",INVITE_STATUS:"inviteStatus",INVITE_TOKEN:"inviteToken",INVITED_BY_ID:"invitedById",INVITED_BY_INFO:"invitedByInfo",INVITEE_USER_ID:"inviteeUserId",INVITEE_EMAIL:"inviteeEmail",INVITEE_PHONE:"inviteePhone",ACCEPTED_AT:"acceptedAt",DECLINED_AT:"declinedAt",INVITE_TENANT_PK:"inviteTenantPk",INVITE_TENANT_SK:"inviteTenantSk",INVITE_TOKEN_GSI:"inviteTokenGsi",INVITEE_EMAIL_GSI:"inviteeEmailGsi",INVITEE_EMAIL_TENANT_SK:"inviteeEmailTenantSk",INVITEE_PHONE_GSI:"inviteePhoneGsi",INVITEE_PHONE_TENANT_SK:"inviteePhoneTenantSk",USER_TENANT_PK:"userTenantPk",USER_TENANT_SK:"userTenantSk",DISPLAY_NAME:"displayName",AVATAR_URL:"avatarUrl",TITLE:"title",BIO:"bio"},hd={sessionSK:(t,e)=>`${t instanceof Date?t.getTime():t}${Tt}${e}`,extractCreatedAt:t=>{let e=t.indexOf(Tt),r=e===-1?t:t.slice(0,e);return Number(r)}};var ue={ACTIVE_SESSIONS:"GSI_ActiveSessions",USER_SESSIONS:"GSI_UserSessions",USERS_BY_STATUS:"GSI_UsersByStatus",USER_PROVIDERS:"GSI_UserProviders",USER_IDENTITIES:"GSI_UserIdentities",USER_CREDENTIALS:"GSI_UserCredentials",TENANT_INVITES:"GSI_TenantInvites",INVITE_TOKEN:"GSI_InviteToken",INVITEE_EMAIL:"GSI_InviteeEmail",INVITEE_PHONE:"GSI_InviteePhone",USER_TENANTS:"GSI_UserTenants"},We="S",x0={partitionKey:{name:"PK",type:We},sortKey:{name:"SK",type:We},ttlAttribute:"TTL",globalSecondaryIndexes:[{indexName:ue.ACTIVE_SESSIONS,partitionKey:{name:"activeSessionPk",type:We},sortKey:{name:"activeSessionSk",type:We},projection:{type:"KEYS_ONLY"}},{indexName:ue.USER_SESSIONS,partitionKey:{name:"userSessionPk",type:We},sortKey:{name:"userSessionSk",type:We},projection:{type:"KEYS_ONLY"}},{indexName:ue.USERS_BY_STATUS,partitionKey:{name:"userStatusPk",type:We},sortKey:{name:"userStatusSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["displayName","createdAt"]}},{indexName:ue.USER_PROVIDERS,partitionKey:{name:"userProviderPk",type:We},sortKey:{name:"userProviderSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["userId","externalEmail","externalName","createdAt"]}},{indexName:ue.USER_IDENTITIES,partitionKey:{name:"identityUserPk",type:We},sortKey:{name:"identityUserSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["loginEnabled","verifiedAt","createdAt"]}},{indexName:ue.USER_CREDENTIALS,partitionKey:{name:"credentialUserPk",type:We},sortKey:{name:"credentialUserSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["revokedAt","createdAt"]}},{indexName:ue.USER_TENANTS,partitionKey:{name:"userTenantPk",type:We},sortKey:{name:"userTenantSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["userStatus","role","roles","perm","authPerm","isOwner","createdAt","updatedAt"]}},{indexName:ue.TENANT_INVITES,partitionKey:{name:"inviteTenantPk",type:We},sortKey:{name:"inviteTenantSk",type:We},projection:{type:"ALL"}},{indexName:ue.INVITE_TOKEN,partitionKey:{name:"inviteTokenGsi",type:We},projection:{type:"KEYS_ONLY"}},{indexName:ue.INVITEE_EMAIL,partitionKey:{name:"inviteeEmailGsi",type:We},sortKey:{name:"inviteeEmailTenantSk",type:We},projection:{type:"ALL"}},{indexName:ue.INVITEE_PHONE,partitionKey:{name:"inviteePhoneGsi",type:We},sortKey:{name:"inviteePhoneTenantSk",type:We},projection:{type:"ALL"}}]};import{DeleteCommand as J0,GetCommand as Y0,PutCommand as X0,UpdateCommand as RT}from"@aws-sdk/lib-dynamodb";var b0=BigInt(0),ac=BigInt(1),S0=BigInt(2),w0=BigInt(7),N0=BigInt(256),R0=BigInt(113),yT=[],gT=[],vT=[];for(let t=0,e=ac,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],yT.push(2*(5*n+r)),gT.push((t+1)*(t+2)/2%64);let i=b0;for(let o=0;o<7;o++)e=(e<<ac^(e>>w0)*R0)%N0,e&S0&&(i^=ac<<(ac<<BigInt(o))-ac);vT.push(i)}var AT=Ov(vT,!0),O0=AT[0],k0=AT[1],C0=(t,e,r)=>t<<r|e>>>32-r,D0=(t,e,r)=>e<<r|t>>>32-r,P0=(t,e,r)=>e<<r-32|t>>>64-r,U0=(t,e,r)=>t<<r-32|e>>>64-r,hT=(t,e,r)=>r>32?P0(t,e,r):C0(t,e,r),ET=(t,e,r)=>r>32?U0(t,e,r):D0(t,e,r),_s=new Uint32Array(10);function L0(t,e=24){if(!(t instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof t);if(t.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+t.length);if(Ye(e,"rounds"),e<1||e>24)throw new Error('"rounds" expected integer 1..24');for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)_s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){let s=(o+8)%10,a=(o+2)%10,c=_s[a],l=_s[a+1],u=hT(c,l,1)^_s[s],p=ET(c,l,1)^_s[s+1];for(let f=0;f<50;f+=10)t[o+f]^=u,t[o+f+1]^=p}let n=t[2],i=t[3];for(let o=0;o<24;o++){let s=gT[o],a=hT(n,i,s),c=ET(n,i,s),l=yT[o];n=t[l],i=t[l+1],t[l]=a,t[l+1]=c}for(let o=0;o<50;o+=10){let s=t[o],a=t[o+1],c=t[o+2],l=t[o+3];t[o]^=~t[o+2]&t[o+4],t[o+1]^=~t[o+3]&t[o+5],t[o+2]^=~t[o+4]&t[o+6],t[o+3]^=~t[o+5]&t[o+7],t[o+4]^=~t[o+6]&t[o+8],t[o+5]^=~t[o+7]&t[o+9],t[o+6]^=~t[o+8]&s,t[o+7]^=~t[o+9]&a,t[o+8]^=~s&c,t[o+9]^=~a&l}t[0]^=O0[r],t[1]^=k0[r]}Nt(_s)}var zm=class t{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,r,n,i=!1,o=24){if(Ye(e,"blockLen"),Ye(r,"suffix"),Ye(o,"rounds"),wv(i,"enableXOF"),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.canXOF=i,this.rounds=o,Ye(n,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=ji(this.state)}clone(){return this._cloneInto()}keccak(){fs(this.state32),L0(this.state32,this.rounds),fs(this.state32),this.posOut=0,this.pos=0}update(e){bn(this),xn(e);let{blockLen:r,state:n,state32:i}=this,o=e.length,s=r%4===0&&e.byteOffset%4===0,a=r/4,c=s&&o>=r?ji(e):void 0;for(let l=0;l<o;){if(c!==void 0&&this.pos===0&&l%4===0&&o-l>=r){for(let p=0,f=l/4;p<a;p++)i[p]^=c[f+p];l+=r,this.pos=r,this.keccak();continue}let u=Math.min(r-this.pos,o-l);for(let p=0;p<u;p++)n[this.pos++]^=e[l++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,(r&128)!==0&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){bn(this,!1),xn(e),this.finish();let r=this.state,{blockLen:n}=this;for(let i=0,o=e.length;i<o;){this.posOut>=n&&this.keccak();let s=Math.min(n-this.posOut,o-i);e.set(r.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(e)}xof(e){return Ye(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ds(e,this),this.finished)throw new Error("digest() was already called");this.writeInto(e.length===this.outputLen?e:e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,Nt(this.state)}_cloneInto(e){let{blockLen:r,suffix:n,outputLen:i,rounds:o,enableXOF:s}=this;return e||=new t(r,n,i,s,o),e.blockLen=r,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=n,e.outputLen=i,e.enableXOF=s,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},M0=(t,e,r,n={})=>Ru(()=>new zm(e,t,r),n);var TT=M0(6,72,64,Ou(10));var K0=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Jm=Math.ceil,pr=Math.floor,Gt="[BigNumber Error] ",_T=Gt+"Number primitive has more than 15 significant digits: ",Pr=1e14,de=14,Ym=9007199254740991,Xm=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],pi=1e7,mt=1e9;function IT(t){var e,r,n,i=R.prototype={constructor:R,toString:null,valueOf:null},o=new R(1),s=20,a=4,c=-7,l=21,u=-1e7,p=1e7,f=!1,m=1,E=0,v={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},N="0123456789abcdefghijklmnopqrstuvwxyz",S=!0;function R(A,x){var b,g,I,O,D,k,C,P,L=this;if(!(L instanceof R))return new R(A,x);if(x==null){if(A&&A._isBigNumber===!0){L.s=A.s,!A.c||A.e>p?L.c=L.e=null:A.e<u?L.c=[L.e=0]:(L.e=A.e,L.c=A.c.slice());return}if((k=typeof A=="number")&&A*0==0){if(L.s=1/A<0?(A=-A,-1):1,A===~~A){for(O=0,D=A;D>=10;D/=10,O++);O>p?L.c=L.e=null:(L.e=O,L.c=[A]);return}P=String(A)}else{if(!K0.test(P=String(A)))return n(L,P,k);L.s=P.charCodeAt(0)==45?(P=P.slice(1),-1):1}(O=P.indexOf("."))>-1&&(P=P.replace(".","")),(D=P.search(/e/i))>0?(O<0&&(O=D),O+=+P.slice(D+1),P=P.substring(0,D)):O<0&&(O=P.length)}else{if(ze(x,2,N.length,"Base"),x==10&&S)return L=new R(A),V(L,s+L.e+1,a);if(P=String(A),k=typeof A=="number"){if(A*0!=0)return n(L,P,k,x);if(L.s=1/A<0?(P=P.slice(1),-1):1,R.DEBUG&&P.replace(/^0\.0*|\./,"").length>15)throw Error(_T+A)}else L.s=P.charCodeAt(0)===45?(P=P.slice(1),-1):1;for(b=N.slice(0,x),O=D=0,C=P.length;D<C;D++)if(b.indexOf(g=P.charAt(D))<0){if(g=="."){if(D>O){O=C;continue}}else if(!I&&(P==P.toUpperCase()&&(P=P.toLowerCase())||P==P.toLowerCase()&&(P=P.toUpperCase()))){I=!0,D=-1,O=0;continue}return n(L,String(A),k,x)}k=!1,P=r(P,x,10,L.s),(O=P.indexOf("."))>-1?P=P.replace(".",""):O=P.length}for(D=0;P.charCodeAt(D)===48;D++);for(C=P.length;P.charCodeAt(--C)===48;);if(P=P.slice(D,++C)){if(C-=D,k&&R.DEBUG&&C>15&&(A>Ym||A!==pr(A)))throw Error(_T+L.s*A);if((O=O-D-1)>p)L.c=L.e=null;else if(O<u)L.c=[L.e=0];else{if(L.e=O,L.c=[],D=(O+1)%de,O<0&&(D+=de),D<C){for(D&&L.c.push(+P.slice(0,D)),C-=de;D<C;)L.c.push(+P.slice(D,D+=de));D=de-(P=P.slice(D)).length}else D-=C;for(;D--;P+="0");L.c.push(+P)}}else L.c=[L.e=0]}R.clone=IT,R.ROUND_UP=0,R.ROUND_DOWN=1,R.ROUND_CEIL=2,R.ROUND_FLOOR=3,R.ROUND_HALF_UP=4,R.ROUND_HALF_DOWN=5,R.ROUND_HALF_EVEN=6,R.ROUND_HALF_CEIL=7,R.ROUND_HALF_FLOOR=8,R.EUCLID=9,R.config=R.set=function(A){var x,b;if(A!=null)if(typeof A=="object"){if(A.hasOwnProperty(x="DECIMAL_PLACES")&&(b=A[x],ze(b,0,mt,x),s=b),A.hasOwnProperty(x="ROUNDING_MODE")&&(b=A[x],ze(b,0,8,x),a=b),A.hasOwnProperty(x="EXPONENTIAL_AT")&&(b=A[x],b&&b.pop?(ze(b[0],-mt,0,x),ze(b[1],0,mt,x),c=b[0],l=b[1]):(ze(b,-mt,mt,x),c=-(l=b<0?-b:b))),A.hasOwnProperty(x="RANGE"))if(b=A[x],b&&b.pop)ze(b[0],-mt,-1,x),ze(b[1],1,mt,x),u=b[0],p=b[1];else if(ze(b,-mt,mt,x),b)u=-(p=b<0?-b:b);else throw Error(Gt+x+" cannot be zero: "+b);if(A.hasOwnProperty(x="CRYPTO"))if(b=A[x],b===!!b)if(b)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))f=b;else throw f=!b,Error(Gt+"crypto unavailable");else f=b;else throw Error(Gt+x+" not true or false: "+b);if(A.hasOwnProperty(x="MODULO_MODE")&&(b=A[x],ze(b,0,9,x),m=b),A.hasOwnProperty(x="POW_PRECISION")&&(b=A[x],ze(b,0,mt,x),E=b),A.hasOwnProperty(x="FORMAT"))if(b=A[x],typeof b=="object")v=b;else throw Error(Gt+x+" not an object: "+b);if(A.hasOwnProperty(x="ALPHABET"))if(b=A[x],typeof b=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(b))S=b.slice(0,10)=="0123456789",N=b;else throw Error(Gt+x+" invalid: "+b)}else throw Error(Gt+"Object expected: "+A);return{DECIMAL_PLACES:s,ROUNDING_MODE:a,EXPONENTIAL_AT:[c,l],RANGE:[u,p],CRYPTO:f,MODULO_MODE:m,POW_PRECISION:E,FORMAT:v,ALPHABET:N}},R.isBigNumber=function(A){if(!A||A._isBigNumber!==!0)return!1;if(!R.DEBUG)return!0;var x,b,g=A.c,I=A.e,O=A.s;e:if({}.toString.call(g)=="[object Array]"){if((O===1||O===-1)&&I>=-mt&&I<=mt&&I===pr(I)){if(g[0]===0){if(I===0&&g.length===1)return!0;break e}if(x=(I+1)%de,x<1&&(x+=de),String(g[0]).length==x){for(x=0;x<g.length;x++)if(b=g[x],b<0||b>=Pr||b!==pr(b))break e;if(b!==0)return!0}}}else if(g===null&&I===null&&(O===null||O===1||O===-1))return!0;throw Error(Gt+"Invalid BigNumber: "+A)},R.maximum=R.max=function(){return K(arguments,-1)},R.minimum=R.min=function(){return K(arguments,1)},R.random=(function(){var A=9007199254740992,x=Math.random()*A&2097151?function(){return pr(Math.random()*A)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(b){var g,I,O,D,k,C=0,P=[],L=new R(o);if(b==null?b=s:ze(b,0,mt),D=Jm(b/de),f)if(crypto.getRandomValues){for(g=crypto.getRandomValues(new Uint32Array(D*=2));C<D;)k=g[C]*131072+(g[C+1]>>>11),k>=9e15?(I=crypto.getRandomValues(new Uint32Array(2)),g[C]=I[0],g[C+1]=I[1]):(P.push(k%1e14),C+=2);C=D/2}else if(crypto.randomBytes){for(g=crypto.randomBytes(D*=7);C<D;)k=(g[C]&31)*281474976710656+g[C+1]*1099511627776+g[C+2]*4294967296+g[C+3]*16777216+(g[C+4]<<16)+(g[C+5]<<8)+g[C+6],k>=9e15?crypto.randomBytes(7).copy(g,C):(P.push(k%1e14),C+=7);C=D/7}else throw f=!1,Error(Gt+"crypto unavailable");if(!f)for(;C<D;)k=x(),k<9e15&&(P[C++]=k%1e14);for(D=P[--C],b%=de,D&&b&&(k=Xm[de-b],P[C]=pr(D/k)*k);P[C]===0;P.pop(),C--);if(C<0)P=[O=0];else{for(O=-1;P[0]===0;P.splice(0,1),O-=de);for(C=1,k=P[0];k>=10;k/=10,C++);C<de&&(O-=de-C)}return L.e=O,L.c=P,L}})(),R.sum=function(){for(var A=1,x=arguments,b=new R(x[0]);A<x.length;)b=b.plus(x[A++]);return b},r=(function(){var A="0123456789";function x(b,g,I,O){for(var D,k=[0],C,P=0,L=b.length;P<L;){for(C=k.length;C--;k[C]*=g);for(k[0]+=O.indexOf(b.charAt(P++)),D=0;D<k.length;D++)k[D]>I-1&&(k[D+1]==null&&(k[D+1]=0),k[D+1]+=k[D]/I|0,k[D]%=I)}return k.reverse()}return function(b,g,I,O,D){var k,C,P,L,H,z,Y,pe,Oe=b.indexOf("."),Fe=s,me=a;for(Oe>=0&&(L=E,E=0,b=b.replace(".",""),pe=new R(g),z=pe.pow(b.length-Oe),E=L,pe.c=x(Nn(dr(z.c),z.e,"0"),10,I,A),pe.e=pe.c.length),Y=x(b,g,I,D?(k=N,A):(k=A,N)),P=L=Y.length;Y[--L]==0;Y.pop());if(!Y[0])return k.charAt(0);if(Oe<0?--P:(z.c=Y,z.e=P,z.s=O,z=e(z,pe,Fe,me,I),Y=z.c,H=z.r,P=z.e),C=P+Fe+1,Oe=Y[C],L=I/2,H=H||C<0||Y[C+1]!=null,H=me<4?(Oe!=null||H)&&(me==0||me==(z.s<0?3:2)):Oe>L||Oe==L&&(me==4||H||me==6&&Y[C-1]&1||me==(z.s<0?8:7)),C<1||!Y[0])b=H?Nn(k.charAt(1),-Fe,k.charAt(0)):k.charAt(0);else{if(Y.length=C,H)for(--I;++Y[--C]>I;)Y[C]=0,C||(++P,Y=[1].concat(Y));for(L=Y.length;!Y[--L];);for(Oe=0,b="";Oe<=L;b+=k.charAt(Y[Oe++]));b=Nn(b,P,k.charAt(0))}return b}})(),e=(function(){function A(g,I,O){var D,k,C,P,L=0,H=g.length,z=I%pi,Y=I/pi|0;for(g=g.slice();H--;)C=g[H]%pi,P=g[H]/pi|0,D=Y*C+P*z,k=z*C+D%pi*pi+L,L=(k/O|0)+(D/pi|0)+Y*P,g[H]=k%O;return L&&(g=[L].concat(g)),g}function x(g,I,O,D){var k,C;if(O!=D)C=O>D?1:-1;else for(k=C=0;k<O;k++)if(g[k]!=I[k]){C=g[k]>I[k]?1:-1;break}return C}function b(g,I,O,D){for(var k=0;O--;)g[O]-=k,k=g[O]<I[O]?1:0,g[O]=k*D+g[O]-I[O];for(;!g[0]&&g.length>1;g.splice(0,1));}return function(g,I,O,D,k){var C,P,L,H,z,Y,pe,Oe,Fe,me,we,st,Zi,Cn,eo,_t,yi,It=g.s==I.s?1:-1,Qe=g.c,Ke=I.c;if(!Qe||!Qe[0]||!Ke||!Ke[0])return new R(!g.s||!I.s||(Qe?Ke&&Qe[0]==Ke[0]:!Ke)?NaN:Qe&&Qe[0]==0||!Ke?It*0:It/0);for(Oe=new R(It),Fe=Oe.c=[],P=g.e-I.e,It=O+P+1,k||(k=Pr,P=fr(g.e/de)-fr(I.e/de),It=It/de|0),L=0;Ke[L]==(Qe[L]||0);L++);if(Ke[L]>(Qe[L]||0)&&P--,It<0)Fe.push(1),H=!0;else{for(Cn=Qe.length,_t=Ke.length,L=0,It+=2,z=pr(k/(Ke[0]+1)),z>1&&(Ke=A(Ke,z,k),Qe=A(Qe,z,k),_t=Ke.length,Cn=Qe.length),Zi=_t,me=Qe.slice(0,_t),we=me.length;we<_t;me[we++]=0);yi=Ke.slice(),yi=[0].concat(yi),eo=Ke[0],Ke[1]>=k/2&&eo++;do{if(z=0,C=x(Ke,me,_t,we),C<0){if(st=me[0],_t!=we&&(st=st*k+(me[1]||0)),z=pr(st/eo),z>1)for(z>=k&&(z=k-1),Y=A(Ke,z,k),pe=Y.length,we=me.length;x(Y,me,pe,we)==1;)z--,b(Y,_t<pe?yi:Ke,pe,k),pe=Y.length,C=1;else z==0&&(C=z=1),Y=Ke.slice(),pe=Y.length;if(pe<we&&(Y=[0].concat(Y)),b(me,Y,we,k),we=me.length,C==-1)for(;x(Ke,me,_t,we)<1;)z++,b(me,_t<we?yi:Ke,we,k),we=me.length}else C===0&&(z++,me=[0]);Fe[L++]=z,me[0]?me[we++]=Qe[Zi]||0:(me=[Qe[Zi]],we=1)}while((Zi++<Cn||me[0]!=null)&&It--);H=me[0]!=null,Fe[0]||Fe.splice(0,1)}if(k==Pr){for(L=1,It=Fe[0];It>=10;It/=10,L++);V(Oe,O+(Oe.e=L+P*de-1)+1,D,H)}else Oe.e=P,Oe.r=+H;return Oe}})();function M(A,x,b,g){var I,O,D,k,C;if(b==null?b=a:ze(b,0,8),!A.c)return A.toString();if(I=A.c[0],D=A.e,x==null)C=dr(A.c),C=g==1||g==2&&(D<=c||D>=l)?yd(C,D):Nn(C,D,"0");else if(A=V(new R(A),x,b),O=A.e,C=dr(A.c),k=C.length,g==1||g==2&&(x<=O||O<=c)){for(;k<x;C+="0",k++);C=yd(C,O)}else if(x-=D+(g===2&&O>D),C=Nn(C,O,"0"),O+1>k){if(--x>0)for(C+=".";x--;C+="0");}else if(x+=O-k,x>0)for(O+1==k&&(C+=".");x--;C+="0");return A.s<0&&I?"-"+C:C}function K(A,x){for(var b,g,I=1,O=new R(A[0]);I<A.length;I++)g=new R(A[I]),(!g.s||(b=Yi(O,g))===x||b===0&&O.s===x)&&(O=g);return O}function B(A,x,b){for(var g=1,I=x.length;!x[--I];x.pop());for(I=x[0];I>=10;I/=10,g++);return(b=g+b*de-1)>p?A.c=A.e=null:b<u?A.c=[A.e=0]:(A.e=b,A.c=x),A}n=(function(){var A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,x=/^([^.]+)\.$/,b=/^\.([^.]+)$/,g=/^-?(Infinity|NaN)$/,I=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(O,D,k,C){var P,L=k?D:D.replace(I,"");if(g.test(L))O.s=isNaN(L)?null:L<0?-1:1;else{if(!k&&(L=L.replace(A,function(H,z,Y){return P=(Y=Y.toLowerCase())=="x"?16:Y=="b"?2:8,!C||C==P?z:H}),C&&(P=C,L=L.replace(x,"$1").replace(b,"0.$1")),D!=L))return new R(L,P);if(R.DEBUG)throw Error(Gt+"Not a"+(C?" base "+C:"")+" number: "+D);O.s=null}O.c=O.e=null}})();function V(A,x,b,g){var I,O,D,k,C,P,L,H=A.c,z=Xm;if(H){e:{for(I=1,k=H[0];k>=10;k/=10,I++);if(O=x-I,O<0)O+=de,D=x,C=H[P=0],L=pr(C/z[I-D-1]%10);else if(P=Jm((O+1)/de),P>=H.length)if(g){for(;H.length<=P;H.push(0));C=L=0,I=1,O%=de,D=O-de+1}else break e;else{for(C=k=H[P],I=1;k>=10;k/=10,I++);O%=de,D=O-de+I,L=D<0?0:pr(C/z[I-D-1]%10)}if(g=g||x<0||H[P+1]!=null||(D<0?C:C%z[I-D-1]),g=b<4?(L||g)&&(b==0||b==(A.s<0?3:2)):L>5||L==5&&(b==4||g||b==6&&(O>0?D>0?C/z[I-D]:0:H[P-1])%10&1||b==(A.s<0?8:7)),x<1||!H[0])return H.length=0,g?(x-=A.e+1,H[0]=z[(de-x%de)%de],A.e=-x||0):H[0]=A.e=0,A;if(O==0?(H.length=P,k=1,P--):(H.length=P+1,k=z[de-O],H[P]=D>0?pr(C/z[I-D]%z[D])*k:0),g)for(;;)if(P==0){for(O=1,D=H[0];D>=10;D/=10,O++);for(D=H[0]+=k,k=1;D>=10;D/=10,k++);O!=k&&(A.e++,H[0]==Pr&&(H[0]=1));break}else{if(H[P]+=k,H[P]!=Pr)break;H[P--]=0,k=1}for(O=H.length;H[--O]===0;H.pop());}A.e>p?A.c=A.e=null:A.e<u&&(A.c=[A.e=0])}return A}function $(A){var x,b=A.e;return b===null?A.toString():(x=dr(A.c),x=b<=c||b>=l?yd(x,b):Nn(x,b,"0"),A.s<0?"-"+x:x)}return i.absoluteValue=i.abs=function(){var A=new R(this);return A.s<0&&(A.s=1),A},i.comparedTo=function(A,x){return Yi(this,new R(A,x))},i.decimalPlaces=i.dp=function(A,x){var b,g,I,O=this;if(A!=null)return ze(A,0,mt),x==null?x=a:ze(x,0,8),V(new R(O),A+O.e+1,x);if(!(b=O.c))return null;if(g=((I=b.length-1)-fr(this.e/de))*de,I=b[I])for(;I%10==0;I/=10,g--);return g<0&&(g=0),g},i.dividedBy=i.div=function(A,x){return e(this,new R(A,x),s,a)},i.dividedToIntegerBy=i.idiv=function(A,x){return e(this,new R(A,x),0,1)},i.exponentiatedBy=i.pow=function(A,x){var b,g,I,O,D,k,C,P,L,H=this;if(A=new R(A),A.c&&!A.isInteger())throw Error(Gt+"Exponent not an integer: "+$(A));if(x!=null&&(x=new R(x)),k=A.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!A.c||!A.c[0])return L=new R(Math.pow(+$(H),k?A.s*(2-Ed(A)):+$(A))),x?L.mod(x):L;if(C=A.s<0,x){if(x.c?!x.c[0]:!x.s)return new R(NaN);g=!C&&H.isInteger()&&x.isInteger(),g&&(H=H.mod(x))}else{if(A.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||k&&H.c[1]>=24e7:H.c[0]<8e13||k&&H.c[0]<=9999975e7)))return O=H.s<0&&Ed(A)?-0:0,H.e>-1&&(O=1/O),new R(C?1/O:O);E&&(O=Jm(E/de+2))}for(k?(b=new R(.5),C&&(A.s=1),P=Ed(A)):(I=Math.abs(+$(A)),P=I%2),L=new R(o);;){if(P){if(L=L.times(H),!L.c)break;O?L.c.length>O&&(L.c.length=O):g&&(L=L.mod(x))}if(I){if(I=pr(I/2),I===0)break;P=I%2}else if(A=A.times(b),V(A,A.e+1,1),A.e>14)P=Ed(A);else{if(I=+$(A),I===0)break;P=I%2}H=H.times(H),O?H.c&&H.c.length>O&&(H.c.length=O):g&&(H=H.mod(x))}return g?L:(C&&(L=o.div(L)),x?L.mod(x):O?V(L,E,a,D):L)},i.integerValue=function(A){var x=new R(this);return A==null?A=a:ze(A,0,8),V(x,x.e+1,A)},i.isEqualTo=i.eq=function(A,x){return Yi(this,new R(A,x))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(A,x){return Yi(this,new R(A,x))>0},i.isGreaterThanOrEqualTo=i.gte=function(A,x){return(x=Yi(this,new R(A,x)))===1||x===0},i.isInteger=function(){return!!this.c&&fr(this.e/de)>this.c.length-2},i.isLessThan=i.lt=function(A,x){return Yi(this,new R(A,x))<0},i.isLessThanOrEqualTo=i.lte=function(A,x){return(x=Yi(this,new R(A,x)))===-1||x===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(A,x){var b,g,I,O,D=this,k=D.s;if(A=new R(A,x),x=A.s,!k||!x)return new R(NaN);if(k!=x)return A.s=-x,D.plus(A);var C=D.e/de,P=A.e/de,L=D.c,H=A.c;if(!C||!P){if(!L||!H)return L?(A.s=-x,A):new R(H?D:NaN);if(!L[0]||!H[0])return H[0]?(A.s=-x,A):new R(L[0]?D:a==3?-0:0)}if(C=fr(C),P=fr(P),L=L.slice(),k=C-P){for((O=k<0)?(k=-k,I=L):(P=C,I=H),I.reverse(),x=k;x--;I.push(0));I.reverse()}else for(g=(O=(k=L.length)<(x=H.length))?k:x,k=x=0;x<g;x++)if(L[x]!=H[x]){O=L[x]<H[x];break}if(O&&(I=L,L=H,H=I,A.s=-A.s),x=(g=H.length)-(b=L.length),x>0)for(;x--;L[b++]=0);for(x=Pr-1;g>k;){if(L[--g]<H[g]){for(b=g;b&&!L[--b];L[b]=x);--L[b],L[g]+=Pr}L[g]-=H[g]}for(;L[0]==0;L.splice(0,1),--P);return L[0]?B(A,L,P):(A.s=a==3?-1:1,A.c=[A.e=0],A)},i.modulo=i.mod=function(A,x){var b,g,I=this;return A=new R(A,x),!I.c||!A.s||A.c&&!A.c[0]?new R(NaN):!A.c||I.c&&!I.c[0]?new R(I):(m==9?(g=A.s,A.s=1,b=e(I,A,0,3),A.s=g,b.s*=g):b=e(I,A,0,m),A=I.minus(b.times(A)),!A.c[0]&&m==1&&(A.s=I.s),A)},i.multipliedBy=i.times=function(A,x){var b,g,I,O,D,k,C,P,L,H,z,Y,pe,Oe,Fe,me=this,we=me.c,st=(A=new R(A,x)).c;if(!we||!st||!we[0]||!st[0])return!me.s||!A.s||we&&!we[0]&&!st||st&&!st[0]&&!we?A.c=A.e=A.s=null:(A.s*=me.s,!we||!st?A.c=A.e=null:(A.c=[0],A.e=0)),A;for(g=fr(me.e/de)+fr(A.e/de),A.s*=me.s,C=we.length,H=st.length,C<H&&(pe=we,we=st,st=pe,I=C,C=H,H=I),I=C+H,pe=[];I--;pe.push(0));for(Oe=Pr,Fe=pi,I=H;--I>=0;){for(b=0,z=st[I]%Fe,Y=st[I]/Fe|0,D=C,O=I+D;O>I;)P=we[--D]%Fe,L=we[D]/Fe|0,k=Y*P+L*z,P=z*P+k%Fe*Fe+pe[O]+b,b=(P/Oe|0)+(k/Fe|0)+Y*L,pe[O--]=P%Oe;pe[O]=b}return b?++g:pe.splice(0,1),B(A,pe,g)},i.negated=function(){var A=new R(this);return A.s=-A.s||null,A},i.plus=function(A,x){var b,g=this,I=g.s;if(A=new R(A,x),x=A.s,!I||!x)return new R(NaN);if(I!=x)return A.s=-x,g.minus(A);var O=g.e/de,D=A.e/de,k=g.c,C=A.c;if(!O||!D){if(!k||!C)return new R(I/0);if(!k[0]||!C[0])return C[0]?A:new R(k[0]?g:I*0)}if(O=fr(O),D=fr(D),k=k.slice(),I=O-D){for(I>0?(D=O,b=C):(I=-I,b=k),b.reverse();I--;b.push(0));b.reverse()}for(I=k.length,x=C.length,I-x<0&&(b=C,C=k,k=b,x=I),I=0;x;)I=(k[--x]=k[x]+C[x]+I)/Pr|0,k[x]=Pr===k[x]?0:k[x]%Pr;return I&&(k=[I].concat(k),++D),B(A,k,D)},i.precision=i.sd=function(A,x){var b,g,I,O=this;if(A!=null&&A!==!!A)return ze(A,1,mt),x==null?x=a:ze(x,0,8),V(new R(O),A,x);if(!(b=O.c))return null;if(I=b.length-1,g=I*de+1,I=b[I]){for(;I%10==0;I/=10,g--);for(I=b[0];I>=10;I/=10,g++);}return A&&O.e+1>g&&(g=O.e+1),g},i.shiftedBy=function(A){return ze(A,-Ym,Ym),this.times("1e"+A)},i.squareRoot=i.sqrt=function(){var A,x,b,g,I,O=this,D=O.c,k=O.s,C=O.e,P=s+4,L=new R("0.5");if(k!==1||!D||!D[0])return new R(!k||k<0&&(!D||D[0])?NaN:D?O:1/0);if(k=Math.sqrt(+$(O)),k==0||k==1/0?(x=dr(D),(x.length+C)%2==0&&(x+="0"),k=Math.sqrt(+x),C=fr((C+1)/2)-(C<0||C%2),k==1/0?x="5e"+C:(x=k.toExponential(),x=x.slice(0,x.indexOf("e")+1)+C),b=new R(x)):b=new R(k+""),b.c[0]){for(C=b.e,k=C+P,k<3&&(k=0);;)if(I=b,b=L.times(I.plus(e(O,I,P,1))),dr(I.c).slice(0,k)===(x=dr(b.c)).slice(0,k))if(b.e<C&&--k,x=x.slice(k-3,k+1),x=="9999"||!g&&x=="4999"){if(!g&&(V(I,I.e+s+2,0),I.times(I).eq(O))){b=I;break}P+=4,k+=4,g=1}else{(!+x||!+x.slice(1)&&x.charAt(0)=="5")&&(V(b,b.e+s+2,1),A=!b.times(b).eq(O));break}}return V(b,b.e+s+1,a,A)},i.toExponential=function(A,x){return A!=null&&(ze(A,0,mt),A++),M(this,A,x,1)},i.toFixed=function(A,x){return A!=null&&(ze(A,0,mt),A=A+this.e+1),M(this,A,x)},i.toFormat=function(A,x,b){var g,I=this;if(b==null)A!=null&&x&&typeof x=="object"?(b=x,x=null):A&&typeof A=="object"?(b=A,A=x=null):b=v;else if(typeof b!="object")throw Error(Gt+"Argument not an object: "+b);if(g=I.toFixed(A,x),I.c){var O,D=g.split("."),k=+b.groupSize,C=+b.secondaryGroupSize,P=b.groupSeparator||"",L=D[0],H=D[1],z=I.s<0,Y=z?L.slice(1):L,pe=Y.length;if(C&&(O=k,k=C,C=O,pe-=O),k>0&&pe>0){for(O=pe%k||k,L=Y.substr(0,O);O<pe;O+=k)L+=P+Y.substr(O,k);C>0&&(L+=P+Y.slice(O)),z&&(L="-"+L)}g=H?L+(b.decimalSeparator||"")+((C=+b.fractionGroupSize)?H.replace(new RegExp("\\d{"+C+"}\\B","g"),"$&"+(b.fractionGroupSeparator||"")):H):L}return(b.prefix||"")+g+(b.suffix||"")},i.toFraction=function(A){var x,b,g,I,O,D,k,C,P,L,H,z,Y=this,pe=Y.c;if(A!=null&&(k=new R(A),!k.isInteger()&&(k.c||k.s!==1)||k.lt(o)))throw Error(Gt+"Argument "+(k.isInteger()?"out of range: ":"not an integer: ")+$(k));if(!pe)return new R(Y);for(x=new R(o),P=b=new R(o),g=C=new R(o),z=dr(pe),O=x.e=z.length-Y.e-1,x.c[0]=Xm[(D=O%de)<0?de+D:D],A=!A||k.comparedTo(x)>0?O>0?x:P:k,D=p,p=1/0,k=new R(z),C.c[0]=0;L=e(k,x,0,1),I=b.plus(L.times(g)),I.comparedTo(A)!=1;)b=g,g=I,P=C.plus(L.times(I=P)),C=I,x=k.minus(L.times(I=x)),k=I;return I=e(A.minus(b),g,0,1),C=C.plus(I.times(P)),b=b.plus(I.times(g)),C.s=P.s=Y.s,O=O*2,H=e(P,g,O,a).minus(Y).abs().comparedTo(e(C,b,O,a).minus(Y).abs())<1?[P,g]:[C,b],p=D,H},i.toNumber=function(){return+$(this)},i.toPrecision=function(A,x){return A!=null&&ze(A,1,mt),M(this,A,x,2)},i.toString=function(A){var x,b=this,g=b.s,I=b.e;return I===null?g?(x="Infinity",g<0&&(x="-"+x)):x="NaN":(A==null?x=I<=c||I>=l?yd(dr(b.c),I):Nn(dr(b.c),I,"0"):A===10&&S?(b=V(new R(b),s+I+1,a),x=Nn(dr(b.c),b.e,"0")):(ze(A,2,N.length,"Base"),x=r(Nn(dr(b.c),I,"0"),10,A,g,!0)),g<0&&b.c[0]&&(x="-"+x)),x},i.valueOf=i.toJSON=function(){return $(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&R.set(t),R}function fr(t){var e=t|0;return t>0||t===e?e:e-1}function dr(t){for(var e,r,n=1,i=t.length,o=t[0]+"";n<i;){for(e=t[n++]+"",r=de-e.length;r--;e="0"+e);o+=e}for(i=o.length;o.charCodeAt(--i)===48;);return o.slice(0,i+1||1)}function Yi(t,e){var r,n,i=t.c,o=e.c,s=t.s,a=e.s,c=t.e,l=e.e;if(!s||!a)return null;if(r=i&&!i[0],n=o&&!o[0],r||n)return r?n?0:-a:s;if(s!=a)return s;if(r=s<0,n=c==l,!i||!o)return n?0:!i^r?1:-1;if(!n)return c>l^r?1:-1;for(a=(c=i.length)<(l=o.length)?c:l,s=0;s<a;s++)if(i[s]!=o[s])return i[s]>o[s]^r?1:-1;return c==l?0:c>l^r?1:-1}function ze(t,e,r,n){if(t<e||t>r||t!==pr(t))throw Error(Gt+(n||"Argument")+(typeof t=="number"?t<e||t>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Ed(t){var e=t.c.length-1;return fr(t.e/de)==e&&t.c[e]%2!=0}function yd(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Nn(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e<n&&(t=t.slice(0,e)+"."+t.slice(e));return t}var H0=IT(),xT=H0;var F0=24,cc=32,V0=()=>typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function"?()=>{let t=new Uint32Array(1);return globalThis.crypto.getRandomValues(t),t[0]/4294967296}:Math.random,Zm=V0(),Qm=(t=4,e=Zm)=>{let r="";for(;r.length<t;)r=r+Math.floor(e()*36).toString(36);return r};function B0(t){let e=new xT(0);for(let r of t.values())e=e.multipliedBy(256).plus(r);return e}var ST=(t="")=>{let e=new TextEncoder;return B0(TT(e.encode(t))).toString(36).slice(1)},bT=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),j0=t=>bT[Math.floor(t()*bT.length)],G0=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Zm}={})=>{let r=Object.keys(t).toString(),n=r.length?r+Qm(cc,e):Qm(cc,e);return ST(n).substring(0,cc)},$0=t=>()=>t++,q0=476782367,wT=({random:t=Zm,counter:e=$0(Math.floor(t()*q0)),length:r=F0,fingerprint:n=G0({random:t})}={})=>{if(r>cc)throw new Error(`Length must be between 2 and ${cc}. Received: ${r}`);return function(){let o=j0(t),s=Date.now().toString(36),a=e().toString(36),c=Qm(r,t),l=`${s+c+a+n}`;return`${o+ST(l).substring(1,r)}`}},ht=W0(wT);function W0(t){let e;return()=>(e||(e=t()),e())}function Is(t){if(typeof t=="object"&&t!==null&&"name"in t){let{name:e}=t;return typeof e=="string"?e:void 0}}function Ce(t){return Is(t)==="ConditionalCheckFailedException"}function z0(t){let e=Is(t),r=t instanceof Error?t.message:typeof t=="string"?t:void 0;return[e,r].filter(Boolean).join(": ")||String(t)}function NT(t,e){console.error(`[repo-plugin-dynamodb] ${t} failed \u2014 ${z0(e)}`)}function G(t,e){return NT(t,e),te.DatabaseQueryError({query:t})}function Rt(t,e){return NT(t,e),te.UnknownError({message:t})}var lc=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return ht()}async get(e){try{let r=await this.docClient.send(new Y0({TableName:this.tableName,Key:{[h.PK]:U.CHALLENGE_PK(e),[h.SK]:U.CHALLENGE_SK()}}));if(!r.Item)return T(null);let n=this.unmarshall(r.Item);return $m(re(n.expiresAt))?T(null):T(n)}catch(r){return d(G("get challenge",r))}}async create(e){try{let r=ae(),n=e.id||this.generateChallengeId(),i={...e,id:n,createdAt:J(r)},o=re(e.expiresAt),s=Math.floor((o+this.ttlGracePeriod)/1e3);return await this.docClient.send(new X0({TableName:this.tableName,Item:this.marshall(i,s)})),T(i)}catch(r){return d(G("create challenge",r))}}async update(e,r){try{let n=[],i={},o={};return r.method!==void 0&&(n.push("#method = :method"),i["#method"]=h.METHOD,o[":method"]=r.method),r.phase!==void 0&&(n.push("#phase = :phase"),i["#phase"]=h.PHASE,o[":phase"]=r.phase),r.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),i["#codeHash"]=h.CODE_HASH,o[":codeHash"]=r.codeHash),r.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),i["#challengeStatus"]=h.CHALLENGE_STATUS,o[":challengeStatus"]=r.status),n.length===0?T(void 0):(await this.docClient.send(new RT({TableName:this.tableName,Key:{[h.PK]:U.CHALLENGE_PK(e),[h.SK]:U.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:o})),T(void 0))}catch(n){return d(G("update challenge",n))}}async incrementAttempts(e,r){let n={":zero":0,":inc":1},i;r!==void 0&&(i="attribute_not_exists(#attempts) OR #attempts < :max",n[":max"]=r);try{let s=(await this.docClient.send(new RT({TableName:this.tableName,Key:{[h.PK]:U.CHALLENGE_PK(e),[h.SK]:U.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...i?{ConditionExpression:i}:{},ExpressionAttributeNames:{"#attempts":h.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[h.ATTEMPTS]??0;return T(s)}catch(o){return Ce(o)?d(te.AttemptsExceeded()):d(G("increment challenge attempts",o))}}async remove(e){try{return await this.docClient.send(new J0({TableName:this.tableName,Key:{[h.PK]:U.CHALLENGE_PK(e),[h.SK]:U.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":h.PK}})),T(void 0)}catch(r){return Ce(r)?T(void 0):d(G("remove challenge",r))}}marshall(e,r){let n={[h.PK]:U.CHALLENGE_PK(e.id),[h.SK]:U.CHALLENGE_SK(),[h.USER_ID]:e.userId,[h.PURPOSE]:e.purpose,[h.CHALLENGE_STATUS]:e.status,[h.EXPIRES_AT]:re(e.expiresAt),[h.CREATED_AT]:re(e.createdAt),[h.TTL]:r};return e.tenantId&&(n[h.TENANT_ID]=e.tenantId),e.phase&&(n[h.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[h.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[h.METHOD]=e.method),e.codeHash&&(n[h.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[h.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[h.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[h.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[h.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[h.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[h.COUNTRY]=e.country),e.city&&(n[h.CITY]=e.city),e.metadata&&(n[h.METADATA]=e.metadata),e.flowKey&&(n[h.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:le.challengeIdFromPK(e[h.PK]),userId:e[h.USER_ID],purpose:e[h.PURPOSE],status:e[h.CHALLENGE_STATUS],expiresAt:J(e[h.EXPIRES_AT]),createdAt:J(e[h.CREATED_AT])};return e[h.TENANT_ID]&&(n.tenantId=e[h.TENANT_ID]),e[h.PHASE]&&(n.phase=e[h.PHASE]),e[h.ALLOWED_METHODS]&&(n.allowedMethods=e[h.ALLOWED_METHODS]),e[h.METHOD]&&(n.method=e[h.METHOD]),e[h.CODE_HASH]&&(n.codeHash=e[h.CODE_HASH]),e[h.ATTEMPTS]!==void 0&&(n.attempts=e[h.ATTEMPTS]),e[h.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[h.MAX_ATTEMPTS]),e[h.IDENTITY_TYPE]&&(n.identityType=e[h.IDENTITY_TYPE]),e[h.IDENTITY_VALUE]&&(n.identityValue=e[h.IDENTITY_VALUE]),e[h.DEVICE_LABEL]&&(n.deviceLabel=e[h.DEVICE_LABEL]),e[h.COUNTRY]&&(n.country=e[h.COUNTRY]),e[h.CITY]&&(n.city=e[h.CITY]),e[h.METADATA]&&(n.metadata=e[h.METADATA]),e[h.FLOW_KEY]&&(n.flowKey=e[h.FLOW_KEY]),n}};import{BatchGetCommand as Q0,DeleteCommand as Z0,GetCommand as eO,PutCommand as tO,QueryCommand as gd,UpdateCommand as rO}from"@aws-sdk/lib-dynamodb";var uc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return ht()}async get(e){try{let r=await this.docClient.send(new eO({TableName:this.tableName,Key:{[h.PK]:U.CREDENTIAL_PK(e),[h.SK]:U.CREDENTIAL_SK()}}));return r.Item?T(this.unmarshall(r.Item)):T(null)}catch(r){return d(G("get credential",r))}}async getByUserIdAndType(e,r){try{let n=await this.docClient.send(new gd({TableName:this.tableName,IndexName:ue.USER_CREDENTIALS,KeyConditionExpression:`${h.CREDENTIAL_USER_PK} = :userPk AND begins_with(${h.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":U.USER_PK(e),":typePrefix":U.CREDENTIAL_TYPE_PREFIX(r)},Limit:1}));if(!n.Items||n.Items.length===0)return T(null);let i=n.Items[0];if(!i)return T(null);let o=le.credentialId(i[h.PK]);return this.get(o)}catch(n){return d(G("get credential by user and type",n))}}async getByUserId(e){try{let r=await this.docClient.send(new gd({TableName:this.tableName,IndexName:ue.USER_CREDENTIALS,KeyConditionExpression:`${h.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":U.USER_PK(e)}}));if(!r.Items||r.Items.length===0)return T([]);let n=r.Items.map(s=>le.credentialId(s[h.PK])),i=await this.batchGet(n);if(i.ok===!1)return d(i.errors,i.meta);if(!i.data)return T([]);let o=i.data.filter(s=>s!==null);return T(o)}catch(r){return d(G("get credentials by user",r))}}async create(e){try{let r=ae(),n=this.generateCredentialId(),i={revokedAt:null,lastUsedAt:null,...e,id:n,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new tO({TableName:this.tableName,Item:this.marshall(i),ConditionExpression:`attribute_not_exists(${h.PK})`})),T(i)}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"credential"})):d(G("create credential",r))}}async update(e,r){try{let n=ae(),i=[],o={},s={};return i.push(`#${h.UPDATED_AT} = :updatedAt`),o[`#${h.UPDATED_AT}`]=h.UPDATED_AT,s[":updatedAt"]=n,r.value!==void 0&&(i.push(`#${h.CREDENTIAL_VALUE} = :value`),o[`#${h.CREDENTIAL_VALUE}`]=h.CREDENTIAL_VALUE,s[":value"]=r.value),r.data!==void 0&&(i.push(`#${h.METADATA} = :data`),o[`#${h.METADATA}`]=h.METADATA,s[":data"]=r.data),r.revokedAt!==void 0&&(i.push(`#${h.REVOKED_AT} = :revokedAt`),o[`#${h.REVOKED_AT}`]=h.REVOKED_AT,s[":revokedAt"]=r.revokedAt?re(r.revokedAt):null),r.lastUsedAt!==void 0&&(i.push(`#${h.LAST_USED_AT} = :lastUsedAt`),o[`#${h.LAST_USED_AT}`]=h.LAST_USED_AT,s[":lastUsedAt"]=r.lastUsedAt?re(r.lastUsedAt):null),await this.docClient.send(new rO({TableName:this.tableName,Key:{[h.PK]:U.CREDENTIAL_PK(e),[h.SK]:U.CREDENTIAL_SK()},UpdateExpression:`SET ${i.join(", ")}`,ExpressionAttributeNames:o,ExpressionAttributeValues:s,ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"credential",id:e})):d(G("update credential",n))}}async remove(e){try{return await this.docClient.send(new Z0({TableName:this.tableName,Key:{[h.PK]:U.CREDENTIAL_PK(e),[h.SK]:U.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(r){return Ce(r)?d(te.NotFound({entity:"credential",id:e})):d(G("delete credential",r))}}async hasType(e,r){try{let n=await this.docClient.send(new gd({TableName:this.tableName,IndexName:ue.USER_CREDENTIALS,KeyConditionExpression:`${h.CREDENTIAL_USER_PK} = :userPk AND begins_with(${h.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":U.USER_PK(e),":typePrefix":U.CREDENTIAL_TYPE_PREFIX(r)},Select:"COUNT",Limit:1}));return T((n.Count||0)>0)}catch(n){return d(G("check credential type",n))}}async countByUserId(e){try{let r=await this.docClient.send(new gd({TableName:this.tableName,IndexName:ue.USER_CREDENTIALS,KeyConditionExpression:`${h.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":U.USER_PK(e)},Select:"COUNT"}));return T(r.Count||0)}catch(r){return d(G("count credentials",r))}}async batchGet(e){if(e.length===0)return T([]);try{let r=[];for(let i=0;i<e.length;i+=100)r.push(e.slice(i,i+100));let n=[];for(let i of r){let s=(await this.docClient.send(new Q0({RequestItems:{[this.tableName]:{Keys:i.map(c=>({[h.PK]:U.CREDENTIAL_PK(c),[h.SK]:U.CREDENTIAL_SK()}))}}}))).Responses?.[this.tableName]||[],a=new Map;for(let c of s){let l=this.unmarshall(c);a.set(l.id,l)}for(let c of i)n.push(a.get(c)||null)}return T(n)}catch(r){return d(G("batch get credentials",r))}}marshall(e){let r={[h.PK]:U.CREDENTIAL_PK(e.id),[h.SK]:U.CREDENTIAL_SK(),[h.CREDENTIAL_USER_PK]:U.USER_PK(e.userId),[h.CREDENTIAL_USER_SK]:U.CREDENTIAL_USER_SK(e.type,e.id),[h.USER_ID]:e.userId,[h.CREDENTIAL_VALUE]:e.value,[h.METADATA]:e.data,[h.REVOKED_AT]:e.revokedAt?re(e.revokedAt):null,[h.CREATED_AT]:re(e.createdAt),[h.UPDATED_AT]:re(e.updatedAt)};return e.lastUsedAt&&(r[h.LAST_USED_AT]=re(e.lastUsedAt)),r}unmarshall(e){let r=le.credentialId(e[h.PK]),n=le.credentialTypeFromUserSK(e[h.CREDENTIAL_USER_SK]);return{id:r,userId:e[h.USER_ID],type:n,value:e[h.CREDENTIAL_VALUE],data:e[h.METADATA]||{},revokedAt:Kt(e[h.REVOKED_AT]),createdAt:J(e[h.CREATED_AT]),updatedAt:J(e[h.UPDATED_AT]),lastUsedAt:Kt(e[h.LAST_USED_AT])}}};import{BatchGetCommand as nO,DeleteCommand as iO,GetCommand as oO,PutCommand as sO,QueryCommand as aO,UpdateCommand as eh}from"@aws-sdk/lib-dynamodb";function th(t){return{failedAttempts:t.failedAttempts,lastFailedAt:Cr(t.lastFailedAt),lockedUntil:Cr(t.lockedUntil)}}function OT(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]={failedAttempts:n.failedAttempts??0,lastFailedAt:Kt(n.lastFailedAt),lockedUntil:Kt(n.lockedUntil)};return e}function kT(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))n&&(e[r]=th(n));return e}var dc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e,r){try{let n=await this.docClient.send(new oO({TableName:this.tableName,Key:{[h.PK]:U.IDENTITY_PK(e,r),[h.SK]:U.IDENTITY_SK()}}));if(!n.Item)return T(null);let i=this.unmarshall(n.Item);return T(i)}catch(n){return d(G("get identity",n))}}async getByUserId(e){try{let r=await this.docClient.send(new aO({TableName:this.tableName,IndexName:ue.USER_IDENTITIES,KeyConditionExpression:`${h.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":U.USER_INDEX_PK(e)}})),n=[];for(let i of r.Items||[]){let o=this.unmarshall(i);o!==null&&n.push(o)}return T(n)}catch(r){return d(G("get identities by userId",r))}}async create(e){try{let r=ae(),n={...e,createdAt:J(r),updatedAt:J(r)};return await this.docClient.send(new sO({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),T(n)}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"identity"})):d(G("create identity",r))}}async update(e,r,n){try{let i=[],o=[],s={},a={};if(n.loginEnabled!==void 0&&(i.push("#loginEnabled = :loginEnabled"),s["#loginEnabled"]=h.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let l=Cr(n.verifiedAt);l===null?(o.push("#verifiedAt"),s["#verifiedAt"]=h.VERIFIED_AT):(i.push("#verifiedAt = :verifiedAt"),s["#verifiedAt"]=h.VERIFIED_AT,a[":verifiedAt"]=l)}n.guards!==void 0&&(i.push("#guards = :guards"),s["#guards"]=h.GUARDS,a[":guards"]=kT(n.guards)),n.pendingVerification!==void 0&&(s["#pendingVerification"]=h.PENDING_VERIFICATION,n.pendingVerification===null?o.push("#pendingVerification"):(i.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Ht({...n.pendingVerification,expiresAt:re(n.pendingVerification.expiresAt),resendAvailableAt:Cr(n.pendingVerification.resendAvailableAt)}))),i.push("#updatedAt = :updatedAt"),s["#updatedAt"]=h.UPDATED_AT,a[":updatedAt"]=ae();let c=[];return i.length>0&&c.push(`SET ${i.join(", ")}`),o.length>0&&c.push(`REMOVE ${o.join(", ")}`),await this.docClient.send(new eh({TableName:this.tableName,Key:{[h.PK]:U.IDENTITY_PK(e,r),[h.SK]:U.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:s,ExpressionAttributeValues:a})),T(void 0)}catch(i){return d(G("update identity",i))}}async remove(e,r){try{return await this.docClient.send(new iO({TableName:this.tableName,Key:{[h.PK]:U.IDENTITY_PK(e,r),[h.SK]:U.IDENTITY_SK()}})),T(void 0)}catch(n){return d(G("remove identity",n))}}async updateGuard(e,r,n,i){let o={[h.PK]:U.IDENTITY_PK(e,r),[h.SK]:U.IDENTITY_SK()};try{return await this.docClient.send(new eh({TableName:this.tableName,Key:o,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":h.GUARDS,"#guardKey":n,"#updatedAt":h.UPDATED_AT},ExpressionAttributeValues:{":guard":th(i),":updatedAt":ae()}})),T(void 0)}catch(s){if(Ce(s))try{return await this.docClient.send(new eh({TableName:this.tableName,Key:o,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":h.GUARDS,"#updatedAt":h.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:th(i)},":updatedAt":ae()}})),T(void 0)}catch(a){return d(G("update guard",a))}return d(G("update guard",s))}}async batchGet(e){try{if(e.length===0)return T([]);let n=(await this.docClient.send(new nO({RequestItems:{[this.tableName]:{Keys:e.map(({type:s,value:a})=>({[h.PK]:U.IDENTITY_PK(s,a),[h.SK]:U.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],i=new Map;for(let s of n){let a=this.unmarshall(s);if(a!==null){let c=`${a.type}#${a.value}`;i.set(c,a)}}let o=e.map(({type:s,value:a})=>{let c=`${s}#${a}`;return i.get(c)||null});return T(o)}catch(r){return d(G("batch get identities",r))}}marshall(e){let r={[h.PK]:U.IDENTITY_PK(e.type,e.value),[h.SK]:U.IDENTITY_SK(),[h.IDENTITY_USER_PK]:U.USER_INDEX_PK(e.userId),[h.IDENTITY_USER_SK]:U.USER_INDEX_SK(e.type,e.value),[h.USER_ID]:e.userId,[h.LOGIN_ENABLED]:e.loginEnabled,[h.CREATED_AT]:re(e.createdAt),[h.UPDATED_AT]:re(e.updatedAt)},n=Cr(e.verifiedAt);return n!==null&&(r[h.VERIFIED_AT]=n),r[h.GUARDS]=kT(e.guards),e.pendingVerification&&(r[h.PENDING_VERIFICATION]=Ht({...e.pendingVerification,expiresAt:re(e.pendingVerification.expiresAt),resendAvailableAt:Cr(e.pendingVerification.resendAvailableAt)})),r}unmarshall(e){let r=le.identityPKInfo(e[h.PK]);if(!r){let n=e[h.IDENTITY_USER_SK]?le.userIndexSKInfo(e[h.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[h.USER_ID],loginEnabled:e[h.LOGIN_ENABLED],verifiedAt:Kt(e[h.VERIFIED_AT]),guards:OT(e[h.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[h.PENDING_VERIFICATION]),createdAt:J(e[h.CREATED_AT]),updatedAt:J(e[h.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[h.PK],GSI1SK:e[h.IDENTITY_USER_SK]}),null)}return{type:r.type,value:r.value,userId:e[h.USER_ID],loginEnabled:e[h.LOGIN_ENABLED],verifiedAt:Kt(e[h.VERIFIED_AT]),guards:OT(e[h.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[h.PENDING_VERIFICATION]),createdAt:J(e[h.CREATED_AT]),updatedAt:J(e[h.UPDATED_AT])}}unmarshallPendingVerification(e){if(!e||typeof e!="object")return null;let r=e;return{challengeId:r.challengeId,purpose:r.purpose,channel:r.channel,expiresAt:J(r.expiresAt),resendAvailableAt:Kt(r.resendAvailableAt)}}};import{TransactWriteCommand as cO}from"@aws-sdk/lib-dynamodb";var pc=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}async createEmailVerificationRegistration(e){try{let r=ae(),n=ht(),i=re(e.challenge.expiresAt),o=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new cO({TransactItems:[this.putItem(this.marshallProfile(e,r)),this.putItem(this.marshallUserAuth(e,r)),this.putItem(this.marshallIdentity(e,r)),this.putItem(this.marshallCredential(e,n,r)),this.putItem(this.marshallChallenge(e,r,o))]})),T(void 0)}catch(r){return Is(r)==="TransactionCanceledException"||Ce(r)?d(te.UniqueConstraintViolation({field:"registration"})):d(G("create email verification registration transaction",r))}}putItem(e){return{Put:{TableName:this.tableName,Item:Ht(e),ConditionExpression:`attribute_not_exists(${h.PK})`}}}marshallProfile(e,r){let n=e.profile.status,i={[h.PK]:U.USER_PK(e.profile.id),[h.SK]:U.USER_PROFILE_SK(),userStatus:n,[h.CREATED_AT]:r,[h.UPDATED_AT]:r,[h.USER_STATUS_PK]:Ae.USER_STATUS_PK(n),[h.USER_STATUS_SK]:Ae.USER_STATUS_SK(e.profile.id)};return e.profile.contactEmail&&(i.contactEmail=e.profile.contactEmail),e.profile.contactPhone&&(i.contactPhone=e.profile.contactPhone),e.profile.username&&(i.username=e.profile.username),e.profile.displayName&&(i.displayName=e.profile.displayName),e.profile.givenName&&(i.givenName=e.profile.givenName),e.profile.familyName&&(i.familyName=e.profile.familyName),e.profile.avatarUrl&&(i.avatarUrl=e.profile.avatarUrl),e.profile.locale&&(i.locale=e.profile.locale),e.profile.metadata&&(i.metadata=JSON.stringify(e.profile.metadata)),i}marshallUserAuth(e,r){return{[h.PK]:U.USER_PK(e.userAuth.userId),[h.SK]:U.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[h.CREATED_AT]:r,[h.UPDATED_AT]:r}}marshallIdentity(e,r){let n=e.identity,i={[h.PK]:U.IDENTITY_PK(n.type,n.value),[h.SK]:U.IDENTITY_SK(),[h.IDENTITY_USER_PK]:U.USER_INDEX_PK(n.userId),[h.IDENTITY_USER_SK]:U.USER_INDEX_SK(n.type,n.value),[h.USER_ID]:n.userId,[h.LOGIN_ENABLED]:n.loginEnabled,[h.CREATED_AT]:r,[h.UPDATED_AT]:r,[h.PENDING_VERIFICATION]:Ht({...n.pendingVerification,expiresAt:re(n.pendingVerification.expiresAt),resendAvailableAt:Cr(n.pendingVerification.resendAvailableAt)})},o=Cr(n.verifiedAt);return o!==null&&(i[h.VERIFIED_AT]=o),i[h.GUARDS]=n.guards??{},i}marshallCredential(e,r,n){let i=e.credential,o={[h.PK]:U.CREDENTIAL_PK(r),[h.SK]:U.CREDENTIAL_SK(),[h.CREDENTIAL_USER_PK]:U.USER_PK(i.userId),[h.CREDENTIAL_USER_SK]:U.CREDENTIAL_USER_SK(i.type,r),[h.USER_ID]:i.userId,[h.CREDENTIAL_VALUE]:i.value,[h.METADATA]:i.data,[h.REVOKED_AT]:i.revokedAt?re(i.revokedAt):null,[h.CREATED_AT]:n,[h.UPDATED_AT]:n};return i.lastUsedAt&&(o[h.LAST_USED_AT]=re(i.lastUsedAt)),o}marshallChallenge(e,r,n){let i=e.challenge,o={[h.PK]:U.CHALLENGE_PK(i.id),[h.SK]:U.CHALLENGE_SK(),[h.USER_ID]:i.userId,[h.PURPOSE]:i.purpose,[h.CHALLENGE_STATUS]:i.status,[h.EXPIRES_AT]:re(i.expiresAt),[h.CREATED_AT]:r,[h.TTL]:n};return i.tenantId&&(o[h.TENANT_ID]=i.tenantId),i.phase&&(o[h.PHASE]=i.phase),i.allowedMethods&&i.allowedMethods.length>0&&(o[h.ALLOWED_METHODS]=i.allowedMethods),i.method&&(o[h.METHOD]=i.method),i.codeHash&&(o[h.CODE_HASH]=i.codeHash),i.attempts!==void 0&&(o[h.ATTEMPTS]=i.attempts),i.maxAttempts!==void 0&&(o[h.MAX_ATTEMPTS]=i.maxAttempts),i.identityType&&(o[h.IDENTITY_TYPE]=i.identityType),i.identityValue&&(o[h.IDENTITY_VALUE]=i.identityValue),i.deviceLabel&&(o[h.DEVICE_LABEL]=i.deviceLabel),i.country&&(o[h.COUNTRY]=i.country),i.city&&(o[h.CITY]=i.city),i.metadata&&(o[h.METADATA]=i.metadata),i.flowKey&&(o[h.FLOW_KEY]=i.flowKey),o}};import{DynamoDBClient as dO}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as pO,GetCommand as PT,PutCommand as fO,QueryCommand as fc,UpdateCommand as bs}from"@aws-sdk/lib-dynamodb";import{BatchGetCommand as lO}from"@aws-sdk/lib-dynamodb";var CT=100,DT=5;function uO(t){return new Promise(e=>setTimeout(e,t))}async function xs(t,e,r){if(r.length===0)return[];let n=[];for(let i=0;i<r.length;i+=CT){let o=r.slice(i,i+CT),s=0;for(;o.length>0;){let a=await t.send(new lO({RequestItems:{[e]:{Keys:o}}})),c=a.Responses?.[e];c&&n.push(...c);let l=a.UnprocessedKeys?.[e]?.Keys;if(!l||l.length===0)break;if(s+=1,s>DT)throw new Error(`BatchGet left ${l.length} unprocessed keys after ${DT} retries`);o=l,await uO(2**s*25)}}return n}var mc=class{docClient;tableName;ttlGracePeriod;constructor(e){let r=e.client||new dO({});this.docClient=e.docClient||pO.from(r),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return ht()}generateTokenId(){return ht()}async get(e){try{let r=await this.docClient.send(new PT({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()}}));return r.Item?T(this.unmarshall(r.Item)):T(null)}catch(r){return d(G("get session",r))}}async create(e){try{let r=ae(),n=e.id||this.generateSessionId(),i=e.tokenId||this.generateTokenId(),o={...e,id:n,tokenId:i,revokedAt:null,createdAt:new Date(r),lastUsedAt:new Date(r)},s=sc(re(e.expiresAt)+this.ttlGracePeriod),a=hd.sessionSK(r,n);return await this.docClient.send(new fO({TableName:this.tableName,Item:this.marshall(o,s,a)})),T(o)}catch(r){return d(G("create session",r))}}async update(e,r){try{let n=[],i={},o={};if(r.tokenId!==void 0&&(n.push(`#${h.TOKEN_ID} = :tokenId`),i[`#${h.TOKEN_ID}`]=h.TOKEN_ID,o[":tokenId"]=r.tokenId),r.expiresAt!==void 0){n.push(`#${h.EXPIRES_AT} = :expiresAt`),i[`#${h.EXPIRES_AT}`]=h.EXPIRES_AT,o[":expiresAt"]=re(r.expiresAt);let s=sc(re(r.expiresAt)+this.ttlGracePeriod);n.push(`#${h.TTL} = :ttl`),i[`#${h.TTL}`]=h.TTL,o[":ttl"]=s}return r.lastUsedAt!==void 0&&(n.push(`#${h.LAST_USED_AT} = :lastUsedAt`),i[`#${h.LAST_USED_AT}`]=h.LAST_USED_AT,o[":lastUsedAt"]=re(r.lastUsedAt)),r.metadata!==void 0&&(n.push(`#${h.METADATA} = :metadata`),i[`#${h.METADATA}`]=h.METADATA,o[":metadata"]=r.metadata),r.previousTokenId!==void 0&&(n.push(`#${h.PREVIOUS_TOKEN_ID} = :previousTokenId`),i[`#${h.PREVIOUS_TOKEN_ID}`]=h.PREVIOUS_TOKEN_ID,o[":previousTokenId"]=r.previousTokenId),r.rotatedAt!==void 0&&(n.push(`#${h.ROTATED_AT} = :rotatedAt`),i[`#${h.ROTATED_AT}`]=h.ROTATED_AT,o[":rotatedAt"]=r.rotatedAt),n.length===0?T():(await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:o})),T())}catch(n){return d(G("update session",n))}}async rotateToken(e,r,n){try{let i=sc(re(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET #${h.TOKEN_ID} = :tokenId, #${h.PREVIOUS_TOKEN_ID} = :previousTokenId, #${h.ROTATED_AT} = :rotatedAt, #${h.EXPIRES_AT} = :expiresAt, #${h.LAST_USED_AT} = :lastUsedAt, #${h.TTL} = :ttl`,ConditionExpression:`#${h.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${h.TOKEN_ID}`]:h.TOKEN_ID,[`#${h.PREVIOUS_TOKEN_ID}`]:h.PREVIOUS_TOKEN_ID,[`#${h.ROTATED_AT}`]:h.ROTATED_AT,[`#${h.EXPIRES_AT}`]:h.EXPIRES_AT,[`#${h.LAST_USED_AT}`]:h.LAST_USED_AT,[`#${h.TTL}`]:h.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":re(n.expiresAt),":lastUsedAt":re(n.lastUsedAt),":ttl":i,":expectedCurrentTokenId":r}})),T(!0)}catch(i){return Ce(i)?T(!1):d(G("rotate session token",i))}}async switchTenant(e,r){try{let n=[`#${h.TENANT_ID} = :tenantId`,`#${h.TOKEN_ID} = :tokenId`,`#${h.LAST_USED_AT} = :lastUsedAt`],i=[],o={[`#${h.TENANT_ID}`]:h.TENANT_ID,[`#${h.TOKEN_ID}`]:h.TOKEN_ID,[`#${h.LAST_USED_AT}`]:h.LAST_USED_AT},s={":tenantId":r.tenantId,":tokenId":r.tokenId,":lastUsedAt":ae()};o[`#${h.TENANT_TYPE}`]=h.TENANT_TYPE,r.tenantType!==void 0?(n.push(`#${h.TENANT_TYPE} = :tenantType`),s[":tenantType"]=r.tenantType):i.push(`#${h.TENANT_TYPE}`),o[`#${h.PERM}`]=h.PERM,r.perms!==void 0?(n.push(`#${h.PERM} = :perms`),s[":perms"]=JSON.stringify(r.perms)):i.push(`#${h.PERM}`),o[`#${h.ROLES}`]=h.ROLES,r.roles!==void 0?(n.push(`#${h.ROLES} = :roles`),s[":roles"]=r.roles):i.push(`#${h.ROLES}`),o["#revokedAt"]=h.REVOKED_AT;let a=`SET ${n.join(", ")}${i.length>0?` REMOVE ${i.join(", ")}`:""}`;return await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:o,ExpressionAttributeValues:s,ConditionExpression:`attribute_exists(${h.PK}) AND attribute_not_exists(#revokedAt)`})),T()}catch(n){return Ce(n)?d(te.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):d(G("switch tenant",n))}}async revoke(e){try{return await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET #${h.REVOKED_AT} = :revokedAt REMOVE #${h.ACTIVE_SESSION_PK}, #${h.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${h.REVOKED_AT}`]:h.REVOKED_AT,[`#${h.ACTIVE_SESSION_PK}`]:h.ACTIVE_SESSION_PK,[`#${h.ACTIVE_SESSION_SK}`]:h.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":re(new Date)},ConditionExpression:`attribute_exists(${h.PK})`})),T()}catch(r){return Ce(r)?T():d(G("revoke session",r))}}async revokeByIdAndUserId(e,r){try{return await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET #${h.REVOKED_AT} = :revokedAt REMOVE #${h.ACTIVE_SESSION_PK}, #${h.ACTIVE_SESSION_SK}`,ConditionExpression:`#${h.USER_ID} = :userId AND attribute_not_exists(#${h.REVOKED_AT})`,ExpressionAttributeNames:{[`#${h.REVOKED_AT}`]:h.REVOKED_AT,[`#${h.USER_ID}`]:h.USER_ID,[`#${h.ACTIVE_SESSION_PK}`]:h.ACTIVE_SESSION_PK,[`#${h.ACTIVE_SESSION_SK}`]:h.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":re(new Date),":userId":r}})),T()}catch(n){return Ce(n)?T():d(G("revoke session by user",n))}}async findByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return d(te.DatabaseQueryError({query:"invalid pagination cursor"}))}let o=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.USER_SESSIONS,KeyConditionExpression:`${h.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":U.USER_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!o.Items||o.Items.length===0){let m={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return T([],{pagination:m})}let a=o.Items.map(m=>le.sessionId(m[h.PK])).map(m=>({[h.PK]:U.SESSION_PK(m),[h.SK]:U.SESSION_SK()})),l=(await xs(this.docClient,this.tableName,a)).map(m=>this.unmarshall(m)),u=!!o.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null,f={type:"cursor",limit:n,count:l.length,hasNext:u,hasPrev:!!r?.cursor,cursor:p};return T(l,{pagination:f})}catch(n){return d(G("find sessions by user",n))}}async findActiveByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return d(te.DatabaseQueryError({query:"invalid pagination cursor"}))}let o=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.ACTIVE_SESSIONS,KeyConditionExpression:`${h.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!o.Items||o.Items.length===0){let m={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return T([],{pagination:m})}let a=o.Items.map(m=>le.sessionId(m[h.PK])).map(m=>({[h.PK]:U.SESSION_PK(m),[h.SK]:U.SESSION_SK()})),l=(await xs(this.docClient,this.tableName,a)).map(m=>this.unmarshall(m)),u=!!o.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null,f={type:"cursor",limit:n,count:l.length,hasNext:u,hasPrev:!!r?.cursor,cursor:p};return T(l,{pagination:f})}catch(n){return d(G("find active sessions by user",n))}}async getActiveSessionsForLimit(e){try{let r=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.ACTIVE_SESSIONS,KeyConditionExpression:`${h.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!r.Items||r.Items.length===0)return T([]);let n=r.Items.map(i=>{let o=le.sessionId(i[h.PK]),s=hd.extractCreatedAt(i[h.ACTIVE_SESSION_SK]);return{id:o,createdAt:new Date(s)}});return T(n)}catch(r){return d(G("get active sessions for limit",r))}}async revokeSessionsByIds(e,r){if(e.length===0)return 0;let n=re(new Date),i=await Promise.allSettled(e.map(s=>this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(s),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET #${h.REVOKED_AT} = :revokedAt REMOVE #${h.ACTIVE_SESSION_PK}, #${h.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${h.REVOKED_AT}`]:h.REVOKED_AT,[`#${h.ACTIVE_SESSION_PK}`]:h.ACTIVE_SESSION_PK,[`#${h.ACTIVE_SESSION_SK}`]:h.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),o=0;for(let s of i)s.status==="fulfilled"?o+=1:console.error(`[session-repo] ${r}: session revoke failed (may remain active):`,{name:Is(s.reason)});return o}async revokeAllByUserId(e,r){try{let n=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.ACTIVE_SESSIONS,KeyConditionExpression:`${h.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return T(0);let i=n.Items.map(s=>le.sessionId(s[h.PK])).filter(s=>!r||s!==r),o=await this.revokeSessionsByIds(i,"revokeAllByUserId");return T(o)}catch(n){return d(G("revoke all sessions by user",n))}}async revokeBatch(e){try{let r=await this.revokeSessionsByIds(e,"revokeBatch");return T(r)}catch(r){return d(G("revoke batch sessions",r))}}async countByUserId(e){try{let r=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.ACTIVE_SESSIONS,KeyConditionExpression:`${h.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return T(r.Count||0)}catch(r){return d(G("count active sessions by user",r))}}async isTokenActive(e,r){try{let n=await this.docClient.send(new PT({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(r),[h.SK]:U.SESSION_SK()},ProjectionExpression:`${h.TOKEN_ID}, ${h.REVOKED_AT}, ${h.EXPIRES_AT}`}));if(!n.Item)return T(!1);let i=n.Item,o=i[h.TOKEN_ID]===e&&!i[h.REVOKED_AT]&&J(i[h.EXPIRES_AT])>new Date;return T(o)}catch(n){return d(G("check token active",n))}}marshall(e,r,n){let i={[h.PK]:U.SESSION_PK(e.id),[h.SK]:U.SESSION_SK(),[h.USER_SESSION_PK]:U.USER_PK(e.userId),[h.USER_SESSION_SK]:n,...!e.revokedAt&&{[h.ACTIVE_SESSION_PK]:Ae.ACTIVE_SESSION_PK(e.userId),[h.ACTIVE_SESSION_SK]:n},[h.USER_ID]:e.userId,[h.TOKEN_ID]:e.tokenId,[h.EXPIRES_AT]:re(e.expiresAt),[h.CREATED_AT]:re(e.createdAt),[h.LAST_USED_AT]:re(e.lastUsedAt),[h.TTL]:r};return e.tenantId&&(i[h.TENANT_ID]=e.tenantId),e.tenantType&&(i[h.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(i[h.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(i[h.ROLES]=e.roles),e.deviceLabel&&(i[h.DEVICE_LABEL]=e.deviceLabel),e.country&&(i[h.COUNTRY]=e.country),e.city&&(i[h.CITY]=e.city),e.metadata&&(i[h.METADATA]=e.metadata),e.revokedAt&&(i[h.REVOKED_AT]=re(e.revokedAt)),e.previousTokenId&&(i[h.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(i[h.ROTATED_AT]=e.rotatedAt),i}unmarshall(e){let n={id:le.sessionId(e[h.PK]),userId:e[h.USER_ID],tokenId:e[h.TOKEN_ID],expiresAt:J(e[h.EXPIRES_AT]),createdAt:J(e[h.CREATED_AT]),lastUsedAt:J(e[h.LAST_USED_AT]),revokedAt:e[h.REVOKED_AT]?J(e[h.REVOKED_AT]):null};return e[h.TENANT_ID]&&(n.tenantId=e[h.TENANT_ID]),e[h.TENANT_TYPE]&&(n.tenantType=e[h.TENANT_TYPE]),e[h.PERM]!==void 0&&(n.perms=JSON.parse(e[h.PERM])),e[h.ROLES]!==void 0&&(n.roles=e[h.ROLES]),e[h.DEVICE_LABEL]&&(n.deviceLabel=e[h.DEVICE_LABEL]),e[h.COUNTRY]&&(n.country=e[h.COUNTRY]),e[h.CITY]&&(n.city=e[h.CITY]),e[h.METADATA]&&(n.metadata=e[h.METADATA]),e[h.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[h.PREVIOUS_TOKEN_ID]),e[h.ROTATED_AT]!==void 0&&(n.rotatedAt=e[h.ROTATED_AT]),n}};import{QueryCommand as mO}from"@aws-sdk/lib-dynamodb";var hc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":h.INVITE_TENANT_PK},o={":pk":Ae.INVITE_TENANT_PK(e)},s={TableName:this.tableName,IndexName:ue.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:o,ScanIndexForward:!1,Limit:n};r?.cursor&&(s.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(s.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=h.INVITE_TENANT_SK,o[":statusPrefix"]=Ae.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new mO(s)),c=(a.Items||[]).map(p=>this.toListItem(p)),l=!!a.LastEvaluatedKey,u=l?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return mr(c,{limit:n,hasNext:l,cursor:u,prevCursor:r?.cursor??null})}catch(n){return d(G("listByTenant query",n))}}toListItem(e){let r=le.inviteId(e.PK),n={id:e.invitedById};e.invitedByInfo&&(e.invitedByInfo.name&&(n.name=e.invitedByInfo.name),e.invitedByInfo.email&&(n.email=e.invitedByInfo.email),e.invitedByInfo.jobTitle&&(n.jobTitle=e.invitedByInfo.jobTitle));let i={id:r,tenantId:e.tenantId,invitedBy:n,status:e.inviteStatus,expiresAt:J(e.expiresAt),createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};return e.inviteeUserId&&(i.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(i.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(i.inviteePhone=e.inviteePhone),e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),e.displayName&&(i.displayName=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.jobTitle&&(i.jobTitle=e.jobTitle),e.acceptedAt&&(i.acceptedAt=J(e.acceptedAt)),e.declinedAt&&(i.declinedAt=J(e.declinedAt)),e.revokedAt&&(i.revokedAt=J(e.revokedAt)),i}};import{GetCommand as UT,PutCommand as hO,QueryCommand as fi,UpdateCommand as EO}from"@aws-sdk/lib-dynamodb";var yO=10080*60*1e3,Ec=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:le.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:J(e.expiresAt),createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};e.inviteeUserId&&(n.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(n.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(n.inviteePhone=e.inviteePhone),e.roles!==void 0&&(n.roles=e.roles);let i=e[h.PERM];return i!==void 0&&(n.perms=JSON.parse(i)),e.authPerm!==void 0&&(n.authPerm=e.authPerm),e.displayName&&(n.displayName=e.displayName),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.jobTitle&&(n.jobTitle=e.jobTitle),e.acceptedAt&&(n.acceptedAt=J(e.acceptedAt)),e.declinedAt&&(n.declinedAt=J(e.declinedAt)),e.revokedAt&&(n.revokedAt=J(e.revokedAt)),n}generateInviteId(){return ht()}async getById(e){try{let r=await this.docClient.send(new UT({TableName:this.tableName,Key:{PK:U.INVITE_PK(e),SK:U.INVITE_SK()}}));return r.Item?T(this.mapItemToEntity(r.Item)):T(null)}catch(r){return d(G("getById invite",r))}}async getByToken(e){try{let n=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":h.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return T(null);let i=n[0],o=await this.docClient.send(new UT({TableName:this.tableName,Key:{PK:i.PK,SK:i.SK}}));return o.Item?T(this.mapItemToEntity(o.Item)):T(null)}catch(r){return d(G("getByToken invite",r))}}async create(e){try{let r=ae(),n=re(e.expiresAt),i=Math.floor((n+yO)/1e3),o={PK:U.INVITE_PK(e.id),SK:U.INVITE_SK(),[h.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[h.INVITED_BY_ID]:e.invitedById,[h.INVITE_STATUS]:e.status,[h.INVITE_TOKEN]:e.inviteToken,[h.EXPIRES_AT]:n,[h.CREATED_AT]:r,[h.UPDATED_AT]:r,[h.TTL]:i,[h.INVITE_TENANT_PK]:Ae.INVITE_TENANT_PK(e.tenantId),[h.INVITE_TENANT_SK]:Ae.INVITE_TENANT_SK(e.status,r,e.id),[h.INVITE_TOKEN_GSI]:e.inviteToken},s={};e.invitedByName&&(s.name=e.invitedByName),e.invitedByEmail&&(s.email=e.invitedByEmail),e.invitedByJobTitle&&(s.jobTitle=e.invitedByJobTitle),Object.keys(s).length>0&&(o[h.INVITED_BY_INFO]=s),e.inviteeUserId&&(o[h.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(o[h.INVITEE_EMAIL]=e.inviteeEmail,o[h.INVITEE_EMAIL_GSI]=e.inviteeEmail,o[h.INVITEE_EMAIL_TENANT_SK]=`${ce.TENANT}${e.tenantId}`),e.inviteePhone&&(o[h.INVITEE_PHONE]=e.inviteePhone,o[h.INVITEE_PHONE_GSI]=e.inviteePhone,o[h.INVITEE_PHONE_TENANT_SK]=`${ce.TENANT}${e.tenantId}`),e.roles!==void 0&&(o[h.ROLES]=e.roles),e.perms!==void 0&&(o[h.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(o[h.AUTH_PERM]=e.authPerm),e.displayName&&(o[h.DISPLAY_NAME]=e.displayName),e.givenName&&(o.givenName=e.givenName),e.familyName&&(o.familyName=e.familyName),e.jobTitle&&(o.jobTitle=e.jobTitle),await this.docClient.send(new hO({TableName:this.tableName,Item:o,ConditionExpression:"attribute_not_exists(PK)"}));let a={id:e.id,tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.status,inviteToken:e.inviteToken,expiresAt:e.expiresAt,createdAt:J(r),updatedAt:J(r)};return e.inviteeUserId&&(a.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(a.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(a.inviteePhone=e.inviteePhone),e.roles!==void 0&&(a.roles=e.roles),e.perms!==void 0&&(a.perms=e.perms),e.authPerm!==void 0&&(a.authPerm=e.authPerm),e.displayName&&(a.displayName=e.displayName),e.givenName&&(a.givenName=e.givenName),e.familyName&&(a.familyName=e.familyName),e.jobTitle&&(a.jobTitle=e.jobTitle),T(a)}catch(r){return r.name==="ConditionalCheckFailedException"?d(te.UniqueConstraintViolation({field:"invite id"})):d(Rt("create invite",r))}}async updateStatus(e,r){try{let n=ae(),i=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],o={"#inviteStatus":h.INVITE_STATUS,"#inviteTenantSk":h.INVITE_TENANT_SK,"#updatedAt":h.UPDATED_AT},s={":inviteStatus":r.status,":inviteTenantSk":Ae.INVITE_TENANT_SK(r.status,n,e),":updatedAt":n};r.acceptedAt&&(i.push("#acceptedAt = :acceptedAt"),o["#acceptedAt"]=h.ACCEPTED_AT,s[":acceptedAt"]=re(r.acceptedAt)),r.declinedAt&&(i.push("#declinedAt = :declinedAt"),o["#declinedAt"]=h.DECLINED_AT,s[":declinedAt"]=re(r.declinedAt)),r.revokedAt&&(i.push("#revokedAt = :revokedAt"),o["#revokedAt"]=h.REVOKED_AT,s[":revokedAt"]=re(r.revokedAt));let a=[];r.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),o["#inviteTokenGsi"]=h.INVITE_TOKEN_GSI,o["#inviteeEmailGsi"]=h.INVITEE_EMAIL_GSI,o["#inviteeEmailTenantSk"]=h.INVITEE_EMAIL_TENANT_SK,o["#inviteePhoneGsi"]=h.INVITEE_PHONE_GSI,o["#inviteePhoneTenantSk"]=h.INVITEE_PHONE_TENANT_SK);let c=`SET ${i.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new EO({TableName:this.tableName,Key:{PK:U.INVITE_PK(e),SK:U.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:o,ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"TenantInvite",id:e})):d(Rt("updateStatus invite",n))}}async findByTenantAndEmail(e,r){try{let i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":h.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":h.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":r,":tenantSk":`${ce.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?T(null):T(this.mapItemToEntity(i[0]))}catch(n){return d(G("findByTenantAndEmail",n))}}async findByTenantAndPhone(e,r){try{let i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":h.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":h.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":r,":tenantSk":`${ce.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?T(null):T(this.mapItemToEntity(i[0]))}catch(n){return d(G("findByTenantAndPhone",n))}}async findByTenantAndUserId(e,r){try{let i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":h.INVITE_TENANT_PK,"#sk":h.INVITE_TENANT_SK,"#inviteeUserId":h.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":Ae.INVITE_TENANT_PK(e),":pendingPrefix":Ae.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":r},Limit:1}))).Items;return!i||i.length===0?T(null):T(this.mapItemToEntity(i[0]))}catch(n){return d(G("findByTenantAndUserId",n))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":h.INVITE_TENANT_PK},o={":pk":Ae.INVITE_TENANT_PK(e)},s={TableName:this.tableName,IndexName:ue.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:o,ScanIndexForward:!1,Limit:n};r?.cursor&&(s.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(s.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=h.INVITE_TENANT_SK,o[":statusPrefix"]=Ae.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new fi(s)),c=(a.Items||[]).map(p=>this.mapItemToEntity(p)),l=!!a.LastEvaluatedKey,u=l?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return mr(c,{limit:n,hasNext:l,cursor:u,prevCursor:r?.cursor??null})}catch(n){return d(G("listByTenant",n))}}async findPendingByEmail(e){try{let r=ae(),i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":h.INVITEE_EMAIL_GSI,"#expiresAt":h.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":r}}))).Items||[];if(i.length===0)return T([]);let o=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await xs(this.docClient,this.tableName,o)).map(c=>this.mapItemToEntity(c));return T(a)}catch(r){return d(G("findPendingByEmail",r))}}async findPendingByPhone(e){try{let r=ae(),i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":h.INVITEE_PHONE_GSI,"#expiresAt":h.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":r}}))).Items||[];if(i.length===0)return T([]);let o=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await xs(this.docClient,this.tableName,o)).map(c=>this.mapItemToEntity(c));return T(a)}catch(r){return d(G("findPendingByPhone",r))}}async countPendingByTenant(e){try{let r=await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":h.INVITE_TENANT_PK,"#sk":h.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":Ae.INVITE_TENANT_PK(e),":pendingPrefix":Ae.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return T(r.Count??0)}catch(r){return d(G("countPendingByTenant",r))}}async expireOld(e){return T(0)}};import{QueryCommand as gO}from"@aws-sdk/lib-dynamodb";var yc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":U.TENANT_MEMBER_PK(e)}};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let s=(await this.docClient.send(new gO(i))).Items||[],a=[],c=new Map;for(let m of s){let E=m.SK;if(E.startsWith(Be.TENANT_PROFILE)){let v=le.tenantProfileUserId(E);c.set(v,m)}else E.startsWith(ce.USER)&&a.push(m)}a.sort((m,E)=>E.createdAt-m.createdAt);let l=a.slice(0,n),u=a.length>n,p=l.map(m=>{let E=le.tenantMemberUserId(m.SK),v=c.get(E);return this.toListItem(m,e,E,v)}),f=u&&l.length>0?Buffer.from(JSON.stringify({PK:l[l.length-1].PK,SK:l[l.length-1].SK})).toString("base64url"):null;return mr(p,{limit:n,hasNext:u,cursor:f,prevCursor:r?.cursor??null})}catch(n){return d(G("listByTenant query",n))}}toListItem(e,r,n,i){let o={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};if(e.roles!==void 0&&(o.roles=e.roles),e.perms!==void 0&&(o.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(o.authPerm=e.authPerm),i){let s={tenantId:r,userId:n,createdAt:J(i.createdAt),updatedAt:J(i.updatedAt)};i.contactEmail&&(s.contactEmail=i.contactEmail),i.contactPhone&&(s.contactPhone=i.contactPhone),i.displayName&&(s.displayName=i.displayName),i.displayNameSource&&(s.displayNameSource=i.displayNameSource),i.givenName&&(s.givenName=i.givenName),i.familyName&&(s.familyName=i.familyName),i.avatarUrl&&(s.avatarUrl=i.avatarUrl),i.locale&&(s.locale=i.locale),i.jobTitle&&(s.jobTitle=i.jobTitle),i.bio&&(s.bio=i.bio),i.metadata&&(s.metadata=JSON.parse(i.metadata)),o.tenantProfile=s}return o}};import{DeleteCommand as vO,DynamoDBDocumentClient as AO,GetCommand as LT,PutCommand as TO,QueryCommand as _O,TransactWriteCommand as IO,UpdateCommand as MT}from"@aws-sdk/lib-dynamodb";var gc=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=AO.from(e)}mapItemToEntity(e){let r=le.tenantId(e.PK),n=le.tenantMemberUserId(e.SK),i={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};return e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),i}async get(e,r){try{let n=await this.docClient.send(new LT({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_MEMBER_SK(r)}}));if(!n.Item)return T(null);let i=this.mapItemToEntity(n.Item);return T(i)}catch(n){return d(G("get",n))}}async create(e){try{let r=ae(),n=e.isOwner?void 0:e.authPerm,i=Ht({PK:U.TENANT_MEMBER_PK(e.tenantId),SK:U.TENANT_MEMBER_SK(e.userId),userStatus:e.status,roles:e.roles,perms:e.perms!==void 0?JSON.stringify(e.perms):void 0,authPerm:n,isOwner:e.isOwner,createdAt:r,updatedAt:r,userTenantPk:Ae.USER_TENANT_PK(e.userId),userTenantSk:Ae.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,r,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new IO({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:U.TENANT_MEMBER_PK(e.tenantId),SK:U.TENANT_OWNER_MARKER_SK(),createdAt:r},ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}},{Put:{TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}}]})):await this.docClient.send(new TO({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(void 0)}catch(r){return r.name==="TransactionCanceledException"?r.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?d(te.UniqueConstraintViolation({field:"tenant owner"})):d(te.UniqueConstraintViolation({field:"tenant member"})):r.name==="ConditionalCheckFailedException"?d(te.UniqueConstraintViolation({field:"tenant member"})):d(Rt("create tenant member",r))}}async updatePermissions(e,r,n){try{let i={...n,updatedAt:ae()},{UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a}=Dr(i);return await this.docClient.send(new MT({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_MEMBER_SK(r)},UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"TenantMember",id:`${e}:${r}`})):d(Rt("updatePermissions tenant member",i))}}async updateStatus(e,r,n){try{return await this.docClient.send(new MT({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_MEMBER_SK(r)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":ae()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"TenantMember",id:`${e}:${r}`})):d(Rt("updateStatus tenant member",i))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":U.TENANT_MEMBER_PK(e),":skPrefix":ce.USER},Limit:n};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let o=await this.docClient.send(new _O(i)),s=(o.Items||[]).map(l=>this.mapItemToEntity(l)),a=!!o.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return mr(s,{limit:n,hasNext:a,cursor:c,prevCursor:r?.cursor??null})}catch(n){return d(G("listByTenant",n))}}async hasOwner(e){try{let r=await this.docClient.send(new LT({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_OWNER_MARKER_SK()}}));return T(!!r.Item)}catch(r){return d(G("hasOwner",r))}}async remove(e,r){try{return await this.docClient.send(new vO({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_MEMBER_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"TenantMember",id:`${e}:${r}`})):d(Rt("remove tenant member",n))}}};import{BatchGetCommand as xO,QueryCommand as bO}from"@aws-sdk/lib-dynamodb";var vc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByUser(e,r){try{let n=Math.min(r?.limit??50,100),i=r?.tenantType??Qt.DEFAULT,o=r?.parentTenantId,s=o?`${i}#${o}#`:`${i}#`,a={TableName:this.tableName,IndexName:ue.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":Ae.USER_TENANT_PK(e),":skPrefix":s},ScanIndexForward:!1,Limit:n};r?.cursor&&(a.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let c=await this.docClient.send(new bO(a)),l=c.Items??[],u=await this.fetchProfileMap(e,l),p=l.map(E=>this.toListItem(E,e,u)),f=!!c.LastEvaluatedKey,m=f?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return mr(p,{limit:n,hasNext:f,cursor:m,prevCursor:r?.cursor??null})}catch(n){return d(G("listByUser query",n))}}async fetchProfileMap(e,r){let n=new Map;if(r.length===0)return n;let i=r.map(s=>({PK:U.TENANT_PROFILE_PK(le.tenantId(s.PK)),SK:U.TENANT_PROFILE_SK(e)})),o=await this.docClient.send(new xO({RequestItems:{[this.tableName]:{Keys:i}}}));for(let s of o.Responses?.[this.tableName]??[]){let a=s,c=le.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,r,n){let i=le.tenantId(e.PK),o={tenantId:i,userId:r,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};e.roles!==void 0&&(o.roles=e.roles),e.perms!==void 0&&(o.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(o.authPerm=e.authPerm);let s=n.get(i);return s&&(s.contactEmail&&(o.contactEmail=s.contactEmail),s.contactPhone&&(o.contactPhone=s.contactPhone),s.displayName&&(o.displayName=s.displayName),s.displayNameSource&&(o.displayNameSource=s.displayNameSource),s.givenName&&(o.givenName=s.givenName),s.familyName&&(o.familyName=s.familyName),s.avatarUrl&&(o.avatarUrl=s.avatarUrl),s.locale&&(o.locale=s.locale),s.jobTitle&&(o.jobTitle=s.jobTitle),s.bio&&(o.bio=s.bio),s.metadata&&(o.metadata=JSON.parse(s.metadata))),o}};import{DeleteCommand as SO,GetCommand as wO,PutCommand as NO,UpdateCommand as RO}from"@aws-sdk/lib-dynamodb";var Ac=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return ht()}toEntity(e){let n={id:le.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let r=await this.docClient.send(new wO({TableName:this.tableName,Key:{PK:U.TENANT_PK(e),SK:U.TENANT_SK()}}));return r.Item?T(this.toEntity(r.Item)):T(null)}catch(r){return d(G("get tenant",r))}}async create(e){try{let r=e.id??this.generateTenantId(),n=ae(),i=Ht({PK:U.TENANT_PK(r),SK:U.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new NO({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?d(te.UniqueConstraintViolation({field:"tenant"})):d(Rt("create tenant",r))}}async update(e,r){try{let n={updatedAt:ae()};r.type!==void 0&&(n.tenantType=r.type),r.ownerId!==void 0&&(n.ownerId=r.ownerId),r.parentTenantId!==void 0&&(n.parentTenantId=r.parentTenantId===null?void 0:r.parentTenantId);let{UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:s}=Dr(n);return await this.docClient.send(new RO({TableName:this.tableName,Key:{PK:U.TENANT_PK(e),SK:U.TENANT_SK()},UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"Tenant",id:e})):d(Rt("update tenant",n))}}async delete(e){try{return await this.docClient.send(new SO({TableName:this.tableName,Key:{PK:U.TENANT_PK(e),SK:U.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"Tenant",id:e})):d(Rt("delete tenant",r))}}async list(){return d(te.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return d(te.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return d(te.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};import{DeleteCommand as OO,GetCommand as kO,PutCommand as CO,UpdateCommand as vd}from"@aws-sdk/lib-dynamodb";var Tc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let r=await this.docClient.send(new kO({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()}}));return r.Item?T(this.unmarshall(r.Item,e)):T(null)}catch(r){return d(G("get user auth",r))}}async create(e){try{let r=ae(),n={...e,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new CO({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${h.PK})`})),T(n)}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"userAuth"})):d(G("create user auth",r))}}async updateStatus(e,r){try{let n=ae();return await this.docClient.send(new vd({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${h.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${h.UPDATED_AT}`]:h.UPDATED_AT},ExpressionAttributeValues:{":userStatus":r,":updatedAt":n},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userAuth",id:e})):d(G("update user auth status",n))}}async updateMfaRequired(e,r){try{let n=ae();return await this.docClient.send(new vd({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${h.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${h.UPDATED_AT}`]:h.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r,":updatedAt":n},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userAuth",id:e})):d(G("update mfa required",n))}}async updateMfaMethods(e,r){try{let n=ae();return await this.docClient.send(new vd({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${h.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${h.UPDATED_AT}`]:h.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":r,":updatedAt":n},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userAuth",id:e})):d(G("update mfa methods",n))}}async updateMfaSettings(e,r){try{let n=ae();return await this.docClient.send(new vd({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${h.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${h.UPDATED_AT}`]:h.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r.mfaRequired,":mfaMethods":r.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userAuth",id:e})):d(G("update mfa settings",n))}}async remove(e){try{return await this.docClient.send(new OO({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()}})),T(void 0)}catch(r){return d(G("remove user auth",r))}}marshall(e){return{[h.PK]:U.USER_PK(e.userId),[h.SK]:U.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[h.CREATED_AT]:re(e.createdAt),[h.UPDATED_AT]:re(e.updatedAt)}}unmarshall(e,r){return{userId:r,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:J(e[h.CREATED_AT]),updatedAt:J(e[h.UPDATED_AT])}}};import{DynamoDBDocumentClient as DO,DeleteCommand as PO,GetCommand as UO,PutCommand as LO,QueryCommand as KT,UpdateCommand as rh}from"@aws-sdk/lib-dynamodb";function Ss(t,e){return e?U.USER_MFA_WITH_ID_SK(t,e):U.USER_MFA_SK(t)}var _c=class{client;tableName;docClient;constructor(e,r){this.client=e,this.tableName=r,this.docClient=DO.from(e)}toDynamoDBItem(e){let r={PK:U.USER_PK(e.userId),SK:Ss(e.method,e.id),method:e.method,data:JSON.stringify(e.data),createdAt:Date.now(),failedAttempts:0};return e.label&&(r.label=e.label),e.verifiedAt&&(r.verifiedAt=e.verifiedAt.getTime()),e.metadata&&(r.metadata=JSON.stringify(e.metadata)),r}fromDynamoDBItem(e,r){let n=le.mfaSKInfo(e.SK),i={userId:r,method:e.method,data:JSON.parse(e.data),createdAt:J(e.createdAt),verifiedAt:Kt(e.verifiedAt)??null};return n?.id&&(i.id=n.id),e.label&&(i.label=e.label),e.failedAttempts!==void 0&&(i.failedAttempts=e.failedAttempts),e.lastFailedAt!==void 0&&(i.lastFailedAt=Kt(e.lastFailedAt)),e.lockedUntil!==void 0&&(i.lockedUntil=Kt(e.lockedUntil)),e.lastUsedAt!==void 0&&(i.lastUsedAt=Kt(e.lastUsedAt)),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r,n){try{let i=Ss(r,n),o=await this.docClient.send(new UO({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:i}}));return o.Item?T(this.fromDynamoDBItem(o.Item,e)):T(null)}catch(i){return d(G("get MFA authenticator",i))}}async findByUserId(e){try{let r={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":U.USER_PK(e),":skPrefix":Be.MFA}},o=((await this.docClient.send(new KT(r))).Items??[]).map(s=>this.fromDynamoDBItem(s,e));return T(o)}catch(r){return d(G("find MFA authenticators by user",r))}}async findByUserIdAndMethod(e,r){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":U.USER_PK(e),":skPrefix":`${Be.MFA}${r}`}},s=((await this.docClient.send(new KT(n))).Items??[]).filter(a=>a.method===r).map(a=>this.fromDynamoDBItem(a,e));return T(s)}catch(n){return d(G("find MFA authenticators by method",n))}}async create(e){try{let r={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(r.id=ht());let n=this.toDynamoDBItem(r);return await this.docClient.send(new LO({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(this.fromDynamoDBItem(n,e.userId))}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"MFA authenticator"})):d(G("create MFA authenticator",r))}}async update(e,r,n,i){try{let o=Ss(r,n),s=[],a={},c={};if(i.label!==void 0&&(s.push("#label = :label"),a["#label"]="label",c[":label"]=i.label),i.data!==void 0&&(s.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(i.data)),i.verifiedAt!==void 0&&(s.push("#verifiedAt = :verifiedAt"),a["#verifiedAt"]="verifiedAt",c[":verifiedAt"]=i.verifiedAt instanceof Date?i.verifiedAt.getTime():i.verifiedAt===null?void 0:i.verifiedAt),i.lastUsedAt!==void 0&&(s.push("#lastUsedAt = :lastUsedAt"),a["#lastUsedAt"]="lastUsedAt",c[":lastUsedAt"]=i.lastUsedAt instanceof Date?i.lastUsedAt.getTime():i.lastUsedAt===null?void 0:i.lastUsedAt),i.failedAttempts!==void 0&&(s.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=i.failedAttempts),i.lastFailedAt!==void 0&&(s.push("#lastFailedAt = :lastFailedAt"),a["#lastFailedAt"]="lastFailedAt",c[":lastFailedAt"]=i.lastFailedAt instanceof Date?i.lastFailedAt.getTime():i.lastFailedAt===null?void 0:i.lastFailedAt),i.lockedUntil!==void 0&&(s.push("#lockedUntil = :lockedUntil"),a["#lockedUntil"]="lockedUntil",c[":lockedUntil"]=i.lockedUntil instanceof Date?i.lockedUntil.getTime():i.lockedUntil===null?void 0:i.lockedUntil),i.metadata!==void 0&&(s.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(i.metadata)),s.length===0)return T(void 0);let l={TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:o},UpdateExpression:`SET ${s.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new rh(l)),T(void 0)}catch(o){return d(G("update MFA authenticator",o))}}async remove(e,r,n){try{let i=Ss(r,n);return await this.docClient.send(new PO({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:i}})),T(void 0)}catch(i){return d(G("remove MFA authenticator",i))}}async incrementFailedAttempts(e,r,n,i,o){try{let s=Ss(r,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],l={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},u={":zero":0,":inc":1,":lastFailedAt":a};o!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),l["#lockedUntil"]="lockedUntil",u[":lockedUntil"]=a+o*60*1e3,u[":maxAttempts"]=i);let p={TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:s},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:l,ExpressionAttributeValues:u};return await this.docClient.send(new rh(p)),T(void 0)}catch(s){return d(G("increment failed attempts",s))}}async resetFailedAttempts(e,r,n){try{let i=Ss(r,n),o={TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:i},UpdateExpression:"SET #failedAttempts = :zero REMOVE #lastFailedAt, #lockedUntil",ExpressionAttributeNames:{"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt","#lockedUntil":"lockedUntil"},ExpressionAttributeValues:{":zero":0}};return await this.docClient.send(new rh(o)),T(void 0)}catch(i){return d(G("reset failed attempts",i))}}async unlock(e,r,n){return this.resetFailedAttempts(e,r,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};import{DeleteCommand as MO,DynamoDBDocumentClient as KO,GetCommand as HO,PutCommand as FO,QueryCommand as HT,UpdateCommand as FT}from"@aws-sdk/lib-dynamodb";var Ic=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=KO.from(e)}generateUserId(){return ht()}async getById(e){try{let r=await this.docClient.send(new HO({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:U.USER_PROFILE_SK()}}));if(!r.Item)return T(null);let n=r.Item;if(n.deletedAt)return T(null);let o={id:le.userId(n.PK),status:n.userStatus,createdAt:J(n.createdAt),updatedAt:J(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:J(n.deletedAt)},...n.contactEmail!==void 0&&{contactEmail:n.contactEmail},...n.contactPhone!==void 0&&{contactPhone:n.contactPhone},...n.username!==void 0&&{username:n.username},...n.displayName!==void 0&&{displayName:n.displayName},...n.givenName!==void 0&&{givenName:n.givenName},...n.familyName!==void 0&&{familyName:n.familyName},...n.avatarUrl!==void 0&&{avatarUrl:n.avatarUrl},...n.locale!==void 0&&{locale:n.locale},...n.metadata!==void 0&&{metadata:JSON.parse(n.metadata)}};return T(o)}catch(r){return d(G("getById user",r))}}async create(e){try{let r=ae(),n=e.id||this.generateUserId(),i=e.status||"pending",o={PK:U.USER_PK(n),SK:U.USER_PROFILE_SK(),userStatus:i,createdAt:r,updatedAt:r};e.contactEmail&&(o.contactEmail=e.contactEmail),e.contactPhone&&(o.contactPhone=e.contactPhone),e.username&&(o.username=e.username),e.displayName&&(o.displayName=e.displayName),e.givenName&&(o.givenName=e.givenName),e.familyName&&(o.familyName=e.familyName),e.avatarUrl&&(o.avatarUrl=e.avatarUrl),e.locale&&(o.locale=e.locale),e.metadata&&(o.metadata=JSON.stringify(e.metadata)),o[h.USER_STATUS_PK]=Ae.USER_STATUS_PK(i),o[h.USER_STATUS_SK]=Ae.USER_STATUS_SK(n),await this.docClient.send(new FO({TableName:this.tableName,Item:Ht(o),ConditionExpression:qm("PK")}));let s={id:n,status:i,createdAt:J(r),updatedAt:J(r),...e.contactEmail&&{contactEmail:e.contactEmail},...e.contactPhone&&{contactPhone:e.contactPhone},...e.username&&{username:e.username},...e.displayName&&{displayName:e.displayName},...e.givenName&&{givenName:e.givenName},...e.familyName&&{familyName:e.familyName},...e.avatarUrl&&{avatarUrl:e.avatarUrl},...e.locale&&{locale:e.locale},...e.metadata&&{metadata:e.metadata}};return T(s)}catch(r){return d(G("create user",r))}}async updateProfile(e,r){try{let n=ae(),i={};if(r.contactEmail!==void 0&&(i.contactEmail=r.contactEmail),r.contactPhone!==void 0&&(i.contactPhone=r.contactPhone),r.displayName!==void 0&&(i.displayName=r.displayName),r.givenName!==void 0&&(i.givenName=r.givenName),r.familyName!==void 0&&(i.familyName=r.familyName),r.avatarUrl!==void 0&&(i.avatarUrl=r.avatarUrl),r.locale!==void 0&&(i.locale=r.locale),r.metadata!==void 0&&(i.metadata=JSON.stringify(r.metadata)),Object.keys(i).length===0)return T(void 0);i.updatedAt=n;let o=Dr(i);return await this.docClient.send(new FT({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:U.USER_PROFILE_SK()},UpdateExpression:o.UpdateExpression,ExpressionAttributeNames:o.ExpressionAttributeNames,ExpressionAttributeValues:o.ExpressionAttributeValues})),T(void 0)}catch(n){return d(G("updateProfile",n))}}async getByStatus(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return d(te.DatabaseQueryError({query:"invalid pagination cursor"}))}let o=Ae.USER_STATUS_PK(e),s=await this.docClient.send(new HT({TableName:this.tableName,IndexName:ue.USERS_BY_STATUS,KeyConditionExpression:`${h.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":o},Limit:n,ExclusiveStartKey:i})),a=[];if(s.Items&&s.Items.length>0)for(let u of s.Items){let p=le.userId(u.PK);a.push(p)}let c=!!s.LastEvaluatedKey,l=c?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null;return T(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!r?.cursor,cursor:l}})}catch(n){return d(G("get users by status",n))}}async countByStatus(e){try{let r=Ae.USER_STATUS_PK(e),n=await this.docClient.send(new HT({TableName:this.tableName,IndexName:ue.USERS_BY_STATUS,KeyConditionExpression:`${h.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":r},Select:"COUNT"}));return T(n.Count||0)}catch(r){return d(G("count users by status",r))}}async syncAuthStatus(e,r){try{let n=ae(),i=`SET userStatus = :userStatus, #${h.UPDATED_AT} = :updatedAt, #${h.USER_STATUS_PK} = :statusPk, #${h.USER_STATUS_SK} = :statusSk`,o={":userStatus":r,":updatedAt":n,":statusPk":Ae.USER_STATUS_PK(r),":statusSk":Ae.USER_STATUS_SK(e)};return r===ye.DELETED?(i+=", deletedAt = :deletedAt",o[":deletedAt"]=n):i+=" REMOVE deletedAt",await this.docClient.send(new FT({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:U.USER_PROFILE_SK()},UpdateExpression:i,ExpressionAttributeNames:{[`#${h.UPDATED_AT}`]:h.UPDATED_AT,[`#${h.USER_STATUS_PK}`]:h.USER_STATUS_PK,[`#${h.USER_STATUS_SK}`]:h.USER_STATUS_SK},ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userProfile",id:e})):d(G("sync auth status",n))}}async remove(e){try{return await this.docClient.send(new MO({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:U.USER_PROFILE_SK()}})),T(void 0)}catch(r){return d(G("remove user profile",r))}}};import{DeleteCommand as VO,DynamoDBDocumentClient as BO,GetCommand as jO,PutCommand as GO,QueryCommand as $O,UpdateCommand as qO}from"@aws-sdk/lib-dynamodb";var xc=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=BO.from(e)}mapItemToUserProviderLink(e){let r=le.providerPKInfo(e.PK);if(!r)throw new Error(`Invalid provider PK: ${e.PK}`);let n={userId:e.userId,provider:r.provider,externalId:r.externalId,createdAt:J(e.createdAt)};if(e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata)try{n.metadata=JSON.parse(e.metadata)}catch{}return n}mapUserProviderLinkToItem(e){let r=ae(),n={PK:U.PROVIDER_PK(e.provider,e.externalId),SK:U.PROVIDER_METADATA_SK(),userProviderPk:U.USER_PK(e.userId),userProviderSk:U.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?re(e.createdAt):r};return e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),Ht(n)}async findByProviderAndExternalId(e,r){try{let n=await this.docClient.send(new jO({TableName:this.tableName,Key:{PK:U.PROVIDER_PK(e,r),SK:U.PROVIDER_METADATA_SK()}}));return n.Item?T(this.mapItemToUserProviderLink(n.Item)):T(null)}catch(n){return d(G("find provider by external id",n))}}async findByUserId(e){try{let r=await this.docClient.send(new $O({TableName:this.tableName,IndexName:ue.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":h.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":U.USER_PK(e)}}));return!r.Items||r.Items.length===0?T([]):T(r.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch(r){return d(G("find providers by user id",r))}}async create(e){try{let r={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(r);return await this.docClient.send(new GO({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),T(this.mapItemToUserProviderLink(n))}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):d(G("create user provider",r))}}async update(e,r,n){try{let i={};if(n.externalUsername!==void 0&&(i.externalUsername=n.externalUsername),n.externalEmail!==void 0&&(i.externalEmail=n.externalEmail),n.externalPhone!==void 0&&(i.externalPhone=n.externalPhone),n.externalName!==void 0&&(i.externalName=n.externalName),n.externalAvatarUrl!==void 0&&(i.externalAvatarUrl=n.externalAvatarUrl),n.metadata!==void 0&&(i.metadata=JSON.stringify(n.metadata)),Object.keys(i).length===0)return T(void 0);let{UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a}=Dr(i);return await this.docClient.send(new qO({TableName:this.tableName,Key:{PK:U.PROVIDER_PK(e,r),SK:U.PROVIDER_METADATA_SK()},UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a})),T(void 0)}catch(i){return d(G("update user provider",i))}}async remove(e,r){try{return await this.docClient.send(new VO({TableName:this.tableName,Key:{PK:U.PROVIDER_PK(e,r),SK:U.PROVIDER_METADATA_SK()}})),T(void 0)}catch(n){return d(G("delete user provider",n))}}};import{DeleteCommand as WO,GetCommand as zO,PutCommand as JO,UpdateCommand as YO}from"@aws-sdk/lib-dynamodb";var bc=class{docClient;tableName;constructor(e,r){this.docClient=e,this.tableName=r}mapItemToEntity(e){let r=le.tenantId(e.PK),n=le.tenantProfileUserId(e.SK),i={tenantId:r,userId:n,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r){try{let n=await this.docClient.send(new zO({TableName:this.tableName,Key:{PK:U.TENANT_PROFILE_PK(e),SK:U.TENANT_PROFILE_SK(r)}}));return n.Item?T(this.mapItemToEntity(n.Item)):T(null)}catch(n){return d(G("get user tenant profile",n))}}async create(e){try{let r=ae(),n={PK:U.TENANT_PROFILE_PK(e.tenantId),SK:U.TENANT_PROFILE_SK(e.userId),createdAt:r,updatedAt:r};e.contactEmail&&(n.contactEmail=e.contactEmail),e.contactPhone&&(n.contactPhone=e.contactPhone),e.displayName&&(n.displayName=e.displayName),e.displayNameSource&&(n.displayNameSource=e.displayNameSource),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.locale&&(n.locale=e.locale),e.jobTitle&&(n.jobTitle=e.jobTitle),e.bio&&(n.bio=e.bio),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),await this.docClient.send(new JO({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let i={tenantId:e.tenantId,userId:e.userId,createdAt:J(r),updatedAt:J(r)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=e.metadata),T(i)}catch(r){return r.name==="ConditionalCheckFailedException"?d(te.UniqueConstraintViolation({field:"user tenant profile"})):d(Rt("create user tenant profile",r))}}async update(e,r,n){try{let i={updatedAt:ae()};n.contactEmail!==void 0&&(i.contactEmail=n.contactEmail),n.contactPhone!==void 0&&(i.contactPhone=n.contactPhone),n.displayName!==void 0&&(i.displayName=n.displayName),n.displayNameSource!==void 0&&(i.displayNameSource=n.displayNameSource),n.givenName!==void 0&&(i.givenName=n.givenName),n.familyName!==void 0&&(i.familyName=n.familyName),n.avatarUrl!==void 0&&(i.avatarUrl=n.avatarUrl),n.locale!==void 0&&(i.locale=n.locale),n.jobTitle!==void 0&&(i.jobTitle=n.jobTitle),n.bio!==void 0&&(i.bio=n.bio),n.metadata!==void 0&&(i.metadata=n.metadata?JSON.stringify(n.metadata):null);let{UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a}=Dr(i);return await this.docClient.send(new YO({TableName:this.tableName,Key:{PK:U.TENANT_PROFILE_PK(e),SK:U.TENANT_PROFILE_SK(r)},UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):d(Rt("update user tenant profile",i))}}async remove(e,r){try{return await this.docClient.send(new WO({TableName:this.tableName,Key:{PK:U.TENANT_PROFILE_PK(e),SK:U.TENANT_PROFILE_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):d(Rt("remove user tenant profile",n))}}};var nh=class{name="database-dynamodb";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;registration;userAuths;tenantMembers;tenantInvites;userTenantProfiles;tenants;queries;client;tableName;constructor(e){this.tableName=e.tableName,this.client=e.client||new QO(e.clientConfig||{});let r=ZO.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new Ic(this.client,this.tableName),this.sessions=new mc({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new xc(this.client,this.tableName),this.userMfaAuthenticators=new _c(this.client,this.tableName),this.challenges=new lc({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new dc({docClient:r,tableName:this.tableName}),this.credentials=new uc({docClient:r,tableName:this.tableName}),this.registration=new pc({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new Tc({docClient:r,tableName:this.tableName}),this.tenantMembers=new gc(this.client,this.tableName),this.tenantInvites=new Ec({docClient:r,tableName:this.tableName}),this.userTenantProfiles=new bc(r,this.tableName),this.tenants=new Ac({docClient:r,tableName:this.tableName}),this.queries={tenantInvites:new hc({docClient:r,tableName:this.tableName}),tenantMembers:new yc({docClient:r,tableName:this.tableName}),tenants:new vc({docClient:r,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new XO({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};function VT(t){return new nh(t)}ra();var ih=1,BT=2,jT=3,GT="auth-craft:internal";async function ek(t){let e=t.replace(/^0x/,""),r=qT(e),n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length);let o=`-----BEGIN PRIVATE KEY-----
131
+ `}};var oc=class t{static createDirectSmtp(e){return new cd(e)}static create(e){return t.createDirectSmtp(e.smtp)}};var f0={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function sT(t={}){let e={...f0,...t},n=(()=>{if(t.customRegex)return t.customRegex;let i="[a-zA-Z0-9_\\-]";e.allowDots?(i+="+",i=`(${i}\\.?)+`):i+="+",e.allowPlusAddressing&&(i=`${i}(\\+[a-zA-Z0-9_\\-]+)?`);let o=e.requireTLD?"(?:[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}":"[a-zA-Z0-9][a-zA-Z0-9\\-\\.]*";return new RegExp(`^${i}@${o}$`)})();return{name:"email-identity",version:"1.0.0",identityType:"email",normalize(i){return i.toLowerCase().trim()},validate(i){if(!i||i.trim().length===0)return d([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(i.length>254)return d([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(i))return d([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(i.includes(".."))return d([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let o=i.split("@");if(o.length!==2)return d([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[s,a]=o;return!s||s.length>64?d([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?d([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):T()}}}function Lm(t=6){let e="";for(;e.length<t;){let r=new Uint8Array(t);crypto.getRandomValues(r);for(let n=0;n<r.length&&e.length<t;n++){let i=r[n];i>=250||(e+=(i%10).toString())}}return e}function m0(t){return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function Mm(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return m0(r)}var Km="email",ld={EMAIL_SYSTEM_NOT_AVAILABLE:_("MFA_EMAIL_SYSTEM_NOT_AVAILABLE","Email system is not configured"),RECIPIENT_NOT_FOUND:_("MFA_EMAIL_RECIPIENT_NOT_FOUND","No email address on file for this user"),SEND_FAILED:_("MFA_EMAIL_SEND_FAILED","Failed to send the verification email"),USE_CHALLENGE_CODE_HASH:_("MFA_EMAIL_USE_CHALLENGE_CODE_HASH","Email MFA codes are verified against the challenge code hash, not stored credentials")};function h0(t){let[e,r]=t.split("@");return!e||!r?"***":`${e.slice(0,1)}***@${r}`}function aT(t={}){let e=t.codeLength??6,r=t.template??"mfa-email-code";return{name:"email-mfa",version:"1.0.0",method:Km,requiresServerDelivery:!0,async sendCode(n,i){if(!i.plugins.emailSystem)return d(ld.EMAIL_SYSTEM_NOT_AVAILABLE());let o=await i.plugins.database.users.getById(n.userId),s=o.ok&&o.data?o.data.contactEmail:void 0;if(!s)return d(ld.RECIPIENT_NOT_FOUND());let a=Lm(e),c=await Mm(a);return(await i.plugins.emailSystem.send({to:s,template:r,variables:{code:a,purpose:"mfa"}})).ok===!1?d(ld.SEND_FAILED()):T({codeHash:c,maskedRecipient:h0(s)})},async issueChallenge(n){return T({challengeId:`email_${Date.now()}`,methods:n.availableMethods.includes(Km)?[Km]:n.availableMethods,expiresAt:new Date(Date.now()+300*1e3)})},async verify(){return d(ld.USE_CHALLENGE_CODE_HASH())}}}var cT="ABCDEFGHIJKLMNPQRSTUVWXYZ23456789";function ud(t=10,e=10){let r=[];for(let n=0;n<t;n++){let i=new Uint8Array(e);crypto.getRandomValues(i);let o="";for(let s of i)o+=cT[s%cT.length];r.push(o)}return r}function E0(t){return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function dd(t){let e=new TextEncoder().encode(t.toUpperCase().trim()),r=await crypto.subtle.digest("SHA-256",e);return E0(r)}function y0(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function Hm(t,e){let r=await dd(t),n=null;for(let i of e)y0(r,i)&&(n=i);return n}var Fm="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function lT(t){let e=t.toUpperCase().replace(/=+$/u,"").replace(/\s+/gu,""),r=0,n=0,i=[];for(let o of e){let s=Fm.indexOf(o);if(s===-1)throw new Error("Invalid base32 character in TOTP secret");n=n<<5|s,r+=5,r>=8&&(r-=8,i.push(n>>>r&255))}return new Uint8Array(i)}function uT(t){let e=0,r=0,n="";for(let i of t)for(r=r<<8|i,e+=8;e>=5;)e-=5,n+=Fm[r>>>e&31];return e>0&&(n+=Fm[r<<5-e&31]),n}function pd(t=20){let e=new Uint8Array(t);return crypto.getRandomValues(e),uT(e)}function g0(t){let e=new Uint8Array(8),r=t;for(let n=7;n>=0;n--)e[n]=r&255,r=Math.floor(r/256);return e}async function v0(t,e,r){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-1"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",n,g0(e))),o=i[i.length-1]&15;return(((i[o]&127)<<24|(i[o+1]&255)<<16|(i[o+2]&255)<<8|i[o+3]&255)%10**r).toString().padStart(r,"0")}async function fd(t,e,r=Date.now(),n={}){let i=n.period??30,o=n.digits??6,s=n.window??1,a=e.trim();if(a.length!==o||!/^\d+$/u.test(a))return!1;let c=lT(t),l=Math.floor(r/1e3/i),u=!1;for(let p=-s;p<=s;p++){let f=await v0(c,l+p,o);A0(f,a)&&(u=!0)}return u}function A0(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}function dT(t){let e=encodeURIComponent(`${t.issuer}:${t.accountName}`),r=new URLSearchParams({secret:t.secretBase32,issuer:t.issuer,algorithm:"SHA1",digits:String(t.digits??6),period:String(t.period??30)});return`otpauth://totp/${e}?${r.toString()}`}var Vm="totp",T0={USE_VERIFY_WITH_CREDENTIALS:{code:"TOTP_USE_VERIFY_WITH_CREDENTIALS",message:"TOTP verification requires credential data; call verifyWithCredentials()"}};function pT(t={}){let e=t.issuer??"Auth Craft",r=t.backupCodeCount??10,n=t.window??1;return{name:"totp-mfa",version:"1.0.0",method:Vm,requiresServerDelivery:!1,generateSecret(){return pd()},generateBackupCodes(i){return ud(i||r)},async issueChallenge(i){return T({challengeId:`totp_${Date.now()}`,methods:i.availableMethods.includes(Vm)?[Vm]:i.availableMethods,expiresAt:new Date(Date.now()+300*1e3)})},async verify(){return d(T0.USE_VERIFY_WITH_CREDENTIALS)},async setup(i){let o=pd(),s=ud(r),a=await Promise.all(s.map(p=>dd(p))),c=i.data.accountName??i.userId,l=dT({secretBase32:o,accountName:c,issuer:e});return T({secret:o,otpauthUri:l,backupCodes:s,credentialData:{secret:o,backupCodeHashes:a}})},async verifyWithCredentials(i){let o=i.credentialData,s=i.data.code?.trim();if(!s||!o?.secret)return T({verified:!1,data:{}});if(await fd(o.secret,s,Date.now(),{window:n}))return T({verified:!0,data:{}});let c=o.backupCodeHashes??[];if(c.length>0){let l=await Hm(s,c);if(l)return T({verified:!0,data:{usedBackupCodeHash:l}})}return T({verified:!1,data:{}})},async verifyCredential(i,o){let s=i.data.code,a=i.data.secret;if(!s||!a)return T({verified:!1,data:{}});let c=await fd(a,s,Date.now(),{window:n});return T({verified:c,data:{}})}}}var Bm={scopes:["email","public_profile"],apiVersion:"v18.0"};var Zr={INVALID_CODE:_("FACEBOOK_INVALID_CODE","Invalid authorization code"),TOKEN_EXCHANGE_FAILED:_("FACEBOOK_TOKEN_EXCHANGE_FAILED","Failed to exchange code for token"),USER_PROFILE_FAILED:_("FACEBOOK_USER_PROFILE_FAILED","Failed to fetch user profile"),INVALID_TOKEN:_("FACEBOOK_INVALID_TOKEN","Invalid access token"),MISSING_CONFIG:_("FACEBOOK_MISSING_CONFIG","Missing required Facebook OAuth configuration")};function jm(t={}){let{scopes:e=Bm.scopes,apiVersion:r=Bm.apiVersion}=t,n={AUTHORIZATION:`https://www.facebook.com/${r}/dialog/oauth`,TOKEN:`https://graph.facebook.com/${r}/oauth/access_token`,USER_INFO:`https://graph.facebook.com/${r}/me`,DEBUG_TOKEN:`https://graph.facebook.com/${r}/debug_token`};return{name:"facebook-oauth-provider",version:"1.0.0",getAuthorizationUrl(i,o){let s=new URLSearchParams({client_id:i.clientId,redirect_uri:i.redirectUri,scope:(i.scopes??e).join(","),response_type:"code",...o&&{state:o}});return`${n.AUTHORIZATION}?${s.toString()}`},async exchangeCodeForToken(i,o){try{if(!i)return d(Zr.INVALID_CODE());let s=new URLSearchParams({client_id:o.clientId,client_secret:o.clientSecret,code:i,redirect_uri:o.redirectUri}),a=await fetch(`${n.TOKEN}?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return d(Zr.TOKEN_EXCHANGE_FAILED());let c=await a.json();return T({accessToken:c.access_token,...c.expires_in&&{expiresIn:c.expires_in}})}catch(s){return console.error("Facebook token exchange error:",s),d(Zr.TOKEN_EXCHANGE_FAILED())}},async getUserProfile(i){try{if(!i)return d(Zr.INVALID_TOKEN());let o=["id","email","name","first_name","last_name","picture","locale"],s=new URLSearchParams({fields:o.join(","),access_token:i}),a=await fetch(`${n.USER_INFO}?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return d(Zr.USER_PROFILE_FAILED());let c=await a.json(),l={id:c.id,...c.email&&{email:c.email},...c.email&&{emailVerified:!1},...c.name&&{name:c.name},...c.first_name&&{givenName:c.first_name},...c.last_name&&{familyName:c.last_name},...c.picture?.data?.url&&{avatarUrl:c.picture.data.url},...c.locale&&{locale:c.locale},provider:"facebook"};return T(l)}catch(o){return console.error("Facebook user profile error:",o),d(Zr.USER_PROFILE_FAILED())}},async verifyAccessToken(i){try{if(!i)return d(Zr.INVALID_TOKEN());let o=`${t.appId}|${t.appSecret}`,s=new URLSearchParams({input_token:i,access_token:o}),a=await fetch(`${n.DEBUG_TOKEN}?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}});return a.ok?(await a.json()).data.is_valid?this.getUserProfile(i):d(Zr.INVALID_TOKEN()):d(Zr.INVALID_TOKEN())}catch(o){return console.error("Facebook token verification error:",o),d(Zr.INVALID_TOKEN())}}}}var md={scopes:["openid","email","profile"],accessType:"online",includeGrantedScopes:!1},Ji={AUTHORIZATION:"https://accounts.google.com/o/oauth2/v2/auth",TOKEN:"https://oauth2.googleapis.com/token",USER_INFO:"https://www.googleapis.com/oauth2/v2/userinfo",TOKEN_INFO:"https://oauth2.googleapis.com/tokeninfo",REVOKE:"https://oauth2.googleapis.com/revoke"};var tt={INVALID_CODE:_("GOOGLE_INVALID_CODE","Invalid authorization code"),TOKEN_EXCHANGE_FAILED:_("GOOGLE_TOKEN_EXCHANGE_FAILED","Failed to exchange code for token"),USER_PROFILE_FAILED:_("GOOGLE_USER_PROFILE_FAILED","Failed to fetch user profile"),INVALID_TOKEN:_("GOOGLE_INVALID_TOKEN","Invalid access token"),INVALID_CREDENTIAL:_("GOOGLE_INVALID_CREDENTIAL","Invalid ID token or credential"),CREDENTIAL_VERIFICATION_FAILED:_("GOOGLE_CREDENTIAL_VERIFICATION_FAILED","Failed to verify credential"),REFRESH_TOKEN_FAILED:_("GOOGLE_REFRESH_TOKEN_FAILED","Failed to refresh access token"),MISSING_CONFIG:_("GOOGLE_MISSING_CONFIG","Missing required Google OAuth configuration")};function _0(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;if(r){if(r===1)throw new Error("Invalid base64url string");e+=new Array(5-r).join("=")}try{return decodeURIComponent(atob(e).split("").map(n=>`%${`00${n.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""))}catch{throw new Error("Failed to decode base64url")}}function I0(t){try{let e=t.split(".");if(e.length!==3)return null;let r=e[1];if(!r)return null;let n=_0(r);return JSON.parse(n)}catch(e){return console.error("Failed to decode JWT:",e),null}}function Gm(t={}){let{clientId:e,clientSecret:r,redirectUri:n,scopes:i=md.scopes,accessType:o=md.accessType,includeGrantedScopes:s=md.includeGrantedScopes,prompt:a}=t;return{name:"google-oauth-provider",version:"1.0.0",getAuthorizationUrl(c,l){let u=c?.clientId??e,p=c?.redirectUri??n;if(!u||!p)throw new Error("Google OAuth: clientId and redirectUri are required");let f=new URLSearchParams({client_id:u,redirect_uri:p,response_type:"code",scope:(c?.scopes??i).join(" "),access_type:o,...l&&{state:l},...a&&{prompt:a},...s&&{include_granted_scopes:"true"}});return`${Ji.AUTHORIZATION}?${f.toString()}`},async exchangeCodeForToken(c,l){let u=l?.clientId??e,p=l?.clientSecret??r,f=l?.redirectUri??n;try{if(!c)return d(tt.INVALID_CODE());if(!u||!p||!f)return d(tt.MISSING_CONFIG());let m=new URLSearchParams({client_id:u,client_secret:p,code:c,redirect_uri:f,grant_type:"authorization_code"}),E=await fetch(Ji.TOKEN,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:m.toString()});if(!E.ok)return console.error("Google token exchange failed with status:",E.status),d(tt.TOKEN_EXCHANGE_FAILED());let v=await E.json();return T({accessToken:v.access_token,...v.refresh_token&&{refreshToken:v.refresh_token},...v.expires_in&&{expiresIn:v.expires_in}})}catch(m){return console.error("Google token exchange error:",m),d(tt.TOKEN_EXCHANGE_FAILED())}},async getUserProfile(c){try{if(!c)return d(tt.INVALID_TOKEN());let l=await fetch(Ji.USER_INFO,{method:"GET",headers:{Authorization:`Bearer ${c}`,Accept:"application/json"}});if(!l.ok)return console.error("Google user profile failed with status:",l.status),d(tt.USER_PROFILE_FAILED());let u=await l.json(),p={id:u.id,...u.email&&{email:u.email},...u.verified_email!==void 0&&{emailVerified:u.verified_email},...u.name&&{name:u.name},...u.given_name&&{givenName:u.given_name},...u.family_name&&{familyName:u.family_name},...u.picture&&{avatarUrl:u.picture},...u.locale&&{locale:u.locale},provider:"google"};return T(p)}catch(l){return console.error("Google user profile error:",l),d(tt.USER_PROFILE_FAILED())}},async verifyAccessToken(c){try{if(!c)return d(tt.INVALID_TOKEN());let l=await fetch(`${Ji.TOKEN_INFO}?access_token=${c}`,{method:"GET",headers:{Accept:"application/json"}});if(!l.ok)return d(tt.INVALID_TOKEN());let u=await l.json();return parseInt(u.expires_in,10)<=0?d(tt.INVALID_TOKEN()):this.getUserProfile(c)}catch(l){return console.error("Google token verification error:",l),d(tt.INVALID_TOKEN())}},async verifyCredential(c){try{if(!c)return d(tt.INVALID_CREDENTIAL());let l=await fetch(`${Ji.TOKEN_INFO}?id_token=${encodeURIComponent(c)}`,{method:"GET",headers:{Accept:"application/json"}});if(!l.ok)return console.error("Google credential verification failed with status:",l.status),d(tt.INVALID_CREDENTIAL());let u=await l.json();if(!e)return d(tt.MISSING_CONFIG());if(u.aud!==e)return d(tt.INVALID_CREDENTIAL());if(parseInt(u.expires_in,10)<=0)return d(tt.INVALID_CREDENTIAL());let f=u.email_verified==="true",m=I0(c),E={id:u.sub,...u.email&&{email:u.email},...u.email&&{emailVerified:f},...m?.name&&{name:m.name},...m?.given_name&&{givenName:m.given_name},...m?.family_name&&{familyName:m.family_name},...m?.picture&&{avatarUrl:m.picture},...m?.locale&&{locale:m.locale},provider:"google"};return T(E)}catch(l){return console.error("Google credential verification error:",l),d(tt.CREDENTIAL_VERIFICATION_FAILED())}},async refreshAccessToken(c,l){let u=l?.clientId??e,p=l?.clientSecret??r;try{if(!c)return d(tt.INVALID_TOKEN());if(!u||!p)return d(tt.MISSING_CONFIG());let f=new URLSearchParams({client_id:u,client_secret:p,refresh_token:c,grant_type:"refresh_token"}),m=await fetch(Ji.TOKEN,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:f.toString()});if(!m.ok)return console.error("Google refresh token failed with status:",m.status),d(tt.REFRESH_TOKEN_FAILED());let E=await m.json();return T({accessToken:E.access_token,...E.expires_in&&{expiresIn:E.expires_in}})}catch(f){return console.error("Google refresh token error:",f),d(tt.REFRESH_TOKEN_FAILED())}}}}function fT(t={}){let e=new Map,r=t.sweepIntervalMs??6e4,n=0,i;function o(){if(n===0)return;let s=Date.now()-n;for(let[a,c]of e){let l=c.hits.filter(u=>u>s);l.length===0?e.delete(a):c.hits=l}}return r>0&&(i=setInterval(o,r),i.unref?.()),{name:"rate-limiter-memory",version:"1.0.0",async consume(s,a){let{limit:c,windowMs:l}=a;l>n&&(n=l);let u=Date.now(),p=u-l,f=e.get(s)??{hits:[]},m=f.hits.filter(E=>E>p);if(m.length>=c){let E=m[0]??u,v=Math.max(0,E+l-u);return f.hits=m,e.set(s,f),{allowed:!1,remaining:0,retryAfterMs:v,limit:c}}return m.push(u),f.hits=m,e.set(s,f),{allowed:!0,remaining:c-m.length,retryAfterMs:0,limit:c}},async reset(s){e.delete(s)},async cleanup(){i&&clearInterval(i),e.clear()}}}import{DescribeTableCommand as XO,DynamoDBClient as QO}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as ZO}from"@aws-sdk/lib-dynamodb";var te={DatabaseConnectionError:_("DATABASE_CONNECTION_ERROR","Failed to connect to database"),DatabaseQueryError:Q("DATABASE_QUERY_ERROR","Database query execution failed: {query}"),NotFound:Q("REPOSITORY_NOT_FOUND","{entity} with {id} not found"),UniqueConstraintViolation:Q("UNIQUE_CONSTRAINT_VIOLATION","Record with this {field} already exists"),ForeignKeyViolation:Q("FOREIGN_KEY_VIOLATION","Referenced {field} does not exist"),RecordLocked:_("RECORD_LOCKED","Record is currently locked by another operation"),DeadlockDetected:_("DEADLOCK_DETECTED","Transaction deadlock detected"),InvalidData:Q("INVALID_DATA","Invalid data: {reason}"),Timeout:_("REPOSITORY_TIMEOUT","Database operation timed out"),AttemptsExceeded:_("ATTEMPTS_EXCEEDED","Attempt limit reached"),TransactionFailed:Q("TRANSACTION_FAILED","Transaction failed: {reason}"),UnknownError:Q("REPOSITORY_UNKNOWN_ERROR","Unexpected database error: {message}")};function re(t){return t.getTime()}function J(t){return new Date(t)}function mT(t){return Math.floor(t/1e3)}function ae(){return Date.now()}function sc(t){return t instanceof Date?mT(t.getTime()):mT(t)}function $m(t){return t<Date.now()}function Cr(t){return t?re(t):null}function Kt(t){return t==null?null:J(t)}function Ht(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}function Dr(t){let e=[],r=[],n={},i={},o=0;for(let[c,l]of Object.entries(t)){if(c==="PK"||c==="SK")continue;let u=`#${c}`;if(n[u]=c,l==null)r.push(u);else{let p=`:val${o}`;e.push(`${u} = ${p}`),i[p]=l,o++}}let s=[];return e.length>0&&s.push(`SET ${e.join(", ")}`),r.length>0&&s.push(`REMOVE ${r.join(", ")}`),{UpdateExpression:s.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:i}}function qm(t="PK"){return`attribute_not_exists(${t})`}var Wm={USER:"USR"},ce={USER:`${Wm.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},Be={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},Tt="#",U={USER_PK:t=>`${ce.USER}${t}`,USER_AUTH_SK:()=>Be.AUTH,USER_PROFILE_SK:()=>Be.PROFILE,USER_MFA_SK:t=>`${Be.MFA}${t}`,USER_MFA_WITH_ID_SK:(t,e)=>`${Be.MFA}${t}${Tt}${e}`,TENANT_MEMBER_PK:t=>`${ce.TENANT}${t}`,TENANT_MEMBER_SK:t=>`${ce.USER}${t}`,TENANT_OWNER_MARKER_SK:()=>Be.OWNER,TENANT_PK:t=>`${ce.TENANT}${t}`,TENANT_SK:()=>Be.METADATA,INVITE_PK:t=>`${ce.INVITE}${t}`,INVITE_SK:()=>Be.METADATA,TENANT_PROFILE_PK:t=>`${ce.TENANT}${t}`,TENANT_PROFILE_SK:t=>`${Be.TENANT_PROFILE}${ce.USER}${t}`,SESSION_PK:t=>`${ce.SESSION}${t}`,SESSION_METADATA_SK:()=>Be.METADATA,SESSION_SK:()=>Be.METADATA,PROVIDER_SK:(t,e)=>`${Be.PROVIDER}${t}${Tt}${e}`,PROVIDER_PK:(t,e)=>`${ce.PROVIDER}${t}${Tt}${e}`,PROVIDER_METADATA_SK:()=>Be.METADATA,CHALLENGE_PK:t=>`${ce.CHALLENGE}${t}`,CHALLENGE_SK:()=>Be.METADATA,IDENTITY_PK:(t,e)=>`${ce.IDENTITY}${t}#${e}`,IDENTITY_SK:()=>Be.METADATA,CREDENTIAL_PK:t=>`${ce.CREDENTIAL}${t}`,CREDENTIAL_SK:()=>Be.METADATA,CREDENTIAL_TYPE_PREFIX:t=>`${ce.CREDENTIAL}${t}#`,CREDENTIAL_USER_SK:(t,e)=>`${ce.CREDENTIAL}${t}#${e}`,USER_INDEX_PK:t=>`${ce.USER}${t}`,USER_INDEX_SK:(t,e)=>`${ce.IDENTITY}${t}#${e}`},le={userId:t=>t.slice(ce.USER.length),sessionId:t=>t.slice(ce.SESSION.length),providerPKInfo:t=>{let e=t.slice(ce.PROVIDER.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},providerInfo:t=>{let e=t.slice(Be.PROVIDER.length),r=e.indexOf(Tt);if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},mfaSKInfo:t=>{let e=t.slice(Be.MFA.length),r=e.indexOf(Tt);if(r===-1)return{method:e};let n=e.slice(0,r),i=e.slice(r+1);return{method:n,id:i}},tenantId:t=>t.slice(ce.TENANT.length),tenantMemberUserId:t=>t.slice(ce.USER.length),challengeIdFromPK:t=>t.slice(ce.CHALLENGE.length),inviteId:t=>t.slice(ce.INVITE.length),tenantProfileUserId:t=>t.slice(Be.TENANT_PROFILE.length+ce.USER.length),identityPKInfo:t=>{let e=t.slice(ce.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}},credentialId:t=>t.slice(ce.CREDENTIAL.length),credentialTypeFromUserSK:t=>{let e=t.slice(ce.CREDENTIAL.length),r=e.indexOf("#");return r===-1?"":e.slice(0,r)},userIndexSKInfo:t=>{let e=t.slice(ce.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}}};var Ae={ACTIVE_SESSION_PK:t=>`${ce.USER}${t}`,ACTIVE_SESSION_SK:(t,e)=>`${t}${Tt}${e}`,USER_SESSION_PK:t=>`${ce.USER}${t}`,USER_SESSION_SK:(t,e)=>`${t}${Tt}${e}`,USER_STATUS_PK:t=>{let e=t===ye.ACTIVE?"ACTIVE":"INACTIVE";return`${Wm.USER}${Tt}${e}`},USER_STATUS_SK:t=>t,USER_PROVIDER_PK:t=>`${ce.USER}${t}`,USER_PROVIDER_SK:(t,e)=>`${Be.PROVIDER}${t}${Tt}${e}`,INVITE_TENANT_PK:t=>`${ce.TENANT}${t}`,INVITE_TENANT_SK:(t,e,r)=>`${t}${Tt}${e}${Tt}${r}`,INVITE_TENANT_STATUS_PREFIX:t=>`${t}${Tt}`,USER_TENANT_PK:t=>`${ce.USER}${t}`,USER_TENANT_SK:(t,e,r,n)=>`${t}${Tt}${e??"ROOT"}${Tt}${r}${Tt}${n}`},h={PK:"PK",SK:"SK",TTL:"TTL",ACTIVE_SESSION_PK:"activeSessionPk",ACTIVE_SESSION_SK:"activeSessionSk",USER_SESSION_PK:"userSessionPk",USER_SESSION_SK:"userSessionSk",USER_STATUS_PK:"userStatusPk",USER_STATUS_SK:"userStatusSk",USER_PROVIDER_PK:"userProviderPk",USER_PROVIDER_SK:"userProviderSk",USER_ID:"userId",TENANT_ID:"tenantId",TENANT_TYPE:"tenantType",AUDIENCE:"audience",PURPOSE:"purpose",CHALLENGE_STATUS:"challengeStatus",PHASE:"phase",ALLOWED_METHODS:"allowedMethods",METHOD:"method",IDENTITY_TYPE:"identityType",IDENTITY_VALUE:"identityValue",CODE_HASH:"codeHash",ATTEMPTS:"attempts",MAX_ATTEMPTS:"maxAttempts",METADATA:"metadata",FLOW_KEY:"flowKey",EXPIRES_AT:"expiresAt",CREATED_AT:"createdAt",TOKEN_ID:"tokenId",PREVIOUS_TOKEN_ID:"previousTokenId",ROTATED_AT:"rotatedAt",LAST_USED_AT:"lastUsedAt",REVOKED_AT:"revokedAt",ROLE:"role",ROLES:"roles",PERM:"perm",AUTH_PERM:"authPerm",IS_OWNER:"isOwner",DEVICE_LABEL:"deviceLabel",COUNTRY:"country",CITY:"city",IDENTITY_USER_PK:"identityUserPk",IDENTITY_USER_SK:"identityUserSk",LOGIN_ENABLED:"loginEnabled",VERIFIED_AT:"verifiedAt",GUARDS:"guards",PENDING_VERIFICATION:"pendingVerification",UPDATED_AT:"updatedAt",CREDENTIAL_USER_PK:"credentialUserPk",CREDENTIAL_USER_SK:"credentialUserSk",CREDENTIAL_VALUE:"value",INVITE_STATUS:"inviteStatus",INVITE_TOKEN:"inviteToken",INVITED_BY_ID:"invitedById",INVITED_BY_INFO:"invitedByInfo",INVITEE_USER_ID:"inviteeUserId",INVITEE_EMAIL:"inviteeEmail",INVITEE_PHONE:"inviteePhone",ACCEPTED_AT:"acceptedAt",DECLINED_AT:"declinedAt",INVITE_TENANT_PK:"inviteTenantPk",INVITE_TENANT_SK:"inviteTenantSk",INVITE_TOKEN_GSI:"inviteTokenGsi",INVITEE_EMAIL_GSI:"inviteeEmailGsi",INVITEE_EMAIL_TENANT_SK:"inviteeEmailTenantSk",INVITEE_PHONE_GSI:"inviteePhoneGsi",INVITEE_PHONE_TENANT_SK:"inviteePhoneTenantSk",USER_TENANT_PK:"userTenantPk",USER_TENANT_SK:"userTenantSk",DISPLAY_NAME:"displayName",AVATAR_URL:"avatarUrl",TITLE:"title",BIO:"bio"},hd={sessionSK:(t,e)=>`${t instanceof Date?t.getTime():t}${Tt}${e}`,extractCreatedAt:t=>{let e=t.indexOf(Tt),r=e===-1?t:t.slice(0,e);return Number(r)}};var ue={ACTIVE_SESSIONS:"GSI_ActiveSessions",USER_SESSIONS:"GSI_UserSessions",USERS_BY_STATUS:"GSI_UsersByStatus",USER_PROVIDERS:"GSI_UserProviders",USER_IDENTITIES:"GSI_UserIdentities",USER_CREDENTIALS:"GSI_UserCredentials",TENANT_INVITES:"GSI_TenantInvites",INVITE_TOKEN:"GSI_InviteToken",INVITEE_EMAIL:"GSI_InviteeEmail",INVITEE_PHONE:"GSI_InviteePhone",USER_TENANTS:"GSI_UserTenants"},We="S",x0={partitionKey:{name:"PK",type:We},sortKey:{name:"SK",type:We},ttlAttribute:"TTL",globalSecondaryIndexes:[{indexName:ue.ACTIVE_SESSIONS,partitionKey:{name:"activeSessionPk",type:We},sortKey:{name:"activeSessionSk",type:We},projection:{type:"KEYS_ONLY"}},{indexName:ue.USER_SESSIONS,partitionKey:{name:"userSessionPk",type:We},sortKey:{name:"userSessionSk",type:We},projection:{type:"KEYS_ONLY"}},{indexName:ue.USERS_BY_STATUS,partitionKey:{name:"userStatusPk",type:We},sortKey:{name:"userStatusSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["displayName","createdAt"]}},{indexName:ue.USER_PROVIDERS,partitionKey:{name:"userProviderPk",type:We},sortKey:{name:"userProviderSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["userId","externalEmail","externalName","createdAt"]}},{indexName:ue.USER_IDENTITIES,partitionKey:{name:"identityUserPk",type:We},sortKey:{name:"identityUserSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["loginEnabled","verifiedAt","createdAt"]}},{indexName:ue.USER_CREDENTIALS,partitionKey:{name:"credentialUserPk",type:We},sortKey:{name:"credentialUserSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["revokedAt","createdAt"]}},{indexName:ue.USER_TENANTS,partitionKey:{name:"userTenantPk",type:We},sortKey:{name:"userTenantSk",type:We},projection:{type:"INCLUDE",nonKeyAttributes:["userStatus","role","roles","perm","authPerm","isOwner","createdAt","updatedAt"]}},{indexName:ue.TENANT_INVITES,partitionKey:{name:"inviteTenantPk",type:We},sortKey:{name:"inviteTenantSk",type:We},projection:{type:"ALL"}},{indexName:ue.INVITE_TOKEN,partitionKey:{name:"inviteTokenGsi",type:We},projection:{type:"KEYS_ONLY"}},{indexName:ue.INVITEE_EMAIL,partitionKey:{name:"inviteeEmailGsi",type:We},sortKey:{name:"inviteeEmailTenantSk",type:We},projection:{type:"ALL"}},{indexName:ue.INVITEE_PHONE,partitionKey:{name:"inviteePhoneGsi",type:We},sortKey:{name:"inviteePhoneTenantSk",type:We},projection:{type:"ALL"}}]};import{DeleteCommand as J0,GetCommand as Y0,PutCommand as X0,UpdateCommand as RT}from"@aws-sdk/lib-dynamodb";var b0=BigInt(0),ac=BigInt(1),S0=BigInt(2),w0=BigInt(7),N0=BigInt(256),R0=BigInt(113),yT=[],gT=[],vT=[];for(let t=0,e=ac,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],yT.push(2*(5*n+r)),gT.push((t+1)*(t+2)/2%64);let i=b0;for(let o=0;o<7;o++)e=(e<<ac^(e>>w0)*R0)%N0,e&S0&&(i^=ac<<(ac<<BigInt(o))-ac);vT.push(i)}var AT=Ov(vT,!0),O0=AT[0],k0=AT[1],C0=(t,e,r)=>t<<r|e>>>32-r,D0=(t,e,r)=>e<<r|t>>>32-r,P0=(t,e,r)=>e<<r-32|t>>>64-r,U0=(t,e,r)=>t<<r-32|e>>>64-r,hT=(t,e,r)=>r>32?P0(t,e,r):C0(t,e,r),ET=(t,e,r)=>r>32?U0(t,e,r):D0(t,e,r),_s=new Uint32Array(10);function L0(t,e=24){if(!(t instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof t);if(t.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+t.length);if(Ye(e,"rounds"),e<1||e>24)throw new Error('"rounds" expected integer 1..24');for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)_s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){let s=(o+8)%10,a=(o+2)%10,c=_s[a],l=_s[a+1],u=hT(c,l,1)^_s[s],p=ET(c,l,1)^_s[s+1];for(let f=0;f<50;f+=10)t[o+f]^=u,t[o+f+1]^=p}let n=t[2],i=t[3];for(let o=0;o<24;o++){let s=gT[o],a=hT(n,i,s),c=ET(n,i,s),l=yT[o];n=t[l],i=t[l+1],t[l]=a,t[l+1]=c}for(let o=0;o<50;o+=10){let s=t[o],a=t[o+1],c=t[o+2],l=t[o+3];t[o]^=~t[o+2]&t[o+4],t[o+1]^=~t[o+3]&t[o+5],t[o+2]^=~t[o+4]&t[o+6],t[o+3]^=~t[o+5]&t[o+7],t[o+4]^=~t[o+6]&t[o+8],t[o+5]^=~t[o+7]&t[o+9],t[o+6]^=~t[o+8]&s,t[o+7]^=~t[o+9]&a,t[o+8]^=~s&c,t[o+9]^=~a&l}t[0]^=O0[r],t[1]^=k0[r]}Nt(_s)}var zm=class t{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,r,n,i=!1,o=24){if(Ye(e,"blockLen"),Ye(r,"suffix"),Ye(o,"rounds"),wv(i,"enableXOF"),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.canXOF=i,this.rounds=o,Ye(n,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=ji(this.state)}clone(){return this._cloneInto()}keccak(){fs(this.state32),L0(this.state32,this.rounds),fs(this.state32),this.posOut=0,this.pos=0}update(e){bn(this),xn(e);let{blockLen:r,state:n,state32:i}=this,o=e.length,s=r%4===0&&e.byteOffset%4===0,a=r/4,c=s&&o>=r?ji(e):void 0;for(let l=0;l<o;){if(c!==void 0&&this.pos===0&&l%4===0&&o-l>=r){for(let p=0,f=l/4;p<a;p++)i[p]^=c[f+p];l+=r,this.pos=r,this.keccak();continue}let u=Math.min(r-this.pos,o-l);for(let p=0;p<u;p++)n[this.pos++]^=e[l++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,(r&128)!==0&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){bn(this,!1),xn(e),this.finish();let r=this.state,{blockLen:n}=this;for(let i=0,o=e.length;i<o;){this.posOut>=n&&this.keccak();let s=Math.min(n-this.posOut,o-i);e.set(r.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(e)}xof(e){return Ye(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ds(e,this),this.finished)throw new Error("digest() was already called");this.writeInto(e.length===this.outputLen?e:e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,Nt(this.state)}_cloneInto(e){let{blockLen:r,suffix:n,outputLen:i,rounds:o,enableXOF:s}=this;return e||=new t(r,n,i,s,o),e.blockLen=r,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=n,e.outputLen=i,e.enableXOF=s,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},M0=(t,e,r,n={})=>Ru(()=>new zm(e,t,r),n);var TT=M0(6,72,64,Ou(10));var K0=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Jm=Math.ceil,pr=Math.floor,Gt="[BigNumber Error] ",_T=Gt+"Number primitive has more than 15 significant digits: ",Pr=1e14,de=14,Ym=9007199254740991,Xm=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],pi=1e7,mt=1e9;function IT(t){var e,r,n,i=R.prototype={constructor:R,toString:null,valueOf:null},o=new R(1),s=20,a=4,c=-7,l=21,u=-1e7,p=1e7,f=!1,m=1,E=0,v={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},N="0123456789abcdefghijklmnopqrstuvwxyz",S=!0;function R(A,x){var b,g,I,O,D,k,C,P,L=this;if(!(L instanceof R))return new R(A,x);if(x==null){if(A&&A._isBigNumber===!0){L.s=A.s,!A.c||A.e>p?L.c=L.e=null:A.e<u?L.c=[L.e=0]:(L.e=A.e,L.c=A.c.slice());return}if((k=typeof A=="number")&&A*0==0){if(L.s=1/A<0?(A=-A,-1):1,A===~~A){for(O=0,D=A;D>=10;D/=10,O++);O>p?L.c=L.e=null:(L.e=O,L.c=[A]);return}P=String(A)}else{if(!K0.test(P=String(A)))return n(L,P,k);L.s=P.charCodeAt(0)==45?(P=P.slice(1),-1):1}(O=P.indexOf("."))>-1&&(P=P.replace(".","")),(D=P.search(/e/i))>0?(O<0&&(O=D),O+=+P.slice(D+1),P=P.substring(0,D)):O<0&&(O=P.length)}else{if(ze(x,2,N.length,"Base"),x==10&&S)return L=new R(A),V(L,s+L.e+1,a);if(P=String(A),k=typeof A=="number"){if(A*0!=0)return n(L,P,k,x);if(L.s=1/A<0?(P=P.slice(1),-1):1,R.DEBUG&&P.replace(/^0\.0*|\./,"").length>15)throw Error(_T+A)}else L.s=P.charCodeAt(0)===45?(P=P.slice(1),-1):1;for(b=N.slice(0,x),O=D=0,C=P.length;D<C;D++)if(b.indexOf(g=P.charAt(D))<0){if(g=="."){if(D>O){O=C;continue}}else if(!I&&(P==P.toUpperCase()&&(P=P.toLowerCase())||P==P.toLowerCase()&&(P=P.toUpperCase()))){I=!0,D=-1,O=0;continue}return n(L,String(A),k,x)}k=!1,P=r(P,x,10,L.s),(O=P.indexOf("."))>-1?P=P.replace(".",""):O=P.length}for(D=0;P.charCodeAt(D)===48;D++);for(C=P.length;P.charCodeAt(--C)===48;);if(P=P.slice(D,++C)){if(C-=D,k&&R.DEBUG&&C>15&&(A>Ym||A!==pr(A)))throw Error(_T+L.s*A);if((O=O-D-1)>p)L.c=L.e=null;else if(O<u)L.c=[L.e=0];else{if(L.e=O,L.c=[],D=(O+1)%de,O<0&&(D+=de),D<C){for(D&&L.c.push(+P.slice(0,D)),C-=de;D<C;)L.c.push(+P.slice(D,D+=de));D=de-(P=P.slice(D)).length}else D-=C;for(;D--;P+="0");L.c.push(+P)}}else L.c=[L.e=0]}R.clone=IT,R.ROUND_UP=0,R.ROUND_DOWN=1,R.ROUND_CEIL=2,R.ROUND_FLOOR=3,R.ROUND_HALF_UP=4,R.ROUND_HALF_DOWN=5,R.ROUND_HALF_EVEN=6,R.ROUND_HALF_CEIL=7,R.ROUND_HALF_FLOOR=8,R.EUCLID=9,R.config=R.set=function(A){var x,b;if(A!=null)if(typeof A=="object"){if(A.hasOwnProperty(x="DECIMAL_PLACES")&&(b=A[x],ze(b,0,mt,x),s=b),A.hasOwnProperty(x="ROUNDING_MODE")&&(b=A[x],ze(b,0,8,x),a=b),A.hasOwnProperty(x="EXPONENTIAL_AT")&&(b=A[x],b&&b.pop?(ze(b[0],-mt,0,x),ze(b[1],0,mt,x),c=b[0],l=b[1]):(ze(b,-mt,mt,x),c=-(l=b<0?-b:b))),A.hasOwnProperty(x="RANGE"))if(b=A[x],b&&b.pop)ze(b[0],-mt,-1,x),ze(b[1],1,mt,x),u=b[0],p=b[1];else if(ze(b,-mt,mt,x),b)u=-(p=b<0?-b:b);else throw Error(Gt+x+" cannot be zero: "+b);if(A.hasOwnProperty(x="CRYPTO"))if(b=A[x],b===!!b)if(b)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))f=b;else throw f=!b,Error(Gt+"crypto unavailable");else f=b;else throw Error(Gt+x+" not true or false: "+b);if(A.hasOwnProperty(x="MODULO_MODE")&&(b=A[x],ze(b,0,9,x),m=b),A.hasOwnProperty(x="POW_PRECISION")&&(b=A[x],ze(b,0,mt,x),E=b),A.hasOwnProperty(x="FORMAT"))if(b=A[x],typeof b=="object")v=b;else throw Error(Gt+x+" not an object: "+b);if(A.hasOwnProperty(x="ALPHABET"))if(b=A[x],typeof b=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(b))S=b.slice(0,10)=="0123456789",N=b;else throw Error(Gt+x+" invalid: "+b)}else throw Error(Gt+"Object expected: "+A);return{DECIMAL_PLACES:s,ROUNDING_MODE:a,EXPONENTIAL_AT:[c,l],RANGE:[u,p],CRYPTO:f,MODULO_MODE:m,POW_PRECISION:E,FORMAT:v,ALPHABET:N}},R.isBigNumber=function(A){if(!A||A._isBigNumber!==!0)return!1;if(!R.DEBUG)return!0;var x,b,g=A.c,I=A.e,O=A.s;e:if({}.toString.call(g)=="[object Array]"){if((O===1||O===-1)&&I>=-mt&&I<=mt&&I===pr(I)){if(g[0]===0){if(I===0&&g.length===1)return!0;break e}if(x=(I+1)%de,x<1&&(x+=de),String(g[0]).length==x){for(x=0;x<g.length;x++)if(b=g[x],b<0||b>=Pr||b!==pr(b))break e;if(b!==0)return!0}}}else if(g===null&&I===null&&(O===null||O===1||O===-1))return!0;throw Error(Gt+"Invalid BigNumber: "+A)},R.maximum=R.max=function(){return K(arguments,-1)},R.minimum=R.min=function(){return K(arguments,1)},R.random=(function(){var A=9007199254740992,x=Math.random()*A&2097151?function(){return pr(Math.random()*A)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(b){var g,I,O,D,k,C=0,P=[],L=new R(o);if(b==null?b=s:ze(b,0,mt),D=Jm(b/de),f)if(crypto.getRandomValues){for(g=crypto.getRandomValues(new Uint32Array(D*=2));C<D;)k=g[C]*131072+(g[C+1]>>>11),k>=9e15?(I=crypto.getRandomValues(new Uint32Array(2)),g[C]=I[0],g[C+1]=I[1]):(P.push(k%1e14),C+=2);C=D/2}else if(crypto.randomBytes){for(g=crypto.randomBytes(D*=7);C<D;)k=(g[C]&31)*281474976710656+g[C+1]*1099511627776+g[C+2]*4294967296+g[C+3]*16777216+(g[C+4]<<16)+(g[C+5]<<8)+g[C+6],k>=9e15?crypto.randomBytes(7).copy(g,C):(P.push(k%1e14),C+=7);C=D/7}else throw f=!1,Error(Gt+"crypto unavailable");if(!f)for(;C<D;)k=x(),k<9e15&&(P[C++]=k%1e14);for(D=P[--C],b%=de,D&&b&&(k=Xm[de-b],P[C]=pr(D/k)*k);P[C]===0;P.pop(),C--);if(C<0)P=[O=0];else{for(O=-1;P[0]===0;P.splice(0,1),O-=de);for(C=1,k=P[0];k>=10;k/=10,C++);C<de&&(O-=de-C)}return L.e=O,L.c=P,L}})(),R.sum=function(){for(var A=1,x=arguments,b=new R(x[0]);A<x.length;)b=b.plus(x[A++]);return b},r=(function(){var A="0123456789";function x(b,g,I,O){for(var D,k=[0],C,P=0,L=b.length;P<L;){for(C=k.length;C--;k[C]*=g);for(k[0]+=O.indexOf(b.charAt(P++)),D=0;D<k.length;D++)k[D]>I-1&&(k[D+1]==null&&(k[D+1]=0),k[D+1]+=k[D]/I|0,k[D]%=I)}return k.reverse()}return function(b,g,I,O,D){var k,C,P,L,H,z,Y,pe,Oe=b.indexOf("."),Fe=s,me=a;for(Oe>=0&&(L=E,E=0,b=b.replace(".",""),pe=new R(g),z=pe.pow(b.length-Oe),E=L,pe.c=x(Nn(dr(z.c),z.e,"0"),10,I,A),pe.e=pe.c.length),Y=x(b,g,I,D?(k=N,A):(k=A,N)),P=L=Y.length;Y[--L]==0;Y.pop());if(!Y[0])return k.charAt(0);if(Oe<0?--P:(z.c=Y,z.e=P,z.s=O,z=e(z,pe,Fe,me,I),Y=z.c,H=z.r,P=z.e),C=P+Fe+1,Oe=Y[C],L=I/2,H=H||C<0||Y[C+1]!=null,H=me<4?(Oe!=null||H)&&(me==0||me==(z.s<0?3:2)):Oe>L||Oe==L&&(me==4||H||me==6&&Y[C-1]&1||me==(z.s<0?8:7)),C<1||!Y[0])b=H?Nn(k.charAt(1),-Fe,k.charAt(0)):k.charAt(0);else{if(Y.length=C,H)for(--I;++Y[--C]>I;)Y[C]=0,C||(++P,Y=[1].concat(Y));for(L=Y.length;!Y[--L];);for(Oe=0,b="";Oe<=L;b+=k.charAt(Y[Oe++]));b=Nn(b,P,k.charAt(0))}return b}})(),e=(function(){function A(g,I,O){var D,k,C,P,L=0,H=g.length,z=I%pi,Y=I/pi|0;for(g=g.slice();H--;)C=g[H]%pi,P=g[H]/pi|0,D=Y*C+P*z,k=z*C+D%pi*pi+L,L=(k/O|0)+(D/pi|0)+Y*P,g[H]=k%O;return L&&(g=[L].concat(g)),g}function x(g,I,O,D){var k,C;if(O!=D)C=O>D?1:-1;else for(k=C=0;k<O;k++)if(g[k]!=I[k]){C=g[k]>I[k]?1:-1;break}return C}function b(g,I,O,D){for(var k=0;O--;)g[O]-=k,k=g[O]<I[O]?1:0,g[O]=k*D+g[O]-I[O];for(;!g[0]&&g.length>1;g.splice(0,1));}return function(g,I,O,D,k){var C,P,L,H,z,Y,pe,Oe,Fe,me,we,st,Zi,Cn,eo,_t,yi,It=g.s==I.s?1:-1,Qe=g.c,Ke=I.c;if(!Qe||!Qe[0]||!Ke||!Ke[0])return new R(!g.s||!I.s||(Qe?Ke&&Qe[0]==Ke[0]:!Ke)?NaN:Qe&&Qe[0]==0||!Ke?It*0:It/0);for(Oe=new R(It),Fe=Oe.c=[],P=g.e-I.e,It=O+P+1,k||(k=Pr,P=fr(g.e/de)-fr(I.e/de),It=It/de|0),L=0;Ke[L]==(Qe[L]||0);L++);if(Ke[L]>(Qe[L]||0)&&P--,It<0)Fe.push(1),H=!0;else{for(Cn=Qe.length,_t=Ke.length,L=0,It+=2,z=pr(k/(Ke[0]+1)),z>1&&(Ke=A(Ke,z,k),Qe=A(Qe,z,k),_t=Ke.length,Cn=Qe.length),Zi=_t,me=Qe.slice(0,_t),we=me.length;we<_t;me[we++]=0);yi=Ke.slice(),yi=[0].concat(yi),eo=Ke[0],Ke[1]>=k/2&&eo++;do{if(z=0,C=x(Ke,me,_t,we),C<0){if(st=me[0],_t!=we&&(st=st*k+(me[1]||0)),z=pr(st/eo),z>1)for(z>=k&&(z=k-1),Y=A(Ke,z,k),pe=Y.length,we=me.length;x(Y,me,pe,we)==1;)z--,b(Y,_t<pe?yi:Ke,pe,k),pe=Y.length,C=1;else z==0&&(C=z=1),Y=Ke.slice(),pe=Y.length;if(pe<we&&(Y=[0].concat(Y)),b(me,Y,we,k),we=me.length,C==-1)for(;x(Ke,me,_t,we)<1;)z++,b(me,_t<we?yi:Ke,we,k),we=me.length}else C===0&&(z++,me=[0]);Fe[L++]=z,me[0]?me[we++]=Qe[Zi]||0:(me=[Qe[Zi]],we=1)}while((Zi++<Cn||me[0]!=null)&&It--);H=me[0]!=null,Fe[0]||Fe.splice(0,1)}if(k==Pr){for(L=1,It=Fe[0];It>=10;It/=10,L++);V(Oe,O+(Oe.e=L+P*de-1)+1,D,H)}else Oe.e=P,Oe.r=+H;return Oe}})();function M(A,x,b,g){var I,O,D,k,C;if(b==null?b=a:ze(b,0,8),!A.c)return A.toString();if(I=A.c[0],D=A.e,x==null)C=dr(A.c),C=g==1||g==2&&(D<=c||D>=l)?yd(C,D):Nn(C,D,"0");else if(A=V(new R(A),x,b),O=A.e,C=dr(A.c),k=C.length,g==1||g==2&&(x<=O||O<=c)){for(;k<x;C+="0",k++);C=yd(C,O)}else if(x-=D+(g===2&&O>D),C=Nn(C,O,"0"),O+1>k){if(--x>0)for(C+=".";x--;C+="0");}else if(x+=O-k,x>0)for(O+1==k&&(C+=".");x--;C+="0");return A.s<0&&I?"-"+C:C}function K(A,x){for(var b,g,I=1,O=new R(A[0]);I<A.length;I++)g=new R(A[I]),(!g.s||(b=Yi(O,g))===x||b===0&&O.s===x)&&(O=g);return O}function B(A,x,b){for(var g=1,I=x.length;!x[--I];x.pop());for(I=x[0];I>=10;I/=10,g++);return(b=g+b*de-1)>p?A.c=A.e=null:b<u?A.c=[A.e=0]:(A.e=b,A.c=x),A}n=(function(){var A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,x=/^([^.]+)\.$/,b=/^\.([^.]+)$/,g=/^-?(Infinity|NaN)$/,I=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(O,D,k,C){var P,L=k?D:D.replace(I,"");if(g.test(L))O.s=isNaN(L)?null:L<0?-1:1;else{if(!k&&(L=L.replace(A,function(H,z,Y){return P=(Y=Y.toLowerCase())=="x"?16:Y=="b"?2:8,!C||C==P?z:H}),C&&(P=C,L=L.replace(x,"$1").replace(b,"0.$1")),D!=L))return new R(L,P);if(R.DEBUG)throw Error(Gt+"Not a"+(C?" base "+C:"")+" number: "+D);O.s=null}O.c=O.e=null}})();function V(A,x,b,g){var I,O,D,k,C,P,L,H=A.c,z=Xm;if(H){e:{for(I=1,k=H[0];k>=10;k/=10,I++);if(O=x-I,O<0)O+=de,D=x,C=H[P=0],L=pr(C/z[I-D-1]%10);else if(P=Jm((O+1)/de),P>=H.length)if(g){for(;H.length<=P;H.push(0));C=L=0,I=1,O%=de,D=O-de+1}else break e;else{for(C=k=H[P],I=1;k>=10;k/=10,I++);O%=de,D=O-de+I,L=D<0?0:pr(C/z[I-D-1]%10)}if(g=g||x<0||H[P+1]!=null||(D<0?C:C%z[I-D-1]),g=b<4?(L||g)&&(b==0||b==(A.s<0?3:2)):L>5||L==5&&(b==4||g||b==6&&(O>0?D>0?C/z[I-D]:0:H[P-1])%10&1||b==(A.s<0?8:7)),x<1||!H[0])return H.length=0,g?(x-=A.e+1,H[0]=z[(de-x%de)%de],A.e=-x||0):H[0]=A.e=0,A;if(O==0?(H.length=P,k=1,P--):(H.length=P+1,k=z[de-O],H[P]=D>0?pr(C/z[I-D]%z[D])*k:0),g)for(;;)if(P==0){for(O=1,D=H[0];D>=10;D/=10,O++);for(D=H[0]+=k,k=1;D>=10;D/=10,k++);O!=k&&(A.e++,H[0]==Pr&&(H[0]=1));break}else{if(H[P]+=k,H[P]!=Pr)break;H[P--]=0,k=1}for(O=H.length;H[--O]===0;H.pop());}A.e>p?A.c=A.e=null:A.e<u&&(A.c=[A.e=0])}return A}function $(A){var x,b=A.e;return b===null?A.toString():(x=dr(A.c),x=b<=c||b>=l?yd(x,b):Nn(x,b,"0"),A.s<0?"-"+x:x)}return i.absoluteValue=i.abs=function(){var A=new R(this);return A.s<0&&(A.s=1),A},i.comparedTo=function(A,x){return Yi(this,new R(A,x))},i.decimalPlaces=i.dp=function(A,x){var b,g,I,O=this;if(A!=null)return ze(A,0,mt),x==null?x=a:ze(x,0,8),V(new R(O),A+O.e+1,x);if(!(b=O.c))return null;if(g=((I=b.length-1)-fr(this.e/de))*de,I=b[I])for(;I%10==0;I/=10,g--);return g<0&&(g=0),g},i.dividedBy=i.div=function(A,x){return e(this,new R(A,x),s,a)},i.dividedToIntegerBy=i.idiv=function(A,x){return e(this,new R(A,x),0,1)},i.exponentiatedBy=i.pow=function(A,x){var b,g,I,O,D,k,C,P,L,H=this;if(A=new R(A),A.c&&!A.isInteger())throw Error(Gt+"Exponent not an integer: "+$(A));if(x!=null&&(x=new R(x)),k=A.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!A.c||!A.c[0])return L=new R(Math.pow(+$(H),k?A.s*(2-Ed(A)):+$(A))),x?L.mod(x):L;if(C=A.s<0,x){if(x.c?!x.c[0]:!x.s)return new R(NaN);g=!C&&H.isInteger()&&x.isInteger(),g&&(H=H.mod(x))}else{if(A.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||k&&H.c[1]>=24e7:H.c[0]<8e13||k&&H.c[0]<=9999975e7)))return O=H.s<0&&Ed(A)?-0:0,H.e>-1&&(O=1/O),new R(C?1/O:O);E&&(O=Jm(E/de+2))}for(k?(b=new R(.5),C&&(A.s=1),P=Ed(A)):(I=Math.abs(+$(A)),P=I%2),L=new R(o);;){if(P){if(L=L.times(H),!L.c)break;O?L.c.length>O&&(L.c.length=O):g&&(L=L.mod(x))}if(I){if(I=pr(I/2),I===0)break;P=I%2}else if(A=A.times(b),V(A,A.e+1,1),A.e>14)P=Ed(A);else{if(I=+$(A),I===0)break;P=I%2}H=H.times(H),O?H.c&&H.c.length>O&&(H.c.length=O):g&&(H=H.mod(x))}return g?L:(C&&(L=o.div(L)),x?L.mod(x):O?V(L,E,a,D):L)},i.integerValue=function(A){var x=new R(this);return A==null?A=a:ze(A,0,8),V(x,x.e+1,A)},i.isEqualTo=i.eq=function(A,x){return Yi(this,new R(A,x))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(A,x){return Yi(this,new R(A,x))>0},i.isGreaterThanOrEqualTo=i.gte=function(A,x){return(x=Yi(this,new R(A,x)))===1||x===0},i.isInteger=function(){return!!this.c&&fr(this.e/de)>this.c.length-2},i.isLessThan=i.lt=function(A,x){return Yi(this,new R(A,x))<0},i.isLessThanOrEqualTo=i.lte=function(A,x){return(x=Yi(this,new R(A,x)))===-1||x===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(A,x){var b,g,I,O,D=this,k=D.s;if(A=new R(A,x),x=A.s,!k||!x)return new R(NaN);if(k!=x)return A.s=-x,D.plus(A);var C=D.e/de,P=A.e/de,L=D.c,H=A.c;if(!C||!P){if(!L||!H)return L?(A.s=-x,A):new R(H?D:NaN);if(!L[0]||!H[0])return H[0]?(A.s=-x,A):new R(L[0]?D:a==3?-0:0)}if(C=fr(C),P=fr(P),L=L.slice(),k=C-P){for((O=k<0)?(k=-k,I=L):(P=C,I=H),I.reverse(),x=k;x--;I.push(0));I.reverse()}else for(g=(O=(k=L.length)<(x=H.length))?k:x,k=x=0;x<g;x++)if(L[x]!=H[x]){O=L[x]<H[x];break}if(O&&(I=L,L=H,H=I,A.s=-A.s),x=(g=H.length)-(b=L.length),x>0)for(;x--;L[b++]=0);for(x=Pr-1;g>k;){if(L[--g]<H[g]){for(b=g;b&&!L[--b];L[b]=x);--L[b],L[g]+=Pr}L[g]-=H[g]}for(;L[0]==0;L.splice(0,1),--P);return L[0]?B(A,L,P):(A.s=a==3?-1:1,A.c=[A.e=0],A)},i.modulo=i.mod=function(A,x){var b,g,I=this;return A=new R(A,x),!I.c||!A.s||A.c&&!A.c[0]?new R(NaN):!A.c||I.c&&!I.c[0]?new R(I):(m==9?(g=A.s,A.s=1,b=e(I,A,0,3),A.s=g,b.s*=g):b=e(I,A,0,m),A=I.minus(b.times(A)),!A.c[0]&&m==1&&(A.s=I.s),A)},i.multipliedBy=i.times=function(A,x){var b,g,I,O,D,k,C,P,L,H,z,Y,pe,Oe,Fe,me=this,we=me.c,st=(A=new R(A,x)).c;if(!we||!st||!we[0]||!st[0])return!me.s||!A.s||we&&!we[0]&&!st||st&&!st[0]&&!we?A.c=A.e=A.s=null:(A.s*=me.s,!we||!st?A.c=A.e=null:(A.c=[0],A.e=0)),A;for(g=fr(me.e/de)+fr(A.e/de),A.s*=me.s,C=we.length,H=st.length,C<H&&(pe=we,we=st,st=pe,I=C,C=H,H=I),I=C+H,pe=[];I--;pe.push(0));for(Oe=Pr,Fe=pi,I=H;--I>=0;){for(b=0,z=st[I]%Fe,Y=st[I]/Fe|0,D=C,O=I+D;O>I;)P=we[--D]%Fe,L=we[D]/Fe|0,k=Y*P+L*z,P=z*P+k%Fe*Fe+pe[O]+b,b=(P/Oe|0)+(k/Fe|0)+Y*L,pe[O--]=P%Oe;pe[O]=b}return b?++g:pe.splice(0,1),B(A,pe,g)},i.negated=function(){var A=new R(this);return A.s=-A.s||null,A},i.plus=function(A,x){var b,g=this,I=g.s;if(A=new R(A,x),x=A.s,!I||!x)return new R(NaN);if(I!=x)return A.s=-x,g.minus(A);var O=g.e/de,D=A.e/de,k=g.c,C=A.c;if(!O||!D){if(!k||!C)return new R(I/0);if(!k[0]||!C[0])return C[0]?A:new R(k[0]?g:I*0)}if(O=fr(O),D=fr(D),k=k.slice(),I=O-D){for(I>0?(D=O,b=C):(I=-I,b=k),b.reverse();I--;b.push(0));b.reverse()}for(I=k.length,x=C.length,I-x<0&&(b=C,C=k,k=b,x=I),I=0;x;)I=(k[--x]=k[x]+C[x]+I)/Pr|0,k[x]=Pr===k[x]?0:k[x]%Pr;return I&&(k=[I].concat(k),++D),B(A,k,D)},i.precision=i.sd=function(A,x){var b,g,I,O=this;if(A!=null&&A!==!!A)return ze(A,1,mt),x==null?x=a:ze(x,0,8),V(new R(O),A,x);if(!(b=O.c))return null;if(I=b.length-1,g=I*de+1,I=b[I]){for(;I%10==0;I/=10,g--);for(I=b[0];I>=10;I/=10,g++);}return A&&O.e+1>g&&(g=O.e+1),g},i.shiftedBy=function(A){return ze(A,-Ym,Ym),this.times("1e"+A)},i.squareRoot=i.sqrt=function(){var A,x,b,g,I,O=this,D=O.c,k=O.s,C=O.e,P=s+4,L=new R("0.5");if(k!==1||!D||!D[0])return new R(!k||k<0&&(!D||D[0])?NaN:D?O:1/0);if(k=Math.sqrt(+$(O)),k==0||k==1/0?(x=dr(D),(x.length+C)%2==0&&(x+="0"),k=Math.sqrt(+x),C=fr((C+1)/2)-(C<0||C%2),k==1/0?x="5e"+C:(x=k.toExponential(),x=x.slice(0,x.indexOf("e")+1)+C),b=new R(x)):b=new R(k+""),b.c[0]){for(C=b.e,k=C+P,k<3&&(k=0);;)if(I=b,b=L.times(I.plus(e(O,I,P,1))),dr(I.c).slice(0,k)===(x=dr(b.c)).slice(0,k))if(b.e<C&&--k,x=x.slice(k-3,k+1),x=="9999"||!g&&x=="4999"){if(!g&&(V(I,I.e+s+2,0),I.times(I).eq(O))){b=I;break}P+=4,k+=4,g=1}else{(!+x||!+x.slice(1)&&x.charAt(0)=="5")&&(V(b,b.e+s+2,1),A=!b.times(b).eq(O));break}}return V(b,b.e+s+1,a,A)},i.toExponential=function(A,x){return A!=null&&(ze(A,0,mt),A++),M(this,A,x,1)},i.toFixed=function(A,x){return A!=null&&(ze(A,0,mt),A=A+this.e+1),M(this,A,x)},i.toFormat=function(A,x,b){var g,I=this;if(b==null)A!=null&&x&&typeof x=="object"?(b=x,x=null):A&&typeof A=="object"?(b=A,A=x=null):b=v;else if(typeof b!="object")throw Error(Gt+"Argument not an object: "+b);if(g=I.toFixed(A,x),I.c){var O,D=g.split("."),k=+b.groupSize,C=+b.secondaryGroupSize,P=b.groupSeparator||"",L=D[0],H=D[1],z=I.s<0,Y=z?L.slice(1):L,pe=Y.length;if(C&&(O=k,k=C,C=O,pe-=O),k>0&&pe>0){for(O=pe%k||k,L=Y.substr(0,O);O<pe;O+=k)L+=P+Y.substr(O,k);C>0&&(L+=P+Y.slice(O)),z&&(L="-"+L)}g=H?L+(b.decimalSeparator||"")+((C=+b.fractionGroupSize)?H.replace(new RegExp("\\d{"+C+"}\\B","g"),"$&"+(b.fractionGroupSeparator||"")):H):L}return(b.prefix||"")+g+(b.suffix||"")},i.toFraction=function(A){var x,b,g,I,O,D,k,C,P,L,H,z,Y=this,pe=Y.c;if(A!=null&&(k=new R(A),!k.isInteger()&&(k.c||k.s!==1)||k.lt(o)))throw Error(Gt+"Argument "+(k.isInteger()?"out of range: ":"not an integer: ")+$(k));if(!pe)return new R(Y);for(x=new R(o),P=b=new R(o),g=C=new R(o),z=dr(pe),O=x.e=z.length-Y.e-1,x.c[0]=Xm[(D=O%de)<0?de+D:D],A=!A||k.comparedTo(x)>0?O>0?x:P:k,D=p,p=1/0,k=new R(z),C.c[0]=0;L=e(k,x,0,1),I=b.plus(L.times(g)),I.comparedTo(A)!=1;)b=g,g=I,P=C.plus(L.times(I=P)),C=I,x=k.minus(L.times(I=x)),k=I;return I=e(A.minus(b),g,0,1),C=C.plus(I.times(P)),b=b.plus(I.times(g)),C.s=P.s=Y.s,O=O*2,H=e(P,g,O,a).minus(Y).abs().comparedTo(e(C,b,O,a).minus(Y).abs())<1?[P,g]:[C,b],p=D,H},i.toNumber=function(){return+$(this)},i.toPrecision=function(A,x){return A!=null&&ze(A,1,mt),M(this,A,x,2)},i.toString=function(A){var x,b=this,g=b.s,I=b.e;return I===null?g?(x="Infinity",g<0&&(x="-"+x)):x="NaN":(A==null?x=I<=c||I>=l?yd(dr(b.c),I):Nn(dr(b.c),I,"0"):A===10&&S?(b=V(new R(b),s+I+1,a),x=Nn(dr(b.c),b.e,"0")):(ze(A,2,N.length,"Base"),x=r(Nn(dr(b.c),I,"0"),10,A,g,!0)),g<0&&b.c[0]&&(x="-"+x)),x},i.valueOf=i.toJSON=function(){return $(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&R.set(t),R}function fr(t){var e=t|0;return t>0||t===e?e:e-1}function dr(t){for(var e,r,n=1,i=t.length,o=t[0]+"";n<i;){for(e=t[n++]+"",r=de-e.length;r--;e="0"+e);o+=e}for(i=o.length;o.charCodeAt(--i)===48;);return o.slice(0,i+1||1)}function Yi(t,e){var r,n,i=t.c,o=e.c,s=t.s,a=e.s,c=t.e,l=e.e;if(!s||!a)return null;if(r=i&&!i[0],n=o&&!o[0],r||n)return r?n?0:-a:s;if(s!=a)return s;if(r=s<0,n=c==l,!i||!o)return n?0:!i^r?1:-1;if(!n)return c>l^r?1:-1;for(a=(c=i.length)<(l=o.length)?c:l,s=0;s<a;s++)if(i[s]!=o[s])return i[s]>o[s]^r?1:-1;return c==l?0:c>l^r?1:-1}function ze(t,e,r,n){if(t<e||t>r||t!==pr(t))throw Error(Gt+(n||"Argument")+(typeof t=="number"?t<e||t>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Ed(t){var e=t.c.length-1;return fr(t.e/de)==e&&t.c[e]%2!=0}function yd(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Nn(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e<n&&(t=t.slice(0,e)+"."+t.slice(e));return t}var H0=IT(),xT=H0;var F0=24,cc=32,V0=()=>typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function"?()=>{let t=new Uint32Array(1);return globalThis.crypto.getRandomValues(t),t[0]/4294967296}:Math.random,Zm=V0(),Qm=(t=4,e=Zm)=>{let r="";for(;r.length<t;)r=r+Math.floor(e()*36).toString(36);return r};function B0(t){let e=new xT(0);for(let r of t.values())e=e.multipliedBy(256).plus(r);return e}var ST=(t="")=>{let e=new TextEncoder;return B0(TT(e.encode(t))).toString(36).slice(1)},bT=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),j0=t=>bT[Math.floor(t()*bT.length)],G0=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Zm}={})=>{let r=Object.keys(t).toString(),n=r.length?r+Qm(cc,e):Qm(cc,e);return ST(n).substring(0,cc)},$0=t=>()=>t++,q0=476782367,wT=({random:t=Zm,counter:e=$0(Math.floor(t()*q0)),length:r=F0,fingerprint:n=G0({random:t})}={})=>{if(r>cc)throw new Error(`Length must be between 2 and ${cc}. Received: ${r}`);return function(){let o=j0(t),s=Date.now().toString(36),a=e().toString(36),c=Qm(r,t),l=`${s+c+a+n}`;return`${o+ST(l).substring(1,r)}`}},ht=W0(wT);function W0(t){let e;return()=>(e||(e=t()),e())}function Is(t){if(typeof t=="object"&&t!==null&&"name"in t){let{name:e}=t;return typeof e=="string"?e:void 0}}function Ce(t){return Is(t)==="ConditionalCheckFailedException"}function z0(t){let e=Is(t),r=t instanceof Error?t.message:typeof t=="string"?t:void 0;return[e,r].filter(Boolean).join(": ")||String(t)}function NT(t,e){console.error(`[repo-plugin-dynamodb] ${t} failed \u2014 ${z0(e)}`)}function G(t,e){return NT(t,e),te.DatabaseQueryError({query:t})}function Rt(t,e){return NT(t,e),te.UnknownError({message:t})}var lc=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return ht()}async get(e){try{let r=await this.docClient.send(new Y0({TableName:this.tableName,Key:{[h.PK]:U.CHALLENGE_PK(e),[h.SK]:U.CHALLENGE_SK()}}));if(!r.Item)return T(null);let n=this.unmarshall(r.Item);return $m(re(n.expiresAt))?T(null):T(n)}catch(r){return d(G("get challenge",r))}}async create(e){try{let r=ae(),n=e.id||this.generateChallengeId(),i={...e,id:n,createdAt:J(r)},o=re(e.expiresAt),s=Math.floor((o+this.ttlGracePeriod)/1e3);return await this.docClient.send(new X0({TableName:this.tableName,Item:this.marshall(i,s)})),T(i)}catch(r){return d(G("create challenge",r))}}async update(e,r){try{let n=[],i={},o={};return r.method!==void 0&&(n.push("#method = :method"),i["#method"]=h.METHOD,o[":method"]=r.method),r.phase!==void 0&&(n.push("#phase = :phase"),i["#phase"]=h.PHASE,o[":phase"]=r.phase),r.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),i["#codeHash"]=h.CODE_HASH,o[":codeHash"]=r.codeHash),r.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),i["#challengeStatus"]=h.CHALLENGE_STATUS,o[":challengeStatus"]=r.status),n.length===0?T(void 0):(await this.docClient.send(new RT({TableName:this.tableName,Key:{[h.PK]:U.CHALLENGE_PK(e),[h.SK]:U.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:o})),T(void 0))}catch(n){return d(G("update challenge",n))}}async incrementAttempts(e,r){let n={":zero":0,":inc":1},i;r!==void 0&&(i="attribute_not_exists(#attempts) OR #attempts < :max",n[":max"]=r);try{let s=(await this.docClient.send(new RT({TableName:this.tableName,Key:{[h.PK]:U.CHALLENGE_PK(e),[h.SK]:U.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...i?{ConditionExpression:i}:{},ExpressionAttributeNames:{"#attempts":h.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[h.ATTEMPTS]??0;return T(s)}catch(o){return Ce(o)?d(te.AttemptsExceeded()):d(G("increment challenge attempts",o))}}async remove(e){try{return await this.docClient.send(new J0({TableName:this.tableName,Key:{[h.PK]:U.CHALLENGE_PK(e),[h.SK]:U.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":h.PK}})),T(void 0)}catch(r){return Ce(r)?T(void 0):d(G("remove challenge",r))}}marshall(e,r){let n={[h.PK]:U.CHALLENGE_PK(e.id),[h.SK]:U.CHALLENGE_SK(),[h.USER_ID]:e.userId,[h.PURPOSE]:e.purpose,[h.CHALLENGE_STATUS]:e.status,[h.EXPIRES_AT]:re(e.expiresAt),[h.CREATED_AT]:re(e.createdAt),[h.TTL]:r};return e.tenantId&&(n[h.TENANT_ID]=e.tenantId),e.phase&&(n[h.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[h.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[h.METHOD]=e.method),e.codeHash&&(n[h.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[h.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[h.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[h.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[h.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[h.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[h.COUNTRY]=e.country),e.city&&(n[h.CITY]=e.city),e.metadata&&(n[h.METADATA]=e.metadata),e.flowKey&&(n[h.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:le.challengeIdFromPK(e[h.PK]),userId:e[h.USER_ID],purpose:e[h.PURPOSE],status:e[h.CHALLENGE_STATUS],expiresAt:J(e[h.EXPIRES_AT]),createdAt:J(e[h.CREATED_AT])};return e[h.TENANT_ID]&&(n.tenantId=e[h.TENANT_ID]),e[h.PHASE]&&(n.phase=e[h.PHASE]),e[h.ALLOWED_METHODS]&&(n.allowedMethods=e[h.ALLOWED_METHODS]),e[h.METHOD]&&(n.method=e[h.METHOD]),e[h.CODE_HASH]&&(n.codeHash=e[h.CODE_HASH]),e[h.ATTEMPTS]!==void 0&&(n.attempts=e[h.ATTEMPTS]),e[h.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[h.MAX_ATTEMPTS]),e[h.IDENTITY_TYPE]&&(n.identityType=e[h.IDENTITY_TYPE]),e[h.IDENTITY_VALUE]&&(n.identityValue=e[h.IDENTITY_VALUE]),e[h.DEVICE_LABEL]&&(n.deviceLabel=e[h.DEVICE_LABEL]),e[h.COUNTRY]&&(n.country=e[h.COUNTRY]),e[h.CITY]&&(n.city=e[h.CITY]),e[h.METADATA]&&(n.metadata=e[h.METADATA]),e[h.FLOW_KEY]&&(n.flowKey=e[h.FLOW_KEY]),n}};import{BatchGetCommand as Q0,DeleteCommand as Z0,GetCommand as eO,PutCommand as tO,QueryCommand as gd,UpdateCommand as rO}from"@aws-sdk/lib-dynamodb";var uc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return ht()}async get(e){try{let r=await this.docClient.send(new eO({TableName:this.tableName,Key:{[h.PK]:U.CREDENTIAL_PK(e),[h.SK]:U.CREDENTIAL_SK()}}));return r.Item?T(this.unmarshall(r.Item)):T(null)}catch(r){return d(G("get credential",r))}}async getByUserIdAndType(e,r){try{let n=await this.docClient.send(new gd({TableName:this.tableName,IndexName:ue.USER_CREDENTIALS,KeyConditionExpression:`${h.CREDENTIAL_USER_PK} = :userPk AND begins_with(${h.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":U.USER_PK(e),":typePrefix":U.CREDENTIAL_TYPE_PREFIX(r)},Limit:1}));if(!n.Items||n.Items.length===0)return T(null);let i=n.Items[0];if(!i)return T(null);let o=le.credentialId(i[h.PK]);return this.get(o)}catch(n){return d(G("get credential by user and type",n))}}async getByUserId(e){try{let r=await this.docClient.send(new gd({TableName:this.tableName,IndexName:ue.USER_CREDENTIALS,KeyConditionExpression:`${h.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":U.USER_PK(e)}}));if(!r.Items||r.Items.length===0)return T([]);let n=r.Items.map(s=>le.credentialId(s[h.PK])),i=await this.batchGet(n);if(i.ok===!1)return d(i.errors,i.meta);if(!i.data)return T([]);let o=i.data.filter(s=>s!==null);return T(o)}catch(r){return d(G("get credentials by user",r))}}async create(e){try{let r=ae(),n=this.generateCredentialId(),i={revokedAt:null,lastUsedAt:null,...e,id:n,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new tO({TableName:this.tableName,Item:this.marshall(i),ConditionExpression:`attribute_not_exists(${h.PK})`})),T(i)}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"credential"})):d(G("create credential",r))}}async update(e,r){try{let n=ae(),i=[],o={},s={};return i.push(`#${h.UPDATED_AT} = :updatedAt`),o[`#${h.UPDATED_AT}`]=h.UPDATED_AT,s[":updatedAt"]=n,r.value!==void 0&&(i.push(`#${h.CREDENTIAL_VALUE} = :value`),o[`#${h.CREDENTIAL_VALUE}`]=h.CREDENTIAL_VALUE,s[":value"]=r.value),r.data!==void 0&&(i.push(`#${h.METADATA} = :data`),o[`#${h.METADATA}`]=h.METADATA,s[":data"]=r.data),r.revokedAt!==void 0&&(i.push(`#${h.REVOKED_AT} = :revokedAt`),o[`#${h.REVOKED_AT}`]=h.REVOKED_AT,s[":revokedAt"]=r.revokedAt?re(r.revokedAt):null),r.lastUsedAt!==void 0&&(i.push(`#${h.LAST_USED_AT} = :lastUsedAt`),o[`#${h.LAST_USED_AT}`]=h.LAST_USED_AT,s[":lastUsedAt"]=r.lastUsedAt?re(r.lastUsedAt):null),await this.docClient.send(new rO({TableName:this.tableName,Key:{[h.PK]:U.CREDENTIAL_PK(e),[h.SK]:U.CREDENTIAL_SK()},UpdateExpression:`SET ${i.join(", ")}`,ExpressionAttributeNames:o,ExpressionAttributeValues:s,ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"credential",id:e})):d(G("update credential",n))}}async remove(e){try{return await this.docClient.send(new Z0({TableName:this.tableName,Key:{[h.PK]:U.CREDENTIAL_PK(e),[h.SK]:U.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(r){return Ce(r)?d(te.NotFound({entity:"credential",id:e})):d(G("delete credential",r))}}async hasType(e,r){try{let n=await this.docClient.send(new gd({TableName:this.tableName,IndexName:ue.USER_CREDENTIALS,KeyConditionExpression:`${h.CREDENTIAL_USER_PK} = :userPk AND begins_with(${h.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":U.USER_PK(e),":typePrefix":U.CREDENTIAL_TYPE_PREFIX(r)},Select:"COUNT",Limit:1}));return T((n.Count||0)>0)}catch(n){return d(G("check credential type",n))}}async countByUserId(e){try{let r=await this.docClient.send(new gd({TableName:this.tableName,IndexName:ue.USER_CREDENTIALS,KeyConditionExpression:`${h.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":U.USER_PK(e)},Select:"COUNT"}));return T(r.Count||0)}catch(r){return d(G("count credentials",r))}}async batchGet(e){if(e.length===0)return T([]);try{let r=[];for(let i=0;i<e.length;i+=100)r.push(e.slice(i,i+100));let n=[];for(let i of r){let s=(await this.docClient.send(new Q0({RequestItems:{[this.tableName]:{Keys:i.map(c=>({[h.PK]:U.CREDENTIAL_PK(c),[h.SK]:U.CREDENTIAL_SK()}))}}}))).Responses?.[this.tableName]||[],a=new Map;for(let c of s){let l=this.unmarshall(c);a.set(l.id,l)}for(let c of i)n.push(a.get(c)||null)}return T(n)}catch(r){return d(G("batch get credentials",r))}}marshall(e){let r={[h.PK]:U.CREDENTIAL_PK(e.id),[h.SK]:U.CREDENTIAL_SK(),[h.CREDENTIAL_USER_PK]:U.USER_PK(e.userId),[h.CREDENTIAL_USER_SK]:U.CREDENTIAL_USER_SK(e.type,e.id),[h.USER_ID]:e.userId,[h.CREDENTIAL_VALUE]:e.value,[h.METADATA]:e.data,[h.REVOKED_AT]:e.revokedAt?re(e.revokedAt):null,[h.CREATED_AT]:re(e.createdAt),[h.UPDATED_AT]:re(e.updatedAt)};return e.lastUsedAt&&(r[h.LAST_USED_AT]=re(e.lastUsedAt)),r}unmarshall(e){let r=le.credentialId(e[h.PK]),n=le.credentialTypeFromUserSK(e[h.CREDENTIAL_USER_SK]);return{id:r,userId:e[h.USER_ID],type:n,value:e[h.CREDENTIAL_VALUE],data:e[h.METADATA]||{},revokedAt:Kt(e[h.REVOKED_AT]),createdAt:J(e[h.CREATED_AT]),updatedAt:J(e[h.UPDATED_AT]),lastUsedAt:Kt(e[h.LAST_USED_AT])}}};import{BatchGetCommand as nO,DeleteCommand as iO,GetCommand as oO,PutCommand as sO,QueryCommand as aO,UpdateCommand as eh}from"@aws-sdk/lib-dynamodb";function th(t){return{failedAttempts:t.failedAttempts,lastFailedAt:Cr(t.lastFailedAt),lockedUntil:Cr(t.lockedUntil)}}function OT(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]={failedAttempts:n.failedAttempts??0,lastFailedAt:Kt(n.lastFailedAt),lockedUntil:Kt(n.lockedUntil)};return e}function kT(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))n&&(e[r]=th(n));return e}var dc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e,r){try{let n=await this.docClient.send(new oO({TableName:this.tableName,Key:{[h.PK]:U.IDENTITY_PK(e,r),[h.SK]:U.IDENTITY_SK()}}));if(!n.Item)return T(null);let i=this.unmarshall(n.Item);return T(i)}catch(n){return d(G("get identity",n))}}async getByUserId(e){try{let r=await this.docClient.send(new aO({TableName:this.tableName,IndexName:ue.USER_IDENTITIES,KeyConditionExpression:`${h.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":U.USER_INDEX_PK(e)}})),n=[];for(let i of r.Items||[]){let o=this.unmarshall(i);o!==null&&n.push(o)}return T(n)}catch(r){return d(G("get identities by userId",r))}}async create(e){try{let r=ae(),n={...e,createdAt:J(r),updatedAt:J(r)};return await this.docClient.send(new sO({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),T(n)}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"identity"})):d(G("create identity",r))}}async update(e,r,n){try{let i=[],o=[],s={},a={};if(n.loginEnabled!==void 0&&(i.push("#loginEnabled = :loginEnabled"),s["#loginEnabled"]=h.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let l=Cr(n.verifiedAt);l===null?(o.push("#verifiedAt"),s["#verifiedAt"]=h.VERIFIED_AT):(i.push("#verifiedAt = :verifiedAt"),s["#verifiedAt"]=h.VERIFIED_AT,a[":verifiedAt"]=l)}n.guards!==void 0&&(i.push("#guards = :guards"),s["#guards"]=h.GUARDS,a[":guards"]=kT(n.guards)),n.pendingVerification!==void 0&&(s["#pendingVerification"]=h.PENDING_VERIFICATION,n.pendingVerification===null?o.push("#pendingVerification"):(i.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Ht({...n.pendingVerification,expiresAt:re(n.pendingVerification.expiresAt),resendAvailableAt:Cr(n.pendingVerification.resendAvailableAt)}))),i.push("#updatedAt = :updatedAt"),s["#updatedAt"]=h.UPDATED_AT,a[":updatedAt"]=ae();let c=[];return i.length>0&&c.push(`SET ${i.join(", ")}`),o.length>0&&c.push(`REMOVE ${o.join(", ")}`),await this.docClient.send(new eh({TableName:this.tableName,Key:{[h.PK]:U.IDENTITY_PK(e,r),[h.SK]:U.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:s,ExpressionAttributeValues:a})),T(void 0)}catch(i){return d(G("update identity",i))}}async remove(e,r){try{return await this.docClient.send(new iO({TableName:this.tableName,Key:{[h.PK]:U.IDENTITY_PK(e,r),[h.SK]:U.IDENTITY_SK()}})),T(void 0)}catch(n){return d(G("remove identity",n))}}async updateGuard(e,r,n,i){let o={[h.PK]:U.IDENTITY_PK(e,r),[h.SK]:U.IDENTITY_SK()};try{return await this.docClient.send(new eh({TableName:this.tableName,Key:o,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":h.GUARDS,"#guardKey":n,"#updatedAt":h.UPDATED_AT},ExpressionAttributeValues:{":guard":th(i),":updatedAt":ae()}})),T(void 0)}catch(s){if(Ce(s))try{return await this.docClient.send(new eh({TableName:this.tableName,Key:o,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":h.GUARDS,"#updatedAt":h.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:th(i)},":updatedAt":ae()}})),T(void 0)}catch(a){return d(G("update guard",a))}return d(G("update guard",s))}}async batchGet(e){try{if(e.length===0)return T([]);let n=(await this.docClient.send(new nO({RequestItems:{[this.tableName]:{Keys:e.map(({type:s,value:a})=>({[h.PK]:U.IDENTITY_PK(s,a),[h.SK]:U.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],i=new Map;for(let s of n){let a=this.unmarshall(s);if(a!==null){let c=`${a.type}#${a.value}`;i.set(c,a)}}let o=e.map(({type:s,value:a})=>{let c=`${s}#${a}`;return i.get(c)||null});return T(o)}catch(r){return d(G("batch get identities",r))}}marshall(e){let r={[h.PK]:U.IDENTITY_PK(e.type,e.value),[h.SK]:U.IDENTITY_SK(),[h.IDENTITY_USER_PK]:U.USER_INDEX_PK(e.userId),[h.IDENTITY_USER_SK]:U.USER_INDEX_SK(e.type,e.value),[h.USER_ID]:e.userId,[h.LOGIN_ENABLED]:e.loginEnabled,[h.CREATED_AT]:re(e.createdAt),[h.UPDATED_AT]:re(e.updatedAt)},n=Cr(e.verifiedAt);return n!==null&&(r[h.VERIFIED_AT]=n),r[h.GUARDS]=kT(e.guards),e.pendingVerification&&(r[h.PENDING_VERIFICATION]=Ht({...e.pendingVerification,expiresAt:re(e.pendingVerification.expiresAt),resendAvailableAt:Cr(e.pendingVerification.resendAvailableAt)})),r}unmarshall(e){let r=le.identityPKInfo(e[h.PK]);if(!r){let n=e[h.IDENTITY_USER_SK]?le.userIndexSKInfo(e[h.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[h.USER_ID],loginEnabled:e[h.LOGIN_ENABLED],verifiedAt:Kt(e[h.VERIFIED_AT]),guards:OT(e[h.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[h.PENDING_VERIFICATION]),createdAt:J(e[h.CREATED_AT]),updatedAt:J(e[h.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[h.PK],GSI1SK:e[h.IDENTITY_USER_SK]}),null)}return{type:r.type,value:r.value,userId:e[h.USER_ID],loginEnabled:e[h.LOGIN_ENABLED],verifiedAt:Kt(e[h.VERIFIED_AT]),guards:OT(e[h.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[h.PENDING_VERIFICATION]),createdAt:J(e[h.CREATED_AT]),updatedAt:J(e[h.UPDATED_AT])}}unmarshallPendingVerification(e){if(!e||typeof e!="object")return null;let r=e;return{challengeId:r.challengeId,purpose:r.purpose,channel:r.channel,expiresAt:J(r.expiresAt),resendAvailableAt:Kt(r.resendAvailableAt)}}};import{TransactWriteCommand as cO}from"@aws-sdk/lib-dynamodb";var pc=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}async createEmailVerificationRegistration(e){try{let r=ae(),n=ht(),i=re(e.challenge.expiresAt),o=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new cO({TransactItems:[this.putItem(this.marshallProfile(e,r)),this.putItem(this.marshallUserAuth(e,r)),this.putItem(this.marshallIdentity(e,r)),this.putItem(this.marshallCredential(e,n,r)),this.putItem(this.marshallChallenge(e,r,o))]})),T(void 0)}catch(r){return Is(r)==="TransactionCanceledException"||Ce(r)?d(te.UniqueConstraintViolation({field:"registration"})):d(G("create email verification registration transaction",r))}}putItem(e){return{Put:{TableName:this.tableName,Item:Ht(e),ConditionExpression:`attribute_not_exists(${h.PK})`}}}marshallProfile(e,r){let n=e.profile.status,i={[h.PK]:U.USER_PK(e.profile.id),[h.SK]:U.USER_PROFILE_SK(),userStatus:n,[h.CREATED_AT]:r,[h.UPDATED_AT]:r,[h.USER_STATUS_PK]:Ae.USER_STATUS_PK(n),[h.USER_STATUS_SK]:Ae.USER_STATUS_SK(e.profile.id)};return e.profile.contactEmail&&(i.contactEmail=e.profile.contactEmail),e.profile.contactPhone&&(i.contactPhone=e.profile.contactPhone),e.profile.username&&(i.username=e.profile.username),e.profile.displayName&&(i.displayName=e.profile.displayName),e.profile.givenName&&(i.givenName=e.profile.givenName),e.profile.familyName&&(i.familyName=e.profile.familyName),e.profile.avatarUrl&&(i.avatarUrl=e.profile.avatarUrl),e.profile.locale&&(i.locale=e.profile.locale),e.profile.metadata&&(i.metadata=JSON.stringify(e.profile.metadata)),i}marshallUserAuth(e,r){return{[h.PK]:U.USER_PK(e.userAuth.userId),[h.SK]:U.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[h.CREATED_AT]:r,[h.UPDATED_AT]:r}}marshallIdentity(e,r){let n=e.identity,i={[h.PK]:U.IDENTITY_PK(n.type,n.value),[h.SK]:U.IDENTITY_SK(),[h.IDENTITY_USER_PK]:U.USER_INDEX_PK(n.userId),[h.IDENTITY_USER_SK]:U.USER_INDEX_SK(n.type,n.value),[h.USER_ID]:n.userId,[h.LOGIN_ENABLED]:n.loginEnabled,[h.CREATED_AT]:r,[h.UPDATED_AT]:r,[h.PENDING_VERIFICATION]:Ht({...n.pendingVerification,expiresAt:re(n.pendingVerification.expiresAt),resendAvailableAt:Cr(n.pendingVerification.resendAvailableAt)})},o=Cr(n.verifiedAt);return o!==null&&(i[h.VERIFIED_AT]=o),i[h.GUARDS]=n.guards??{},i}marshallCredential(e,r,n){let i=e.credential,o={[h.PK]:U.CREDENTIAL_PK(r),[h.SK]:U.CREDENTIAL_SK(),[h.CREDENTIAL_USER_PK]:U.USER_PK(i.userId),[h.CREDENTIAL_USER_SK]:U.CREDENTIAL_USER_SK(i.type,r),[h.USER_ID]:i.userId,[h.CREDENTIAL_VALUE]:i.value,[h.METADATA]:i.data,[h.REVOKED_AT]:i.revokedAt?re(i.revokedAt):null,[h.CREATED_AT]:n,[h.UPDATED_AT]:n};return i.lastUsedAt&&(o[h.LAST_USED_AT]=re(i.lastUsedAt)),o}marshallChallenge(e,r,n){let i=e.challenge,o={[h.PK]:U.CHALLENGE_PK(i.id),[h.SK]:U.CHALLENGE_SK(),[h.USER_ID]:i.userId,[h.PURPOSE]:i.purpose,[h.CHALLENGE_STATUS]:i.status,[h.EXPIRES_AT]:re(i.expiresAt),[h.CREATED_AT]:r,[h.TTL]:n};return i.tenantId&&(o[h.TENANT_ID]=i.tenantId),i.phase&&(o[h.PHASE]=i.phase),i.allowedMethods&&i.allowedMethods.length>0&&(o[h.ALLOWED_METHODS]=i.allowedMethods),i.method&&(o[h.METHOD]=i.method),i.codeHash&&(o[h.CODE_HASH]=i.codeHash),i.attempts!==void 0&&(o[h.ATTEMPTS]=i.attempts),i.maxAttempts!==void 0&&(o[h.MAX_ATTEMPTS]=i.maxAttempts),i.identityType&&(o[h.IDENTITY_TYPE]=i.identityType),i.identityValue&&(o[h.IDENTITY_VALUE]=i.identityValue),i.deviceLabel&&(o[h.DEVICE_LABEL]=i.deviceLabel),i.country&&(o[h.COUNTRY]=i.country),i.city&&(o[h.CITY]=i.city),i.metadata&&(o[h.METADATA]=i.metadata),i.flowKey&&(o[h.FLOW_KEY]=i.flowKey),o}};import{DynamoDBClient as dO}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as pO,GetCommand as PT,PutCommand as fO,QueryCommand as fc,UpdateCommand as bs}from"@aws-sdk/lib-dynamodb";import{BatchGetCommand as lO}from"@aws-sdk/lib-dynamodb";var CT=100,DT=5;function uO(t){return new Promise(e=>setTimeout(e,t))}async function xs(t,e,r){if(r.length===0)return[];let n=[];for(let i=0;i<r.length;i+=CT){let o=r.slice(i,i+CT),s=0;for(;o.length>0;){let a=await t.send(new lO({RequestItems:{[e]:{Keys:o}}})),c=a.Responses?.[e];c&&n.push(...c);let l=a.UnprocessedKeys?.[e]?.Keys;if(!l||l.length===0)break;if(s+=1,s>DT)throw new Error(`BatchGet left ${l.length} unprocessed keys after ${DT} retries`);o=l,await uO(2**s*25)}}return n}var mc=class{docClient;tableName;ttlGracePeriod;constructor(e){let r=e.client||new dO({});this.docClient=e.docClient||pO.from(r),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return ht()}generateTokenId(){return ht()}async get(e){try{let r=await this.docClient.send(new PT({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()}}));return r.Item?T(this.unmarshall(r.Item)):T(null)}catch(r){return d(G("get session",r))}}async create(e){try{let r=ae(),n=e.id||this.generateSessionId(),i=e.tokenId||this.generateTokenId(),o={...e,id:n,tokenId:i,revokedAt:null,createdAt:new Date(r),lastUsedAt:new Date(r)},s=sc(re(e.expiresAt)+this.ttlGracePeriod),a=hd.sessionSK(r,n);return await this.docClient.send(new fO({TableName:this.tableName,Item:this.marshall(o,s,a)})),T(o)}catch(r){return d(G("create session",r))}}async update(e,r){try{let n=[],i={},o={};if(r.tokenId!==void 0&&(n.push(`#${h.TOKEN_ID} = :tokenId`),i[`#${h.TOKEN_ID}`]=h.TOKEN_ID,o[":tokenId"]=r.tokenId),r.expiresAt!==void 0){n.push(`#${h.EXPIRES_AT} = :expiresAt`),i[`#${h.EXPIRES_AT}`]=h.EXPIRES_AT,o[":expiresAt"]=re(r.expiresAt);let s=sc(re(r.expiresAt)+this.ttlGracePeriod);n.push(`#${h.TTL} = :ttl`),i[`#${h.TTL}`]=h.TTL,o[":ttl"]=s}return r.lastUsedAt!==void 0&&(n.push(`#${h.LAST_USED_AT} = :lastUsedAt`),i[`#${h.LAST_USED_AT}`]=h.LAST_USED_AT,o[":lastUsedAt"]=re(r.lastUsedAt)),r.metadata!==void 0&&(n.push(`#${h.METADATA} = :metadata`),i[`#${h.METADATA}`]=h.METADATA,o[":metadata"]=r.metadata),r.previousTokenId!==void 0&&(n.push(`#${h.PREVIOUS_TOKEN_ID} = :previousTokenId`),i[`#${h.PREVIOUS_TOKEN_ID}`]=h.PREVIOUS_TOKEN_ID,o[":previousTokenId"]=r.previousTokenId),r.rotatedAt!==void 0&&(n.push(`#${h.ROTATED_AT} = :rotatedAt`),i[`#${h.ROTATED_AT}`]=h.ROTATED_AT,o[":rotatedAt"]=r.rotatedAt),n.length===0?T():(await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:o})),T())}catch(n){return d(G("update session",n))}}async rotateToken(e,r,n){try{let i=sc(re(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET #${h.TOKEN_ID} = :tokenId, #${h.PREVIOUS_TOKEN_ID} = :previousTokenId, #${h.ROTATED_AT} = :rotatedAt, #${h.EXPIRES_AT} = :expiresAt, #${h.LAST_USED_AT} = :lastUsedAt, #${h.TTL} = :ttl`,ConditionExpression:`#${h.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${h.TOKEN_ID}`]:h.TOKEN_ID,[`#${h.PREVIOUS_TOKEN_ID}`]:h.PREVIOUS_TOKEN_ID,[`#${h.ROTATED_AT}`]:h.ROTATED_AT,[`#${h.EXPIRES_AT}`]:h.EXPIRES_AT,[`#${h.LAST_USED_AT}`]:h.LAST_USED_AT,[`#${h.TTL}`]:h.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":re(n.expiresAt),":lastUsedAt":re(n.lastUsedAt),":ttl":i,":expectedCurrentTokenId":r}})),T(!0)}catch(i){return Ce(i)?T(!1):d(G("rotate session token",i))}}async switchTenant(e,r){try{let n=[`#${h.TENANT_ID} = :tenantId`,`#${h.TOKEN_ID} = :tokenId`,`#${h.LAST_USED_AT} = :lastUsedAt`],i=[],o={[`#${h.TENANT_ID}`]:h.TENANT_ID,[`#${h.TOKEN_ID}`]:h.TOKEN_ID,[`#${h.LAST_USED_AT}`]:h.LAST_USED_AT},s={":tenantId":r.tenantId,":tokenId":r.tokenId,":lastUsedAt":ae()};o[`#${h.TENANT_TYPE}`]=h.TENANT_TYPE,r.tenantType!==void 0?(n.push(`#${h.TENANT_TYPE} = :tenantType`),s[":tenantType"]=r.tenantType):i.push(`#${h.TENANT_TYPE}`),o[`#${h.PERM}`]=h.PERM,r.perms!==void 0?(n.push(`#${h.PERM} = :perms`),s[":perms"]=JSON.stringify(r.perms)):i.push(`#${h.PERM}`),o[`#${h.ROLES}`]=h.ROLES,r.roles!==void 0?(n.push(`#${h.ROLES} = :roles`),s[":roles"]=r.roles):i.push(`#${h.ROLES}`),o["#revokedAt"]=h.REVOKED_AT;let a=`SET ${n.join(", ")}${i.length>0?` REMOVE ${i.join(", ")}`:""}`;return await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:o,ExpressionAttributeValues:s,ConditionExpression:`attribute_exists(${h.PK}) AND attribute_not_exists(#revokedAt)`})),T()}catch(n){return Ce(n)?d(te.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):d(G("switch tenant",n))}}async revoke(e){try{return await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET #${h.REVOKED_AT} = :revokedAt REMOVE #${h.ACTIVE_SESSION_PK}, #${h.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${h.REVOKED_AT}`]:h.REVOKED_AT,[`#${h.ACTIVE_SESSION_PK}`]:h.ACTIVE_SESSION_PK,[`#${h.ACTIVE_SESSION_SK}`]:h.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":re(new Date)},ConditionExpression:`attribute_exists(${h.PK})`})),T()}catch(r){return Ce(r)?T():d(G("revoke session",r))}}async revokeByIdAndUserId(e,r){try{return await this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(e),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET #${h.REVOKED_AT} = :revokedAt REMOVE #${h.ACTIVE_SESSION_PK}, #${h.ACTIVE_SESSION_SK}`,ConditionExpression:`#${h.USER_ID} = :userId AND attribute_not_exists(#${h.REVOKED_AT})`,ExpressionAttributeNames:{[`#${h.REVOKED_AT}`]:h.REVOKED_AT,[`#${h.USER_ID}`]:h.USER_ID,[`#${h.ACTIVE_SESSION_PK}`]:h.ACTIVE_SESSION_PK,[`#${h.ACTIVE_SESSION_SK}`]:h.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":re(new Date),":userId":r}})),T()}catch(n){return Ce(n)?T():d(G("revoke session by user",n))}}async findByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return d(te.DatabaseQueryError({query:"invalid pagination cursor"}))}let o=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.USER_SESSIONS,KeyConditionExpression:`${h.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":U.USER_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!o.Items||o.Items.length===0){let m={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return T([],{pagination:m})}let a=o.Items.map(m=>le.sessionId(m[h.PK])).map(m=>({[h.PK]:U.SESSION_PK(m),[h.SK]:U.SESSION_SK()})),l=(await xs(this.docClient,this.tableName,a)).map(m=>this.unmarshall(m)),u=!!o.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null,f={type:"cursor",limit:n,count:l.length,hasNext:u,hasPrev:!!r?.cursor,cursor:p};return T(l,{pagination:f})}catch(n){return d(G("find sessions by user",n))}}async findActiveByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return d(te.DatabaseQueryError({query:"invalid pagination cursor"}))}let o=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.ACTIVE_SESSIONS,KeyConditionExpression:`${h.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!o.Items||o.Items.length===0){let m={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return T([],{pagination:m})}let a=o.Items.map(m=>le.sessionId(m[h.PK])).map(m=>({[h.PK]:U.SESSION_PK(m),[h.SK]:U.SESSION_SK()})),l=(await xs(this.docClient,this.tableName,a)).map(m=>this.unmarshall(m)),u=!!o.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null,f={type:"cursor",limit:n,count:l.length,hasNext:u,hasPrev:!!r?.cursor,cursor:p};return T(l,{pagination:f})}catch(n){return d(G("find active sessions by user",n))}}async getActiveSessionsForLimit(e){try{let r=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.ACTIVE_SESSIONS,KeyConditionExpression:`${h.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!r.Items||r.Items.length===0)return T([]);let n=r.Items.map(i=>{let o=le.sessionId(i[h.PK]),s=hd.extractCreatedAt(i[h.ACTIVE_SESSION_SK]);return{id:o,createdAt:new Date(s)}});return T(n)}catch(r){return d(G("get active sessions for limit",r))}}async revokeSessionsByIds(e,r){if(e.length===0)return 0;let n=re(new Date),i=await Promise.allSettled(e.map(s=>this.docClient.send(new bs({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(s),[h.SK]:U.SESSION_SK()},UpdateExpression:`SET #${h.REVOKED_AT} = :revokedAt REMOVE #${h.ACTIVE_SESSION_PK}, #${h.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${h.REVOKED_AT}`]:h.REVOKED_AT,[`#${h.ACTIVE_SESSION_PK}`]:h.ACTIVE_SESSION_PK,[`#${h.ACTIVE_SESSION_SK}`]:h.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),o=0;for(let s of i)s.status==="fulfilled"?o+=1:console.error(`[session-repo] ${r}: session revoke failed (may remain active):`,{name:Is(s.reason)});return o}async revokeAllByUserId(e,r){try{let n=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.ACTIVE_SESSIONS,KeyConditionExpression:`${h.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return T(0);let i=n.Items.map(s=>le.sessionId(s[h.PK])).filter(s=>!r||s!==r),o=await this.revokeSessionsByIds(i,"revokeAllByUserId");return T(o)}catch(n){return d(G("revoke all sessions by user",n))}}async revokeBatch(e){try{let r=await this.revokeSessionsByIds(e,"revokeBatch");return T(r)}catch(r){return d(G("revoke batch sessions",r))}}async countByUserId(e){try{let r=await this.docClient.send(new fc({TableName:this.tableName,IndexName:ue.ACTIVE_SESSIONS,KeyConditionExpression:`${h.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return T(r.Count||0)}catch(r){return d(G("count active sessions by user",r))}}async isTokenActive(e,r){try{let n=await this.docClient.send(new PT({TableName:this.tableName,Key:{[h.PK]:U.SESSION_PK(r),[h.SK]:U.SESSION_SK()},ProjectionExpression:`${h.TOKEN_ID}, ${h.REVOKED_AT}, ${h.EXPIRES_AT}`}));if(!n.Item)return T(!1);let i=n.Item,o=i[h.TOKEN_ID]===e&&!i[h.REVOKED_AT]&&J(i[h.EXPIRES_AT])>new Date;return T(o)}catch(n){return d(G("check token active",n))}}marshall(e,r,n){let i={[h.PK]:U.SESSION_PK(e.id),[h.SK]:U.SESSION_SK(),[h.USER_SESSION_PK]:U.USER_PK(e.userId),[h.USER_SESSION_SK]:n,...!e.revokedAt&&{[h.ACTIVE_SESSION_PK]:Ae.ACTIVE_SESSION_PK(e.userId),[h.ACTIVE_SESSION_SK]:n},[h.USER_ID]:e.userId,[h.TOKEN_ID]:e.tokenId,[h.EXPIRES_AT]:re(e.expiresAt),[h.CREATED_AT]:re(e.createdAt),[h.LAST_USED_AT]:re(e.lastUsedAt),[h.TTL]:r};return e.tenantId&&(i[h.TENANT_ID]=e.tenantId),e.tenantType&&(i[h.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(i[h.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(i[h.ROLES]=e.roles),e.deviceLabel&&(i[h.DEVICE_LABEL]=e.deviceLabel),e.country&&(i[h.COUNTRY]=e.country),e.city&&(i[h.CITY]=e.city),e.metadata&&(i[h.METADATA]=e.metadata),e.revokedAt&&(i[h.REVOKED_AT]=re(e.revokedAt)),e.previousTokenId&&(i[h.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(i[h.ROTATED_AT]=e.rotatedAt),i}unmarshall(e){let n={id:le.sessionId(e[h.PK]),userId:e[h.USER_ID],tokenId:e[h.TOKEN_ID],expiresAt:J(e[h.EXPIRES_AT]),createdAt:J(e[h.CREATED_AT]),lastUsedAt:J(e[h.LAST_USED_AT]),revokedAt:e[h.REVOKED_AT]?J(e[h.REVOKED_AT]):null};return e[h.TENANT_ID]&&(n.tenantId=e[h.TENANT_ID]),e[h.TENANT_TYPE]&&(n.tenantType=e[h.TENANT_TYPE]),e[h.PERM]!==void 0&&(n.perms=JSON.parse(e[h.PERM])),e[h.ROLES]!==void 0&&(n.roles=e[h.ROLES]),e[h.DEVICE_LABEL]&&(n.deviceLabel=e[h.DEVICE_LABEL]),e[h.COUNTRY]&&(n.country=e[h.COUNTRY]),e[h.CITY]&&(n.city=e[h.CITY]),e[h.METADATA]&&(n.metadata=e[h.METADATA]),e[h.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[h.PREVIOUS_TOKEN_ID]),e[h.ROTATED_AT]!==void 0&&(n.rotatedAt=e[h.ROTATED_AT]),n}};import{QueryCommand as mO}from"@aws-sdk/lib-dynamodb";var hc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":h.INVITE_TENANT_PK},o={":pk":Ae.INVITE_TENANT_PK(e)},s={TableName:this.tableName,IndexName:ue.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:o,ScanIndexForward:!1,Limit:n};r?.cursor&&(s.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(s.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=h.INVITE_TENANT_SK,o[":statusPrefix"]=Ae.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new mO(s)),c=(a.Items||[]).map(p=>this.toListItem(p)),l=!!a.LastEvaluatedKey,u=l?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return mr(c,{limit:n,hasNext:l,cursor:u,prevCursor:r?.cursor??null})}catch(n){return d(G("listByTenant query",n))}}toListItem(e){let r=le.inviteId(e.PK),n={id:e.invitedById};e.invitedByInfo&&(e.invitedByInfo.name&&(n.name=e.invitedByInfo.name),e.invitedByInfo.email&&(n.email=e.invitedByInfo.email),e.invitedByInfo.jobTitle&&(n.jobTitle=e.invitedByInfo.jobTitle));let i={id:r,tenantId:e.tenantId,invitedBy:n,status:e.inviteStatus,expiresAt:J(e.expiresAt),createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};return e.inviteeUserId&&(i.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(i.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(i.inviteePhone=e.inviteePhone),e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),e.displayName&&(i.displayName=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.jobTitle&&(i.jobTitle=e.jobTitle),e.acceptedAt&&(i.acceptedAt=J(e.acceptedAt)),e.declinedAt&&(i.declinedAt=J(e.declinedAt)),e.revokedAt&&(i.revokedAt=J(e.revokedAt)),i}};import{GetCommand as UT,PutCommand as hO,QueryCommand as fi,UpdateCommand as EO}from"@aws-sdk/lib-dynamodb";var yO=10080*60*1e3,Ec=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:le.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:J(e.expiresAt),createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};e.inviteeUserId&&(n.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(n.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(n.inviteePhone=e.inviteePhone),e.roles!==void 0&&(n.roles=e.roles);let i=e[h.PERM];return i!==void 0&&(n.perms=JSON.parse(i)),e.authPerm!==void 0&&(n.authPerm=e.authPerm),e.displayName&&(n.displayName=e.displayName),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.jobTitle&&(n.jobTitle=e.jobTitle),e.acceptedAt&&(n.acceptedAt=J(e.acceptedAt)),e.declinedAt&&(n.declinedAt=J(e.declinedAt)),e.revokedAt&&(n.revokedAt=J(e.revokedAt)),n}generateInviteId(){return ht()}async getById(e){try{let r=await this.docClient.send(new UT({TableName:this.tableName,Key:{PK:U.INVITE_PK(e),SK:U.INVITE_SK()}}));return r.Item?T(this.mapItemToEntity(r.Item)):T(null)}catch(r){return d(G("getById invite",r))}}async getByToken(e){try{let n=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":h.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return T(null);let i=n[0],o=await this.docClient.send(new UT({TableName:this.tableName,Key:{PK:i.PK,SK:i.SK}}));return o.Item?T(this.mapItemToEntity(o.Item)):T(null)}catch(r){return d(G("getByToken invite",r))}}async create(e){try{let r=ae(),n=re(e.expiresAt),i=Math.floor((n+yO)/1e3),o={PK:U.INVITE_PK(e.id),SK:U.INVITE_SK(),[h.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[h.INVITED_BY_ID]:e.invitedById,[h.INVITE_STATUS]:e.status,[h.INVITE_TOKEN]:e.inviteToken,[h.EXPIRES_AT]:n,[h.CREATED_AT]:r,[h.UPDATED_AT]:r,[h.TTL]:i,[h.INVITE_TENANT_PK]:Ae.INVITE_TENANT_PK(e.tenantId),[h.INVITE_TENANT_SK]:Ae.INVITE_TENANT_SK(e.status,r,e.id),[h.INVITE_TOKEN_GSI]:e.inviteToken},s={};e.invitedByName&&(s.name=e.invitedByName),e.invitedByEmail&&(s.email=e.invitedByEmail),e.invitedByJobTitle&&(s.jobTitle=e.invitedByJobTitle),Object.keys(s).length>0&&(o[h.INVITED_BY_INFO]=s),e.inviteeUserId&&(o[h.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(o[h.INVITEE_EMAIL]=e.inviteeEmail,o[h.INVITEE_EMAIL_GSI]=e.inviteeEmail,o[h.INVITEE_EMAIL_TENANT_SK]=`${ce.TENANT}${e.tenantId}`),e.inviteePhone&&(o[h.INVITEE_PHONE]=e.inviteePhone,o[h.INVITEE_PHONE_GSI]=e.inviteePhone,o[h.INVITEE_PHONE_TENANT_SK]=`${ce.TENANT}${e.tenantId}`),e.roles!==void 0&&(o[h.ROLES]=e.roles),e.perms!==void 0&&(o[h.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(o[h.AUTH_PERM]=e.authPerm),e.displayName&&(o[h.DISPLAY_NAME]=e.displayName),e.givenName&&(o.givenName=e.givenName),e.familyName&&(o.familyName=e.familyName),e.jobTitle&&(o.jobTitle=e.jobTitle),await this.docClient.send(new hO({TableName:this.tableName,Item:o,ConditionExpression:"attribute_not_exists(PK)"}));let a={id:e.id,tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.status,inviteToken:e.inviteToken,expiresAt:e.expiresAt,createdAt:J(r),updatedAt:J(r)};return e.inviteeUserId&&(a.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(a.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(a.inviteePhone=e.inviteePhone),e.roles!==void 0&&(a.roles=e.roles),e.perms!==void 0&&(a.perms=e.perms),e.authPerm!==void 0&&(a.authPerm=e.authPerm),e.displayName&&(a.displayName=e.displayName),e.givenName&&(a.givenName=e.givenName),e.familyName&&(a.familyName=e.familyName),e.jobTitle&&(a.jobTitle=e.jobTitle),T(a)}catch(r){return r.name==="ConditionalCheckFailedException"?d(te.UniqueConstraintViolation({field:"invite id"})):d(Rt("create invite",r))}}async updateStatus(e,r){try{let n=ae(),i=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],o={"#inviteStatus":h.INVITE_STATUS,"#inviteTenantSk":h.INVITE_TENANT_SK,"#updatedAt":h.UPDATED_AT},s={":inviteStatus":r.status,":inviteTenantSk":Ae.INVITE_TENANT_SK(r.status,n,e),":updatedAt":n};r.acceptedAt&&(i.push("#acceptedAt = :acceptedAt"),o["#acceptedAt"]=h.ACCEPTED_AT,s[":acceptedAt"]=re(r.acceptedAt)),r.declinedAt&&(i.push("#declinedAt = :declinedAt"),o["#declinedAt"]=h.DECLINED_AT,s[":declinedAt"]=re(r.declinedAt)),r.revokedAt&&(i.push("#revokedAt = :revokedAt"),o["#revokedAt"]=h.REVOKED_AT,s[":revokedAt"]=re(r.revokedAt));let a=[];r.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),o["#inviteTokenGsi"]=h.INVITE_TOKEN_GSI,o["#inviteeEmailGsi"]=h.INVITEE_EMAIL_GSI,o["#inviteeEmailTenantSk"]=h.INVITEE_EMAIL_TENANT_SK,o["#inviteePhoneGsi"]=h.INVITEE_PHONE_GSI,o["#inviteePhoneTenantSk"]=h.INVITEE_PHONE_TENANT_SK);let c=`SET ${i.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new EO({TableName:this.tableName,Key:{PK:U.INVITE_PK(e),SK:U.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:o,ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"TenantInvite",id:e})):d(Rt("updateStatus invite",n))}}async findByTenantAndEmail(e,r){try{let i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":h.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":h.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":r,":tenantSk":`${ce.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?T(null):T(this.mapItemToEntity(i[0]))}catch(n){return d(G("findByTenantAndEmail",n))}}async findByTenantAndPhone(e,r){try{let i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":h.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":h.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":r,":tenantSk":`${ce.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?T(null):T(this.mapItemToEntity(i[0]))}catch(n){return d(G("findByTenantAndPhone",n))}}async findByTenantAndUserId(e,r){try{let i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":h.INVITE_TENANT_PK,"#sk":h.INVITE_TENANT_SK,"#inviteeUserId":h.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":Ae.INVITE_TENANT_PK(e),":pendingPrefix":Ae.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":r},Limit:1}))).Items;return!i||i.length===0?T(null):T(this.mapItemToEntity(i[0]))}catch(n){return d(G("findByTenantAndUserId",n))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":h.INVITE_TENANT_PK},o={":pk":Ae.INVITE_TENANT_PK(e)},s={TableName:this.tableName,IndexName:ue.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:o,ScanIndexForward:!1,Limit:n};r?.cursor&&(s.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(s.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=h.INVITE_TENANT_SK,o[":statusPrefix"]=Ae.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new fi(s)),c=(a.Items||[]).map(p=>this.mapItemToEntity(p)),l=!!a.LastEvaluatedKey,u=l?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return mr(c,{limit:n,hasNext:l,cursor:u,prevCursor:r?.cursor??null})}catch(n){return d(G("listByTenant",n))}}async findPendingByEmail(e){try{let r=ae(),i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":h.INVITEE_EMAIL_GSI,"#expiresAt":h.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":r}}))).Items||[];if(i.length===0)return T([]);let o=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await xs(this.docClient,this.tableName,o)).map(c=>this.mapItemToEntity(c));return T(a)}catch(r){return d(G("findPendingByEmail",r))}}async findPendingByPhone(e){try{let r=ae(),i=(await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":h.INVITEE_PHONE_GSI,"#expiresAt":h.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":r}}))).Items||[];if(i.length===0)return T([]);let o=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await xs(this.docClient,this.tableName,o)).map(c=>this.mapItemToEntity(c));return T(a)}catch(r){return d(G("findPendingByPhone",r))}}async countPendingByTenant(e){try{let r=await this.docClient.send(new fi({TableName:this.tableName,IndexName:ue.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":h.INVITE_TENANT_PK,"#sk":h.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":Ae.INVITE_TENANT_PK(e),":pendingPrefix":Ae.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return T(r.Count??0)}catch(r){return d(G("countPendingByTenant",r))}}async expireOld(e){return T(0)}};import{QueryCommand as gO}from"@aws-sdk/lib-dynamodb";var yc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":U.TENANT_MEMBER_PK(e)}};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let s=(await this.docClient.send(new gO(i))).Items||[],a=[],c=new Map;for(let m of s){let E=m.SK;if(E.startsWith(Be.TENANT_PROFILE)){let v=le.tenantProfileUserId(E);c.set(v,m)}else E.startsWith(ce.USER)&&a.push(m)}a.sort((m,E)=>E.createdAt-m.createdAt);let l=a.slice(0,n),u=a.length>n,p=l.map(m=>{let E=le.tenantMemberUserId(m.SK),v=c.get(E);return this.toListItem(m,e,E,v)}),f=u&&l.length>0?Buffer.from(JSON.stringify({PK:l[l.length-1].PK,SK:l[l.length-1].SK})).toString("base64url"):null;return mr(p,{limit:n,hasNext:u,cursor:f,prevCursor:r?.cursor??null})}catch(n){return d(G("listByTenant query",n))}}toListItem(e,r,n,i){let o={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};if(e.roles!==void 0&&(o.roles=e.roles),e.perms!==void 0&&(o.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(o.authPerm=e.authPerm),i){let s={tenantId:r,userId:n,createdAt:J(i.createdAt),updatedAt:J(i.updatedAt)};i.contactEmail&&(s.contactEmail=i.contactEmail),i.contactPhone&&(s.contactPhone=i.contactPhone),i.displayName&&(s.displayName=i.displayName),i.displayNameSource&&(s.displayNameSource=i.displayNameSource),i.givenName&&(s.givenName=i.givenName),i.familyName&&(s.familyName=i.familyName),i.avatarUrl&&(s.avatarUrl=i.avatarUrl),i.locale&&(s.locale=i.locale),i.jobTitle&&(s.jobTitle=i.jobTitle),i.bio&&(s.bio=i.bio),i.metadata&&(s.metadata=JSON.parse(i.metadata)),o.tenantProfile=s}return o}};import{DeleteCommand as vO,DynamoDBDocumentClient as AO,GetCommand as LT,PutCommand as TO,QueryCommand as _O,TransactWriteCommand as IO,UpdateCommand as MT}from"@aws-sdk/lib-dynamodb";var gc=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=AO.from(e)}mapItemToEntity(e){let r=le.tenantId(e.PK),n=le.tenantMemberUserId(e.SK),i={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};return e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),i}async get(e,r){try{let n=await this.docClient.send(new LT({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_MEMBER_SK(r)}}));if(!n.Item)return T(null);let i=this.mapItemToEntity(n.Item);return T(i)}catch(n){return d(G("get",n))}}async create(e){try{let r=ae(),n=e.isOwner?void 0:e.authPerm,i=Ht({PK:U.TENANT_MEMBER_PK(e.tenantId),SK:U.TENANT_MEMBER_SK(e.userId),userStatus:e.status,roles:e.roles,perms:e.perms!==void 0?JSON.stringify(e.perms):void 0,authPerm:n,isOwner:e.isOwner,createdAt:r,updatedAt:r,userTenantPk:Ae.USER_TENANT_PK(e.userId),userTenantSk:Ae.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,r,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new IO({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:U.TENANT_MEMBER_PK(e.tenantId),SK:U.TENANT_OWNER_MARKER_SK(),createdAt:r},ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}},{Put:{TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}}]})):await this.docClient.send(new TO({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(void 0)}catch(r){return r.name==="TransactionCanceledException"?r.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?d(te.UniqueConstraintViolation({field:"tenant owner"})):d(te.UniqueConstraintViolation({field:"tenant member"})):r.name==="ConditionalCheckFailedException"?d(te.UniqueConstraintViolation({field:"tenant member"})):d(Rt("create tenant member",r))}}async updatePermissions(e,r,n){try{let i={...n,updatedAt:ae()},{UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a}=Dr(i);return await this.docClient.send(new MT({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_MEMBER_SK(r)},UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"TenantMember",id:`${e}:${r}`})):d(Rt("updatePermissions tenant member",i))}}async updateStatus(e,r,n){try{return await this.docClient.send(new MT({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_MEMBER_SK(r)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":ae()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"TenantMember",id:`${e}:${r}`})):d(Rt("updateStatus tenant member",i))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":U.TENANT_MEMBER_PK(e),":skPrefix":ce.USER},Limit:n};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let o=await this.docClient.send(new _O(i)),s=(o.Items||[]).map(l=>this.mapItemToEntity(l)),a=!!o.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return mr(s,{limit:n,hasNext:a,cursor:c,prevCursor:r?.cursor??null})}catch(n){return d(G("listByTenant",n))}}async hasOwner(e){try{let r=await this.docClient.send(new LT({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_OWNER_MARKER_SK()}}));return T(!!r.Item)}catch(r){return d(G("hasOwner",r))}}async remove(e,r){try{return await this.docClient.send(new vO({TableName:this.tableName,Key:{PK:U.TENANT_MEMBER_PK(e),SK:U.TENANT_MEMBER_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"TenantMember",id:`${e}:${r}`})):d(Rt("remove tenant member",n))}}};import{BatchGetCommand as xO,QueryCommand as bO}from"@aws-sdk/lib-dynamodb";var vc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByUser(e,r){try{let n=Math.min(r?.limit??50,100),i=r?.tenantType??Qt.DEFAULT,o=r?.parentTenantId,s=o?`${i}#${o}#`:`${i}#`,a={TableName:this.tableName,IndexName:ue.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":Ae.USER_TENANT_PK(e),":skPrefix":s},ScanIndexForward:!1,Limit:n};r?.cursor&&(a.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let c=await this.docClient.send(new bO(a)),l=c.Items??[],u=await this.fetchProfileMap(e,l),p=l.map(E=>this.toListItem(E,e,u)),f=!!c.LastEvaluatedKey,m=f?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return mr(p,{limit:n,hasNext:f,cursor:m,prevCursor:r?.cursor??null})}catch(n){return d(G("listByUser query",n))}}async fetchProfileMap(e,r){let n=new Map;if(r.length===0)return n;let i=r.map(s=>({PK:U.TENANT_PROFILE_PK(le.tenantId(s.PK)),SK:U.TENANT_PROFILE_SK(e)})),o=await this.docClient.send(new xO({RequestItems:{[this.tableName]:{Keys:i}}}));for(let s of o.Responses?.[this.tableName]??[]){let a=s,c=le.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,r,n){let i=le.tenantId(e.PK),o={tenantId:i,userId:r,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};e.roles!==void 0&&(o.roles=e.roles),e.perms!==void 0&&(o.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(o.authPerm=e.authPerm);let s=n.get(i);return s&&(s.contactEmail&&(o.contactEmail=s.contactEmail),s.contactPhone&&(o.contactPhone=s.contactPhone),s.displayName&&(o.displayName=s.displayName),s.displayNameSource&&(o.displayNameSource=s.displayNameSource),s.givenName&&(o.givenName=s.givenName),s.familyName&&(o.familyName=s.familyName),s.avatarUrl&&(o.avatarUrl=s.avatarUrl),s.locale&&(o.locale=s.locale),s.jobTitle&&(o.jobTitle=s.jobTitle),s.bio&&(o.bio=s.bio),s.metadata&&(o.metadata=JSON.parse(s.metadata))),o}};import{DeleteCommand as SO,GetCommand as wO,PutCommand as NO,UpdateCommand as RO}from"@aws-sdk/lib-dynamodb";var Ac=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return ht()}toEntity(e){let n={id:le.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let r=await this.docClient.send(new wO({TableName:this.tableName,Key:{PK:U.TENANT_PK(e),SK:U.TENANT_SK()}}));return r.Item?T(this.toEntity(r.Item)):T(null)}catch(r){return d(G("get tenant",r))}}async create(e){try{let r=e.id??this.generateTenantId(),n=ae(),i=Ht({PK:U.TENANT_PK(r),SK:U.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new NO({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?d(te.UniqueConstraintViolation({field:"tenant"})):d(Rt("create tenant",r))}}async update(e,r){try{let n={updatedAt:ae()};r.type!==void 0&&(n.tenantType=r.type),r.ownerId!==void 0&&(n.ownerId=r.ownerId),r.parentTenantId!==void 0&&(n.parentTenantId=r.parentTenantId===null?void 0:r.parentTenantId);let{UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:s}=Dr(n);return await this.docClient.send(new RO({TableName:this.tableName,Key:{PK:U.TENANT_PK(e),SK:U.TENANT_SK()},UpdateExpression:i,ExpressionAttributeNames:o,ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"Tenant",id:e})):d(Rt("update tenant",n))}}async delete(e){try{return await this.docClient.send(new SO({TableName:this.tableName,Key:{PK:U.TENANT_PK(e),SK:U.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"Tenant",id:e})):d(Rt("delete tenant",r))}}async list(){return d(te.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return d(te.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return d(te.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};import{DeleteCommand as OO,GetCommand as kO,PutCommand as CO,UpdateCommand as vd}from"@aws-sdk/lib-dynamodb";var Tc=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let r=await this.docClient.send(new kO({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()}}));return r.Item?T(this.unmarshall(r.Item,e)):T(null)}catch(r){return d(G("get user auth",r))}}async create(e){try{let r=ae(),n={...e,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new CO({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${h.PK})`})),T(n)}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"userAuth"})):d(G("create user auth",r))}}async updateStatus(e,r){try{let n=ae();return await this.docClient.send(new vd({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${h.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${h.UPDATED_AT}`]:h.UPDATED_AT},ExpressionAttributeValues:{":userStatus":r,":updatedAt":n},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userAuth",id:e})):d(G("update user auth status",n))}}async updateMfaRequired(e,r){try{let n=ae();return await this.docClient.send(new vd({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${h.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${h.UPDATED_AT}`]:h.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r,":updatedAt":n},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userAuth",id:e})):d(G("update mfa required",n))}}async updateMfaMethods(e,r){try{let n=ae();return await this.docClient.send(new vd({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${h.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${h.UPDATED_AT}`]:h.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":r,":updatedAt":n},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userAuth",id:e})):d(G("update mfa methods",n))}}async updateMfaSettings(e,r){try{let n=ae();return await this.docClient.send(new vd({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${h.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${h.UPDATED_AT}`]:h.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r.mfaRequired,":mfaMethods":r.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${h.PK})`})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userAuth",id:e})):d(G("update mfa settings",n))}}async remove(e){try{return await this.docClient.send(new OO({TableName:this.tableName,Key:{[h.PK]:U.USER_PK(e),[h.SK]:U.USER_AUTH_SK()}})),T(void 0)}catch(r){return d(G("remove user auth",r))}}marshall(e){return{[h.PK]:U.USER_PK(e.userId),[h.SK]:U.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[h.CREATED_AT]:re(e.createdAt),[h.UPDATED_AT]:re(e.updatedAt)}}unmarshall(e,r){return{userId:r,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:J(e[h.CREATED_AT]),updatedAt:J(e[h.UPDATED_AT])}}};import{DynamoDBDocumentClient as DO,DeleteCommand as PO,GetCommand as UO,PutCommand as LO,QueryCommand as KT,UpdateCommand as rh}from"@aws-sdk/lib-dynamodb";function Ss(t,e){return e?U.USER_MFA_WITH_ID_SK(t,e):U.USER_MFA_SK(t)}var _c=class{client;tableName;docClient;constructor(e,r){this.client=e,this.tableName=r,this.docClient=DO.from(e)}toDynamoDBItem(e){let r={PK:U.USER_PK(e.userId),SK:Ss(e.method,e.id),method:e.method,data:JSON.stringify(e.data),createdAt:Date.now(),failedAttempts:0};return e.label&&(r.label=e.label),e.verifiedAt&&(r.verifiedAt=e.verifiedAt.getTime()),e.metadata&&(r.metadata=JSON.stringify(e.metadata)),r}fromDynamoDBItem(e,r){let n=le.mfaSKInfo(e.SK),i={userId:r,method:e.method,data:JSON.parse(e.data),createdAt:J(e.createdAt),verifiedAt:Kt(e.verifiedAt)??null};return n?.id&&(i.id=n.id),e.label&&(i.label=e.label),e.failedAttempts!==void 0&&(i.failedAttempts=e.failedAttempts),e.lastFailedAt!==void 0&&(i.lastFailedAt=Kt(e.lastFailedAt)),e.lockedUntil!==void 0&&(i.lockedUntil=Kt(e.lockedUntil)),e.lastUsedAt!==void 0&&(i.lastUsedAt=Kt(e.lastUsedAt)),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r,n){try{let i=Ss(r,n),o=await this.docClient.send(new UO({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:i}}));return o.Item?T(this.fromDynamoDBItem(o.Item,e)):T(null)}catch(i){return d(G("get MFA authenticator",i))}}async findByUserId(e){try{let r={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":U.USER_PK(e),":skPrefix":Be.MFA}},o=((await this.docClient.send(new KT(r))).Items??[]).map(s=>this.fromDynamoDBItem(s,e));return T(o)}catch(r){return d(G("find MFA authenticators by user",r))}}async findByUserIdAndMethod(e,r){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":U.USER_PK(e),":skPrefix":`${Be.MFA}${r}`}},s=((await this.docClient.send(new KT(n))).Items??[]).filter(a=>a.method===r).map(a=>this.fromDynamoDBItem(a,e));return T(s)}catch(n){return d(G("find MFA authenticators by method",n))}}async create(e){try{let r={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(r.id=ht());let n=this.toDynamoDBItem(r);return await this.docClient.send(new LO({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),T(this.fromDynamoDBItem(n,e.userId))}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"MFA authenticator"})):d(G("create MFA authenticator",r))}}async update(e,r,n,i){try{let o=Ss(r,n),s=[],a={},c={};if(i.label!==void 0&&(s.push("#label = :label"),a["#label"]="label",c[":label"]=i.label),i.data!==void 0&&(s.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(i.data)),i.verifiedAt!==void 0&&(s.push("#verifiedAt = :verifiedAt"),a["#verifiedAt"]="verifiedAt",c[":verifiedAt"]=i.verifiedAt instanceof Date?i.verifiedAt.getTime():i.verifiedAt===null?void 0:i.verifiedAt),i.lastUsedAt!==void 0&&(s.push("#lastUsedAt = :lastUsedAt"),a["#lastUsedAt"]="lastUsedAt",c[":lastUsedAt"]=i.lastUsedAt instanceof Date?i.lastUsedAt.getTime():i.lastUsedAt===null?void 0:i.lastUsedAt),i.failedAttempts!==void 0&&(s.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=i.failedAttempts),i.lastFailedAt!==void 0&&(s.push("#lastFailedAt = :lastFailedAt"),a["#lastFailedAt"]="lastFailedAt",c[":lastFailedAt"]=i.lastFailedAt instanceof Date?i.lastFailedAt.getTime():i.lastFailedAt===null?void 0:i.lastFailedAt),i.lockedUntil!==void 0&&(s.push("#lockedUntil = :lockedUntil"),a["#lockedUntil"]="lockedUntil",c[":lockedUntil"]=i.lockedUntil instanceof Date?i.lockedUntil.getTime():i.lockedUntil===null?void 0:i.lockedUntil),i.metadata!==void 0&&(s.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(i.metadata)),s.length===0)return T(void 0);let l={TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:o},UpdateExpression:`SET ${s.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new rh(l)),T(void 0)}catch(o){return d(G("update MFA authenticator",o))}}async remove(e,r,n){try{let i=Ss(r,n);return await this.docClient.send(new PO({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:i}})),T(void 0)}catch(i){return d(G("remove MFA authenticator",i))}}async incrementFailedAttempts(e,r,n,i,o){try{let s=Ss(r,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],l={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},u={":zero":0,":inc":1,":lastFailedAt":a};o!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),l["#lockedUntil"]="lockedUntil",u[":lockedUntil"]=a+o*60*1e3,u[":maxAttempts"]=i);let p={TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:s},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:l,ExpressionAttributeValues:u};return await this.docClient.send(new rh(p)),T(void 0)}catch(s){return d(G("increment failed attempts",s))}}async resetFailedAttempts(e,r,n){try{let i=Ss(r,n),o={TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:i},UpdateExpression:"SET #failedAttempts = :zero REMOVE #lastFailedAt, #lockedUntil",ExpressionAttributeNames:{"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt","#lockedUntil":"lockedUntil"},ExpressionAttributeValues:{":zero":0}};return await this.docClient.send(new rh(o)),T(void 0)}catch(i){return d(G("reset failed attempts",i))}}async unlock(e,r,n){return this.resetFailedAttempts(e,r,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};import{DeleteCommand as MO,DynamoDBDocumentClient as KO,GetCommand as HO,PutCommand as FO,QueryCommand as HT,UpdateCommand as FT}from"@aws-sdk/lib-dynamodb";var Ic=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=KO.from(e)}generateUserId(){return ht()}async getById(e){try{let r=await this.docClient.send(new HO({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:U.USER_PROFILE_SK()}}));if(!r.Item)return T(null);let n=r.Item;if(n.deletedAt)return T(null);let o={id:le.userId(n.PK),status:n.userStatus,createdAt:J(n.createdAt),updatedAt:J(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:J(n.deletedAt)},...n.contactEmail!==void 0&&{contactEmail:n.contactEmail},...n.contactPhone!==void 0&&{contactPhone:n.contactPhone},...n.username!==void 0&&{username:n.username},...n.displayName!==void 0&&{displayName:n.displayName},...n.givenName!==void 0&&{givenName:n.givenName},...n.familyName!==void 0&&{familyName:n.familyName},...n.avatarUrl!==void 0&&{avatarUrl:n.avatarUrl},...n.locale!==void 0&&{locale:n.locale},...n.metadata!==void 0&&{metadata:JSON.parse(n.metadata)}};return T(o)}catch(r){return d(G("getById user",r))}}async create(e){try{let r=ae(),n=e.id||this.generateUserId(),i=e.status||"pending",o={PK:U.USER_PK(n),SK:U.USER_PROFILE_SK(),userStatus:i,createdAt:r,updatedAt:r};e.contactEmail&&(o.contactEmail=e.contactEmail),e.contactPhone&&(o.contactPhone=e.contactPhone),e.username&&(o.username=e.username),e.displayName&&(o.displayName=e.displayName),e.givenName&&(o.givenName=e.givenName),e.familyName&&(o.familyName=e.familyName),e.avatarUrl&&(o.avatarUrl=e.avatarUrl),e.locale&&(o.locale=e.locale),e.metadata&&(o.metadata=JSON.stringify(e.metadata)),o[h.USER_STATUS_PK]=Ae.USER_STATUS_PK(i),o[h.USER_STATUS_SK]=Ae.USER_STATUS_SK(n),await this.docClient.send(new FO({TableName:this.tableName,Item:Ht(o),ConditionExpression:qm("PK")}));let s={id:n,status:i,createdAt:J(r),updatedAt:J(r),...e.contactEmail&&{contactEmail:e.contactEmail},...e.contactPhone&&{contactPhone:e.contactPhone},...e.username&&{username:e.username},...e.displayName&&{displayName:e.displayName},...e.givenName&&{givenName:e.givenName},...e.familyName&&{familyName:e.familyName},...e.avatarUrl&&{avatarUrl:e.avatarUrl},...e.locale&&{locale:e.locale},...e.metadata&&{metadata:e.metadata}};return T(s)}catch(r){return d(G("create user",r))}}async updateProfile(e,r){try{let n=ae(),i={};if(r.contactEmail!==void 0&&(i.contactEmail=r.contactEmail),r.contactPhone!==void 0&&(i.contactPhone=r.contactPhone),r.displayName!==void 0&&(i.displayName=r.displayName),r.givenName!==void 0&&(i.givenName=r.givenName),r.familyName!==void 0&&(i.familyName=r.familyName),r.avatarUrl!==void 0&&(i.avatarUrl=r.avatarUrl),r.locale!==void 0&&(i.locale=r.locale),r.metadata!==void 0&&(i.metadata=JSON.stringify(r.metadata)),Object.keys(i).length===0)return T(void 0);i.updatedAt=n;let o=Dr(i);return await this.docClient.send(new FT({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:U.USER_PROFILE_SK()},UpdateExpression:o.UpdateExpression,ExpressionAttributeNames:o.ExpressionAttributeNames,ExpressionAttributeValues:o.ExpressionAttributeValues})),T(void 0)}catch(n){return d(G("updateProfile",n))}}async getByStatus(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return d(te.DatabaseQueryError({query:"invalid pagination cursor"}))}let o=Ae.USER_STATUS_PK(e),s=await this.docClient.send(new HT({TableName:this.tableName,IndexName:ue.USERS_BY_STATUS,KeyConditionExpression:`${h.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":o},Limit:n,ExclusiveStartKey:i})),a=[];if(s.Items&&s.Items.length>0)for(let u of s.Items){let p=le.userId(u.PK);a.push(p)}let c=!!s.LastEvaluatedKey,l=c?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null;return T(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!r?.cursor,cursor:l}})}catch(n){return d(G("get users by status",n))}}async countByStatus(e){try{let r=Ae.USER_STATUS_PK(e),n=await this.docClient.send(new HT({TableName:this.tableName,IndexName:ue.USERS_BY_STATUS,KeyConditionExpression:`${h.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":r},Select:"COUNT"}));return T(n.Count||0)}catch(r){return d(G("count users by status",r))}}async syncAuthStatus(e,r){try{let n=ae(),i=`SET userStatus = :userStatus, #${h.UPDATED_AT} = :updatedAt, #${h.USER_STATUS_PK} = :statusPk, #${h.USER_STATUS_SK} = :statusSk`,o={":userStatus":r,":updatedAt":n,":statusPk":Ae.USER_STATUS_PK(r),":statusSk":Ae.USER_STATUS_SK(e)};return r===ye.DELETED?(i+=", deletedAt = :deletedAt",o[":deletedAt"]=n):i+=" REMOVE deletedAt",await this.docClient.send(new FT({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:U.USER_PROFILE_SK()},UpdateExpression:i,ExpressionAttributeNames:{[`#${h.UPDATED_AT}`]:h.UPDATED_AT,[`#${h.USER_STATUS_PK}`]:h.USER_STATUS_PK,[`#${h.USER_STATUS_SK}`]:h.USER_STATUS_SK},ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),T(void 0)}catch(n){return Ce(n)?d(te.NotFound({entity:"userProfile",id:e})):d(G("sync auth status",n))}}async remove(e){try{return await this.docClient.send(new MO({TableName:this.tableName,Key:{PK:U.USER_PK(e),SK:U.USER_PROFILE_SK()}})),T(void 0)}catch(r){return d(G("remove user profile",r))}}};import{DeleteCommand as VO,DynamoDBDocumentClient as BO,GetCommand as jO,PutCommand as GO,QueryCommand as $O,UpdateCommand as qO}from"@aws-sdk/lib-dynamodb";var xc=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=BO.from(e)}mapItemToUserProviderLink(e){let r=le.providerPKInfo(e.PK);if(!r)throw new Error(`Invalid provider PK: ${e.PK}`);let n={userId:e.userId,provider:r.provider,externalId:r.externalId,createdAt:J(e.createdAt)};if(e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata)try{n.metadata=JSON.parse(e.metadata)}catch{}return n}mapUserProviderLinkToItem(e){let r=ae(),n={PK:U.PROVIDER_PK(e.provider,e.externalId),SK:U.PROVIDER_METADATA_SK(),userProviderPk:U.USER_PK(e.userId),userProviderSk:U.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?re(e.createdAt):r};return e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),Ht(n)}async findByProviderAndExternalId(e,r){try{let n=await this.docClient.send(new jO({TableName:this.tableName,Key:{PK:U.PROVIDER_PK(e,r),SK:U.PROVIDER_METADATA_SK()}}));return n.Item?T(this.mapItemToUserProviderLink(n.Item)):T(null)}catch(n){return d(G("find provider by external id",n))}}async findByUserId(e){try{let r=await this.docClient.send(new $O({TableName:this.tableName,IndexName:ue.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":h.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":U.USER_PK(e)}}));return!r.Items||r.Items.length===0?T([]):T(r.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch(r){return d(G("find providers by user id",r))}}async create(e){try{let r={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(r);return await this.docClient.send(new GO({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),T(this.mapItemToUserProviderLink(n))}catch(r){return Ce(r)?d(te.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):d(G("create user provider",r))}}async update(e,r,n){try{let i={};if(n.externalUsername!==void 0&&(i.externalUsername=n.externalUsername),n.externalEmail!==void 0&&(i.externalEmail=n.externalEmail),n.externalPhone!==void 0&&(i.externalPhone=n.externalPhone),n.externalName!==void 0&&(i.externalName=n.externalName),n.externalAvatarUrl!==void 0&&(i.externalAvatarUrl=n.externalAvatarUrl),n.metadata!==void 0&&(i.metadata=JSON.stringify(n.metadata)),Object.keys(i).length===0)return T(void 0);let{UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a}=Dr(i);return await this.docClient.send(new qO({TableName:this.tableName,Key:{PK:U.PROVIDER_PK(e,r),SK:U.PROVIDER_METADATA_SK()},UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a})),T(void 0)}catch(i){return d(G("update user provider",i))}}async remove(e,r){try{return await this.docClient.send(new VO({TableName:this.tableName,Key:{PK:U.PROVIDER_PK(e,r),SK:U.PROVIDER_METADATA_SK()}})),T(void 0)}catch(n){return d(G("delete user provider",n))}}};import{DeleteCommand as WO,GetCommand as zO,PutCommand as JO,UpdateCommand as YO}from"@aws-sdk/lib-dynamodb";var bc=class{docClient;tableName;constructor(e,r){this.docClient=e,this.tableName=r}mapItemToEntity(e){let r=le.tenantId(e.PK),n=le.tenantProfileUserId(e.SK),i={tenantId:r,userId:n,createdAt:J(e.createdAt),updatedAt:J(e.updatedAt)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r){try{let n=await this.docClient.send(new zO({TableName:this.tableName,Key:{PK:U.TENANT_PROFILE_PK(e),SK:U.TENANT_PROFILE_SK(r)}}));return n.Item?T(this.mapItemToEntity(n.Item)):T(null)}catch(n){return d(G("get user tenant profile",n))}}async create(e){try{let r=ae(),n={PK:U.TENANT_PROFILE_PK(e.tenantId),SK:U.TENANT_PROFILE_SK(e.userId),createdAt:r,updatedAt:r};e.contactEmail&&(n.contactEmail=e.contactEmail),e.contactPhone&&(n.contactPhone=e.contactPhone),e.displayName&&(n.displayName=e.displayName),e.displayNameSource&&(n.displayNameSource=e.displayNameSource),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.locale&&(n.locale=e.locale),e.jobTitle&&(n.jobTitle=e.jobTitle),e.bio&&(n.bio=e.bio),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),await this.docClient.send(new JO({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let i={tenantId:e.tenantId,userId:e.userId,createdAt:J(r),updatedAt:J(r)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=e.metadata),T(i)}catch(r){return r.name==="ConditionalCheckFailedException"?d(te.UniqueConstraintViolation({field:"user tenant profile"})):d(Rt("create user tenant profile",r))}}async update(e,r,n){try{let i={updatedAt:ae()};n.contactEmail!==void 0&&(i.contactEmail=n.contactEmail),n.contactPhone!==void 0&&(i.contactPhone=n.contactPhone),n.displayName!==void 0&&(i.displayName=n.displayName),n.displayNameSource!==void 0&&(i.displayNameSource=n.displayNameSource),n.givenName!==void 0&&(i.givenName=n.givenName),n.familyName!==void 0&&(i.familyName=n.familyName),n.avatarUrl!==void 0&&(i.avatarUrl=n.avatarUrl),n.locale!==void 0&&(i.locale=n.locale),n.jobTitle!==void 0&&(i.jobTitle=n.jobTitle),n.bio!==void 0&&(i.bio=n.bio),n.metadata!==void 0&&(i.metadata=n.metadata?JSON.stringify(n.metadata):null);let{UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a}=Dr(i);return await this.docClient.send(new YO({TableName:this.tableName,Key:{PK:U.TENANT_PROFILE_PK(e),SK:U.TENANT_PROFILE_SK(r)},UpdateExpression:o,ExpressionAttributeNames:s,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):d(Rt("update user tenant profile",i))}}async remove(e,r){try{return await this.docClient.send(new WO({TableName:this.tableName,Key:{PK:U.TENANT_PROFILE_PK(e),SK:U.TENANT_PROFILE_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),T(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?d(te.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):d(Rt("remove user tenant profile",n))}}};var nh=class{name="database-dynamodb";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;registration;userAuths;tenantMembers;tenantInvites;userTenantProfiles;tenants;queries;client;tableName;constructor(e){this.tableName=e.tableName,this.client=e.client||new QO(e.clientConfig||{});let r=ZO.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new Ic(this.client,this.tableName),this.sessions=new mc({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new xc(this.client,this.tableName),this.userMfaAuthenticators=new _c(this.client,this.tableName),this.challenges=new lc({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new dc({docClient:r,tableName:this.tableName}),this.credentials=new uc({docClient:r,tableName:this.tableName}),this.registration=new pc({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new Tc({docClient:r,tableName:this.tableName}),this.tenantMembers=new gc(this.client,this.tableName),this.tenantInvites=new Ec({docClient:r,tableName:this.tableName}),this.userTenantProfiles=new bc(r,this.tableName),this.tenants=new Ac({docClient:r,tableName:this.tableName}),this.queries={tenantInvites:new hc({docClient:r,tableName:this.tableName}),tenantMembers:new yc({docClient:r,tableName:this.tableName}),tenants:new vc({docClient:r,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new XO({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};function VT(t){return new nh(t)}ra();var ih=1,BT=2,jT=3,GT="auth-craft:internal";async function ek(t){let e=t.replace(/^0x/,""),r=qT(e),n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length);let o=`-----BEGIN PRIVATE KEY-----
132
132
  `+btoa(String.fromCharCode(...i)).match(/.{1,64}/g).join(`
133
133
  `)+`
134
134
  -----END PRIVATE KEY-----`;return ta(o,"EdDSA")}async function tk(t){let e=t.replace(/^0x/,""),r=qT(e),n=nk(r);return Vt({kty:"OKP",crv:"Ed25519",x:n},"EdDSA")}async function oh(t,e){if(e==="EdDSA"){let r=t.trim();if(r.startsWith("{"))return Vt(JSON.parse(r),e);if(!r.includes(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auth-craft/aws-cf-stack",
3
- "version": "1.10.1",
3
+ "version": "1.10.2",
4
4
  "description": "Self-contained, versioned distribution of the Auth Craft AWS (DynamoDB + Lambda) + Cloudflare gateway stack. Bundles prebuilt Lambda/worker artifacts + CDK app so consumers deploy without cloning auth-craft.",
5
5
  "type": "module",
6
6
  "bin": {