import { z } from 'zod';

// src/auth/multi-tenancy/theme-presets.ts
var THEME_PRESETS = [
  "default",
  "tactical",
  "regal",
  "cyber-volt",
  "aurora",
  "rose-gold",
  "midnight",
  "titanium",
  "canopy",
  "slate",
  "cyber-strike",
  "cyber-chrome",
  "cyber-void",
  "nirvana",
  "wave",
  "synapse",
  "cortex",
  "helios",
  "graphite",
  "quarry"
];
var ThemePresetEnum = z.enum(THEME_PRESETS);
var UuidSchema = z.string().uuid();
z.string().trim().min(1).max(1e3);
z.enum(["agent", "workflow"]);
z.enum(["agent", "workflow", "scheduler", "api"]);
z.string().trim().toLowerCase().min(1, "Credential name required").max(100, "Credential name too long (max 100 chars)").regex(
  /^[a-z0-9]+(-[a-z0-9]+)+$/,
  "Credential name must be lowercase letters, numbers, and hyphens in format: service-environment (e.g., gmail-prod, attio-dev)"
);
z.enum(["google-sheets", "google-calendar", "dropbox"]);
z.string().min(10, "Authorization code too short").max(1e3, "Authorization code too long");
z.string().min(10, "State parameter too short").max(2048, "State parameter too long");
z.string().trim().transform((str) => str.replace(/[<>'"]/g, ""));
var EmailSchema = z.string().email();
z.string().url();
z.object({
  limit: z.coerce.number().int().min(1).max(100).default(20),
  offset: z.coerce.number().int().min(0).default(0)
});
z.string().datetime();
z.object({
  startDate: z.string().datetime(),
  endDate: z.string().datetime()
});
function createStringSchema(minLength, maxLength, fieldName) {
  const schema = z.string().trim().min(minLength).max(maxLength);
  return fieldName ? schema.describe(`${fieldName} (${minLength}-${maxLength} characters)`) : schema;
}

// src/auth/multi-tenancy/org-id.ts
var WORKOS_ORG_ID_PREFIX = "org_";
function isSupabaseOrgId(value) {
  return UuidSchema.safeParse(value).success;
}
function isWorkOsOrgId(value) {
  return value.startsWith(WORKOS_ORG_ID_PREFIX);
}
function asSupabaseOrgId(value) {
  if (!isSupabaseOrgId(value)) {
    throw new Error(
      `Expected a Supabase organization UUID, received "${value}". A WorkOS org id (org_...) was likely used where the database key is required.`
    );
  }
  return value;
}
function asWorkOsOrgId(value) {
  if (!isWorkOsOrgId(value)) {
    throw new Error(
      `Expected a WorkOS organization id (org_...), received "${value}". A Supabase UUID was likely used where the auth identity is required.`
    );
  }
  return value;
}
function asSupabaseOrgIdOrNull(value) {
  return value == null ? null : asSupabaseOrgId(value);
}
function asWorkOsOrgIdOrNull(value) {
  return value == null ? null : asWorkOsOrgId(value);
}
function brandSupabaseOrgId(value) {
  return value ?? null;
}
function brandWorkOsOrgId(value) {
  return value ?? null;
}

// src/auth/multi-tenancy/permissions.ts
var PERMISSIONS = {
  ORG_READ: "org.read",
  ORG_MANAGE: "org.manage",
  ORG_DELETE: "org.delete",
  MEMBERS_MANAGE: "members.manage",
  ROLES_MANAGE: "roles.manage",
  SECRETS_MANAGE: "secrets.manage",
  OPERATIONS_READ: "operations.read",
  OPERATIONS_MANAGE: "operations.manage",
  SALES_LEAD_GEN_MANAGE: "sales.lead-gen.manage",
  ACQUISITION_MANAGE: "acquisition.manage",
  PROJECTS_MANAGE: "projects.manage",
  CLIENTS_MANAGE: "clients.manage"
};
var PERMISSION_CATALOG = [
  {
    key: "org.read",
    description: "Read organization profile and listings",
    isOrgGrantable: true
  },
  {
    key: "org.manage",
    description: "Update organization settings",
    isOrgGrantable: false
  },
  {
    key: "org.delete",
    description: "Delete the organization (owner-only)",
    isOrgGrantable: false
  },
  {
    key: "members.manage",
    description: "Invite, remove, and reassign roles for members",
    isOrgGrantable: false
  },
  {
    key: "roles.manage",
    description: "Grant or revoke privileged system roles (owner, admin) within the organization",
    isOrgGrantable: false
  },
  {
    key: "secrets.manage",
    description: "Create, update, and delete API keys and credentials",
    isOrgGrantable: false
  },
  {
    key: "operations.read",
    description: "View executions, sessions, schedules, and command queue",
    isOrgGrantable: true
  },
  {
    key: "operations.manage",
    description: "Run and modify executions, sessions, schedules, queue",
    isOrgGrantable: true
  },
  {
    key: "sales.lead-gen.manage",
    description: "Operate Lead Gen lists and list-builder workflows",
    isOrgGrantable: true
  },
  {
    key: "acquisition.manage",
    description: "Create, update, and delete acquisition records (acq_companies, acq_contacts, acq_deals, acq_lists*, acq_content*, acquisition storage files)",
    isOrgGrantable: false
  },
  {
    key: "projects.manage",
    description: "Create, update, and delete project records (prj_projects, prj_milestones, prj_tasks, prj_notes)",
    isOrgGrantable: false
  },
  {
    key: "clients.manage",
    description: "Create, update, and delete client hub records (clients, clt_* satellites)",
    isOrgGrantable: false
  }
];
var PERMISSION_KEY_SET = new Set(PERMISSION_CATALOG.map((p) => p.key));
function isPermissionKey(value) {
  return typeof value === "string" && PERMISSION_KEY_SET.has(value);
}
var PermissionKeySchema = z.string().min(1).max(100);
var OrgRoleParamsSchema = z.object({
  orgId: z.string().uuid(),
  roleId: z.string().uuid()
}).strict();
var OrgRolesParamsSchema = z.object({
  orgId: z.string().uuid()
}).strict();
var MembershipRoleParamsSchema = z.object({
  membershipId: z.string().min(1),
  roleId: z.string().uuid()
}).strict();
var MembershipParamsSchema = z.object({
  membershipId: z.string().min(1)
}).strict();
var CreateOrgRoleRequestSchema = z.object({
  name: z.string().min(1).max(100).trim(),
  slug: z.string().min(1).max(100).regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/, "Role slug must be lowercase letters, numbers, dashes, or underscores"),
  description: z.string().max(500).trim().optional(),
  permissionKeys: z.array(PermissionKeySchema).default([])
}).strict();
var UpdateOrgRoleRequestSchema = z.object({
  name: z.string().min(1).max(100).trim().optional(),
  slug: z.string().min(1).max(100).regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/, "Role slug must be lowercase letters, numbers, dashes, or underscores").optional(),
  description: z.string().max(500).trim().nullable().optional(),
  permissionKeys: z.array(PermissionKeySchema).optional()
}).strict().refine(
  (data) => data.name !== void 0 || data.slug !== void 0 || data.description !== void 0 || data.permissionKeys !== void 0,
  { message: "At least one field must be provided" }
);
var AssignMembershipRoleRequestSchema = z.object({
  roleId: z.string().uuid()
}).strict();
var OrganizationNameSchema = z.string().min(2, "Organization name must be at least 2 characters").max(100, "Organization name must be at most 100 characters").trim().regex(
  /^[a-zA-Z0-9\s\-_]+$/,
  "Organization name must contain only letters, numbers, spaces, hyphens, and underscores"
);
var OrganizationIdSchema = z.union([
  UuidSchema,
  z.string().regex(/^org_[a-zA-Z0-9]+$/, "Invalid WorkOS organization ID")
]);
var OrganizationDomainSchema = z.object({
  domain: z.string().min(3).max(255),
  state: z.enum(["verified", "pending", "failed"]).optional()
});
var OrganizationIdParamSchema = z.object({
  id: OrganizationIdSchema
}).strict();
var CreateOrganizationSchema = z.object({
  name: OrganizationNameSchema,
  domainData: z.array(OrganizationDomainSchema).max(10).optional(),
  metadata: z.record(z.string(), z.unknown()).refine((val) => JSON.stringify(val).length <= 10240, "Metadata must be under 10KB").optional()
}).strict();
var UpdateOrganizationSchema = CreateOrganizationSchema.partial().strict().refine((data) => Object.keys(data).length > 0, {
  message: "At least one field (name, domainData, or metadata) must be provided"
});
var UpdateOrganizationAuthConfigSchema = z.object({
  appOrigin: z.string().trim().url("App origin must be a valid URL").max(2048, "App origin must be at most 2048 characters").refine((value) => {
    try {
      const url = new URL(value);
      return url.pathname === "/" && url.search === "" && url.hash === "";
    } catch {
      return false;
    }
  }, "App origin must not include a path, query string, or hash")
}).strict();
var ListOrganizationsQuerySchema = z.object({
  limit: z.coerce.number().int().min(1).max(100).default(20),
  before: z.string().optional(),
  // WorkOS pagination cursor
  after: z.string().optional()
  // WorkOS pagination cursor
});
var UserIdParamSchema = z.object({
  id: z.string().min(1)
  // WorkOS user IDs can be UUID or 'user_' prefixed strings
}).strict();
var ExternalIdParamSchema = z.object({
  externalId: z.string().min(1)
}).strict();
var UpdateUserSchema = z.object({
  email: EmailSchema.optional(),
  firstName: createStringSchema(1, 100, "First name").optional(),
  lastName: createStringSchema(1, 100, "Last name").optional()
}).strict();
var UpdateMyProfileSchema = z.object({
  firstName: createStringSchema(1, 100, "First name").optional(),
  lastName: createStringSchema(1, 100, "Last name").optional(),
  profilePictureUrl: z.string().url().refine((url) => url.startsWith("https://"), { message: "Only HTTPS URLs are allowed" }).optional(),
  lastVisitedOrg: z.string().uuid().optional(),
  config: z.object({
    theme: z.object({
      // `.catch('default')` makes the write path tolerant of stale/unknown preset strings.
      // Any value that fails enum validation silently coerces to 'default' instead of 400ing.
      // This protects against preset renames (e.g. cyber-punk → cyber-chrome) and drift between
      // the enum and legacy DB values. Paired with a read-path sync-back in main.tsx that
      // persists the corrected value back to DB on next profile load.
      // ThemePresetEnum is derived from THEME_PRESETS — the single source of truth in
      // packages/core/src/auth/multi-tenancy/theme-presets.ts.
      preset: ThemePresetEnum.catch("default").optional(),
      colorScheme: z.enum(["light", "dark", "auto"]).catch("auto").optional()
    }).strict().optional(),
    onboarding: z.object({
      completed: z.boolean().optional(),
      completedAt: z.string().datetime().nullable().optional(),
      role: z.string().max(100).nullable().optional(),
      primaryUseCase: z.array(z.string().max(100)).max(10).nullable().optional(),
      experienceLevel: z.string().max(100).nullable().optional(),
      guides: z.object({
        completedIds: z.array(z.string().max(100)).max(20).optional(),
        dismissed: z.boolean().optional(),
        completedAt: z.string().datetime().nullable().optional()
      }).strict().optional()
    }).strict().optional()
  }).strict().optional()
}).strict();
var ListUsersQuerySchema = z.object({
  email: EmailSchema.optional(),
  organizationId: z.string().optional(),
  // WorkOS org IDs can be UUID or 'org_' prefixed
  limit: z.coerce.number().int().min(1).max(100).optional(),
  before: z.string().optional(),
  // WorkOS pagination cursor
  after: z.string().optional()
  // WorkOS pagination cursor
}).strict();

// src/auth/multi-tenancy/memberships/membership.ts
function transformMembershipToTableRow(membership) {
  return {
    id: membership.id,
    userId: membership.userId,
    organizationId: membership.organizationId,
    userEmail: membership.user?.email || "Unknown",
    userFullName: membership.user?.firstName && membership.user?.lastName ? `${membership.user.firstName} ${membership.user.lastName}` : membership.user?.email || "Unknown User",
    organizationName: membership.organization?.name || "Unknown Organization",
    role: membership.role.slug,
    status: membership.status,
    statusBadge: membership.status,
    joinedAt: new Date(membership.createdAt),
    updatedAt: new Date(membership.updatedAt),
    canEdit: membership.status === "active",
    canRemove: true
  };
}
var MEMBERSHIP_STATUS_COLORS = {
  active: "green",
  inactive: "gray"
};

// src/auth/multi-tenancy/memberships/supabase.ts
function mapSupabaseStatus(status) {
  if (status === "active") return "active";
  return "inactive";
}
function transformSupabaseToMembership(supabaseData) {
  return {
    object: "organization_membership",
    id: supabaseData.workos_membership_id ?? supabaseData.id,
    userId: supabaseData.user_id,
    // Always use Supabase user_id
    organizationId: supabaseData.organization_id,
    // Always use Supabase organization_id
    role: { slug: supabaseData.role_slug || "member" },
    status: mapSupabaseStatus(supabaseData.membership_status),
    createdAt: supabaseData.created_at || (/* @__PURE__ */ new Date()).toISOString(),
    updatedAt: supabaseData.updated_at || (/* @__PURE__ */ new Date()).toISOString()
  };
}
var MembershipRoleSchema = z.string().min(1).max(64);
var MembershipStatusSchema = z.enum(["active", "inactive"]);
var MembershipIdParamSchema = z.object({
  id: z.string().min(1)
  // WorkOS membership IDs can be various formats
}).strict();
var OrgIdParamSchema = z.object({
  orgId: z.string().uuid()
}).strict();
var MyOrgPermissionsResponseSchema = z.object({
  permissions: z.array(z.string())
});
var CreateMembershipSchema = z.object({
  userId: z.string().min(1),
  organizationId: z.string().min(1),
  roleSlug: MembershipRoleSchema.default("member")
}).strict();
var UpdateMembershipSchema = z.object({
  roleSlug: MembershipRoleSchema
}).strict();
var ListMembershipsQuerySchema = z.object({
  userId: z.string().optional(),
  organizationId: z.string().optional(),
  limit: z.coerce.number().int().min(1).max(100).optional(),
  before: z.string().optional(),
  // WorkOS pagination cursor
  after: z.string().optional()
  // WorkOS pagination cursor
}).strict().refine((data) => data.userId || data.organizationId, {
  message: "Either userId or organizationId must be provided"
});

// src/auth/multi-tenancy/invitations/supabase.ts
function transformSupabaseToInvitation(supabaseInvitation) {
  return {
    id: supabaseInvitation.id,
    workosInvitationId: supabaseInvitation.workos_invitation_id,
    email: supabaseInvitation.email,
    organizationId: supabaseInvitation.organization_id,
    inviterUserId: supabaseInvitation.inviter_user_id,
    invitationState: supabaseInvitation.invitation_state,
    roleSlug: supabaseInvitation.role_slug,
    invitationToken: supabaseInvitation.invitation_token,
    acceptInvitationUrl: supabaseInvitation.accept_invitation_url,
    acceptedAt: supabaseInvitation.accepted_at,
    revokedAt: supabaseInvitation.revoked_at,
    expiresAt: supabaseInvitation.expires_at,
    createdAt: supabaseInvitation.created_at,
    updatedAt: supabaseInvitation.updated_at
  };
}
var InvitationIdParamSchema = z.object({
  id: z.string().min(1)
  // WorkOS invitation IDs
}).strict();
var SendInvitationSchema = z.object({
  email: EmailSchema,
  organizationId: z.string().optional(),
  // For WorkOS API - but typically from JWT
  roleSlug: MembershipRoleSchema.default("member"),
  expiresInDays: z.number().int().min(1).max(90).default(7)
}).strict();
var AcceptInvitationSchema = z.object({
  invitation_token: z.string().min(1, "Invitation token is required")
}).strict();
var InviteRouterQuerySchema = z.object({
  invitation_token: z.string().min(1, "Invitation token is required")
}).strict();
var ListInvitationsQuerySchema = z.object({
  organizationId: z.string().optional(),
  userId: z.string().optional(),
  email: EmailSchema.optional(),
  limit: z.coerce.number().int().min(1).max(100).optional(),
  before: z.string().optional(),
  // WorkOS pagination cursor
  after: z.string().optional()
  // WorkOS pagination cursor
}).strict().refine((data) => data.organizationId || data.userId, { message: "Either organizationId or userId must be provided" });

// src/organization-model/helpers.ts
function childSystemsOf(system) {
  return system.systems ?? system.subsystems ?? {};
}
function getSystem(model, path) {
  const flatMatch = model.systems[path];
  if (flatMatch !== void 0) return flatMatch;
  const segments = path.split(".");
  let current = model.systems;
  let node;
  for (const seg of segments) {
    node = current[seg];
    if (node === void 0) return void 0;
    current = childSystemsOf(node);
  }
  return node;
}
function listAllSystems(model) {
  const results = [];
  function walk(map, prefix) {
    for (const [localId, system] of Object.entries(map)) {
      const fullPath = prefix ? `${prefix}.${localId}` : localId;
      results.push({ path: fullPath, system });
      const childSystems = childSystemsOf(system);
      if (Object.keys(childSystems).length > 0) {
        walk(childSystems, fullPath);
      }
    }
  }
  walk(model.systems, "");
  return results;
}

// src/auth/access-keys.ts
var DEFAULT_ACCESS_ACTION = "view";
var PLATFORM_ADMIN_ACCESS_KEY = "platform.admin";
var PLATFORM_ADMIN_ACCESS_KEY_SHORTHAND = "platformAdmin";
var AccessActionSchema = z.enum(["view", "manage"]);
var AccessKeyObjectSchema = z.object({
  systemPath: z.string().trim().min(1),
  action: AccessActionSchema.default(DEFAULT_ACCESS_ACTION)
}).strict();
var AccessKeyInputSchema = z.union([z.string().trim().min(1), AccessKeyObjectSchema]);
var NormalizedAccessKeySchema = AccessKeyObjectSchema;
var AccessKeySchema = AccessKeyInputSchema;
var DIAGNOSTIC_VIEW_ACCESS_KEYS = [
  "diagnostic.operations.overview",
  "diagnostic.operations.recent-executions",
  "diagnostic.monitoring.execution-logs",
  "diagnostic.monitoring.notifications"
];
var AccessKeys = {
  platformAdmin: { systemPath: PLATFORM_ADMIN_ACCESS_KEY, action: DEFAULT_ACCESS_ACTION },
  organizationManage: { systemPath: "permission.org", action: "manage" },
  membersManage: { systemPath: "permission.members", action: "manage" },
  rolesManage: { systemPath: "permission.roles", action: "manage" },
  /** @reserved Reserved for first-class secret administration routes and command surfaces. */
  secretsManage: { systemPath: "permission.secrets", action: "manage" },
  operationsRead: { systemPath: "permission.operations", action: DEFAULT_ACCESS_ACTION },
  /** @reserved Reserved for write-level operations administration beyond read-only monitoring. */
  operationsManage: { systemPath: "permission.operations", action: "manage" },
  leadGenManage: { systemPath: "sales.lead-gen", action: "manage" },
  /** @reserved Reserved for acquisition administration once that permission namespace is wired. */
  acquisitionManage: { systemPath: "permission.acquisition", action: "manage" },
  /** @reserved Reserved for project administration permission catalog compatibility. */
  projectsManage: { systemPath: "permission.projects", action: "manage" },
  /** @reserved Reserved for client administration permission catalog compatibility. */
  clientsManage: { systemPath: "permission.clients", action: "manage" },
  operationsOverview: { systemPath: "diagnostic.operations.overview", action: DEFAULT_ACCESS_ACTION },
  /** @reserved Reserved for a diagnostics surface that lists recent operations executions. */
  operationsRecentExecutions: { systemPath: "diagnostic.operations.recent-executions", action: DEFAULT_ACCESS_ACTION },
  monitoringExecutionLogs: { systemPath: "diagnostic.monitoring.execution-logs", action: DEFAULT_ACCESS_ACTION },
  monitoringNotifications: { systemPath: "diagnostic.monitoring.notifications", action: DEFAULT_ACCESS_ACTION }
};
var PERMISSION_ACCESS_KEY_DEFINITIONS = [
  { key: AccessKeys.organizationManage, rolePermission: PERMISSIONS.ORG_MANAGE },
  { key: AccessKeys.membersManage, rolePermission: PERMISSIONS.MEMBERS_MANAGE },
  { key: AccessKeys.rolesManage, rolePermission: PERMISSIONS.ROLES_MANAGE },
  { key: AccessKeys.secretsManage, rolePermission: PERMISSIONS.SECRETS_MANAGE },
  { key: AccessKeys.operationsRead, rolePermission: PERMISSIONS.OPERATIONS_READ },
  { key: AccessKeys.operationsManage, rolePermission: PERMISSIONS.OPERATIONS_MANAGE },
  { key: AccessKeys.acquisitionManage, rolePermission: PERMISSIONS.ACQUISITION_MANAGE },
  { key: AccessKeys.projectsManage, rolePermission: PERMISSIONS.PROJECTS_MANAGE },
  { key: AccessKeys.clientsManage, rolePermission: PERMISSIONS.CLIENTS_MANAGE }
];
function normalizeAccessKey(input) {
  const parsed = AccessKeyInputSchema.parse(input);
  const normalized = typeof parsed === "string" ? {
    systemPath: parsed === PLATFORM_ADMIN_ACCESS_KEY_SHORTHAND ? PLATFORM_ADMIN_ACCESS_KEY : parsed,
    action: DEFAULT_ACCESS_ACTION
  } : parsed;
  return NormalizedAccessKeySchema.parse(normalized);
}
function accessKeyToString(input) {
  const key = normalizeAccessKey(input);
  return `${key.systemPath}:${key.action}`;
}
function rolePermissionForAccessKey(key) {
  if (key.action === DEFAULT_ACCESS_ACTION) return void 0;
  return `${key.systemPath}.${key.action}`;
}
function groupCatalogEntries(entries) {
  const grouped = /* @__PURE__ */ new Map();
  for (const entry of entries) {
    const existing = grouped.get(entry.key.systemPath) ?? [];
    existing.push(entry);
    grouped.set(entry.key.systemPath, existing);
  }
  return grouped;
}
function buildCatalogEntry(systemPath, action, source) {
  const key = normalizeAccessKey({ systemPath, action });
  return {
    key,
    source,
    rolePermission: rolePermissionForAccessKey(key)
  };
}
function deriveAccessKeyCatalog(organizationModel, options = {}) {
  const { diagnosticKeys = DIAGNOSTIC_VIEW_ACCESS_KEYS, includeManageActions = true } = options;
  const entries = [
    buildCatalogEntry(PLATFORM_ADMIN_ACCESS_KEY, DEFAULT_ACCESS_ACTION, "platform")
  ];
  for (const { path } of listAllSystems(organizationModel)) {
    entries.push(buildCatalogEntry(path, DEFAULT_ACCESS_ACTION, "om-system"));
    if (includeManageActions) {
      entries.push(buildCatalogEntry(path, "manage", "om-system"));
    }
  }
  for (const { key, rolePermission } of PERMISSION_ACCESS_KEY_DEFINITIONS) {
    entries.push({
      key,
      source: "permission",
      rolePermission
    });
  }
  for (const systemPath of diagnosticKeys) {
    entries.push(buildCatalogEntry(systemPath, DEFAULT_ACCESS_ACTION, "diagnostic"));
  }
  return {
    bySystemPath: groupCatalogEntries(entries),
    entries
  };
}
function findAccessCatalogEntry(catalog, key) {
  return catalog.bySystemPath.get(key.systemPath)?.find((entry) => entry.key.action === key.action);
}
function listAccessKeys(catalog) {
  return catalog.entries.map((entry) => entry.key);
}

// src/auth/access-model.ts
var ALLOWED = { allowed: true, restrictedBy: null, reason: "allowed" };
var PLATFORM_ADMIN_BYPASS = {
  allowed: true,
  restrictedBy: null,
  reason: "platform-admin-bypass"
};
function deny(restrictedBy, reason) {
  return { allowed: false, restrictedBy, reason };
}
function isPlatformAdmin(profile) {
  return profile?.isPlatformAdmin === true || profile?.is_platform_admin === true;
}
function diagnosticAllowlistHas(allowlist, systemPath) {
  if (allowlist === void 0) return false;
  return "has" in allowlist ? allowlist.has(systemPath) : allowlist.includes(systemPath);
}
function lifecycleAllowsAccess(lifecycle, ctx) {
  if (lifecycle === "active") return true;
  if (lifecycle === "beta") return ctx.betaAccessEnabled === true || ctx.isDevelopment === true;
  return false;
}
function getPermissionSource(ctx) {
  return ctx.permissions ?? ctx.membership?.effectivePermissions;
}
function hasRequiredPermission(key, rolePermission, ctx) {
  const permissionSource = getPermissionSource(ctx);
  if (permissionSource === void 0 || permissionSource === null) return true;
  const requiredPermission = rolePermission ?? `${key.systemPath}.${key.action}`;
  return permissionSource.includes(requiredPermission);
}
function hasExplicitRequiredPermission(rolePermission, ctx) {
  const permissionSource = getPermissionSource(ctx);
  return rolePermission !== void 0 && permissionSource !== void 0 && permissionSource !== null ? permissionSource.includes(rolePermission) : false;
}
function checkAccess(input, ctx) {
  if (isPlatformAdmin(ctx.profile)) return PLATFORM_ADMIN_BYPASS;
  const parsed = (() => {
    try {
      return normalizeAccessKey(input);
    } catch {
      return null;
    }
  })();
  if (parsed === null) return deny("catalog", "invalid-access-key");
  const catalog = ctx.accessCatalog ?? deriveAccessKeyCatalog(ctx.organizationModel);
  const catalogEntry = findAccessCatalogEntry(catalog, parsed);
  if (catalogEntry === void 0) return deny("catalog", "unknown-access-key");
  const membership = ctx.membership;
  if (membership === void 0 || membership === null) return deny("membership", "missing-membership");
  if (membership.organizationId !== ctx.organizationId) return deny("membership", "organization-mismatch");
  if (parsed.systemPath === PLATFORM_ADMIN_ACCESS_KEY) {
    return deny("role-permission", "role-permission-denied");
  }
  if (catalogEntry.source === "diagnostic") {
    if (!diagnosticAllowlistHas(ctx.diagnosticAllowlist, parsed.systemPath)) {
      return deny("diagnostic-allowlist", "diagnostic-key-not-allowed");
    }
    if (parsed.action !== DEFAULT_ACCESS_ACTION && !hasRequiredPermission(parsed, catalogEntry.rolePermission, ctx)) {
      return deny("role-permission", "role-permission-denied");
    }
    return ALLOWED;
  }
  if (catalogEntry.source === "permission") {
    if (!hasExplicitRequiredPermission(catalogEntry.rolePermission, ctx)) {
      return deny("role-permission", "role-permission-denied");
    }
    return ALLOWED;
  }
  const system = getSystem(ctx.organizationModel, parsed.systemPath);
  if (system === void 0 || !lifecycleAllowsAccess(system.lifecycle, ctx)) {
    return deny("system-lifecycle", "system-not-active");
  }
  if (parsed.action !== DEFAULT_ACCESS_ACTION && !hasRequiredPermission(parsed, catalogEntry.rolePermission, ctx)) {
    return deny("role-permission", "role-permission-denied");
  }
  return ALLOWED;
}
function createAccessModel(organizationModel) {
  const catalog = deriveAccessKeyCatalog(organizationModel);
  return {
    catalog,
    checkAccess: (key, ctx) => checkAccess(key, { ...ctx, organizationModel, accessCatalog: catalog })
  };
}

export { AcceptInvitationSchema, AccessActionSchema, AccessKeyInputSchema, AccessKeyObjectSchema, AccessKeySchema, AccessKeys, AssignMembershipRoleRequestSchema, CreateMembershipSchema, CreateOrgRoleRequestSchema, CreateOrganizationSchema, DEFAULT_ACCESS_ACTION, DIAGNOSTIC_VIEW_ACCESS_KEYS, ExternalIdParamSchema, InvitationIdParamSchema, InviteRouterQuerySchema, ListInvitationsQuerySchema, ListMembershipsQuerySchema, ListOrganizationsQuerySchema, ListUsersQuerySchema, MEMBERSHIP_STATUS_COLORS, MembershipIdParamSchema, MembershipParamsSchema, MembershipRoleParamsSchema, MembershipRoleSchema, MembershipStatusSchema, MyOrgPermissionsResponseSchema, NormalizedAccessKeySchema, OrgIdParamSchema, OrgRoleParamsSchema, OrgRolesParamsSchema, OrganizationDomainSchema, OrganizationIdParamSchema, OrganizationNameSchema, PERMISSIONS, PERMISSION_CATALOG, PLATFORM_ADMIN_ACCESS_KEY, PLATFORM_ADMIN_ACCESS_KEY_SHORTHAND, SendInvitationSchema, THEME_PRESETS, ThemePresetEnum, UpdateMembershipSchema, UpdateMyProfileSchema, UpdateOrgRoleRequestSchema, UpdateOrganizationAuthConfigSchema, UpdateOrganizationSchema, UpdateUserSchema, UserIdParamSchema, accessKeyToString, asSupabaseOrgId, asSupabaseOrgIdOrNull, asWorkOsOrgId, asWorkOsOrgIdOrNull, brandSupabaseOrgId, brandWorkOsOrgId, checkAccess, createAccessModel, deriveAccessKeyCatalog, findAccessCatalogEntry, isPermissionKey, isSupabaseOrgId, isWorkOsOrgId, listAccessKeys, normalizeAccessKey, rolePermissionForAccessKey, transformMembershipToTableRow, transformSupabaseToInvitation, transformSupabaseToMembership };
