@north-light/plugin 0.3.598 → 0.3.599

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 CHANGED
@@ -132,7 +132,7 @@ The kit holds no prices: the directory owns every price, maximum and allowance (
132
132
 
133
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
134
 
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 })`.
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 and the admission it answers for `ctx.meter`; it reserves nothing and resolves with `{ status, admission_id, funding, prices }` (`prices` is every row of the group's price, `[price]` when the directory answers only `price`, empty when unpriced; `admission_id` is the directory's id for this funding decision, `null` when nothing is charging; `funding` is who pays: `trial`, `person`, `team` or `app`). After a check, `ctx.meter` stamps `admission_id` on every receipt it builds, so the ledger settles the work under that admission. Work that finishes in a later request (a long run) must save the check's `admission_id` itself and set it on the receipt it builds then. 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, details }` on a refusal (`payment_required` or `limit_reached`, with `next` the page that fixes it and `details` the directory's whole `error.details`, which carries the structured `payment` refusal), 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, ...(e.details !== null ? { details: e.details } : {}) })`; `LeafError`'s optional `details` object is serialized as `error.details`.
136
136
 
137
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.
138
138
 
package/dist/define.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { CrtrCaller } from './caller.js';
2
2
  import type { OutField, Output } from './fields.js';
3
3
  import type { LeafErrorQuestion } from './errors.js';
4
- import type { Receipt, SpendPrice } from './receipts.js';
4
+ import type { Receipt, SpendCheckAnswer } from './receipts.js';
5
5
  import type { AnyParam, Input } from './params.js';
6
6
  /** Thrown by `definePlugin` when a declaration is malformed, before anything is served. */
7
7
  export declare class PluginDefinitionError extends Error {
@@ -77,14 +77,14 @@ export interface LeafContext {
77
77
  }) => Receipt;
78
78
  /**
79
79
  * Asks the directory, before a priced call, whether `caller.payer` may spend on this command
80
- * (it sends the command path after the plugin name as `tool`). Resolves with the group's price
81
- * rows (`prices`, empty when unpriced) and reserves nothing; keeps them for `ctx.meter`. Throws `SpendRefusedError` when the directory refuses (HTTP 402) and
80
+ * (it sends the command path after the plugin name as `tool`). Resolves with the answer: the group's price
81
+ * rows (`prices`, empty when unpriced), the directory's `admission_id` (null when nothing is charging) and `funding`. It reserves nothing; the
82
+ * kit keeps the prices and the admission for `ctx.meter`, which stamps `admission_id` on every receipt it builds afterwards. A receipt for work
83
+ * finished in a later request (a run's settlement) carries the id the leaf saved from the original check. Throws `SpendRefusedError` when the directory refuses (HTTP 402) and
82
84
  * `ReceiptPostError` when the check cannot be completed. Throws an `Error` when the leaf has no
83
85
  * verified caller or the handler has no `receipts` (with `receipts.ledger`).
84
86
  */
85
- readonly checkSpend: () => Promise<{
86
- readonly prices: readonly SpendPrice[];
87
- }>;
87
+ readonly checkSpend: () => Promise<SpendCheckAnswer>;
88
88
  }
89
89
  /** One command an agent can invoke, as returned by `defineLeaf` or `defineStreamingLeaf`. */
