UNPKG

@happykit/flags

Version:

Feature Flags for Next.js

2 lines (1 loc) 1.5 kB
import{a as f,b as g,c as d,d as m,e as y}from"./chunk-HCCDXSZ4.mjs";var N={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,HEAD,POST,OPTIONS","Access-Control-Max-Age":"86400","Access-Control-Expose-Headers":"*"};function F({getDefinitions:h,corsHeaders:w=N,serverTiming:x=!1}){let e={...w,"content-type":"application/json"};return async function(n,T){if(n.url.endsWith("favicon.ico"))return new Response(null,{status:404,headers:e});let t=n.method==="POST"?await n.json().catch(()=>({})):{},a=t&&typeof t.visitorKey=="string"?t.visitorKey:null,s=a||null,R=f(t?t.user:null),E=s?g(s):null,A=d(t?t.traits:null),i=(()=>{let r=new URL(n.url).pathname.match(/^\/api\/flags\/([_a-z0-9]+)$/);return r&&r.length===2?r[1]:null})();if(typeof i!="string")return new Response(JSON.stringify({reason:"Missing envKey"}),{status:422,headers:e});let o=i.match(/^flags_pub_(?:(development|preview|production)_)?([a-z0-9]+)$/);if(!o||o.length<2)return new Response(JSON.stringify({reason:"Invalid envKey"}),{status:422,headers:e});let l=o[1]||"production",S=o[2],c,u=Date.now(),p=await h(S,i,l),v=Date.now();if(!p)return new Response(null,{status:500,statusText:"Internal Server Error",headers:e});c=p.flags;let D=y({flags:c,environment:l,user:R,visitor:E,traits:A}),K=x?{"server-timing":[v!==null&&u!==null?`definitions;dur=${v-u}`:null].filter(Boolean).join(", ")}:null;return new Response(JSON.stringify({flags:m(D),visitor:s?{key:s}:null}),{headers:{...e,...K}})}}export{F as createApiRoute};