module.exports=[18622,(e,t,a)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(e,t,a)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(e,t,a)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},24725,(e,t,a)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},50227,(e,t,a)=>{t.exports=e.x("node:path",()=>require("node:path"))},60526,(e,t,a)=>{t.exports=e.x("node:os",()=>require("node:os"))},66680,(e,t,a)=>{t.exports=e.x("node:crypto",()=>require("node:crypto"))},2157,(e,t,a)=>{t.exports=e.x("node:fs",()=>require("node:fs"))},86607,(e,t,a)=>{t.exports=e.x("better-sqlite3-cf218e5bd1d5f04c",()=>require("better-sqlite3-cf218e5bd1d5f04c"))},93695,(e,t,a)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},31770,e=>{"use strict";var t=e.i(2157),a=e.i(60526),s=e.i(50227),r=e.i(86607);let n=[{name:"001_init.sql",sql:`
-- notfair-cmo SQLite schema, migration 001.
-- Forward-only; do not edit after release. New changes go in a new numbered migration.

CREATE TABLE IF NOT EXISTS projects (
  id           TEXT PRIMARY KEY,
  slug         TEXT NOT NULL UNIQUE,
  display_name TEXT NOT NULL,
  created_at   TEXT NOT NULL,
  archived_at  TEXT
);

-- Task lifecycle:
-- proposed -> approved -> running -> (succeeded | failed | cancelled)
CREATE TABLE IF NOT EXISTS tasks (
  id               TEXT PRIMARY KEY,
  project_slug     TEXT NOT NULL REFERENCES projects(slug),
  agent_id         TEXT NOT NULL,
  brief            TEXT NOT NULL,
  success_criteria TEXT,
  deadline_iso     TEXT,
  status           TEXT NOT NULL CHECK (status IN ('proposed','approved','running','succeeded','failed','cancelled')),
  result_json      TEXT,
  error_message    TEXT,
  created_at       TEXT NOT NULL,
  updated_at       TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);

CREATE TABLE IF NOT EXISTS approvals (
  id                TEXT PRIMARY KEY,
  project_slug      TEXT NOT NULL REFERENCES projects(slug),
  agent_id          TEXT NOT NULL,
  action_summary    TEXT NOT NULL,
  action_type       TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
  cost_estimate_usd REAL NOT NULL DEFAULT 0,
  reasoning         TEXT,
  payload_json      TEXT NOT NULL,
  status            TEXT NOT NULL CHECK (status IN ('pending','approved','rejected','expired')),
  created_at        TEXT NOT NULL,
  resolved_at       TEXT
);
CREATE INDEX IF NOT EXISTS idx_approvals_pending ON approvals(project_slug, status) WHERE status = 'pending';

CREATE TABLE IF NOT EXISTS cost_events (
  id           TEXT PRIMARY KEY,
  project_slug TEXT NOT NULL REFERENCES projects(slug),
  agent_id     TEXT,
  source       TEXT NOT NULL CHECK (source IN ('llm','google_ads','gsc','other')),
  amount_usd   REAL NOT NULL,
  ref          TEXT,
  occurred_at  TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_cost_events_project_time ON cost_events(project_slug, occurred_at);

CREATE TABLE IF NOT EXISTS oauth_tokens (
  id                TEXT PRIMARY KEY,
  project_slug      TEXT NOT NULL REFERENCES projects(slug),
  provider          TEXT NOT NULL CHECK (provider IN ('google_ads','gsc')),
  account_label     TEXT NOT NULL,
  access_token_enc  TEXT NOT NULL,
  refresh_token_enc TEXT NOT NULL,
  expires_at        TEXT NOT NULL,
  scope             TEXT NOT NULL,
  created_at        TEXT NOT NULL,
  updated_at        TEXT NOT NULL,
  UNIQUE(project_slug, provider, account_label)
);

CREATE TABLE IF NOT EXISTS guardrails (
  project_slug TEXT PRIMARY KEY REFERENCES projects(slug),
  config_json  TEXT NOT NULL,
  updated_at   TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS agent_actions (
  id            TEXT PRIMARY KEY,
  project_slug  TEXT NOT NULL REFERENCES projects(slug),
  agent_id      TEXT NOT NULL,
  task_id       TEXT,
  action_type   TEXT NOT NULL,
  summary       TEXT NOT NULL,
  reasoning     TEXT,
  payload_json  TEXT,
  occurred_at   TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_agent_actions_project_time ON agent_actions(project_slug, occurred_at);

CREATE TABLE IF NOT EXISTS sequence_runs (
  id            TEXT PRIMARY KEY,
  project_slug  TEXT NOT NULL REFERENCES projects(slug),
  agent_id      TEXT NOT NULL,
  sequence_kind TEXT NOT NULL,
  cursor        TEXT NOT NULL,
  status        TEXT NOT NULL CHECK (status IN ('pending','running','succeeded','failed','cancelled')),
  payload_json  TEXT,
  last_tick_at  TEXT,
  next_tick_at  TEXT,
  created_at    TEXT NOT NULL,
  updated_at    TEXT NOT NULL
);
`},{name:"002_google_ads_account.sql",sql:`
-- Per-project Google Ads account selection. Bearers from notfair.co's MCP
-- can grant access to multiple customer accounts; onboarding asks the user
-- to pick one and persists it here so the audit + later automation always
-- target the right account.
ALTER TABLE projects ADD COLUMN google_ads_account_id TEXT;
`},{name:"003_tasks_orchestration.sql",sql:`
-- Tasks gain three columns to power the autonomous CMO orchestrator:
--
--   title              — short label distinct from the long brief, shown
--                        on /tasks cards + task detail header.
--   thread_id          — the OpenClaw chat session id this task's
--                        per-task thread runs under. The assignee picks
--                        up the task in this thread (TASK_BRIEF.md
--                        kickoff). Null until the user (or the CMO
--                        autonomously) opens the detail page; populated
--                        once and immutable.
--   assigner_agent_id  — who created this task. CMO assigns to specialists;
--                        in v1.1 specialists can create sub-tasks and
--                        this lets us walk the chain back to the planner.
ALTER TABLE tasks ADD COLUMN title TEXT;
ALTER TABLE tasks ADD COLUMN thread_id TEXT;
ALTER TABLE tasks ADD COLUMN assigner_agent_id TEXT;
`},{name:"004_task_display_id.sql",sql:`
-- Human-readable per-project task IDs (e.g. demo7-3) shown in the UI and
-- used in URLs. PK stays as the UUID for FK integrity / agent protocol;
-- display_id is the surface that humans + URLs see.
--
-- Backfill assigns sequential numbers in created_at order per project,
-- so existing demos get pretty IDs without manual cleanup.
ALTER TABLE tasks ADD COLUMN display_id TEXT;

WITH numbered AS (
  SELECT
    id,
    project_slug || '-' || ROW_NUMBER() OVER (
      PARTITION BY project_slug ORDER BY created_at
    ) AS dn
  FROM tasks
)
UPDATE tasks
SET display_id = numbered.dn
FROM numbered
WHERE tasks.id = numbered.id;

CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
`},{name:"005_drop_guardrails.sql",sql:`
-- Remove the guardrails autonomy feature. The Settings page no longer
-- exposes per-project autonomy knobs and no runtime code reads/writes
-- this table, so drop it to keep the schema honest.
DROP TABLE IF EXISTS guardrails;
`},{name:"006_approvals_v2.sql",sql:`
-- Approval system v2: blocked task state, comments, auto-policies, decision tracking.
--
-- Changes:
--   1. tasks.status CHECK gains 'blocked' (task is waiting on an approval).
--      SQLite can't ALTER CHECK in place, so recreate the table.
--   2. approvals gains task_id, decision_note, decided_by_kind, decided_by_id;
--      status CHECK gains 'revision_requested' (paperclip-style push-back loop).
--   3. New approval_comments table — discussion thread per approval.
--   4. New approval_policies table — "always allow" / "always reject" rules
--      consulted before pending rows are created.

CREATE TABLE tasks_new (
  id                TEXT PRIMARY KEY,
  project_slug      TEXT NOT NULL REFERENCES projects(slug),
  agent_id          TEXT NOT NULL,
  brief             TEXT NOT NULL,
  success_criteria  TEXT,
  deadline_iso      TEXT,
  status            TEXT NOT NULL CHECK (status IN ('proposed','approved','running','blocked','succeeded','failed','cancelled')),
  result_json       TEXT,
  error_message     TEXT,
  created_at        TEXT NOT NULL,
  updated_at        TEXT NOT NULL,
  title             TEXT,
  thread_id         TEXT,
  assigner_agent_id TEXT,
  display_id        TEXT
);
INSERT INTO tasks_new (id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id)
SELECT id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id
FROM tasks;
DROP TABLE tasks;
ALTER TABLE tasks_new RENAME TO tasks;
CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);
CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);

CREATE TABLE approvals_new (
  id                TEXT PRIMARY KEY,
  project_slug      TEXT NOT NULL REFERENCES projects(slug),
  agent_id          TEXT NOT NULL,
  task_id           TEXT,
  action_summary    TEXT NOT NULL,
  action_type       TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
  cost_estimate_usd REAL NOT NULL DEFAULT 0,
  reasoning         TEXT,
  payload_json      TEXT NOT NULL,
  status            TEXT NOT NULL CHECK (status IN ('pending','revision_requested','approved','rejected','expired')),
  decision_note     TEXT,
  decided_by_kind   TEXT CHECK (decided_by_kind IN ('user','agent','policy')),
  decided_by_id     TEXT,
  created_at        TEXT NOT NULL,
  resolved_at       TEXT
);
INSERT INTO approvals_new (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at)
SELECT id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at
FROM approvals;
DROP TABLE approvals;
ALTER TABLE approvals_new RENAME TO approvals;
CREATE INDEX IF NOT EXISTS idx_approvals_actionable ON approvals(project_slug, status) WHERE status IN ('pending','revision_requested');
CREATE INDEX IF NOT EXISTS idx_approvals_task ON approvals(task_id) WHERE task_id IS NOT NULL;

CREATE TABLE IF NOT EXISTS approval_comments (
  id          TEXT PRIMARY KEY,
  approval_id TEXT NOT NULL REFERENCES approvals(id) ON DELETE CASCADE,
  author_kind TEXT NOT NULL CHECK (author_kind IN ('user','agent','system')),
  author_id   TEXT,
  body        TEXT NOT NULL,
  created_at  TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_approval_comments_approval ON approval_comments(approval_id, created_at);

CREATE TABLE IF NOT EXISTS approval_policies (
  id              TEXT PRIMARY KEY,
  project_slug    TEXT NOT NULL REFERENCES projects(slug),
  action_type     TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
  agent_id        TEXT,
  max_cost_usd    REAL,
  auto_decision   TEXT NOT NULL CHECK (auto_decision IN ('approve','reject')),
  note            TEXT,
  created_at      TEXT NOT NULL,
  created_by_kind TEXT NOT NULL CHECK (created_by_kind IN ('user','agent')),
  created_by_id   TEXT
);
CREATE INDEX IF NOT EXISTS idx_approval_policies_project ON approval_policies(project_slug, action_type);
`},{name:"007_unify_task_status_vocab.sql",sql:`
-- Unify TaskStatus on the agent-facing verb form: running→working,
-- succeeded→done. SQLite can't ALTER CHECK in place — recreate the table
-- and transform existing rows via CASE. See 007_unify_task_status_vocab.sql
-- for the rationale.

CREATE TABLE tasks_new (
  id                TEXT PRIMARY KEY,
  project_slug      TEXT NOT NULL REFERENCES projects(slug),
  agent_id          TEXT NOT NULL,
  brief             TEXT NOT NULL,
  success_criteria  TEXT,
  deadline_iso      TEXT,
  status            TEXT NOT NULL CHECK (status IN ('proposed','approved','working','blocked','done','failed','cancelled')),
  result_json       TEXT,
  error_message     TEXT,
  created_at        TEXT NOT NULL,
  updated_at        TEXT NOT NULL,
  title             TEXT,
  thread_id         TEXT,
  assigner_agent_id TEXT,
  display_id        TEXT
);

INSERT INTO tasks_new (
  id, project_slug, agent_id, brief, success_criteria, deadline_iso,
  status, result_json, error_message, created_at, updated_at, title,
  thread_id, assigner_agent_id, display_id
)
SELECT
  id, project_slug, agent_id, brief, success_criteria, deadline_iso,
  CASE status
    WHEN 'running' THEN 'working'
    WHEN 'succeeded' THEN 'done'
    ELSE status
  END AS status,
  result_json, error_message, created_at, updated_at, title,
  thread_id, assigner_agent_id, display_id
FROM tasks;

DROP TABLE tasks;
ALTER TABLE tasks_new RENAME TO tasks;
CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);
CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
`},{name:"008_project_brief_and_task_blocks.sql",sql:`
-- Migration 008: project context inputs + task-blocks-task dependencies.
--
-- Two unrelated-looking changes ship together because they're the schema
-- side of the same product change: the new CMO onboarding task that learns
-- about the project (writes PROJECT.md), and the audit task gated on it.
--
-- 1. projects gains two optional inputs collected at onboarding time:
--    \`website_url\` and \`codebase_path\`. The CMO uses whichever are present
--    to research the project during its first task and produce PROJECT.md.
--
-- 2. tasks gains \`blocked_by_task_id\` — a generic "this task can't start
--    until that one finishes" pointer. When the blocker transitions to
--    \`done\`, the orchestrator clears the pointer, flips the dependent
--    blocked→proposed, and kicks it off. Co-exists with approval-blocking
--    (approval-blocked tasks have a null blocked_by_task_id and resolve
--    via the existing wakeTaskOnApprovalResolution path).
ALTER TABLE projects ADD COLUMN website_url TEXT;
ALTER TABLE projects ADD COLUMN codebase_path TEXT;

ALTER TABLE tasks ADD COLUMN blocked_by_task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_tasks_blocked_by ON tasks(blocked_by_task_id) WHERE blocked_by_task_id IS NOT NULL;
`},{name:"009_questions.sql",sql:`
-- Migration 009: questions table for ask_user_question.
--
-- Agents call the ask_user_question MCP tool to surface a structured
-- question to the user (with optional multiple-choice options). Previously
-- this only logged an action; now it persists a row, blocks the gating
-- task, and the UI renders a QuestionCard alongside ApprovalCard. The
-- user picks an option or types free-text; the wake-up streams the
-- resolution back to the agent.
--
-- Modeled like approvals: one row per question, pending → answered |
-- cancelled (terminal). No comments table — single-shot Q&A; if the
-- agent needs more, it asks again.

CREATE TABLE IF NOT EXISTS questions (
  id                  TEXT PRIMARY KEY,
  project_slug        TEXT NOT NULL REFERENCES projects(slug),
  agent_id            TEXT NOT NULL,
  task_id             TEXT REFERENCES tasks(id) ON DELETE SET NULL,
  prompt              TEXT NOT NULL,
  options_json        TEXT NOT NULL DEFAULT '[]',
  status              TEXT NOT NULL CHECK (status IN ('pending','answered','cancelled')),
  answer_option_index INTEGER,
  answer_text         TEXT,
  resolved_by_kind    TEXT CHECK (resolved_by_kind IN ('user','system')),
  created_at          TEXT NOT NULL,
  resolved_at         TEXT
);
CREATE INDEX IF NOT EXISTS idx_questions_pending ON questions(project_slug, status) WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS idx_questions_task ON questions(task_id) WHERE task_id IS NOT NULL;
`}],o=process.env.NOTFAIR_CMO_DATA_DIR??(0,s.join)((0,a.homedir)(),".notfair-cmo"),i=(0,s.join)(o,"db.sqlite"),d=null;e.s(["getDb",0,function(){if(d)return d;(0,t.existsSync)(o)||(0,t.mkdirSync)(o,{recursive:!0,mode:448});let e=new r.default(i);return e.pragma("journal_mode = WAL"),e.pragma("foreign_keys = ON"),e.pragma("busy_timeout = 5000"),function(e){e.exec(`
    CREATE TABLE IF NOT EXISTS _migrations (
      name       TEXT PRIMARY KEY,
      applied_at TEXT NOT NULL
    );
  `);let t=new Set(e.prepare("SELECT name FROM _migrations").all().map(e=>e.name));for(let a of n)t.has(a.name)||e.transaction(()=>{e.exec(a.sql),e.prepare("INSERT INTO _migrations (name, applied_at) VALUES (?, ?)").run(a.name,new Date().toISOString())})()}(e),d=e,e}],31770)},8404,e=>{"use strict";var t=e.i(34953),a=e.i(49201),s=e.i(69102),r=e.i(19309),n=e.i(89554),o=e.i(73525),i=e.i(27176),d=e.i(99736),c=e.i(97998),l=e.i(14255),T=e.i(69267),p=e.i(80309),E=e.i(31611),u=e.i(88950),_=e.i(31065),N=e.i(93695);e.i(971);var g=e.i(67902),h=e.i(73943),L=e.i(66680),R=e.i(31770);let O="notfair-cmo",k="master-key",X=null,m=!1;async function I(){try{let t=await e.A(74016);return t.default??t}catch{return null}}async function C(){if(X)return X;if(m)throw Error("Master key unavailable (keytar not loadable)");m=!0;let e=await I();if(!e)throw Error("OS keychain (keytar) not available on this platform. OAuth credentials cannot be stored securely.");let t=await e.getPassword(O,k);if(!t){let a=(0,L.randomBytes)(32).toString("base64");await e.setPassword(O,k,a),t=a}return X=Buffer.from(t,"base64")}async function A(e){let t=await C(),a=(0,L.randomBytes)(12),s=(0,L.createCipheriv)("aes-256-gcm",t,a),r=Buffer.concat([s.update(e,"utf8"),s.final()]),n=s.getAuthTag();return Buffer.concat([a,r,n]).toString("base64")}async function S(e){var t,a,s;let r,n=(0,R.getDb)(),o=new Date().toISOString(),i=(0,L.randomUUID)(),d=await A(e.access_token),c=await A(e.refresh_token);return n.prepare(`INSERT INTO oauth_tokens
       (id, project_slug, provider, account_label, access_token_enc, refresh_token_enc, expires_at, scope, created_at, updated_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
     ON CONFLICT(project_slug, provider, account_label) DO UPDATE SET
       access_token_enc = excluded.access_token_enc,
       refresh_token_enc = excluded.refresh_token_enc,
       expires_at = excluded.expires_at,
       scope = excluded.scope,
       updated_at = excluded.updated_at`).run(i,e.project_slug,e.provider,e.account_label,d,c,e.expires_at,e.scope,o,o),t=e.project_slug,a=e.provider,s=e.account_label,r=(0,R.getDb)(),s?r.prepare("SELECT * FROM oauth_tokens WHERE project_slug = ? AND provider = ? AND account_label = ?").get(t,a,s)??null:r.prepare("SELECT * FROM oauth_tokens WHERE project_slug = ? AND provider = ? LIMIT 1").get(t,a)??null}async function f(e,{params:t}){let a,{provider:s}=await t,r=new URL(e.url),n=r.searchParams.get("code"),o=r.searchParams.get("state"),i=r.searchParams.get("error");if(i)return b(`<h1>OAuth denied</h1><p>The provider returned: <code>${y(i)}</code></p><p><a href="/">Back to app</a></p>`,400);if(!n||!o)return b("<h1>OAuth error</h1><p>Missing code or state.</p>",400);try{a=JSON.parse(Buffer.from(o,"base64url").toString("utf8")).project}catch{return b("<h1>OAuth error</h1><p>Invalid state token.</p>",400)}let d=v[s];if(!d||!d.clientId||!d.clientSecret)return b(`<h1>OAuth not configured</h1><p>Set ${d?.envClientId??"(client id env var)"} + secret in your environment.</p>`,503);let c=r.origin,l=await fetch(d.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:n,client_id:d.clientId,client_secret:d.clientSecret,redirect_uri:`${c}/api/oauth/${s}/callback`,grant_type:"authorization_code"})});if(!l.ok){let e=await l.text();return b(`<h1>Token exchange failed</h1><pre>${y(e)}</pre>`,502)}let T=await l.json();if(!T.refresh_token)return b(`<h1>No refresh token</h1><p>Re-authorize and ensure the consent screen prompts for offline access.</p><p><a href="/${encodeURIComponent(a)}/connections">Back</a></p>`,400);try{await S({project_slug:a,provider:s,account_label:"default",access_token:T.access_token,refresh_token:T.refresh_token,expires_at:new Date(Date.now()+1e3*T.expires_in).toISOString(),scope:T.scope??d.scopes.join(" ")})}catch(e){return b(`<h1>Could not store token</h1><pre>${y(e instanceof Error?e.message:String(e))}</pre><p>This usually means OS keychain is unavailable.</p>`,500)}return h.NextResponse.redirect(`${c}/${encodeURIComponent(a)}/connections?connected=${s}`)}let v={google_ads:{clientId:process.env.GOOGLE_ADS_CLIENT_ID,clientSecret:process.env.GOOGLE_ADS_CLIENT_SECRET,envClientId:"GOOGLE_ADS_CLIENT_ID",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:["https://www.googleapis.com/auth/adwords"]},gsc:{clientId:process.env.GSC_CLIENT_ID,clientSecret:process.env.GSC_CLIENT_SECRET,envClientId:"GSC_CLIENT_ID",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:["https://www.googleapis.com/auth/webmasters.readonly"]}};function b(e,t=200){return new Response(`<!doctype html><meta charset="utf-8"><style>body{font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#18181b}h1{font-size:1.2rem}a{color:#2563eb}pre{background:#f4f4f5;padding:.75rem;border-radius:.5rem;overflow:auto}</style>${e}`,{status:t,headers:{"Content-Type":"text/html; charset=utf-8"}})}function y(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}e.s(["GET",0,f,"runtime",0,"nodejs"],94583);var U=e.i(94583);let w=new t.AppRouteRouteModule({definition:{kind:a.RouteKind.APP_ROUTE,page:"/api/oauth/[provider]/callback/route",pathname:"/api/oauth/[provider]/callback",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/oauth/[provider]/callback/route.ts",nextConfigOutput:"standalone",userland:U,...{}}),{workAsyncStorage:x,workUnitAsyncStorage:j,serverHooks:D}=w;async function F(e,t,s){s.requestMeta&&(0,r.setRequestMeta)(e,s.requestMeta),w.isDev&&(0,r.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let h="/api/oauth/[provider]/callback/route";h=h.replace(/\/index$/,"")||"/";let L=await w.prepare(e,t,{srcPage:h,multiZoneDraftMode:!1});if(!L)return t.statusCode=400,t.end("Bad Request"),null==s.waitUntil||s.waitUntil.call(s,Promise.resolve()),null;let{buildId:R,deploymentId:O,params:k,nextConfig:X,parsedUrl:m,isDraftMode:I,prerenderManifest:C,routerServerContext:A,isOnDemandRevalidate:S,revalidateOnlyGenerated:f,resolvedPathname:v,clientReferenceManifest:b,serverActionsManifest:y}=L,U=(0,i.normalizeAppPath)(h),x=!!(C.dynamicRoutes[U]||C.routes[v]),j=async()=>((null==A?void 0:A.render404)?await A.render404(e,t,m,!1):t.end("This page could not be found"),null);if(x&&!I){let e=!!C.routes[v],t=C.dynamicRoutes[U];if(t&&!1===t.fallback&&!e){if(X.adapterPath)return await j();throw new N.NoFallbackError}}let D=null;!x||w.isDev||I||(D="/index"===(D=v)?"/":D);let F=!0===w.isDev||!x,q=x&&!F;y&&b&&(0,o.setManifestsSingleton)({page:h,clientReferenceManifest:b,serverActionsManifest:y});let M=e.method||"GET",P=(0,n.getTracer)(),H=P.getActiveScopeSpan(),B=!!(null==A?void 0:A.isWrappedByNextServer),K=!!(0,r.getRequestMeta)(e,"minimalMode"),Y=(0,r.getRequestMeta)(e,"incrementalCache")||await w.getIncrementalCache(e,X,C,K);null==Y||Y.resetRequestCache(),globalThis.__incrementalCache=Y;let $={params:k,previewProps:C.preview,renderOpts:{experimental:{authInterrupts:!!X.experimental.authInterrupts},cacheComponents:!!X.cacheComponents,supportsDynamicResponse:F,incrementalCache:Y,cacheLifeProfiles:X.cacheLife,waitUntil:s.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,a,s,r)=>w.onRequestError(e,t,s,r,A)},sharedContext:{buildId:R,deploymentId:O}},W=new d.NodeNextRequest(e),G=new d.NodeNextResponse(t),Q=c.NextRequestAdapter.fromNodeNextRequest(W,(0,c.signalFromNodeResponse)(t));try{let r,o=async e=>w.handle(Q,$).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let a=P.getRootSpanAttributes();if(!a)return;if(a.get("next.span_type")!==l.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${a.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let s=a.get("next.route");if(s){let t=`${M} ${s}`;e.setAttributes({"next.route":s,"http.route":s,"next.span_name":t}),e.updateName(t),r&&r!==e&&(r.setAttribute("http.route",s),r.updateName(t))}else e.updateName(`${M} ${h}`)}),i=async r=>{var n,i;let d=async({previousCacheEntry:a})=>{try{if(!K&&S&&f&&!a)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=await o(r);e.fetchMetrics=$.renderOpts.fetchMetrics;let i=$.renderOpts.pendingWaitUntil;i&&s.waitUntil&&(s.waitUntil(i),i=void 0);let d=$.renderOpts.collectedTags;if(!x)return await (0,p.sendResponse)(W,G,n,$.renderOpts.pendingWaitUntil),null;{let e=await n.blob(),t=(0,E.toNodeOutgoingHttpHeaders)(n.headers);d&&(t[_.NEXT_CACHE_TAGS_HEADER]=d),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let a=void 0!==$.renderOpts.collectedRevalidate&&!($.renderOpts.collectedRevalidate>=_.INFINITE_CACHE)&&$.renderOpts.collectedRevalidate,s=void 0===$.renderOpts.collectedExpire||$.renderOpts.collectedExpire>=_.INFINITE_CACHE?void 0:$.renderOpts.collectedExpire;return{value:{kind:g.CachedRouteKind.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:a,expire:s}}}}catch(t){throw(null==a?void 0:a.isStale)&&await w.onRequestError(e,t,{routerKind:"App Router",routePath:h,routeType:"route",revalidateReason:(0,T.getRevalidateReason)({isStaticGeneration:q,isOnDemandRevalidate:S})},!1,A),t}},c=await w.handleResponse({req:e,nextConfig:X,cacheKey:D,routeKind:a.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:C,isRoutePPREnabled:!1,isOnDemandRevalidate:S,revalidateOnlyGenerated:f,responseGenerator:d,waitUntil:s.waitUntil,isMinimalMode:K});if(!x)return null;if((null==c||null==(n=c.value)?void 0:n.kind)!==g.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==c||null==(i=c.value)?void 0:i.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});K||t.setHeader("x-nextjs-cache",S?"REVALIDATED":c.isMiss?"MISS":c.isStale?"STALE":"HIT"),I&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let l=(0,E.fromNodeOutgoingHttpHeaders)(c.value.headers);return K&&x||l.delete(_.NEXT_CACHE_TAGS_HEADER),!c.cacheControl||t.getHeader("Cache-Control")||l.get("Cache-Control")||l.set("Cache-Control",(0,u.getCacheControlHeader)(c.cacheControl)),await (0,p.sendResponse)(W,G,new Response(c.value.body,{headers:l,status:c.value.status||200})),null};B&&H?await i(H):(r=P.getActiveScopeSpan(),await P.withPropagatedContext(e.headers,()=>P.trace(l.BaseServerSpan.handleRequest,{spanName:`${M} ${h}`,kind:n.SpanKind.SERVER,attributes:{"http.method":M,"http.target":e.url}},i),void 0,!B))}catch(t){if(t instanceof N.NoFallbackError||await w.onRequestError(e,t,{routerKind:"App Router",routePath:U,routeType:"route",revalidateReason:(0,T.getRevalidateReason)({isStaticGeneration:q,isOnDemandRevalidate:S})},!1,A),x)throw t;return await (0,p.sendResponse)(W,G,new Response(null,{status:500})),null}}e.s(["handler",0,F,"patchFetch",0,function(){return(0,s.patchFetch)({workAsyncStorage:x,workUnitAsyncStorage:j})},"routeModule",0,w,"serverHooks",0,D,"workAsyncStorage",0,x,"workUnitAsyncStorage",0,j],8404)},74016,e=>{e.v(t=>Promise.all(["server/chunks/[externals]_keytar_106hs-p._.js"].map(t=>e.l(t))).then(()=>t(58433)))}];

//# sourceMappingURL=%5Broot-of-the-server%5D__0ryn0rj._.js.map