~ knotless Search/
↑↓ move↵ open⇧↵ all results

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0
56 lines · 2.3 KB Raw History
export interface SiteConfig {
  origin?: string;
  plcUrl?: string;
  pdsUrl?: string;
}

const PROD_PLC = "https://plc.directory";
const PROD_PDS = "https://bsky.social";

function httpsOrigin(raw: string, name: string): string {
  const u = new URL(raw);
  if (u.protocol !== "https:" || u.origin !== raw.replace(/\/+$/, "")) throw new Error(`${name} must be an https origin, got ${raw}`);
  return u.origin;
}

export function siteConfigFromEnv(env: (name: string) => string | undefined): SiteConfig {
  return { origin: env("DKA_ORIGIN") || undefined, plcUrl: env("DKA_PLC_URL") || undefined, pdsUrl: env("DKA_PDS_URL") || undefined };
}

export async function applySiteConfig(dist: string, cfg: SiteConfig): Promise<void> {
  if (cfg.origin) {
    const origin = httpsOrigin(cfg.origin, "origin");
    const path = `${dist}/oauth-client-metadata.json`;
    const metadata = JSON.parse(await Deno.readTextFile(path)) as Record<string, unknown>;
    metadata.client_id = `${origin}/oauth-client-metadata.json`;
    metadata.redirect_uris = [origin];
    metadata.client_uri = origin;
    await Deno.writeTextFile(path, JSON.stringify(metadata, null, 2) + "\n");
  }
  const swaps: [string, string][] = [];
  if (cfg.plcUrl) swaps.push([PROD_PLC, httpsOrigin(cfg.plcUrl, "plc-url")]);
  if (cfg.pdsUrl) swaps.push([PROD_PDS, httpsOrigin(cfg.pdsUrl, "pds-url")]);
  if (swaps.length === 0) return;
  const path = `${dist}/dka-app.js`;
  let bundle = await Deno.readTextFile(path);
  for (const [from, to] of swaps) {
    if (!bundle.includes(from)) throw new Error(`${path} does not name ${from}`);
    bundle = bundle.replaceAll(from, to);
  }
  await Deno.writeTextFile(path, bundle);
}

if (import.meta.main) {
  const [dist, ...rest] = Deno.args;
  const cfg: SiteConfig = {};
  for (let i = 0; i + 1 < rest.length; i += 2) {
    if (rest[i] === "--origin") cfg.origin = rest[i + 1];
    else if (rest[i] === "--plc-url") cfg.plcUrl = rest[i + 1];
    else if (rest[i] === "--pds-url") cfg.pdsUrl = rest[i + 1];
  }
  if (!dist || rest.length % 2 !== 0 || rest.some((a, i) => i % 2 === 0 && !["--origin", "--plc-url", "--pds-url"].includes(a))) {
    console.error("usage: site-config.ts <dist> [--origin <https origin>] [--plc-url <https origin>] [--pds-url <https origin>]");
    Deno.exit(2);
  }
  await applySiteConfig(dist, cfg);
}