palbase 0.11.1 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +11 -11
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{KNPQNBC2.js → 2J3RT5GV.js} +2 -2
- package/dist/chunks/2QE7TIVQ.js +6 -0
- package/dist/chunks/{BUAGC2PT.js → 3CFHP6H7.js} +1 -1
- package/dist/chunks/5MMZNWFL.js +21 -0
- package/dist/chunks/5U3YIYBP.js +13 -0
- package/dist/chunks/{43VM626B.js → 6SINT3YD.js} +1 -1
- package/dist/chunks/{EWBRYA7P.js → 7MBBS4BC.js} +2 -2
- package/dist/chunks/{26UTOC32.js → AZ3Z3ME2.js} +1 -1
- package/dist/chunks/BJL7ZBG7.js +2 -0
- package/dist/chunks/{LYEEW4UG.js → C2WFUOF7.js} +2 -2
- package/dist/chunks/{NGE3D2K4.js → C3UPTONG.js} +7 -7
- package/dist/chunks/CMDUL3VE.js +2 -0
- package/dist/chunks/{R3EIGCWV.js → EQ4HNSWU.js} +2 -2
- package/dist/chunks/{FVLHT7UQ.js → EWXQUZSU.js} +2 -2
- package/dist/chunks/{3VY3ZZCI.js → GXLUNOFZ.js} +1 -1
- package/dist/chunks/L4NDDBYW.js +2 -0
- package/dist/chunks/{7WIMZTYB.js → MERWSLS2.js} +2 -2
- package/dist/chunks/MYHRHZYN.js +2 -0
- package/dist/chunks/{S2KRJF6J.js → QRWMVBF4.js} +2 -2
- package/dist/chunks/{EEWP43KI.js → R26ROMEG.js} +1 -1
- package/dist/chunks/{ZZG7ICDG.js → SGCYJGSM.js} +2 -2
- package/dist/chunks/{3453XVQL.js → SGDOCWYB.js} +2 -2
- package/dist/chunks/{KW6ODEYS.js → W33A3OUV.js} +1 -1
- package/dist/cli.js +132 -131
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/chats.d.ts +7 -0
- package/types/backend/src/index.d.ts +1 -0
- package/types/backend/src/transit.d.ts +39 -0
- package/types/internal/src/modules/ai.d.ts +8 -0
- package/types/internal/src/modules/purchases.d.ts +95 -11
- package/types/internal/src/modules/secrets.d.ts +148 -1
- package/types/internal/src/transit-marks.d.ts +51 -0
- package/types/internal/src/transit.d.ts +108 -0
- package/types/server/src/index.d.ts +1 -0
- package/types/server/src/server.d.ts +8 -0
- package/types/server/src/transit.d.ts +91 -0
- package/types/web/src/backend-transit.d.ts +23 -0
- package/types/web/src/backends.d.ts +8 -1
- package/types/web/src/index.d.ts +1 -0
- package/dist/chunks/AFFE3Q5O.js +0 -6
- package/dist/chunks/BUYFMLTF.js +0 -2
- package/dist/chunks/Q3S76MYJ.js +0 -2
- package/dist/chunks/V2FEPVVD.js +0 -13
- package/dist/chunks/WLAO2QSR.js +0 -20
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
type JsonObject = Record<string, unknown>;
|
|
2
|
+
/** An operation's encrypted places: its request's (body and query) and its answer's. */
|
|
3
|
+
export interface Encryption {
|
|
4
|
+
request: string[];
|
|
5
|
+
response: string[];
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The places op (an operation of document) carries encrypted, or undefined
|
|
9
|
+
* when it carries none. A mark the client could not seal — in a path or a
|
|
10
|
+
* header parameter, under a record's any key, in a streamed answer, on an
|
|
11
|
+
* upload — is refused: the contract is one no client honours.
|
|
12
|
+
*/
|
|
13
|
+
export declare function encryptionOf(document: unknown, op: JsonObject, where: string): Encryption | undefined;
|
|
14
|
+
/** The project's id and its signing key's public half: what a client verifies the list of keys it seals to with. */
|
|
15
|
+
export interface TransitConfig {
|
|
16
|
+
projectId: string;
|
|
17
|
+
/** Ed25519, base64url without padding (GET /secrets/transit's signer). */
|
|
18
|
+
signer: string;
|
|
19
|
+
}
|
|
20
|
+
/** Whether any operation of document carries a field encrypted. */
|
|
21
|
+
export declare function marksAny(document: unknown): boolean;
|
|
22
|
+
/** A route's call by hand, its fields sealed: what goes, and how its answer is read. */
|
|
23
|
+
export interface EncryptedCall {
|
|
24
|
+
/** The Palbase-Encryption header's value; none when the route carries no encrypted field. */
|
|
25
|
+
header?: string;
|
|
26
|
+
body?: unknown;
|
|
27
|
+
query?: Record<string, unknown>;
|
|
28
|
+
/** The answer with its marked fields opened — one that came plain, or does not open, throws; the answer as it is when the route marks none. */
|
|
29
|
+
open: (answer: unknown) => Promise<unknown>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A backend's route called by hand — Studio's Try it, palbase machines:call:
|
|
33
|
+
* the fields its contract marks in the request sealed to the project's key in
|
|
34
|
+
* use (a developer reads its public half from GET /secrets/transit), and a way
|
|
35
|
+
* to open the answer's. A route that marks none goes as it came. `path` is the
|
|
36
|
+
* contract's template (/patients/{id}), `params` its values in order.
|
|
37
|
+
*/
|
|
38
|
+
export declare function encryptedCall(input: {
|
|
39
|
+
contract: unknown;
|
|
40
|
+
method: string;
|
|
41
|
+
path: string;
|
|
42
|
+
params?: readonly string[];
|
|
43
|
+
body?: unknown;
|
|
44
|
+
query?: Record<string, unknown>;
|
|
45
|
+
projectId: string;
|
|
46
|
+
key: {
|
|
47
|
+
kid: string;
|
|
48
|
+
publicKey: string;
|
|
49
|
+
};
|
|
50
|
+
}): Promise<EncryptedCall>;
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** What a marked field becomes. */
|
|
2
|
+
export declare const FIELD_PREFIX = "pbt1.";
|
|
3
|
+
/** The header a request names its key in. */
|
|
4
|
+
export declare const HEADER = "Palbase-Encryption";
|
|
5
|
+
/** The format's version, the header's first part. */
|
|
6
|
+
export declare const VERSION = "1";
|
|
7
|
+
/** What the contract marks a field it carries encrypted with. */
|
|
8
|
+
export declare const MARK = "x-palbase-encrypted";
|
|
9
|
+
/** A field, a header or a list that does not open, or a request the format refuses. */
|
|
10
|
+
export declare class TransitError extends Error {
|
|
11
|
+
/** `unopenable` (tampered, moved, another key's), `malformed`, `unverified` (a list whose signature or project does not hold) */
|
|
12
|
+
readonly code: 'unopenable' | 'malformed' | 'unverified';
|
|
13
|
+
constructor(code: TransitError['code'], message: string);
|
|
14
|
+
}
|
|
15
|
+
type Bytes = Uint8Array<ArrayBuffer>;
|
|
16
|
+
/** base64url without padding, as every part of the format is written. */
|
|
17
|
+
export declare function toBase64Url(b: Uint8Array): string;
|
|
18
|
+
/** The bytes of base64url text, padded or not; malformed text throws. */
|
|
19
|
+
export declare function fromBase64Url(s: string): Bytes;
|
|
20
|
+
/** An ephemeral X25519 key pair; given one, a test's — the vectors' — is used. */
|
|
21
|
+
export interface Ephemeral {
|
|
22
|
+
privateKey: Uint8Array;
|
|
23
|
+
publicKey: Uint8Array;
|
|
24
|
+
}
|
|
25
|
+
/** HPKE's single-shot seal to pkR (the first message of base mode's context). */
|
|
26
|
+
export declare function hpkeSeal(pkR: Uint8Array, info: Uint8Array, plaintext: Uint8Array, aad?: Uint8Array, ephemeral?: Ephemeral): Promise<{
|
|
27
|
+
enc: Bytes;
|
|
28
|
+
ct: Bytes;
|
|
29
|
+
}>;
|
|
30
|
+
/** HPKE's single-shot open with skR, whose public half is pkR. */
|
|
31
|
+
export declare function hpkeOpen(skR: Uint8Array, pkR: Uint8Array, enc: Uint8Array, info: Uint8Array, ct: Uint8Array, aad?: Uint8Array): Promise<Bytes>;
|
|
32
|
+
/** The X25519 public key of a private one. */
|
|
33
|
+
export declare function x25519PublicOf(privateKey: Uint8Array): Promise<Bytes>;
|
|
34
|
+
/**
|
|
35
|
+
* What a request's key is sealed for: its project, its method, its route as
|
|
36
|
+
* the contract writes the path (/patients/{id}) — each parameter's place,
|
|
37
|
+
* not its name: "/patients/{}" — and the path's values, in the template's
|
|
38
|
+
* order, as they are before the URL escapes them.
|
|
39
|
+
*/
|
|
40
|
+
export declare function infoOf(projectId: string, method: string, path: string, params?: readonly string[]): Bytes;
|
|
41
|
+
/** A path template with each parameter's name left out: "/patients/{id}" is "/patients/{}". */
|
|
42
|
+
export declare function routeShape(path: string): string;
|
|
43
|
+
/** A request's own key: 32 random bytes, sealed to the project's key in its header. */
|
|
44
|
+
export interface RequestKey {
|
|
45
|
+
/** The project's key it is sealed to. */
|
|
46
|
+
kid: string;
|
|
47
|
+
/** The AES-256-GCM key its fields are sealed with. */
|
|
48
|
+
key: Bytes;
|
|
49
|
+
/** The Palbase-Encryption header's value. */
|
|
50
|
+
header: string;
|
|
51
|
+
}
|
|
52
|
+
/** A new request's key, sealed to the project's key kid (its public half pkR). */
|
|
53
|
+
export declare function newRequestKey(kid: string, pkR: Uint8Array, info: Uint8Array, opts?: {
|
|
54
|
+
key?: Uint8Array;
|
|
55
|
+
ephemeral?: Ephemeral;
|
|
56
|
+
}): Promise<RequestKey>;
|
|
57
|
+
/** A Palbase-Encryption header's parts; malformed ones throw. */
|
|
58
|
+
export declare function parseHeader(value: string): {
|
|
59
|
+
kid: string;
|
|
60
|
+
enc: Bytes;
|
|
61
|
+
ct: Bytes;
|
|
62
|
+
};
|
|
63
|
+
/** The request's key in a header, opened with the project's private key skR (public half pkR). */
|
|
64
|
+
export declare function openRequestKey(header: string, skR: Uint8Array, pkR: Uint8Array, info: Uint8Array): Promise<Bytes>;
|
|
65
|
+
/** value, sealed at pointer with a request's key; nonce is a test's. */
|
|
66
|
+
export declare function encryptField(key: Uint8Array, pointer: string, value: unknown, nonce?: Uint8Array): Promise<string>;
|
|
67
|
+
/** Whether v is an encrypted field: a string with the format's prefix. */
|
|
68
|
+
export declare function isEncryptedField(v: unknown): v is string;
|
|
69
|
+
/** The value sealed at pointer with a request's key; anything else throws. */
|
|
70
|
+
export declare function decryptField(key: Uint8Array, pointer: string, field: string): Promise<unknown>;
|
|
71
|
+
/** A pointer's segment, escaped: ~ ~0, / ~1, * ~2. */
|
|
72
|
+
export declare function escapeSegment(s: string): string;
|
|
73
|
+
/** A pointer's segment, unescaped. */
|
|
74
|
+
export declare function unescapeSegment(s: string): string;
|
|
75
|
+
/**
|
|
76
|
+
* value, its fields at marks below root (each a full pointer: "/body/a/*\/b",
|
|
77
|
+
* every item of an array; "/response/a/2/b", the one of index 2) mapped
|
|
78
|
+
* through fn — given the field's own pointer, an array's item by its index
|
|
79
|
+
* ("/body/a/0/b"). A field a mark names that is absent is left absent.
|
|
80
|
+
*/
|
|
81
|
+
export declare function mapMarked(value: unknown, root: string, marks: readonly string[], fn: (pointer: string, field: unknown) => Promise<unknown>): Promise<unknown>;
|
|
82
|
+
/** The signed list the secrets module answers GET /secrets/transit/public with. */
|
|
83
|
+
export interface SignedKeyList {
|
|
84
|
+
payload: string;
|
|
85
|
+
signature: string;
|
|
86
|
+
signer: string;
|
|
87
|
+
}
|
|
88
|
+
/** One key an app may seal to. */
|
|
89
|
+
export interface PublicKey {
|
|
90
|
+
kid: string;
|
|
91
|
+
key: Bytes;
|
|
92
|
+
}
|
|
93
|
+
/** A list an app holds once verified: its keys, the first sealed to. */
|
|
94
|
+
export interface KeyList {
|
|
95
|
+
project: string;
|
|
96
|
+
issuedAt: string;
|
|
97
|
+
keys: PublicKey[];
|
|
98
|
+
}
|
|
99
|
+
/** A nonce the list is asked for with: 16 random bytes, base64url. */
|
|
100
|
+
export declare function newNonce(): string;
|
|
101
|
+
/**
|
|
102
|
+
* The list, verified: signed by signer (the Ed25519 public key the app's
|
|
103
|
+
* generated client holds, base64url), its project's and carrying the nonce it
|
|
104
|
+
* was asked with — anything else throws `unverified`, and nothing in it is
|
|
105
|
+
* sealed to.
|
|
106
|
+
*/
|
|
107
|
+
export declare function verifyKeyList(signed: SignedKeyList, signer: string, projectId: string, nonce: string): Promise<KeyList>;
|
|
108
|
+
export {};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { createServer, type PalbaseServer, type ServerOptions } from './server.js';
|
|
2
2
|
export { FieldError, Fields, type FieldKeySet } from './fields.js';
|
|
3
|
+
export { Transit, TransitRefusal, TransitRequest, type TransitKeySet } from './transit.js';
|
|
3
4
|
export { EVENT_TYPES, signatureHeader, verifySignature, verifyWebhook, verifyWebhookRequest, WebhookSignatureError, type EventType, type PalbaseEvent, type PlatformEvent, type PlatformEvents, type SignatureOptions, type VerifyOptions, type WebhookEvent, type WebhookRefusal, } from './webhooks.js';
|
|
4
5
|
export { AuthUnavailable, requestAddress, sessionStanding, TokenError, TokenVerifier, type ProofContext, type RequestLike, type SessionStanding, type TokenRefusal, type TokenUser, type VerifierOptions, } from './auth/jwt.js';
|
|
5
6
|
export { isEntitled, ReservationSettled, withReservation, type CustomerInfo, type Reservation, type SpendReceipt } from './purchases.js';
|
|
@@ -2,6 +2,7 @@ import { type Fetch, type Transport } from '../../internal/src/transport.js';
|
|
|
2
2
|
import { type RetryPolicy } from '../../internal/src/retry.js';
|
|
3
3
|
import * as modules from '../../internal/src/modules/index.js';
|
|
4
4
|
import { Fields } from './fields.js';
|
|
5
|
+
import { Transit } from './transit.js';
|
|
5
6
|
export interface ServerOptions {
|
|
6
7
|
/** The project's address: https://<ref>.<domain> */
|
|
7
8
|
url: string;
|
|
@@ -40,6 +41,13 @@ export interface PalbaseServer {
|
|
|
40
41
|
secrets: ReturnType<typeof modules.secrets.client>;
|
|
41
42
|
storage: ReturnType<typeof modules.storage.client>;
|
|
42
43
|
stores: ReturnType<typeof modules.stores.client>;
|
|
44
|
+
/**
|
|
45
|
+
* The encrypted fields of a request to this backend and of its answer
|
|
46
|
+
* (transit.ts): `await palbase.transit.load()` at startup, then the request's
|
|
47
|
+
* key from its Palbase-Encryption header — open() its body or query, seal()
|
|
48
|
+
* its answer. palbase/backend does it for every route its schema marks.
|
|
49
|
+
*/
|
|
50
|
+
transit: Transit;
|
|
43
51
|
/** The transport every call goes through (the secret key, retries). */
|
|
44
52
|
transport: Transport;
|
|
45
53
|
/** The project's address its calls go to — what a public URL of its is made with. */
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/** What the secrets module answers GET /secrets/transit/keys with. */
|
|
2
|
+
export interface TransitKeySet {
|
|
3
|
+
project: string;
|
|
4
|
+
keys: Array<{
|
|
5
|
+
id: string;
|
|
6
|
+
key: string;
|
|
7
|
+
}>;
|
|
8
|
+
retired: string[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A request the format refuses, answered 400 with its code: a marked field
|
|
12
|
+
* that came plain, or a request with no key (`encryption_required`), one that
|
|
13
|
+
* does not open (`encryption_unopenable`), one sealed to a key retired since
|
|
14
|
+
* (`encryption_key_retired`) or to one the project has not made
|
|
15
|
+
* (`encryption_key_unknown`) — the app fetches the list again and sends the
|
|
16
|
+
* request once more.
|
|
17
|
+
*/
|
|
18
|
+
export declare class TransitRefusal extends Error {
|
|
19
|
+
readonly status = 400;
|
|
20
|
+
readonly code: 'encryption_required' | 'encryption_unopenable' | 'encryption_key_retired' | 'encryption_key_unknown';
|
|
21
|
+
/** The field (a pointer) or the header the refusal is about, and the key apps seal to now. */
|
|
22
|
+
readonly data: {
|
|
23
|
+
field?: string;
|
|
24
|
+
current?: string;
|
|
25
|
+
};
|
|
26
|
+
constructor(code: TransitRefusal['code'], message: string, data?: TransitRefusal['data']);
|
|
27
|
+
}
|
|
28
|
+
/** How often the keys are fetched again: a rotation's key is met sooner only by a request that names it. */
|
|
29
|
+
export declare const REFRESH_MS = 60000;
|
|
30
|
+
export interface TransitOptions {
|
|
31
|
+
/** Reads the project's keys (the secrets module's GetTransitKeys). */
|
|
32
|
+
fetch: (signal?: AbortSignal) => Promise<TransitKeySet>;
|
|
33
|
+
/** The clock (tests). */
|
|
34
|
+
now?: () => number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The project's transit keys. `await load()` once at startup: requests are
|
|
38
|
+
* opened with the keys held, fetched again every minute and when a request
|
|
39
|
+
* names a key not held.
|
|
40
|
+
*/
|
|
41
|
+
export declare class Transit {
|
|
42
|
+
private keys;
|
|
43
|
+
private retired;
|
|
44
|
+
private order;
|
|
45
|
+
private project;
|
|
46
|
+
private timer;
|
|
47
|
+
private fetchedAt;
|
|
48
|
+
private fetching;
|
|
49
|
+
private readonly opts;
|
|
50
|
+
private readonly now;
|
|
51
|
+
constructor(opts: TransitOptions);
|
|
52
|
+
/** Whether the keys are loaded. */
|
|
53
|
+
get loaded(): boolean;
|
|
54
|
+
/** The project's id, which a request's key is sealed for. */
|
|
55
|
+
get projectId(): string;
|
|
56
|
+
/** The key apps seal to now: the newest not retired. */
|
|
57
|
+
current(): string | undefined;
|
|
58
|
+
/** Reads the keys, and keeps reading them every minute until close(). A failed refresh keeps the keys held. */
|
|
59
|
+
load(signal?: AbortSignal): Promise<void>;
|
|
60
|
+
/** Stops the refresh. */
|
|
61
|
+
close(): void;
|
|
62
|
+
private refresh;
|
|
63
|
+
private key;
|
|
64
|
+
/**
|
|
65
|
+
* A request's key, from its Palbase-Encryption header: sealed for this
|
|
66
|
+
* project, the request's method, its route as the contract writes the path
|
|
67
|
+
* (/patients/{id}) and that path's values, in order.
|
|
68
|
+
*/
|
|
69
|
+
request(init: {
|
|
70
|
+
header: string | null | undefined;
|
|
71
|
+
method: string;
|
|
72
|
+
path: string;
|
|
73
|
+
params?: readonly string[];
|
|
74
|
+
}): Promise<TransitRequest>;
|
|
75
|
+
}
|
|
76
|
+
/** One request's key: its fields opened, its answer's sealed. */
|
|
77
|
+
export declare class TransitRequest {
|
|
78
|
+
readonly kid: string;
|
|
79
|
+
private readonly key;
|
|
80
|
+
constructor(kid: string, key: Uint8Array);
|
|
81
|
+
/**
|
|
82
|
+
* value (a request's body under root "/body", its query under "/query")
|
|
83
|
+
* with the fields at marks opened. A marked field that came plain is
|
|
84
|
+
* refused — never let through as it came.
|
|
85
|
+
*/
|
|
86
|
+
open(value: unknown, root: '/body' | '/query', marks: readonly string[]): Promise<unknown>;
|
|
87
|
+
/** value (the answer) with the fields at marks below "/response" sealed. */
|
|
88
|
+
seal(value: unknown, marks: readonly string[]): Promise<unknown>;
|
|
89
|
+
/** One field sealed at pointer: what seal() does at each mark. */
|
|
90
|
+
sealField(pointer: string, value: unknown): Promise<string>;
|
|
91
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type KeyList, type RequestKey } from '../../internal/src/transit.js';
|
|
2
|
+
import type { Transport } from '../../internal/src/transport.js';
|
|
3
|
+
/** The project's id and its signing key's public half, as the generated module holds them (palbase apps:sync). */
|
|
4
|
+
export interface TransitConfig {
|
|
5
|
+
projectId: string;
|
|
6
|
+
/** Ed25519, base64url without padding. */
|
|
7
|
+
signer: string;
|
|
8
|
+
}
|
|
9
|
+
/** A descriptor's encrypted places: its request's (/body/…, /query/…) and its answer's (/response/…). */
|
|
10
|
+
export interface EncryptionMarks {
|
|
11
|
+
request?: string[];
|
|
12
|
+
response?: string[];
|
|
13
|
+
}
|
|
14
|
+
/** The project's verified list of keys, fetched again when asked fresh or older than an hour. */
|
|
15
|
+
export declare function keyList(project: Transport, config: TransitConfig, fresh?: boolean): Promise<KeyList>;
|
|
16
|
+
/** A call's key: sealed to the project's current key, for its method, its route and its path's values. */
|
|
17
|
+
export declare function requestKey(project: Transport, config: TransitConfig, method: string, path: string, pathValues: string[], fresh: boolean): Promise<RequestKey>;
|
|
18
|
+
/** value (a body under "/body", a query's input under "/query") with its marked fields sealed. */
|
|
19
|
+
export declare function sealInput(key: RequestKey, value: unknown, root: '/body' | '/query', marks: readonly string[] | undefined): Promise<unknown>;
|
|
20
|
+
/** An answer with its marked fields opened; one that came plain, or does not open, is refused. */
|
|
21
|
+
export declare function openAnswer(key: RequestKey, answer: unknown, marks: readonly string[] | undefined, where: string): Promise<unknown>;
|
|
22
|
+
/** The backend's word that the call's key is one the project retired, or one it has not made: the list is fetched again. */
|
|
23
|
+
export declare function staleKey(e: unknown): boolean;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type Transport } from '../../internal/src/transport.js';
|
|
2
2
|
import { BackendError } from './backend-error.js';
|
|
3
|
+
import { type EncryptionMarks, type TransitConfig } from './backend-transit.js';
|
|
3
4
|
import { type GatewayDescriptor, type GatewayEvent, type JoinedGateway, type JoinOptions } from './gateways.js';
|
|
4
5
|
import type { RealtimeSocket } from './socket.js';
|
|
5
6
|
export interface CallOptions {
|
|
@@ -46,6 +47,12 @@ export interface EndpointDescriptor {
|
|
|
46
47
|
* the file and answers what the route's completion answered.
|
|
47
48
|
*/
|
|
48
49
|
upload?: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* The places the route carries encrypted (x-palbase-encrypted): its
|
|
52
|
+
* request's, sealed before the call goes, and its answer's, opened when it
|
|
53
|
+
* comes (backend-transit.ts).
|
|
54
|
+
*/
|
|
55
|
+
encryption?: EncryptionMarks;
|
|
49
56
|
}
|
|
50
57
|
export type NamespaceTree = {
|
|
51
58
|
[key: string]: NamespaceTree | EndpointDescriptor;
|
|
@@ -88,4 +95,4 @@ export declare function bindMachines(client: object, project: string, machine: (
|
|
|
88
95
|
* by its generated module, once, as it loads. The tree is checked whole here,
|
|
89
96
|
* so a broken one fails as the module loads, not at a call.
|
|
90
97
|
*/
|
|
91
|
-
export declare function __registerBackend(project: string, client: string, machine: string, url: string, tree: NamespaceTree): void;
|
|
98
|
+
export declare function __registerBackend(project: string, client: string, machine: string, url: string, tree: NamespaceTree, transit?: TransitConfig): void;
|
package/types/web/src/index.d.ts
CHANGED
|
@@ -18,5 +18,6 @@ export type { PaywallPackage, PaywallView } from './screen/render.js';
|
|
|
18
18
|
export { PalbaseError } from '../../internal/src/transport.js';
|
|
19
19
|
export { BackendError, isBackendError, type BackendErrorKind, type FieldError } from './backend-error.js';
|
|
20
20
|
export type { BackendBase, CallOptions, UploadOptions, UploadProgress } from './backends.js';
|
|
21
|
+
export { encryptedCall, type EncryptedCall } from '../../internal/src/transit-marks.js';
|
|
21
22
|
export { GatewayError, type ChatGatewayHandle, type GatewayDescriptor, type GatewayEvent, type GatewayHandle, type GatewaySubscription, type JoinedGateway, type JoinOptions } from './gateways.js';
|
|
22
23
|
export type { RetryPolicy } from '../../internal/src/retry.js';
|
package/dist/chunks/AFFE3Q5O.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.11.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import"./43VM626B.js";import{realpathSync as Ue}from"node:fs";import{resolve as de}from"node:path";import Nt from"typescript";import{existsSync as Se,readFileSync as ye}from"node:fs";import{createRequire as qe}from"node:module";import{dirname as ne,join as W,relative as Je,resolve as Te,sep as te}from"node:path";var h=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},G=new Set(["palbase/backend","@palbase/backend","palgres"]),Qe=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function he(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new h(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var We={bun:"bun-types",node:"@types/node"},Ge=qe(import.meta.url);function Ze(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=We[i],a=e.resolveTypeReferenceDirective(i,W(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=Ge.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(ye(c,"utf8"));s.push(W(ne(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function be(e,t){he(e);let n=W(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(Se(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new h(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
|
|
3
|
-
`)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Ze(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function xe(e,t,n,r,s){he(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=Te(t);return!n.includes(`${te}node_modules${te}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+te))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function we(e,t){let n=[],r=ne(Te(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=W(r,"package.json");if(Se(o)){try{let c=JSON.parse(ye(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=ne(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function re(e,t){if($(e,t))return!1;let n=we(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):G.has(n)}function ke(e,t){if($(e,t))return!1;let n=we(e,t)??"";return G.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${Je(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function Z(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=Z(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ge(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&G.has(ge(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&G.has(ge(n,i)??""))return(i.propertyName||i.name).text;if(re(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function pe(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function H(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>pe(e,o)==="Controller"))continue;if(!s.name)throw new h(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Qe.has(pe(e,a)??""))){if(P(n,o.name)===null)throw new h(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var He=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function Xe(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ee(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=f=>{throw new h(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${f}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let f=[];for(let p of n.getSourceFiles()){if(f.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ke(e,p.fileName)||f.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!He.has(x.code)))}f.length&&u(t.formatDiagnostics(f.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
|
|
4
|
-
`})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(Xe(g))return{kind:"raw"};let S=new Set,d=0;function C(f,p){if(++d>2e3||S.size>24)return u(`${p}: contract is too large; name its schema`);let x=f.flags,y=t.TypeFlags;if(x&(y.Any|y.Unknown|y.Never|y.TypeParameter))return u(`${p}: ${r.typeToString(f)}`);let me=b=>{let w=r.getPropertiesOfType(b);if(!(b.flags&y.Object)||w.length!==1||w[0].name!=="__pg"||!(w[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(b).length)return!1;let N=r.getTypeOfSymbolAtLocation(w[0],o);return(N.isUnion()?N.types:[N]).every(k=>k.flags&(y.StringLiteral|y.Undefined))};if(f.isIntersection()){let b=f.types.filter(w=>!me(w));if(b.length===1&&b.length<f.types.length)return C(b[0],p)}if(me(f))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&y.StringLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.NumberLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.BooleanLiteral)return`z.literal(${r.typeToString(f)==="true"})`;if(x&y.String)return"z.string()";if(x&y.TemplateLiteral){let b=f;if(b.types.length>8||!b.types.every(k=>k.flags&y.String))return u(`${p}: template literal requires an explicit schema`);let w=k=>k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+w(b.texts[0]);for(let k of b.texts.slice(1,-1))if(k){let ee=w(k);N+=`(?:(?!${ee})[\\s\\S])*${ee}`}return N+="[\\s\\S]*"+w(b.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&y.Number)return"z.number().finite()";if(x&y.Boolean)return"z.boolean()";if(x&y.Null)return"z.null()";if(x&y.Undefined)return"z.undefined()";if(S.has(f))return u(`${p}: recursive response`);S.add(f);try{if(f.isUnion()){if(f.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=f.types.some(M=>M.flags&y.Null),Q=f.types.some(M=>M.flags&y.Undefined),j=f.types.filter(M=>!(M.flags&(y.Null|y.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?C(j[0],p):`z.union([${j.map(M=>C(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(Q?".optional()":"")}if(r.isTupleType(f))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(f)){let A=r.getTypeArguments(f)[0];return A.flags&y.Never?"z.array(z.string()).length(0)":`z.array(${C(A,`${p}[]`)})`}let b=f.isIntersection()&&f.types.every(A=>A.flags&y.Object);if(!(x&y.Object)&&!b||f.getCallSignatures().length||f.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(f)}`);let w=f.symbol?.declarations?.[0];if(w&&(t.isClassDeclaration(w)||t.isClassExpression(w)))return u(`${p}: class instance ${r.typeToString(f)}`);let N=r.getPropertiesOfType(f),k=r.getIndexInfosOfType(f);return k.length?k.length!==1||!(k[0].keyType.flags&y.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${C(k[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let Q=A.getName(),j=C(r.getTypeOfSymbolAtLocation(A,o),`${p}.${Q}`);return`${JSON.stringify(Q)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{S.delete(f)}}return{kind:"expression",expression:C(g,"return")}}}import{resolve as Ye}from"node:path";var se=Symbol("not a named schema");function Ce(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=d=>new h(`${i.fileName} \u2014 ${n}.${o}: ${d}`);function c(d){if(s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Promise"&&d.typeArguments&&d.typeArguments.length===1)return c(d.typeArguments[0]);if(d.kind===s.SyntaxKind.VoidKeyword||d.kind===s.SyntaxKind.UndefinedKeyword)return null;let C=s.isArrayTypeNode(d)?d.elementType:s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Array"&&d.typeArguments&&d.typeArguments.length===1?d.typeArguments[0]:void 0,f=l(C??d);return f===se?f:{...f,isArray:C!==void 0}}function l(d){if(s.isTypeReferenceNode(d)&&!d.typeArguments)return{typeName:d.typeName.getText(i),node:d.typeName};if(s.isTypeReferenceNode(d)&&d.typeArguments&&d.typeArguments.length===1){let C=d.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(C)){let f=d.typeArguments[0];if(s.isTypeQueryNode(f))return{typeName:f.exprName.getText(i),node:f.exprName};if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName}}}if(d.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return se}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===se)return u();let g=et(e,m.node);if(!g)return u();let S=tt(e,g.symbol);return S?{kind:"schema",...S,array:m.isArray}:u()}function et(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=Z(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function tt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>Z(e,i)===t).map(i=>i.name);return s.length===0?null:{file:Ye(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ce={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},nt=new Set(["HttpError","PalError"]),rt=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],st=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function Le(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=Ct(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function it(e,t,n){throw new h(`${O(e,t)} \u2014 ${n}`)}function U(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function ue(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Pe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function $e(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ot(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=$e(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function q(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Fe(e,t,n){for(let r=q(e,t);r;r=q(e,r))if(r===n)return!0;return!1}function V(e,t,n,r){let s=e.ts;for(let i=t;i;i=q(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||ue(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function at(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function Ne(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Pe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function Oe(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ct(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ie(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function J(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)J(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Pe(r,a)||n.add(a);for(let l of Ne(e))Fe(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of Ne(e)){let u=Oe(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function le(e,t,n){let r=ct(e,t);if(r){let s=at(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Fe(e,o,r));if(i.length===1){n.add(i[0]);return}}J(e,t,n)}function lt(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function Re(e,t){return t.fn&<(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function E(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(E(e,t.whenTrue,n,r)),a(E(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(E(e,t.left,n,r)),a(E(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(E(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of Y(e,t,n))for(let l of X(s,c.fn))a(E(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(E(e,c.initializer,Re(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&J(e,ie(e,c),i),i;if(c&&s.isParameter(c)){let l=ie(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?le(e,l,i):J(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(E(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):le(e,ie(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of X(s,c))a(E(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(E(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return J(e,e.checker.getTypeAtLocation(t),i),i}function X(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function ze(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function je(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function ut(e,t){let n=e.ts,r=ze(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(je(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!re(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of rt)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function ft(e,t){let n=e.checker.getSymbolAtLocation(je(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Me(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=q(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||ue(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function Y(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&q(e,n.owner);return c?Me(e,c,n.receiver):[]}let i=ze(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&q(e,n.owner),S=g&&V(e,g,i,!1);return S?[{fn:S.fn,ctx:{receiver:n.receiver,owner:S.owner,fn:S.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=V(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!ft(e,c))return[];let m=[];for(let g of E(e,l,n)){let S=V(e,g,i,!1);S&&m.push({fn:S.fn,ctx:{receiver:g,owner:S.owner,fn:S.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!ue(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function Ae(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of E(e,s.expression,n)){let l=V(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function ve(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function dt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function De(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ie(e,t,n,r,s){if(nt.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(ve(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:De(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ce,t)?ce[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!dt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return ve(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:De(c),code:c,status:i.status}))}function fe(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function Be(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&it(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function mt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ke(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(d=>d.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(d=>s.isConstructorDeclaration(d)&&!!d.body),c=n,l=r;if(a){let d=mt(s,a);if(!d)return[];c=d.arguments,l=d}let u=ot(s,t),m=I(e,o);if(m)return Ie(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let d=fe(e,g);return d?[{...Be(e,g,d),name:u||g.name.getText()}]:[]}let S=_(e,o);if(S){let d=Ke(e,S,c,l);return d.length===1&&u?[{...d[0],name:u}]:d}return[]}function gt(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ie(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=fe(e,o);if(c)return[Be(e,o,c)]}let a=$e(n,o);return a&&v(e,a)?Ke(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,gt(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of Y(e,t,n))for(let u of X(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?Re(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function oe(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function pt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function St(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function yt(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=pt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||St(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function Tt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ce))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=fe(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function ht(e,t){let n=Tt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new h(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)ht(e,o);let i=yt(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function _e(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function bt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?_e(e,n.body,r.name.text):!1:!0:!1}return!0}function xt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function ae(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,ae(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?_e(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(xt(e,o,"allSettled")){D(e,t.expression,n,r);let u=ae(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=bt(s,t.arguments[a]);D(e,u.expression,n,ae(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?st.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=ut(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of Y(e,t,n))R(e,r,t,oe(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of Ae(e,u,n))R(e,r,u,oe(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Me(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of Ae(e,a,n))R(e,r,a,oe(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of E(e,t.expression,n)){let c=V(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function Ve(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of Y(e,t,{receiver:null,owner:null,fn:null}))for(let o of X(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...Ve(e,a,n))}return s}function wt(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of Ve(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;le(e,Oe(e,c),l);for(let u of l){let m=V(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function kt(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Et(e,t,n){let r=new Map;for(let i of wt(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=kt(i.name),a=s.get(o);if(a)throw new h(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function Ct(e,t){let n=[];for(let{cls:r,routes:s}of H(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Et(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Qt(e,t,n={}){let r=n.typescript??Nt,s=Ue(de(e)),{options:i,ambient:o}=be(r,s);return At(xe(r,s,[Ue(de(t)),...o],i))}function At(e){let t=e.ts,n=Ee(e),r=Le(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=H(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ce(e,n,u.name.text,g))}catch(S){if(!(S instanceof h))throw S;o.push(S.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,S]of Object.entries(m))s.push({file:de(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:S})}if(o.length===1)throw new h(o[0]);if(o.length>1)throw new h(`${o.length} routes have no contract:
|
|
5
|
-
${o.map(a=>`- ${a}`).join(`
|
|
6
|
-
`)}`);return{routes:s,warnings:r.warnings()}}export{h as ContractAnalysisError,Qt as analyzeProject,At as analyzeRoutes};
|
package/dist/chunks/BUYFMLTF.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.11.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import"./43VM626B.js";import{pathToFileURL as i}from"node:url";import{z as c}from"zod";async function f(e){let n=new Map,t=new Map;for(let r of e){let a=`${r.className}.${r.method}`,o=t.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(r.className,r.file),n.set(a,{returns:await u(r),throws:r.throws})}return r=>n.get(`${r.controller.name}.${r.fn}`)}async function u(e){let n=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(i(e.returns.file).href))[e.returns.exportName];if(!s(r))throw new Error(`${n}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let t=new Function("z",`return (${e.returns.expression});`)(c);if(!s(t))throw new Error(`${n}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function s(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{f as routeContracts};
|
package/dist/chunks/Q3S76MYJ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.11.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{b as v}from"./26UTOC32.js";import{a as F}from"./EEWP43KI.js";import{a as P,b as R,c as x,d as O,e as j,f as M,g as C,h as L,i as U,j as K,k as N,l as $}from"./7WIMZTYB.js";import{a as I,b as D}from"./R3EIGCWV.js";import{b as S,d as w}from"./KNPQNBC2.js";var ce=/^pb_[a-z0-9]+_s/;function E(n){if(F())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ce.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=D(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??I),t=K.client(e);return{ai:P.client(e),analytics:R.client(e),auth:x.client(e),cache:O.client(e),fields:new v({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:j.client(e),machines:M.client(e),notify:C.client(e),purchases:L.client(e),realtime:U.client(e),secrets:t,storage:N.client(e),stores:$.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,le=/^[0-9]{1,12}$/,fe=/^[0-9a-f]{64}$/,W=8,he=/^whsec_[0-9A-Za-z]{32,}$/,pe=1024*1024;async function B(n){if(typeof n.secret!="string"||!he.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await H(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(V(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!ke(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function H(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=V(n.body),{t,v1:r}=z(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,be(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let d of r)we(o,me(d))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function z(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let a of r.split(",")){let d=a.indexOf("=");if(d<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,d).trim(),i=a.slice(d+1).trim();if(c==="t"){if(s!==void 0||!le.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!fe.test(i))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(i)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function ye(n,e,t={}){let r=await ge(n,t.maxBytes??pe);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ge(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],a=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;if(a+=l.byteLength,a>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let d=new Uint8Array(a),c=0;for(let i of o)d.set(i,c),c+=i.byteLength;return d}function V(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function me(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function we(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function be(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function ke(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var J=60,Se=60,ve=8*1024,Ee=1e5;function _(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function G(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function q(n){let e=G(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var b=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ee){this.max=e}spend(e,t){if(t>=e.until)throw new u("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new u("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,a]of s)a>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function _e(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return _(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function Y(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function X(n,e,t,r){let s=ae=>{throw new u("proof",`the DPoP proof is not taken: ${ae}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>ve)return s("it is too long");let a=o.split(".");if(a.length!==3)return s("it is not a JWS of three parts");let d=q(a[0]),c=q(a[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let i=d.jwk;if(!i||typeof i!="object"||i.kty!=="EC"||i.crv!=="P-256"||typeof i.x!="string"||typeof i.y!="string")return s("its header carries no P-256 public key");if("d"in i)return s("its header carries a private key");if(await _e(i.x,i.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:i.x,y:i.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=G(a[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${a[0]}.${a[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?Y(c.htu):void 0,y=Y(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let se=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-se)>J)return s("it was not made within a minute of now");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==oe)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let ie=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:ie,until:(c.iat+J+Se)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},Te=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Ae(n){return async e=>{let t=w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof S&&r.status===401&&!Te.has(r.code))return!1;throw new g("a session's standing could not be told",{cause:r})}}}var T={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},Z=60,Pe=16*1024,Re=10*6e4,xe=5e4,Q=n=>typeof n=="string"&&Object.hasOwn(T,n),A=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new b;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Pe)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=ee(r[0]),o=ee(r[1]);if(!s||!o)throw new u("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Q(a))throw new u("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==a)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${a}`);let i=ne(r[2]);if(!i)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(T[c.alg].verify,c.key,i,l).catch(()=>!1))throw new u("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");y=await X(e,h.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:je(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",a=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:te(t,a)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let a;try{a=await o}catch(c){let i=this.standings.get(t),l=this.now();if(i&&l<i.at+this.standingStaleMs)return i.until=Math.min(l+this.standingTtlMs,i.at+this.standingStaleMs),i.live;throw new g("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:d,until:d+this.standingTtlMs}),this.standings.size>xe&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new u("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+Z<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-Z>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new u("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Re;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let a=o.alg;if(typeof o.kid!="string"||!Q(a))continue;let d=T[a];if(o.kty!==d.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...i}=o;try{r.set(o.kid,{alg:a,key:await crypto.subtle.importKey("jwk",i,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Me(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function te(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Oe.test(s)?`${r}://${s}${e.pathname}`:""}var Oe=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function je(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Me(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function ne(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function ee(n){let e=ne(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Ce(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var k=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Le(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:d}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...a!==void 0?{ttl_seconds:a}:{},...d!==void 0?{metadata:d}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new k(i);let l={customer_id:i.customer,spend_id:i.id},p;try{p=await r(i)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Ue(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Ke=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Ne=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function re(n){return!Ke.test(n)||Ne.test(n)||/_PROXY$/i.test(n)}var $e=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function Ie(n){return $e.test(n)}async function De(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=E({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:a}=await o.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(re(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:i.sort()}}export{E as a,f as b,B as c,H as d,z as e,ye as f,u as g,g as h,Ae as i,A as j,te as k,Ce as l,k as m,Le as n,Ue as o,re as p,Ie as q,De as r};
|
package/dist/chunks/V2FEPVVD.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.11.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{b as j,c as A,d as R}from"./LYEEW4UG.js";import{d as G}from"./R3EIGCWV.js";import{a as k,b as L,c as _,e as $}from"./KNPQNBC2.js";var l=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function K(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function N(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??ke(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:be(e)??t.retryAfter});let s=ve(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function T(t){return t instanceof L||t instanceof Error&&t.name==="PalbaseError"}function F(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function ve(t){let e=E(E(t,"data"),"fields");if(F(e))return e;let n=E(t,"fields");return F(n)?n:void 0}function be(t){return W(t,"retry_after")??W(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function W(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function ke(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var _e=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ee=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),xe=new Set(Ee),Ce=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Ce.has(t)}function H(t){return t==="call"||t==="join"||P(t)}function U(t){return typeof t=="string"&&_e.test(t)&&!xe.has(t)&&!P(t)}function V(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function z(t){$(t)}function Q(t){return $(t).origin}var I=class{me;reader;messages=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let o=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(o,s)}if(this.ended)return!1;let a=(r?.parts??[]).map(o=>j(o)).filter(o=>o!==void 0);return this.older=[...a,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let a=this.state;if(a!==n){n=a,yield a;continue}if(this.ended)return;await new Promise(o=>e=o)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=j(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:A(n.text),thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:A(n.text),thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);n.text=n.text.slice(0,R(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,R(n.text,e.offset));break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Re(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?Y(e.attachments):s?.attachments??[]}),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n}),this.changed()}place(e,n){let s=e.response_id??null,a=s!==null&&![...this.messages.entries()].some(([o,d])=>o!==n&&d.responseId===s)?this.order.findIndex(o=>o.type==="response"&&o.key===s):-1;a>=0?this.order.splice(a,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=i=>e!==void 0&&i.startedBy===e,s=new Map;for(let i of this.responses.values()){let c=i.parentId!==null?this.responses.get(i.parentId)??i:i;s.set(i.id,Te(i,c.startedBy??null,n(c),i.goal??c.goal))}let r=new Map([...this.messages].map(([i,c])=>[i,e!==void 0&&c.author===e?{...c,mine:!0}:c])),a=[...this.history.entries()].sort(([i],[c])=>i-c).flatMap(([i,c])=>c.map((b,w)=>Pe(b,`${i}:${w}`,e))),o=[...a];for(let i of this.order)i.type==="goal"?o.push({type:"goal",goal:i.event}):i.type==="voice"?o.push({type:"voice",voice:i.event}):i.type==="message"?o.push({type:"message",message:r.get(i.key)}):this.responses.get(i.key).parentId===null&&o.push({type:"response",response:s.get(i.key)});let d=a.flatMap(i=>i.type==="message"?[i.message]:[]),u=a.flatMap(i=>i.type==="response"?[i.response]:[]),p=[...this.calls.values()].filter(i=>s.get(i.response_id)?.mine===!0);return{items:o,messages:[...d,...r.values()],responses:[...u,...s.values()],turn:this.turn,waiting:{approvals:p.filter(i=>i.status==="awaiting_approval"),outputs:p.filter(i=>i.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Se(this.voice,e):null}}};function Se(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function Y(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Re(t){return`${t.author??""}\0${t.client_id}`}function Te(t,e,n,s){let r=[...t.marks.values()].map((u,p)=>({m:u,i:p,at:R(t.text,Math.max(0,Number(u.text_offset)||0))}));r.sort((u,p)=>u.at-p.at||u.i-p.i);let a=[],o=[],d=0;for(let{m:u,at:p}of r)p>d&&a.push({type:"text",text:t.text.slice(d,p)}),d=Math.max(d,p),u.type==="thinking"?(a.push({type:"thinking",thinking:u.thinking}),o.push(u.thinking)):a.push(u.type==="tool"?{type:"tool",tool:u}:{type:"agent",agent:u});return d<t.text.length&&a.push({type:"text",text:t.text.slice(d)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:a,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:o,goal:s,history:!1,truncated:!1}}function Pe(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:Y(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var M=[["ApiKeyAuth","userJWT"]];function Z(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:M,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:M,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let a={path:n};return s!==void 0&&(a.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:M,answers:{200:"raw"},query:a,signal:r})).data.blob()}}}var O=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},X=new WeakMap;async function te(t,e,n,s={},r=()=>{},a){let{pattern:o,events:d,messages:u,durable:p,chat:i}=Ie(e),c=Oe(o,n),b=X.get(t);b||X.set(t,b=new Map);let w=b,g=w.get(c)??{count:0};w.set(c,g),g.count++;let f=t.channel(c,p&&s.history!==!1?{after:0}:{});if(i&&!g.chat){let h=n.chatId,v=new I(r,a,typeof h=="string"&&h!==""?h:void 0);g.chat=v,g.unchat=f.on("broadcast",y=>{y.event==="chat"&&v.takePayload(y.payload)})}let x=()=>{--g.count>0||(w.delete(c),g.unchat?.(),g.chat?.end(),f.leave())};try{await f.join()}catch{let h=f.state==="refused"?ee(f.refusal,"unavailable"):"socket closed";throw x(),new O(`gateway ${JSON.stringify(c)} was not joined: ${h}`,h)}let C=!1,S=new Set,B=()=>{if(!C){C=!0,we();for(let h of[...S])h();x()}},we=f.onClosed(B),q=h=>{if(C)return()=>{};let v=f.on("broadcast",m=>{typeof m.event=="string"&&d.has(m.event)&&h(m.event,k(m.payload))}),y=()=>{S.delete(y),v()};return S.add(y),y},J={topic:c,get seq(){return f.logSeq},on(h,v){if(typeof h=="function")return q((y,m)=>h({event:y,payload:m}));if(!d.has(h))throw new TypeError(`gateway ${JSON.stringify(o)} declares no event ${JSON.stringify(String(h))}`);if(typeof v!="function")throw new TypeError(`gateway ${JSON.stringify(o)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return q((y,m)=>{y===h&&v(m)})},off(h){S.has(h)&&h()},async send(h,v){if(!u.has(h))throw new TypeError(`gateway ${JSON.stringify(o)} declares no message ${JSON.stringify(String(h))}`);let y=C?{status:"error",response:{reason:"not joined"}}:await f.push("broadcast",{type:"broadcast",event:h,payload:v});if(y.status==="ok")return k(y.response.reply);let m=ee(y.response,"unavailable");throw new O(`gateway ${JSON.stringify(c)} did not take ${JSON.stringify(h)}: ${m}`,m)},leave:B};return i&&Object.defineProperty(J,"chat",{value:g.chat,enumerable:!0}),J}function Ie(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function Oe(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),a=Object.hasOwn(n,r)?n[r]:void 0;if(typeof a!="string"||a==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(a.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return a}).join(":")}function ee(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var D=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
3
|
-
`);let n=[],s=this.pending.indexOf(`
|
|
4
|
-
`);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let a=r.endsWith("\r")?r.slice(0,-1):r;if(a==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
|
-
`)}),this.dataLines=[],this.eventName=void 0;else if(!a.startsWith(":")){if(a.startsWith("data:")){let o=a.slice(5);this.dataLines.push(o.startsWith(" ")?o.slice(1):o)}else if(a.startsWith("event:")){let o=a.slice(6);this.eventName=o.startsWith(" ")?o.slice(1):o}}s=this.pending.indexOf(`
|
|
6
|
-
`)}return n}};async function*ne(t,e){let n=t.getReader(),s=new TextDecoder,r=new D;try{for(;;){let{done:a,value:o}=await n.read();if(a)break;for(let d of r.consume(s.decode(o,{stream:!0}))){if(d.event==="error")throw new l("network",{code:"stream_failed",message:`stream failed: ${d.payload}`});let u;try{u=JSON.parse(d.payload)}catch{throw new l("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${d.payload.slice(0,120)}`})}yield k(u)}}}finally{e.abort();try{await n.cancel()}catch{}}}var $e={},re=new WeakMap;function pt(t,e,n,s,r,a=()=>{}){re.set(t,{project:e,machine:n,storage:s,socket:r,me:a})}var ae=new Map,se=new WeakMap;function ht(t,e,n,s,r){if(!U(e))throw new l("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let a=Q(t);if(!V(n))throw new TypeError(`${JSON.stringify(String(n))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);z(s),de(r);for(let o of Object.keys(r))if(H(o))throw oe(o);(ae.get(e)??Ge(e)).set(a,{machine:n,url:s,tree:r})}function Ge(t){let e=new Map;return ae.set(t,e),Object.defineProperty($e,t,{configurable:!0,get(){return je(this,t,e)}}),e}function je(t,e,n){let s=re.get(t);if(!s)return;let r=n.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...n.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let a=se.get(t);a||se.set(t,a=new Map);let o=a.get(e);if(o?.registration===r)return o.ns;let d={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine},u=Object.assign({call:(p,i,c)=>qe(d.machine,p,i,c),join:(p,i,c)=>te(s.socket,p,i,c,s.me,Z(s.storage))},le(r.tree,d));return a.set(e,{registration:r,ns:u}),u}function oe(t){return new l("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(t)}: the name is reserved.`})}function ie(t){return typeof t.path=="string"&&typeof t.method=="string"}function Ae(t,e){if(t.pathParams!==void 0){if(!Array.isArray(t.pathParams)||!t.pathParams.every(n=>typeof n=="string"))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let n of t.pathParams)if(!t.path.includes(`{${n}}`))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${n}' has no '{${n}}' placeholder in the path.`})}if(t.sse!==void 0&&typeof t.sse!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(t.idempotent!==void 0&&typeof t.idempotent!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(t.upload!==void 0&&typeof t.upload!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(t.upload===!0&&(t.method!=="POST"||t.sse===!0))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(t.sse===!0&&t.input==="query")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(t.input!==void 0&&t.input!=="body"&&t.input!=="query"&&t.input!=="none")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(t.errors!==void 0){for(let[n,s]of Object.entries(t.errors))if(typeof s!="function")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${n}'] must be a function.`})}}function de(t){if(typeof t!="object"||t===null)throw new l("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)throw new l("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[n,s]of Object.entries(t)){if(P(n))throw oe(n);typeof s=="object"&&s!==null&&ie(s)?(s.method=s.method.toUpperCase(),Ae(s,s.path)):de(s)}}function le(t,e){if(ie(t))return t.upload===!0?async(...s)=>De(e,t,s):async(...s)=>he(e.machine(),t,s);let n={};for(let[s,r]of Object.entries(t))n[s]=le(r,e);return n}function ue(t){if(t==null)return"";let e=Object.entries(t).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new l("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function ce(t,e,n){try{return _(t.path,e,n)}catch(s){if(!T(s)||s.code!=="invalid_path_parameter")throw s;let r=String(n);throw new l("validation",{code:"invalid_path_parameter",message:`${t.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function pe(t,e){let n=t.pathParams??[],s=t.path;for(let r=0;r<n.length;r++){let a=e[r];if(typeof a!="string"&&typeof a!="number")throw new l("validation",{code:"missing_path_param",message:`${t.path}: path parameter '${n[r]}' must be a string or number`});s=s.replace(`{${n[r]}}`,ce(t,`path parameter '${n[r]}'`,a))}return s}var Ne=new Set(["POST","PUT","PATCH","DELETE"]);async function he(t,e,n){let s=e.pathParams??[],r=pe(e,n);if(e.input==="none"&&n.length>s.length+1)throw new l("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let a=e.input==="none"?void 0:n[s.length],o=e.input==="none"?s.length:s.length+1,d=n[o],u;if(e.input==="query")r+=ue(a);else if(e.input!=="none")if(e.method==="GET"){if(a!==void 0)throw new l("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else u=a;let p={...d?.headers};Ne.has(e.method)&&!Object.keys(p).some(i=>i.toLowerCase()==="idempotency-key")&&(p["Idempotency-Key"]=G());try{return e.sse===!0?await Fe(t,e,r,u,p,d?.signal):await Le(t,e,r,u,p,d?.signal)}catch(i){throw ge(e,i)}}function ge(t,e){return t.errors&&K(e)&&Object.hasOwn(t.errors,e.code)?t.errors[e.code](e):e}var Me=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function De(t,e,n){let s=e.pathParams??[],r=pe(e,n),a=e.input==="none"?s.length:s.length+1;if(n.length>a+2)throw new l("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let o=e.input==="none"?void 0:n[s.length],d=n[a],u=n[a+1];if(!(d instanceof Blob))throw new l("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let p=`/storage/upload/${t.name}/${ce(e,"the route",r.slice(1))}`;e.input==="query"&&(p+=ue(o));let i=Be(e.input==="query"?void 0:o,d),c=i.body.size,b=0,w=g=>{b=g;try{u?.onProgress?.({loaded:g,total:c})}catch{}};u?.onProgress&&w(0);try{let g;try{let f={op:`Upload ${e.path}`,method:"POST",path:p,auth:Me,answers:fe,body:{kind:"raw",contentType:i.type,value:i.body},signal:u?.signal,...u?.onProgress?{onUploadProgress:x=>w(x)}:{}};g=(await t.storage.send(f)).data}catch(f){throw T(f)?N(f):f}return u?.onProgress&&b<c&&w(c),await me(e,g,u?.signal)}catch(g){throw ge(e,g)}}function Be(t,e){let n=`Palbase-${G()}`,s=d=>d.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",a=(d,u)=>`--${n}\r
|
|
7
|
-
Content-Disposition: form-data; ${d}\r
|
|
8
|
-
Content-Type: ${u}\r
|
|
9
|
-
\r
|
|
10
|
-
`,o=[];return t!==void 0&&o.push(a('name="body"',"application/json"),JSON.stringify(t),`\r
|
|
11
|
-
`),o.push(a(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
|
|
12
|
-
--${n}--\r
|
|
13
|
-
`),{body:new Blob(o),type:`multipart/form-data; boundary=${n}`}}async function qe(t,e,n,s){if(typeof e!="string"||e===""||e==="/")throw new l("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return he(t(),{method:"POST",path:r},[n,s])}var fe=Object.fromEntries(Array.from({length:100},(t,e)=>[200+e,"raw"])),Je=[["userJWT"],[]];async function ye(t,e,n,s,r,a){let o={op:`${e.method} ${e.path}`,method:e.method,path:n,auth:Je,answers:fe,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:a};try{return(await t.send(o)).data}catch(d){throw T(d)?N(d):d}}async function Le(t,e,n,s,r,a){return me(e,await ye(t,e,n,s,r,a),a)}async function me(t,e,n){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(a){throw n?.aborted?a:new l("network",{code:"network_error",message:`${t.method} ${t.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:a})}if(r!=="")try{return k(JSON.parse(r))}catch(a){throw new l("decode",{code:"invalid_json",message:`${t.method} ${t.path}: the answer is not JSON`,status:e.status,requestId:s,cause:a})}}async function Fe(t,e,n,s,r,a){let o=new AbortController;a&&(a.aborted?o.abort():a.addEventListener("abort",()=>o.abort(),{once:!0}));let d=await ye(t,e,n,s,{accept:"text/event-stream",...r},o.signal);if(!d.body)throw new l("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:d.status});return ne(d.body,o)}export{l as a,K as b,Ee as c,U as d,Z as e,O as f,$e as g,pt as h,ht as i};
|