← back to Redbullvine__speccomllc

Function bodies 103 total

All specs Real LLM only Function bodies
extract_exif_metadata function · python · L79-L109 (31 LOC)
scripts/import_proof_packets.py
def extract_exif_metadata(image_bytes: bytes) -> dict[str, Any]:
    result: dict[str, Any] = {
        "width": None,
        "height": None,
        "captured_at": None,
        "gps_lat": None,
        "gps_lng": None,
    }
    try:
        with Image.open(io.BytesIO(image_bytes)) as img:
            result["width"] = img.width
            result["height"] = img.height
            exif = img.getexif() or {}
            tags = exif_tag_lookup()
            dt_tag = tags.get("DateTimeOriginal")
            fallback_dt_tag = tags.get("DateTime")
            captured = exif.get(dt_tag) if dt_tag else None
            if not captured and fallback_dt_tag:
                captured = exif.get(fallback_dt_tag)
            if captured:
                captured_text = captured.decode() if isinstance(captured, bytes) else str(captured)
                result["captured_at"] = captured_text.replace(":", "-", 2)
            gps_tag = tags.get("GPSInfo")
            gps_raw = exif.get(gps_tag) if 
extract_jpegs_from_pdf_bytes function · python · L112-L127 (16 LOC)
scripts/import_proof_packets.py
def extract_jpegs_from_pdf_bytes(pdf_bytes: bytes) -> list[bytes]:
    images: list[bytes] = []
    cursor = 0
    while True:
        start = pdf_bytes.find(b"\xff\xd8", cursor)
        if start < 0:
            break
        end = pdf_bytes.find(b"\xff\xd9", start + 2)
        if end < 0:
            break
        chunk = pdf_bytes[start : end + 2]
        cursor = end + 2
        if len(chunk) < MIN_JPEG_BYTES:
            continue
        images.append(chunk)
    return images
write_seed_csv function · python · L130-L136 (7 LOC)
scripts/import_proof_packets.py
def write_seed_csv(path: Path, rows: list[dict[str, Any]]) -> None:
    headers = ["location_name", "latitude", "longitude", "notes", "source_pdf"]
    with path.open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        writer.writeheader()
        for row in rows:
            writer.writerow(row)
run function · python · L139-L224 (86 LOC)
scripts/import_proof_packets.py
def run(pdf_paths: list[Path], out_root: Path) -> None:
    out_root.mkdir(parents=True, exist_ok=True)
    manifest: dict[str, Any] = {
        "generated_at": datetime.utcnow().isoformat() + "Z",
        "files": [],
    }
    seed_rows: list[dict[str, Any]] = []

    for pdf_path in pdf_paths:
        pdf_bytes = pdf_path.read_bytes()
        location_name, prefix_code, reported_count = parse_source_name(pdf_path.name)
        location_slug = sanitize_slug(location_name)
        location_dir = out_root / location_slug
        location_dir.mkdir(parents=True, exist_ok=True)

        raw_images = extract_jpegs_from_pdf_bytes(pdf_bytes)
        dedupe: set[str] = set()
        photo_records: list[PhotoRecord] = []
        first_lat = None
        first_lng = None

        for idx, chunk in enumerate(raw_images, start=1):
            sha1 = hashlib.sha1(chunk).hexdigest()
            if sha1 in dedupe:
                continue
            dedupe.add(sha1)

            image_meta = extra
main function · python · L227-L249 (23 LOC)
scripts/import_proof_packets.py
def main() -> None:
    parser = argparse.ArgumentParser(
        description="Extract proof photos from PM PDF packets and generate import manifest/seed CSV."
    )
    parser.add_argument(
        "--input",
        nargs="+",
        required=True,
        help="One or more PDF file paths.",
    )
    parser.add_argument(
        "--out",
        default=str(Path("project_uploads") / f"packet_import_{datetime.now().strftime('%Y%m%d_%H%M%S')}"),
        help="Output directory root for extracted photos and manifests.",
    )
    args = parser.parse_args()

    pdf_paths = [Path(p) for p in args.input]
    missing = [str(p) for p in pdf_paths if not p.exists()]
    if missing:
        raise SystemExit(f"Missing input files: {missing}")
    out_root = Path(args.out)
    run(pdf_paths, out_root)
