@enlitt/sdk 0.0.0-stage → 0.1.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 (117) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +63 -2
  4. package/dist/browser/auth.d.cts +44 -0
  5. package/dist/browser/auth.d.ts +45 -0
  6. package/dist/browser/auth.d.ts.map +1 -0
  7. package/dist/browser.cjs +35 -0
  8. package/dist/browser.cjs.map +1 -0
  9. package/dist/browser.d.cts +12 -0
  10. package/dist/browser.d.ts +13 -0
  11. package/dist/browser.d.ts.map +1 -0
  12. package/dist/browser.js +32 -0
  13. package/dist/browser.js.map +1 -0
  14. package/dist/chunk-2BGWYTJM.cjs +1097 -0
  15. package/dist/chunk-2BGWYTJM.cjs.map +1 -0
  16. package/dist/chunk-6OWXYBBT.cjs +146 -0
  17. package/dist/chunk-6OWXYBBT.cjs.map +1 -0
  18. package/dist/chunk-NI6WH5FI.js +33 -0
  19. package/dist/chunk-NI6WH5FI.js.map +1 -0
  20. package/dist/chunk-O6ASIA3X.js +866 -0
  21. package/dist/chunk-O6ASIA3X.js.map +1 -0
  22. package/dist/chunk-PPOUNWNA.cjs +895 -0
  23. package/dist/chunk-PPOUNWNA.cjs.map +1 -0
  24. package/dist/chunk-UVZMKGIL.js +1091 -0
  25. package/dist/chunk-UVZMKGIL.js.map +1 -0
  26. package/dist/chunk-V5TCSQ7C.js +143 -0
  27. package/dist/chunk-V5TCSQ7C.js.map +1 -0
  28. package/dist/chunk-YPA4R65T.cjs +35 -0
  29. package/dist/chunk-YPA4R65T.cjs.map +1 -0
  30. package/dist/core/errors.d.cts +262 -0
  31. package/dist/core/errors.d.ts +263 -0
  32. package/dist/core/errors.d.ts.map +1 -0
  33. package/dist/core/index.d.cts +24 -0
  34. package/dist/core/index.d.ts +25 -0
  35. package/dist/core/index.d.ts.map +1 -0
  36. package/dist/core/premium.d.cts +230 -0
  37. package/dist/core/premium.d.ts +231 -0
  38. package/dist/core/premium.d.ts.map +1 -0
  39. package/dist/core/session.d.cts +122 -0
  40. package/dist/core/session.d.ts +123 -0
  41. package/dist/core/session.d.ts.map +1 -0
  42. package/dist/core/sse.d.cts +79 -0
  43. package/dist/core/sse.d.ts +80 -0
  44. package/dist/core/sse.d.ts.map +1 -0
  45. package/dist/core/transport.d.cts +223 -0
  46. package/dist/core/transport.d.ts +224 -0
  47. package/dist/core/transport.d.ts.map +1 -0
  48. package/dist/core/usage.d.cts +35 -0
  49. package/dist/core/usage.d.ts +36 -0
  50. package/dist/core/usage.d.ts.map +1 -0
  51. package/dist/core.cjs +77 -0
  52. package/dist/core.cjs.map +1 -0
  53. package/dist/core.js +4 -0
  54. package/dist/core.js.map +1 -0
  55. package/dist/index.cjs +4 -0
  56. package/dist/index.cjs.map +1 -0
  57. package/dist/index.d.cts +16 -0
  58. package/dist/index.d.ts +17 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +3 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/openai/client.d.cts +72 -0
  63. package/dist/openai/client.d.ts +73 -0
  64. package/dist/openai/client.d.ts.map +1 -0
  65. package/dist/openai/index.d.cts +2 -0
  66. package/dist/openai/index.d.ts +3 -0
  67. package/dist/openai/index.d.ts.map +1 -0
  68. package/dist/openai/media.d.cts +108 -0
  69. package/dist/openai/media.d.ts +109 -0
  70. package/dist/openai/media.d.ts.map +1 -0
  71. package/dist/openai.cjs +623 -0
  72. package/dist/openai.cjs.map +1 -0
  73. package/dist/openai.js +617 -0
  74. package/dist/openai.js.map +1 -0
  75. package/dist/server/callback.d.cts +107 -0
  76. package/dist/server/callback.d.ts +108 -0
  77. package/dist/server/callback.d.ts.map +1 -0
  78. package/dist/server/client-sign-in.d.cts +77 -0
  79. package/dist/server/client-sign-in.d.ts +78 -0
  80. package/dist/server/client-sign-in.d.ts.map +1 -0
  81. package/dist/server/index.d.cts +20 -0
  82. package/dist/server/index.d.ts +21 -0
  83. package/dist/server/index.d.ts.map +1 -0
  84. package/dist/server/secrets.d.cts +46 -0
  85. package/dist/server/secrets.d.ts +47 -0
  86. package/dist/server/secrets.d.ts.map +1 -0
  87. package/dist/server-unavailable.cjs +8 -0
  88. package/dist/server-unavailable.cjs.map +1 -0
  89. package/dist/server-unavailable.d.cts +10 -0
  90. package/dist/server-unavailable.d.ts +11 -0
  91. package/dist/server-unavailable.d.ts.map +1 -0
  92. package/dist/server-unavailable.js +6 -0
  93. package/dist/server-unavailable.js.map +1 -0
  94. package/dist/server.cjs +880 -0
  95. package/dist/server.cjs.map +1 -0
  96. package/dist/server.js +795 -0
  97. package/dist/server.js.map +1 -0
  98. package/dist/vercel/index.d.cts +17 -0
  99. package/dist/vercel/index.d.ts +18 -0
  100. package/dist/vercel/index.d.ts.map +1 -0
  101. package/dist/vercel/language-model.d.cts +146 -0
  102. package/dist/vercel/language-model.d.ts +147 -0
  103. package/dist/vercel/language-model.d.ts.map +1 -0
  104. package/dist/vercel/premium-language-model.d.cts +127 -0
  105. package/dist/vercel/premium-language-model.d.ts +128 -0
  106. package/dist/vercel/premium-language-model.d.ts.map +1 -0
  107. package/dist/vercel/premium-media-model.d.cts +101 -0
  108. package/dist/vercel/premium-media-model.d.ts +102 -0
  109. package/dist/vercel/premium-media-model.d.ts.map +1 -0
  110. package/dist/vercel/standard-language-model.d.cts +104 -0
  111. package/dist/vercel/standard-language-model.d.ts +105 -0
  112. package/dist/vercel/standard-language-model.d.ts.map +1 -0
  113. package/dist/vercel.cjs +22 -0
  114. package/dist/vercel.cjs.map +1 -0
  115. package/dist/vercel.js +5 -0
  116. package/dist/vercel.js.map +1 -0
  117. package/package.json +139 -3
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The read end of the Enlitt session cookie.
3
+ *
4
+ * `specs/SDK-side routing.md` gives this file the session handle, the
5
+ * middleware, and the async-context accessors. It owns "the user logs in and
6
+ * their credits are just used": it carries Enlitt's opaque session token from
7
+ * the cookie Account's login callback already set, through an
8
+ * `AsyncLocalStorage` context, to whatever call site needs it, without ever
9
+ * reading, parsing, or validating what the token contains. Validity is
10
+ * Enlitt's answer to give at call time, not this file's to guess.
11
+ */
12
+ /**
13
+ * The canonical Enlitt session cookie name, and the default of both
14
+ * `CallbackConfig.cookieName` and `SessionMiddlewareOptions.cookieName`.
15
+ *
16
+ * A business that passes a custom `cookieName` to the callback must pass the
17
+ * identical value to the middleware. That is the one case the two ends can
18
+ * still disagree, and it is the business's own to keep consistent; the default
19
+ * is not, which is why it is one constant rather than two literals.
20
+ */
21
+ export declare const ENLITT_SESSION_COOKIE_NAME = "enlitt_session";
22
+ /**
23
+ * The request header that carries a session token from a game or native client
24
+ * with no cookie jar. Account's "Client sign-in handoff" gives the client the
25
+ * token, and the client sends it here on every request to the business backend.
26
+ * `enlittSessionMiddleware()` reads it only when `header: true` is passed.
27
+ */
28
+ export declare const ENLITT_SESSION_HEADER_NAME = "Enlitt-Session";
29
+ /**
30
+ * An opaque handle around Enlitt's session token.
31
+ *
32
+ * The token has no subject, expiry, or scope readable from the SDK side, and
33
+ * every fact about the user lives on Enlitt's servers. Deliberately just a
34
+ * string wrapper: exposing it as a bare `string` anywhere in the call surface
35
+ * would invite a business to construct or compare tokens as ordinary strings,
36
+ * and there is no format a business can legitimately synthesize.
37
+ */
38
+ export interface EnlittSession {
39
+ readonly token: string;
40
+ }
41
+ /**
42
+ * The only way to construct an `EnlittSession`.
43
+ *
44
+ * The token is a string the SDK never parses, decodes, validates, or
45
+ * inspects; this is what lets Enlitt rotate or restructure the underlying
46
+ * credential without a business shipping a release, and what keeps the
47
+ * business from ever holding an OAuth token or implementing a refresh.
48
+ * Constructing one from a value a business stored itself is legitimate and is
49
+ * how linked accounts and background jobs work; constructing one from a value
50
+ * the business derived, guessed, or built from a user identifier is not a
51
+ * session, and Enlitt rejects it at call time. The factory validates only
52
+ * that the token is a non-empty bounded string, because anything more would
53
+ * be inspecting a credential this module must treat as opaque.
54
+ */
55
+ export declare function enlittSession(token: string): EnlittSession;
56
+ /**
57
+ * Options for `enlittSessionMiddleware()`.
58
+ *
59
+ * `cookieName` exists solely to mirror a business's own custom
60
+ * `CallbackConfig.cookieName`; the default matches `ENLITT_SESSION_COOKIE_NAME`
61
+ * so the common case names nothing.
62
+ *
63
+ * `header` opts in to the `Enlitt-Session` header as the session source for
64
+ * clients without a cookie jar. It defaults to `false` so a browser-only
65
+ * business never accepts a token from a header it does not expect. The header
66
+ * is a bearer credential like the cookie: serve these routes over https and
67
+ * keep it out of logs. It is not CSRF-relevant, since a browser never attaches
68
+ * it on its own.
69
+ */
70
+ export interface SessionMiddlewareOptions {
71
+ cookieName?: string;
72
+ header?: boolean;
73
+ }
74
+ /**
75
+ * The shape `enlittSessionMiddleware()` returns.
76
+ *
77
+ * Framework-agnostic over Web `Request` and `Response`, exactly as Account's
78
+ * callback handlers are: v1 ships no per-framework adapter, so this is the
79
+ * one shape every framework's own middleware layer can wrap.
80
+ */
81
+ export type EnlittMiddleware = (request: Request, next: () => Promise<Response>) => Promise<Response>;
82
+ /**
83
+ * Reads the Enlitt session cookie from an incoming request, runs `next()`
84
+ * with an `AsyncLocalStorage` context carrying the resulting `EnlittSession`
85
+ * or an explicit `null`, and leaves the context when the request ends.
86
+ *
87
+ * It never rejects a request: plenty of a business's routes are for
88
+ * signed-out visitors, and deciding the business's authentication policy is
89
+ * not this middleware's job. It performs no network call and no validation,
90
+ * because validity is Enlitt's answer to give at call time and pre-validating
91
+ * here would add a round trip to every request, including the ones that never
92
+ * call a model. The cookie lives on the business's own domain and was set by
93
+ * Enlitt's login callback, so no cross-site cookie, third-party storage, or
94
+ * browser-side token is involved.
95
+ */
96
+ export declare function enlittSessionMiddleware(options?: SessionMiddlewareOptions): EnlittMiddleware;
97
+ /**
98
+ * Runs `fn` with an explicit `EnlittSession` (or `null`) bound as the ambient
99
+ * session for its entire synchronous and asynchronous extent.
100
+ *
101
+ * The escape hatch for a framework whose middleware shape
102
+ * `enlittSessionMiddleware()` cannot wrap directly: a business on such a
103
+ * framework establishes the same context in one line instead of waiting on a
104
+ * per-framework adapter that v1 does not ship.
105
+ */
106
+ export declare function runWithEnlittSession<T>(session: EnlittSession | null, fn: () => T): T;
107
+ /**
108
+ * Returns the ambient session for the current request context.
109
+ *
110
+ * Throws `EnlittConfigurationError` when there is no context at all: no
111
+ * context means the middleware is not installed on this path, which is the
112
+ * business's own wiring bug, and treating that as "signed out" would make
113
+ * every user of a misconfigured deployment silently unauthenticated. Returns
114
+ * `null` when there is a context and no session, which is the genuine
115
+ * signed-out state a business checks before calling a model. These two
116
+ * conditions must never collapse into one: a deployment bug and a
117
+ * signed-out visitor look identical at the call site and must not be
118
+ * reported identically. A session this returns may still be expired or
119
+ * revoked; that is not knowable locally, so the call carries it and Enlitt
120
+ * answers with `personal_login_required` if it must.
121
+ */
122
+ export declare function getEnlittSession(): EnlittSession | null;
123
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/core/session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAE3D;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAa3D;;;;;;;;GAQG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAQ1D;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,wBAAwB;IACvC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC7B,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,MAAM,OAAO,CAAC,QAAQ,CAAC,KAC1B,OAAO,CAAC,QAAQ,CAAC,CAAC;AAavB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,CAAC,EAAE,wBAAwB,GAAG,gBAAgB,CAwB5F;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,OAAO,EAAE,aAAa,GAAG,IAAI,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAErF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,IAAI,aAAa,GAAG,IAAI,CAQvD"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Generic server-sent-event framing. This file knows nothing about Enlitt:
3
+ * no event name, no sequence rule, no Enlitt-specific type. It turns a raw
4
+ * byte stream into a stream of parsed `{ event, data }` pairs and nothing
5
+ * more. It is kept separate from the modules that interpret those events
6
+ * because framing — splitting arbitrary chunk boundaries into well-formed
7
+ * lines and fields — is the largest and most failure-prone piece of the
8
+ * standard streaming path, and is worth getting right and testing against
9
+ * byte-level fixtures on its own.
10
+ */
11
+ /**
12
+ * One decoded SSE event. Only `event` and `data` are exposed because those
13
+ * are the only fields a caller of this module ever needs: `id` and `retry`
14
+ * are standard SSE fields this parser recognizes and consumes (so it never
15
+ * misparses a line beginning with `id:` or `retry:` as a comment or an
16
+ * unknown field), but neither reconnection nor last-event-id replay is a
17
+ * concept this byte-framing layer implements, so their values are parsed
18
+ * and discarded rather than threaded through as dead fields on every event.
19
+ */
20
+ export interface SseEvent {
21
+ readonly event: string;
22
+ readonly data: string;
23
+ }
24
+ /**
25
+ * Raised when the input violates SSE framing bounds — a line or an event
26
+ * grew past the deployed maximum before a terminator ever arrived — which
27
+ * is the one failure mode this purely-syntactic layer can detect on its
28
+ * own. It carries the stable wire code `malformed_response` as `code` so a
29
+ * caller can fold it into Enlitt's typed error hierarchy without this file
30
+ * importing that hierarchy: this module must stay ignorant of Enlitt, so it
31
+ * raises its own narrow, self-contained error shape instead of reaching for
32
+ * one defined elsewhere.
33
+ */
34
+ export declare class SseFramingError extends Error {
35
+ readonly code: "malformed_response";
36
+ constructor(message: string);
37
+ }
38
+ /**
39
+ * Maximum size, in UTF-8 bytes, of a single SSE line (a `field: value` line,
40
+ * a comment line, or the blank delimiter line) before framing fails rather
41
+ * than growing an unterminated line without bound. The spec names this bound
42
+ * as "the deployed event and line size bounds" without giving a number;
43
+ * 16 KiB comfortably covers any single field line a JSON-carrying `data:`
44
+ * chunk would reasonably use and is called out here, exported, so the
45
+ * concrete figure is visible and easy to reconcile against whatever value
46
+ * the deployment settles on.
47
+ */
48
+ export declare const MAX_SSE_LINE_BYTES: number;
49
+ /**
50
+ * Maximum size, in UTF-8 bytes, of all lines belonging to one SSE event
51
+ * (from the end of the previous blank line to the next one) before framing
52
+ * fails rather than accumulating an unterminated event without bound. Not
53
+ * named by the spec; 256 KiB is chosen as a multiple of `MAX_SSE_LINE_BYTES`
54
+ * generous enough for a multi-line `data:` payload and is exported for the
55
+ * same reason `MAX_SSE_LINE_BYTES` is.
56
+ */
57
+ export declare const MAX_SSE_EVENT_BYTES: number;
58
+ /**
59
+ * Turns a raw byte stream into a stream of parsed SSE events. Decodes UTF-8
60
+ * incrementally so a multi-byte character split across an arbitrary chunk
61
+ * boundary decodes correctly, splits on CRLF/CR/LF line terminators so a
62
+ * terminator split across a boundary is recognized as one delimiter rather
63
+ * than two, and accumulates `event:`/`data:`/`id:`/`retry:` fields into one
64
+ * `SseEvent` per blank-line-delimited block.
65
+ *
66
+ * It is built as a pull-driven `ReadableStream` rather than eagerly reading
67
+ * and enqueuing everything: `pull` reads from `source` only until it can
68
+ * emit one event and then returns, so the platform's own backpressure
69
+ * mechanics stop new reads until the consumer asks for more, and `cancel`
70
+ * forwards straight to the source's reader. Only the event currently being
71
+ * assembled — a handful of small strings — is ever held in memory; nothing
72
+ * about already-dispatched or not-yet-arrived events is buffered.
73
+ *
74
+ * Fails the returned stream with `SseFramingError` (`code: "malformed_response"`)
75
+ * if a line or event exceeds the deployed size bounds, so an unterminated
76
+ * or malicious stream cannot grow this parser's memory without bound. Never
77
+ * logs event data.
78
+ */
79
+ export declare function createSseEventStream(source: ReadableStream<Uint8Array>): ReadableStream<SseEvent>;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Generic server-sent-event framing. This file knows nothing about Enlitt:
3
+ * no event name, no sequence rule, no Enlitt-specific type. It turns a raw
4
+ * byte stream into a stream of parsed `{ event, data }` pairs and nothing
5
+ * more. It is kept separate from the modules that interpret those events
6
+ * because framing — splitting arbitrary chunk boundaries into well-formed
7
+ * lines and fields — is the largest and most failure-prone piece of the
8
+ * standard streaming path, and is worth getting right and testing against
9
+ * byte-level fixtures on its own.
10
+ */
11
+ /**
12
+ * One decoded SSE event. Only `event` and `data` are exposed because those
13
+ * are the only fields a caller of this module ever needs: `id` and `retry`
14
+ * are standard SSE fields this parser recognizes and consumes (so it never
15
+ * misparses a line beginning with `id:` or `retry:` as a comment or an
16
+ * unknown field), but neither reconnection nor last-event-id replay is a
17
+ * concept this byte-framing layer implements, so their values are parsed
18
+ * and discarded rather than threaded through as dead fields on every event.
19
+ */
20
+ export interface SseEvent {
21
+ readonly event: string;
22
+ readonly data: string;
23
+ }
24
+ /**
25
+ * Raised when the input violates SSE framing bounds — a line or an event
26
+ * grew past the deployed maximum before a terminator ever arrived — which
27
+ * is the one failure mode this purely-syntactic layer can detect on its
28
+ * own. It carries the stable wire code `malformed_response` as `code` so a
29
+ * caller can fold it into Enlitt's typed error hierarchy without this file
30
+ * importing that hierarchy: this module must stay ignorant of Enlitt, so it
31
+ * raises its own narrow, self-contained error shape instead of reaching for
32
+ * one defined elsewhere.
33
+ */
34
+ export declare class SseFramingError extends Error {
35
+ readonly code: "malformed_response";
36
+ constructor(message: string);
37
+ }
38
+ /**
39
+ * Maximum size, in UTF-8 bytes, of a single SSE line (a `field: value` line,
40
+ * a comment line, or the blank delimiter line) before framing fails rather
41
+ * than growing an unterminated line without bound. The spec names this bound
42
+ * as "the deployed event and line size bounds" without giving a number;
43
+ * 16 KiB comfortably covers any single field line a JSON-carrying `data:`
44
+ * chunk would reasonably use and is called out here, exported, so the
45
+ * concrete figure is visible and easy to reconcile against whatever value
46
+ * the deployment settles on.
47
+ */
48
+ export declare const MAX_SSE_LINE_BYTES: number;
49
+ /**
50
+ * Maximum size, in UTF-8 bytes, of all lines belonging to one SSE event
51
+ * (from the end of the previous blank line to the next one) before framing
52
+ * fails rather than accumulating an unterminated event without bound. Not
53
+ * named by the spec; 256 KiB is chosen as a multiple of `MAX_SSE_LINE_BYTES`
54
+ * generous enough for a multi-line `data:` payload and is exported for the
55
+ * same reason `MAX_SSE_LINE_BYTES` is.
56
+ */
57
+ export declare const MAX_SSE_EVENT_BYTES: number;
58
+ /**
59
+ * Turns a raw byte stream into a stream of parsed SSE events. Decodes UTF-8
60
+ * incrementally so a multi-byte character split across an arbitrary chunk
61
+ * boundary decodes correctly, splits on CRLF/CR/LF line terminators so a
62
+ * terminator split across a boundary is recognized as one delimiter rather
63
+ * than two, and accumulates `event:`/`data:`/`id:`/`retry:` fields into one
64
+ * `SseEvent` per blank-line-delimited block.
65
+ *
66
+ * It is built as a pull-driven `ReadableStream` rather than eagerly reading
67
+ * and enqueuing everything: `pull` reads from `source` only until it can
68
+ * emit one event and then returns, so the platform's own backpressure
69
+ * mechanics stop new reads until the consumer asks for more, and `cancel`
70
+ * forwards straight to the source's reader. Only the event currently being
71
+ * assembled — a handful of small strings — is ever held in memory; nothing
72
+ * about already-dispatched or not-yet-arrived events is buffered.
73
+ *
74
+ * Fails the returned stream with `SseFramingError` (`code: "malformed_response"`)
75
+ * if a line or event exceeds the deployed size bounds, so an unterminated
76
+ * or malicious stream cannot grow this parser's memory without bound. Never
77
+ * logs event data.
78
+ */
79
+ export declare function createSseEventStream(source: ReadableStream<Uint8Array>): ReadableStream<SseEvent>;
80
+ //# sourceMappingURL=sse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/core/sse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;;;;;GAQG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;;GASG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,QAAQ,CAAC,IAAI,EAAG,oBAAoB,CAAU;IAE9C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,kBAAkB,QAAY,CAAC;AAE5C;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,QAAa,CAAC;AA8H9C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC,QAAQ,CAAC,CAiEjG"}
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The module's single authenticated exit to Enlitt.
3
+ *
4
+ * `specs/SDK-side routing.md` gives this file three jobs that must live in
5
+ * exactly one place: the definition of the internal client
6
+ * (`InternalEnlittClient`, built once per factory call by
7
+ * `createInternalClient()`), the one place a personal session is resolved
8
+ * (`InternalEnlittClient.resolveSession`), and the one function that ever
9
+ * issues an HTTP request to Enlitt (`requestEnlitt()`). Both the standard and
10
+ * premium model files call through this file rather than `fetch` directly, so
11
+ * every header, every safety check, and every retry the spec requires exists
12
+ * exactly once instead of once per model.
13
+ *
14
+ * It owns exactly two internal retries and no others: the bounded, jittered
15
+ * wait that absorbs `rate_limit_exceeded` (inside `requestEnlitt()` itself,
16
+ * because it applies uniformly to every request this module sends), and a
17
+ * bounded transient retry of a premium terminal report under one unchanged
18
+ * `report_id`/`Idempotency-Key` (`reportEnlittPremiumTerminal()`, layered on
19
+ * top of `requestEnlitt()` because it applies to exactly one call shape and
20
+ * must never leak onto a preflight, a standard call, or a refusal). Every
21
+ * other failure — every refusal, every conflict, every `4xx` other than `429
22
+ * rate_limit_exceeded` — is normalized and thrown once, never retried here.
23
+ *
24
+ * It never accepts a personal identity as a caller-supplied parameter: the
25
+ * only personal value that ever leaves this file is the opaque token
26
+ * `client.resolveSession()` returns, and no argument, option, or request body
27
+ * field can supply or override it. It never logs or returns that token,
28
+ * prompt content, or a raw provider error, and it never runs in a browser —
29
+ * it is reachable only through `@enlitt/sdk/server`, which the package export
30
+ * map keeps out of the `browser` condition.
31
+ */
32
+ import { EnlittError } from "./errors.cjs";
33
+ import { type EnlittSession } from "./session.cjs";
34
+ /**
35
+ * The SDK's own version, sent as `X-Enlitt-SDK-Version` so Enlitt's own logs
36
+ * can tell which client behavior produced a given request without the header
37
+ * carrying anything about the business or the user.
38
+ *
39
+ * A literal rather than a `package.json` import: this package ships as both
40
+ * ESM and CJS, its `tsup` build does not embed the manifest, and a JSON
41
+ * import here would tie a request-time value to a file layout assumption
42
+ * this module has no other reason to make. It must be bumped by hand
43
+ * alongside `package.json`'s `version` field.
44
+ */
45
+ export declare const SDK_VERSION = "0.1.1";
46
+ /**
47
+ * Caller-supplied tuning for the rate-limit wait. Every field is optional
48
+ * because `createInternalClient()` folds it over the SDK's own defaults
49
+ * exactly once, at construction, which is what lets every later read of
50
+ * `client.rateLimit` assume every field but `onRateLimit` is present.
51
+ */
52
+ export interface EnlittRateLimitRetryOptions {
53
+ /** Upper bound on attempts, including the first (minimum 1). Default {@link DEFAULT_RATE_LIMIT_MAX_ATTEMPTS}. */
54
+ readonly maxAttempts?: number;
55
+ /** Upper bound on total time spent waiting, measured from the first refusal. Default {@link DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS}. */
56
+ readonly maxTotalWaitMs?: number;
57
+ /**
58
+ * Invoked once per wait, with the attempt number (1-based) about to be
59
+ * slept and the jittered delay in milliseconds. The only way a business
60
+ * observes a rate-limit wait without this module disclosing a plan fact.
61
+ */
62
+ readonly onRateLimit?: (attempt: number, delayMs: number) => void;
63
+ }
64
+ /**
65
+ * Constructor options for `createInternalClient()`.
66
+ *
67
+ * `secretKey` and `baseUrl` are exactly what `resolveBusinessAuthorizationHeader()`
68
+ * and the HTTPS assertion need and nothing more; neither this type nor the
69
+ * client it builds ever carries a personal identity, because the only
70
+ * personal value the transport ever sends is the token `resolveSession()`
71
+ * (built from `session`, or from the ambient context) produces at request
72
+ * time.
73
+ */
74
+ export interface EnlittOptions {
75
+ /** Forwarded to `resolveBusinessAuthorizationHeader()` unchanged. */
76
+ readonly secretKey?: string;
77
+ /**
78
+ * Enlitt's base URL. Resolves from this option, then `ENLITT_BASE_URL`, then
79
+ * the deployed Enlitt origin compiled into the package. Must be `https:`, or
80
+ * `http:` on a local host. Parsed and validated once, at construction.
81
+ */
82
+ readonly baseUrl?: string;
83
+ /**
84
+ * An explicit session, for a caller that cannot rely on the ambient
85
+ * `AsyncLocalStorage` context — a background job, or a framework
86
+ * `enlittSessionMiddleware()` cannot wrap. When absent, every call resolves
87
+ * the session from `getEnlittSession()` instead.
88
+ */
89
+ readonly session?: EnlittSession;
90
+ readonly rateLimit?: EnlittRateLimitRetryOptions;
91
+ /**
92
+ * Observes a failure `reportEnlittPremiumTerminal()` could not recover
93
+ * from after exhausting its bounded retry. There is no caller left to
94
+ * return the error to by the time this fires — the provider call this
95
+ * report describes has already completed — so this hook is the only way a
96
+ * business ever learns a terminal report did not land.
97
+ */
98
+ readonly onTerminalReportError?: (error: EnlittError) => void;
99
+ }
100
+ /**
101
+ * The internal client every request in this module is built from.
102
+ *
103
+ * Constructed once per factory call from the business's resolved secret and
104
+ * the deployed environment, and never held as nullable: holding a client at
105
+ * all is what makes a call managed, so there is no code path in this package
106
+ * that represents "no Enlitt configuration" as a null or optional client
107
+ * instead of failing at construction.
108
+ */
109
+ export interface InternalEnlittClient {
110
+ readonly baseUrl: string;
111
+ /** The full `Authorization` header value, e.g. `Bearer sk_...`. Never logged or returned. */
112
+ readonly businessAuthorization: string;
113
+ readonly sdkVersion: string;
114
+ /**
115
+ * The module's single session resolution. Returns the explicit
116
+ * `EnlittOptions.session` when one was given; otherwise defers to
117
+ * `getEnlittSession()`, which itself distinguishes "no middleware
118
+ * installed" (`EnlittConfigurationError`) from "signed out" (`null`,
119
+ * raised here as `EnlittLoginRequiredError` with `providerInvoked: false`).
120
+ * Both model files call this indirectly through `requestEnlitt()` rather
121
+ * than resolving a session themselves, which is what keeps the three
122
+ * outcomes from drifting apart between the standard and premium paths.
123
+ */
124
+ readonly resolveSession: () => EnlittSession;
125
+ readonly rateLimit: Required<Omit<EnlittRateLimitRetryOptions, "onRateLimit">> & Pick<EnlittRateLimitRetryOptions, "onRateLimit">;
126
+ readonly onTerminalReportError?: (error: EnlittError) => void;
127
+ }
128
+ /**
129
+ * Builds the internal client from a factory call's resolved options.
130
+ *
131
+ * Resolves the business authorization header eagerly (through
132
+ * `resolveBusinessAuthorizationHeader()`, the only path to that secret) so a
133
+ * missing or unusable key fails at construction, before any network call and
134
+ * before a provider is ever at risk of running unaccounted. Folds
135
+ * `rateLimit` over the SDK's defaults exactly once here, so no per-request
136
+ * code has to treat any field but `onRateLimit` as possibly absent.
137
+ */
138
+ export declare function createInternalClient(options: EnlittOptions): InternalEnlittClient;
139
+ /** One request this module knows how to issue. */
140
+ export interface EnlittRequestInit {
141
+ readonly path: string;
142
+ /** `POST` unless a read endpoint (`GET /v1/enlitt/usage`) says otherwise. */
143
+ readonly method?: "POST" | "GET";
144
+ /** Ignored for `GET`, which has no body. */
145
+ readonly body?: unknown;
146
+ /**
147
+ * Sent as `Idempotency-Key` (and, for a terminal report, equals the body's
148
+ * own `report_id`). Required for `POST`; a `GET` sends no `Idempotency-Key`,
149
+ * because `PROTOCOLS.md` forbids one on a route that does not deduplicate.
150
+ */
151
+ readonly callId?: string;
152
+ readonly accept: "application/json" | "text/event-stream";
153
+ readonly signal?: AbortSignal;
154
+ }
155
+ /**
156
+ * Issues one `POST` to `client.baseUrl + init.path` carrying every header the
157
+ * protocol requires and no other identity-bearing header, and returns the
158
+ * successful `Response` unread so a caller that needs a stream can consume
159
+ * it incrementally.
160
+ *
161
+ * This is the only function in the package that calls `fetch()` against
162
+ * Enlitt. Every safety property the spec requires — HTTPS, no redirects,
163
+ * bounded response size, normalization of every failure, and the
164
+ * `rate_limit_exceeded` wait — lives here so no call site can accidentally
165
+ * skip one.
166
+ */
167
+ export declare function requestEnlitt(client: InternalEnlittClient, init: EnlittRequestInit): Promise<Response>;
168
+ /**
169
+ * Retries a premium terminal report a bounded number of times on a
170
+ * transient failure, resending the identical `init` — the same body (and so
171
+ * the same `report_id`) and the same `Idempotency-Key` — on every attempt,
172
+ * which is what makes the retry safe: Enlitt's own idempotency on that key
173
+ * turns a duplicate send into a replay rather than a second report.
174
+ *
175
+ * Only a failure with no distinct business action of its own is treated as
176
+ * transient: a transport failure that never produced a response, or one of
177
+ * the three retryable server-side wire codes (`server_error`,
178
+ * `provider_error`, `no_capable_route`). A refusal, a conflict, or an
179
+ * exhausted `rate_limit_exceeded` wait (already retried once, inside
180
+ * `requestEnlitt()`) is never retried again here — retrying a refusal a
181
+ * second time under a different name is exactly what the spec forbids.
182
+ *
183
+ * Exhausting the bound reports the last error to `client.onTerminalReportError`
184
+ * and rethrows it, rather than swallowing it: the hook exists because the
185
+ * provider call this report describes has already finished and there is no
186
+ * result left to withhold from a caller, not because the failure stops
187
+ * mattering.
188
+ */
189
+ export declare function reportEnlittPremiumTerminal(client: InternalEnlittClient, init: EnlittRequestInit): Promise<Response>;
190
+ /**
191
+ * True for an unfollowed redirect under `redirect: "manual"`: a `3xx` status
192
+ * (server runtimes such as Workers and Node) or an `opaqueredirect` response
193
+ * with status `0` (browsers, which hide the redirect's details).
194
+ */
195
+ export declare function isRedirectResponse(response: Response): boolean;
196
+ /**
197
+ * The `transport_failed` error for a refused redirect. The body is cancelled
198
+ * unread so the connection is released; nothing from it is used.
199
+ */
200
+ export declare function redirectRefused(response: Response): EnlittError;
201
+ /**
202
+ * Reads a successful response's body as JSON, bounded by the same body-size
203
+ * limit every other read in this file uses. An oversized body or one that is
204
+ * not valid JSON is a `malformed_response` `EnlittError`, never a raw parser
205
+ * exception. Every JSON-bodied Enlitt response (begin, terminal report, usage,
206
+ * non-streaming standard response) is read through here, so no caller buffers
207
+ * an unbounded body or parses JSON on its own.
208
+ */
209
+ export declare function readEnlittJson(response: Response): Promise<unknown>;
210
+ /**
211
+ * HTTPS is required outside local development. `http:` is accepted only for
212
+ * the three hosts a developer's own machine can present as, and there is no
213
+ * environment flag that relaxes this — a business misconfiguring its own
214
+ * deployed base URL must fail loudly rather than send its business and
215
+ * personal credentials in the clear.
216
+ *
217
+ * Exported (in addition to being used per-request by `requestEnlitt()`) so
218
+ * `language-model.ts` can run the identical check once, at `enlitt()`
219
+ * construction, against the resolved `baseUrl` before any request is made —
220
+ * the spec requires base URL validation to happen at construction, not per
221
+ * call, and duplicating this rule there would let the two copies drift.
222
+ */
223
+ export declare function assertHttps(baseUrl: string): void;