palbase 0.11.2 → 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.
Files changed (62) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +11 -11
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{5FJNJOWL.js → 2J3RT5GV.js} +2 -2
  8. package/dist/chunks/2QE7TIVQ.js +6 -0
  9. package/dist/chunks/{NT7K4S2X.js → 3CFHP6H7.js} +1 -1
  10. package/dist/chunks/5MMZNWFL.js +21 -0
  11. package/dist/chunks/5U3YIYBP.js +13 -0
  12. package/dist/chunks/{PF3S7VGN.js → 6SINT3YD.js} +1 -1
  13. package/dist/chunks/{MWKPDZHT.js → 7MBBS4BC.js} +2 -2
  14. package/dist/chunks/{XOPSQEWX.js → AZ3Z3ME2.js} +1 -1
  15. package/dist/chunks/BJL7ZBG7.js +2 -0
  16. package/dist/chunks/{W6LUHPMU.js → C2WFUOF7.js} +2 -2
  17. package/dist/chunks/{4OASGT7Q.js → C3UPTONG.js} +7 -7
  18. package/dist/chunks/CMDUL3VE.js +2 -0
  19. package/dist/chunks/{FIWWCA6S.js → EQ4HNSWU.js} +2 -2
  20. package/dist/chunks/{E765DY7Q.js → EWXQUZSU.js} +2 -2
  21. package/dist/chunks/{6FV2T52H.js → GXLUNOFZ.js} +1 -1
  22. package/dist/chunks/L4NDDBYW.js +2 -0
  23. package/dist/chunks/{4NC6D3AY.js → MERWSLS2.js} +2 -2
  24. package/dist/chunks/MYHRHZYN.js +2 -0
  25. package/dist/chunks/{BPFIGT6G.js → QRWMVBF4.js} +2 -2
  26. package/dist/chunks/{SI2TXLYT.js → R26ROMEG.js} +1 -1
  27. package/dist/chunks/{W7UOMPUA.js → SGCYJGSM.js} +2 -2
  28. package/dist/chunks/{XQUWS373.js → SGDOCWYB.js} +2 -2
  29. package/dist/chunks/{NZRVCF6B.js → W33A3OUV.js} +1 -1
  30. package/dist/cli.js +132 -131
  31. package/dist/refuse/ai.js +1 -1
  32. package/dist/refuse/backend.js +1 -1
  33. package/dist/refuse/server.js +1 -1
  34. package/dist/server/index.js +2 -2
  35. package/dist/server/testing.js +2 -2
  36. package/dist/web/index.js +2 -2
  37. package/dist/web/message.js +2 -2
  38. package/dist/web/palbe.js +2 -2
  39. package/dist/web/paywall.js +2 -2
  40. package/dist/web/push-sw.js +1 -1
  41. package/dist/web/ssr.js +2 -2
  42. package/dist/web/vite.js +2 -2
  43. package/package.json +2 -2
  44. package/types/ai/src/chats.d.ts +7 -0
  45. package/types/backend/src/index.d.ts +1 -0
  46. package/types/backend/src/transit.d.ts +39 -0
  47. package/types/internal/src/modules/ai.d.ts +8 -0
  48. package/types/internal/src/modules/purchases.d.ts +95 -11
  49. package/types/internal/src/modules/secrets.d.ts +148 -1
  50. package/types/internal/src/transit-marks.d.ts +51 -0
  51. package/types/internal/src/transit.d.ts +108 -0
  52. package/types/server/src/index.d.ts +1 -0
  53. package/types/server/src/server.d.ts +8 -0
  54. package/types/server/src/transit.d.ts +91 -0
  55. package/types/web/src/backend-transit.d.ts +23 -0
  56. package/types/web/src/backends.d.ts +8 -1
  57. package/types/web/src/index.d.ts +1 -0
  58. package/dist/chunks/6S6MUPJA.js +0 -2
  59. package/dist/chunks/D5A6USBN.js +0 -6
  60. package/dist/chunks/QNJK2UIR.js +0 -20
  61. package/dist/chunks/VPFDS7G7.js +0 -2
  62. package/dist/chunks/WUPBDP6G.js +0 -13
@@ -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;
@@ -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';
@@ -1,2 +0,0 @@
1
- /*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
2
- import"./PF3S7VGN.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};
@@ -1,6 +0,0 @@
1
- /*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
2
- import"./PF3S7VGN.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&&lt(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};