parseCsvText function · javascript · L36-L44 (9 LOC)
scripts/rewrite_photo_csv.js
function parseCsvText(text){
  const lines = text.split(/\r?\n/);
  const rows = [];
  for (const line of lines){
    if (!line) continue;
    rows.push(parseCsvLine(line));
  }
  return rows;
}
parseCsvLine function · javascript · L46-L70 (25 LOC)
scripts/rewrite_photo_csv.js
function parseCsvLine(line){
  const out = [];
  let cur = '';
  let inQuotes = false;
  for (let i = 0; i < line.length; i++){
    const ch = line[i];
    if (ch === '"'){
      if (inQuotes && line[i+1] === '"'){
        cur += '"';
        i += 1;
        continue;
      }
      inQuotes = !inQuotes;
      continue;
    }
    if (ch === ',' && !inQuotes){
      out.push(cur);
      cur = '';
      continue;
    }
    cur += ch;
  }
  out.push(cur);
  return out;
}
About: code-quality intelligence by Repobility · https://repobility.com
csvCell function · javascript · L72-L75 (4 LOC)
scripts/rewrite_photo_csv.js
function csvCell(v) {
  const s = String(v ?? "");
  return `"${s.replace(/"/g, '""')}"`;
}
normKey function · javascript · L77-L79 (3 LOC)
scripts/rewrite_photo_csv.js
function normKey(v){
  return String(v || '').toLowerCase().trim().replace(/\s+/g, '').replace(/[-_()\[\]]/g, '');
}
extractEnclosureToken function · javascript · L81-L98 (18 LOC)
scripts/rewrite_photo_csv.js
function extractEnclosureToken(raw){
  const text = String(raw || '').trim();
  if (!text) return '';
  const numericTokens = (text.match(/\d+(?:\/@[\w.]+)?/g) || []);
  if (numericTokens.length > 1 && /(node\s*\d+|1635\s*ca)/i.test(text)){
    const candidates = numericTokens.filter((token) => {
      const base = String(token).split('/@')[0] || token;
      const num = Number.parseInt(base, 10);
      return Number.isFinite(num) && (num >= 100 || base.length >= 3);
    });
    if (candidates.length) return candidates[candidates.length - 1];
    return numericTokens[numericTokens.length - 1];
  }
  const direct = text.match(/^\d+(?:\/@[\w.]+)?$/);
  if (direct) return direct[0];
  const token = text.match(/\b(\d+(?:\/@[\w.]+)?)\b/);
  return token ? token[1] : '';
}
matchSiteFromSegment function · javascript · L100-L126 (27 LOC)
scripts/rewrite_photo_csv.js
function matchSiteFromSegment(segmentRaw, sitesByName, sites){
  const seg = String(segmentRaw || '').trim();
  if (!seg) return null;
  // exact
  if (sitesByName.has(seg)) return sitesByName.get(seg);
  const segNorm = normKey(seg);
  // normalized equality
  for (const s of sites){ if (normKey(s.name) === segNorm) return s; }
  // extract core/suffix
  const m = seg.match(/^([a-z0-9]+)[_\-]?(\d+)?$/i);
  const core = (m && m[1]) ? m[1] : seg;
  const suffix = (m && m[2]) ? m[2] : '';
  const coreNorm = normKey(core);
  // contains core and optional suffix
  for (const s of sites){
    const n = normKey(s.name || '');
    if (n.includes(coreNorm) && (!suffix || n.includes(normKey(suffix)))) return s;
  }
  // contains full segment norm
  for (const s of sites){ if (normKey(s.name || '').includes(segNorm)) return s; }
  // enclosure token match
  const encl = extractEnclosureToken(seg);
  if (encl){
    for (const s of sites){ if ((s.name || '').includes(encl)) return s; }
  }
  retur
parse_codes function · python · L22-L37 (16 LOC)
scripts/wired_production_pdf_to_csv.py
def parse_codes(codes_raw: str) -> list[tuple[str, int]]:
    parts = [clean_text(p) for p in str(codes_raw or "").split(",")]
    result: list[tuple[str, int]] = []
    for part in parts:
        if not part:
            continue
        m = CODE_QTY_RE.match(part)
        if m:
            code = clean_text(m.group(1))
            qty = int(m.group(2))
        else:
            code = part
            qty = 1
        if code:
            result.append((code, qty))
    return result
extract_rows function · python · L40-L77 (38 LOC)
scripts/wired_production_pdf_to_csv.py
def extract_rows(pdf_path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    with pdfplumber.open(str(pdf_path)) as pdf:
        for page in pdf.pages:
            tables = page.extract_tables() or []
            for table in tables:
                if not table:
                    continue
                for raw_row in table[1:]:
                    if not raw_row or len(raw_row) < 5:
                        continue
                    job_map = clean_text(raw_row[0])
                    enclosure = clean_text(raw_row[1])
                    tech = clean_text(raw_row[2])
                    date = clean_text(raw_row[3])
                    codes_raw = clean_text(raw_row[4])
                    test_raw = clean_text(raw_row[5] if len(raw_row) > 5 else "")
                    if not job_map or job_map.lower() == "job/map":
                        continue
                    if job_map.lower().startswith("production summary"):
                        continue
   
load_coords_map function · python · L84-L122 (39 LOC)
scripts/wired_production_pdf_to_csv.py
def load_coords_map(coords_csv: Path | None) -> dict[str, tuple[str, str]]:
    if not coords_csv:
        return {}
    key_to_coords: dict[str, tuple[str, str]] = {}
    with coords_csv.open("r", encoding="utf-8-sig", newline="") as f:
        reader = csv.DictReader(f)
        headers = [normalize_key(h) for h in (reader.fieldnames or [])]
        hdr_map = {normalize_key(h): h for h in (reader.fieldnames or [])}

        def find_header(candidates: list[str]) -> str | None:
            for c in candidates:
                if c in headers:
                    return hdr_map[c]
            return None

        lat_h = find_header(["latitude", "lat", "gps_lat"])
        lng_h = find_header(["longitude", "lng", "gps_lng"])
        if not lat_h or not lng_h:
            raise SystemExit("coords CSV is missing latitude/longitude headers.")
        key_headers = [
            find_header(["external_ref"]),
            find_header(["location_name"]),
            find_header(["enclosure"]),
build_import_rows function · python · L125-L169 (45 LOC)
scripts/wired_production_pdf_to_csv.py
def build_import_rows(
    production_rows: list[dict[str, Any]],
    coords_map: dict[str, tuple[str, str]],
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
    all_rows: list[dict[str, Any]] = []
    app_rows: list[dict[str, Any]] = []
    missing_coords: list[dict[str, Any]] = []

    for src in production_rows:
        lat = ""
        lng = ""
        for key in (
            normalize_key(src["external_ref"]),
            normalize_key(src["enclosure"]),
            normalize_key(src["job_map"]),
        ):
            if key in coords_map:
                lat, lng = coords_map[key]
                break

        notes = f"Wired production import | job_map={src['job_map']} | enclosure={src['enclosure']} | tech={src['tech']} | date={src['date']}"
        row: dict[str, Any] = {
            "location_name": src["enclosure"] or src["external_ref"],
            "latitude": lat,
            "longitude": lng,
            "progress_notes": notes,
          
All rows above produced by Repobility · https://repobility.com
write_csv function · python · L172-L182 (11 LOC)
scripts/wired_production_pdf_to_csv.py
def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
    all_headers: list[str] = []
    for row in rows:
        for key in row.keys():
            if key not in all_headers:
                all_headers.append(key)
    with path.open("w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=all_headers)
        writer.writeheader()
        for row in rows:
            writer.writerow(row)
run function · python · L185-L210 (26 LOC)
scripts/wired_production_pdf_to_csv.py
def run(pdf_path: Path, out_dir: Path, coords_csv: Path | None) -> None:
    out_dir.mkdir(parents=True, exist_ok=True)
    production_rows = extract_rows(pdf_path)
    coords_map = load_coords_map(coords_csv)
    all_rows, app_rows, missing_coords = build_import_rows(production_rows, coords_map)

    stem = pdf_path.stem
    all_path = out_dir / f"{stem}__normalized.csv"
    app_path = out_dir / f"{stem}__app_import_ready.csv"
    missing_path = out_dir / f"{stem}__missing_coords.csv"

    write_csv(all_path, all_rows)
    write_csv(app_path, app_rows)
    write_csv(missing_path, missing_coords)

    by_map = Counter([r["job_map"] for r in production_rows])
    print(f"Source PDF: {pdf_path}")
    print(f"Rows extracted: {len(production_rows)}")
    print(f"Unique Job/Map IDs: {len(by_map)}")
    print("Top Job/Map IDs:", by_map.most_common(8))
    print(f"Coords map keys: {len(coords_map)}")
    print(f"Output (all rows): {all_path}")
    print(f"Output (app import ready): {app_path}
main function · python · L213-L238 (26 LOC)
scripts/wired_production_pdf_to_csv.py
def main() -> None:
    parser = argparse.ArgumentParser(
        description="Convert Wired production PDF into import-ready CSV for SpecCom."
    )
    parser.add_argument("--pdf", required=True, help="Path to Wired production PDF.")
    parser.add_argument(
        "--out",
        default=str(Path("project_uploads") / f"wired_production_{datetime.now().strftime('%Y%m%d_%H%M%S')}"),
        help="Output directory.",
    )
    parser.add_argument(
        "--coords-csv",
        default="",
        help="Optional CSV with coordinates keyed by external_ref or location_name/enclosure.",
    )
    args = parser.parse_args()

    pdf_path = Path(args.pdf)
    if not pdf_path.exists():
        raise SystemExit(f"PDF not found: {pdf_path}")
    out_dir = Path(args.out)
    coords_csv = Path(args.coords_csv) if args.coords_csv else None
    if coords_csv and not coords_csv.exists():
        raise SystemExit(f"coords CSV not found: {coords_csv}")

    run(pdf_path, out_dir, coords_csv)
ApiError class · javascript · L11-L21 (11 LOC)
services/apiService.js
export class ApiError extends Error {
  constructor(message, details = {}) {
    super(message);
    this.name = "ApiError";
    this.status = details.status || 0;
    this.body = details.body;
    this.method = details.method || "GET";
    this.url = details.url || "";
    this.headers = details.headers || {};
  }
}
constructor method · javascript · L12-L20 (9 LOC)
services/apiService.js
  constructor(message, details = {}) {
    super(message);
    this.name = "ApiError";
    this.status = details.status || 0;
    this.body = details.body;
    this.method = details.method || "GET";
    this.url = details.url || "";
    this.headers = details.headers || {};
  }
AuthenticationError class · javascript · L23-L28 (6 LOC)
services/apiService.js
export class AuthenticationError extends ApiError {
  constructor(message, details = {}) {
    super(message, details);
    this.name = "AuthenticationError";
  }
}
constructor method · javascript · L24-L27 (4 LOC)
services/apiService.js
  constructor(message, details = {}) {
    super(message, details);
    this.name = "AuthenticationError";
  }
ServerError class · javascript · L30-L35 (6 LOC)
services/apiService.js
export class ServerError extends ApiError {
  constructor(message, details = {}) {
    super(message, details);
    this.name = "ServerError";
  }
}
Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
constructor method · javascript · L31-L34 (4 LOC)
services/apiService.js
  constructor(message, details = {}) {
    super(message, details);
    this.name = "ServerError";
  }
normalizeApiBase function · javascript · L37-L40 (4 LOC)
services/apiService.js
function normalizeApiBase(apiBase) {
  const base = String(apiBase || DEFAULT_API_BASE).trim() || DEFAULT_API_BASE;
  return base.replace(/\/+$/, "");
}
buildUrl function · javascript · L42-L57 (16 LOC)
services/apiService.js
function buildUrl(apiBase, path, query = {}) {
  const base = normalizeApiBase(apiBase);
  const normalizedPath = String(path || "").startsWith("/") ? String(path) : `/${String(path || "")}`;
  const url = `${base}${normalizedPath}`;

  const params = new URLSearchParams();
  Object.entries(query || {}).forEach(([key, value]) => {
    if (value == null) return;
    const asString = String(value).trim();
    if (!asString.length) return;
    params.set(key, asString);
  });

  const queryString = params.toString();
  return queryString ? `${url}?${queryString}` : url;
}
parseResponseBody function · javascript · L59-L75 (17 LOC)
services/apiService.js
async function parseResponseBody(response) {
  const contentType = String(response.headers.get("content-type") || "").toLowerCase();
  if (contentType.includes("application/json")) {
    try {
      return await response.json();
    } catch {
      return null;
    }
  }

  try {
    const text = await response.text();
    return text ? { raw: text } : null;
  } catch {
    return null;
  }
}
pickErrorMessage function · javascript · L77-L83 (7 LOC)
services/apiService.js
function pickErrorMessage(status, body, fallback) {
  if (body && typeof body === "object") {
    if (typeof body.error === "string" && body.error.trim()) return body.error;
    if (typeof body.message === "string" && body.message.trim()) return body.message;
  }
  return fallback || `HTTP ${status}`;
}
toHeadersObject function · javascript · L85-L91 (7 LOC)
services/apiService.js
function toHeadersObject(headers) {
  const out = {};
  headers.forEach((value, key) => {
    out[key] = value;
  });
  return out;
}
createHttpError function · javascript · L93-L107 (15 LOC)
services/apiService.js
function createHttpError(response, body, requestInfo) {
  const status = response.status;
  const message = pickErrorMessage(status, body, `Request failed with status ${status}`);
  const details = {
    status,
    body,
    method: requestInfo.method,
    url: requestInfo.url,
    headers: toHeadersObject(response.headers),
  };

  if (status === 401) return new AuthenticationError(message, details);
  if (status >= 500) return new ServerError(message, details);
  return new ApiError(message, details);
}
shouldRetry function · javascript · L109-L118 (10 LOC)
services/apiService.js
function shouldRetry(error) {
  if (!error) return false;
  if (error.name === "AbortError") return false;
  if (error instanceof AuthenticationError) return false;
  if (error instanceof ServerError) return true;
  if (error instanceof ApiError) {
    return error.status === 408 || error.status === 429;
  }
  return true;
}
Repobility · code-quality intelligence platform · https://repobility.com
sleep function · javascript · L120-L129 (10 LOC)
services/apiService.js
function sleep(ms, signal) {
  if (signal?.aborted) return Promise.reject(new DOMException("Aborted", "AbortError"));
  return new Promise((resolve, reject) => {
    const timer = setTimeout(resolve, ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(new DOMException("Aborted", "AbortError"));
    }, { once: true });
  });
}
defaultFetchImpl function · javascript · L131-L133 (3 LOC)
services/apiService.js
function defaultFetchImpl(...args) {
  return fetch(...args);
}
createApiClient function · javascript · L135-L225 (91 LOC)
services/apiService.js
export function createApiClient({ authToken, apiBase = DEFAULT_API_BASE, fetchImpl = defaultFetchImpl } = {}) {
  let token = authToken || "";

  function getToken() {
    return typeof token === "function" ? token() : token;
  }

  function setAuthToken(nextToken) {
    token = nextToken || "";
  }

  async function request({ method = "GET", path, query, body, signal, retry = false, retryDelays = DEFAULT_RETRY_DELAYS_MS } = {}) {
    const upperMethod = String(method || "GET").toUpperCase();
    const url = buildUrl(apiBase, path, query);
    const headers = { Accept: "application/json" };

    const bearerToken = getToken();
    if (bearerToken) headers.Authorization = `Bearer ${bearerToken}`;

    let payload = body;
    if (body && !(body instanceof FormData)) {
      headers["Content-Type"] = "application/json";
      payload = JSON.stringify(body);
    }

    let attempt = 0;
    while (true) {
      try {
        const response = await fetchImpl(url, {
          method: upperMet
getToken function · javascript · L138-L140 (3 LOC)
services/apiService.js
  function getToken() {
    return typeof token === "function" ? token() : token;
  }
setAuthToken function · javascript · L142-L144 (3 LOC)
services/apiService.js
  function setAuthToken(nextToken) {
    token = nextToken || "";
  }
request function · javascript · L146-L180 (35 LOC)
services/apiService.js
  async function request({ method = "GET", path, query, body, signal, retry = false, retryDelays = DEFAULT_RETRY_DELAYS_MS } = {}) {
    const upperMethod = String(method || "GET").toUpperCase();
    const url = buildUrl(apiBase, path, query);
    const headers = { Accept: "application/json" };

    const bearerToken = getToken();
    if (bearerToken) headers.Authorization = `Bearer ${bearerToken}`;

    let payload = body;
    if (body && !(body instanceof FormData)) {
      headers["Content-Type"] = "application/json";
      payload = JSON.stringify(body);
    }

    let attempt = 0;
    while (true) {
      try {
        const response = await fetchImpl(url, {
          method: upperMethod,
          headers,
          body: upperMethod === "GET" ? undefined : payload,
          signal,
        });

        const responseBody = await parseResponseBody(response);
        if (!response.ok) throw createHttpError(response, responseBody, { method: upperMethod, url });
        return resp
getProjects function · javascript · L182-L199 (18 LOC)
services/apiService.js
  async function getProjects(
    { cursor = null, pageSize = 50, status = "", technicianId = "", siteId = "" } = {},
    { signal } = {}
  ) {
    return request({
      method: "GET",
      path: API_ENDPOINTS.GET_PROJECTS,
      query: {
        cursor,
        page_size: pageSize,
        status,
        technician_id: technicianId,
        site_id: siteId,
      },
      signal,
      retry: true,
    });
  }
uploadFile function · javascript · L201-L222 (22 LOC)
services/apiService.js
  async function uploadFile({ file, projectId, table = "sites", fields = {} } = {}, { signal } = {}) {
    if (!file) throw new ApiError("file is required", { status: 0 });
    const endpoint = table === "sites" ? API_ENDPOINTS.IMPORT_SITES : API_ENDPOINTS.UPLOAD_FILE;

    const formData = new FormData();
    formData.append("file", file);
    if (projectId) formData.append("project_id", String(projectId));
    if (table) formData.append("table", String(table));

    Object.entries(fields || {}).forEach(([key, value]) => {
      if (value == null) return;
      formData.append(key, String(value));
    });

    return request({
      method: "POST",
      path: endpoint,
      body: formData,
      signal,
      retry: false,
    });
  }
About: code-quality intelligence by Repobility · https://repobility.com
safeAuthLock function · javascript · L9-L11 (3 LOC)
supabaseClient.js
async function safeAuthLock(_name, _acquireTimeout, fn) {
  return await fn();
}
getProjectRefFromUrl function · javascript · L13-L24 (12 LOC)
supabaseClient.js
function getProjectRefFromUrl(url) {
  const raw = String(url || "").trim();
  if (!raw) return "";
  try {
    const parsed = new URL(raw);
    const host = String(parsed.hostname || "").trim().toLowerCase();
    const ref = host.split(".")[0] || "";
    return ref;
  } catch {
    return "";
  }
}
getAuthStorageKey function · javascript · L26-L30 (5 LOC)
supabaseClient.js
function getAuthStorageKey() {
  const ref = getProjectRefFromUrl(SUPABASE_URL);
  if (!ref) return "";
  return `sb-${ref}-auth-token`;
}
clearSupabaseAuthStorage function · javascript · L32-L49 (18 LOC)
supabaseClient.js
export function clearSupabaseAuthStorage() {
  if (typeof window === "undefined") return;
  const key = getAuthStorageKey();
  const clearFrom = (store) => {
    if (!store) return;
    try {
      if (key) store.removeItem(key);
      const toDelete = [];
      for (let i = 0; i < store.length; i += 1) {
        const k = store.key(i) || "";
        if (/^sb-.*-auth-token$/i.test(k)) toDelete.push(k);
      }
      toDelete.forEach((k) => store.removeItem(k));
    } catch {}
  };
  clearFrom(window.localStorage);
  clearFrom(window.sessionStorage);
}
isInvalidRefreshError function · javascript · L51-L55 (5 LOC)
supabaseClient.js
export function isInvalidRefreshError(error) {
  const msg = String(error?.message || error || "").toLowerCase();
  return msg.includes("invalid refresh token")
    || msg.includes("refresh token not found");
}
readWindowEnv function · javascript · L57-L60 (4 LOC)
supabaseClient.js
function readWindowEnv() {
  if (typeof window === "undefined") return null;
  return window.__ENV || null;
}
isLikelyMaskedSecret function · javascript · L62-L66 (5 LOC)
supabaseClient.js
function isLikelyMaskedSecret(value) {
  const text = String(value || "").trim();
  if (!text) return false;
  return /^\*+$/.test(text) || /\*{4,}/.test(text) || /redacted|masked/i.test(text);
}
refreshConfig function · javascript · L68-L74 (7 LOC)
supabaseClient.js
export function refreshConfig() {
  const env = readWindowEnv();
  SUPABASE_URL = (env?.SUPABASE_URL || "").trim();
  SUPABASE_ANON_KEY = (env?.SUPABASE_ANON_KEY || "").trim();
  APP_MODE = (env?.APP_MODE || "real").trim();
  return { SUPABASE_URL, SUPABASE_ANON_KEY, APP_MODE };
}
All rows above produced by Repobility · https://repobility.com
hasSupabaseConfig function · javascript · L76-L79 (4 LOC)
supabaseClient.js
export function hasSupabaseConfig() {
  refreshConfig();
  return !!SUPABASE_URL && !!SUPABASE_ANON_KEY && !isLikelyMaskedSecret(SUPABASE_ANON_KEY);
}
loadSupabaseCreateClient function · javascript · L81-L88 (8 LOC)
supabaseClient.js
async function loadSupabaseCreateClient() {
  if (typeof window === "undefined") return null;
  if (!window.__supabaseCreateClient) {
    const mod = await import("https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/+esm");
    window.__supabaseCreateClient = mod.createClient;
  }
  return window.__supabaseCreateClient || null;
}
makeClient function · javascript · L90-L120 (31 LOC)
supabaseClient.js
export async function makeClient() {
  refreshConfig();

  if (!SUPABASE_URL || !SUPABASE_ANON_KEY || isLikelyMaskedSecret(SUPABASE_ANON_KEY)) {
    return null;
  }

  if (_client) return _client;
  if (_clientPromise) return _clientPromise;
  _clientPromise = (async () => {
    try {
      const createClient = await loadSupabaseCreateClient();
      if (!createClient) return null;
      const client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
        auth: {
          lock: safeAuthLock,
        },
      });
      _client = client;
      if (typeof window !== "undefined") {
        window.supabase = client;
      }
      return client;
    } catch (error) {
      _clientPromise = null;
      _client = null;
      throw error;
    }
  })();
  return _clientPromise;
}
‹ prevpage 2 / 3next ›