@brickflow/http 0.0.14 → 0.0.16

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 (46) hide show
  1. package/README.md +272 -288
  2. package/dist/create-get.d.ts +12 -0
  3. package/dist/create-get.d.ts.map +1 -0
  4. package/dist/http.d.ts +46 -0
  5. package/dist/http.d.ts.map +1 -0
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.mjs +171 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/nuxt-DAmJOX58.js +233 -0
  11. package/dist/nuxt-DAmJOX58.js.map +1 -0
  12. package/dist/nuxt.d.ts +55 -0
  13. package/dist/nuxt.d.ts.map +1 -0
  14. package/dist/nuxt.mjs +2 -0
  15. package/dist/utils.d.ts +5 -0
  16. package/dist/utils.d.ts.map +1 -0
  17. package/package.json +30 -18
  18. package/src/app.d.ts +11 -0
  19. package/src/create-get.ts +43 -0
  20. package/src/http.ts +286 -0
  21. package/src/index.ts +3 -0
  22. package/src/nuxt.ts +355 -0
  23. package/src/utils.ts +50 -0
  24. package/dist/module.d.mts +0 -73
  25. package/dist/module.json +0 -12
  26. package/dist/module.mjs +0 -59
  27. package/dist/runtime/composables/useHttp.d.ts +0 -27
  28. package/dist/runtime/composables/useHttp.js +0 -197
  29. package/dist/runtime/http/client.d.ts +0 -3
  30. package/dist/runtime/http/client.js +0 -217
  31. package/dist/runtime/plugin.d.ts +0 -7
  32. package/dist/runtime/plugin.js +0 -56
  33. package/dist/runtime/types.d.ts +0 -21
  34. package/dist/runtime/utils/helpers.d.ts +0 -5
  35. package/dist/runtime/utils/helpers.js +0 -14
  36. package/dist/runtime/utils/index.d.ts +0 -6
  37. package/dist/runtime/utils/index.js +0 -5
  38. package/dist/runtime/utils/indexeddb.d.ts +0 -14
  39. package/dist/runtime/utils/indexeddb.js +0 -222
  40. package/dist/runtime/utils/middleware.d.ts +0 -8
  41. package/dist/runtime/utils/middleware.js +0 -20
  42. package/dist/runtime/utils/shared.d.ts +0 -83
  43. package/dist/runtime/utils/shared.js +0 -50
  44. package/dist/runtime/utils/typed.d.ts +0 -46
  45. package/dist/runtime/utils/typed.js +0 -9
  46. package/dist/types.d.mts +0 -11
