@north-light/plugin 0.3.551 → 0.3.552
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/README.md +2 -0
- package/dist/define.d.ts +6 -0
- package/dist/serve.js +3 -3
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -130,6 +130,8 @@ With directory authentication, configure `createFetchHandler(plugin, { auth, rec
|
|
|
130
130
|
|
|
131
131
|
The kit holds no prices: the directory owns every price, maximum and allowance (set in the console or with `crtr cloud apps provider pricing`), and charges from the receipt's `units` or its reported cost. `ctx.meter` sets the receipt's `usd_equivalent` to the first of: the `usdEquivalent` you pass (a tool that reports its cost passes it); `units` × the price row of this request's `ctx.checkSpend()` answer whose `unit` matches, for a unit-priced tool; otherwise `0`. It never throws for a missing price. The figure is what the runtime shows as the call's cost; the directory recomputes the charge itself and never trusts it. `ReceiptOptions.rates` no longer exists: delete it when you upgrade (TypeScript flags it; a JavaScript config that still passes it is ignored).
|
|
132
132
|
|
|
133
|
+
`ctx.causedBy` is `request:<this request's Crtr-Request-Id>` (absent when the request carries none). A handler that calls a runtime itself passes it on, so the spend of those calls is traced to this call: `new Crouter({ causedBy: ctx.causedBy })`, or `causedBy` on `runs.start`.
|
|
134
|
+
|
|
133
135
|
`ctx.caller.payer` is the principal charged for the call, `user:<id>` or `app:<id>`: the token's `payer` claim, or `sub` when the token has none. `ctx.meter` stamps it on the receipt. Before a priced call, `await ctx.checkSpend()` asks the directory (`POST <auth.issuer>/v1/billing/check`, sending the request's outbound token) whether that payer may spend on this command (it posts `{ token, tool }`, `tool` being the command path above) and keeps the price rows it answers for `ctx.meter`; it reserves nothing and resolves with `{ prices }` (every row of the group's price, `[price]` when the directory answers only `price`, empty when unpriced). It needs `receipts.ledger: { clientId, privateKey, keyId? }`, the same credentials you pass to `postReceipt`, and throws a plain `Error` without them or without a verified caller. It resolves when the call may go ahead, throws `SpendRefusedError { code, message, next }` on a refusal (`payment_required` or `limit_reached`, with `next` the page that fixes it), and throws `ReceiptPostError` when the check cannot be completed. To refuse the call, rethrow it as `new LeafError({ code: e.code, message: e.message, status: 402, next: e.next })`.
|
|
134
136
|
|
|
135
137
|
To answer a rate limit, throw a `LeafError` with `retryAfter` (seconds, or a `Date`): `throw new LeafError({ code: 'rate_limited', status: 429, message: 'Slow down.', retryAfter: 30 })` answers 429 with `Retry-After: 30`. `headers: { 'X-RateLimit-Reset': '…' }` sets any other response header; `Content-Type`, `Content-Length`, `Content-Encoding`, `Transfer-Encoding` and `Crtr-Receipt` belong to the kit. For a side-effect leaf the kit passes the headers to `requests.store` as `answer.headers` (lowercase names); a store that keeps and returns them makes a repeated request answer with the same headers.
|
package/dist/define.d.ts
CHANGED
|
@@ -50,6 +50,12 @@ export interface LeafContext {
|
|
|
50
50
|
readonly request: Request;
|
|
51
51
|
/** The verified caller when the handler was created with `auth`; `undefined` under `token`. */
|
|
52
52
|
readonly caller?: LeafCaller;
|
|
53
|
+
/**
|
|
54
|
+
* The cause to put on this handler's own calls into a runtime: `request:<this request's Crtr-Request-Id>`. Pass it as
|
|
55
|
+
* `causedBy` when creating an SDK client (`new Crouter({ causedBy: ctx.causedBy })`) or to `runs.start`, so what the app
|
|
56
|
+
* spends on its own is traced to this call. Absent when the request carries no `Crtr-Request-Id`.
|
|
57
|
+
*/
|
|
58
|
+
readonly causedBy?: string;
|
|
53
59
|
/** Returns the runtime's approval choice or asks the runtime to obtain one. */
|
|
54
60
|
readonly approval: {
|
|
55
61
|
require(question: LeafErrorQuestion): Promise<string>;
|
package/dist/serve.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ee=Object.defineProperty;var s=(n,e)=>ee(n,"name",{value:e,configurable:!0});import{approvalFor as ne}from"./approval.js";import{requestSpendCheck as te}from"./receipts.js";import{validateDeclaredResult as re,validateValue as ie}from"@north-light/api/command-manifest";import{errorResponse as A,LeafError as T,leafErrorResponse as L,storedAnswerHeaders as oe}from"./errors.js";import{buildCommandManifest as ae}from"./manifest.js";import{buildBundle as de}from"./bundle.js";import{parseCrtrCaller as se}from"./caller.js";import{createCallerVerifier as ce,normalizeProviderId as ue,scopeMissing as fe}from"./verify.js";const V=/^v([1-9][0-9]*)$/;function Oe(n,e={}){if(e.token!==void 0&&e.auth!==void 0)throw new Error("createFetchHandler takes either token or auth, not both");if(e.token!==void 0&&e.receipts!==void 0)throw new Error("createFetchHandler cannot meter with a static token");if(e.receipts!==void 0&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(e.receipts.provider))throw new Error("createFetchHandler receipts.provider must be an app principal (app:<id>)");const i=e.auth===void 0?void 0:ue(e.auth),t=Array.isArray(n)||n.version!==void 0,r=me(Array.isArray(n)?n:[n],Array.isArray(n),i),d=r[0].plugin.name;for(const f of r)for(const y of f.commands.values())if(y.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${y.path.join(" ")}`);const c=e.auth===void 0?void 0:ce(e.auth);if(c!==void 0){for(const f of r)for(const y of f.commands.values())if(y.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${y.path.join(" ")} has none`)}const o=new Map,g=e.baseUrl===void 0?void 0:D(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${d} is serving without bearer authentication`);const m=s(async(f,y,z)=>{const u=`${y.version}\0${z}`;let l=o.get(u);if(l===void 0){const I=await de(y.plugin,{mountPath:z,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:I.tar,etag:I.etag},o.set(u,l)}const p={ETag:l.etag};return f.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:p}):new Response(new Uint8Array(l.tar).buffer,{headers:{...p,"Content-Type":"application/x-tar"}})},"archiveResponse");return async f=>{if(f.method!=="POST"&&e.token!==void 0&&!Y(f.headers.get("authorization")??"",`Bearer ${e.token}`))return A(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."});const y=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return m(f,h,g??D(y));const w=J(y),$=w[w.length-1],R=g??D(`/${w.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(v=>v.version)});const H=$===void 0?null:V.exec($),k=H===null?void 0:r.find(v=>v.version===Number(H[1]));return k===void 0?P():m(f,k,`${R}/v${k.version}`)}if(f.method!=="POST")return P();const z=performance.now();let u,l;const p=[];let I=[],F=!1,B=!1;const E=s(w=>{if(l!==void 0)try{e.onAnswer?.({...u===void 0?{}:{sub:u.sub,grantee:u.grantee,initiatingApp:u.initiatingApp,act:u.act,jti:u.jti,requestId:u.requestId,...u.runId===void 0?{}:{runId:u.runId}},...u===void 0&&b!==null&&b!==""?{requestId:b}:{},tool:l.path.slice(1).join(" "),status:w.status,durationMs:performance.now()-z,...p.length===0?{}:{receiptId:p[0].receipt_id},...p.length>1?{receiptIds:p.map($=>$.receipt_id)}:{},replayed:B})}catch{}return w},"answer");let b=f.headers.get("crtr-request-id");try{if(l=t?ge(r,y):we(h.commands,y),e.token!==void 0&&!Y(f.headers.get("authorization")??"",`Bearer ${e.token}`))return E(A(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."}));const w=c===void 0?void 0:await c(f);if(l===void 0)return P();if(w!==void 0&&!w.scope.includes(l.scope)){u=Object.freeze({...w,requestId:b??"",...f.headers.get("crtr-run-id")?{runId:f.headers.get("crtr-run-id")}:{}});const a=l.leaf.group,x=i===void 0&&a!==void 0?w.scope.find(j=>j.endsWith(`:${a}`)&&j.length>a.length+1)?.slice(0,-(a.length+1)):void 0;throw fe(l.scope,x)}if(w!==void 0){if(b===null||b==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const a=f.headers.get("crtr-run-id"),x=se(f.headers.get("crtr-caller"));u=Object.freeze({...w,requestId:b,...a!==null&&a!==""?{runId:a}:{},...Object.keys(x).length>0?{crtr:Object.freeze(x)}:{}})}const $=await ye(f,l.manifest,w!==void 0);if(l.leaf.sideEffect){if(b===null||b==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const a=u===void 0?null:{sub:u.sub,grantee:u.grantee};if(!await e.requests.record(b,a)){B=!0;const j=await he(e.requests,b,a,l.plugin.timeouts?.requestMs??3e4);if(j!==!0){const _=j.headers.get("Crtr-Receipt");if(_!==null)try{const C=JSON.parse(_);p.push(...Array.isArray(C)?C:[C])}catch{}return E(j)}B=!1}F=!0}const R=l,H={request:f,...u!==void 0?{caller:u}:{},approval:ne(f),meter(a){if(u===void 0)throw new Error("ctx.meter needs an authenticated caller");if(p.some(S=>S.unit===a.unit))throw new Error(`ctx.meter may be called only once for unit ${a.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const x=a.receiptId??u.requestId;if(p.some(S=>S.receipt_id===x))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${x} is taken`);const j=R.path.slice(1).join(" "),_=I.find(S=>S.mode==="unit"&&S.unit===a.unit),C=a.usdEquivalent??(_?.usd_per_unit!=null?a.units*_.usd_per_unit:0),G={receipt_id:x,provider:e.receipts.provider,tool:j,sub:u.sub,grantee:u.grantee,payer:u.payer,units:a.units,unit:a.unit,usd_equivalent:C,request_id:u.requestId,...u.runId!==void 0?{run_id:u.runId}:{},time:new Date().toISOString()};return p.push(G),G},async checkSpend(){if(u===void 0)throw new Error("ctx.checkSpend needs an authenticated caller");if(e.receipts===void 0)throw new Error("ctx.checkSpend needs receipts with a provider and outbox");if(e.receipts.ledger===void 0)throw new Error("ctx.checkSpend needs receipts.ledger (the provider's directory client credentials)");const a=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(a===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");return I=(await te(e.auth.issuer,a,R.path.slice(1).join(" "),e.receipts.ledger)).prices,{prices:I}}};let k,v;try{const a=await l.leaf.run($,H);k=l.leaf.streaming?await xe(a,e.onError,l.path):Ee(a,l.manifest)}catch(a){a instanceof T?(k=L(a),v=a.headers):(N(e.onError,a,l.path),k=M(a))}if(F&&k.status===403&&await le(k))return await e.requests.delete(b),E(W(k,p));try{if(F)await e.requests.store(b,{status:k.status,body:await k.clone().text(),...v!==void 0?{headers:{...v}}:{},...p.length>0?{receipt:p[0]}:{},...p.length>1?{receipts:[...p]}:{}});else if(p.length>0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${R.path.join(" ")}`);for(const a of p)await e.receipts.outbox.save(a)}}catch(a){return N(e.onError,a,l.path,p),E(M(a))}return E(W(k,p))}catch(w){return w instanceof T?E(L(w)):(N(e.onError,w,l?.path??[]),E(M(w)))}}}s(Oe,"createFetchHandler");function M(n){return A(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(M,"handlerFailed");function W(n,e){if(e.length===0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",Z(e)),new Response(n.body,{status:n.status,headers:i})}s(W,"responseWithReceipts");function Z(n){return JSON.stringify(n.length===1?n[0]:n)}s(Z,"receiptHeader");async function le(n){try{const e=await n.clone().json();return U(e)&&U(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(le,"isApprovalRequired");async function he(n,e,i,t){for(;;){const r=await n.read(e);if(r===null){if(await n.record(e,i))return!0;continue}if(r.identity?.sub!==i?.sub||r.identity?.grantee!==i?.grantee)return A(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const d=oe(r.answer.headers);d.set("Content-Type","application/json");const c=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return c.length>0&&d.set("Crtr-Receipt",Z(c)),new Response(r.answer.body,{status:r.answer.status,headers:d})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return M(new Error("The earlier request has no stored answer."));await new Promise(d=>setTimeout(d,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}s(he,"replay");function me(n,e,i){if(n.length===0)throw new Error("createFetchHandler needs at least one plugin definition");const t=n[0].name,r=new Map;for(const d of n){if(d.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${d.name}`);if(e&&d.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const c=d.version??1;if(r.has(c))throw new Error(`createFetchHandler got two definitions of ${t} major ${c}`);r.set(c,{version:c,plugin:d,commands:pe(d,i)})}return[...r.values()].sort((d,c)=>d.version-c.version)}s(me,"servedMajors");function pe(n,e){const t=ae(n,{mountPath:""}).mounts[0]?.node;if(t===void 0||t.kind!=="branch")throw new Error("Generated plugin manifest has no root branch");const r=new Map;return K(t.children,n.commands,[t.name],n,r,e),r}s(pe,"commandMap");function K(n,e,i,t,r,d){const c=Object.entries(e);if(n.length!==c.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[o,[g,h]]of c.entries()){const m=n[o];if(m===void 0||m.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${g}`);const f=[...i,m.name];if(m.kind==="branch"&&h.kind==="branch"){K(m.children,h.children,f,t,r,d);continue}if(m.kind==="leaf"&&h.kind==="leaf"){r.set(f.join("/"),{path:f,leaf:h,plugin:t,manifest:m,...h.group!==void 0?{scope:`${d??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${g}`)}}s(K,"collectCommands");function we(n,e){const i=J(e);for(let t=0;t<i.length;t+=1){const r=n.get(i.slice(t).join("/"));if(r!==void 0)return r}}s(we,"findCommand");function ge(n,e){const i=J(e);for(let t=i.length-2;t>=0;t-=1){const r=V.exec(i[t]);if(r===null)continue;const c=n.find(o=>o.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(c!==void 0)return c}}s(ge,"findVersionedCommand");function J(n){return n.split("/").filter(e=>e.length>0)}s(J,"pathSegments");async function ye(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const o=JSON.parse(t);if(!U(o))throw new Error("not an object");r=o}catch{throw q("Request body must be a JSON object.",i?"body":void 0,i,t)}const d=new Map(e.params.map(o=>[o.name,o]));for(const o of Object.keys(r))if(!d.has(o))throw i?q(`Unknown parameter ${o}.`,o,!0,r[o]):new T({code:"unknown_parameter",message:`Unknown parameter ${o}.`,field:o});const c={};for(const o of e.params){if(!Object.hasOwn(r,o.name)){if(o.required)throw q(`Missing required parameter ${o.name}.`,o.name,i,null);continue}const g=r[o.name];if(o.kind==="flag"&&o.type==="json"){const m=ie(o.shape,g,o.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,g);c[X(o.name)]=g;continue}const h=be(g,o);if(h===void 0)throw q(`Invalid value for parameter ${o.name}.`,o.name,i,g);c[X(o.name)]=h}return c}s(ye,"decodeInput");function be(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>Q(t,e));return i.some(t=>t===void 0)?void 0:i}return Q(n,e)}s(be,"decodeParameter");function Q(n,e){if(e.kind==="stdin"||e.kind==="positional")return typeof n=="string"?n:void 0;if(e.kind!=="context-file"){if(e.type==="string")return typeof n=="string"?n:void 0;if(e.type==="int")return typeof n=="number"&&Number.isInteger(n)?n:void 0;if(e.type==="bool")return typeof n=="boolean"?n:void 0;if(e.type==="enum")return typeof n=="string"&&Array.isArray(e.choices)&&e.choices.includes(n)?n:void 0;if(e.type==="file")return typeof n=="string"?n:void 0;if(e.type==="path")return typeof n!="string"?void 0:e.encoding==="base64"?ke(n):n}}s(Q,"decodeScalar");function ke(n){if(!(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0))try{const e=atob(n);return Uint8Array.from(e,i=>i.charCodeAt(0))}catch{return}}s(ke,"decodeBase64");function Ee(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw O("result")}if(!U(t))throw O("result");const r=re(e.output,t);if(r!==null)throw O(r.field,r.receivedType);for(const d of Object.keys(t))if(!e.output.some(c=>c.name===d))throw O(d);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(Ee,"resultResponse");async function xe(n,e,i){if(!je(n))throw O("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,d=await t.next();let c=d.done,o=c?void 0:r.encode(`${JSON.stringify(d.value)}
|
|
2
|
-
`);const
|
|
3
|
-
`))}catch(m){N(e,m,i),h.error(m)}},async cancel(h){await t.return?.(h)}});return new Response(
|
|
1
|
+
var ee=Object.defineProperty;var s=(n,e)=>ee(n,"name",{value:e,configurable:!0});import{approvalFor as ne}from"./approval.js";import{requestSpendCheck as te}from"./receipts.js";import{validateDeclaredResult as re,validateValue as ie}from"@north-light/api/command-manifest";import{errorResponse as A,LeafError as T,leafErrorResponse as L,storedAnswerHeaders as oe}from"./errors.js";import{buildCommandManifest as ae}from"./manifest.js";import{buildBundle as de}from"./bundle.js";import{parseCrtrCaller as se}from"./caller.js";import{createCallerVerifier as ce,normalizeProviderId as ue,scopeMissing as fe}from"./verify.js";const V=/^v([1-9][0-9]*)$/;function Oe(n,e={}){if(e.token!==void 0&&e.auth!==void 0)throw new Error("createFetchHandler takes either token or auth, not both");if(e.token!==void 0&&e.receipts!==void 0)throw new Error("createFetchHandler cannot meter with a static token");if(e.receipts!==void 0&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(e.receipts.provider))throw new Error("createFetchHandler receipts.provider must be an app principal (app:<id>)");const i=e.auth===void 0?void 0:ue(e.auth),t=Array.isArray(n)||n.version!==void 0,r=me(Array.isArray(n)?n:[n],Array.isArray(n),i),d=r[0].plugin.name;for(const f of r)for(const b of f.commands.values())if(b.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${b.path.join(" ")}`);const c=e.auth===void 0?void 0:ce(e.auth);if(c!==void 0){for(const f of r)for(const b of f.commands.values())if(b.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${b.path.join(" ")} has none`)}const o=new Map,y=e.baseUrl===void 0?void 0:D(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${d} is serving without bearer authentication`);const m=s(async(f,b,z)=>{const u=`${b.version}\0${z}`;let l=o.get(u);if(l===void 0){const I=await de(b.plugin,{mountPath:z,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:I.tar,etag:I.etag},o.set(u,l)}const p={ETag:l.etag};return f.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:p}):new Response(new Uint8Array(l.tar).buffer,{headers:{...p,"Content-Type":"application/x-tar"}})},"archiveResponse");return async f=>{if(f.method!=="POST"&&e.token!==void 0&&!Y(f.headers.get("authorization")??"",`Bearer ${e.token}`))return A(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."});const b=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return m(f,h,y??D(b));const w=J(b),j=w[w.length-1],R=y??D(`/${w.slice(0,-1).join("/")}`);if(j==="versions")return Response.json({latest:h.version,supported:r.map(v=>v.version)});const H=j===void 0?null:V.exec(j),k=H===null?void 0:r.find(v=>v.version===Number(H[1]));return k===void 0?P():m(f,k,`${R}/v${k.version}`)}if(f.method!=="POST")return P();const z=performance.now();let u,l;const p=[];let I=[],F=!1,B=!1;const E=s(w=>{if(l!==void 0)try{e.onAnswer?.({...u===void 0?{}:{sub:u.sub,grantee:u.grantee,initiatingApp:u.initiatingApp,act:u.act,jti:u.jti,requestId:u.requestId,...u.runId===void 0?{}:{runId:u.runId}},...u===void 0&&g!==null&&g!==""?{requestId:g}:{},tool:l.path.slice(1).join(" "),status:w.status,durationMs:performance.now()-z,...p.length===0?{}:{receiptId:p[0].receipt_id},...p.length>1?{receiptIds:p.map(j=>j.receipt_id)}:{},replayed:B})}catch{}return w},"answer");let g=f.headers.get("crtr-request-id");try{if(l=t?ge(r,b):we(h.commands,b),e.token!==void 0&&!Y(f.headers.get("authorization")??"",`Bearer ${e.token}`))return E(A(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."}));const w=c===void 0?void 0:await c(f);if(l===void 0)return P();if(w!==void 0&&!w.scope.includes(l.scope)){u=Object.freeze({...w,requestId:g??"",...f.headers.get("crtr-run-id")?{runId:f.headers.get("crtr-run-id")}:{}});const a=l.leaf.group,x=i===void 0&&a!==void 0?w.scope.find($=>$.endsWith(`:${a}`)&&$.length>a.length+1)?.slice(0,-(a.length+1)):void 0;throw fe(l.scope,x)}if(w!==void 0){if(g===null||g==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const a=f.headers.get("crtr-run-id"),x=se(f.headers.get("crtr-caller"));u=Object.freeze({...w,requestId:g,...a!==null&&a!==""?{runId:a}:{},...Object.keys(x).length>0?{crtr:Object.freeze(x)}:{}})}const j=await ye(f,l.manifest,w!==void 0);if(l.leaf.sideEffect){if(g===null||g==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const a=u===void 0?null:{sub:u.sub,grantee:u.grantee};if(!await e.requests.record(g,a)){B=!0;const $=await he(e.requests,g,a,l.plugin.timeouts?.requestMs??3e4);if($!==!0){const _=$.headers.get("Crtr-Receipt");if(_!==null)try{const C=JSON.parse(_);p.push(...Array.isArray(C)?C:[C])}catch{}return E($)}B=!1}F=!0}const R=l,H={request:f,...u!==void 0?{caller:u}:{},...g!==null&&g!==""?{causedBy:`request:${g}`}:{},approval:ne(f),meter(a){if(u===void 0)throw new Error("ctx.meter needs an authenticated caller");if(p.some(S=>S.unit===a.unit))throw new Error(`ctx.meter may be called only once for unit ${a.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const x=a.receiptId??u.requestId;if(p.some(S=>S.receipt_id===x))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${x} is taken`);const $=R.path.slice(1).join(" "),_=I.find(S=>S.mode==="unit"&&S.unit===a.unit),C=a.usdEquivalent??(_?.usd_per_unit!=null?a.units*_.usd_per_unit:0),G={receipt_id:x,provider:e.receipts.provider,tool:$,sub:u.sub,grantee:u.grantee,payer:u.payer,units:a.units,unit:a.unit,usd_equivalent:C,request_id:u.requestId,...u.runId!==void 0?{run_id:u.runId}:{},time:new Date().toISOString()};return p.push(G),G},async checkSpend(){if(u===void 0)throw new Error("ctx.checkSpend needs an authenticated caller");if(e.receipts===void 0)throw new Error("ctx.checkSpend needs receipts with a provider and outbox");if(e.receipts.ledger===void 0)throw new Error("ctx.checkSpend needs receipts.ledger (the provider's directory client credentials)");const a=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(a===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");return I=(await te(e.auth.issuer,a,R.path.slice(1).join(" "),e.receipts.ledger)).prices,{prices:I}}};let k,v;try{const a=await l.leaf.run(j,H);k=l.leaf.streaming?await xe(a,e.onError,l.path):Ee(a,l.manifest)}catch(a){a instanceof T?(k=L(a),v=a.headers):(N(e.onError,a,l.path),k=M(a))}if(F&&k.status===403&&await le(k))return await e.requests.delete(g),E(W(k,p));try{if(F)await e.requests.store(g,{status:k.status,body:await k.clone().text(),...v!==void 0?{headers:{...v}}:{},...p.length>0?{receipt:p[0]}:{},...p.length>1?{receipts:[...p]}:{}});else if(p.length>0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${R.path.join(" ")}`);for(const a of p)await e.receipts.outbox.save(a)}}catch(a){return N(e.onError,a,l.path,p),E(M(a))}return E(W(k,p))}catch(w){return w instanceof T?E(L(w)):(N(e.onError,w,l?.path??[]),E(M(w)))}}}s(Oe,"createFetchHandler");function M(n){return A(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(M,"handlerFailed");function W(n,e){if(e.length===0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",Z(e)),new Response(n.body,{status:n.status,headers:i})}s(W,"responseWithReceipts");function Z(n){return JSON.stringify(n.length===1?n[0]:n)}s(Z,"receiptHeader");async function le(n){try{const e=await n.clone().json();return U(e)&&U(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(le,"isApprovalRequired");async function he(n,e,i,t){for(;;){const r=await n.read(e);if(r===null){if(await n.record(e,i))return!0;continue}if(r.identity?.sub!==i?.sub||r.identity?.grantee!==i?.grantee)return A(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const d=oe(r.answer.headers);d.set("Content-Type","application/json");const c=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return c.length>0&&d.set("Crtr-Receipt",Z(c)),new Response(r.answer.body,{status:r.answer.status,headers:d})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return M(new Error("The earlier request has no stored answer."));await new Promise(d=>setTimeout(d,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}s(he,"replay");function me(n,e,i){if(n.length===0)throw new Error("createFetchHandler needs at least one plugin definition");const t=n[0].name,r=new Map;for(const d of n){if(d.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${d.name}`);if(e&&d.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const c=d.version??1;if(r.has(c))throw new Error(`createFetchHandler got two definitions of ${t} major ${c}`);r.set(c,{version:c,plugin:d,commands:pe(d,i)})}return[...r.values()].sort((d,c)=>d.version-c.version)}s(me,"servedMajors");function pe(n,e){const t=ae(n,{mountPath:""}).mounts[0]?.node;if(t===void 0||t.kind!=="branch")throw new Error("Generated plugin manifest has no root branch");const r=new Map;return K(t.children,n.commands,[t.name],n,r,e),r}s(pe,"commandMap");function K(n,e,i,t,r,d){const c=Object.entries(e);if(n.length!==c.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[o,[y,h]]of c.entries()){const m=n[o];if(m===void 0||m.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${y}`);const f=[...i,m.name];if(m.kind==="branch"&&h.kind==="branch"){K(m.children,h.children,f,t,r,d);continue}if(m.kind==="leaf"&&h.kind==="leaf"){r.set(f.join("/"),{path:f,leaf:h,plugin:t,manifest:m,...h.group!==void 0?{scope:`${d??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${y}`)}}s(K,"collectCommands");function we(n,e){const i=J(e);for(let t=0;t<i.length;t+=1){const r=n.get(i.slice(t).join("/"));if(r!==void 0)return r}}s(we,"findCommand");function ge(n,e){const i=J(e);for(let t=i.length-2;t>=0;t-=1){const r=V.exec(i[t]);if(r===null)continue;const c=n.find(o=>o.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(c!==void 0)return c}}s(ge,"findVersionedCommand");function J(n){return n.split("/").filter(e=>e.length>0)}s(J,"pathSegments");async function ye(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const o=JSON.parse(t);if(!U(o))throw new Error("not an object");r=o}catch{throw q("Request body must be a JSON object.",i?"body":void 0,i,t)}const d=new Map(e.params.map(o=>[o.name,o]));for(const o of Object.keys(r))if(!d.has(o))throw i?q(`Unknown parameter ${o}.`,o,!0,r[o]):new T({code:"unknown_parameter",message:`Unknown parameter ${o}.`,field:o});const c={};for(const o of e.params){if(!Object.hasOwn(r,o.name)){if(o.required)throw q(`Missing required parameter ${o.name}.`,o.name,i,null);continue}const y=r[o.name];if(o.kind==="flag"&&o.type==="json"){const m=ie(o.shape,y,o.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,y);c[X(o.name)]=y;continue}const h=be(y,o);if(h===void 0)throw q(`Invalid value for parameter ${o.name}.`,o.name,i,y);c[X(o.name)]=h}return c}s(ye,"decodeInput");function be(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>Q(t,e));return i.some(t=>t===void 0)?void 0:i}return Q(n,e)}s(be,"decodeParameter");function Q(n,e){if(e.kind==="stdin"||e.kind==="positional")return typeof n=="string"?n:void 0;if(e.kind!=="context-file"){if(e.type==="string")return typeof n=="string"?n:void 0;if(e.type==="int")return typeof n=="number"&&Number.isInteger(n)?n:void 0;if(e.type==="bool")return typeof n=="boolean"?n:void 0;if(e.type==="enum")return typeof n=="string"&&Array.isArray(e.choices)&&e.choices.includes(n)?n:void 0;if(e.type==="file")return typeof n=="string"?n:void 0;if(e.type==="path")return typeof n!="string"?void 0:e.encoding==="base64"?ke(n):n}}s(Q,"decodeScalar");function ke(n){if(!(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0))try{const e=atob(n);return Uint8Array.from(e,i=>i.charCodeAt(0))}catch{return}}s(ke,"decodeBase64");function Ee(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw O("result")}if(!U(t))throw O("result");const r=re(e.output,t);if(r!==null)throw O(r.field,r.receivedType);for(const d of Object.keys(t))if(!e.output.some(c=>c.name===d))throw O(d);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(Ee,"resultResponse");async function xe(n,e,i){if(!$e(n))throw O("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,d=await t.next();let c=d.done,o=c?void 0:r.encode(`${JSON.stringify(d.value)}
|
|
2
|
+
`);const y=new ReadableStream({async pull(h){if(o!==void 0){h.enqueue(o),o=void 0;return}if(c){h.close();return}try{const m=await t.next();m.done?(c=!0,h.close()):h.enqueue(r.encode(`${JSON.stringify(m.value)}
|
|
3
|
+
`))}catch(m){N(e,m,i),h.error(m)}},async cancel(h){await t.return?.(h)}});return new Response(y,{headers:{"Content-Type":"application/x-ndjson"}})}s(xe,"streamResponse");function N(n,e,i,t=[]){try{t.length>1?n?.(e,i,t[0],t):n?.(e,i,t[0])}catch{}}s(N,"reportUnhandledError");function O(n,e){return new T({code:"handler_output_invalid",message:`Handler returned an invalid value for ${n}.`,status:500,field:n,...e!==void 0?{received:e}:{}})}s(O,"outputInvalid");function q(n,e,i=!1,t){return new T({code:i?"invalid_argument":"invalid_input",message:n,...e!==void 0?{field:e}:{},...i?{received:t}:{}})}s(q,"invalidInput");function P(){return A(404,{code:"no_such_command",message:"No command matches this request."})}s(P,"noSuchCommand");function D(n){return n==="/"?"":n.replace(/\/+$/,"")}s(D,"mountPath");function X(n){return n.replace(/-([a-z])/g,(e,i)=>i.toUpperCase())}s(X,"camel");function Y(n,e){const i=new TextEncoder().encode(n),t=new TextEncoder().encode(e);let r=i.length^t.length;for(let d=0;d<Math.min(i.length,t.length);d+=1)r|=i[d]^t[d];return r===0}s(Y,"constantTimeEqual");function U(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(U,"isRecord");function $e(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}s($e,"isAsyncIterable");export{Oe as createFetchHandler};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.552",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.552",
|
|
31
|
+
"@north-light/identity": "0.3.552"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|