@lunora/server 1.0.0-alpha.284 → 1.0.0-alpha.285
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.
- package/dist/index.d.mts +10 -1
- package/dist/index.d.ts +10 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{defineLiveStream-q9yO3wl6.mjs → defineLiveStream-D3xRvNDy.mjs} +1 -1
- package/dist/packem_shared/httpAction-DD8h1jcf.mjs +1 -0
- package/package.json +1 -1
- package/dist/packem_shared/httpAction-Bfw3qwLG.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1921,7 +1921,7 @@ declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
|
|
|
1921
1921
|
*/
|
|
1922
1922
|
declare const isSafeHeaderValue: (value: string) => boolean;
|
|
1923
1923
|
/** HTTP verbs the typed {@link httpRoute} builder can bind to. */
|
|
1924
|
-
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
|
|
1924
|
+
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "QUERY";
|
|
1925
1925
|
/** The `run*` trio, shared between {@link HttpActionCtx} itself and its `forShard(key)` view. */
|
|
1926
1926
|
type HttpRunners = Pick<ActionCtx, "runAction" | "runMutation" | "runQuery">;
|
|
1927
1927
|
/**
|
|
@@ -2214,6 +2214,7 @@ interface HttpRoute {
|
|
|
2214
2214
|
patch: HttpRouteFactory;
|
|
2215
2215
|
post: HttpRouteFactory;
|
|
2216
2216
|
put: HttpRouteFactory;
|
|
2217
|
+
query: HttpRouteFactory;
|
|
2217
2218
|
}
|
|
2218
2219
|
/**
|
|
2219
2220
|
* Read the SSE resume position off a request: the `Last-Event-ID` header a
|
|
@@ -2283,9 +2284,17 @@ declare const sseEvent: <R>(frame: {
|
|
|
2283
2284
|
* .params({ id: v.string() })
|
|
2284
2285
|
* .handler(async ({ ctx, params }) => ctx.runQuery(api.todos.get, params));
|
|
2285
2286
|
*
|
|
2287
|
+
* // QUERY (RFC 10008) is a safe, idempotent read whose filter travels as a typed
|
|
2288
|
+
* // JSON body instead of strings in the URL. Hono has no `app.query`, so mount it with `on`.
|
|
2289
|
+
* export const searchTodos = httpRoute
|
|
2290
|
+
* .query("/api/todos/search")
|
|
2291
|
+
* .body({ done: v.boolean(), limit: v.number() })
|
|
2292
|
+
* .handler(async ({ ctx, body }) => ctx.runQuery(api.todos.search, body));
|
|
2293
|
+
*
|
|
2286
2294
|
* const app = httpRouter();
|
|
2287
2295
|
* app.get("/api/todos", listTodos);
|
|
2288
2296
|
* app.get("/api/todos/:id", getTodo);
|
|
2297
|
+
* app.on("QUERY", "/api/todos/search", searchTodos);
|
|
2289
2298
|
* ```
|
|
2290
2299
|
*/
|
|
2291
2300
|
declare const httpRoute: HttpRoute;
|
package/dist/index.d.ts
CHANGED
|
@@ -1921,7 +1921,7 @@ declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
|
|
|
1921
1921
|
*/
|
|
1922
1922
|
declare const isSafeHeaderValue: (value: string) => boolean;
|
|
1923
1923
|
/** HTTP verbs the typed {@link httpRoute} builder can bind to. */
|
|
1924
|
-
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
|
|
1924
|
+
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "QUERY";
|
|
1925
1925
|
/** The `run*` trio, shared between {@link HttpActionCtx} itself and its `forShard(key)` view. */
|
|
1926
1926
|
type HttpRunners = Pick<ActionCtx, "runAction" | "runMutation" | "runQuery">;
|
|
1927
1927
|
/**
|
|
@@ -2214,6 +2214,7 @@ interface HttpRoute {
|
|
|
2214
2214
|
patch: HttpRouteFactory;
|
|
2215
2215
|
post: HttpRouteFactory;
|
|
2216
2216
|
put: HttpRouteFactory;
|
|
2217
|
+
query: HttpRouteFactory;
|
|
2217
2218
|
}
|
|
2218
2219
|
/**
|
|
2219
2220
|
* Read the SSE resume position off a request: the `Last-Event-ID` header a
|
|
@@ -2283,9 +2284,17 @@ declare const sseEvent: <R>(frame: {
|
|
|
2283
2284
|
* .params({ id: v.string() })
|
|
2284
2285
|
* .handler(async ({ ctx, params }) => ctx.runQuery(api.todos.get, params));
|
|
2285
2286
|
*
|
|
2287
|
+
* // QUERY (RFC 10008) is a safe, idempotent read whose filter travels as a typed
|
|
2288
|
+
* // JSON body instead of strings in the URL. Hono has no `app.query`, so mount it with `on`.
|
|
2289
|
+
* export const searchTodos = httpRoute
|
|
2290
|
+
* .query("/api/todos/search")
|
|
2291
|
+
* .body({ done: v.boolean(), limit: v.number() })
|
|
2292
|
+
* .handler(async ({ ctx, body }) => ctx.runQuery(api.todos.search, body));
|
|
2293
|
+
*
|
|
2286
2294
|
* const app = httpRouter();
|
|
2287
2295
|
* app.get("/api/todos", listTodos);
|
|
2288
2296
|
* app.get("/api/todos/:id", getTodo);
|
|
2297
|
+
* app.on("QUERY", "/api/todos/search", searchTodos);
|
|
2289
2298
|
* ```
|
|
2290
2299
|
*/
|
|
2291
2300
|
declare const httpRoute: HttpRoute;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-Dv4DKrj0.mjs";import{authorize as s}from"./packem_shared/authorize-CVLZJxf_.mjs";import{initLunora as p}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as c,tagPerDispatchMiddleware as l}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as u}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as D,withDeferredDeletes as T}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as A,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as _,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as C,documentHistoryExtension as M}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as b,defineEnv as y}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as F,bindTableFacade as v,defineLazyFacade as N}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as H,httpRoute as k,httpRouter as w,lastEventId as B,sseEvent as V}from"./packem_shared/httpAction-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-Dv4DKrj0.mjs";import{authorize as s}from"./packem_shared/authorize-CVLZJxf_.mjs";import{initLunora as p}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as c,tagPerDispatchMiddleware as l}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as u}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as D,withDeferredDeletes as T}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as A,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as _,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as C,documentHistoryExtension as M}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as b,defineEnv as y}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as F,bindTableFacade as v,defineLazyFacade as N}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as H,httpRoute as k,httpRouter as w,lastEventId as B,sseEvent as V}from"./packem_shared/httpAction-DD8h1jcf.mjs";import{serveStorageObject as j}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as J}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as Q,onDisconnect as X,onShardInit as q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as $,DEFAULT_MAX_LIMIT as ee,clampLimit as re,defineListArgs as oe}from"./packem_shared/DEFAULT_LIMIT-z7HB19s7.mjs";import{defineLiveStream as ie,liveStreamRouter as ne}from"./packem_shared/defineLiveStream-D3xRvNDy.mjs";import{defineMigration as ae}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as se}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as pe}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as ce}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as Ee,d as ue,a as Se,b as he,e as De,f as Te,g as Re,h as Ae,i as ge,j as Le,k as _e,m as Ie}from"./packem_shared/plugin-CyLqvCB9.mjs";import{PRESENCE_DEFAULT_TTL_MS as Me,PRESENCE_TABLE as Pe,definePresence as be,presenceExtension as ye}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-aj9Ec70J.mjs";import{PROCEDURE_META as Fe,UNLOADED_META as ve,procedureMeta as Ne}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as He}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as we}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Ve}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as je}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ye}from"./packem_shared/defineShape-H-0IbZlb.mjs";import{defineWebSocket as Je}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Qe}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as qe}from"@lunora/errors";import{cronJobs as $e}from"@lunora/scheduler";import{ValidationError as rr,v as or}from"@lunora/values";import{allowAll as ir,deny as nr,isDeny as fr,toWhereInput as ar}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as sr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as pr,buildRlsReadRegistry as xr,composeShapeReadWhere as cr}from"./packem_shared/assertShapesDeclareReadPolicies-C09SMvM4.mjs";import{buildMaskRegistry as Er}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Sr,definePermission as hr,definePolicies as Dr,definePolicy as Tr,defineRole as Rr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as gr,defineStorageRules as Lr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as Ir}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Mr}from"./packem_shared/mask-ocdNb1L3.mjs";import{r as br}from"./packem_shared/redact-secrets-BpatNz48.mjs";import{r as Or}from"./packem_shared/middleware-CHYtnvZP.mjs";import{storageRules as vr}from"./packem_shared/storageRules-BVIXkoRg.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,$ as DEFAULT_LIMIT,ee as DEFAULT_MAX_LIMIT,_ as DOCUMENT_HISTORY_REDACTED_FIELDS,I as DOCUMENT_HISTORY_TABLE,b as LunoraEnvError,qe as LunoraError,Me as PRESENCE_DEFAULT_TTL_MS,Pe as PRESENCE_TABLE,Fe as PROCEDURE_META,ve as UNLOADED_META,e as VERSION,rr as ValidationError,n as actionCacheExtension,ir as allowAll,sr as asBucketStorage,pr as assertShapesDeclareReadPolicies,s as authorize,h as beginDeferredDeletes,A as beginDeferredSchedules,F as bindOrm,v as bindTableFacade,Er as buildMaskRegistry,xr as buildRlsReadRegistry,f as cacheKeyFor,re as clampLimit,Ee as composePluginMiddleware,cr as composeShapeReadWhere,Sr as createPolicyDsl,u as createSecrets,je as createServices,$e as cronJobs,a as defineActionCache,ue as defineAggregateIndex,Se as defineComponent,C as defineDocumentHistory,y as defineEnv,Y as defineIdentity,J as defineIdentityGuard,N as defineLazyFacade,oe as defineListArgs,ie as defineLiveStream,ae as defineMigration,se as defineModule,pe as defineMutator,hr as definePermission,he as definePlugin,Dr as definePolicies,Tr as definePolicy,be as definePresence,De as defineRankIndex,Rr as defineRole,Ve as defineRoom,Te as defineSchema,Re as defineSchemaExtension,Ye as defineShape,gr as defineStorageRule,Lr as defineStorageRules,Ae as defineTable,ge as defineVectorIndex,Je as defineWebSocket,nr as deny,M as documentHistoryExtension,D as flushDeferredDeletes,H as httpAction,k as httpRoute,w as httpRouter,Le as indexFieldsFromSchema,p as initLunora,_e as installPlugins,fr as isDeny,c as isPerDispatchMiddleware,Ir as isSafeHeaderValue,B as lastEventId,ne as liveStreamRouter,Mr as mask,Ie as mergeSchemaExtension,Q as onConnect,X as onDisconnect,we as onQueryChange,q as onShardInit,Qe as onWhisper,ce as platformAdmin,ye as presenceExtension,Ne as procedureMeta,He as protectPublic,br as redactSecrets,Or as rls,j as serveStorageObject,V as sseEvent,vr as storageRules,l as tagPerDispatchMiddleware,ar as toWhereInput,or as v,T as withDeferredDeletes,g as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as O,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as b}from"@lunora/values";import{Hono as g}from"hono";import{isHttpRouter as j,httpRouter as C,httpAction as E}from"./httpAction-
|
|
1
|
+
import{LunoraError as O,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as b}from"@lunora/values";import{Hono as g}from"hono";import{isHttpRouter as j,httpRouter as C,httpAction as E}from"./httpAction-DD8h1jcf.mjs";const A="/_lunora/live/connect",N="/_lunora/live/control",D="room:",B="__lunora_socket__:",K=256,m=e=>`/live/${e}/connect`,v=e=>`/live/${e}/control`,U=/^[A-Za-z]\w*$/u,T=e=>U.test(e),H=e=>`${e}:`.startsWith(D)||`${e}:`.startsWith(B),V=(e,t,o)=>[e,...t.map(d=>{const i=o[d];if(typeof i!="string")throw new TypeError(`live topic "${e}" needs a string key.${d}`);return encodeURIComponent(i)})].join(":"),k=(e,t)=>{if(e.length>K)return;const[o,...d]=e.split(":");if(o===void 0||!Object.hasOwn(t,o))return;const i=t[o];if(d.length!==i.length)return;const r={};try{for(const[c,u]of i.entries())r[u]=decodeURIComponent(d[c]);return V(o,i,r)===e?{key:r,name:o}:void 0}catch{return}},F=async e=>{try{const t=await e.json();return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},S=e=>Response.json({code:"FORBIDDEN_TOPIC",error:`subscribe to "${e}" was denied`},{status:403}),h=e=>Response.json({code:"BAD_REQUEST",error:e},{status:400}),M=(e,t)=>{for(const[o,d]of Object.entries(t)){if(!T(o))throw new TypeError(`defineLiveStream("${e}"): topic name "${o}" must be a plain identifier (letters, digits and "_", starting with a letter)`);if(H(o))throw new TypeError(`defineLiveStream("${e}"): topic name "${o}" would encode into a reserved topic prefix`);for(const[i,r]of Object.entries(d.key??{})){if(!T(i))throw new TypeError(`defineLiveStream("${e}"): key field "${o}.${i}" must be a plain identifier`);if(!P(r))throw new TypeError(`defineLiveStream("${e}"): key field "${o}.${i}" must be a string validator (v.string(), v.id(), v.literal(…))`)}}},z=(e,t)=>new O("BAD_REQUEST",`publish to "${e}" was refused: ${t instanceof Error?t.message:String(t)}`,{status:400}),q=e=>{M(e.id,e.topics);const t=m(e.id),o=v(e.id),d=Object.fromEntries(Object.entries(e.topics).map(([s,a])=>[s,Object.keys(a.key??{})])),i=s=>{const a=k(s,d),n=a===void 0?void 0:e.topics[a.name];if(!(a===void 0||n===void 0))try{return{declaration:n,key:b(n.key??{},a.key,"key"),name:a.name}}catch{return}},r=(s,a)=>{const n=i(s);if(n===void 0)throw new O("BAD_REQUEST",`"${s}" is not a topic declared by live stream "${e.id}"`,{status:400});const{declaration:p}=n;try{return b({payload:p.payload},{payload:a},"topic").payload}catch(f){throw z(s,f)}},c=async(s,a)=>{const n=i(a);if(n===void 0)return!1;if(!e.onSubscribe)return e.allowAnonymousControl===!0&&s.auth.userId===null;try{return await e.onSubscribe({ctx:s,key:n.key,raw:a,topic:n.name})===!0}catch(p){return console.error("[lunora] live subscribe authorization threw; denying:",p),!1}},u=E(async(s,a)=>{const n=new URL(a.url).searchParams.get("shard")??void 0;return s.fetchShard(n,A,{method:"GET"})}),R=E(async(s,a)=>{const n=await F(a);if(!n)return h("Expected a JSON object body");const{action:p}=n,f=typeof n.topic=="string"?n.topic:void 0;if(f===void 0||f.length===0)return h("topic is required");if(p!=="subscribe"&&p!=="unsubscribe")return h("action must be subscribe or unsubscribe");const y=typeof n.shardKey=="string"?n.shardKey:void 0,L=y===void 0?s:{...s,...s.forShard(y)};if(p==="subscribe"&&!await c(L,f))return S(f);const w=s.fetchShard(y,N,{body:JSON.stringify({...n,stream:e.id}),method:"POST"});if(p!=="subscribe")return w;try{return await w}catch(l){if(I(l)&&l.code==="FORBIDDEN_SHARD")return S(f);throw l}});return{connect:u,connectPath:t,control:R,controlPath:o,id:e.id,topics:e.topics,validatePublish:r}},G=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},_=new WeakMap,$=(e,t)=>{for(const o of t){let d;const i=()=>(d??=o.load().catch(r=>{throw d=void 0,r}),d);e.get(m(o.id),async r=>{const{connect:c}=await i();return c(r)}),e.post(v(o.id),async r=>{const{control:c}=await i();return c(r)})}},Y=(e,t)=>{if(t instanceof g&&j(t)){const r=_.get(t)??new Set,c=e.filter(u=>!r.has(u.id));$(t,c),_.set(t,r);for(const u of c)r.add(u.id);return t}const o=C();if($(o,e),t===void 0)return o;const d=new Set(e.flatMap(r=>[`GET ${m(r.id)}`,`POST ${v(r.id)}`])),i=(r,c,u)=>typeof t=="function"?t(r,c,u):t.fetch(r,c,u);return{...G(t),fetch:(r,c,u)=>d.has(`${r.method} ${new URL(r.url).pathname}`)?o.fetch(r,c,u):i(r,c,u)}};export{q as defineLiveStream,Y as liveStreamRouter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as f,isLunoraError as F,toErrorBody as N}from"@lunora/errors";import{ValidationError as M,parseValidatorMap as v}from"@lunora/values";import{encodeWire as S}from"@lunora/wire";import{Hono as C}from"hono";import{SSE_HEADERS as A,sseFrame as R,isSafeHeaderValue as $}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as b}from"./apply-output-C5wZ5EAL.mjs";import{isDevEnvironment as B}from"@lunora/shard-engine";const j=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],W=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,O=e=>W.test(e),V=(e,t,r=[])=>t?.access!==void 0||j.some(n=>e.has(n))||r.some(n=>!O(n)||e.has(n)),Q=e=>{const t=[];let r="",n=!1,o=!1;for(const s of e){if(o)o=!1;else if(n&&s==="\\")o=!0;else if(s==='"')n=!n;else if(s===","&&!n){t.push(r.trim()),r="";continue}r+=s}return t.push(r.trim()),t.filter(s=>s!=="")},J=new Set(["proxy-revalidate","public","s-maxage"]),Y=e=>{const t=Q(e),r=t.map(o=>o.toLowerCase());return r.includes("private")||r.includes("no-store")?e:["private",...t.filter((o,s)=>{const a=(r[s]?.split("=",1)[0]??"").trim();return!J.has(a)&&a!=="private"})].join(", ")},_=new WeakSet,z=e=>{try{return e.executionCtx}catch{return}},G=(e,t)=>[...j,...t].find(r=>e.has(r))??"cloudflare access",K=(e,t,r)=>{const{headers:n}=r.req.raw,o=e.credentialHeaders??[];if(!V(n,z(r),o))return t;const s=Y(t);return s!==t&&!_.has(e)&&B(r.env)&&(_.add(e),console.warn(`[lunora] httpRoute ${e.method} ${e.path}: sent Cache-Control "${s}" instead of the declared "${t}" because the request carries a credential (${G(n,o)}). A shared cache must not store a per-caller response. Further downgrades on this route are not reported.`)),s},g=e=>{if(e instanceof M)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(F(e)){const{body:t,redacted:r,status:n}=N(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return r&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message,...t.why===void 0?{}:{why:t.why}},{status:n})}throw e},Ee=e=>async t=>{try{return await e(t.get("lunora"),t.req.raw)}catch(r){return g(r)}},T=new WeakSet,H=new WeakSet,Re=e=>H.has(e),k=new WeakSet,Z=new Set(["*","/*"]),X="__COMPOSED_HANDLER",ee=e=>e[X]??e,te=e=>{let t,r=-1;return async n=>{if(t===void 0||r!==e.routes.length){const s=new C;for(const a of e.routes)k.has(ee(a.handler))||s.on(a.method,a.path,()=>new Response(null,{status:204}));t=s,r=e.routes.length}return(await t.fetch(new Request(n.url,{method:n.method}))).status===204}},be=()=>{const e=new C,t=te(e),r=e.use.bind(e);H.add(e),e.use=((...o)=>{const[s]=o;if(typeof s!="string"||Z.has(s))for(const a of o)typeof a=="function"&&k.add(a);return r(...o)}),e.use("*",async(o,s)=>{const a=o.env.__lunoraCtx;if(!a)throw new f("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");o.set("lunora",a);const{__lunoraShellFirst:i,__lunoraUnrouted:u}=o.env;if(i===!0&&!await t(o.req.raw))return u?.(),o.text("404 Not Found",404);const c=o.notFound;o.notFound=()=>(T.add(o),c()),await s()});const n=e.notFound;return e.notFound=o=>n(s=>{const{__lunoraUnrouted:a}=s.env;return T.has(s)||a?.(),o(s)}),e.notFound(o=>o.text("404 Not Found",404)),e},P=e=>e.kind==="optional"?e._meta?.inner??e:e,w=(e,t)=>{switch(e){case"bigint":try{return BigInt(t)}catch{return t}case"boolean":return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:t;case"number":return t===""?Number.NaN:Number(t);default:return t}},re=(e,t,r)=>{const n=P(e);if(n.kind==="array"){const s=t.req.queries(r);if(s===void 0)return;const a=n._meta?.inner;return s.map(i=>w(a?.kind??"string",i))}const o=t.req.query(r);return o===void 0?void 0:w(n.kind,o)},D=(e,t)=>{const r={};for(const n of Object.keys(e)){const o=e[n];o&&(r[n]=re(o,t,n))}return v(e,r,"searchParams")},q=(e,t)=>{const r=t.req.param(),n={};for(const o of Object.keys(e)){const s=e[o];if(!s)continue;const a=r[o];n[o]=a===void 0?void 0:w(P(s).kind,a)}return v(e,n,"params")},oe=async(e,t)=>{let r;try{r=await t.req.json()}catch{throw new f("BAD_REQUEST","Invalid JSON body")}if(typeof r!="object"||r===null||Array.isArray(r))throw new f("BAD_REQUEST","Expected a JSON object body");return v(e,r,"body")},L=(e,t)=>{const{method:r}=t.req;if(!(r===e.method||e.method==="GET"&&r==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${r} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},ne=e=>{const t=e.split(";",1)[0]?.trim().toLowerCase()??"";return t==="application/json"||t.startsWith("application/")&&t.endsWith("+json")},x=(e,t)=>{if(e.method!=="QUERY"||Object.keys(e.body).length===0)return;const r=t.req.header("content-type");if(r===void 0||r.trim()==="")return Response.json({code:"BAD_REQUEST",error:"A QUERY request must declare its Content-Type"},{status:400});if(!ne(r))return Response.json({code:"UNSUPPORTED_MEDIA_TYPE",error:`${r} is not supported on this route; send application/json`},{headers:{"accept-query":"application/json"},status:415})},se=(e,t)=>async r=>{const n=L(e,r)??x(e,r);if(n)return n;try{const o=r.get("lunora"),s=Object.keys(e.searchParams).length>0?D(e.searchParams,r):{},a=Object.keys(e.params).length>0?q(e.params,r):{},i=Object.keys(e.body).length>0?await oe(e.body,r):{},u=await t({body:i,ctx:o,params:a,searchParams:s}),c=e.output?b(e.output,u):u,d={};e.cacheControl&&(d["cache-control"]=K(e,e.cacheControl,r)),e.cacheTag&&(d["cache-tag"]=e.cacheTag),e.vary&&(d.vary=e.vary);const y=Object.keys(d).length>0;return c===void 0?new Response(null,{headers:y?d:void 0,status:204}):Response.json(c,{headers:y?d:void 0})}catch(o){return g(o)}},we=e=>{const t=e.headers.get("last-event-id");if(t!==null)return t===""?void 0:t;const r=new URL(e.url).searchParams.get("lastEventId");return r===null||r===""?void 0:r},I=Symbol.for("@lunora/server/sse-event"),ve=e=>({[I]:!0,data:e.data,id:e.id}),ae=e=>typeof e=="object"&&e!==null&&e[I]===!0,ce=(e,t)=>{if(ae(t)){if(!$(t.id))throw new f("INTERNAL","sseEvent id must not contain CR, LF or NUL");const r=e?b(e,t.data):t.data;return R(S(r),void 0,t.id)}return R(S(e?b(e,t):t))},ie=(e,t)=>(async r=>{const n=L(e,r)??x(e,r);if(n)return n;let o,s;try{o=Object.keys(e.searchParams).length>0?D(e.searchParams,r):{},s=Object.keys(e.params).length>0?q(e.params,r):{}}catch(p){return g(p)}const a=r.get("lunora"),i=r.req.raw,u=new TextEncoder,c=new AbortController;if(i.signal.aborted)return c.abort(),new Response("",{headers:A});const d=()=>{c.abort()};i.signal.addEventListener("abort",d,{once:!0});const y=new ReadableStream({cancel(){i.signal.removeEventListener("abort",d),c.abort()},async start(p){try{const E=t({ctx:a,params:s,request:i,searchParams:o,signal:c.signal});for await(const m of E){if(c.signal.aborted)break;p.enqueue(u.encode(ce(e.output,m)))}c.signal.aborted||p.enqueue(u.encode(R({},"complete")))}catch(E){const{body:m,redacted:U}=N(E,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});U&&console.error("[lunora] unhandled stream handler error:",E),c.signal.aborted||p.enqueue(u.encode(R({code:m.code,hint:m.hint,message:m.message,why:m.why},"error")))}finally{i.signal.removeEventListener("abort",d);try{p.close()}catch{}}}});return new Response(y,{headers:A})}),de=e=>{const t=e?.find(r=>!O(r));if(t!==void 0)throw new f("INTERNAL",`httpRoute .cacheControl(): credentialHeaders entry ${JSON.stringify(t)} is not a header name`);return e},h=e=>({body:t=>h({...e,body:{...e.body,...t}}),cacheControl:(t,r)=>h({...e,cacheControl:t,credentialHeaders:de(r?.credentialHeaders)}),cacheTag:t=>h({...e,cacheTag:t}),handler:t=>se(e,t),output:t=>h({...e,output:t}),params:t=>h({...e,params:{...e.params,...t}}),searchParams:t=>h({...e,searchParams:{...e.searchParams,...t}}),stream:t=>ie(e,t),vary:t=>h({...e,vary:t})}),l=e=>t=>h({body:{},method:e,params:{},path:t,searchParams:{}}),ge={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),query:l("QUERY")};export{Ee as httpAction,ge as httpRoute,be as httpRouter,Re as isHttpRouter,$ as isSafeHeaderValue,we as lastEventId,ve as sseEvent};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f,isLunoraError as I,toErrorBody as C}from"@lunora/errors";import{ValidationError as M,parseValidatorMap as v}from"@lunora/values";import{encodeWire as S}from"@lunora/wire";import{Hono as H}from"hono";import{SSE_HEADERS as A,sseFrame as w,isSafeHeaderValue as U}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as R}from"./apply-output-C5wZ5EAL.mjs";import{isDevEnvironment as $}from"@lunora/shard-engine";const O=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],B=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,T=e=>B.test(e),V=(e,r,t=[])=>r?.access!==void 0||O.some(n=>e.has(n))||t.some(n=>!T(n)||e.has(n)),W=e=>{const r=[];let t="",n=!1,o=!1;for(const a of e){if(o)o=!1;else if(n&&a==="\\")o=!0;else if(a==='"')n=!n;else if(a===","&&!n){r.push(t.trim()),t="";continue}t+=a}return r.push(t.trim()),r.filter(a=>a!=="")},J=new Set(["proxy-revalidate","public","s-maxage"]),Q=e=>{const r=W(e),t=r.map(o=>o.toLowerCase());return t.includes("private")||t.includes("no-store")?e:["private",...r.filter((o,a)=>{const s=(t[a]?.split("=",1)[0]??"").trim();return!J.has(s)&&s!=="private"})].join(", ")},N=new WeakSet,z=e=>{try{return e.executionCtx}catch{return}},G=(e,r)=>[...O,...r].find(t=>e.has(t))??"cloudflare access",K=(e,r,t)=>{const{headers:n}=t.req.raw,o=e.credentialHeaders??[];if(!V(n,z(t),o))return r;const a=Q(r);return a!==r&&!N.has(e)&&$(t.env)&&(N.add(e),console.warn(`[lunora] httpRoute ${e.method} ${e.path}: sent Cache-Control "${a}" instead of the declared "${r}" because the request carries a credential (${G(n,o)}). A shared cache must not store a per-caller response. Further downgrades on this route are not reported.`)),a},g=e=>{if(e instanceof M)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(I(e)){const{body:r,redacted:t,status:n}=C(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return t&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message,...r.why===void 0?{}:{why:r.why}},{status:n})}throw e},fe=e=>async r=>{try{return await e(r.get("lunora"),r.req.raw)}catch(t){return g(t)}},_=new WeakSet,k=new WeakSet,ye=e=>k.has(e),L=new WeakSet,Z=new Set(["*","/*"]),X="__COMPOSED_HANDLER",Y=e=>e[X]??e,ee=e=>{let r,t=-1;return async n=>{if(r===void 0||t!==e.routes.length){const a=new H;for(const s of e.routes)L.has(Y(s.handler))||a.on(s.method,s.path,()=>new Response(null,{status:204}));r=a,t=e.routes.length}return(await r.fetch(new Request(n.url,{method:n.method}))).status===204}},Ee=()=>{const e=new H,r=ee(e),t=e.use.bind(e);k.add(e),e.use=((...o)=>{const[a]=o;if(typeof a!="string"||Z.has(a))for(const s of o)typeof s=="function"&&L.add(s);return t(...o)}),e.use("*",async(o,a)=>{const s=o.env.__lunoraCtx;if(!s)throw new f("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");o.set("lunora",s);const{__lunoraShellFirst:i,__lunoraUnrouted:u}=o.env;if(i===!0&&!await r(o.req.raw))return u?.(),o.text("404 Not Found",404);const c=o.notFound;o.notFound=()=>(_.add(o),c()),await a()});const n=e.notFound;return e.notFound=o=>n(a=>{const{__lunoraUnrouted:s}=a.env;return _.has(a)||s?.(),o(a)}),e.notFound(o=>o.text("404 Not Found",404)),e},P=e=>e.kind==="optional"?e._meta?.inner??e:e,b=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},re=(e,r,t)=>{const n=P(e);if(n.kind==="array"){const a=r.req.queries(t);if(a===void 0)return;const s=n._meta?.inner;return a.map(i=>b(s?.kind??"string",i))}const o=r.req.query(t);return o===void 0?void 0:b(n.kind,o)},j=(e,r)=>{const t={};for(const n of Object.keys(e)){const o=e[n];o&&(t[n]=re(o,r,n))}return v(e,t,"searchParams")},D=(e,r)=>{const t=r.req.param(),n={};for(const o of Object.keys(e)){const a=e[o];if(!a)continue;const s=t[o];n[o]=s===void 0?void 0:b(P(a).kind,s)}return v(e,n,"params")},te=async(e,r)=>{let t;try{t=await r.req.json()}catch{throw new f("BAD_REQUEST","Invalid JSON body")}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("BAD_REQUEST","Expected a JSON object body");return v(e,t,"body")},x=(e,r)=>{const{method:t}=r.req;if(!(t===e.method||e.method==="GET"&&t==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${t} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},oe=(e,r)=>async t=>{const n=x(e,t);if(n)return n;try{const o=t.get("lunora"),a=Object.keys(e.searchParams).length>0?j(e.searchParams,t):{},s=Object.keys(e.params).length>0?D(e.params,t):{},i=Object.keys(e.body).length>0?await te(e.body,t):{},u=await r({body:i,ctx:o,params:s,searchParams:a}),c=e.output?R(e.output,u):u,d={};e.cacheControl&&(d["cache-control"]=K(e,e.cacheControl,t)),e.cacheTag&&(d["cache-tag"]=e.cacheTag),e.vary&&(d.vary=e.vary);const y=Object.keys(d).length>0;return c===void 0?new Response(null,{headers:y?d:void 0,status:204}):Response.json(c,{headers:y?d:void 0})}catch(o){return g(o)}},we=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const t=new URL(e.url).searchParams.get("lastEventId");return t===null||t===""?void 0:t},q=Symbol.for("@lunora/server/sse-event"),Re=e=>({[q]:!0,data:e.data,id:e.id}),ne=e=>typeof e=="object"&&e!==null&&e[q]===!0,ae=(e,r)=>{if(ne(r)){if(!U(r.id))throw new f("INTERNAL","sseEvent id must not contain CR, LF or NUL");const t=e?R(e,r.data):r.data;return w(S(t),void 0,r.id)}return w(S(e?R(e,r):r))},se=(e,r)=>(async t=>{const n=x(e,t);if(n)return n;let o,a;try{o=Object.keys(e.searchParams).length>0?j(e.searchParams,t):{},a=Object.keys(e.params).length>0?D(e.params,t):{}}catch(p){return g(p)}const s=t.get("lunora"),i=t.req.raw,u=new TextEncoder,c=new AbortController;if(i.signal.aborted)return c.abort(),new Response("",{headers:A});const d=()=>{c.abort()};i.signal.addEventListener("abort",d,{once:!0});const y=new ReadableStream({cancel(){i.signal.removeEventListener("abort",d),c.abort()},async start(p){try{const E=r({ctx:s,params:a,request:i,searchParams:o,signal:c.signal});for await(const m of E){if(c.signal.aborted)break;p.enqueue(u.encode(ae(e.output,m)))}c.signal.aborted||p.enqueue(u.encode(w({},"complete")))}catch(E){const{body:m,redacted:F}=C(E,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});F&&console.error("[lunora] unhandled stream handler error:",E),c.signal.aborted||p.enqueue(u.encode(w({code:m.code,hint:m.hint,message:m.message,why:m.why},"error")))}finally{i.signal.removeEventListener("abort",d);try{p.close()}catch{}}}});return new Response(y,{headers:A})}),ce=e=>{const r=e?.find(t=>!T(t));if(r!==void 0)throw new f("INTERNAL",`httpRoute .cacheControl(): credentialHeaders entry ${JSON.stringify(r)} is not a header name`);return e},l=e=>({body:r=>l({...e,body:{...e.body,...r}}),cacheControl:(r,t)=>l({...e,cacheControl:r,credentialHeaders:ce(t?.credentialHeaders)}),cacheTag:r=>l({...e,cacheTag:r}),handler:r=>oe(e,r),output:r=>l({...e,output:r}),params:r=>l({...e,params:{...e.params,...r}}),searchParams:r=>l({...e,searchParams:{...e.searchParams,...r}}),stream:r=>se(e,r),vary:r=>l({...e,vary:r})}),h=e=>r=>l({body:{},method:e,params:{},path:r,searchParams:{}}),be={delete:h("DELETE"),get:h("GET"),head:h("HEAD"),options:h("OPTIONS"),patch:h("PATCH"),post:h("POST"),put:h("PUT")};export{fe as httpAction,be as httpRoute,Ee as httpRouter,ye as isHttpRouter,U as isSafeHeaderValue,we as lastEventId,Re as sseEvent};
|