@lpdjs/firestore-repo-service 2.6.37 → 2.6.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {z as z$1}from'zod';import {AsyncLocalStorage}from'async_hooks';import {readdirSync,statSync,mkdirSync,writeFileSync}from'fs';import {join,relative,sep,dirname}from'path';function ge(t){return t}var R=class extends Error{constructor(n,o){super("Request validation failed");this.zodError=n;this.source=o;this.statusCode=400;this.name="ValidationError";}};var k=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},O=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Q(t){return t.issues.map(e=>({path:e.path.join("."),code:e.code,message:e.message}))}function P(t,e){return e instanceof R?t.json({success:false,error:"Validation failed",issues:Q(e.zodError)},400):e instanceof k?t.json({success:false,error:"Bad Request",message:e.message},400):e instanceof O?t.json({success:false,error:"Output validation failed",issues:Q(e.zodError)},500):null}extendZodWithOpenApi(z$1);var ee="Successful response",te="Error response";function xe(t){return t==="get"?"query":"json"}function Se(t,e){let n=e?.output;return n?typeof n=="function"?n(t):n:t}function Te(t){if(typeof t.safeParse=="function")return {description:te,schema:t};let e=t;return {description:e.description??te,schema:e.schema}}function F(t,e,n,o){let s=new OpenAPIRegistry;if(n.securitySchemes)for(let[i,c]of Object.entries(n.securitySchemes))s.registerComponent("securitySchemes",i,c);for(let i of t){let c=i.method,u=i.source??xe(c),p=Re(e,i.path??"/"),l=i.status??200,m=we(c,u,i.input),v=ne(u,i.input,"query"),x=ne(u,i.input,"param"),f=Ee(c,p),g=Se(i.output,o),S={[l]:g?{description:ee,content:{"application/json":{schema:g}}}:{description:ee}};if(o?.errors)for(let[E,b]of Object.entries(o.errors)){let{description:d,schema:y}=Te(b);S[E]=y?{description:d,content:{"application/json":{schema:y}}}:{description:d};}s.registerPath({method:c,path:Ae(p),operationId:f,summary:i.summary,description:i.description,tags:i.tags,deprecated:i.deprecated,security:i.security,request:{...v?{query:v}:{},...x?{params:x}:{},...m?{body:m}:{}},responses:S});}return new OpenApiGeneratorV31(s.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function we(t,e,n){return !n||t==="get"?null:e==="json"?{content:{"application/json":{schema:n}}}:e==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function ne(t,e,n){if(e&&(n==="query"&&t==="query"||n==="param"&&t==="param"))return e}function Ae(t){return t.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Re(t,e){let n=t.endsWith("/")?t.slice(0,-1):t,o=e.startsWith("/")?e:`/${e}`,s=`${n}${o}`;return s===""?"/":s}function Ee(t,e){let n=e.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${t}_${n||"root"}`}function L(t,e){let n=t.replace(/"/g,"&quot;");return `<!doctype html>
1
+ import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {z}from'zod';import {AsyncLocalStorage}from'async_hooks';import {readdirSync,statSync,mkdirSync,writeFileSync}from'fs';import {join,relative,sep,dirname}from'path';function ge(t){return t}var E=class extends Error{constructor(n,o){super("Request validation failed");this.zodError=n;this.source=o;this.statusCode=400;this.name="ValidationError";}};var b=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},k=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Q(t){return t.issues.map(e=>({path:e.path.join("."),code:e.code,message:e.message}))}function C(t,e){return e instanceof E?t.json({success:false,error:"Validation failed",issues:Q(e.zodError)},400):e instanceof b?t.json({success:false,error:"Bad Request",message:e.message},400):e instanceof k?t.json({success:false,error:"Output validation failed",issues:Q(e.zodError)},500):null}extendZodWithOpenApi(z);var ee="Successful response",te="Error response";function xe(t){return t==="get"?"query":"json"}function Se(t,e){let n=e?.output;return n?typeof n=="function"?n(t):n:t}function Te(t){if(typeof t.safeParse=="function")return {description:te,schema:t};let e=t;return {description:e.description??te,schema:e.schema}}function j(t,e,n,o){let s=new OpenAPIRegistry;if(n.securitySchemes)for(let[i,c]of Object.entries(n.securitySchemes))s.registerComponent("securitySchemes",i,c);for(let i of t){let c=i.method,u=i.source??xe(c),p=Re(e,i.path??"/"),l=i.status??200,v=we(c,u,i.input),x=ne(u,i.input,"query"),S=ne(u,i.input,"param"),f=Ee(c,p),g=Se(i.output,o),A={[l]:g?{description:ee,content:{"application/json":{schema:g}}}:{description:ee}};if(o?.errors)for(let[y,X]of Object.entries(o.errors)){let{description:d,schema:h}=Te(X);A[y]=h?{description:d,content:{"application/json":{schema:h}}}:{description:d};}s.registerPath({method:c,path:Ae(p),operationId:f,summary:i.summary,description:i.description,tags:i.tags,deprecated:i.deprecated,security:i.security,request:{...x?{query:x}:{},...S?{params:S}:{},...v?{body:v}:{}},responses:A});}return new OpenApiGeneratorV31(s.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function we(t,e,n){return !n||t==="get"?null:e==="json"?{content:{"application/json":{schema:n}}}:e==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function ne(t,e,n){if(e&&(n==="query"&&t==="query"||n==="param"&&t==="param"))return e}function Ae(t){return t.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Re(t,e){let n=t.endsWith("/")?t.slice(0,-1):t,o=e.startsWith("/")?e:`/${e}`,s=`${n}${o}`;return s===""?"/":s}function Ee(t,e){let n=e.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${t}_${n||"root"}`}function F(t,e){let n=t.replace(/"/g,"&quot;");return `<!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="utf-8" />
@@ -9,12 +9,12 @@ import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';impor
9
9
  <script id="api-reference" data-url="${n}"></script>
10
10
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
11
11
  </body>
12
- </html>`}function be(t){return t?/^https?:\/\//.test(t)?t:`http://${t}`:""}function _(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function q(t){return JSON.stringify(t).slice(1,-1)}function re(t){let e=t.providers.includes("password"),n=t.providers.includes("google"),o=t.error?_(t.error):"";return `<!doctype html>
12
+ </html>`}function be(t){return t?/^https?:\/\//.test(t)?t:`http://${t}`:""}function L(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function _(t){return JSON.stringify(t).slice(1,-1)}function re(t){let e=t.providers.includes("password"),n=t.providers.includes("google"),o=t.error?L(t.error):"";return `<!doctype html>
13
13
  <html lang="en">
14
14
  <head>
15
15
  <meta charset="utf-8" />
16
16
  <meta name="viewport" content="width=device-width,initial-scale=1" />
17
- <title>${_(t.title)}</title>
17
+ <title>${L(t.title)}</title>
18
18
  <style>
19
19
  :root { color-scheme: light dark; }
20
20
  * { box-sizing: border-box; }
@@ -110,7 +110,7 @@ import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';impor
110
110
  </head>
111
111
  <body>
112
112
  <main class="card">
113
- <h1>${_(t.title)}</h1>
113
+ <h1>${L(t.title)}</h1>
114
114
  <p class="sub">Sign in to continue.</p>
115
115
  <div id="err" class="err">${o}</div>
116
116
  <div id="ok" class="ok"></div>
@@ -149,15 +149,15 @@ import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';impor
149
149
  } from "https://www.gstatic.com/firebasejs/10.13.2/firebase-auth.js";
150
150
 
151
151
  const app = initializeApp({
152
- apiKey: "${q(t.apiKey)}",
153
- authDomain: "${q(t.authDomain)}",
152
+ apiKey: "${_(t.apiKey)}",
153
+ authDomain: "${_(t.authDomain)}",
154
154
  });
155
155
  const auth = getAuth(app);
156
156
  ${t.authEmulatorHost?`connectAuthEmulator(auth, ${JSON.stringify(be(t.authEmulatorHost))}, { disableWarnings: true });`:""}
157
157
  // Don't persist client-side \u2014 the server-side session cookie is the source of truth.
158
158
  await setPersistence(auth, browserSessionPersistence).catch(() => {});
159
159
 
160
- const SESSION_PATH = "${q(t.sessionPath)}";
160
+ const SESSION_PATH = "${_(t.sessionPath)}";
161
161
  const NEXT = ${JSON.stringify(t.next)};
162
162
 
163
163
  // Defense-in-depth against open redirect (issue #07): only ever navigate
@@ -239,7 +239,7 @@ import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';impor
239
239
  }
240
240
  </script>
241
241
  </body>
242
- </html>`}function $(t){let e={};if(!t)return e;for(let n of t.split(";")){let o=n.indexOf("=");if(o===-1)continue;let s=n.slice(0,o).trim();if(!s)continue;let r=n.slice(o+1).trim();r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1));try{e[s]=decodeURIComponent(r);}catch{e[s]=r;}}return e}function ke(t){let{getAuth:e,allow:n,checkRevoked:o=false,contextKey:s="docsUser"}=t;return async(r,a)=>{let c=(r.req.header("authorization")??r.req.header("Authorization"))?.match(/^Bearer\s+(.+)$/i);if(!c)return r.json({error:"Unauthorized"},401,{"WWW-Authenticate":"Bearer"});let u;try{u=await e().verifyIdToken(c[1],o);}catch{return r.json({error:"Unauthorized"},401,{"WWW-Authenticate":"Bearer"})}if(n){let p=false;try{p=await n(u);}catch{p=false;}if(!p)return r.json({error:"Forbidden"},403)}return r.set(s,u),a()}}function Oe(t){let{username:e,password:n,realm:o="Docs"}=t,s=`Basic ${btoa(`${e}:${n}`)}`;return async(r,a)=>{let i=r.req.header("authorization")??r.req.header("Authorization")??"";return Ce(i,s)?a():r.text("Unauthorized",401,{"WWW-Authenticate":`Basic realm="${o}"`})}}function Ce(t,e){if(t.length!==e.length)return false;let n=0;for(let o=0;o<t.length;o++)n|=t.charCodeAt(o)^e.charCodeAt(o);return n===0}function U(t){return typeof t=="object"&&t!==null&&t.__docsAuthExtension===true}var B="__login",oe="__session",Pe="__logout";function Ie(t){let e=t.split("?")[0].split("/").filter(Boolean);return e[e.length-1]??""}function se(t,e,n){let o=[`${t}=${e}`,"Path=/",`Max-Age=${n.maxAgeSeconds}`,"HttpOnly",`SameSite=${n.sameSite}`];return n.secure&&o.push("Secure"),o.join("; ")}function He(t,e){return !t||t.startsWith("/")||t.includes("://")||t.includes("\\")?e:t}function De(t){let{getAuth:e,apiKey:n,authDomain:o,mode:s="cookie",allow:r,providers:a=["password","google"],title:i="Docs sign-in",cookieName:c="__docs_session",sessionTtlDays:u=5,secureCookie:p=true,sameSite:l="Lax",contextKey:m="docsUser",onUnauthenticated:v="redirect",authEmulatorHost:x=process.env.FIREBASE_AUTH_EMULATOR_HOST}=t;async function f(d){if(!r)return true;try{return !!await r(d)}catch{return false}}return {__docsAuthExtension:true,middleware:async(d,y)=>{let T=e();if(s==="both"){let D=(d.req.header("authorization")??d.req.header("Authorization"))?.match(/^Bearer\s+(.+)$/i);if(D)try{let Y=await T.verifyIdToken(D[1],!1);if(await f(Y))return d.set(m,Y),y()}catch{}}let w=$(d.req.header("cookie")??"")[c];if(w)try{let A=await T.verifySessionCookie(w,!1);if(await f(A))return d.set(m,A),y()}catch{}let H=d.req.header("accept")??"",j=d.req.method==="GET"&&H.includes("text/html");if(v==="redirect"&&j){let A=encodeURIComponent(Ie(d.req.path)||"docs");return d.redirect(`${B}?next=${A}`,302)}return d.json({error:"Unauthorized"},401)},loginName:B,routes:[{method:"GET",name:B,handler:async d=>{if(!n||!o)throw new Error("[firebaseDocsAuth] `apiKey` and `authDomain` are required for the login page. Find both in the Firebase Console \u2192 Project Settings \u2192 General \u2192 Web app config.");let y=He(d.req.query("next"),"docs"),T=d.req.query("error")??null,h=re({title:i,providers:a,apiKey:n,authDomain:o,sessionPath:oe,next:y,error:T,authEmulatorHost:x});return d.html(h,200,{"Cache-Control":"no-store"})}},{method:"POST",name:oe,handler:async d=>{let y="";try{let h=await d.req.json();y=typeof h.idToken=="string"?h.idToken:"";}catch{y="";}if(!y)return d.json({success:false,error:"Missing idToken"},400);let T=u*24*60*60*1e3;try{let h=e(),w=await h.verifyIdToken(y,!0);if(!await f(w))return d.json({success:!1,error:"Forbidden"},403);let H=w.auth_time,j=typeof H=="number"?H*1e3:Date.now();if(Date.now()-j>300*1e3)return d.json({success:!1,error:"Recent sign-in required"},401);let A=await h.createSessionCookie(y,{expiresIn:T}),D=se(c,encodeURIComponent(A),{maxAgeSeconds:Math.floor(T/1e3),secure:p,sameSite:l});return d.header("Set-Cookie",D),d.json({success:!0})}catch(h){let w=h instanceof Error?h.message:"Invalid idToken";return d.json({success:false,error:w},401)}}},{method:"POST",name:Pe,handler:async d=>{let T=$(d.req.header("cookie")??"")[c];if(T)try{let h=e(),w=await h.verifySessionCookie(T,!1);await h.revokeRefreshTokens(w.uid);}catch{}return d.header("Set-Cookie",se(c,"",{maxAgeSeconds:0,secure:p,sameSite:l})),d.json({success:true})}}]}}var M=new AsyncLocalStorage,ze=Object.freeze({get c(){let t=M.getStore();if(!t)throw new Error("[services] requestContext.c was accessed outside of a request. Wrap non-HTTP code paths (cron, triggers, scripts, tests) in `withRequestContext({ c }, () => ...)` to supply a Hono Context.");return t.c},get maybeC(){return M.getStore()?.c}});function N(){return async(t,e)=>{await M.run({c:t},async()=>{await e();});}}function je(t,e){return M.run({c:t.c},async()=>e())}var I="ctx";function Fe(t){let e=new Map,n=[],o=new Proxy({},{get(s,r){if(typeof r!="string")return;if(r===I)return ze;if(e.has(r))return e.get(r);let a=t[r];if(typeof a!="function")throw new Error(`[services] unknown service "${r}". Registered: ${[I,...Object.keys(t)].join(", ")}`);if(n.includes(r))throw new Error(`[services] circular dependency detected: ${[...n,r].join(" \u2192 ")}`);n.push(r);try{let i=Le(a)?new a(o):a(o);return e.set(r,i),i}finally{n.pop();}},has(s,r){return typeof r!="string"?false:r===I||r in t},ownKeys(){return [I,...Object.keys(t)]},getOwnPropertyDescriptor(s,r){if(typeof r=="string"&&(r===I||r in t))return {enumerable:true,configurable:true}}});return o}function Le(t){return /^class[\s{]/.test(Function.prototype.toString.call(t))}var $e=Object.freeze({}),C=class{constructor(e){this.cachedSpec=null;this.options=e,this.app=new Hono,this.mountedRoutes=Ne(e.routes,e.api),e.services&&this.app.use("*",N());let n=[...e.middlewares??[],...e.globalMiddlewares??[]];for(let o of n)this.app.use("*",o);this.mountRoutes(),this.mountOpenApi(),e.notFound&&this.app.notFound(e.notFound),e.onError&&this.app.onError(e.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(e,n){let o=this.nodeHandler;return n?e(n,o):e(o)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=F(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Ue(this.options.interceptor)),this.cachedSpec}mountRoutes(){let e=this.options.basePath??"",n=this.options.validateOutput??false,o=this.options.verbose??false;for(let s of this.mountedRoutes){if(!s.path)throw new Error(`[HonoServer] route "${s.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let r=z(e,s.path),a=s.middlewares??[],i=s.source??(s.method==="get"?"query":"json"),c=Ke(s,i,n,Be(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),u=s.method.toUpperCase();this.app.on(u,[r],...a,c),o&&console.log(`[HonoServer] ${s.method.toUpperCase().padEnd(6)} ${r}`);}}mountOpenApi(){let e=this.options.openapi;if(!e)return;let n=e.path??"/openapi.json",o=e.docsPath===void 0?"/docs":e.docsPath,s=z(this.options.basePath??"",n),r=o===false?null:z(this.options.basePath??"",o),a;if(U(e.docsAuth)){let i=e.docsAuth;a=[i.middleware];let c=Ze(r??s);for(let u of i.routes)this.app.on(u.method,[z(c,u.name)],u.handler);}else a=e.docsAuth?Array.isArray(e.docsAuth)?e.docsAuth:[e.docsAuth]:[];if(this.app.on("GET",[s],...a,i=>i.json(this.buildOpenApiSpec())),r){let i=Ge(r,s);this.app.on("GET",[r],...a,c=>c.html(L(i,e.info.title)));}}};function ie(t){return typeof t=="object"&&t!==null&&typeof t.handler=="function"}function Be(t){if(t)return ie(t)?t.handler:t}function Ue(t){return ie(t)?t:void 0}function Ne(t,e){return e?t.filter(n=>Array.isArray(n.api)?n.api.includes(e):n.api===e):t.slice()}function z(t,e){let n=t.endsWith("/")?t.slice(0,-1):t,o=e.startsWith("/")?e:`/${e}`,s=`${n}${o}`;return s===""?"/":s}function Ze(t){let e=t.lastIndexOf("/");return e<=0?"":t.slice(0,e)}function Ge(t,e){let n=t.split("/").filter(Boolean),o=e.split("/").filter(Boolean);n.pop();let s=0;for(;s<n.length&&s<o.length&&n[s]===o[s];)s++;let r=n.length-s;return [...Array(r).fill(".."),...o.slice(s)].join("/")||"./"}function Ke(t,e,n,o,s,r,a){let i=t.input,c=t.output,u=t.status??200,p=s??$e;return async l=>{let m=async f=>{if(r){let g=await r.handle({error:f,c:l,route:t,services:p,logger:a});if(g)return g}return P(l,f)},v=async()=>{let f;if(i){let S;try{S=await We(l,e,t.method);}catch(b){throw new k(b instanceof Error?b.message:String(b))}let E=i.safeParse(S);if(!E.success)throw new R(E.error,e);f=E.data;}let g=await t.handler({input:f,c:l,services:p,errorHandler:r,logger:a});if(n&&c&&!(g instanceof Response)){let S=c.safeParse(g);if(!S.success)throw new O(S.error);return S.data}return g},x;if(o)try{x=await o({next:v,route:t,c:l,services:p,errorHandler:r,logger:a});}catch(f){let g=await m(f);if(g)return g;throw f}else try{x=await v();}catch(f){let g=await m(f);if(g)return g;throw f}return x instanceof Response?x:l.json(x,u)}}async function We(t,e,n){switch(e){case "json":{if(n==="get")return t.req.query();let o=await t.req.text();if(!o)return {};try{return JSON.parse(o)}catch(s){throw new Error(`Invalid JSON body: ${s instanceof Error?s.message:String(s)}`)}}case "query":return t.req.query();case "form":return await t.req.parseBody();case "param":return t.req.param();default:return {}}}var Z=class{constructor(e){this.services=e;}};function G(t,e){return {...e,input:t.input,output:t.output,handler:({input:n,services:o})=>new t(o).execute(n)}}function Je(t,e){let n=e?.services,o=e?.errorHandler,s=e?.logger;return {configs:t,defineRoute(r){return r},useCaseRoute(r,a){return G(r,a)},serverFor(r,a){let i=t[r];if(!i)throw new Error(`[ApiRegistry] unknown api "${r}". Registered: ${Object.keys(t).join(", ")}`);return new C({...i,api:r,routes:a,services:n,errorHandler:i.errorHandler??o,logger:i.logger??s})},spec(r,a){return this.serverFor(r,a).buildOpenApiSpec()},toFunctions(r,a,i){let c={};for(let u of Object.keys(t)){let p={...i?.defaults??{},...i?.per?.[u]??{}},l=new C({...t[u],api:u,routes:r,services:n,errorHandler:t[u].errorHandler??o,logger:t[u].logger??s});c[u]=Object.keys(p).length?l.toFunction(a,p):l.toFunction(a);}return c}}}function ae(t){return t||process.env.GOOGLE_CLOUD_PROJECT||process.env.GCLOUD_PROJECT||process.env.GCP_PROJECT||void 0}function K(t,e={}){if(!e.enabled||!t)return;let n=ae(e.projectId);if(!n)return;let s=`jsonPayload.${e.field??"errorId"}="${t}"`,r=[`query=${encodeURIComponent(s)}`];return e.duration&&r.push(`duration=${encodeURIComponent(e.duration)}`),`https://console.cloud.google.com/logs/query;${r.join(";")}?project=${encodeURIComponent(n)}`}var W=class{constructor(e={}){this.options=e;}gcpLogsUrl(e){return K(e,this.options.gcpLogs)}async handle(e){let n=await this.mapError(e);return n?(this.logError(e,n),n):this.handleBuiltin(e)}mapError(e){return null}logError(e,n){}handleBuiltin(e){return P(e.c,e.error)}};var J=class t{info(e,n){this.write("INFO",this.payload(e,n));}warn(e,n){this.write("WARNING",this.payload(e,n));}debug(e,n){this.write("DEBUG",this.payload(e,n));}error(e,n){let o=t.errorId(e);return this.write("ERROR",{errorId:o,message:e instanceof Error?e.message:String(e),...e instanceof Error&&e.stack?{stack:e.stack}:{},...n!==void 0?{meta:n}:{}}),o}payload(e,n){return n!==void 0?{message:e,meta:n}:{message:e}}write(e,n){let o={severity:e,...n};e==="ERROR"?console.error(o):e==="WARNING"?console.warn(o):console.log(o);}static errorId(e){return e&&typeof e=="object"&&"errorId"in e&&typeof e.errorId=="string"?e.errorId:Math.random().toString(36).slice(2,12)}};var ue={skipSegments:["useCases","useCase","use-cases","use-case"],casing:"preserve"};function V(t,e=ue){let n=new Set(e.skipSegments.map(s=>s.toLowerCase()));return "/"+t.split("/").filter(Boolean).filter(s=>!n.has(s.toLowerCase())).map(s=>e.casing==="kebab"?Ve(s):s).join("/")}function Ve(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase()}function X(t,e,n){let o=ce(t),s=ce(e),r=0;for(;r<o.length&&r<s.length&&o[r]===s[r];)r++;let a=o.length-r,i=s.slice(r),u=(i[i.length-1]??"").replace(/\.[mc]?[tj]sx?$/i,""),p=n===""?u:`${u}${n}`;return i[i.length-1]=p,(a===0?"./":"../".repeat(a))+i.join("/")}function ce(t){return t.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter((n,o)=>!(o===0&&n===""))}var de={routesFile:"routes.ts",excludeSegments:["node_modules","__generated__","tests","__tests__",".turbo","dist","build",".next"]};function nt(t,e=de){let n=[];return pe(t,t,e,n),n.sort((o,s)=>o.relPath.localeCompare(s.relPath)),n}function pe(t,e,n,o){let s;try{s=readdirSync(e);}catch{return}for(let r of s){if(n.excludeSegments.includes(r))continue;let a=join(e,r),i;try{i=statSync(a);}catch{continue}if(i.isDirectory())pe(t,a,n,o);else if(i.isFile()&&r===n.routesFile){let c=relative(t,a).split(sep).join("/"),u=c.replace(/\/?[^/]+$/,"");o.push({absPath:a,relPath:c,relDir:u});}}}var le="/**\n * AUTO-GENERATED by `@lpdjs/firestore-repo-service` Hono codegen.\n * Do not edit by hand \u2014 re-run `hono:gen` after adding / removing route files.\n */\n";function fe(t,e){let n=dirname(e.outFile);mkdirSync(n,{recursive:true});let o=e.banner??le,s=(e.now??new Date).toISOString(),r=e.importExtension,a=[],i=[],c=[];t.forEach((p,l)=>{let m=X(n,p.absPath,r),v=V(p.relDir,e.derive);a.push(`import mod${l} from ${JSON.stringify(m)};`),i.push(` { __derivedPath: ${JSON.stringify(v)}, mod: mod${l} },`),c.push({source:p.relPath,url:v});});let u=`${o}// Generated at ${s} \u2014 ${t.length} route file${t.length===1?"":"s"}.
242
+ </html>`}function q(t){let e={};if(!t)return e;for(let n of t.split(";")){let o=n.indexOf("=");if(o===-1)continue;let s=n.slice(0,o).trim();if(!s)continue;let r=n.slice(o+1).trim();r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1));try{e[s]=decodeURIComponent(r);}catch{e[s]=r;}}return e}function ke(t){let{getAuth:e,allow:n,checkRevoked:o=false,contextKey:s="docsUser"}=t;return async(r,a)=>{let c=(r.req.header("authorization")??r.req.header("Authorization"))?.match(/^Bearer\s+(.+)$/i);if(!c)return r.json({error:"Unauthorized"},401,{"WWW-Authenticate":"Bearer"});let u;try{u=await e().verifyIdToken(c[1],o);}catch{return r.json({error:"Unauthorized"},401,{"WWW-Authenticate":"Bearer"})}if(n){let p=false;try{p=await n(u);}catch{p=false;}if(!p)return r.json({error:"Forbidden"},403)}return r.set(s,u),a()}}function Oe(t){let{username:e,password:n,realm:o="Docs"}=t,s=`Basic ${btoa(`${e}:${n}`)}`;return async(r,a)=>{let i=r.req.header("authorization")??r.req.header("Authorization")??"";return Ce(i,s)?a():r.text("Unauthorized",401,{"WWW-Authenticate":`Basic realm="${o}"`})}}function Ce(t,e){if(t.length!==e.length)return false;let n=0;for(let o=0;o<t.length;o++)n|=t.charCodeAt(o)^e.charCodeAt(o);return n===0}function B(t){return typeof t=="object"&&t!==null&&t.__docsAuthExtension===true}var $="__login",oe="__session",Pe="__logout";function Ie(t){let e=t.split("?")[0].split("/").filter(Boolean);return e[e.length-1]??""}function se(t,e,n){let o=[`${t}=${e}`,"Path=/",`Max-Age=${n.maxAgeSeconds}`,"HttpOnly",`SameSite=${n.sameSite}`];return n.secure&&o.push("Secure"),o.join("; ")}function He(t,e){return !t||t.startsWith("/")||t.includes("://")||t.includes("\\")?e:t}function De(t){let{getAuth:e,apiKey:n,authDomain:o,mode:s="cookie",allow:r,providers:a=["password","google"],title:i="Docs sign-in",cookieName:c="__docs_session",sessionTtlDays:u=5,secureCookie:p=true,sameSite:l="Lax",contextKey:v="docsUser",onUnauthenticated:x="redirect",authEmulatorHost:S=process.env.FIREBASE_AUTH_EMULATOR_HOST}=t;async function f(d){if(!r)return true;try{return !!await r(d)}catch{return false}}return {__docsAuthExtension:true,middleware:async(d,h)=>{let T=e();if(s==="both"){let H=(d.req.header("authorization")??d.req.header("Authorization"))?.match(/^Bearer\s+(.+)$/i);if(H)try{let Y=await T.verifyIdToken(H[1],!1);if(await f(Y))return d.set(v,Y),h()}catch{}}let w=q(d.req.header("cookie")??"")[c];if(w)try{let R=await T.verifySessionCookie(w,!1);if(await f(R))return d.set(v,R),h()}catch{}let I=d.req.header("accept")??"",z=d.req.method==="GET"&&I.includes("text/html");if(x==="redirect"&&z){let R=encodeURIComponent(Ie(d.req.path)||"docs");return d.redirect(`${$}?next=${R}`,302)}return d.json({error:"Unauthorized"},401)},loginName:$,routes:[{method:"GET",name:$,handler:async d=>{if(!n||!o)throw new Error("[firebaseDocsAuth] `apiKey` and `authDomain` are required for the login page. Find both in the Firebase Console \u2192 Project Settings \u2192 General \u2192 Web app config.");let h=He(d.req.query("next"),"docs"),T=d.req.query("error")??null,m=re({title:i,providers:a,apiKey:n,authDomain:o,sessionPath:oe,next:h,error:T,authEmulatorHost:S});return d.html(m,200,{"Cache-Control":"no-store"})}},{method:"POST",name:oe,handler:async d=>{let h="";try{let m=await d.req.json();h=typeof m.idToken=="string"?m.idToken:"";}catch{h="";}if(!h)return d.json({success:false,error:"Missing idToken"},400);let T=u*24*60*60*1e3;try{let m=e(),w=await m.verifyIdToken(h,!0);if(!await f(w))return d.json({success:!1,error:"Forbidden"},403);let I=w.auth_time,z=typeof I=="number"?I*1e3:Date.now();if(Date.now()-z>300*1e3)return d.json({success:!1,error:"Recent sign-in required"},401);let R=await m.createSessionCookie(h,{expiresIn:T}),H=se(c,encodeURIComponent(R),{maxAgeSeconds:Math.floor(T/1e3),secure:p,sameSite:l});return d.header("Set-Cookie",H),d.json({success:!0})}catch(m){let w=m instanceof Error?m.message:"Invalid idToken";return d.json({success:false,error:w},401)}}},{method:"POST",name:Pe,handler:async d=>{let T=q(d.req.header("cookie")??"")[c];if(T)try{let m=e(),w=await m.verifySessionCookie(T,!1);await m.revokeRefreshTokens(w.uid);}catch{}return d.header("Set-Cookie",se(c,"",{maxAgeSeconds:0,secure:p,sameSite:l})),d.json({success:true})}}]}}var D=new AsyncLocalStorage,ze=Object.freeze({get c(){let t=D.getStore();if(!t)throw new Error("[services] requestContext.c was accessed outside of a request. Wrap non-HTTP code paths (cron, triggers, scripts, tests) in `withRequestContext({ c }, () => ...)` to supply a Hono Context.");return t.c},get maybeC(){return D.getStore()?.c}});function U(){return async(t,e)=>{await D.run({c:t},async()=>{await e();});}}function je(t,e){return D.run({c:t.c},async()=>e())}var P="ctx";function Fe(t){let e=new Map,n=[],o=new Proxy({},{get(s,r){if(typeof r!="string")return;if(r===P)return ze;if(e.has(r))return e.get(r);let a=t[r];if(typeof a!="function")throw new Error(`[services] unknown service "${r}". Registered: ${[P,...Object.keys(t)].join(", ")}`);if(n.includes(r))throw new Error(`[services] circular dependency detected: ${[...n,r].join(" \u2192 ")}`);n.push(r);try{let i=Le(a)?new a(o):a(o);return e.set(r,i),i}finally{n.pop();}},has(s,r){return typeof r!="string"?false:r===P||r in t},ownKeys(){return [P,...Object.keys(t)]},getOwnPropertyDescriptor(s,r){if(typeof r=="string"&&(r===P||r in t))return {enumerable:true,configurable:true}}});return o}function Le(t){return /^class[\s{]/.test(Function.prototype.toString.call(t))}var $e=Object.freeze({}),O=class{constructor(e){this.cachedSpec=null;this.options=e,this.app=new Hono,this.mountedRoutes=Ne(e.routes,e.api),e.services&&this.app.use("*",U());let n=[...e.middlewares??[],...e.globalMiddlewares??[]];for(let o of n)this.app.use("*",o);this.mountRoutes(),this.mountOpenApi(),e.notFound&&this.app.notFound(e.notFound),e.onError&&this.app.onError(e.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(e,n){let o=this.nodeHandler;return n?e(n,o):e(o)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=j(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Ue(this.options.interceptor)),this.cachedSpec}mountRoutes(){let e=this.options.basePath??"",n=this.options.validateOutput??false,o=this.options.verbose??false;for(let s of this.mountedRoutes){if(!s.path)throw new Error(`[HonoServer] route "${s.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let r=M(e,s.path),a=s.middlewares??[],i=s.source??(s.method==="get"?"query":"json"),c=Ke(s,i,n,Be(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),u=s.method.toUpperCase();this.app.on(u,[r],...a,c),o&&console.log(`[HonoServer] ${s.method.toUpperCase().padEnd(6)} ${r}`);}}mountOpenApi(){let e=this.options.openapi;if(!e)return;let n=e.path??"/openapi.json",o=e.docsPath===void 0?"/docs":e.docsPath,s=M(this.options.basePath??"",n),r=o===false?null:M(this.options.basePath??"",o),a;if(B(e.docsAuth)){let i=e.docsAuth;a=[i.middleware];let c=Ze(r??s);for(let u of i.routes)this.app.on(u.method,[M(c,u.name)],u.handler);}else a=e.docsAuth?Array.isArray(e.docsAuth)?e.docsAuth:[e.docsAuth]:[];if(this.app.on("GET",[s],...a,i=>i.json(this.buildOpenApiSpec())),r){let i=Ge(r,s);this.app.on("GET",[r],...a,c=>c.html(F(i,e.info.title)));}}};function ie(t){return typeof t=="object"&&t!==null&&typeof t.handler=="function"}function Be(t){if(t)return ie(t)?t.handler:t}function Ue(t){return ie(t)?t:void 0}function Ne(t,e){return e?t.filter(n=>Array.isArray(n.api)?n.api.includes(e):n.api===e):t.slice()}function M(t,e){let n=t.endsWith("/")?t.slice(0,-1):t,o=e.startsWith("/")?e:`/${e}`,s=`${n}${o}`;return s===""?"/":s}function Ze(t){let e=t.lastIndexOf("/");return e<=0?"":t.slice(0,e)}function Ge(t,e){let n=t.split("/").filter(Boolean),o=e.split("/").filter(Boolean);n.pop();let s=0;for(;s<n.length&&s<o.length&&n[s]===o[s];)s++;let r=n.length-s;return [...Array(r).fill(".."),...o.slice(s)].join("/")||"./"}function Ke(t,e,n,o,s,r,a){let i=t.input,c=t.output,u=t.status??200,p=s??$e;return async l=>{let v=async f=>{if(r){let g=await r.handle({error:f,c:l,route:t,services:p,logger:a});if(g)return g}return C(l,f)},x=async()=>{let f,g;try{g=await We(l,e,t.method);}catch(y){throw new b(y instanceof Error?y.message:String(y))}if(i){let y=i.safeParse(g);if(!y.success)throw new E(y.error,e);f=y.data;}else f=g;let A=await t.handler({input:f,c:l,services:p,errorHandler:r,logger:a});if(n&&c&&!(A instanceof Response)){let y=c.safeParse(A);if(!y.success)throw new k(y.error);return y.data}return A},S;if(o)try{S=await o({next:x,route:t,c:l,services:p,errorHandler:r,logger:a});}catch(f){let g=await v(f);if(g)return g;throw f}else try{S=await x();}catch(f){let g=await v(f);if(g)return g;throw f}return S instanceof Response?S:l.json(S,u)}}async function We(t,e,n){switch(e){case "json":{if(n==="get")return t.req.query();let o=await t.req.text();if(!o)return {};try{return JSON.parse(o)}catch(s){throw new Error(`Invalid JSON body: ${s instanceof Error?s.message:String(s)}`)}}case "query":return t.req.query();case "form":return await t.req.parseBody();case "param":return t.req.param();default:return {}}}var N=class{constructor(e){this.services=e;}};function Z(t,e){return {...e,input:t.input,output:t.output,handler:({input:n,services:o})=>new t(o).execute(n)}}function Je(t,e){let n=e?.services,o=e?.errorHandler,s=e?.logger;return {configs:t,defineRoute(r){return r},useCaseRoute(r,a){return Z(r,a)},serverFor(r,a){let i=t[r];if(!i)throw new Error(`[ApiRegistry] unknown api "${r}". Registered: ${Object.keys(t).join(", ")}`);return new O({...i,api:r,routes:a,services:n,errorHandler:i.errorHandler??o,logger:i.logger??s})},spec(r,a){return this.serverFor(r,a).buildOpenApiSpec()},toFunctions(r,a,i){let c={};for(let u of Object.keys(t)){let p={...i?.defaults??{},...i?.per?.[u]??{}},l=new O({...t[u],api:u,routes:r,services:n,errorHandler:t[u].errorHandler??o,logger:t[u].logger??s});c[u]=Object.keys(p).length?l.toFunction(a,p):l.toFunction(a);}return c}}}function ae(t){return t||process.env.GOOGLE_CLOUD_PROJECT||process.env.GCLOUD_PROJECT||process.env.GCP_PROJECT||void 0}function G(t,e={}){if(!e.enabled||!t)return;let n=ae(e.projectId);if(!n)return;let s=`jsonPayload.${e.field??"errorId"}="${t}"`,r=[`query=${encodeURIComponent(s)}`];return e.duration&&r.push(`duration=${encodeURIComponent(e.duration)}`),`https://console.cloud.google.com/logs/query;${r.join(";")}?project=${encodeURIComponent(n)}`}var K=class{constructor(e={}){this.options=e;}gcpLogsUrl(e){return G(e,this.options.gcpLogs)}async handle(e){let n=await this.mapError(e);return n?(this.logError(e,n),n):this.handleBuiltin(e)}mapError(e){return null}logError(e,n){}handleBuiltin(e){return C(e.c,e.error)}};var W=class t{info(e,n){this.write("INFO",this.payload(e,n));}warn(e,n){this.write("WARNING",this.payload(e,n));}debug(e,n){this.write("DEBUG",this.payload(e,n));}error(e,n){let o=t.errorId(e);return this.write("ERROR",{errorId:o,message:e instanceof Error?e.message:String(e),...e instanceof Error&&e.stack?{stack:e.stack}:{},...n!==void 0?{meta:n}:{}}),o}payload(e,n){return n!==void 0?{message:e,meta:n}:{message:e}}write(e,n){let o={severity:e,...n};e==="ERROR"?console.error(o):e==="WARNING"?console.warn(o):console.log(o);}static errorId(e){return e&&typeof e=="object"&&"errorId"in e&&typeof e.errorId=="string"?e.errorId:Math.random().toString(36).slice(2,12)}};var ue={skipSegments:["useCases","useCase","use-cases","use-case"],casing:"preserve"};function J(t,e=ue){let n=new Set(e.skipSegments.map(s=>s.toLowerCase()));return "/"+t.split("/").filter(Boolean).filter(s=>!n.has(s.toLowerCase())).map(s=>e.casing==="kebab"?Ve(s):s).join("/")}function Ve(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase()}function V(t,e,n){let o=ce(t),s=ce(e),r=0;for(;r<o.length&&r<s.length&&o[r]===s[r];)r++;let a=o.length-r,i=s.slice(r),u=(i[i.length-1]??"").replace(/\.[mc]?[tj]sx?$/i,""),p=n===""?u:`${u}${n}`;return i[i.length-1]=p,(a===0?"./":"../".repeat(a))+i.join("/")}function ce(t){return t.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter((n,o)=>!(o===0&&n===""))}var de={routesFile:"routes.ts",excludeSegments:["node_modules","__generated__","tests","__tests__",".turbo","dist","build",".next"]};function nt(t,e=de){let n=[];return pe(t,t,e,n),n.sort((o,s)=>o.relPath.localeCompare(s.relPath)),n}function pe(t,e,n,o){let s;try{s=readdirSync(e);}catch{return}for(let r of s){if(n.excludeSegments.includes(r))continue;let a=join(e,r),i;try{i=statSync(a);}catch{continue}if(i.isDirectory())pe(t,a,n,o);else if(i.isFile()&&r===n.routesFile){let c=relative(t,a).split(sep).join("/"),u=c.replace(/\/?[^/]+$/,"");o.push({absPath:a,relPath:c,relDir:u});}}}var le="/**\n * AUTO-GENERATED by `@lpdjs/firestore-repo-service` Hono codegen.\n * Do not edit by hand \u2014 re-run `hono:gen` after adding / removing route files.\n */\n";function fe(t,e){let n=dirname(e.outFile);mkdirSync(n,{recursive:true});let o=e.banner??le,s=(e.now??new Date).toISOString(),r=e.importExtension,a=[],i=[],c=[];t.forEach((p,l)=>{let v=V(n,p.absPath,r),x=J(p.relDir,e.derive);a.push(`import mod${l} from ${JSON.stringify(v)};`),i.push(` { __derivedPath: ${JSON.stringify(x)}, mod: mod${l} },`),c.push({source:p.relPath,url:x});});let u=`${o}// Generated at ${s} \u2014 ${t.length} route file${t.length===1?"":"s"}.
243
243
 
244
244
  import type { AnyRouteDef, RouteModuleDefault } from "@lpdjs/firestore-repo-service/servers/hono";
245
245
 
@@ -256,5 +256,5 @@ export const routes: AnyRouteDef[] = __defs.flatMap(({ __derivedPath, mod }) =>
256
256
  const list = Array.isArray(mod) ? mod : [mod];
257
257
  return list.map((route) => ({ ...route, path: route.path ?? __derivedPath }));
258
258
  });
259
- `;return writeFileSync(e.outFile,u,"utf8"),{outFile:e.outFile,routeCount:t.length,derivedPaths:c}}function at(t,e,n,o,s){let r=s(t),a=join(t,e);return fe(r,{outFile:a,derive:n,importExtension:o})}export{k as BadRequestError,W as BaseErrorHandler,J as BaseLogger,ue as DEFAULT_DERIVE,le as DEFAULT_GENERATOR_BANNER,de as DEFAULT_SCANNER,C as HonoServer,O as OutputValidationError,Z as UseCase,R as ValidationError,Oe as basicAuth,F as buildOpenApiDocument,Je as createApiRegistry,N as createRequestContextMiddleware,Fe as createServices,P as defaultErrorResponse,ge as defineRoutes,V as derivePath,ke as firebaseBearerAuth,De as firebaseDocsAuth,K as gcpLogsUrl,at as generateFromRoot,fe as generateRoutesManifest,U as isDocsAuthExtension,L as renderDocsHtml,ae as resolveGcpProjectId,nt as scanRoutes,X as toImportSpecifier,G as useCaseRoute,je as withRequestContext};//# sourceMappingURL=index.js.map
259
+ `;return writeFileSync(e.outFile,u,"utf8"),{outFile:e.outFile,routeCount:t.length,derivedPaths:c}}function at(t,e,n,o,s){let r=s(t),a=join(t,e);return fe(r,{outFile:a,derive:n,importExtension:o})}export{b as BadRequestError,K as BaseErrorHandler,W as BaseLogger,ue as DEFAULT_DERIVE,le as DEFAULT_GENERATOR_BANNER,de as DEFAULT_SCANNER,O as HonoServer,k as OutputValidationError,N as UseCase,E as ValidationError,Oe as basicAuth,j as buildOpenApiDocument,Je as createApiRegistry,U as createRequestContextMiddleware,Fe as createServices,C as defaultErrorResponse,ge as defineRoutes,J as derivePath,ke as firebaseBearerAuth,De as firebaseDocsAuth,G as gcpLogsUrl,at as generateFromRoot,fe as generateRoutesManifest,B as isDocsAuthExtension,F as renderDocsHtml,ae as resolveGcpProjectId,nt as scanRoutes,V as toImportSpecifier,Z as useCaseRoute,je as withRequestContext};//# sourceMappingURL=index.js.map
260
260
  //# sourceMappingURL=index.js.map