@auth-craft/aws-cf-stack 1.6.1 → 1.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/admin/cli.mjs +1 -1
- package/assets/lambda/index.mjs +2 -1
- package/package.json +1 -1
package/assets/admin/cli.mjs
CHANGED
|
@@ -184,7 +184,7 @@ Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{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 w(this.toEntity(r[0]))}catch(r){let n=r;return n.code==="23505"?T(N.UniqueConstraintViolation({field:"provider link"})):n.code==="23503"?T(N.ForeignKeyViolation({field:"userId"})):T(N.DatabaseQueryError({query:"create provider"}))}}async update(e,r,n){try{let i=[],s=[],o=1;return n.externalUsername!==void 0&&(i.push(`external_username = $${o++}`),s.push(n.externalUsername??null)),n.externalEmail!==void 0&&(i.push(`external_email = $${o++}`),s.push(n.externalEmail??null)),n.externalPhone!==void 0&&(i.push(`external_phone = $${o++}`),s.push(n.externalPhone??null)),n.externalName!==void 0&&(i.push(`external_name = $${o++}`),s.push(n.externalName??null)),n.externalAvatarUrl!==void 0&&(i.push(`external_avatar_url = $${o++}`),s.push(n.externalAvatarUrl??null)),n.metadata!==void 0&&(i.push(`metadata = $${o++}`),s.push(n.metadata?JSON.stringify(n.metadata):null)),i.length===0?w(void 0):(s.push(e,r),await this.pool.query(`UPDATE user_providers SET ${i.join(", ")} WHERE provider = $${o++} AND external_id = $${o}`,s),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update provider"}))}}async remove(e,r){try{return await this.pool.query("DELETE FROM user_providers WHERE provider = $1 AND external_id = $2",[e,r]),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove provider"}))}}toEntity(e){let r={userId:e.user_id,provider:e.provider,externalId:e.external_id,createdAt:new Date(e.created_at)};return e.external_username&&(r.externalUsername=e.external_username),e.external_email&&(r.externalEmail=e.external_email),e.external_phone&&(r.externalPhone=e.external_phone),e.external_name&&(r.externalName=e.external_name),e.external_avatar_url&&(r.externalAvatarUrl=e.external_avatar_url),e.metadata&&(r.metadata=e.metadata),r}};var yd=class{pool;constructor(e){this.pool=e}async get(e,r){try{let{rows:n}=await this.pool.query("SELECT * FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,r]);return n.length===0?w(null):w(this.toEntity(n[0]))}catch{return T(N.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let{rows:r}=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 w(this.toEntity(r[0]))}catch(r){console.error("[DEBUG] user_tenant_profiles insert error:",r);let n=r;return n.code==="23505"?T(N.UniqueConstraintViolation({field:"tenant profile"})):n.code==="23503"?T(N.ForeignKeyViolation({field:"userId"})):T(N.DatabaseQueryError({query:"create user tenant profile"}))}}async update(e,r,n){try{let i=["updated_at = NOW()"],s=[],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&&(i.push(`${u} = $${o++}`),s.push(n[c]??null));return n.metadata!==void 0&&(i.push(`metadata = $${o++}`),s.push(n.metadata?JSON.stringify(n.metadata):null)),s.length===0?w(void 0):(s.push(e,r),await this.pool.query(`UPDATE user_tenant_profiles SET ${i.join(", ")} WHERE tenant_id = $${o++} AND user_id = $${o}`,s),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update user tenant profile"}))}}async remove(e,r){try{return await this.pool.query("DELETE FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,r]),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user tenant profile"}))}}toEntity(e){let r={tenantId:e.tenant_id,userId:e.user_id,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)};return e.contact_email&&(r.contactEmail=e.contact_email),e.contact_phone&&(r.contactPhone=e.contact_phone),e.display_name&&(r.displayName=e.display_name),e.display_name_source&&(r.displayNameSource=e.display_name_source),e.given_name&&(r.givenName=e.given_name),e.family_name&&(r.familyName=e.family_name),e.avatar_url&&(r.avatarUrl=e.avatar_url),e.locale&&(r.locale=e.locale),e.job_title&&(r.jobTitle=e.job_title),e.bio&&(r.bio=e.bio),e.metadata&&(r.metadata=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata),r}};var mb=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 Ed(e),this.userAuths=new md(e),this.sessions=new sd(e),this.identities=new id(e),this.credentials=new nd(e),this.challenges=new rd(e),this.userProviders=new gd(e),this.userMfaAuthenticators=new hd(e),this.tenants=new fd(e),this.tenantMembers=new ud(e),this.tenantInvites=new ad(e),this.userTenantProfiles=new yd(e),this.queries={tenantInvites:new od(e),tenantMembers:new cd(e),tenants:new ld(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 HO(t){let e=new mh(t);return new mb(e)}var _J={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function GO(t={}){let e={..._J,...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 s=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}@${s}$`)})();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 T([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(i.length>254)return T([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(i))return T([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(i.includes(".."))return T([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let s=i.split("@");if(s.length!==2)return T([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[o,a]=s;return!o||o.length>64?T([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?T([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):w()}}}var z_=ge(v_(),1),m8=ge(ir(),1);function Te(t){return t.getTime()}function oe(t){return new Date(t)}function n8(t){return Math.floor(t/1e3)}function Ne(){return Date.now()}function Kf(t){return t instanceof Date?n8(t.getTime()):n8(t)}function tv(t){return t<Date.now()}function Ui(t){return t?Te(t):null}function Xr(t){return t==null?null:oe(t)}function Zr(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}function $i(t){let e=[],r=[],n={},i={},s=0;for(let[c,u]of Object.entries(t)){if(c==="PK"||c==="SK")continue;let p=`#${c}`;if(n[p]=c,u==null)r.push(p);else{let d=`:val${s}`;e.push(`${p} = ${d}`),i[d]=u,s++}}let o=[];return e.length>0&&o.push(`SET ${e.join(", ")}`),r.length>0&&o.push(`REMOVE ${r.join(", ")}`),{UpdateExpression:o.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:i}}function rv(t="PK"){return`attribute_not_exists(${t})`}var wr={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},mge=wr.VIEW_ACCOUNTS|wr.UPDATE_ACCOUNT_PROFILE|wr.UPDATE_ACCOUNT_STATUS|wr.RESET_ACCOUNT_CREDENTIALS|wr.REMOVE_ACCOUNTS;var i8={[wr.INVITE_MEMBERS]:"tenant.member.invite",[wr.REMOVE_MEMBERS]:"tenant.member.remove",[wr.VIEW_MEMBERS]:"tenant.member.view",[wr.CHANGE_MEMBER_PERMISSION]:"tenant.member.permission",[wr.UPDATE_MEMBER_PROFILE]:"tenant.member.profile.update",[wr.UPDATE_MEMBER_STATUS]:"tenant.member.status.update",[wr.VIEW_ACCOUNTS]:"account.view",[wr.UPDATE_ACCOUNT_PROFILE]:"account.profile.update",[wr.UPDATE_ACCOUNT_STATUS]:"account.status.update",[wr.RESET_ACCOUNT_CREDENTIALS]:"account.credentials.reset",[wr.REMOVE_ACCOUNTS]:"account.remove"},hge=Object.fromEntries(Object.entries(i8).map(([t,e])=>[e,Number(t)]));var nv={SYSTEM:"system",DEFAULT:"org"};var iv={USER:"USR"},De={USER:`${iv.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},_t={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},Cr="#",K={USER_PK:t=>`${De.USER}${t}`,USER_AUTH_SK:()=>_t.AUTH,USER_PROFILE_SK:()=>_t.PROFILE,USER_MFA_SK:t=>`${_t.MFA}${t}`,USER_MFA_WITH_ID_SK:(t,e)=>`${_t.MFA}${t}${Cr}${e}`,TENANT_MEMBER_PK:t=>`${De.TENANT}${t}`,TENANT_MEMBER_SK:t=>`${De.USER}${t}`,TENANT_OWNER_MARKER_SK:()=>_t.OWNER,TENANT_PK:t=>`${De.TENANT}${t}`,TENANT_SK:()=>_t.METADATA,INVITE_PK:t=>`${De.INVITE}${t}`,INVITE_SK:()=>_t.METADATA,TENANT_PROFILE_PK:t=>`${De.TENANT}${t}`,TENANT_PROFILE_SK:t=>`${_t.TENANT_PROFILE}${De.USER}${t}`,SESSION_PK:t=>`${De.SESSION}${t}`,SESSION_METADATA_SK:()=>_t.METADATA,SESSION_SK:()=>_t.METADATA,PROVIDER_SK:(t,e)=>`${_t.PROVIDER}${t}${Cr}${e}`,PROVIDER_PK:(t,e)=>`${De.PROVIDER}${t}${Cr}${e}`,PROVIDER_METADATA_SK:()=>_t.METADATA,CHALLENGE_PK:t=>`${De.CHALLENGE}${t}`,CHALLENGE_SK:()=>_t.METADATA,IDENTITY_PK:(t,e)=>`${De.IDENTITY}${t}#${e}`,IDENTITY_SK:()=>_t.METADATA,CREDENTIAL_PK:t=>`${De.CREDENTIAL}${t}`,CREDENTIAL_SK:()=>_t.METADATA,CREDENTIAL_TYPE_PREFIX:t=>`${De.CREDENTIAL}${t}#`,CREDENTIAL_USER_SK:(t,e)=>`${De.CREDENTIAL}${t}#${e}`,USER_INDEX_PK:t=>`${De.USER}${t}`,USER_INDEX_SK:(t,e)=>`${De.IDENTITY}${t}#${e}`},ve={userId:t=>t.slice(De.USER.length),sessionId:t=>t.slice(De.SESSION.length),providerPKInfo:t=>{let e=t.slice(De.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(_t.PROVIDER.length),r=e.indexOf(Cr);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(_t.MFA.length),r=e.indexOf(Cr);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(De.TENANT.length),tenantMemberUserId:t=>t.slice(De.USER.length),challengeIdFromPK:t=>t.slice(De.CHALLENGE.length),inviteId:t=>t.slice(De.INVITE.length),tenantProfileUserId:t=>t.slice(_t.TENANT_PROFILE.length+De.USER.length),identityPKInfo:t=>{let e=t.slice(De.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(De.CREDENTIAL.length),credentialTypeFromUserSK:t=>{let e=t.slice(De.CREDENTIAL.length),r=e.indexOf("#");return r===-1?"":e.slice(0,r)},userIndexSKInfo:t=>{let e=t.slice(De.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 ze={ACTIVE_SESSION_PK:t=>`${De.USER}${t}`,ACTIVE_SESSION_SK:(t,e)=>`${t}${Cr}${e}`,USER_SESSION_PK:t=>`${De.USER}${t}`,USER_SESSION_SK:(t,e)=>`${t}${Cr}${e}`,USER_STATUS_PK:t=>{let e=t===Hi.ACTIVE?"ACTIVE":"INACTIVE";return`${iv.USER}${Cr}${e}`},USER_STATUS_SK:t=>t,USER_PROVIDER_PK:t=>`${De.USER}${t}`,USER_PROVIDER_SK:(t,e)=>`${_t.PROVIDER}${t}${Cr}${e}`,INVITE_TENANT_PK:t=>`${De.TENANT}${t}`,INVITE_TENANT_SK:(t,e,r)=>`${t}${Cr}${e}${Cr}${r}`,INVITE_TENANT_STATUS_PREFIX:t=>`${t}${Cr}`,USER_TENANT_PK:t=>`${De.USER}${t}`,USER_TENANT_SK:(t,e,r,n)=>`${t}${Cr}${e??"ROOT"}${Cr}${r}${Cr}${n}`},E={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"},tt={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"},q_={sessionSK:(t,e)=>`${t instanceof Date?t.getTime():t}${Cr}${e}`,extractCreatedAt:t=>{let e=t.indexOf(Cr),r=e===-1?t:t.slice(0,e);return Number(r)}};var Po=ge(ir(),1);function Vf(t){if(typeof t=="object"&&t!==null&&"name"in t){let{name:e}=t;return typeof e=="string"?e:void 0}}function lt(t){return Vf(t)==="ConditionalCheckFailedException"}var Hf=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return Lt()}async get(e){try{let r=await this.docClient.send(new Po.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()}}));if(!r.Item)return w(null);let n=this.unmarshall(r.Item);return tv(Te(n.expiresAt))?w(null):w(n)}catch{return T(N.DatabaseQueryError({query:"get challenge"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateChallengeId(),i={...e,id:n,createdAt:oe(r)},s=Te(e.expiresAt),o=Math.floor((s+this.ttlGracePeriod)/1e3);return await this.docClient.send(new Po.PutCommand({TableName:this.tableName,Item:this.marshall(i,o)})),w(i)}catch{return T(N.DatabaseQueryError({query:"create challenge"}))}}async update(e,r){try{let n=[],i={},s={};return r.method!==void 0&&(n.push("#method = :method"),i["#method"]=E.METHOD,s[":method"]=r.method),r.phase!==void 0&&(n.push("#phase = :phase"),i["#phase"]=E.PHASE,s[":phase"]=r.phase),r.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),i["#codeHash"]=E.CODE_HASH,s[":codeHash"]=r.codeHash),r.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),i["#challengeStatus"]=E.CHALLENGE_STATUS,s[":challengeStatus"]=r.status),n.length===0?w(void 0):(await this.docClient.send(new Po.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update challenge"}))}}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 o=(await this.docClient.send(new Po.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...i?{ConditionExpression:i}:{},ExpressionAttributeNames:{"#attempts":E.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[E.ATTEMPTS]??0;return w(o)}catch(s){return lt(s)?T(N.AttemptsExceeded()):T(N.DatabaseQueryError({query:"increment challenge attempts"}))}}async remove(e){try{return await this.docClient.send(new Po.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":E.PK}})),w(void 0)}catch(r){return lt(r)?w(void 0):T(N.DatabaseQueryError({query:"remove challenge"}))}}marshall(e,r){let n={[E.PK]:K.CHALLENGE_PK(e.id),[E.SK]:K.CHALLENGE_SK(),[E.USER_ID]:e.userId,[E.PURPOSE]:e.purpose,[E.CHALLENGE_STATUS]:e.status,[E.EXPIRES_AT]:Te(e.expiresAt),[E.CREATED_AT]:Te(e.createdAt),[E.TTL]:r};return e.tenantId&&(n[E.TENANT_ID]=e.tenantId),e.phase&&(n[E.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[E.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[E.METHOD]=e.method),e.codeHash&&(n[E.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[E.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[E.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[E.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[E.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[E.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[E.COUNTRY]=e.country),e.city&&(n[E.CITY]=e.city),e.metadata&&(n[E.METADATA]=e.metadata),e.flowKey&&(n[E.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:ve.challengeIdFromPK(e[E.PK]),userId:e[E.USER_ID],purpose:e[E.PURPOSE],status:e[E.CHALLENGE_STATUS],expiresAt:oe(e[E.EXPIRES_AT]),createdAt:oe(e[E.CREATED_AT])};return e[E.TENANT_ID]&&(n.tenantId=e[E.TENANT_ID]),e[E.PHASE]&&(n.phase=e[E.PHASE]),e[E.ALLOWED_METHODS]&&(n.allowedMethods=e[E.ALLOWED_METHODS]),e[E.METHOD]&&(n.method=e[E.METHOD]),e[E.CODE_HASH]&&(n.codeHash=e[E.CODE_HASH]),e[E.ATTEMPTS]!==void 0&&(n.attempts=e[E.ATTEMPTS]),e[E.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[E.MAX_ATTEMPTS]),e[E.IDENTITY_TYPE]&&(n.identityType=e[E.IDENTITY_TYPE]),e[E.IDENTITY_VALUE]&&(n.identityValue=e[E.IDENTITY_VALUE]),e[E.DEVICE_LABEL]&&(n.deviceLabel=e[E.DEVICE_LABEL]),e[E.COUNTRY]&&(n.country=e[E.COUNTRY]),e[E.CITY]&&(n.city=e[E.CITY]),e[E.METADATA]&&(n.metadata=e[E.METADATA]),e[E.FLOW_KEY]&&(n.flowKey=e[E.FLOW_KEY]),n}};var en=ge(ir(),1);var Gf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return Lt()}async get(e){try{let r=await this.docClient.send(new en.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()}}));return r.Item?w(this.unmarshall(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get credential"}))}}async getByUserIdAndType(e,r){try{let n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk AND begins_with(${E.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":K.USER_PK(e),":typePrefix":K.CREDENTIAL_TYPE_PREFIX(r)},Limit:1}));if(!n.Items||n.Items.length===0)return w(null);let i=n.Items[0];if(!i)return w(null);let s=ve.credentialId(i[E.PK]);return this.get(s)}catch{return T(N.DatabaseQueryError({query:"get credential by user and type"}))}}async getByUserId(e){try{let r=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)}}));if(!r.Items||r.Items.length===0)return w([]);let n=r.Items.map(o=>ve.credentialId(o[E.PK])),i=await this.batchGet(n);if(i.ok===!1)return T(i.errors,i.meta);if(!i.data)return w([]);let s=i.data.filter(o=>o!==null);return w(s)}catch{return T(N.DatabaseQueryError({query:"get credentials by user"}))}}async create(e){try{let r=Ne(),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 en.PutCommand({TableName:this.tableName,Item:this.marshall(i),ConditionExpression:`attribute_not_exists(${E.PK})`})),w(i)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"credential"})):T(N.DatabaseQueryError({query:"create credential"}))}}async update(e,r){try{let n=Ne(),i=[],s={},o={};return i.push(`#${E.UPDATED_AT} = :updatedAt`),s[`#${E.UPDATED_AT}`]=E.UPDATED_AT,o[":updatedAt"]=n,r.value!==void 0&&(i.push(`#${E.CREDENTIAL_VALUE} = :value`),s[`#${E.CREDENTIAL_VALUE}`]=E.CREDENTIAL_VALUE,o[":value"]=r.value),r.data!==void 0&&(i.push(`#${E.METADATA} = :data`),s[`#${E.METADATA}`]=E.METADATA,o[":data"]=r.data),r.revokedAt!==void 0&&(i.push(`#${E.REVOKED_AT} = :revokedAt`),s[`#${E.REVOKED_AT}`]=E.REVOKED_AT,o[":revokedAt"]=r.revokedAt?Te(r.revokedAt):null),r.lastUsedAt!==void 0&&(i.push(`#${E.LAST_USED_AT} = :lastUsedAt`),s[`#${E.LAST_USED_AT}`]=E.LAST_USED_AT,o[":lastUsedAt"]=r.lastUsedAt?Te(r.lastUsedAt):null),await this.docClient.send(new en.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()},UpdateExpression:`SET ${i.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"credential",id:e})):T(N.DatabaseQueryError({query:"update credential"}))}}async remove(e){try{return await this.docClient.send(new en.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(r){return lt(r)?T(N.NotFound({entity:"credential",id:e})):T(N.DatabaseQueryError({query:"delete credential"}))}}async hasType(e,r){try{let n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk AND begins_with(${E.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":K.USER_PK(e),":typePrefix":K.CREDENTIAL_TYPE_PREFIX(r)},Select:"COUNT",Limit:1}));return w((n.Count||0)>0)}catch{return T(N.DatabaseQueryError({query:"check credential type"}))}}async countByUserId(e){try{let r=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)},Select:"COUNT"}));return w(r.Count||0)}catch{return T(N.DatabaseQueryError({query:"count credentials"}))}}async batchGet(e){if(e.length===0)return w([]);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 o=(await this.docClient.send(new en.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:i.map(c=>({[E.PK]:K.CREDENTIAL_PK(c),[E.SK]:K.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 i)n.push(a.get(c)||null)}return w(n)}catch{return T(N.DatabaseQueryError({query:"batch get credentials"}))}}marshall(e){let r={[E.PK]:K.CREDENTIAL_PK(e.id),[E.SK]:K.CREDENTIAL_SK(),[E.CREDENTIAL_USER_PK]:K.USER_PK(e.userId),[E.CREDENTIAL_USER_SK]:K.CREDENTIAL_USER_SK(e.type,e.id),[E.USER_ID]:e.userId,[E.CREDENTIAL_VALUE]:e.value,[E.METADATA]:e.data,[E.REVOKED_AT]:e.revokedAt?Te(e.revokedAt):null,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)};return e.lastUsedAt&&(r[E.LAST_USED_AT]=Te(e.lastUsedAt)),r}unmarshall(e){let r=ve.credentialId(e[E.PK]),n=ve.credentialTypeFromUserSK(e[E.CREDENTIAL_USER_SK]);return{id:r,userId:e[E.USER_ID],type:n,value:e[E.CREDENTIAL_VALUE],data:e[E.METADATA]||{},revokedAt:Xr(e[E.REVOKED_AT]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT]),lastUsedAt:Xr(e[E.LAST_USED_AT])}}};var Tn=ge(ir(),1);function sv(t){return{failedAttempts:t.failedAttempts,lastFailedAt:Ui(t.lastFailedAt),lockedUntil:Ui(t.lockedUntil)}}function s8(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]={failedAttempts:n.failedAttempts??0,lastFailedAt:Xr(n.lastFailedAt),lockedUntil:Xr(n.lockedUntil)};return e}function o8(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))n&&(e[r]=sv(n));return e}var qf=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 Tn.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()}}));if(!n.Item)return w(null);let i=this.unmarshall(n.Item);return w(i)}catch(n){return console.error("[DynamoDB] identities.get error:",n),T(N.DatabaseQueryError({query:"get identity"}))}}async getByUserId(e){try{let r=await this.docClient.send(new Tn.QueryCommand({TableName:this.tableName,IndexName:tt.USER_IDENTITIES,KeyConditionExpression:`${E.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":K.USER_INDEX_PK(e)}})),n=[];for(let i of r.Items||[]){let s=this.unmarshall(i);s!==null&&n.push(s)}return w(n)}catch{return T(N.DatabaseQueryError({query:"get identities by userId"}))}}async create(e){try{let r=Ne(),n={...e,createdAt:oe(r),updatedAt:oe(r)};return await this.docClient.send(new Tn.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),w(n)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"identity"})):T(N.DatabaseQueryError({query:"create identity"}))}}async update(e,r,n){try{let i=[],s=[],o={},a={};if(n.loginEnabled!==void 0&&(i.push("#loginEnabled = :loginEnabled"),o["#loginEnabled"]=E.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let u=Ui(n.verifiedAt);u===null?(s.push("#verifiedAt"),o["#verifiedAt"]=E.VERIFIED_AT):(i.push("#verifiedAt = :verifiedAt"),o["#verifiedAt"]=E.VERIFIED_AT,a[":verifiedAt"]=u)}n.guards!==void 0&&(i.push("#guards = :guards"),o["#guards"]=E.GUARDS,a[":guards"]=o8(n.guards)),n.pendingVerification!==void 0&&(o["#pendingVerification"]=E.PENDING_VERIFICATION,n.pendingVerification===null?s.push("#pendingVerification"):(i.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Zr({...n.pendingVerification,expiresAt:Te(n.pendingVerification.expiresAt),resendAvailableAt:Ui(n.pendingVerification.resendAvailableAt)}))),i.push("#updatedAt = :updatedAt"),o["#updatedAt"]=E.UPDATED_AT,a[":updatedAt"]=Ne();let c=[];return i.length>0&&c.push(`SET ${i.join(", ")}`),s.length>0&&c.push(`REMOVE ${s.join(", ")}`),await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:o,ExpressionAttributeValues:a})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update identity"}))}}async remove(e,r){try{return await this.docClient.send(new Tn.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove identity"}))}}async updateGuard(e,r,n,i){let s={[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()};try{return await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":E.GUARDS,"#guardKey":n,"#updatedAt":E.UPDATED_AT},ExpressionAttributeValues:{":guard":sv(i),":updatedAt":Ne()}})),w(void 0)}catch(o){if(lt(o))try{return await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":E.GUARDS,"#updatedAt":E.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:sv(i)},":updatedAt":Ne()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update guard"}))}return T(N.DatabaseQueryError({query:"update guard"}))}}async batchGet(e){try{if(e.length===0)return w([]);let n=(await this.docClient.send(new Tn.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:e.map(({type:o,value:a})=>({[E.PK]:K.IDENTITY_PK(o,a),[E.SK]:K.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],i=new Map;for(let o of n){let a=this.unmarshall(o);if(a!==null){let c=`${a.type}#${a.value}`;i.set(c,a)}}let s=e.map(({type:o,value:a})=>{let c=`${o}#${a}`;return i.get(c)||null});return w(s)}catch{return T(N.DatabaseQueryError({query:"batch get identities"}))}}marshall(e){let r={[E.PK]:K.IDENTITY_PK(e.type,e.value),[E.SK]:K.IDENTITY_SK(),[E.IDENTITY_USER_PK]:K.USER_INDEX_PK(e.userId),[E.IDENTITY_USER_SK]:K.USER_INDEX_SK(e.type,e.value),[E.USER_ID]:e.userId,[E.LOGIN_ENABLED]:e.loginEnabled,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)},n=Ui(e.verifiedAt);return n!==null&&(r[E.VERIFIED_AT]=n),r[E.GUARDS]=o8(e.guards),e.pendingVerification&&(r[E.PENDING_VERIFICATION]=Zr({...e.pendingVerification,expiresAt:Te(e.pendingVerification.expiresAt),resendAvailableAt:Ui(e.pendingVerification.resendAvailableAt)})),r}unmarshall(e){let r=ve.identityPKInfo(e[E.PK]);if(!r){let n=e[E.IDENTITY_USER_SK]?ve.userIndexSKInfo(e[E.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[E.USER_ID],loginEnabled:e[E.LOGIN_ENABLED],verifiedAt:Xr(e[E.VERIFIED_AT]),guards:s8(e[E.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[E.PENDING_VERIFICATION]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[E.PK],GSI1SK:e[E.IDENTITY_USER_SK]}),null)}return{type:r.type,value:r.value,userId:e[E.USER_ID],loginEnabled:e[E.LOGIN_ENABLED],verifiedAt:Xr(e[E.VERIFIED_AT]),guards:s8(e[E.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[E.PENDING_VERIFICATION]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.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:oe(r.expiresAt),resendAvailableAt:Xr(r.resendAvailableAt)}}};var a8=ge(ir(),1);var Wf=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=Ne(),n=Lt(),i=Te(e.challenge.expiresAt),s=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new a8.TransactWriteCommand({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,s))]})),w(void 0)}catch(r){return Vf(r)==="TransactionCanceledException"||lt(r)?T(N.UniqueConstraintViolation({field:"registration"})):T(N.DatabaseQueryError({query:"create email verification registration transaction"}))}}putItem(e){return{Put:{TableName:this.tableName,Item:Zr(e),ConditionExpression:`attribute_not_exists(${E.PK})`}}}marshallProfile(e,r){let n=e.profile.status,i={[E.PK]:K.USER_PK(e.profile.id),[E.SK]:K.USER_PROFILE_SK(),userStatus:n,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.USER_STATUS_PK]:ze.USER_STATUS_PK(n),[E.USER_STATUS_SK]:ze.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{[E.PK]:K.USER_PK(e.userAuth.userId),[E.SK]:K.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[E.CREATED_AT]:r,[E.UPDATED_AT]:r}}marshallIdentity(e,r){let n=e.identity,i={[E.PK]:K.IDENTITY_PK(n.type,n.value),[E.SK]:K.IDENTITY_SK(),[E.IDENTITY_USER_PK]:K.USER_INDEX_PK(n.userId),[E.IDENTITY_USER_SK]:K.USER_INDEX_SK(n.type,n.value),[E.USER_ID]:n.userId,[E.LOGIN_ENABLED]:n.loginEnabled,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.PENDING_VERIFICATION]:Zr({...n.pendingVerification,expiresAt:Te(n.pendingVerification.expiresAt),resendAvailableAt:Ui(n.pendingVerification.resendAvailableAt)})},s=Ui(n.verifiedAt);return s!==null&&(i[E.VERIFIED_AT]=s),i[E.GUARDS]=n.guards??{},i}marshallCredential(e,r,n){let i=e.credential,s={[E.PK]:K.CREDENTIAL_PK(r),[E.SK]:K.CREDENTIAL_SK(),[E.CREDENTIAL_USER_PK]:K.USER_PK(i.userId),[E.CREDENTIAL_USER_SK]:K.CREDENTIAL_USER_SK(i.type,r),[E.USER_ID]:i.userId,[E.CREDENTIAL_VALUE]:i.value,[E.METADATA]:i.data,[E.REVOKED_AT]:i.revokedAt?Te(i.revokedAt):null,[E.CREATED_AT]:n,[E.UPDATED_AT]:n};return i.lastUsedAt&&(s[E.LAST_USED_AT]=Te(i.lastUsedAt)),s}marshallChallenge(e,r,n){let i=e.challenge,s={[E.PK]:K.CHALLENGE_PK(i.id),[E.SK]:K.CHALLENGE_SK(),[E.USER_ID]:i.userId,[E.PURPOSE]:i.purpose,[E.CHALLENGE_STATUS]:i.status,[E.EXPIRES_AT]:Te(i.expiresAt),[E.CREATED_AT]:r,[E.TTL]:n};return i.tenantId&&(s[E.TENANT_ID]=i.tenantId),i.phase&&(s[E.PHASE]=i.phase),i.allowedMethods&&i.allowedMethods.length>0&&(s[E.ALLOWED_METHODS]=i.allowedMethods),i.method&&(s[E.METHOD]=i.method),i.codeHash&&(s[E.CODE_HASH]=i.codeHash),i.attempts!==void 0&&(s[E.ATTEMPTS]=i.attempts),i.maxAttempts!==void 0&&(s[E.MAX_ATTEMPTS]=i.maxAttempts),i.identityType&&(s[E.IDENTITY_TYPE]=i.identityType),i.identityValue&&(s[E.IDENTITY_VALUE]=i.identityValue),i.deviceLabel&&(s[E.DEVICE_LABEL]=i.deviceLabel),i.country&&(s[E.COUNTRY]=i.country),i.city&&(s[E.CITY]=i.city),i.metadata&&(s[E.METADATA]=i.metadata),i.flowKey&&(s[E.FLOW_KEY]=i.flowKey),s}};var d8=ge(v_(),1),Zt=ge(ir(),1);var l8=ge(ir(),1),c8=100,u8=5;function Ege(t){return new Promise(e=>setTimeout(e,t))}async function Sl(t,e,r){if(r.length===0)return[];let n=[];for(let i=0;i<r.length;i+=c8){let s=r.slice(i,i+c8),o=0;for(;s.length>0;){let a=await t.send(new l8.BatchGetCommand({RequestItems:{[e]:{Keys:s}}})),c=a.Responses?.[e];c&&n.push(...c);let u=a.UnprocessedKeys?.[e]?.Keys;if(!u||u.length===0)break;if(o+=1,o>u8)throw new Error(`BatchGet left ${u.length} unprocessed keys after ${u8} retries`);s=u,await Ege(2**o*25)}}return n}var jf=class{docClient;tableName;ttlGracePeriod;constructor(e){let r=e.client||new d8.DynamoDBClient({});this.docClient=e.docClient||Zt.DynamoDBDocumentClient.from(r),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return Lt()}generateTokenId(){return Lt()}async get(e){try{let r=await this.docClient.send(new Zt.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()}}));return r.Item?w(this.unmarshall(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get session"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateSessionId(),i=e.tokenId||this.generateTokenId(),s={...e,id:n,tokenId:i,revokedAt:null,createdAt:new Date(r),lastUsedAt:new Date(r)},o=Kf(Te(e.expiresAt)+this.ttlGracePeriod),a=q_.sessionSK(r,n);return await this.docClient.send(new Zt.PutCommand({TableName:this.tableName,Item:this.marshall(s,o,a)})),w(s)}catch{return T(N.DatabaseQueryError({query:"create session"}))}}async update(e,r){try{let n=[],i={},s={};if(r.tokenId!==void 0&&(n.push(`#${E.TOKEN_ID} = :tokenId`),i[`#${E.TOKEN_ID}`]=E.TOKEN_ID,s[":tokenId"]=r.tokenId),r.expiresAt!==void 0){n.push(`#${E.EXPIRES_AT} = :expiresAt`),i[`#${E.EXPIRES_AT}`]=E.EXPIRES_AT,s[":expiresAt"]=Te(r.expiresAt);let o=Kf(Te(r.expiresAt)+this.ttlGracePeriod);n.push(`#${E.TTL} = :ttl`),i[`#${E.TTL}`]=E.TTL,s[":ttl"]=o}return r.lastUsedAt!==void 0&&(n.push(`#${E.LAST_USED_AT} = :lastUsedAt`),i[`#${E.LAST_USED_AT}`]=E.LAST_USED_AT,s[":lastUsedAt"]=Te(r.lastUsedAt)),r.metadata!==void 0&&(n.push(`#${E.METADATA} = :metadata`),i[`#${E.METADATA}`]=E.METADATA,s[":metadata"]=r.metadata),r.previousTokenId!==void 0&&(n.push(`#${E.PREVIOUS_TOKEN_ID} = :previousTokenId`),i[`#${E.PREVIOUS_TOKEN_ID}`]=E.PREVIOUS_TOKEN_ID,s[":previousTokenId"]=r.previousTokenId),r.rotatedAt!==void 0&&(n.push(`#${E.ROTATED_AT} = :rotatedAt`),i[`#${E.ROTATED_AT}`]=E.ROTATED_AT,s[":rotatedAt"]=r.rotatedAt),n.length===0?w():(await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),w())}catch{return T(N.DatabaseQueryError({query:"update session"}))}}async rotateToken(e,r,n){try{let i=Kf(Te(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.TOKEN_ID} = :tokenId, #${E.PREVIOUS_TOKEN_ID} = :previousTokenId, #${E.ROTATED_AT} = :rotatedAt, #${E.EXPIRES_AT} = :expiresAt, #${E.LAST_USED_AT} = :lastUsedAt, #${E.TTL} = :ttl`,ConditionExpression:`#${E.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${E.TOKEN_ID}`]:E.TOKEN_ID,[`#${E.PREVIOUS_TOKEN_ID}`]:E.PREVIOUS_TOKEN_ID,[`#${E.ROTATED_AT}`]:E.ROTATED_AT,[`#${E.EXPIRES_AT}`]:E.EXPIRES_AT,[`#${E.LAST_USED_AT}`]:E.LAST_USED_AT,[`#${E.TTL}`]:E.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":Te(n.expiresAt),":lastUsedAt":Te(n.lastUsedAt),":ttl":i,":expectedCurrentTokenId":r}})),w(!0)}catch(i){return lt(i)?w(!1):T(N.DatabaseQueryError({query:"rotate session token"}))}}async switchTenant(e,r){try{let n=[`#${E.TENANT_ID} = :tenantId`,`#${E.TOKEN_ID} = :tokenId`,`#${E.LAST_USED_AT} = :lastUsedAt`],i=[],s={[`#${E.TENANT_ID}`]:E.TENANT_ID,[`#${E.TOKEN_ID}`]:E.TOKEN_ID,[`#${E.LAST_USED_AT}`]:E.LAST_USED_AT},o={":tenantId":r.tenantId,":tokenId":r.tokenId,":lastUsedAt":Ne()};s[`#${E.TENANT_TYPE}`]=E.TENANT_TYPE,r.tenantType!==void 0?(n.push(`#${E.TENANT_TYPE} = :tenantType`),o[":tenantType"]=r.tenantType):i.push(`#${E.TENANT_TYPE}`),s[`#${E.PERM}`]=E.PERM,r.perms!==void 0?(n.push(`#${E.PERM} = :perms`),o[":perms"]=JSON.stringify(r.perms)):i.push(`#${E.PERM}`),s[`#${E.ROLES}`]=E.ROLES,r.roles!==void 0?(n.push(`#${E.ROLES} = :roles`),o[":roles"]=r.roles):i.push(`#${E.ROLES}`),s["#revokedAt"]=E.REVOKED_AT;let a=`SET ${n.join(", ")}${i.length>0?` REMOVE ${i.join(", ")}`:""}`;return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${E.PK}) AND attribute_not_exists(#revokedAt)`})),w()}catch(n){return lt(n)?T(N.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):T(N.DatabaseQueryError({query:"switch tenant"}))}}async revoke(e){try{return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":Te(new Date)},ConditionExpression:`attribute_exists(${E.PK})`})),w()}catch(r){return lt(r)?w():T(N.DatabaseQueryError({query:"revoke session"}))}}async revokeByIdAndUserId(e,r){try{return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ConditionExpression:`#${E.USER_ID} = :userId AND attribute_not_exists(#${E.REVOKED_AT})`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.USER_ID}`]:E.USER_ID,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":Te(new Date),":userId":r}})),w()}catch(n){return lt(n)?w():T(N.DatabaseQueryError({query:"revoke session by user"}))}}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 T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.USER_SESSIONS,KeyConditionExpression:`${E.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let y={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return w([],{pagination:y})}let a=s.Items.map(y=>ve.sessionId(y[E.PK])).map(y=>({[E.PK]:K.SESSION_PK(y),[E.SK]:K.SESSION_SK()})),u=(await Sl(this.docClient,this.tableName,a)).map(y=>this.unmarshall(y)),p=!!s.LastEvaluatedKey,d=p?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,h={type:"cursor",limit:n,count:u.length,hasNext:p,hasPrev:!!r?.cursor,cursor:d};return w(u,{pagination:h})}catch{return T(N.DatabaseQueryError({query:"find sessions by user"}))}}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 T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let y={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return w([],{pagination:y})}let a=s.Items.map(y=>ve.sessionId(y[E.PK])).map(y=>({[E.PK]:K.SESSION_PK(y),[E.SK]:K.SESSION_SK()})),u=(await Sl(this.docClient,this.tableName,a)).map(y=>this.unmarshall(y)),p=!!s.LastEvaluatedKey,d=p?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,h={type:"cursor",limit:n,count:u.length,hasNext:p,hasPrev:!!r?.cursor,cursor:d};return w(u,{pagination:h})}catch{return T(N.DatabaseQueryError({query:"find active sessions by user"}))}}async getActiveSessionsForLimit(e){try{let r=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!r.Items||r.Items.length===0)return w([]);let n=r.Items.map(i=>{let s=ve.sessionId(i[E.PK]),o=q_.extractCreatedAt(i[E.ACTIVE_SESSION_SK]);return{id:s,createdAt:new Date(o)}});return w(n)}catch{return T(N.DatabaseQueryError({query:"get active sessions for limit"}))}}async revokeSessionsByIds(e,r){if(e.length===0)return 0;let n=Te(new Date),i=await Promise.allSettled(e.map(o=>this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(o),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),s=0;for(let o of i)o.status==="fulfilled"?s+=1:console.error(`[session-repo] ${r}: session revoke failed (may remain active):`,{name:Vf(o.reason)});return s}async revokeAllByUserId(e,r){try{let n=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return w(0);let i=n.Items.map(o=>ve.sessionId(o[E.PK])).filter(o=>!r||o!==r),s=await this.revokeSessionsByIds(i,"revokeAllByUserId");return w(s)}catch{return T(N.DatabaseQueryError({query:"revoke all sessions by user"}))}}async revokeBatch(e){try{let r=await this.revokeSessionsByIds(e,"revokeBatch");return w(r)}catch{return T(N.DatabaseQueryError({query:"revoke batch sessions"}))}}async countByUserId(e){try{let r=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return w(r.Count||0)}catch{return T(N.DatabaseQueryError({query:"count active sessions by user"}))}}async isTokenActive(e,r){try{let n=await this.docClient.send(new Zt.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(r),[E.SK]:K.SESSION_SK()},ProjectionExpression:`${E.TOKEN_ID}, ${E.REVOKED_AT}, ${E.EXPIRES_AT}`}));if(!n.Item)return w(!1);let i=n.Item,s=i[E.TOKEN_ID]===e&&!i[E.REVOKED_AT]&&oe(i[E.EXPIRES_AT])>new Date;return w(s)}catch{return T(N.DatabaseQueryError({query:"check token active"}))}}marshall(e,r,n){let i={[E.PK]:K.SESSION_PK(e.id),[E.SK]:K.SESSION_SK(),[E.USER_SESSION_PK]:K.USER_PK(e.userId),[E.USER_SESSION_SK]:n,...!e.revokedAt&&{[E.ACTIVE_SESSION_PK]:ze.ACTIVE_SESSION_PK(e.userId),[E.ACTIVE_SESSION_SK]:n},[E.USER_ID]:e.userId,[E.TOKEN_ID]:e.tokenId,[E.EXPIRES_AT]:Te(e.expiresAt),[E.CREATED_AT]:Te(e.createdAt),[E.LAST_USED_AT]:Te(e.lastUsedAt),[E.TTL]:r};return e.tenantId&&(i[E.TENANT_ID]=e.tenantId),e.tenantType&&(i[E.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(i[E.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(i[E.ROLES]=e.roles),e.deviceLabel&&(i[E.DEVICE_LABEL]=e.deviceLabel),e.country&&(i[E.COUNTRY]=e.country),e.city&&(i[E.CITY]=e.city),e.metadata&&(i[E.METADATA]=e.metadata),e.revokedAt&&(i[E.REVOKED_AT]=Te(e.revokedAt)),e.previousTokenId&&(i[E.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(i[E.ROTATED_AT]=e.rotatedAt),i}unmarshall(e){let n={id:ve.sessionId(e[E.PK]),userId:e[E.USER_ID],tokenId:e[E.TOKEN_ID],expiresAt:oe(e[E.EXPIRES_AT]),createdAt:oe(e[E.CREATED_AT]),lastUsedAt:oe(e[E.LAST_USED_AT]),revokedAt:e[E.REVOKED_AT]?oe(e[E.REVOKED_AT]):null};return e[E.TENANT_ID]&&(n.tenantId=e[E.TENANT_ID]),e[E.TENANT_TYPE]&&(n.tenantType=e[E.TENANT_TYPE]),e[E.PERM]!==void 0&&(n.perms=JSON.parse(e[E.PERM])),e[E.ROLES]!==void 0&&(n.roles=e[E.ROLES]),e[E.DEVICE_LABEL]&&(n.deviceLabel=e[E.DEVICE_LABEL]),e[E.COUNTRY]&&(n.country=e[E.COUNTRY]),e[E.CITY]&&(n.city=e[E.CITY]),e[E.METADATA]&&(n.metadata=e[E.METADATA]),e[E.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[E.PREVIOUS_TOKEN_ID]),e[E.ROTATED_AT]!==void 0&&(n.rotatedAt=e[E.ROTATED_AT]),n}};var p8=ge(ir(),1);var zf=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":E.INVITE_TENANT_PK},s={":pk":ze.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=E.INVITE_TENANT_SK,s[":statusPrefix"]=ze.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new p8.QueryCommand(o)),c=(a.Items||[]).map(d=>this.toListItem(d)),u=!!a.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return gt(c,{limit:n,hasNext:u,cursor:p,prevCursor:r?.cursor??null})}catch(n){return console.error("[DynamoDBTenantInviteQuery.listByTenant] Error:",n instanceof Error?n.message:n),T(N.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e){let r=ve.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:oe(e.expiresAt),createdAt:oe(e.createdAt),updatedAt:oe(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=oe(e.acceptedAt)),e.declinedAt&&(i.declinedAt=oe(e.declinedAt)),e.revokedAt&&(i.revokedAt=oe(e.revokedAt)),i}};var Fr=ge(ir(),1);var gge=10080*60*1e3,Qf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:ve.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:oe(e.expiresAt),createdAt:oe(e.createdAt),updatedAt:oe(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[E.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=oe(e.acceptedAt)),e.declinedAt&&(n.declinedAt=oe(e.declinedAt)),e.revokedAt&&(n.revokedAt=oe(e.revokedAt)),n}generateInviteId(){return Lt()}async getById(e){try{let r=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:K.INVITE_PK(e),SK:K.INVITE_SK()}}));return r.Item?w(this.mapItemToEntity(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"getById invite"}))}}async getByToken(e){try{let n=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":E.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return w(null);let i=n[0],s=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:i.PK,SK:i.SK}}));return s.Item?w(this.mapItemToEntity(s.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"getByToken invite"}))}}async create(e){try{let r=Ne(),n=Te(e.expiresAt),i=Math.floor((n+gge)/1e3),s={PK:K.INVITE_PK(e.id),SK:K.INVITE_SK(),[E.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[E.INVITED_BY_ID]:e.invitedById,[E.INVITE_STATUS]:e.status,[E.INVITE_TOKEN]:e.inviteToken,[E.EXPIRES_AT]:n,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.TTL]:i,[E.INVITE_TENANT_PK]:ze.INVITE_TENANT_PK(e.tenantId),[E.INVITE_TENANT_SK]:ze.INVITE_TENANT_SK(e.status,r,e.id),[E.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&&(s[E.INVITED_BY_INFO]=o),e.inviteeUserId&&(s[E.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(s[E.INVITEE_EMAIL]=e.inviteeEmail,s[E.INVITEE_EMAIL_GSI]=e.inviteeEmail,s[E.INVITEE_EMAIL_TENANT_SK]=`${De.TENANT}${e.tenantId}`),e.inviteePhone&&(s[E.INVITEE_PHONE]=e.inviteePhone,s[E.INVITEE_PHONE_GSI]=e.inviteePhone,s[E.INVITEE_PHONE_TENANT_SK]=`${De.TENANT}${e.tenantId}`),e.roles!==void 0&&(s[E.ROLES]=e.roles),e.perms!==void 0&&(s[E.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(s[E.AUTH_PERM]=e.authPerm),e.displayName&&(s[E.DISPLAY_NAME]=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.jobTitle&&(s.jobTitle=e.jobTitle),await this.docClient.send(new Fr.PutCommand({TableName:this.tableName,Item:s,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:oe(r),updatedAt:oe(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),w(a)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"invite id"})):T(N.UnknownError({message:r.message}))}}async updateStatus(e,r){try{let n=Ne(),i=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],s={"#inviteStatus":E.INVITE_STATUS,"#inviteTenantSk":E.INVITE_TENANT_SK,"#updatedAt":E.UPDATED_AT},o={":inviteStatus":r.status,":inviteTenantSk":ze.INVITE_TENANT_SK(r.status,n,e),":updatedAt":n};r.acceptedAt&&(i.push("#acceptedAt = :acceptedAt"),s["#acceptedAt"]=E.ACCEPTED_AT,o[":acceptedAt"]=Te(r.acceptedAt)),r.declinedAt&&(i.push("#declinedAt = :declinedAt"),s["#declinedAt"]=E.DECLINED_AT,o[":declinedAt"]=Te(r.declinedAt)),r.revokedAt&&(i.push("#revokedAt = :revokedAt"),s["#revokedAt"]=E.REVOKED_AT,o[":revokedAt"]=Te(r.revokedAt));let a=[];r.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),s["#inviteTokenGsi"]=E.INVITE_TOKEN_GSI,s["#inviteeEmailGsi"]=E.INVITEE_EMAIL_GSI,s["#inviteeEmailTenantSk"]=E.INVITEE_EMAIL_TENANT_SK,s["#inviteePhoneGsi"]=E.INVITEE_PHONE_GSI,s["#inviteePhoneTenantSk"]=E.INVITEE_PHONE_TENANT_SK);let c=`SET ${i.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new Fr.UpdateCommand({TableName:this.tableName,Key:{PK:K.INVITE_PK(e),SK:K.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantInvite",id:e})):T(N.UnknownError({message:n.message}))}}async findByTenantAndEmail(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":E.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":E.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":r,":tenantSk":`${De.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndEmail"}))}}async findByTenantAndPhone(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":E.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":E.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":r,":tenantSk":`${De.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndPhone"}))}}async findByTenantAndUserId(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":E.INVITE_TENANT_PK,"#sk":E.INVITE_TENANT_SK,"#inviteeUserId":E.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":ze.INVITE_TENANT_PK(e),":pendingPrefix":ze.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":r},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndUserId"}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":E.INVITE_TENANT_PK},s={":pk":ze.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=E.INVITE_TENANT_SK,s[":statusPrefix"]=ze.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new Fr.QueryCommand(o)),c=(a.Items||[]).map(d=>this.mapItemToEntity(d)),u=!!a.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return gt(c,{limit:n,hasNext:u,cursor:p,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant"}))}}async findPendingByEmail(e){try{let r=Ne(),i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":E.INVITEE_EMAIL_GSI,"#expiresAt":E.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":r}}))).Items||[];if(i.length===0)return w([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await Sl(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return w(a)}catch{return T(N.DatabaseQueryError({query:"findPendingByEmail"}))}}async findPendingByPhone(e){try{let r=Ne(),i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":E.INVITEE_PHONE_GSI,"#expiresAt":E.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":r}}))).Items||[];if(i.length===0)return w([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await Sl(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return w(a)}catch{return T(N.DatabaseQueryError({query:"findPendingByPhone"}))}}async countPendingByTenant(e){try{let r=await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":E.INVITE_TENANT_PK,"#sk":E.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":ze.INVITE_TENANT_PK(e),":pendingPrefix":ze.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return w(r.Count??0)}catch{return T(N.DatabaseQueryError({query:"countPendingByTenant"}))}}async expireOld(e){return w(0)}};var f8=ge(ir(),1);var Jf=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":K.TENANT_MEMBER_PK(e)}};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let o=(await this.docClient.send(new f8.QueryCommand(i))).Items||[],a=[],c=new Map;for(let y of o){let _=y.SK;if(_.startsWith(_t.TENANT_PROFILE)){let C=ve.tenantProfileUserId(_);c.set(C,y)}else _.startsWith(De.USER)&&a.push(y)}a.sort((y,_)=>_.createdAt-y.createdAt);let u=a.slice(0,n),p=a.length>n,d=u.map(y=>{let _=ve.tenantMemberUserId(y.SK),C=c.get(_);return this.toListItem(y,e,_,C)}),h=p&&u.length>0?Buffer.from(JSON.stringify({PK:u[u.length-1].PK,SK:u[u.length-1].SK})).toString("base64url"):null;return gt(d,{limit:n,hasNext:p,cursor:h,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e,r,n,i){let s={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};if(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),i){let o={tenantId:r,userId:n,createdAt:oe(i.createdAt),updatedAt:oe(i.updatedAt)};i.contactEmail&&(o.contactEmail=i.contactEmail),i.contactPhone&&(o.contactPhone=i.contactPhone),i.displayName&&(o.displayName=i.displayName),i.displayNameSource&&(o.displayNameSource=i.displayNameSource),i.givenName&&(o.givenName=i.givenName),i.familyName&&(o.familyName=i.familyName),i.avatarUrl&&(o.avatarUrl=i.avatarUrl),i.locale&&(o.locale=i.locale),i.jobTitle&&(o.jobTitle=i.jobTitle),i.bio&&(o.bio=i.bio),i.metadata&&(o.metadata=JSON.parse(i.metadata)),s.tenantProfile=o}return s}};var Kr=ge(ir(),1);var Yf=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=Kr.DynamoDBDocumentClient.from(e)}mapItemToEntity(e){let r=ve.tenantId(e.PK),n=ve.tenantMemberUserId(e.SK),i={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(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 Kr.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)}}));if(!n.Item)return w(null);let i=this.mapItemToEntity(n.Item);return w(i)}catch{return T(N.DatabaseQueryError({query:"get"}))}}async create(e){try{let r=Ne(),n=e.isOwner?void 0:e.authPerm,i=Zr({PK:K.TENANT_MEMBER_PK(e.tenantId),SK:K.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:ze.USER_TENANT_PK(e.userId),userTenantSk:ze.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,r,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new Kr.TransactWriteCommand({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:K.TENANT_MEMBER_PK(e.tenantId),SK:K.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 Kr.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(void 0)}catch(r){return r.name==="TransactionCanceledException"?r.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?T(N.UniqueConstraintViolation({field:"tenant owner"})):T(N.UniqueConstraintViolation({field:"tenant member"})):r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"tenant member"})):T(N.UnknownError({message:r.message}))}}async updatePermissions(e,r,n){try{let i={...n,updatedAt:Ne()},{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new Kr.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async updateStatus(e,r,n){try{return await this.docClient.send(new Kr.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":Ne()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}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":K.TENANT_MEMBER_PK(e),":skPrefix":De.USER},Limit:n};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let s=await this.docClient.send(new Kr.QueryCommand(i)),o=(s.Items||[]).map(u=>this.mapItemToEntity(u)),a=!!s.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null;return gt(o,{limit:n,hasNext:a,cursor:c,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant"}))}}async hasOwner(e){try{let r=await this.docClient.send(new Kr.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_OWNER_MARKER_SK()}}));return w(!!r.Item)}catch{return T(N.DatabaseQueryError({query:"hasOwner"}))}}async remove(e,r){try{return await this.docClient.send(new Kr.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:n.message}))}}};var W_=ge(ir(),1);var Xf=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??nv.DEFAULT,s=r?.parentTenantId,o=s?`${i}#${s}#`:`${i}#`,a={TableName:this.tableName,IndexName:tt.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":ze.USER_TENANT_PK(e),":skPrefix":o},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 W_.QueryCommand(a)),u=c.Items??[],p=await this.fetchProfileMap(e,u),d=u.map(_=>this.toListItem(_,e,p)),h=!!c.LastEvaluatedKey,y=h?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return gt(d,{limit:n,hasNext:h,cursor:y,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByUser query"}))}}async fetchProfileMap(e,r){let n=new Map;if(r.length===0)return n;let i=r.map(o=>({PK:K.TENANT_PROFILE_PK(ve.tenantId(o.PK)),SK:K.TENANT_PROFILE_SK(e)})),s=await this.docClient.send(new W_.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:i}}}));for(let o of s.Responses?.[this.tableName]??[]){let a=o,c=ve.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,r,n){let i=ve.tenantId(e.PK),s={tenantId:i,userId:r,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};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);let o=n.get(i);return o&&(o.contactEmail&&(s.contactEmail=o.contactEmail),o.contactPhone&&(s.contactPhone=o.contactPhone),o.displayName&&(s.displayName=o.displayName),o.displayNameSource&&(s.displayNameSource=o.displayNameSource),o.givenName&&(s.givenName=o.givenName),o.familyName&&(s.familyName=o.familyName),o.avatarUrl&&(s.avatarUrl=o.avatarUrl),o.locale&&(s.locale=o.locale),o.jobTitle&&(s.jobTitle=o.jobTitle),o.bio&&(s.bio=o.bio),o.metadata&&(s.metadata=JSON.parse(o.metadata))),s}};var xa=ge(ir(),1);var Zf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return Lt()}toEntity(e){let n={id:ve.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let r=await this.docClient.send(new xa.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()}}));return r.Item?w(this.toEntity(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get tenant"}))}}async create(e){try{let r=e.id??this.generateTenantId(),n=Ne(),i=Zr({PK:K.TENANT_PK(r),SK:K.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new xa.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"tenant"})):T(N.UnknownError({message:r.message}))}}async update(e,r){try{let n={updatedAt:Ne()};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:s,ExpressionAttributeValues:o}=$i(n);return await this.docClient.send(new xa.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()},UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"Tenant",id:e})):T(N.UnknownError({message:n.message}))}}async delete(e){try{return await this.docClient.send(new xa.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"Tenant",id:e})):T(N.UnknownError({message:r.message}))}}async list(){return T(N.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return T(N.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return T(N.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};var Bi=ge(ir(),1);var em=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let r=await this.docClient.send(new Bi.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()}}));return r.Item?w(this.unmarshall(r.Item,e)):w(null)}catch{return T(N.DatabaseQueryError({query:"get user auth"}))}}async create(e){try{let r=Ne(),n={...e,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new Bi.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${E.PK})`})),w(n)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"userAuth"})):T(N.DatabaseQueryError({query:"create user auth"}))}}async updateStatus(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":userStatus":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update user auth status"}))}}async updateMfaRequired(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa required"}))}}async updateMfaMethods(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa methods"}))}}async updateMfaSettings(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r.mfaRequired,":mfaMethods":r.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa settings"}))}}async remove(e){try{return await this.docClient.send(new Bi.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user auth"}))}}marshall(e){return{[E.PK]:K.USER_PK(e.userId),[E.SK]:K.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)}}unmarshall(e,r){return{userId:r,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}}};var tn=ge(ir(),1);function _l(t,e){return e?K.USER_MFA_WITH_ID_SK(t,e):K.USER_MFA_SK(t)}var tm=class{client;tableName;docClient;constructor(e,r){this.client=e,this.tableName=r,this.docClient=tn.DynamoDBDocumentClient.from(e)}toDynamoDBItem(e){let r={PK:K.USER_PK(e.userId),SK:_l(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=ve.mfaSKInfo(e.SK),i={userId:r,method:e.method,data:JSON.parse(e.data),createdAt:oe(e.createdAt),verifiedAt:Xr(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=Xr(e.lastFailedAt)),e.lockedUntil!==void 0&&(i.lockedUntil=Xr(e.lockedUntil)),e.lastUsedAt!==void 0&&(i.lastUsedAt=Xr(e.lastUsedAt)),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r,n){try{let i=_l(r,n),s=await this.docClient.send(new tn.GetCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i}}));return s.Item?w(this.fromDynamoDBItem(s.Item,e)):w(null)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.get error:",i),T(N.DatabaseQueryError({query:"get MFA authenticator"}))}}async findByUserId(e){try{let r={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.USER_PK(e),":skPrefix":_t.MFA}},s=((await this.docClient.send(new tn.QueryCommand(r))).Items??[]).map(o=>this.fromDynamoDBItem(o,e));return w(s)}catch(r){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserId error:",r),T(N.DatabaseQueryError({query:"find MFA authenticators by user"}))}}async findByUserIdAndMethod(e,r){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.USER_PK(e),":skPrefix":`${_t.MFA}${r}`}},o=((await this.docClient.send(new tn.QueryCommand(n))).Items??[]).filter(a=>a.method===r).map(a=>this.fromDynamoDBItem(a,e));return w(o)}catch(n){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserIdAndMethod error:",n),T(N.DatabaseQueryError({query:"find MFA authenticators by method"}))}}async create(e){try{let r={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(r.id=Lt());let n=this.toDynamoDBItem(r);return await this.docClient.send(new tn.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(this.fromDynamoDBItem(n,e.userId))}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"MFA authenticator"})):(console.error("DynamoDBUserMFAAuthenticatorRepository.create error:",r),T(N.DatabaseQueryError({query:"create MFA authenticator"})))}}async update(e,r,n,i){try{let s=_l(r,n),o=[],a={},c={};if(i.label!==void 0&&(o.push("#label = :label"),a["#label"]="label",c[":label"]=i.label),i.data!==void 0&&(o.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(i.data)),i.verifiedAt!==void 0&&(o.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&&(o.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&&(o.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=i.failedAttempts),i.lastFailedAt!==void 0&&(o.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&&(o.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&&(o.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(i.metadata)),o.length===0)return w(void 0);let u={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:s},UpdateExpression:`SET ${o.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new tn.UpdateCommand(u)),w(void 0)}catch(s){return console.error("DynamoDBUserMFAAuthenticatorRepository.update error:",s),T(N.DatabaseQueryError({query:"update MFA authenticator"}))}}async remove(e,r,n){try{let i=_l(r,n);return await this.docClient.send(new tn.DeleteCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i}})),w(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.remove error:",i),T(N.DatabaseQueryError({query:"remove MFA authenticator"}))}}async incrementFailedAttempts(e,r,n,i,s){try{let o=_l(r,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],u={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},p={":zero":0,":inc":1,":lastFailedAt":a};s!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),u["#lockedUntil"]="lockedUntil",p[":lockedUntil"]=a+s*60*1e3,p[":maxAttempts"]=i);let d={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:o},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:u,ExpressionAttributeValues:p};return await this.docClient.send(new tn.UpdateCommand(d)),w(void 0)}catch(o){return console.error("DynamoDBUserMFAAuthenticatorRepository.incrementFailedAttempts error:",o),T(N.DatabaseQueryError({query:"increment failed attempts"}))}}async resetFailedAttempts(e,r,n){try{let i=_l(r,n),s={TableName:this.tableName,Key:{PK:K.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 tn.UpdateCommand(s)),w(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.resetFailedAttempts error:",i),T(N.DatabaseQueryError({query:"reset failed attempts"}))}}async unlock(e,r,n){return this.resetFailedAttempts(e,r,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};var bn=ge(ir(),1);var rm=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=bn.DynamoDBDocumentClient.from(e)}generateUserId(){return Lt()}async getById(e){try{let r=await this.docClient.send(new bn.GetCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()}}));if(!r.Item)return w(null);let n=r.Item;if(n.deletedAt)return w(null);let s={id:ve.userId(n.PK),status:n.userStatus,createdAt:oe(n.createdAt),updatedAt:oe(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:oe(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 w(s)}catch{return T(N.DatabaseQueryError({query:"getById user"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateUserId(),i=e.status||"pending",s={PK:K.USER_PK(n),SK:K.USER_PROFILE_SK(),userStatus:i,createdAt:r,updatedAt:r};e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.username&&(s.username=e.username),e.displayName&&(s.displayName=e.displayName),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.metadata&&(s.metadata=JSON.stringify(e.metadata)),s[E.USER_STATUS_PK]=ze.USER_STATUS_PK(i),s[E.USER_STATUS_SK]=ze.USER_STATUS_SK(n),await this.docClient.send(new bn.PutCommand({TableName:this.tableName,Item:Zr(s),ConditionExpression:rv("PK")}));let o={id:n,status:i,createdAt:oe(r),updatedAt:oe(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 w(o)}catch{return T(N.DatabaseQueryError({query:"create user"}))}}async updateProfile(e,r){try{let n=Ne(),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 w(void 0);i.updatedAt=n;let s=$i(i);return await this.docClient.send(new bn.UpdateCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()},UpdateExpression:s.UpdateExpression,ExpressionAttributeNames:s.ExpressionAttributeNames,ExpressionAttributeValues:s.ExpressionAttributeValues})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"updateProfile"}))}}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 T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=ze.USER_STATUS_PK(e),o=await this.docClient.send(new bn.QueryCommand({TableName:this.tableName,IndexName:tt.USERS_BY_STATUS,KeyConditionExpression:`${E.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":s},Limit:n,ExclusiveStartKey:i})),a=[];if(o.Items&&o.Items.length>0)for(let p of o.Items){let d=ve.userId(p.PK);a.push(d)}let c=!!o.LastEvaluatedKey,u=c?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return w(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!r?.cursor,cursor:u}})}catch{return T(N.DatabaseQueryError({query:"get users by status"}))}}async countByStatus(e){try{let r=ze.USER_STATUS_PK(e),n=await this.docClient.send(new bn.QueryCommand({TableName:this.tableName,IndexName:tt.USERS_BY_STATUS,KeyConditionExpression:`${E.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":r},Select:"COUNT"}));return w(n.Count||0)}catch{return T(N.DatabaseQueryError({query:"count users by status"}))}}async syncAuthStatus(e,r){try{let n=Ne(),i=`SET userStatus = :userStatus, #${E.UPDATED_AT} = :updatedAt, #${E.USER_STATUS_PK} = :statusPk, #${E.USER_STATUS_SK} = :statusSk`,s={":userStatus":r,":updatedAt":n,":statusPk":ze.USER_STATUS_PK(r),":statusSk":ze.USER_STATUS_SK(e)};return r===Hi.DELETED?(i+=", deletedAt = :deletedAt",s[":deletedAt"]=n):i+=" REMOVE deletedAt",await this.docClient.send(new bn.UpdateCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()},UpdateExpression:i,ExpressionAttributeNames:{[`#${E.UPDATED_AT}`]:E.UPDATED_AT,[`#${E.USER_STATUS_PK}`]:E.USER_STATUS_PK,[`#${E.USER_STATUS_SK}`]:E.USER_STATUS_SK},ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK)"})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userProfile",id:e})):T(N.DatabaseQueryError({query:"sync auth status"}))}}async remove(e){try{return await this.docClient.send(new bn.DeleteCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user profile"}))}}};var li=ge(ir(),1);var nm=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=li.DynamoDBDocumentClient.from(e)}mapItemToUserProviderLink(e){let r=ve.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:oe(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=Ne(),n={PK:K.PROVIDER_PK(e.provider,e.externalId),SK:K.PROVIDER_METADATA_SK(),userProviderPk:K.USER_PK(e.userId),userProviderSk:K.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?Te(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)),Zr(n)}async findByProviderAndExternalId(e,r){try{let n=await this.docClient.send(new li.GetCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()}}));return n.Item?w(this.mapItemToUserProviderLink(n.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"find provider by external id"}))}}async findByUserId(e){try{let r=await this.docClient.send(new li.QueryCommand({TableName:this.tableName,IndexName:tt.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":E.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":K.USER_PK(e)}}));return!r.Items||r.Items.length===0?w([]):w(r.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch{return T(N.DatabaseQueryError({query:"find providers by user id"}))}}async create(e){try{let r={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(r);return await this.docClient.send(new li.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),w(this.mapItemToUserProviderLink(n))}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):T(N.DatabaseQueryError({query:"create user provider"}))}}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 w(void 0);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new li.UpdateCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update user provider"}))}}async remove(e,r){try{return await this.docClient.send(new li.DeleteCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"delete user provider"}))}}};var wa=ge(ir(),1);var im=class{docClient;tableName;constructor(e,r){this.docClient=e,this.tableName=r}mapItemToEntity(e){let r=ve.tenantId(e.PK),n=ve.tenantProfileUserId(e.SK),i={tenantId:r,userId:n,createdAt:oe(e.createdAt),updatedAt:oe(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 wa.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)}}));return n.Item?w(this.mapItemToEntity(n.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let r=Ne(),n={PK:K.TENANT_PROFILE_PK(e.tenantId),SK:K.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 wa.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let i={tenantId:e.tenantId,userId:e.userId,createdAt:oe(r),updatedAt:oe(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),w(i)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"user tenant profile"})):T(N.UnknownError({message:r.message}))}}async update(e,r,n){try{let i={updatedAt:Ne()};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:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new wa.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async remove(e,r){try{return await this.docClient.send(new wa.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):T(N.UnknownError({message:n.message}))}}};var j_=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 z_.DynamoDBClient(e.clientConfig||{});let r=m8.DynamoDBDocumentClient.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new rm(this.client,this.tableName),this.sessions=new jf({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new nm(this.client,this.tableName),this.userMfaAuthenticators=new tm(this.client,this.tableName),this.challenges=new Hf({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new qf({docClient:r,tableName:this.tableName}),this.credentials=new Gf({docClient:r,tableName:this.tableName}),this.registration=new Wf({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new em({docClient:r,tableName:this.tableName}),this.tenantMembers=new Yf(this.client,this.tableName),this.tenantInvites=new Qf({docClient:r,tableName:this.tableName}),this.userTenantProfiles=new im(r,this.tableName),this.tenants=new Zf({docClient:r,tableName:this.tableName}),this.queries={tenantInvites:new zf({docClient:r,tableName:this.tableName}),tenantMembers:new Jf({docClient:r,tableName:this.tableName}),tenants:new Xf({docClient:r,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new z_.DescribeTableCommand({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};Bv();var Fv=1,H5=2,G5=3,q5="auth-craft:internal";async function tye(t){let e=t.replace(/^0x/,""),r=j5(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 s=`-----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 w(this.toEntity(r[0]))}catch(r){console.error("[DEBUG] user_tenant_profiles insert error:",r);let n=r;return n.code==="23505"?T(N.UniqueConstraintViolation({field:"tenant profile"})):n.code==="23503"?T(N.ForeignKeyViolation({field:"userId"})):T(N.DatabaseQueryError({query:"create user tenant profile"}))}}async update(e,r,n){try{let i=["updated_at = NOW()"],s=[],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&&(i.push(`${u} = $${o++}`),s.push(n[c]??null));return n.metadata!==void 0&&(i.push(`metadata = $${o++}`),s.push(n.metadata?JSON.stringify(n.metadata):null)),s.length===0?w(void 0):(s.push(e,r),await this.pool.query(`UPDATE user_tenant_profiles SET ${i.join(", ")} WHERE tenant_id = $${o++} AND user_id = $${o}`,s),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update user tenant profile"}))}}async remove(e,r){try{return await this.pool.query("DELETE FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,r]),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user tenant profile"}))}}toEntity(e){let r={tenantId:e.tenant_id,userId:e.user_id,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)};return e.contact_email&&(r.contactEmail=e.contact_email),e.contact_phone&&(r.contactPhone=e.contact_phone),e.display_name&&(r.displayName=e.display_name),e.display_name_source&&(r.displayNameSource=e.display_name_source),e.given_name&&(r.givenName=e.given_name),e.family_name&&(r.familyName=e.family_name),e.avatar_url&&(r.avatarUrl=e.avatar_url),e.locale&&(r.locale=e.locale),e.job_title&&(r.jobTitle=e.job_title),e.bio&&(r.bio=e.bio),e.metadata&&(r.metadata=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata),r}};var mb=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 Ed(e),this.userAuths=new md(e),this.sessions=new sd(e),this.identities=new id(e),this.credentials=new nd(e),this.challenges=new rd(e),this.userProviders=new gd(e),this.userMfaAuthenticators=new hd(e),this.tenants=new fd(e),this.tenantMembers=new ud(e),this.tenantInvites=new ad(e),this.userTenantProfiles=new yd(e),this.queries={tenantInvites:new od(e),tenantMembers:new cd(e),tenants:new ld(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 HO(t){let e=new mh(t);return new mb(e)}var _J={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function GO(t={}){let e={..._J,...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 s=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}@${s}$`)})();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 T([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(i.length>254)return T([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(i))return T([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(i.includes(".."))return T([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let s=i.split("@");if(s.length!==2)return T([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[o,a]=s;return!o||o.length>64?T([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?T([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):w()}}}var z_=ge(v_(),1),m8=ge(ir(),1);function Te(t){return t.getTime()}function oe(t){return new Date(t)}function n8(t){return Math.floor(t/1e3)}function Ne(){return Date.now()}function Kf(t){return t instanceof Date?n8(t.getTime()):n8(t)}function tv(t){return t<Date.now()}function Ui(t){return t?Te(t):null}function Xr(t){return t==null?null:oe(t)}function Zr(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}function $i(t){let e=[],r=[],n={},i={},s=0;for(let[c,u]of Object.entries(t)){if(c==="PK"||c==="SK")continue;let p=`#${c}`;if(n[p]=c,u==null)r.push(p);else{let d=`:val${s}`;e.push(`${p} = ${d}`),i[d]=u,s++}}let o=[];return e.length>0&&o.push(`SET ${e.join(", ")}`),r.length>0&&o.push(`REMOVE ${r.join(", ")}`),{UpdateExpression:o.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:i}}function rv(t="PK"){return`attribute_not_exists(${t})`}var wr={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},mge=wr.VIEW_ACCOUNTS|wr.UPDATE_ACCOUNT_PROFILE|wr.UPDATE_ACCOUNT_STATUS|wr.RESET_ACCOUNT_CREDENTIALS|wr.REMOVE_ACCOUNTS;var i8={[wr.INVITE_MEMBERS]:"tenant.member.invite",[wr.REMOVE_MEMBERS]:"tenant.member.remove",[wr.VIEW_MEMBERS]:"tenant.member.view",[wr.CHANGE_MEMBER_PERMISSION]:"tenant.member.permission",[wr.UPDATE_MEMBER_PROFILE]:"tenant.member.profile.update",[wr.UPDATE_MEMBER_STATUS]:"tenant.member.status.update",[wr.VIEW_ACCOUNTS]:"account.view",[wr.UPDATE_ACCOUNT_PROFILE]:"account.profile.update",[wr.UPDATE_ACCOUNT_STATUS]:"account.status.update",[wr.RESET_ACCOUNT_CREDENTIALS]:"account.credentials.reset",[wr.REMOVE_ACCOUNTS]:"account.remove"},hge=Object.fromEntries(Object.entries(i8).map(([t,e])=>[e,Number(t)]));var nv={SYSTEM:"system",DEFAULT:"org"};var iv={USER:"USR"},De={USER:`${iv.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},_t={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},Cr="#",K={USER_PK:t=>`${De.USER}${t}`,USER_AUTH_SK:()=>_t.AUTH,USER_PROFILE_SK:()=>_t.PROFILE,USER_MFA_SK:t=>`${_t.MFA}${t}`,USER_MFA_WITH_ID_SK:(t,e)=>`${_t.MFA}${t}${Cr}${e}`,TENANT_MEMBER_PK:t=>`${De.TENANT}${t}`,TENANT_MEMBER_SK:t=>`${De.USER}${t}`,TENANT_OWNER_MARKER_SK:()=>_t.OWNER,TENANT_PK:t=>`${De.TENANT}${t}`,TENANT_SK:()=>_t.METADATA,INVITE_PK:t=>`${De.INVITE}${t}`,INVITE_SK:()=>_t.METADATA,TENANT_PROFILE_PK:t=>`${De.TENANT}${t}`,TENANT_PROFILE_SK:t=>`${_t.TENANT_PROFILE}${De.USER}${t}`,SESSION_PK:t=>`${De.SESSION}${t}`,SESSION_METADATA_SK:()=>_t.METADATA,SESSION_SK:()=>_t.METADATA,PROVIDER_SK:(t,e)=>`${_t.PROVIDER}${t}${Cr}${e}`,PROVIDER_PK:(t,e)=>`${De.PROVIDER}${t}${Cr}${e}`,PROVIDER_METADATA_SK:()=>_t.METADATA,CHALLENGE_PK:t=>`${De.CHALLENGE}${t}`,CHALLENGE_SK:()=>_t.METADATA,IDENTITY_PK:(t,e)=>`${De.IDENTITY}${t}#${e}`,IDENTITY_SK:()=>_t.METADATA,CREDENTIAL_PK:t=>`${De.CREDENTIAL}${t}`,CREDENTIAL_SK:()=>_t.METADATA,CREDENTIAL_TYPE_PREFIX:t=>`${De.CREDENTIAL}${t}#`,CREDENTIAL_USER_SK:(t,e)=>`${De.CREDENTIAL}${t}#${e}`,USER_INDEX_PK:t=>`${De.USER}${t}`,USER_INDEX_SK:(t,e)=>`${De.IDENTITY}${t}#${e}`},ve={userId:t=>t.slice(De.USER.length),sessionId:t=>t.slice(De.SESSION.length),providerPKInfo:t=>{let e=t.slice(De.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(_t.PROVIDER.length),r=e.indexOf(Cr);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(_t.MFA.length),r=e.indexOf(Cr);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(De.TENANT.length),tenantMemberUserId:t=>t.slice(De.USER.length),challengeIdFromPK:t=>t.slice(De.CHALLENGE.length),inviteId:t=>t.slice(De.INVITE.length),tenantProfileUserId:t=>t.slice(_t.TENANT_PROFILE.length+De.USER.length),identityPKInfo:t=>{let e=t.slice(De.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(De.CREDENTIAL.length),credentialTypeFromUserSK:t=>{let e=t.slice(De.CREDENTIAL.length),r=e.indexOf("#");return r===-1?"":e.slice(0,r)},userIndexSKInfo:t=>{let e=t.slice(De.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 ze={ACTIVE_SESSION_PK:t=>`${De.USER}${t}`,ACTIVE_SESSION_SK:(t,e)=>`${t}${Cr}${e}`,USER_SESSION_PK:t=>`${De.USER}${t}`,USER_SESSION_SK:(t,e)=>`${t}${Cr}${e}`,USER_STATUS_PK:t=>{let e=t===Hi.ACTIVE?"ACTIVE":"INACTIVE";return`${iv.USER}${Cr}${e}`},USER_STATUS_SK:t=>t,USER_PROVIDER_PK:t=>`${De.USER}${t}`,USER_PROVIDER_SK:(t,e)=>`${_t.PROVIDER}${t}${Cr}${e}`,INVITE_TENANT_PK:t=>`${De.TENANT}${t}`,INVITE_TENANT_SK:(t,e,r)=>`${t}${Cr}${e}${Cr}${r}`,INVITE_TENANT_STATUS_PREFIX:t=>`${t}${Cr}`,USER_TENANT_PK:t=>`${De.USER}${t}`,USER_TENANT_SK:(t,e,r,n)=>`${t}${Cr}${e??"ROOT"}${Cr}${r}${Cr}${n}`},E={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"},tt={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"},q_={sessionSK:(t,e)=>`${t instanceof Date?t.getTime():t}${Cr}${e}`,extractCreatedAt:t=>{let e=t.indexOf(Cr),r=e===-1?t:t.slice(0,e);return Number(r)}};var Po=ge(ir(),1);function Vf(t){if(typeof t=="object"&&t!==null&&"name"in t){let{name:e}=t;return typeof e=="string"?e:void 0}}function lt(t){return Vf(t)==="ConditionalCheckFailedException"}var Hf=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return Lt()}async get(e){try{let r=await this.docClient.send(new Po.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()}}));if(!r.Item)return w(null);let n=this.unmarshall(r.Item);return tv(Te(n.expiresAt))?w(null):w(n)}catch{return T(N.DatabaseQueryError({query:"get challenge"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateChallengeId(),i={...e,id:n,createdAt:oe(r)},s=Te(e.expiresAt),o=Math.floor((s+this.ttlGracePeriod)/1e3);return await this.docClient.send(new Po.PutCommand({TableName:this.tableName,Item:this.marshall(i,o)})),w(i)}catch{return T(N.DatabaseQueryError({query:"create challenge"}))}}async update(e,r){try{let n=[],i={},s={};return r.method!==void 0&&(n.push("#method = :method"),i["#method"]=E.METHOD,s[":method"]=r.method),r.phase!==void 0&&(n.push("#phase = :phase"),i["#phase"]=E.PHASE,s[":phase"]=r.phase),r.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),i["#codeHash"]=E.CODE_HASH,s[":codeHash"]=r.codeHash),r.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),i["#challengeStatus"]=E.CHALLENGE_STATUS,s[":challengeStatus"]=r.status),n.length===0?w(void 0):(await this.docClient.send(new Po.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update challenge"}))}}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 o=(await this.docClient.send(new Po.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...i?{ConditionExpression:i}:{},ExpressionAttributeNames:{"#attempts":E.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[E.ATTEMPTS]??0;return w(o)}catch(s){return lt(s)?T(N.AttemptsExceeded()):T(N.DatabaseQueryError({query:"increment challenge attempts"}))}}async remove(e){try{return await this.docClient.send(new Po.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":E.PK}})),w(void 0)}catch(r){return lt(r)?w(void 0):T(N.DatabaseQueryError({query:"remove challenge"}))}}marshall(e,r){let n={[E.PK]:K.CHALLENGE_PK(e.id),[E.SK]:K.CHALLENGE_SK(),[E.USER_ID]:e.userId,[E.PURPOSE]:e.purpose,[E.CHALLENGE_STATUS]:e.status,[E.EXPIRES_AT]:Te(e.expiresAt),[E.CREATED_AT]:Te(e.createdAt),[E.TTL]:r};return e.tenantId&&(n[E.TENANT_ID]=e.tenantId),e.phase&&(n[E.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[E.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[E.METHOD]=e.method),e.codeHash&&(n[E.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[E.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[E.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[E.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[E.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[E.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[E.COUNTRY]=e.country),e.city&&(n[E.CITY]=e.city),e.metadata&&(n[E.METADATA]=e.metadata),e.flowKey&&(n[E.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:ve.challengeIdFromPK(e[E.PK]),userId:e[E.USER_ID],purpose:e[E.PURPOSE],status:e[E.CHALLENGE_STATUS],expiresAt:oe(e[E.EXPIRES_AT]),createdAt:oe(e[E.CREATED_AT])};return e[E.TENANT_ID]&&(n.tenantId=e[E.TENANT_ID]),e[E.PHASE]&&(n.phase=e[E.PHASE]),e[E.ALLOWED_METHODS]&&(n.allowedMethods=e[E.ALLOWED_METHODS]),e[E.METHOD]&&(n.method=e[E.METHOD]),e[E.CODE_HASH]&&(n.codeHash=e[E.CODE_HASH]),e[E.ATTEMPTS]!==void 0&&(n.attempts=e[E.ATTEMPTS]),e[E.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[E.MAX_ATTEMPTS]),e[E.IDENTITY_TYPE]&&(n.identityType=e[E.IDENTITY_TYPE]),e[E.IDENTITY_VALUE]&&(n.identityValue=e[E.IDENTITY_VALUE]),e[E.DEVICE_LABEL]&&(n.deviceLabel=e[E.DEVICE_LABEL]),e[E.COUNTRY]&&(n.country=e[E.COUNTRY]),e[E.CITY]&&(n.city=e[E.CITY]),e[E.METADATA]&&(n.metadata=e[E.METADATA]),e[E.FLOW_KEY]&&(n.flowKey=e[E.FLOW_KEY]),n}};var en=ge(ir(),1);var Gf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return Lt()}async get(e){try{let r=await this.docClient.send(new en.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()}}));return r.Item?w(this.unmarshall(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get credential"}))}}async getByUserIdAndType(e,r){try{let n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk AND begins_with(${E.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":K.USER_PK(e),":typePrefix":K.CREDENTIAL_TYPE_PREFIX(r)},Limit:1}));if(!n.Items||n.Items.length===0)return w(null);let i=n.Items[0];if(!i)return w(null);let s=ve.credentialId(i[E.PK]);return this.get(s)}catch{return T(N.DatabaseQueryError({query:"get credential by user and type"}))}}async getByUserId(e){try{let r=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)}}));if(!r.Items||r.Items.length===0)return w([]);let n=r.Items.map(o=>ve.credentialId(o[E.PK])),i=await this.batchGet(n);if(i.ok===!1)return T(i.errors,i.meta);if(!i.data)return w([]);let s=i.data.filter(o=>o!==null);return w(s)}catch{return T(N.DatabaseQueryError({query:"get credentials by user"}))}}async create(e){try{let r=Ne(),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 en.PutCommand({TableName:this.tableName,Item:this.marshall(i),ConditionExpression:`attribute_not_exists(${E.PK})`})),w(i)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"credential"})):T(N.DatabaseQueryError({query:"create credential"}))}}async update(e,r){try{let n=Ne(),i=[],s={},o={};return i.push(`#${E.UPDATED_AT} = :updatedAt`),s[`#${E.UPDATED_AT}`]=E.UPDATED_AT,o[":updatedAt"]=n,r.value!==void 0&&(i.push(`#${E.CREDENTIAL_VALUE} = :value`),s[`#${E.CREDENTIAL_VALUE}`]=E.CREDENTIAL_VALUE,o[":value"]=r.value),r.data!==void 0&&(i.push(`#${E.METADATA} = :data`),s[`#${E.METADATA}`]=E.METADATA,o[":data"]=r.data),r.revokedAt!==void 0&&(i.push(`#${E.REVOKED_AT} = :revokedAt`),s[`#${E.REVOKED_AT}`]=E.REVOKED_AT,o[":revokedAt"]=r.revokedAt?Te(r.revokedAt):null),r.lastUsedAt!==void 0&&(i.push(`#${E.LAST_USED_AT} = :lastUsedAt`),s[`#${E.LAST_USED_AT}`]=E.LAST_USED_AT,o[":lastUsedAt"]=r.lastUsedAt?Te(r.lastUsedAt):null),await this.docClient.send(new en.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()},UpdateExpression:`SET ${i.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"credential",id:e})):T(N.DatabaseQueryError({query:"update credential"}))}}async remove(e){try{return await this.docClient.send(new en.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(r){return lt(r)?T(N.NotFound({entity:"credential",id:e})):T(N.DatabaseQueryError({query:"delete credential"}))}}async hasType(e,r){try{let n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk AND begins_with(${E.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":K.USER_PK(e),":typePrefix":K.CREDENTIAL_TYPE_PREFIX(r)},Select:"COUNT",Limit:1}));return w((n.Count||0)>0)}catch{return T(N.DatabaseQueryError({query:"check credential type"}))}}async countByUserId(e){try{let r=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)},Select:"COUNT"}));return w(r.Count||0)}catch{return T(N.DatabaseQueryError({query:"count credentials"}))}}async batchGet(e){if(e.length===0)return w([]);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 o=(await this.docClient.send(new en.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:i.map(c=>({[E.PK]:K.CREDENTIAL_PK(c),[E.SK]:K.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 i)n.push(a.get(c)||null)}return w(n)}catch{return T(N.DatabaseQueryError({query:"batch get credentials"}))}}marshall(e){let r={[E.PK]:K.CREDENTIAL_PK(e.id),[E.SK]:K.CREDENTIAL_SK(),[E.CREDENTIAL_USER_PK]:K.USER_PK(e.userId),[E.CREDENTIAL_USER_SK]:K.CREDENTIAL_USER_SK(e.type,e.id),[E.USER_ID]:e.userId,[E.CREDENTIAL_VALUE]:e.value,[E.METADATA]:e.data,[E.REVOKED_AT]:e.revokedAt?Te(e.revokedAt):null,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)};return e.lastUsedAt&&(r[E.LAST_USED_AT]=Te(e.lastUsedAt)),r}unmarshall(e){let r=ve.credentialId(e[E.PK]),n=ve.credentialTypeFromUserSK(e[E.CREDENTIAL_USER_SK]);return{id:r,userId:e[E.USER_ID],type:n,value:e[E.CREDENTIAL_VALUE],data:e[E.METADATA]||{},revokedAt:Xr(e[E.REVOKED_AT]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT]),lastUsedAt:Xr(e[E.LAST_USED_AT])}}};var Tn=ge(ir(),1);function sv(t){return{failedAttempts:t.failedAttempts,lastFailedAt:Ui(t.lastFailedAt),lockedUntil:Ui(t.lockedUntil)}}function s8(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]={failedAttempts:n.failedAttempts??0,lastFailedAt:Xr(n.lastFailedAt),lockedUntil:Xr(n.lockedUntil)};return e}function o8(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))n&&(e[r]=sv(n));return e}var qf=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 Tn.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()}}));if(!n.Item)return w(null);let i=this.unmarshall(n.Item);return w(i)}catch(n){return console.error("[DynamoDB] identities.get error:",n),T(N.DatabaseQueryError({query:"get identity"}))}}async getByUserId(e){try{let r=await this.docClient.send(new Tn.QueryCommand({TableName:this.tableName,IndexName:tt.USER_IDENTITIES,KeyConditionExpression:`${E.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":K.USER_INDEX_PK(e)}})),n=[];for(let i of r.Items||[]){let s=this.unmarshall(i);s!==null&&n.push(s)}return w(n)}catch{return T(N.DatabaseQueryError({query:"get identities by userId"}))}}async create(e){try{let r=Ne(),n={...e,createdAt:oe(r),updatedAt:oe(r)};return await this.docClient.send(new Tn.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),w(n)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"identity"})):T(N.DatabaseQueryError({query:"create identity"}))}}async update(e,r,n){try{let i=[],s=[],o={},a={};if(n.loginEnabled!==void 0&&(i.push("#loginEnabled = :loginEnabled"),o["#loginEnabled"]=E.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let u=Ui(n.verifiedAt);u===null?(s.push("#verifiedAt"),o["#verifiedAt"]=E.VERIFIED_AT):(i.push("#verifiedAt = :verifiedAt"),o["#verifiedAt"]=E.VERIFIED_AT,a[":verifiedAt"]=u)}n.guards!==void 0&&(i.push("#guards = :guards"),o["#guards"]=E.GUARDS,a[":guards"]=o8(n.guards)),n.pendingVerification!==void 0&&(o["#pendingVerification"]=E.PENDING_VERIFICATION,n.pendingVerification===null?s.push("#pendingVerification"):(i.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Zr({...n.pendingVerification,expiresAt:Te(n.pendingVerification.expiresAt),resendAvailableAt:Ui(n.pendingVerification.resendAvailableAt)}))),i.push("#updatedAt = :updatedAt"),o["#updatedAt"]=E.UPDATED_AT,a[":updatedAt"]=Ne();let c=[];return i.length>0&&c.push(`SET ${i.join(", ")}`),s.length>0&&c.push(`REMOVE ${s.join(", ")}`),await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:o,ExpressionAttributeValues:a})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update identity"}))}}async remove(e,r){try{return await this.docClient.send(new Tn.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove identity"}))}}async updateGuard(e,r,n,i){let s={[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()};try{return await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":E.GUARDS,"#guardKey":n,"#updatedAt":E.UPDATED_AT},ExpressionAttributeValues:{":guard":sv(i),":updatedAt":Ne()}})),w(void 0)}catch(o){if(lt(o))try{return await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":E.GUARDS,"#updatedAt":E.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:sv(i)},":updatedAt":Ne()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update guard"}))}return T(N.DatabaseQueryError({query:"update guard"}))}}async batchGet(e){try{if(e.length===0)return w([]);let n=(await this.docClient.send(new Tn.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:e.map(({type:o,value:a})=>({[E.PK]:K.IDENTITY_PK(o,a),[E.SK]:K.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],i=new Map;for(let o of n){let a=this.unmarshall(o);if(a!==null){let c=`${a.type}#${a.value}`;i.set(c,a)}}let s=e.map(({type:o,value:a})=>{let c=`${o}#${a}`;return i.get(c)||null});return w(s)}catch{return T(N.DatabaseQueryError({query:"batch get identities"}))}}marshall(e){let r={[E.PK]:K.IDENTITY_PK(e.type,e.value),[E.SK]:K.IDENTITY_SK(),[E.IDENTITY_USER_PK]:K.USER_INDEX_PK(e.userId),[E.IDENTITY_USER_SK]:K.USER_INDEX_SK(e.type,e.value),[E.USER_ID]:e.userId,[E.LOGIN_ENABLED]:e.loginEnabled,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)},n=Ui(e.verifiedAt);return n!==null&&(r[E.VERIFIED_AT]=n),r[E.GUARDS]=o8(e.guards),e.pendingVerification&&(r[E.PENDING_VERIFICATION]=Zr({...e.pendingVerification,expiresAt:Te(e.pendingVerification.expiresAt),resendAvailableAt:Ui(e.pendingVerification.resendAvailableAt)})),r}unmarshall(e){let r=ve.identityPKInfo(e[E.PK]);if(!r){let n=e[E.IDENTITY_USER_SK]?ve.userIndexSKInfo(e[E.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[E.USER_ID],loginEnabled:e[E.LOGIN_ENABLED],verifiedAt:Xr(e[E.VERIFIED_AT]),guards:s8(e[E.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[E.PENDING_VERIFICATION]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[E.PK],GSI1SK:e[E.IDENTITY_USER_SK]}),null)}return{type:r.type,value:r.value,userId:e[E.USER_ID],loginEnabled:e[E.LOGIN_ENABLED],verifiedAt:Xr(e[E.VERIFIED_AT]),guards:s8(e[E.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[E.PENDING_VERIFICATION]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.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:oe(r.expiresAt),resendAvailableAt:Xr(r.resendAvailableAt)}}};var a8=ge(ir(),1);var Wf=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=Ne(),n=Lt(),i=Te(e.challenge.expiresAt),s=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new a8.TransactWriteCommand({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,s))]})),w(void 0)}catch(r){return Vf(r)==="TransactionCanceledException"||lt(r)?T(N.UniqueConstraintViolation({field:"registration"})):T(N.DatabaseQueryError({query:"create email verification registration transaction"}))}}putItem(e){return{Put:{TableName:this.tableName,Item:Zr(e),ConditionExpression:`attribute_not_exists(${E.PK})`}}}marshallProfile(e,r){let n=e.profile.status,i={[E.PK]:K.USER_PK(e.profile.id),[E.SK]:K.USER_PROFILE_SK(),userStatus:n,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.USER_STATUS_PK]:ze.USER_STATUS_PK(n),[E.USER_STATUS_SK]:ze.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{[E.PK]:K.USER_PK(e.userAuth.userId),[E.SK]:K.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[E.CREATED_AT]:r,[E.UPDATED_AT]:r}}marshallIdentity(e,r){let n=e.identity,i={[E.PK]:K.IDENTITY_PK(n.type,n.value),[E.SK]:K.IDENTITY_SK(),[E.IDENTITY_USER_PK]:K.USER_INDEX_PK(n.userId),[E.IDENTITY_USER_SK]:K.USER_INDEX_SK(n.type,n.value),[E.USER_ID]:n.userId,[E.LOGIN_ENABLED]:n.loginEnabled,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.PENDING_VERIFICATION]:Zr({...n.pendingVerification,expiresAt:Te(n.pendingVerification.expiresAt),resendAvailableAt:Ui(n.pendingVerification.resendAvailableAt)})},s=Ui(n.verifiedAt);return s!==null&&(i[E.VERIFIED_AT]=s),i[E.GUARDS]=n.guards??{},i}marshallCredential(e,r,n){let i=e.credential,s={[E.PK]:K.CREDENTIAL_PK(r),[E.SK]:K.CREDENTIAL_SK(),[E.CREDENTIAL_USER_PK]:K.USER_PK(i.userId),[E.CREDENTIAL_USER_SK]:K.CREDENTIAL_USER_SK(i.type,r),[E.USER_ID]:i.userId,[E.CREDENTIAL_VALUE]:i.value,[E.METADATA]:i.data,[E.REVOKED_AT]:i.revokedAt?Te(i.revokedAt):null,[E.CREATED_AT]:n,[E.UPDATED_AT]:n};return i.lastUsedAt&&(s[E.LAST_USED_AT]=Te(i.lastUsedAt)),s}marshallChallenge(e,r,n){let i=e.challenge,s={[E.PK]:K.CHALLENGE_PK(i.id),[E.SK]:K.CHALLENGE_SK(),[E.USER_ID]:i.userId,[E.PURPOSE]:i.purpose,[E.CHALLENGE_STATUS]:i.status,[E.EXPIRES_AT]:Te(i.expiresAt),[E.CREATED_AT]:r,[E.TTL]:n};return i.tenantId&&(s[E.TENANT_ID]=i.tenantId),i.phase&&(s[E.PHASE]=i.phase),i.allowedMethods&&i.allowedMethods.length>0&&(s[E.ALLOWED_METHODS]=i.allowedMethods),i.method&&(s[E.METHOD]=i.method),i.codeHash&&(s[E.CODE_HASH]=i.codeHash),i.attempts!==void 0&&(s[E.ATTEMPTS]=i.attempts),i.maxAttempts!==void 0&&(s[E.MAX_ATTEMPTS]=i.maxAttempts),i.identityType&&(s[E.IDENTITY_TYPE]=i.identityType),i.identityValue&&(s[E.IDENTITY_VALUE]=i.identityValue),i.deviceLabel&&(s[E.DEVICE_LABEL]=i.deviceLabel),i.country&&(s[E.COUNTRY]=i.country),i.city&&(s[E.CITY]=i.city),i.metadata&&(s[E.METADATA]=i.metadata),i.flowKey&&(s[E.FLOW_KEY]=i.flowKey),s}};var d8=ge(v_(),1),Zt=ge(ir(),1);var l8=ge(ir(),1),c8=100,u8=5;function Ege(t){return new Promise(e=>setTimeout(e,t))}async function Sl(t,e,r){if(r.length===0)return[];let n=[];for(let i=0;i<r.length;i+=c8){let s=r.slice(i,i+c8),o=0;for(;s.length>0;){let a=await t.send(new l8.BatchGetCommand({RequestItems:{[e]:{Keys:s}}})),c=a.Responses?.[e];c&&n.push(...c);let u=a.UnprocessedKeys?.[e]?.Keys;if(!u||u.length===0)break;if(o+=1,o>u8)throw new Error(`BatchGet left ${u.length} unprocessed keys after ${u8} retries`);s=u,await Ege(2**o*25)}}return n}var jf=class{docClient;tableName;ttlGracePeriod;constructor(e){let r=e.client||new d8.DynamoDBClient({});this.docClient=e.docClient||Zt.DynamoDBDocumentClient.from(r),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return Lt()}generateTokenId(){return Lt()}async get(e){try{let r=await this.docClient.send(new Zt.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()}}));return r.Item?w(this.unmarshall(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get session"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateSessionId(),i=e.tokenId||this.generateTokenId(),s={...e,id:n,tokenId:i,revokedAt:null,createdAt:new Date(r),lastUsedAt:new Date(r)},o=Kf(Te(e.expiresAt)+this.ttlGracePeriod),a=q_.sessionSK(r,n);return await this.docClient.send(new Zt.PutCommand({TableName:this.tableName,Item:this.marshall(s,o,a)})),w(s)}catch{return T(N.DatabaseQueryError({query:"create session"}))}}async update(e,r){try{let n=[],i={},s={};if(r.tokenId!==void 0&&(n.push(`#${E.TOKEN_ID} = :tokenId`),i[`#${E.TOKEN_ID}`]=E.TOKEN_ID,s[":tokenId"]=r.tokenId),r.expiresAt!==void 0){n.push(`#${E.EXPIRES_AT} = :expiresAt`),i[`#${E.EXPIRES_AT}`]=E.EXPIRES_AT,s[":expiresAt"]=Te(r.expiresAt);let o=Kf(Te(r.expiresAt)+this.ttlGracePeriod);n.push(`#${E.TTL} = :ttl`),i[`#${E.TTL}`]=E.TTL,s[":ttl"]=o}return r.lastUsedAt!==void 0&&(n.push(`#${E.LAST_USED_AT} = :lastUsedAt`),i[`#${E.LAST_USED_AT}`]=E.LAST_USED_AT,s[":lastUsedAt"]=Te(r.lastUsedAt)),r.metadata!==void 0&&(n.push(`#${E.METADATA} = :metadata`),i[`#${E.METADATA}`]=E.METADATA,s[":metadata"]=r.metadata),r.previousTokenId!==void 0&&(n.push(`#${E.PREVIOUS_TOKEN_ID} = :previousTokenId`),i[`#${E.PREVIOUS_TOKEN_ID}`]=E.PREVIOUS_TOKEN_ID,s[":previousTokenId"]=r.previousTokenId),r.rotatedAt!==void 0&&(n.push(`#${E.ROTATED_AT} = :rotatedAt`),i[`#${E.ROTATED_AT}`]=E.ROTATED_AT,s[":rotatedAt"]=r.rotatedAt),n.length===0?w():(await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),w())}catch{return T(N.DatabaseQueryError({query:"update session"}))}}async rotateToken(e,r,n){try{let i=Kf(Te(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.TOKEN_ID} = :tokenId, #${E.PREVIOUS_TOKEN_ID} = :previousTokenId, #${E.ROTATED_AT} = :rotatedAt, #${E.EXPIRES_AT} = :expiresAt, #${E.LAST_USED_AT} = :lastUsedAt, #${E.TTL} = :ttl`,ConditionExpression:`#${E.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${E.TOKEN_ID}`]:E.TOKEN_ID,[`#${E.PREVIOUS_TOKEN_ID}`]:E.PREVIOUS_TOKEN_ID,[`#${E.ROTATED_AT}`]:E.ROTATED_AT,[`#${E.EXPIRES_AT}`]:E.EXPIRES_AT,[`#${E.LAST_USED_AT}`]:E.LAST_USED_AT,[`#${E.TTL}`]:E.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":Te(n.expiresAt),":lastUsedAt":Te(n.lastUsedAt),":ttl":i,":expectedCurrentTokenId":r}})),w(!0)}catch(i){return lt(i)?w(!1):T(N.DatabaseQueryError({query:"rotate session token"}))}}async switchTenant(e,r){try{let n=[`#${E.TENANT_ID} = :tenantId`,`#${E.TOKEN_ID} = :tokenId`,`#${E.LAST_USED_AT} = :lastUsedAt`],i=[],s={[`#${E.TENANT_ID}`]:E.TENANT_ID,[`#${E.TOKEN_ID}`]:E.TOKEN_ID,[`#${E.LAST_USED_AT}`]:E.LAST_USED_AT},o={":tenantId":r.tenantId,":tokenId":r.tokenId,":lastUsedAt":Ne()};s[`#${E.TENANT_TYPE}`]=E.TENANT_TYPE,r.tenantType!==void 0?(n.push(`#${E.TENANT_TYPE} = :tenantType`),o[":tenantType"]=r.tenantType):i.push(`#${E.TENANT_TYPE}`),s[`#${E.PERM}`]=E.PERM,r.perms!==void 0?(n.push(`#${E.PERM} = :perms`),o[":perms"]=JSON.stringify(r.perms)):i.push(`#${E.PERM}`),s[`#${E.ROLES}`]=E.ROLES,r.roles!==void 0?(n.push(`#${E.ROLES} = :roles`),o[":roles"]=r.roles):i.push(`#${E.ROLES}`),s["#revokedAt"]=E.REVOKED_AT;let a=`SET ${n.join(", ")}${i.length>0?` REMOVE ${i.join(", ")}`:""}`;return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${E.PK}) AND attribute_not_exists(#revokedAt)`})),w()}catch(n){return lt(n)?T(N.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):T(N.DatabaseQueryError({query:"switch tenant"}))}}async revoke(e){try{return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":Te(new Date)},ConditionExpression:`attribute_exists(${E.PK})`})),w()}catch(r){return lt(r)?w():T(N.DatabaseQueryError({query:"revoke session"}))}}async revokeByIdAndUserId(e,r){try{return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ConditionExpression:`#${E.USER_ID} = :userId AND attribute_not_exists(#${E.REVOKED_AT})`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.USER_ID}`]:E.USER_ID,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":Te(new Date),":userId":r}})),w()}catch(n){return lt(n)?w():T(N.DatabaseQueryError({query:"revoke session by user"}))}}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 T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.USER_SESSIONS,KeyConditionExpression:`${E.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let y={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return w([],{pagination:y})}let a=s.Items.map(y=>ve.sessionId(y[E.PK])).map(y=>({[E.PK]:K.SESSION_PK(y),[E.SK]:K.SESSION_SK()})),u=(await Sl(this.docClient,this.tableName,a)).map(y=>this.unmarshall(y)),p=!!s.LastEvaluatedKey,d=p?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,h={type:"cursor",limit:n,count:u.length,hasNext:p,hasPrev:!!r?.cursor,cursor:d};return w(u,{pagination:h})}catch{return T(N.DatabaseQueryError({query:"find sessions by user"}))}}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 T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let y={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return w([],{pagination:y})}let a=s.Items.map(y=>ve.sessionId(y[E.PK])).map(y=>({[E.PK]:K.SESSION_PK(y),[E.SK]:K.SESSION_SK()})),u=(await Sl(this.docClient,this.tableName,a)).map(y=>this.unmarshall(y)),p=!!s.LastEvaluatedKey,d=p?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,h={type:"cursor",limit:n,count:u.length,hasNext:p,hasPrev:!!r?.cursor,cursor:d};return w(u,{pagination:h})}catch{return T(N.DatabaseQueryError({query:"find active sessions by user"}))}}async getActiveSessionsForLimit(e){try{let r=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!r.Items||r.Items.length===0)return w([]);let n=r.Items.map(i=>{let s=ve.sessionId(i[E.PK]),o=q_.extractCreatedAt(i[E.ACTIVE_SESSION_SK]);return{id:s,createdAt:new Date(o)}});return w(n)}catch{return T(N.DatabaseQueryError({query:"get active sessions for limit"}))}}async revokeSessionsByIds(e,r){if(e.length===0)return 0;let n=Te(new Date),i=await Promise.allSettled(e.map(o=>this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(o),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),s=0;for(let o of i)o.status==="fulfilled"?s+=1:console.error(`[session-repo] ${r}: session revoke failed (may remain active):`,{name:Vf(o.reason)});return s}async revokeAllByUserId(e,r){try{let n=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return w(0);let i=n.Items.map(o=>ve.sessionId(o[E.PK])).filter(o=>!r||o!==r),s=await this.revokeSessionsByIds(i,"revokeAllByUserId");return w(s)}catch{return T(N.DatabaseQueryError({query:"revoke all sessions by user"}))}}async revokeBatch(e){try{let r=await this.revokeSessionsByIds(e,"revokeBatch");return w(r)}catch{return T(N.DatabaseQueryError({query:"revoke batch sessions"}))}}async countByUserId(e){try{let r=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return w(r.Count||0)}catch{return T(N.DatabaseQueryError({query:"count active sessions by user"}))}}async isTokenActive(e,r){try{let n=await this.docClient.send(new Zt.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(r),[E.SK]:K.SESSION_SK()},ProjectionExpression:`${E.TOKEN_ID}, ${E.REVOKED_AT}, ${E.EXPIRES_AT}`}));if(!n.Item)return w(!1);let i=n.Item,s=i[E.TOKEN_ID]===e&&!i[E.REVOKED_AT]&&oe(i[E.EXPIRES_AT])>new Date;return w(s)}catch{return T(N.DatabaseQueryError({query:"check token active"}))}}marshall(e,r,n){let i={[E.PK]:K.SESSION_PK(e.id),[E.SK]:K.SESSION_SK(),[E.USER_SESSION_PK]:K.USER_PK(e.userId),[E.USER_SESSION_SK]:n,...!e.revokedAt&&{[E.ACTIVE_SESSION_PK]:ze.ACTIVE_SESSION_PK(e.userId),[E.ACTIVE_SESSION_SK]:n},[E.USER_ID]:e.userId,[E.TOKEN_ID]:e.tokenId,[E.EXPIRES_AT]:Te(e.expiresAt),[E.CREATED_AT]:Te(e.createdAt),[E.LAST_USED_AT]:Te(e.lastUsedAt),[E.TTL]:r};return e.tenantId&&(i[E.TENANT_ID]=e.tenantId),e.tenantType&&(i[E.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(i[E.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(i[E.ROLES]=e.roles),e.deviceLabel&&(i[E.DEVICE_LABEL]=e.deviceLabel),e.country&&(i[E.COUNTRY]=e.country),e.city&&(i[E.CITY]=e.city),e.metadata&&(i[E.METADATA]=e.metadata),e.revokedAt&&(i[E.REVOKED_AT]=Te(e.revokedAt)),e.previousTokenId&&(i[E.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(i[E.ROTATED_AT]=e.rotatedAt),i}unmarshall(e){let n={id:ve.sessionId(e[E.PK]),userId:e[E.USER_ID],tokenId:e[E.TOKEN_ID],expiresAt:oe(e[E.EXPIRES_AT]),createdAt:oe(e[E.CREATED_AT]),lastUsedAt:oe(e[E.LAST_USED_AT]),revokedAt:e[E.REVOKED_AT]?oe(e[E.REVOKED_AT]):null};return e[E.TENANT_ID]&&(n.tenantId=e[E.TENANT_ID]),e[E.TENANT_TYPE]&&(n.tenantType=e[E.TENANT_TYPE]),e[E.PERM]!==void 0&&(n.perms=JSON.parse(e[E.PERM])),e[E.ROLES]!==void 0&&(n.roles=e[E.ROLES]),e[E.DEVICE_LABEL]&&(n.deviceLabel=e[E.DEVICE_LABEL]),e[E.COUNTRY]&&(n.country=e[E.COUNTRY]),e[E.CITY]&&(n.city=e[E.CITY]),e[E.METADATA]&&(n.metadata=e[E.METADATA]),e[E.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[E.PREVIOUS_TOKEN_ID]),e[E.ROTATED_AT]!==void 0&&(n.rotatedAt=e[E.ROTATED_AT]),n}};var p8=ge(ir(),1);var zf=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":E.INVITE_TENANT_PK},s={":pk":ze.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=E.INVITE_TENANT_SK,s[":statusPrefix"]=ze.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new p8.QueryCommand(o)),c=(a.Items||[]).map(d=>this.toListItem(d)),u=!!a.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return gt(c,{limit:n,hasNext:u,cursor:p,prevCursor:r?.cursor??null})}catch(n){return console.error("[DynamoDBTenantInviteQuery.listByTenant] Error:",n instanceof Error?n.message:n),T(N.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e){let r=ve.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:oe(e.expiresAt),createdAt:oe(e.createdAt),updatedAt:oe(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=oe(e.acceptedAt)),e.declinedAt&&(i.declinedAt=oe(e.declinedAt)),e.revokedAt&&(i.revokedAt=oe(e.revokedAt)),i}};var Fr=ge(ir(),1);var gge=10080*60*1e3,Qf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:ve.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:oe(e.expiresAt),createdAt:oe(e.createdAt),updatedAt:oe(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[E.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=oe(e.acceptedAt)),e.declinedAt&&(n.declinedAt=oe(e.declinedAt)),e.revokedAt&&(n.revokedAt=oe(e.revokedAt)),n}generateInviteId(){return Lt()}async getById(e){try{let r=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:K.INVITE_PK(e),SK:K.INVITE_SK()}}));return r.Item?w(this.mapItemToEntity(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"getById invite"}))}}async getByToken(e){try{let n=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":E.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return w(null);let i=n[0],s=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:i.PK,SK:i.SK}}));return s.Item?w(this.mapItemToEntity(s.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"getByToken invite"}))}}async create(e){try{let r=Ne(),n=Te(e.expiresAt),i=Math.floor((n+gge)/1e3),s={PK:K.INVITE_PK(e.id),SK:K.INVITE_SK(),[E.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[E.INVITED_BY_ID]:e.invitedById,[E.INVITE_STATUS]:e.status,[E.INVITE_TOKEN]:e.inviteToken,[E.EXPIRES_AT]:n,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.TTL]:i,[E.INVITE_TENANT_PK]:ze.INVITE_TENANT_PK(e.tenantId),[E.INVITE_TENANT_SK]:ze.INVITE_TENANT_SK(e.status,r,e.id),[E.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&&(s[E.INVITED_BY_INFO]=o),e.inviteeUserId&&(s[E.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(s[E.INVITEE_EMAIL]=e.inviteeEmail,s[E.INVITEE_EMAIL_GSI]=e.inviteeEmail,s[E.INVITEE_EMAIL_TENANT_SK]=`${De.TENANT}${e.tenantId}`),e.inviteePhone&&(s[E.INVITEE_PHONE]=e.inviteePhone,s[E.INVITEE_PHONE_GSI]=e.inviteePhone,s[E.INVITEE_PHONE_TENANT_SK]=`${De.TENANT}${e.tenantId}`),e.roles!==void 0&&(s[E.ROLES]=e.roles),e.perms!==void 0&&(s[E.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(s[E.AUTH_PERM]=e.authPerm),e.displayName&&(s[E.DISPLAY_NAME]=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.jobTitle&&(s.jobTitle=e.jobTitle),await this.docClient.send(new Fr.PutCommand({TableName:this.tableName,Item:s,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:oe(r),updatedAt:oe(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),w(a)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"invite id"})):T(N.UnknownError({message:r.message}))}}async updateStatus(e,r){try{let n=Ne(),i=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],s={"#inviteStatus":E.INVITE_STATUS,"#inviteTenantSk":E.INVITE_TENANT_SK,"#updatedAt":E.UPDATED_AT},o={":inviteStatus":r.status,":inviteTenantSk":ze.INVITE_TENANT_SK(r.status,n,e),":updatedAt":n};r.acceptedAt&&(i.push("#acceptedAt = :acceptedAt"),s["#acceptedAt"]=E.ACCEPTED_AT,o[":acceptedAt"]=Te(r.acceptedAt)),r.declinedAt&&(i.push("#declinedAt = :declinedAt"),s["#declinedAt"]=E.DECLINED_AT,o[":declinedAt"]=Te(r.declinedAt)),r.revokedAt&&(i.push("#revokedAt = :revokedAt"),s["#revokedAt"]=E.REVOKED_AT,o[":revokedAt"]=Te(r.revokedAt));let a=[];r.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),s["#inviteTokenGsi"]=E.INVITE_TOKEN_GSI,s["#inviteeEmailGsi"]=E.INVITEE_EMAIL_GSI,s["#inviteeEmailTenantSk"]=E.INVITEE_EMAIL_TENANT_SK,s["#inviteePhoneGsi"]=E.INVITEE_PHONE_GSI,s["#inviteePhoneTenantSk"]=E.INVITEE_PHONE_TENANT_SK);let c=`SET ${i.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new Fr.UpdateCommand({TableName:this.tableName,Key:{PK:K.INVITE_PK(e),SK:K.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantInvite",id:e})):T(N.UnknownError({message:n.message}))}}async findByTenantAndEmail(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":E.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":E.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":r,":tenantSk":`${De.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndEmail"}))}}async findByTenantAndPhone(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":E.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":E.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":r,":tenantSk":`${De.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndPhone"}))}}async findByTenantAndUserId(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":E.INVITE_TENANT_PK,"#sk":E.INVITE_TENANT_SK,"#inviteeUserId":E.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":ze.INVITE_TENANT_PK(e),":pendingPrefix":ze.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":r},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndUserId"}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":E.INVITE_TENANT_PK},s={":pk":ze.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=E.INVITE_TENANT_SK,s[":statusPrefix"]=ze.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new Fr.QueryCommand(o)),c=(a.Items||[]).map(d=>this.mapItemToEntity(d)),u=!!a.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return gt(c,{limit:n,hasNext:u,cursor:p,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant"}))}}async findPendingByEmail(e){try{let r=Ne(),i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":E.INVITEE_EMAIL_GSI,"#expiresAt":E.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":r}}))).Items||[];if(i.length===0)return w([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await Sl(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return w(a)}catch{return T(N.DatabaseQueryError({query:"findPendingByEmail"}))}}async findPendingByPhone(e){try{let r=Ne(),i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":E.INVITEE_PHONE_GSI,"#expiresAt":E.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":r}}))).Items||[];if(i.length===0)return w([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await Sl(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return w(a)}catch{return T(N.DatabaseQueryError({query:"findPendingByPhone"}))}}async countPendingByTenant(e){try{let r=await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":E.INVITE_TENANT_PK,"#sk":E.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":ze.INVITE_TENANT_PK(e),":pendingPrefix":ze.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return w(r.Count??0)}catch{return T(N.DatabaseQueryError({query:"countPendingByTenant"}))}}async expireOld(e){return w(0)}};var f8=ge(ir(),1);var Jf=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":K.TENANT_MEMBER_PK(e)}};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let o=(await this.docClient.send(new f8.QueryCommand(i))).Items||[],a=[],c=new Map;for(let y of o){let _=y.SK;if(_.startsWith(_t.TENANT_PROFILE)){let C=ve.tenantProfileUserId(_);c.set(C,y)}else _.startsWith(De.USER)&&a.push(y)}a.sort((y,_)=>_.createdAt-y.createdAt);let u=a.slice(0,n),p=a.length>n,d=u.map(y=>{let _=ve.tenantMemberUserId(y.SK),C=c.get(_);return this.toListItem(y,e,_,C)}),h=p&&u.length>0?Buffer.from(JSON.stringify({PK:u[u.length-1].PK,SK:u[u.length-1].SK})).toString("base64url"):null;return gt(d,{limit:n,hasNext:p,cursor:h,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e,r,n,i){let s={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};if(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),i){let o={tenantId:r,userId:n,createdAt:oe(i.createdAt),updatedAt:oe(i.updatedAt)};i.contactEmail&&(o.contactEmail=i.contactEmail),i.contactPhone&&(o.contactPhone=i.contactPhone),i.displayName&&(o.displayName=i.displayName),i.displayNameSource&&(o.displayNameSource=i.displayNameSource),i.givenName&&(o.givenName=i.givenName),i.familyName&&(o.familyName=i.familyName),i.avatarUrl&&(o.avatarUrl=i.avatarUrl),i.locale&&(o.locale=i.locale),i.jobTitle&&(o.jobTitle=i.jobTitle),i.bio&&(o.bio=i.bio),i.metadata&&(o.metadata=JSON.parse(i.metadata)),s.tenantProfile=o}return s}};var Kr=ge(ir(),1);var Yf=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=Kr.DynamoDBDocumentClient.from(e)}mapItemToEntity(e){let r=ve.tenantId(e.PK),n=ve.tenantMemberUserId(e.SK),i={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(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 Kr.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)}}));if(!n.Item)return w(null);let i=this.mapItemToEntity(n.Item);return w(i)}catch{return T(N.DatabaseQueryError({query:"get"}))}}async create(e){try{let r=Ne(),n=e.isOwner?void 0:e.authPerm,i=Zr({PK:K.TENANT_MEMBER_PK(e.tenantId),SK:K.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:ze.USER_TENANT_PK(e.userId),userTenantSk:ze.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,r,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new Kr.TransactWriteCommand({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:K.TENANT_MEMBER_PK(e.tenantId),SK:K.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 Kr.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(void 0)}catch(r){return r.name==="TransactionCanceledException"?r.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?T(N.UniqueConstraintViolation({field:"tenant owner"})):T(N.UniqueConstraintViolation({field:"tenant member"})):r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"tenant member"})):T(N.UnknownError({message:r.message}))}}async updatePermissions(e,r,n){try{let i={...n,updatedAt:Ne()},{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new Kr.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async updateStatus(e,r,n){try{return await this.docClient.send(new Kr.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":Ne()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}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":K.TENANT_MEMBER_PK(e),":skPrefix":De.USER},Limit:n};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let s=await this.docClient.send(new Kr.QueryCommand(i)),o=(s.Items||[]).map(u=>this.mapItemToEntity(u)),a=!!s.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null;return gt(o,{limit:n,hasNext:a,cursor:c,prevCursor:r?.cursor??null})}catch(n){let i=n instanceof Error?`${n.name}: ${n.message}`:String(n);return console.error("[DynamoDBTenantMemberRepository.listByTenant] Error:",i),T(N.DatabaseQueryError({query:`listByTenant \u2014 ${i}`}))}}async hasOwner(e){try{let r=await this.docClient.send(new Kr.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_OWNER_MARKER_SK()}}));return w(!!r.Item)}catch{return T(N.DatabaseQueryError({query:"hasOwner"}))}}async remove(e,r){try{return await this.docClient.send(new Kr.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:n.message}))}}};var W_=ge(ir(),1);var Xf=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??nv.DEFAULT,s=r?.parentTenantId,o=s?`${i}#${s}#`:`${i}#`,a={TableName:this.tableName,IndexName:tt.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":ze.USER_TENANT_PK(e),":skPrefix":o},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 W_.QueryCommand(a)),u=c.Items??[],p=await this.fetchProfileMap(e,u),d=u.map(_=>this.toListItem(_,e,p)),h=!!c.LastEvaluatedKey,y=h?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return gt(d,{limit:n,hasNext:h,cursor:y,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByUser query"}))}}async fetchProfileMap(e,r){let n=new Map;if(r.length===0)return n;let i=r.map(o=>({PK:K.TENANT_PROFILE_PK(ve.tenantId(o.PK)),SK:K.TENANT_PROFILE_SK(e)})),s=await this.docClient.send(new W_.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:i}}}));for(let o of s.Responses?.[this.tableName]??[]){let a=o,c=ve.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,r,n){let i=ve.tenantId(e.PK),s={tenantId:i,userId:r,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};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);let o=n.get(i);return o&&(o.contactEmail&&(s.contactEmail=o.contactEmail),o.contactPhone&&(s.contactPhone=o.contactPhone),o.displayName&&(s.displayName=o.displayName),o.displayNameSource&&(s.displayNameSource=o.displayNameSource),o.givenName&&(s.givenName=o.givenName),o.familyName&&(s.familyName=o.familyName),o.avatarUrl&&(s.avatarUrl=o.avatarUrl),o.locale&&(s.locale=o.locale),o.jobTitle&&(s.jobTitle=o.jobTitle),o.bio&&(s.bio=o.bio),o.metadata&&(s.metadata=JSON.parse(o.metadata))),s}};var xa=ge(ir(),1);var Zf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return Lt()}toEntity(e){let n={id:ve.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let r=await this.docClient.send(new xa.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()}}));return r.Item?w(this.toEntity(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get tenant"}))}}async create(e){try{let r=e.id??this.generateTenantId(),n=Ne(),i=Zr({PK:K.TENANT_PK(r),SK:K.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new xa.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"tenant"})):T(N.UnknownError({message:r.message}))}}async update(e,r){try{let n={updatedAt:Ne()};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:s,ExpressionAttributeValues:o}=$i(n);return await this.docClient.send(new xa.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()},UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"Tenant",id:e})):T(N.UnknownError({message:n.message}))}}async delete(e){try{return await this.docClient.send(new xa.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"Tenant",id:e})):T(N.UnknownError({message:r.message}))}}async list(){return T(N.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return T(N.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return T(N.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};var Bi=ge(ir(),1);var em=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let r=await this.docClient.send(new Bi.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()}}));return r.Item?w(this.unmarshall(r.Item,e)):w(null)}catch{return T(N.DatabaseQueryError({query:"get user auth"}))}}async create(e){try{let r=Ne(),n={...e,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new Bi.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${E.PK})`})),w(n)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"userAuth"})):T(N.DatabaseQueryError({query:"create user auth"}))}}async updateStatus(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":userStatus":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update user auth status"}))}}async updateMfaRequired(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa required"}))}}async updateMfaMethods(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa methods"}))}}async updateMfaSettings(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r.mfaRequired,":mfaMethods":r.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa settings"}))}}async remove(e){try{return await this.docClient.send(new Bi.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user auth"}))}}marshall(e){return{[E.PK]:K.USER_PK(e.userId),[E.SK]:K.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)}}unmarshall(e,r){return{userId:r,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}}};var tn=ge(ir(),1);function _l(t,e){return e?K.USER_MFA_WITH_ID_SK(t,e):K.USER_MFA_SK(t)}var tm=class{client;tableName;docClient;constructor(e,r){this.client=e,this.tableName=r,this.docClient=tn.DynamoDBDocumentClient.from(e)}toDynamoDBItem(e){let r={PK:K.USER_PK(e.userId),SK:_l(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=ve.mfaSKInfo(e.SK),i={userId:r,method:e.method,data:JSON.parse(e.data),createdAt:oe(e.createdAt),verifiedAt:Xr(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=Xr(e.lastFailedAt)),e.lockedUntil!==void 0&&(i.lockedUntil=Xr(e.lockedUntil)),e.lastUsedAt!==void 0&&(i.lastUsedAt=Xr(e.lastUsedAt)),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r,n){try{let i=_l(r,n),s=await this.docClient.send(new tn.GetCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i}}));return s.Item?w(this.fromDynamoDBItem(s.Item,e)):w(null)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.get error:",i),T(N.DatabaseQueryError({query:"get MFA authenticator"}))}}async findByUserId(e){try{let r={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.USER_PK(e),":skPrefix":_t.MFA}},s=((await this.docClient.send(new tn.QueryCommand(r))).Items??[]).map(o=>this.fromDynamoDBItem(o,e));return w(s)}catch(r){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserId error:",r),T(N.DatabaseQueryError({query:"find MFA authenticators by user"}))}}async findByUserIdAndMethod(e,r){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.USER_PK(e),":skPrefix":`${_t.MFA}${r}`}},o=((await this.docClient.send(new tn.QueryCommand(n))).Items??[]).filter(a=>a.method===r).map(a=>this.fromDynamoDBItem(a,e));return w(o)}catch(n){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserIdAndMethod error:",n),T(N.DatabaseQueryError({query:"find MFA authenticators by method"}))}}async create(e){try{let r={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(r.id=Lt());let n=this.toDynamoDBItem(r);return await this.docClient.send(new tn.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(this.fromDynamoDBItem(n,e.userId))}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"MFA authenticator"})):(console.error("DynamoDBUserMFAAuthenticatorRepository.create error:",r),T(N.DatabaseQueryError({query:"create MFA authenticator"})))}}async update(e,r,n,i){try{let s=_l(r,n),o=[],a={},c={};if(i.label!==void 0&&(o.push("#label = :label"),a["#label"]="label",c[":label"]=i.label),i.data!==void 0&&(o.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(i.data)),i.verifiedAt!==void 0&&(o.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&&(o.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&&(o.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=i.failedAttempts),i.lastFailedAt!==void 0&&(o.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&&(o.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&&(o.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(i.metadata)),o.length===0)return w(void 0);let u={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:s},UpdateExpression:`SET ${o.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new tn.UpdateCommand(u)),w(void 0)}catch(s){return console.error("DynamoDBUserMFAAuthenticatorRepository.update error:",s),T(N.DatabaseQueryError({query:"update MFA authenticator"}))}}async remove(e,r,n){try{let i=_l(r,n);return await this.docClient.send(new tn.DeleteCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i}})),w(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.remove error:",i),T(N.DatabaseQueryError({query:"remove MFA authenticator"}))}}async incrementFailedAttempts(e,r,n,i,s){try{let o=_l(r,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],u={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},p={":zero":0,":inc":1,":lastFailedAt":a};s!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),u["#lockedUntil"]="lockedUntil",p[":lockedUntil"]=a+s*60*1e3,p[":maxAttempts"]=i);let d={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:o},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:u,ExpressionAttributeValues:p};return await this.docClient.send(new tn.UpdateCommand(d)),w(void 0)}catch(o){return console.error("DynamoDBUserMFAAuthenticatorRepository.incrementFailedAttempts error:",o),T(N.DatabaseQueryError({query:"increment failed attempts"}))}}async resetFailedAttempts(e,r,n){try{let i=_l(r,n),s={TableName:this.tableName,Key:{PK:K.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 tn.UpdateCommand(s)),w(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.resetFailedAttempts error:",i),T(N.DatabaseQueryError({query:"reset failed attempts"}))}}async unlock(e,r,n){return this.resetFailedAttempts(e,r,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};var bn=ge(ir(),1);var rm=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=bn.DynamoDBDocumentClient.from(e)}generateUserId(){return Lt()}async getById(e){try{let r=await this.docClient.send(new bn.GetCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()}}));if(!r.Item)return w(null);let n=r.Item;if(n.deletedAt)return w(null);let s={id:ve.userId(n.PK),status:n.userStatus,createdAt:oe(n.createdAt),updatedAt:oe(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:oe(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 w(s)}catch{return T(N.DatabaseQueryError({query:"getById user"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateUserId(),i=e.status||"pending",s={PK:K.USER_PK(n),SK:K.USER_PROFILE_SK(),userStatus:i,createdAt:r,updatedAt:r};e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.username&&(s.username=e.username),e.displayName&&(s.displayName=e.displayName),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.metadata&&(s.metadata=JSON.stringify(e.metadata)),s[E.USER_STATUS_PK]=ze.USER_STATUS_PK(i),s[E.USER_STATUS_SK]=ze.USER_STATUS_SK(n),await this.docClient.send(new bn.PutCommand({TableName:this.tableName,Item:Zr(s),ConditionExpression:rv("PK")}));let o={id:n,status:i,createdAt:oe(r),updatedAt:oe(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 w(o)}catch{return T(N.DatabaseQueryError({query:"create user"}))}}async updateProfile(e,r){try{let n=Ne(),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 w(void 0);i.updatedAt=n;let s=$i(i);return await this.docClient.send(new bn.UpdateCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()},UpdateExpression:s.UpdateExpression,ExpressionAttributeNames:s.ExpressionAttributeNames,ExpressionAttributeValues:s.ExpressionAttributeValues})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"updateProfile"}))}}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 T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=ze.USER_STATUS_PK(e),o=await this.docClient.send(new bn.QueryCommand({TableName:this.tableName,IndexName:tt.USERS_BY_STATUS,KeyConditionExpression:`${E.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":s},Limit:n,ExclusiveStartKey:i})),a=[];if(o.Items&&o.Items.length>0)for(let p of o.Items){let d=ve.userId(p.PK);a.push(d)}let c=!!o.LastEvaluatedKey,u=c?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return w(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!r?.cursor,cursor:u}})}catch{return T(N.DatabaseQueryError({query:"get users by status"}))}}async countByStatus(e){try{let r=ze.USER_STATUS_PK(e),n=await this.docClient.send(new bn.QueryCommand({TableName:this.tableName,IndexName:tt.USERS_BY_STATUS,KeyConditionExpression:`${E.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":r},Select:"COUNT"}));return w(n.Count||0)}catch{return T(N.DatabaseQueryError({query:"count users by status"}))}}async syncAuthStatus(e,r){try{let n=Ne(),i=`SET userStatus = :userStatus, #${E.UPDATED_AT} = :updatedAt, #${E.USER_STATUS_PK} = :statusPk, #${E.USER_STATUS_SK} = :statusSk`,s={":userStatus":r,":updatedAt":n,":statusPk":ze.USER_STATUS_PK(r),":statusSk":ze.USER_STATUS_SK(e)};return r===Hi.DELETED?(i+=", deletedAt = :deletedAt",s[":deletedAt"]=n):i+=" REMOVE deletedAt",await this.docClient.send(new bn.UpdateCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()},UpdateExpression:i,ExpressionAttributeNames:{[`#${E.UPDATED_AT}`]:E.UPDATED_AT,[`#${E.USER_STATUS_PK}`]:E.USER_STATUS_PK,[`#${E.USER_STATUS_SK}`]:E.USER_STATUS_SK},ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK)"})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userProfile",id:e})):T(N.DatabaseQueryError({query:"sync auth status"}))}}async remove(e){try{return await this.docClient.send(new bn.DeleteCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user profile"}))}}};var li=ge(ir(),1);var nm=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=li.DynamoDBDocumentClient.from(e)}mapItemToUserProviderLink(e){let r=ve.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:oe(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=Ne(),n={PK:K.PROVIDER_PK(e.provider,e.externalId),SK:K.PROVIDER_METADATA_SK(),userProviderPk:K.USER_PK(e.userId),userProviderSk:K.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?Te(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)),Zr(n)}async findByProviderAndExternalId(e,r){try{let n=await this.docClient.send(new li.GetCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()}}));return n.Item?w(this.mapItemToUserProviderLink(n.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"find provider by external id"}))}}async findByUserId(e){try{let r=await this.docClient.send(new li.QueryCommand({TableName:this.tableName,IndexName:tt.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":E.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":K.USER_PK(e)}}));return!r.Items||r.Items.length===0?w([]):w(r.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch{return T(N.DatabaseQueryError({query:"find providers by user id"}))}}async create(e){try{let r={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(r);return await this.docClient.send(new li.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),w(this.mapItemToUserProviderLink(n))}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):T(N.DatabaseQueryError({query:"create user provider"}))}}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 w(void 0);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new li.UpdateCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update user provider"}))}}async remove(e,r){try{return await this.docClient.send(new li.DeleteCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"delete user provider"}))}}};var wa=ge(ir(),1);var im=class{docClient;tableName;constructor(e,r){this.docClient=e,this.tableName=r}mapItemToEntity(e){let r=ve.tenantId(e.PK),n=ve.tenantProfileUserId(e.SK),i={tenantId:r,userId:n,createdAt:oe(e.createdAt),updatedAt:oe(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 wa.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)}}));return n.Item?w(this.mapItemToEntity(n.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let r=Ne(),n={PK:K.TENANT_PROFILE_PK(e.tenantId),SK:K.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 wa.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let i={tenantId:e.tenantId,userId:e.userId,createdAt:oe(r),updatedAt:oe(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),w(i)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"user tenant profile"})):T(N.UnknownError({message:r.message}))}}async update(e,r,n){try{let i={updatedAt:Ne()};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:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new wa.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async remove(e,r){try{return await this.docClient.send(new wa.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):T(N.UnknownError({message:n.message}))}}};var j_=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 z_.DynamoDBClient(e.clientConfig||{});let r=m8.DynamoDBDocumentClient.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new rm(this.client,this.tableName),this.sessions=new jf({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new nm(this.client,this.tableName),this.userMfaAuthenticators=new tm(this.client,this.tableName),this.challenges=new Hf({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new qf({docClient:r,tableName:this.tableName}),this.credentials=new Gf({docClient:r,tableName:this.tableName}),this.registration=new Wf({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new em({docClient:r,tableName:this.tableName}),this.tenantMembers=new Yf(this.client,this.tableName),this.tenantInvites=new Qf({docClient:r,tableName:this.tableName}),this.userTenantProfiles=new im(r,this.tableName),this.tenants=new Zf({docClient:r,tableName:this.tableName}),this.queries={tenantInvites:new zf({docClient:r,tableName:this.tableName}),tenantMembers:new Jf({docClient:r,tableName:this.tableName}),tenants:new Xf({docClient:r,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new z_.DescribeTableCommand({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};Bv();var Fv=1,H5=2,G5=3,q5="auth-craft:internal";async function tye(t){let e=t.replace(/^0x/,""),r=j5(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 s=`-----BEGIN PRIVATE KEY-----
|
|
188
188
|
`+btoa(String.fromCharCode(...i)).match(/.{1,64}/g).join(`
|
|
189
189
|
`)+`
|
|
190
190
|
-----END PRIVATE KEY-----`;return fm(s,"EdDSA")}async function rye(t){let e=t.replace(/^0x/,""),r=j5(e),n=iye(r);return In({kty:"OKP",crv:"Ed25519",x:n},"EdDSA")}async function Kv(t,e){if(e==="EdDSA"){let r=t.trim();if(r.startsWith("{"))return In(JSON.parse(r),e);if(!r.includes(`
|