@@ -1,222 +0,0 @@
1
- const dbCache = /* @__PURE__ */ new Map();
2
- const dbVersions = /* @__PURE__ */ new Map();
3
- const DB_PREFIX = "smart";
4
- const allowDb = ["smart-cache-v2"];
5
- export async function dbDeleteKeysWithPart(part, dbName, storeName) {
6
- const db = await openDB(dbName, storeName);
7
- const tx = db.transaction(storeName, "readwrite");
8
- const store = tx.objectStore(storeName);
9
- await new Promise((resolve, reject) => {
10
- const req = store.openCursor();
11
- req.onerror = () => reject(req.error);
12
- req.onsuccess = () => {
13
- const cursor = req.result;
14
- if (!cursor) {
15
- resolve();
16
- return;
17
- }
18
- const key = cursor.key;
19
- if (typeof key === "string" && key.startsWith(part) && !key.startsWith(`${part}/`)) {
20
- cursor.delete();
21
- }
22
- cursor.continue();
23
- };
24
- });
25
- await txDone(tx);
26
- }
27
- export async function dbGet(key, dbName, storeName) {
28
- const db = await openDB(dbName, storeName);
29
- const tx = db.transaction(storeName, "readonly");
30
- const store = tx.objectStore(storeName);
31
- const entry = await requestToPromise(store.get(key));
32
- await txDone(tx);
33
- if (entry === void 0) {
34
- return null;
35
- }
36
- if (entry.expiresAt === void 0 || Date.now() > entry.expiresAt) {
37
- const deleteTx = db.transaction(storeName, "readwrite");
38
- deleteTx.objectStore(storeName).delete(key);
39
- await txDone(deleteTx);
40
- return null;
41
- }
42
- return entry;
43
- }
44
- export async function dbSafeSet(key, value, dbName, storeName, ttl, retries = 1) {
45
- if (retries < 0) {
46
- throw new Error("IndexedDB quota exceeded permanently");
47
- }
48
- const db = await openDB(dbName, storeName);
49
- const entry = {
50
- expiresAt: Date.now() + ttl,
51
- hash: await hashData(value),
52
- key,
53
- value
54
- };
55
- try {
56
- const tx = db.transaction(storeName, "readwrite");
57
- const store = tx.objectStore(storeName);
58
- if (store.keyPath === null) {
59
- store.put(entry, key);
60
- } else {
61
- store.put(entry);
62
- }
63
- await txDone(tx);
64
- } catch (error) {
65
- const domError = error;
66
- if (domError?.name === "QuotaExceededError") {
67
- await dbEvictOldest(dbName, storeName);
68
- await dbSafeSet(key, value, dbName, storeName, ttl, retries - 1);
69
- return;
70
- }
71
- throw domError;
72
- }
73
- }
74
- export async function hashData(data) {
75
- const subtle = globalThis.crypto?.subtle;
76
- if (subtle) {
77
- const encoded = new TextEncoder().encode(JSON.stringify(data));
78
- const buffer = await subtle.digest("SHA-1", encoded);
79
- const bytes = Array.from(new Uint8Array(buffer));
80
- return bytes.map((byte) => byte.toString(16).padStart(2, "0")).join("");
81
- }
82
- return fastDevHash(data);
83
- }
84
- function attachDbGuards(db) {
85
- db.onversionchange = () => {
86
- try {
87
- db.close();
88
- } catch {
89
- }
90
- };
91
- }
92
- async function cleanupOldDatabases() {
93
- if (typeof indexedDB.databases !== "function") {
94
- return;
95
- }
96
- let databases;
97
- try {
98
- databases = await indexedDB.databases();
99
- } catch (error) {
100
- console.error(error);
101
- return;
102
- }
103
- for (const db of databases) {
104
- const name = db.name;
105
- if (!name || !name.startsWith(DB_PREFIX) || allowDb.includes(name)) {
106
- continue;
107
- }
108
- try {
109
- indexedDB.deleteDatabase(name);
110
- } catch {
111
- }
112
- }
113
- }
114
- async function dbEvictOldest(dbName, storeName) {
115
- const db = await openDB(dbName, storeName);
116
- const tx = db.transaction(storeName, "readwrite");
117
- const store = tx.objectStore(storeName);
118
- const total = await requestToPromise(store.count());
119
- if (total === 0) {
120
- await txDone(tx);
121
- return;
122
- }
123
- const limit = Math.floor(total / 2);
124
- if (limit === 0 || !store.indexNames.contains("expiresAt")) {
125
- await txDone(tx);
126
- return;
127
- }
128
- const index = store.index("expiresAt");
129
- let removed = 0;
130
- await new Promise((resolve, reject) => {
131
- const req = index.openCursor();
132
- req.onerror = () => reject(req.error);
133
- req.onsuccess = () => {
134
- const cursor = req.result;
135
- if (cursor === null || removed >= limit) {
136
- resolve();
137
- return;
138
- }
139
- cursor.delete();
140
- removed += 1;
141
- cursor.continue();
142
- };
143
- });
144
- await txDone(tx);
145
- if (removed === 0 && total > 0) {
146
- throw new Error("IndexedDB eviction removed 0 items");
147
- }
148
- }
149
- function fastDevHash(data) {
150
- const text = JSON.stringify(data);
151
- let hash = 0;
152
- for (let index = 0; index < text.length; index += 1) {
153
- const code = text.charCodeAt(index);
154
- hash = (hash << 5) - hash + code;
155
- hash |= 0;
156
- }
157
- return Math.abs(hash).toString(16);
158
- }
159
- async function openDB(dbName, storeName) {
160
- const currentVersion = dbVersions.get(dbName) ?? 1;
161
- const cacheKey = `${dbName}@v${currentVersion}`;
162
- const cached = dbCache.get(cacheKey);
163
- if (cached !== void 0) {
164
- return cached;
165
- }
166
- await cleanupOldDatabases();
167
- const openAtVersion = (version) => new Promise((resolve, reject) => {
168
- const req = indexedDB.open(dbName, version);
169
- req.onupgradeneeded = () => {
170
- const db2 = req.result;
171
- let store;
172
- if (db2.objectStoreNames.contains(storeName)) {
173
- const tx = req.transaction;
174
- if (tx === null) {
175
- throw new Error("[openDB] Missing transaction during upgrade");
176
- }
177
- store = tx.objectStore(storeName);
178
- } else {
179
- store = db2.createObjectStore(storeName, { keyPath: "key" });
180
- }
181
- if (!store.indexNames.contains("expiresAt")) {
182
- store.createIndex("expiresAt", "expiresAt");
183
- }
184
- };
185
- req.onblocked = () => reject(new Error(`[openDB] Upgrade blocked for "${dbName}"`));
186
- req.onsuccess = () => {
187
- const db2 = req.result;
188
- attachDbGuards(db2);
189
- resolve(db2);
190
- };
191
- req.onerror = () => reject(req.error);
192
- });
193
- const promise = openAtVersion(currentVersion);
194
- dbCache.set(cacheKey, promise);
195
- const db = await promise;
196
- if (db.objectStoreNames.contains(storeName)) {
197
- dbVersions.set(dbName, currentVersion);
198
- return db;
199
- }
200
- try {
201
- db.close();
202
- } catch {
203
- }
204
- const nextVersion = currentVersion + 1;
205
- dbVersions.set(dbName, nextVersion);
206
- const upgraded = await openAtVersion(nextVersion);
207
- dbCache.set(`${dbName}@v${nextVersion}`, Promise.resolve(upgraded));
208
- return upgraded;
209
- }
210
- function requestToPromise(req) {
211
- return new Promise((resolve, reject) => {
212
- req.onsuccess = () => resolve(req.result);
213
- req.onerror = () => reject(req.error);
214
- });
215
- }
216
- function txDone(tx) {
217
- return new Promise((resolve, reject) => {
218
- tx.oncomplete = () => resolve();
219
- tx.onerror = () => reject(tx.error ?? new Error("Transaction error"));
220
- tx.onabort = () => reject(tx.error ?? new Error("Transaction aborted"));
221
- });
222
- }
@@ -1,8 +0,0 @@
1
- import type { HttpRequestMiddleware, HttpResponseMiddleware } from './shared.js';
2
- export declare function addHttpRequestMiddleware(middleware: HttpRequestMiddleware): void;
3
- export declare function addHttpResponseMiddleware(middleware: HttpResponseMiddleware): void;
4
- export declare function getHttpRequestMiddlewares(): HttpRequestMiddleware[];
5
- export declare function getHttpResponseMiddlewares(): HttpResponseMiddleware[];
6
- export declare function removeHttpRequestMiddleware(middleware: HttpRequestMiddleware): void;
7
- export declare function removeHttpResponseMiddleware(middleware: HttpResponseMiddleware): void;
8
- //# sourceMappingURL=middleware.d.ts.map
@@ -1,20 +0,0 @@
1
- const requestMiddlewares = /* @__PURE__ */ new Set();
2
- const responseMiddlewares = /* @__PURE__ */ new Set();
3
- export function addHttpRequestMiddleware(middleware) {
4
- requestMiddlewares.add(middleware);
5
- }
6
- export function addHttpResponseMiddleware(middleware) {
7
- responseMiddlewares.add(middleware);
8
- }
9
- export function getHttpRequestMiddlewares() {
10
- return [...requestMiddlewares];
11
- }
12
- export function getHttpResponseMiddlewares() {
13
- return [...responseMiddlewares];
14
- }
15
- export function removeHttpRequestMiddleware(middleware) {
16
- requestMiddlewares.delete(middleware);
17
- }
18
- export function removeHttpResponseMiddleware(middleware) {
19
- responseMiddlewares.delete(middleware);
20
- }
@@ -1,83 +0,0 @@
1
- export interface CreateHttpClientOptions {
2
- baseURL?: HttpBaseURL;
3
- createHeaders?: () => HeadersInit | Promise<HeadersInit>;
4
- requestMiddleware?: HttpRequestMiddleware[];
5
- requestTimeoutMs?: number;
6
- responseMiddleware?: HttpResponseMiddleware[];
7
- retry?: HttpRetryConfig;
8
- }
9
- export interface GetConfig<TParams extends HttpParam = HttpParam, _TError extends HttpErrorPayload = HttpErrorPayload> extends HttpConfig<TParams> {
10
- retry?: HttpRetryConfig;
11
- }
12
- export type HttpBaseURL = HttpBaseURLResolver | string;
13
- export type HttpBaseURLResolver = () => Promise<string> | string;
14
- export interface HttpClient {
15
- get: <TData = unknown, TParams extends HttpParam = HttpParam, TError extends HttpErrorPayload = HttpErrorPayload>(url: string, config?: GetConfig<TParams, TError>) => Promise<HttpResponse<HttpPayload<TData, TError>>>;
16
- post: <TData = unknown, TParams extends HttpParam = HttpParam, TError extends HttpErrorPayload = HttpErrorPayload>(url: string, data?: FormData | Record<string, unknown>, config?: PostConfig<TParams, TError>) => Promise<HttpResponse<HttpPayload<TData, TError>>>;
17
- }
18
- export interface HttpConfig<TParams extends HttpParam = HttpParam> {
19
- params?: TParams;
20
- signal?: AbortSignal | AbortSignal[];
21
- }
22
- export interface HttpErrorPayload {
23
- [key: string]: unknown;
24
- kind?: string;
25
- message?: string;
26
- status: 'error';
27
- }
28
- export type HttpParam = Record<string, HttpParamValue>;
29
- export type HttpParamValue = HttpPrimitive | null | ReadonlyArray<HttpPrimitive> | undefined;
30
- export type HttpPayload<TData, TError extends HttpErrorPayload = HttpErrorPayload> = TData | TError;
31
- export type HttpPrimitive = boolean | number | string;
32
- export interface HttpRequestContext<TParams extends HttpParam = HttpParam, TBody = FormData | Record<string, unknown> | undefined> {
33
- baseURL: string;
34
- body?: TBody;
35
- credentials: RequestCredentials;
36
- headers: Headers;
37
- method: 'GET' | 'POST';
38
- params?: TParams;
39
- signal: AbortSignal;
40
- url: string;
41
- }
42
- export type HttpRequestMiddleware = (request: HttpRequestContext) => Promise<void> | void;
43
- export interface HttpResponse<TData = unknown> {
44
- config: {
45
- url: string;
46
- };
47
- data: TData;
48
- status: number;
49
- }
50
- export type HttpResponseMiddleware = (response: HttpResponse, request: HttpRequestContext) => Promise<void> | void;
51
- export interface HttpRetryConfig {
52
- /**
53
- * Delay between retry attempts in milliseconds.
54
- *
55
- * @default 300
56
- */
57
- delay?: number;
58
- /**
59
- * Number of retry attempts for GET requests.
60
- *
61
- * @default 3
62
- */
63
- retries?: number;
64
- }
65
- export interface HttpRuntimeConfig {
66
- baseURL: string;
67
- cache: boolean;
68
- cacheDbName: 'smart-cache-v2';
69
- cacheStoreName: string;
70
- cacheTtlMs: number;
71
- clientEnvHeader: boolean;
72
- defaultHeaders: Record<string, string>;
73
- disableCacheInDev: boolean;
74
- requestTimeoutMs: number;
75
- retry: Required<HttpRetryConfig>;
76
- }
77
- export interface PostConfig<TParams extends HttpParam = HttpParam, _TError extends HttpErrorPayload = HttpErrorPayload> extends HttpConfig<TParams> {
78
- }
79
- export declare function createHttpUrl(url: string, params?: HttpParam): string;
80
- export declare function createNetworkError(error: unknown): HttpErrorPayload;
81
- export declare function isHttpErrorPayload(value: unknown): value is HttpErrorPayload;
82
- export declare function joinUrl(baseURL: string, url: string): string;
83
- //# sourceMappingURL=shared.d.ts.map
@@ -1,50 +0,0 @@
1
- export function createHttpUrl(url, params = {}) {
2
- const query = serializeParams(params);
3
- if (!query) {
4
- return url;
5
- }
6
- return `${url}?${query}`;
7
- }
8
- export function createNetworkError(error) {
9
- return {
10
- kind: "network_error",
11
- message: error instanceof Error ? error.message : "Network request failed",
12
- status: "error"
13
- };
14
- }
15
- export function isHttpErrorPayload(value) {
16
- return Boolean(value && typeof value === "object" && "status" in value && value.status === "error");
17
- }
18
- export function joinUrl(baseURL, url) {
19
- if (isAbsoluteUrl(url)) {
20
- return url;
21
- }
22
- if (!baseURL) {
23
- return url;
24
- }
25
- const left = baseURL.endsWith("/") ? baseURL.slice(0, -1) : baseURL;
26
- const right = url.startsWith("/") ? url.slice(1) : url;
27
- return `${left}/${right}`;
28
- }
29
- function isAbsoluteUrl(url) {
30
- return /^https?:\/\//.test(url) || url.startsWith("//");
31
- }
32
- function serializeParams(params = {}) {
33
- const query = new URLSearchParams();
34
- Object.entries(params).forEach(([key, value]) => {
35
- const serializedValue = serializeParamValue(value);
36
- if (serializedValue !== null) {
37
- query.append(key, serializedValue);
38
- }
39
- });
40
- return query.toString();
41
- }
42
- function serializeParamValue(value) {
43
- if (value === null || value === void 0) {
44
- return null;
45
- }
46
- if (Array.isArray(value)) {
47
- return JSON.stringify(value);
48
- }
49
- return String(value);
50
- }
@@ -1,46 +0,0 @@
1
- import type { GetConfig, HttpClient, HttpErrorPayload, HttpParam, HttpPayload, HttpResponse, PostConfig } from './shared.js';
2
- declare global {
3
- interface BrickflowHttpRouteMap {
4
- }
5
- }
6
- export type HttpRouteBody<TRoute extends HttpRouteDefinition> = TRoute extends {
7
- body: infer TBody;
8
- } ? TBody extends FormData | Record<string, unknown> ? TBody : FormData | Record<string, unknown> : FormData | Record<string, unknown>;
9
- export type HttpRouteData<TRoute extends HttpRouteDefinition> = TRoute extends {
10
- data: infer TData;
11
- } ? TData : unknown;
12
- export interface HttpRouteDefinition {
13
- body?: FormData | Record<string, unknown>;
14
- data?: unknown;
15
- error?: HttpErrorPayload;
16
- params?: HttpParam;
17
- }
18
- export type HttpRouteError<TRoute extends HttpRouteDefinition> = TRoute extends {
19
- error: infer TError;
20
- } ? TError extends HttpErrorPayload ? TError : HttpErrorPayload : HttpErrorPayload;
21
- export interface HttpRouteMap extends BrickflowHttpRouteMap {
22
- }
23
- export type HttpRouteParams<TRoute extends HttpRouteDefinition> = TRoute extends {
24
- params: infer TParams;
25
- } ? TParams extends HttpParam ? TParams : HttpParam : HttpParam;
26
- export type ResolveHttpRoute<TRoutes, TUrl extends string> = TUrl extends KnownHttpRoute<TRoutes> ? HttpRouteLike<TRoutes[TUrl]> : HttpRouteDefinition;
27
- export interface StrictTypedHttpClient<TRoutes = HttpRouteMap> {
28
- get<TUrl extends KnownHttpRoute<TRoutes>>(url: TUrl, config?: TypedGetConfig<TRoutes, TUrl>): Promise<TypedHttpResponse<TRoutes, TUrl>>;
29
- post<TUrl extends KnownHttpRoute<TRoutes>>(url: TUrl, data?: HttpRouteBody<ResolveHttpRoute<TRoutes, TUrl>>, config?: TypedPostConfig<TRoutes, TUrl>): Promise<TypedHttpResponse<TRoutes, TUrl>>;
30
- }
31
- export type TypedGetConfig<TRoutes, TUrl extends string> = GetConfig<HttpRouteParams<ResolveHttpRoute<TRoutes, TUrl>>, HttpRouteError<ResolveHttpRoute<TRoutes, TUrl>>>;
32
- export interface TypedHttpClient<TRoutes = HttpRouteMap> extends Omit<HttpClient, 'get' | 'post'> {
33
- get<TUrl extends KnownHttpRoute<TRoutes>>(url: TUrl, config?: TypedGetConfig<TRoutes, TUrl>): Promise<TypedHttpResponse<TRoutes, TUrl>>;
34
- get<TData = unknown, TParams extends HttpParam = HttpParam, TError extends HttpErrorPayload = HttpErrorPayload>(url: string, config?: GetConfig<TParams, TError>): Promise<HttpResponse<HttpPayload<TData, TError>>>;
35
- post<TUrl extends KnownHttpRoute<TRoutes>>(url: TUrl, data?: HttpRouteBody<ResolveHttpRoute<TRoutes, TUrl>>, config?: TypedPostConfig<TRoutes, TUrl>): Promise<TypedHttpResponse<TRoutes, TUrl>>;
36
- post<TData = unknown, TParams extends HttpParam = HttpParam, TError extends HttpErrorPayload = HttpErrorPayload>(url: string, data?: FormData | Record<string, unknown>, config?: PostConfig<TParams, TError>): Promise<HttpResponse<HttpPayload<TData, TError>>>;
37
- }
38
- export type TypedHttpResponse<TRoutes, TUrl extends string> = HttpResponse<HttpPayload<HttpRouteData<ResolveHttpRoute<TRoutes, TUrl>>, HttpRouteError<ResolveHttpRoute<TRoutes, TUrl>>>>;
39
- export type TypedPostConfig<TRoutes, TUrl extends string> = PostConfig<HttpRouteParams<ResolveHttpRoute<TRoutes, TUrl>>, HttpRouteError<ResolveHttpRoute<TRoutes, TUrl>>>;
40
- type HttpRouteLike<TValue> = TValue extends HttpRouteDefinition ? TValue : HttpRouteDefinition;
41
- type KnownHttpRoute<TRoutes> = Extract<keyof TRoutes, string>;
42
- export declare function createStrictHttpClient<TRoutes = HttpRouteMap>(client: HttpClient): StrictTypedHttpClient<TRoutes>;
43
- export declare function createTypedHttpClient<TRoutes = HttpRouteMap>(client: HttpClient): TypedHttpClient<TRoutes>;
44
- export declare function defineHttpRoutes<const TRoutes extends Record<string, HttpRouteDefinition>>(routes: TRoutes): TRoutes;
45
- export {};
46
- //# sourceMappingURL=typed.d.ts.map
@@ -1,9 +0,0 @@
1
- export function createStrictHttpClient(client) {
2
- return client;
3
- }
4
- export function createTypedHttpClient(client) {
5
- return client;
6
- }
7
- export function defineHttpRoutes(routes) {
8
- return routes;
9
- }
package/dist/types.d.mts DELETED
@@ -1,11 +0,0 @@
1
- export { type CreateHttpClientOptions, type GetConfig, type HttpBaseURL, type HttpBaseURLResolver, type HttpClient, type HttpConfig, type HttpErrorPayload, type HttpParam, type HttpPayload, type HttpRequestContext, type HttpRequestMiddleware, type HttpResponse, type HttpResponseMiddleware, type HttpRetryConfig, type HttpRuntimeConfig, type PostConfig } from '../dist/runtime/utils/shared.js'
2
-
3
- export { type createHttpClient } from '../dist/runtime/http/client.js'
4
-
5
- export { type addHttpRequestMiddleware, type addHttpResponseMiddleware, type removeHttpRequestMiddleware, type removeHttpResponseMiddleware } from '../dist/runtime/utils/middleware.js'
6
-
7
- export { type HttpRouteBody, type HttpRouteData, type HttpRouteDefinition, type HttpRouteError, type HttpRouteMap, type HttpRouteParams, type ResolveHttpRoute, type StrictTypedHttpClient, type TypedGetConfig, type TypedHttpClient, type TypedHttpResponse, type TypedPostConfig, type createStrictHttpClient, type createTypedHttpClient, type defineHttpRoutes } from '../dist/runtime/utils/typed.js'
8
-
9
- export { default } from './module.mjs'
10
-
11
- export { type ModuleOptions } from './module.mjs'