90
90
  export interface LeafNode {
package/dist/errors.d.ts CHANGED
@@ -22,6 +22,8 @@ export interface LeafErrorOptions {
22
22
  readonly next?: string;
23
23
  /** The value that was rejected. */
24
24
  readonly received?: unknown;
25
+ /** A JSON object serialized as `error.details`, for structured data the caller reads by key (a rethrown 402 passes `SpendRefusedError.details` here unchanged). */
26
+ readonly details?: Readonly<Record<string, unknown>>;
25
27
  /** Tells crtr to refetch the archive and replay the command once. */
26
28
  readonly manifestStale?: true;
27
29
  /** The question an `approval_required` error asks the user, serialized in the error body. */
@@ -61,6 +63,8 @@ export declare class LeafError extends Error {
61
63
  readonly next?: string;
62
64
  /** The value that was rejected. */
63
65
  readonly received?: unknown;
66
+ /** The object serialized as `error.details`. */
67
+ readonly details?: Readonly<Record<string, unknown>>;
64
68
  /** Tells crtr to refetch the archive and replay the command once. */
65
69
  readonly manifestStale?: true;
66
70
  /** The question an `approval_required` error asks the user. */
@@ -87,6 +91,7 @@ export declare function errorResponse(status: number, error: {
87
91
  readonly field?: string;
88
92
  readonly next?: string;
89
93
  readonly received?: unknown;
94
+ readonly details?: Readonly<Record<string, unknown>>;
90
95
  readonly manifest_stale?: true;
91
96
  readonly question?: LeafErrorQuestion;
92
97
  }, extraHeaders?: Readonly<Record<string, string>>): Response;
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- var f=Object.defineProperty;var n=(r,e)=>f(r,"name",{value:e,configurable:!0});import{PluginDefinitionError as d}from"./define.js";const c=/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/,u=new Set(["internal","unknown_path","command_collision","cli_protocol_error"]),l=new Set(["unauthorized","scope_missing","approval_required"]),h=403,o=new Set(["content-type","content-length","content-encoding","transfer-encoding","crtr-receipt"]);class E extends Error{static{n(this,"LeafError")}status;field;next;received;manifestStale;question;constructor(e){if(!c.test(e.code)||u.has(e.code))throw new Error(`LeafError code ${JSON.stringify(e.code)} must be lowercase snake_case and must not be reserved`);if(l.has(e.code)&&!i)throw new d(`LeafError code ${e.code} is emitted only by the kit's own helpers; a leaf cannot throw it`);if(e.question!==void 0&&e.code!=="approval_required")throw new Error(`LeafError question is only valid on approval_required, not ${e.code}`);if(e.status!==void 0&&(!Number.isInteger(e.status)||e.status<400||e.status>599))throw new Error("LeafError status must be an integer from 400 through 599");const t=w(e);super(e.message),this.name="LeafError",Object.defineProperty(this,"code",{value:e.code,enumerable:!0,writable:!1,configurable:!1}),this.status=e.code==="provider_refused"?h:e.status??400,this.field=e.field,this.next=e.next,this.received=e.received,this.manifestStale=e.manifestStale,this.question=e.question,Object.defineProperty(this,"headers",{value:t,enumerable:!0,writable:!1,configurable:!1})}}function w(r){const e=Object.create(null);for(const[t,a]of Object.entries(r.headers??{})){const s=t.toLowerCase();if(o.has(s))throw new Error(`LeafError headers cannot set ${t}; the kit owns it`);if(s in e)throw new Error(`LeafError headers names ${t} twice`);if(typeof a!="string")throw new Error(`LeafError header ${t} must be a string`);try{new Headers({[s]:a})}catch{throw new Error(`LeafError header ${JSON.stringify(t)} is not a valid header`)}e[s]=a}if(r.retryAfter!==void 0){if("retry-after"in e)throw new Error("LeafError sets Retry-After through both retryAfter and headers");const{retryAfter:t}=r;if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Error("LeafError retryAfter must be a valid Date");e["retry-after"]=t.toUTCString()}else if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=0)e["retry-after"]=String(t);else throw new Error("LeafError retryAfter must be a non-negative integer number of seconds or a Date")}return Object.keys(e).length===0?void 0:Object.freeze(e)}n(w,"resolveHeaders");let i=!1;function b(r){i=!0;try{return new E(r)}finally{i=!1}}n(b,"kitLeafError");function _(r){const e=new Headers;if(typeof r!="object"||r===null)return e;for(const[t,a]of Object.entries(r))if(!(typeof a!="string"||o.has(t.toLowerCase())))try{e.set(t,a)}catch{}return e}n(_,"storedAnswerHeaders");function v(r){return m(r.status,{code:r.code,message:r.message,...r.field!==void 0?{field:r.field}:{},...r.next!==void 0?{next:r.next}:{},...r.received!==void 0?{received:r.received}:{},...r.manifestStale===!0?{manifest_stale:!0}:{},...r.question!==void 0?{question:r.question}:{}},r.headers)}n(v,"leafErrorResponse");function m(r,e,t){return new Response(JSON.stringify({error:e}),{status:r,headers:{...t,"Content-Type":"application/json"}})}n(m,"errorResponse");export{E as LeafError,m as errorResponse,b as kitLeafError,v as leafErrorResponse,_ as storedAnswerHeaders};
1
+ var o=Object.defineProperty;var n=(t,e)=>o(t,"name",{value:e,configurable:!0});import{PluginDefinitionError as d}from"./define.js";const c=/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/,u=new Set(["internal","unknown_path","command_collision","cli_protocol_error"]),l=new Set(["unauthorized","scope_missing","approval_required"]),h=403,f=new Set(["content-type","content-length","content-encoding","transfer-encoding","crtr-receipt"]);class E extends Error{static{n(this,"LeafError")}status;field;next;received;details;manifestStale;question;constructor(e){if(!c.test(e.code)||u.has(e.code))throw new Error(`LeafError code ${JSON.stringify(e.code)} must be lowercase snake_case and must not be reserved`);if(l.has(e.code)&&!i)throw new d(`LeafError code ${e.code} is emitted only by the kit's own helpers; a leaf cannot throw it`);if(e.question!==void 0&&e.code!=="approval_required")throw new Error(`LeafError question is only valid on approval_required, not ${e.code}`);if(e.status!==void 0&&(!Number.isInteger(e.status)||e.status<400||e.status>599))throw new Error("LeafError status must be an integer from 400 through 599");const r=w(e);super(e.message),this.name="LeafError",Object.defineProperty(this,"code",{value:e.code,enumerable:!0,writable:!1,configurable:!1}),this.status=e.code==="provider_refused"?h:e.status??400,this.field=e.field,this.next=e.next,this.received=e.received,this.details=e.details,this.manifestStale=e.manifestStale,this.question=e.question,Object.defineProperty(this,"headers",{value:r,enumerable:!0,writable:!1,configurable:!1})}}function w(t){const e=Object.create(null);for(const[r,a]of Object.entries(t.headers??{})){const s=r.toLowerCase();if(f.has(s))throw new Error(`LeafError headers cannot set ${r}; the kit owns it`);if(s in e)throw new Error(`LeafError headers names ${r} twice`);if(typeof a!="string")throw new Error(`LeafError header ${r} must be a string`);try{new Headers({[s]:a})}catch{throw new Error(`LeafError header ${JSON.stringify(r)} is not a valid header`)}e[s]=a}if(t.retryAfter!==void 0){if("retry-after"in e)throw new Error("LeafError sets Retry-After through both retryAfter and headers");const{retryAfter:r}=t;if(r instanceof Date){if(Number.isNaN(r.getTime()))throw new Error("LeafError retryAfter must be a valid Date");e["retry-after"]=r.toUTCString()}else if(typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)e["retry-after"]=String(r);else throw new Error("LeafError retryAfter must be a non-negative integer number of seconds or a Date")}return Object.keys(e).length===0?void 0:Object.freeze(e)}n(w,"resolveHeaders");let i=!1;function b(t){i=!0;try{return new E(t)}finally{i=!1}}n(b,"kitLeafError");function _(t){const e=new Headers;if(typeof t!="object"||t===null)return e;for(const[r,a]of Object.entries(t))if(!(typeof a!="string"||f.has(r.toLowerCase())))try{e.set(r,a)}catch{}return e}n(_,"storedAnswerHeaders");function v(t){return m(t.status,{code:t.code,message:t.message,...t.field!==void 0?{field:t.field}:{},...t.next!==void 0?{next:t.next}:{},...t.received!==void 0?{received:t.received}:{},...t.details!==void 0?{details:t.details}:{},...t.manifestStale===!0?{manifest_stale:!0}:{},...t.question!==void 0?{question:t.question}:{}},t.headers)}n(v,"leafErrorResponse");function m(t,e,r){return new Response(JSON.stringify({error:e}),{status:t,headers:{...r,"Content-Type":"application/json"}})}n(m,"errorResponse");export{E as LeafError,m as errorResponse,b as kitLeafError,v as leafErrorResponse,_ as storedAnswerHeaders};
@@ -11,6 +11,8 @@ export interface Receipt {
11
11
  readonly usd_equivalent: number;
12
12
  readonly request_id: string;
13
13
  readonly run_id?: string;
14
+ /** The directory's admission for the spend check that allowed this call; absent when no priced check ran. Work finished later (a run's settlement) carries the original check's id. */
15
+ readonly admission_id?: string;
14
16
  readonly time: string;
15
17
  }
16
18
  export interface ReceiptOutbox {
@@ -48,6 +50,10 @@ export interface SpendPrice {
48
50
  /** The directory's answer to a spend check that allowed the call. */
49
51
  export interface SpendCheckAnswer {
50
52
  readonly status: string;
53
+ /** The directory's admission for this check: set whenever the call is priced, `null` when nothing is charging (or the directory predates admissions). */
54
+ readonly admission_id: string | null;
55
+ /** Who funds the call (`trial`, `person`, `team` or `app`); `null` when the directory does not say. */
56
+ readonly funding: string | null;
51
57
  /** Every price row of the tool's group: empty when the group is unpriced, `[price]` when the answer carries only `price`. */
52
58
  readonly prices: readonly SpendPrice[];
53
59
  /** Present when the tool's group has exactly one price row. */
@@ -69,13 +75,16 @@ export declare class ReceiptPostError extends Error {
69
75
  }
70
76
  /**
71
77
  * Thrown by `ctx.checkSpend()` when the directory refuses a priced call (HTTP 402). `code` is the
72
- * directory's (`payment_required` or `limit_reached`); `message` is written for the person, and
73
- * `next` is the page that fixes it. Pass all three through unchanged, as a `LeafError` with status 402.
78
+ * directory's (`payment_required` or `limit_reached`); `message` is written for the person, `next`
79
+ * is the page that fixes it, and `details` is the directory's whole `error.details` object (`null`
80
+ * when it sent none), including its structured `payment` refusal. Pass all of them through
81
+ * unchanged, as a `LeafError` with status 402.
74
82
  */
75
83
  export declare class SpendRefusedError extends Error {
76
84
  readonly code: string;
77
85
  readonly next: string;
78
- constructor(code: string, message: string, next: string);
86
+ readonly details: Readonly<Record<string, unknown>> | null;
87
+ constructor(code: string, message: string, next: string, details?: Readonly<Record<string, unknown>> | null);
79
88
  }
80
89
  /** Post one saved receipt; the provider owns durable retry and permanent-error reporting. */
81
90
  export declare function postReceipt(receipt: Receipt, ledger: {
package/dist/receipts.js CHANGED
@@ -1 +1 @@
1
- var b=Object.defineProperty;var c=(t,e)=>b(t,"name",{value:e,configurable:!0});class u extends Error{static{c(this,"ReceiptPostError")}permanent;status;rejection;constructor(e,r,o,n){super(e),this.permanent=r,this.status=o,this.rejection=n,this.name="ReceiptPostError"}}class A extends Error{static{c(this,"SpendRefusedError")}code;next;constructor(e,r,o){super(r),this.code=e,this.next=o,this.name="SpendRefusedError"}}async function O(t,e){const r=await _(e);let o;try{o=await fetch(e.url,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(n){throw new u(`Could not post receipt: ${String(n)}`,!1)}if(!o.ok)throw new u(`Ledger receipt request failed: HTTP ${o.status}`,w(o.status),o.status,await P(o))}c(O,"postReceipt");const T=8192,x=2e3;async function P(t){const e=t.body?.getReader();if(e===void 0)return;let r;const o=new Promise((d,l)=>{r=setTimeout(()=>l(new Error("timed out")),x)});o.catch(()=>{});let n;try{const d=new TextDecoder;let l="",f=0;for(;;){const{done:y,value:h}=await Promise.race([e.read(),o]);if(y)break;if(f+=h.byteLength,f>T)return;l+=d.decode(h,{stream:!0})}n=JSON.parse(l+d.decode()).error}catch{return}finally{clearTimeout(r),e.cancel().catch(()=>{})}if(typeof n!="object"||n===null)return;const i=c(d=>typeof d=="string"?d.slice(0,500):void 0,"field"),a={code:i(n.code),message:i(n.message),param:i(n.param),request_id:i(n.request_id)},s=Object.fromEntries(Object.entries(a).filter(([,d])=>d!==void 0));return Object.keys(s).length===0?void 0:s}c(P,"readRejection");async function _(t,e){const r=new URL("/token",t.url),o=await j(t,r.href);let n;try{n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:o}),...e===void 0?{}:{signal:e}})}catch(a){throw new u(`Could not obtain a ledger token: ${String(a)}`,!1)}if(!n.ok)throw new u(`Ledger token request failed: HTTP ${n.status}`,w(n.status),n.status);let i;try{i=(await n.json()).access_token}catch{throw new u("Ledger token response was not JSON",!1)}if(typeof i!="string"||i.length===0)throw new u("Ledger token response has no access_token",!1);return i}c(_,"ledgerToken");async function I(t,e,r,o){const n=AbortSignal.timeout(1e4),i=await _({...o,url:t},n);let a;try{a=await fetch(`${t.replace(/\/+$/,"")}/v1/billing/check`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({token:e,tool:r}),signal:n})}catch(s){throw new u(`Could not reach the billing check: ${String(s)}`,!1)}if(a.ok)return R(await a.json().catch(()=>{}));if(a.status===402){let s;try{s=(await a.json()).error}catch{}throw typeof s?.code=="string"&&typeof s.message=="string"?new A(s.code,s.message,typeof s.details?.next=="string"?s.details.next:""):new u("Billing check answered 402 without a code and message",!0,402)}throw new u(`Billing check request failed: HTTP ${a.status}`,w(a.status),a.status)}c(I,"requestSpendCheck");function R(t){const e=typeof t=="object"&&t!==null?t:{},r=typeof e.status=="string"?e.status:"ok",n=(Array.isArray(e.prices)?e.prices:[e.price]).flatMap(i=>C(i)??[]);return{status:r,prices:n,...n.length===1?{price:n[0]}:{}}}c(R,"parseSpendAnswer");function C(t){const e=t;if(!(typeof e!="object"||e===null||typeof e.max_usd_per_call!="number")){if(e.mode==="reported")return{mode:"reported",unit:null,usd_per_unit:null,max_usd_per_call:e.max_usd_per_call};if(e.mode==="unit"&&typeof e.unit=="string"&&typeof e.usd_per_unit=="number"&&Number.isFinite(e.usd_per_unit)&&e.usd_per_unit>=0)return{mode:"unit",unit:e.unit,usd_per_unit:e.usd_per_unit,max_usd_per_call:e.max_usd_per_call}}}c(C,"parseSpendPrice");async function j(t,e){const{privateKey:r}=t,o=typeof r=="string";let n=!o&&r.kty==="RSA"?"RS256":"ES256";if(!o&&r.kty!=="RSA"&&r.kty!=="EC")throw new u("Ledger private key must be an ES256 or RS256 PEM or JWK",!0);const i={name:"ECDSA",namedCurve:"P-256"},a={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"};let s;try{if(o){const p=/^-----BEGIN PRIVATE KEY-----\s*([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----\s*$/.exec(r);if(!p)throw new Error("Expected a PKCS#8 PEM private key");const g=Uint8Array.from(atob(p[1].replace(/\s/g,"")),E=>E.charCodeAt(0));try{s=await crypto.subtle.importKey("pkcs8",g,i,!1,["sign"])}catch{n="RS256",s=await crypto.subtle.importKey("pkcs8",g,a,!1,["sign"])}}else{if(r.alg!==void 0&&r.alg!==n)throw new Error(`JWK alg must be ${n}`);s=await crypto.subtle.importKey("jwk",r,n==="ES256"?i:a,!1,["sign"])}}catch(p){throw new u(`Invalid ledger private key: ${String(p)}`,!0)}const d=Math.floor(Date.now()/1e3),l=c(p=>S(new TextEncoder().encode(JSON.stringify(p))),"encode"),f=t.keyId??(o?void 0:r.kid),y=l({alg:n,typ:"JWT",...f?{kid:f}:{}}),h=l({iss:t.clientId,sub:t.clientId,aud:e,iat:d,exp:d+60,jti:crypto.randomUUID()}),m=`${y}.${h}`,k=await crypto.subtle.sign(n==="ES256"?{name:"ECDSA",hash:"SHA-256"}:"RSASSA-PKCS1-v1_5",s,new TextEncoder().encode(m));return`${m}.${S(new Uint8Array(k))}`}c(j,"clientAssertion");function S(t){let e="";for(const r of t)e+=String.fromCharCode(r);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}c(S,"base64url");function w(t){return t>=400&&t<500&&t!==408&&t!==429}c(w,"isPermanent");export{u as ReceiptPostError,A as SpendRefusedError,O as postReceipt,I as requestSpendCheck};
1
+ var b=Object.defineProperty;var d=(n,e)=>b(n,"name",{value:e,configurable:!0});class u extends Error{static{d(this,"ReceiptPostError")}permanent;status;rejection;constructor(e,r,s,t){super(e),this.permanent=r,this.status=s,this.rejection=t,this.name="ReceiptPostError"}}class A extends Error{static{d(this,"SpendRefusedError")}code;next;details;constructor(e,r,s,t=null){super(r),this.code=e,this.next=s,this.details=t,this.name="SpendRefusedError"}}async function O(n,e){const r=await _(e);let s;try{s=await fetch(e.url,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n)})}catch(t){throw new u(`Could not post receipt: ${String(t)}`,!1)}if(!s.ok)throw new u(`Ledger receipt request failed: HTTP ${s.status}`,w(s.status),s.status,await P(s))}d(O,"postReceipt");const T=8192,x=2e3;async function P(n){const e=n.body?.getReader();if(e===void 0)return;let r;const s=new Promise((c,l)=>{r=setTimeout(()=>l(new Error("timed out")),x)});s.catch(()=>{});let t;try{const c=new TextDecoder;let l="",f=0;for(;;){const{done:y,value:h}=await Promise.race([e.read(),s]);if(y)break;if(f+=h.byteLength,f>T)return;l+=c.decode(h,{stream:!0})}t=JSON.parse(l+c.decode()).error}catch{return}finally{clearTimeout(r),e.cancel().catch(()=>{})}if(typeof t!="object"||t===null)return;const a=d(c=>typeof c=="string"?c.slice(0,500):void 0,"field"),i={code:a(t.code),message:a(t.message),param:a(t.param),request_id:a(t.request_id)},o=Object.fromEntries(Object.entries(i).filter(([,c])=>c!==void 0));return Object.keys(o).length===0?void 0:o}d(P,"readRejection");async function _(n,e){const r=new URL("/token",n.url),s=await C(n,r.href);let t;try{t=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:n.clientId,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:s}),...e===void 0?{}:{signal:e}})}catch(i){throw new u(`Could not obtain a ledger token: ${String(i)}`,!1)}if(!t.ok)throw new u(`Ledger token request failed: HTTP ${t.status}`,w(t.status),t.status);let a;try{a=(await t.json()).access_token}catch{throw new u("Ledger token response was not JSON",!1)}if(typeof a!="string"||a.length===0)throw new u("Ledger token response has no access_token",!1);return a}d(_,"ledgerToken");async function I(n,e,r,s){const t=AbortSignal.timeout(1e4),a=await _({...s,url:n},t);let i;try{i=await fetch(`${n.replace(/\/+$/,"")}/v1/billing/check`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({token:e,tool:r}),signal:t})}catch(o){throw new u(`Could not reach the billing check: ${String(o)}`,!1)}if(i.ok)return R(await i.json().catch(()=>{}));if(i.status===402){let o;try{o=(await i.json()).error}catch{}if(typeof o?.code=="string"&&typeof o.message=="string"){const c=typeof o.details=="object"&&o.details!==null&&!Array.isArray(o.details)?o.details:null;throw new A(o.code,o.message,typeof c?.next=="string"?c.next:"",c)}throw new u("Billing check answered 402 without a code and message",!0,402)}throw new u(`Billing check request failed: HTTP ${i.status}`,w(i.status),i.status)}d(I,"requestSpendCheck");function R(n){const e=typeof n=="object"&&n!==null?n:{},r=typeof e.status=="string"?e.status:"ok",t=(Array.isArray(e.prices)?e.prices:[e.price]).flatMap(o=>j(o)??[]),a=typeof e.admission_id=="string"&&e.admission_id!==""?e.admission_id:null,i=typeof e.funding=="string"?e.funding:null;return{status:r,admission_id:a,funding:i,prices:t,...t.length===1?{price:t[0]}:{}}}d(R,"parseSpendAnswer");function j(n){const e=n;if(!(typeof e!="object"||e===null||typeof e.max_usd_per_call!="number")){if(e.mode==="reported")return{mode:"reported",unit:null,usd_per_unit:null,max_usd_per_call:e.max_usd_per_call};if(e.mode==="unit"&&typeof e.unit=="string"&&typeof e.usd_per_unit=="number"&&Number.isFinite(e.usd_per_unit)&&e.usd_per_unit>=0)return{mode:"unit",unit:e.unit,usd_per_unit:e.usd_per_unit,max_usd_per_call:e.max_usd_per_call}}}d(j,"parseSpendPrice");async function C(n,e){const{privateKey:r}=n,s=typeof r=="string";let t=!s&&r.kty==="RSA"?"RS256":"ES256";if(!s&&r.kty!=="RSA"&&r.kty!=="EC")throw new u("Ledger private key must be an ES256 or RS256 PEM or JWK",!0);const a={name:"ECDSA",namedCurve:"P-256"},i={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"};let o;try{if(s){const p=/^-----BEGIN PRIVATE KEY-----\s*([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----\s*$/.exec(r);if(!p)throw new Error("Expected a PKCS#8 PEM private key");const g=Uint8Array.from(atob(p[1].replace(/\s/g,"")),E=>E.charCodeAt(0));try{o=await crypto.subtle.importKey("pkcs8",g,a,!1,["sign"])}catch{t="RS256",o=await crypto.subtle.importKey("pkcs8",g,i,!1,["sign"])}}else{if(r.alg!==void 0&&r.alg!==t)throw new Error(`JWK alg must be ${t}`);o=await crypto.subtle.importKey("jwk",r,t==="ES256"?a:i,!1,["sign"])}}catch(p){throw new u(`Invalid ledger private key: ${String(p)}`,!0)}const c=Math.floor(Date.now()/1e3),l=d(p=>S(new TextEncoder().encode(JSON.stringify(p))),"encode"),f=n.keyId??(s?void 0:r.kid),y=l({alg:t,typ:"JWT",...f?{kid:f}:{}}),h=l({iss:n.clientId,sub:n.clientId,aud:e,iat:c,exp:c+60,jti:crypto.randomUUID()}),m=`${y}.${h}`,k=await crypto.subtle.sign(t==="ES256"?{name:"ECDSA",hash:"SHA-256"}:"RSASSA-PKCS1-v1_5",o,new TextEncoder().encode(m));return`${m}.${S(new Uint8Array(k))}`}d(C,"clientAssertion");function S(n){let e="";for(const r of n)e+=String.fromCharCode(r);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}d(S,"base64url");function w(n){return n>=400&&n<500&&n!==408&&n!==429}d(w,"isPermanent");export{u as ReceiptPostError,A as SpendRefusedError,O as postReceipt,I as requestSpendCheck};
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 E,LeafError as T,leafErrorResponse as V,storedAnswerHeaders as oe}from"./errors.js";import{buildCommandManifest as de}from"./manifest.js";import{buildBundle as ae}from"./bundle.js";import{parseCrtrCaller as se}from"./caller.js";import{createCallerVerifier as ce,normalizeProviderId as ue,scopeMissing as fe}from"./verify.js";const P=/^v([1-9][0-9]*)$/;function Me(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),a=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 d=new Map,b=e.baseUrl===void 0?void 0:G(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${a} is serving without bearer authentication`);const m=s(async(f,y,M)=>{const u=`${y.version}\0${M}`;let l=d.get(u);if(l===void 0){const I=await ae(y.plugin,{mountPath:M,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:I.tar,etag:I.etag},d.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 E(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,b??G(y));const w=H(y),$=w[w.length-1],S=b??G(`/${w.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(A=>A.version)});const N=$===void 0?null:P.exec($),k=N===null?void 0:r.find(A=>A.version===Number(N[1]));return k===void 0?D():m(f,k,`${S}/v${k.version}`)}if(f.method!=="POST")return D();const M=performance.now();let u,l;const p=[];let I=[],B=!1,J=!1;const j=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()-M,...p.length===0?{}:{receiptId:p[0].receipt_id},...p.length>1?{receiptIds:p.map($=>$.receipt_id)}:{},replayed:J})}catch{}return w},"answer");let g=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 j(E(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){const o=t?ye(r,y):void 0;return j(o===void 0?D():be(o,r))}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 o=l.leaf.group,v=i===void 0&&o!==void 0?w.scope.find(x=>x.endsWith(`:${o}`)&&x.length>o.length+1)?.slice(0,-(o.length+1)):void 0;throw fe(l.scope,v)}if(w!==void 0){if(g===null||g==="")return j(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=f.headers.get("crtr-run-id"),v=se(f.headers.get("crtr-caller"));u=Object.freeze({...w,requestId:g,...o!==null&&o!==""?{runId:o}:{},...Object.keys(v).length>0?{crtr:Object.freeze(v)}:{}})}const $=await ke(f,l.manifest,w!==void 0);if(l.leaf.sideEffect){if(g===null||g==="")return j(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=u===void 0?null:{sub:u.sub,grantee:u.grantee};if(!await e.requests.record(g,o)){J=!0;const x=await he(e.requests,g,o,l.plugin.timeouts?.requestMs??3e4);if(x!==!0){const _=x.headers.get("Crtr-Receipt");if(_!==null)try{const C=JSON.parse(_);p.push(...Array.isArray(C)?C:[C])}catch{}return j(x)}J=!1}B=!0}const S=l,N={request:f,...u!==void 0?{caller:u}:{},...g!==null&&g!==""?{causedBy:`request:${g}`}:{},approval:ne(f),meter(o){if(u===void 0)throw new Error("ctx.meter needs an authenticated caller");if(p.some(R=>R.unit===o.unit))throw new Error(`ctx.meter may be called only once for unit ${o.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const v=o.receiptId??u.requestId;if(p.some(R=>R.receipt_id===v))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${v} is taken`);const x=S.path.slice(1).join(" "),_=I.find(R=>R.mode==="unit"&&R.unit===o.unit),C=o.usdEquivalent??(_?.usd_per_unit!=null?o.units*_.usd_per_unit:0),L={receipt_id:v,provider:e.receipts.provider,tool:x,sub:u.sub,grantee:u.grantee,payer:u.payer,units:o.units,unit:o.unit,usd_equivalent:C,request_id:u.requestId,...u.runId!==void 0?{run_id:u.runId}:{},time:new Date().toISOString()};return p.push(L),L},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 o=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(o===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");return I=(await te(e.auth.issuer,o,S.path.slice(1).join(" "),e.receipts.ledger)).prices,{prices:I}}};let k,A;try{const o=await l.leaf.run($,N);k=l.leaf.streaming?await Ee(o,e.onError,l.path):xe(o,l.manifest)}catch(o){o instanceof T?(k=V(o),A=o.headers):(U(e.onError,o,l.path),k=z(o))}if(B&&k.status===403&&await le(k))return await e.requests.delete(g),j(W(k,p));try{if(B)await e.requests.store(g,{status:k.status,body:await k.clone().text(),...A!==void 0?{headers:{...A}}:{},...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 ${S.path.join(" ")}`);for(const o of p)await e.receipts.outbox.save(o)}}catch(o){return U(e.onError,o,l.path,p),j(z(o))}return j(W(k,p))}catch(w){return w instanceof T?j(V(w)):(U(e.onError,w,l?.path??[]),j(z(w)))}}}s(Me,"createFetchHandler");function z(n){return E(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(z,"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 F(e)&&F(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 E(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const a=oe(r.answer.headers);a.set("Content-Type","application/json");const c=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return c.length>0&&a.set("Crtr-Receipt",Z(c)),new Response(r.answer.body,{status:r.answer.status,headers:a})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return z(new Error("The earlier request has no stored answer."));await new Promise(a=>setTimeout(a,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 a of n){if(a.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${a.name}`);if(e&&a.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const c=a.version??1;if(r.has(c))throw new Error(`createFetchHandler got two definitions of ${t} major ${c}`);r.set(c,{version:c,plugin:a,commands:pe(a,i)})}return[...r.values()].sort((a,c)=>a.version-c.version)}s(me,"servedMajors");function pe(n,e){const t=de(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,a){const c=Object.entries(e);if(n.length!==c.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[d,[b,h]]of c.entries()){const m=n[d];if(m===void 0||m.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${b}`);const f=[...i,m.name];if(m.kind==="branch"&&h.kind==="branch"){K(m.children,h.children,f,t,r,a);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:`${a??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${b}`)}}s(K,"collectCommands");function we(n,e){const i=H(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=H(e);for(let t=i.length-2;t>=0;t-=1){const r=P.exec(i[t]);if(r===null)continue;const c=n.find(d=>d.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(c!==void 0)return c}}s(ge,"findVersionedCommand");function ye(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=P.exec(i[t]);if(r!==null)return n.some(a=>a.version===Number(r[1]))?void 0:Number(r[1])}}s(ye,"unservedMajor");function be(n,e){return E(410,{code:"unsupported_major",message:`Major ${n} is not served; supported majors: ${e.map(i=>i.version).join(", ")}.`,next:"Refetch the provider bundle and retry with its current major.",received:n})}s(be,"unsupportedMajor");function H(n){return n.split("/").filter(e=>e.length>0)}s(H,"pathSegments");async function ke(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const d=JSON.parse(t);if(!F(d))throw new Error("not an object");r=d}catch{throw q("Request body must be a JSON object.",i?"body":void 0,i,t)}const a=new Map(e.params.map(d=>[d.name,d]));for(const d of Object.keys(r))if(!a.has(d))throw i?q(`Unknown parameter ${d}.`,d,!0,r[d]):new T({code:"unknown_parameter",message:`Unknown parameter ${d}.`,field:d});const c={};for(const d of e.params){if(!Object.hasOwn(r,d.name)){if(d.required)throw q(`Missing required parameter ${d.name}.`,d.name,i,null);continue}const b=r[d.name];if(d.kind==="flag"&&d.type==="json"){const m=ie(d.shape,b,d.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,b);c[X(d.name)]=b;continue}const h=je(b,d);if(h===void 0)throw q(`Invalid value for parameter ${d.name}.`,d.name,i,b);c[X(d.name)]=h}return c}s(ke,"decodeInput");function je(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(je,"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"?ve(n):n}}s(Q,"decodeScalar");function ve(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(ve,"decodeBase64");function xe(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw O("result")}if(!F(t))throw O("result");const r=re(e.output,t);if(r!==null)throw O(r.field,r.receivedType);for(const a of Object.keys(t))if(!e.output.some(c=>c.name===a))throw O(a);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(xe,"resultResponse");async function Ee(n,e,i){if(!$e(n))throw O("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,a=await t.next();let c=a.done,d=c?void 0:r.encode(`${JSON.stringify(a.value)}
1
+ var ne=Object.defineProperty;var s=(n,e)=>ne(n,"name",{value:e,configurable:!0});import{approvalFor as te}from"./approval.js";import{requestSpendCheck as re}from"./receipts.js";import{validateDeclaredResult as ie,validateValue as oe}from"@north-light/api/command-manifest";import{errorResponse as E,LeafError as T,leafErrorResponse as W,storedAnswerHeaders as de}from"./errors.js";import{buildCommandManifest as ae}from"./manifest.js";import{buildBundle as se}from"./bundle.js";import{parseCrtrCaller as ce}from"./caller.js";import{createCallerVerifier as ue,normalizeProviderId as fe,scopeMissing as le}from"./verify.js";const D=/^v([1-9][0-9]*)$/;function Ne(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:fe(e.auth),t=Array.isArray(n)||n.version!==void 0,r=pe(Array.isArray(n)?n:[n],Array.isArray(n),i),a=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:ue(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 d=new Map,b=e.baseUrl===void 0?void 0:L(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${a} is serving without bearer authentication`);const m=s(async(f,y,M)=>{const u=`${y.version}\0${M}`;let l=d.get(u);if(l===void 0){const _=await se(y.plugin,{mountPath:M,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:_.tar,etag:_.etag},d.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&&!ee(f.headers.get("authorization")??"",`Bearer ${e.token}`))return E(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,b??L(y));const w=H(y),$=w[w.length-1],R=b??L(`/${w.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(A=>A.version)});const N=$===void 0?null:D.exec($),k=N===null?void 0:r.find(A=>A.version===Number(N[1]));return k===void 0?G():m(f,k,`${R}/v${k.version}`)}if(f.method!=="POST")return G();const M=performance.now();let u,l;const p=[];let _=[],B=null,J=!1,P=!1;const v=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()-M,...p.length===0?{}:{receiptId:p[0].receipt_id},...p.length>1?{receiptIds:p.map($=>$.receipt_id)}:{},replayed:P})}catch{}return w},"answer");let g=f.headers.get("crtr-request-id");try{if(l=t?ye(r,y):ge(h.commands,y),e.token!==void 0&&!ee(f.headers.get("authorization")??"",`Bearer ${e.token}`))return v(E(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){const o=t?be(r,y):void 0;return v(o===void 0?G():ke(o,r))}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 o=l.leaf.group,j=i===void 0&&o!==void 0?w.scope.find(x=>x.endsWith(`:${o}`)&&x.length>o.length+1)?.slice(0,-(o.length+1)):void 0;throw le(l.scope,j)}if(w!==void 0){if(g===null||g==="")return v(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=f.headers.get("crtr-run-id"),j=ce(f.headers.get("crtr-caller"));u=Object.freeze({...w,requestId:g,...o!==null&&o!==""?{runId:o}:{},...Object.keys(j).length>0?{crtr:Object.freeze(j)}:{}})}const $=await je(f,l.manifest,w!==void 0);if(l.leaf.sideEffect){if(g===null||g==="")return v(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=u===void 0?null:{sub:u.sub,grantee:u.grantee};if(!await e.requests.record(g,o)){P=!0;const x=await me(e.requests,g,o,l.plugin.timeouts?.requestMs??3e4);if(x!==!0){const S=x.headers.get("Crtr-Receipt");if(S!==null)try{const C=JSON.parse(S);p.push(...Array.isArray(C)?C:[C])}catch{}return v(x)}P=!1}J=!0}const R=l,N={request:f,...u!==void 0?{caller:u}:{},...g!==null&&g!==""?{causedBy:`request:${g}`}:{},approval:te(f),meter(o){if(u===void 0)throw new Error("ctx.meter needs an authenticated caller");if(p.some(I=>I.unit===o.unit))throw new Error(`ctx.meter may be called only once for unit ${o.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const j=o.receiptId??u.requestId;if(p.some(I=>I.receipt_id===j))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${j} is taken`);const x=R.path.slice(1).join(" "),S=_.find(I=>I.mode==="unit"&&I.unit===o.unit),C=o.usdEquivalent??(S?.usd_per_unit!=null?o.units*S.usd_per_unit:0),V={receipt_id:j,provider:e.receipts.provider,tool:x,sub:u.sub,grantee:u.grantee,payer:u.payer,units:o.units,unit:o.unit,usd_equivalent:C,request_id:u.requestId,...u.runId!==void 0?{run_id:u.runId}:{},...B!==null?{admission_id:B}:{},time:new Date().toISOString()};return p.push(V),V},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 o=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(o===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");const j=await re(e.auth.issuer,o,R.path.slice(1).join(" "),e.receipts.ledger);return _=j.prices,B=j.admission_id,j}};let k,A;try{const o=await l.leaf.run($,N);k=l.leaf.streaming?await $e(o,e.onError,l.path):Ee(o,l.manifest)}catch(o){o instanceof T?(k=W(o),A=o.headers):(U(e.onError,o,l.path),k=z(o))}if(J&&k.status===403&&await he(k))return await e.requests.delete(g),v(Z(k,p));try{if(J)await e.requests.store(g,{status:k.status,body:await k.clone().text(),...A!==void 0?{headers:{...A}}:{},...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 o of p)await e.receipts.outbox.save(o)}}catch(o){return U(e.onError,o,l.path,p),v(z(o))}return v(Z(k,p))}catch(w){return w instanceof T?v(W(w)):(U(e.onError,w,l?.path??[]),v(z(w)))}}}s(Ne,"createFetchHandler");function z(n){return E(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(z,"handlerFailed");function Z(n,e){if(e.length===0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",K(e)),new Response(n.body,{status:n.status,headers:i})}s(Z,"responseWithReceipts");function K(n){return JSON.stringify(n.length===1?n[0]:n)}s(K,"receiptHeader");async function he(n){try{const e=await n.clone().json();return F(e)&&F(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(he,"isApprovalRequired");async function me(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 E(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const a=de(r.answer.headers);a.set("Content-Type","application/json");const c=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return c.length>0&&a.set("Crtr-Receipt",K(c)),new Response(r.answer.body,{status:r.answer.status,headers:a})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return z(new Error("The earlier request has no stored answer."));await new Promise(a=>setTimeout(a,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}s(me,"replay");function pe(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 a of n){if(a.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${a.name}`);if(e&&a.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const c=a.version??1;if(r.has(c))throw new Error(`createFetchHandler got two definitions of ${t} major ${c}`);r.set(c,{version:c,plugin:a,commands:we(a,i)})}return[...r.values()].sort((a,c)=>a.version-c.version)}s(pe,"servedMajors");function we(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 Q(t.children,n.commands,[t.name],n,r,e),r}s(we,"commandMap");function Q(n,e,i,t,r,a){const c=Object.entries(e);if(n.length!==c.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[d,[b,h]]of c.entries()){const m=n[d];if(m===void 0||m.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${b}`);const f=[...i,m.name];if(m.kind==="branch"&&h.kind==="branch"){Q(m.children,h.children,f,t,r,a);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:`${a??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${b}`)}}s(Q,"collectCommands");function ge(n,e){const i=H(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(ge,"findCommand");function ye(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=D.exec(i[t]);if(r===null)continue;const c=n.find(d=>d.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(c!==void 0)return c}}s(ye,"findVersionedCommand");function be(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=D.exec(i[t]);if(r!==null)return n.some(a=>a.version===Number(r[1]))?void 0:Number(r[1])}}s(be,"unservedMajor");function ke(n,e){return E(410,{code:"unsupported_major",message:`Major ${n} is not served; supported majors: ${e.map(i=>i.version).join(", ")}.`,next:"Refetch the provider bundle and retry with its current major.",received:n})}s(ke,"unsupportedMajor");function H(n){return n.split("/").filter(e=>e.length>0)}s(H,"pathSegments");async function je(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const d=JSON.parse(t);if(!F(d))throw new Error("not an object");r=d}catch{throw q("Request body must be a JSON object.",i?"body":void 0,i,t)}const a=new Map(e.params.map(d=>[d.name,d]));for(const d of Object.keys(r))if(!a.has(d))throw i?q(`Unknown parameter ${d}.`,d,!0,r[d]):new T({code:"unknown_parameter",message:`Unknown parameter ${d}.`,field:d});const c={};for(const d of e.params){if(!Object.hasOwn(r,d.name)){if(d.required)throw q(`Missing required parameter ${d.name}.`,d.name,i,null);continue}const b=r[d.name];if(d.kind==="flag"&&d.type==="json"){const m=oe(d.shape,b,d.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,b);c[Y(d.name)]=b;continue}const h=ve(b,d);if(h===void 0)throw q(`Invalid value for parameter ${d.name}.`,d.name,i,b);c[Y(d.name)]=h}return c}s(je,"decodeInput");function ve(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>X(t,e));return i.some(t=>t===void 0)?void 0:i}return X(n,e)}s(ve,"decodeParameter");function X(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"?xe(n):n}}s(X,"decodeScalar");function xe(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(xe,"decodeBase64");function Ee(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw O("result")}if(!F(t))throw O("result");const r=ie(e.output,t);if(r!==null)throw O(r.field,r.receivedType);for(const a of Object.keys(t))if(!e.output.some(c=>c.name===a))throw O(a);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(Ee,"resultResponse");async function $e(n,e,i){if(!Ae(n))throw O("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,a=await t.next();let c=a.done,d=c?void 0:r.encode(`${JSON.stringify(a.value)}
2
2
  `);const b=new ReadableStream({async pull(h){if(d!==void 0){h.enqueue(d),d=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){U(e,m,i),h.error(m)}},async cancel(h){await t.return?.(h)}});return new Response(b,{headers:{"Content-Type":"application/x-ndjson"}})}s(Ee,"streamResponse");function U(n,e,i,t=[]){try{t.length>1?n?.(e,i,t[0],t):n?.(e,i,t[0])}catch{}}s(U,"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 D(){return E(404,{code:"no_such_command",message:"No command matches this request."})}s(D,"noSuchCommand");function G(n){return n==="/"?"":n.replace(/\/+$/,"")}s(G,"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 a=0;a<Math.min(i.length,t.length);a+=1)r|=i[a]^t[a];return r===0}s(Y,"constantTimeEqual");function F(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(F,"isRecord");function $e(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}s($e,"isAsyncIterable");export{Me as createFetchHandler};
3
+ `))}catch(m){U(e,m,i),h.error(m)}},async cancel(h){await t.return?.(h)}});return new Response(b,{headers:{"Content-Type":"application/x-ndjson"}})}s($e,"streamResponse");function U(n,e,i,t=[]){try{t.length>1?n?.(e,i,t[0],t):n?.(e,i,t[0])}catch{}}s(U,"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 G(){return E(404,{code:"no_such_command",message:"No command matches this request."})}s(G,"noSuchCommand");function L(n){return n==="/"?"":n.replace(/\/+$/,"")}s(L,"mountPath");function Y(n){return n.replace(/-([a-z])/g,(e,i)=>i.toUpperCase())}s(Y,"camel");function ee(n,e){const i=new TextEncoder().encode(n),t=new TextEncoder().encode(e);let r=i.length^t.length;for(let a=0;a<Math.min(i.length,t.length);a+=1)r|=i[a]^t[a];return r===0}s(ee,"constantTimeEqual");function F(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(F,"isRecord");function Ae(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}s(Ae,"isAsyncIterable");export{Ne as createFetchHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.598",
3
+ "version": "0.3.599",
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.598",
31
- "@north-light/identity": "0.3.598"
30
+ "@north-light/api": "0.3.599",
31
+ "@north-light/identity": "0.3.599"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {