@thetechfossil/upfiles 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,443 +1,449 @@
1
- # @thetechfossil/upfiles
2
-
3
- Lightweight JavaScript client and React component to upload files via a presigned S3 flow. Similar to UploadThing-like DX.
4
-
5
- - Client: get presigned URLs and PUT to S3
6
- - React `<Uploader />`: drag/drop, progress, single/multiple, accepts/types, size limits
7
- - React `<ProjectFilesWidget />`: list all files for a project (Plugin API), pick one, and optionally auto-save to your app
8
-
9
- ## Installation
10
-
11
- ```bash
12
- # Bun (recommended)
13
- bun add @thetechfossil/upfiles
14
-
15
- # npm
16
- npm install @thetechfossil/upfiles
17
-
18
- # pnpm
19
- pnpm add @thetechfossil/upfiles
20
-
21
- # yarn
22
- yarn add @thetechfossil/upfiles
23
- ```
24
-
25
- ## Quickstart
26
-
27
- ```tsx
28
- import { Uploader, ConnectProjectDialog } from '@thetechfossil/upfiles';
29
- import { useState } from 'react';
30
-
31
- export default function Page() {
32
- const [open, setOpen] = useState(false);
33
- const [apiKey, setApiKey] = useState<string | null>(null);
34
-
35
- return (
36
- <div className="space-y-6">
37
- <button className="px-3 py-2 rounded bg-blue-600 text-white" onClick={() => setOpen(true)}>
38
- Connect to Upfiles
39
- </button>
40
-
41
- <Uploader
42
- clientOptions={{
43
- baseUrl: process.env.NEXT_PUBLIC_UPFILES_APP_URL!,
44
- apiKey: apiKey ?? undefined, // set after connecting
45
- apiKeyHeader: 'authorization',
46
- }}
47
- multiple
48
- dropzoneClassName="border border-dashed rounded-md p-6 cursor-pointer"
49
- buttonClassName="px-3 py-2 rounded bg-blue-600 text-white"
50
- />
51
-
52
- <ConnectProjectDialog
53
- baseUrl={process.env.NEXT_PUBLIC_UPFILES_APP_URL!}
54
- open={open}
55
- onOpenChange={setOpen}
56
- onConnected={(key) => setApiKey(key)}
57
- />
58
- </div>
59
- );
60
- }
61
- ```
62
-
63
- ## Server prerequisites
64
-
65
- Your Upfiles app must expose the Plugin API presign endpoint:
66
-
67
- - Method: `POST`
68
- - Path: `/api/plugin/upload/presigned-url` (default; configurable)
69
- - Body: `{ fileName, fileType, fileSize, folderPath?, projectId? }` (`fileSize` is required)
70
- - Response: `{ presignedUrl, fileKey, publicUrl, apiKeyId?, projectId? }`
71
-
72
- This repository already provides a Next.js route at `src/app/api/plugin/upload/presigned-url/route.ts`.
73
-
74
- For plugins/packages calling across origins, authenticate using an API key header as documented below. CORS must allow your plugin origin.
75
-
76
- ## Basic usage (React)
77
-
78
- ```tsx
79
- import { Uploader } from '@thetechfossil/upfiles';
80
-
81
- export default function Page() {
82
- return (
83
- <Uploader
84
- multiple
85
- accept={["image/*", "application/pdf"]}
86
- maxFileSize={100 * 1024 * 1024}
87
- onComplete={(files) => {
88
- console.log('uploaded:', files);
89
- }}
90
- onError={(err) => {
91
- console.error(err);
92
- }}
93
- dropzoneClassName="border border-dashed rounded-md p-6 cursor-pointer"
94
- buttonClassName="px-3 py-2 rounded bg-blue-600 text-white"
95
- // Optional: pass clientOptions for cross-origin + API key auth
96
- // clientOptions={{
97
- // baseUrl: 'https://YOUR_APP_HOST',
98
- // // or presignUrl: 'https://YOUR_APP_HOST/api/plugin/upload/presigned-url',
99
- // apiKey: process.env.NEXT_PUBLIC_UPFILES_API_KEY!,
100
- // apiKeyHeader: 'authorization', // or 'x-api-key' | 'x-up-api-key'
101
- // }}
102
- />
103
- );
104
- }
105
- ```
106
-
107
- ## Basic usage (vanilla JS)
108
-
109
- ```ts
110
- import { UpfilesClient } from '@thetechfossil/upfiles';
111
-
112
- // Same-origin by default; only set these when needed:
113
- const client = new UpfilesClient({
114
- // presignUrl: 'https://YOUR_APP_HOST/api/plugin/upload/presigned-url', // full override
115
- // baseUrl: 'https://YOUR_APP_HOST', // used with presignPath
116
- // presignPath: '/api/plugin/upload/presigned-url', // default
117
- // withCredentials: true, // for session routes (not typical for Plugin API)
118
- // Provide API key for Plugin API auth:
119
- // apiKey: 'upk_...'
120
- // apiKeyHeader: 'authorization' // or 'x-api-key' | 'x-up-api-key'
121
- });
122
-
123
- async function upload(file) {
124
- const { presignedUrl, publicUrl } = await client.getPresignedUrl({
125
- fileName: file.name,
126
- fileType: file.type,
127
- fileSize: file.size, // required
128
- folderPath: 'my-plugin/uploads/',
129
- });
130
- const res = await client.uploadToS3(presignedUrl, file);
131
- if (!res.ok) throw new Error('Upload failed');
132
- return publicUrl;
133
- }
134
- ```
135
-
136
- ## API
137
-
138
- - `new UpfilesClient(options)`
139
- - `presignUrl` (optional): full absolute URL to presign endpoint. Highest priority.
140
- - `baseUrl` (optional): API base origin. Used with `presignPath`.
141
- - `presignPath` (optional): relative path, default `/api/plugin/upload/presigned-url`.
142
- - `headers` (optional): extra headers to send.
143
- - `apiKey` (optional): API key value (e.g., `upk_...`).
144
- - `apiKeyHeader` (optional): one of `'authorization' | 'x-api-key' | 'x-up-api-key'` (default `'authorization'`). If `'authorization'`, `Bearer` prefix is auto-added for `upk_...`.
145
- - `withCredentials` (optional): `true` to send cookies.
146
- - Defaults: same-origin requests to `/api/plugin/upload/presigned-url`.
147
- - `client.getPresignedUrl({ fileName, fileType, fileSize, projectId?, folderPath? })`
148
- - `client.uploadToS3(presignedUrl, file)`
149
- - `client.upload(file, { projectId?, folderPath?, fetchThumbnails? })` returns `{ publicUrl, fileKey, fileName, fileType, fileSize, projectId?, apiKeyId?, thumbnails? }`
150
- - `client.getThumbnails(fileKey)` returns `Thumbnail[]`
151
- - `client.getProjectFiles({ folderPath? })` returns `FileListItem[]`
152
-
153
- - `<Uploader />` props
154
- - `clientOptions` (optional): same as `UpfilesClient` options (only needed for cross-origin or auth customization)
155
- - `multiple` (default true)
156
- - `accept` (array of MIME patterns)
157
- - `maxFileSize` (bytes, default 100MB)
158
- - `maxFiles` (default 10)
159
- - `fetchThumbnails` (boolean): if true, fetch thumbnails after upload via Plugin API
160
- - `onComplete(files)` and `onError(error)`
161
- - `className`, `buttonClassName`, `dropzoneClassName`
162
- - `children`: custom dropzone inner content
163
-
164
- ### Thumbnails usage
165
-
166
- Your Upfiles app exposes `GET /api/plugin/thumbnails?fileKey=...` for plugins. Enable `fetchThumbnails` to auto-fetch after upload, or call `client.getThumbnails(fileKey)` yourself.
167
-
168
- Example with `client.upload`:
169
-
170
- ```ts
171
- const result = await client.upload(file, { folderPath: 'my-plugin/', fetchThumbnails: true });
172
- console.log(result.thumbnails);
173
- ```
174
-
175
- ### List project files (Plugin API)
176
-
177
- Your Upfiles app exposes `GET /api/plugin/files?folderPath=...` for plugins (API key auth + CORS). The client can call it via `getProjectFiles`:
178
-
179
- ```ts
180
- import { UpfilesClient } from '@thetechfossil/upfiles';
181
-
182
- const client = new UpfilesClient({
183
- baseUrl: 'https://YOUR_APP_HOST',
184
- apiKey: 'upk_...',
185
- thumbnailsPath: '/api/plugin/thumbnails', // used to derive /api/plugin/files
186
- });
187
-
188
- const files = await client.getProjectFiles({ folderPath: 'optional/subfolder' });
189
- // [{ key, originalName, size, contentType, uploadedAt, url }, ...]
190
- ```
191
-
192
- ### `<ProjectFilesWidget />`
193
-
194
- Simple UI to fetch and select a file for the project tied to the API key. Emits the selection, and can optionally POST it to your backend.
195
-
196
- ```tsx
197
- import { ProjectFilesWidget } from '@thetechfossil/upfiles';
198
-
199
- export default function PickFile() {
200
- return (
201
- <ProjectFilesWidget
202
- clientOptions={{
203
- baseUrl: 'https://YOUR_APP_HOST',
204
- apiKey: process.env.NEXT_PUBLIC_UPFILES_API_KEY!,
205
- apiKeyHeader: 'authorization',
206
- thumbnailsPath: '/api/plugin/thumbnails',
207
- }}
208
- // Optional: filter within a folder
209
- // folderPath="my-plugin/"
210
-
211
- onSelect={(f) => {
212
- // { name, key, url, size, contentType }
213
- console.log('Selected:', f.name, f.key);
214
- }}
215
-
216
- // Optional: built-in save
217
- // saveUrl="/api/files/save" // Your app route to persist selection
218
- // onSave={async (f) => { await fetch('/api/files/save', { method: 'POST', body: JSON.stringify(f) }); }}
219
- // onSaved={(result) => console.log('Saved!', result)}
220
- />
221
- );
222
- }
223
- ```
224
-
225
- ## Notes
226
-
227
- - Dev with Vite: configure a proxy so `/api/*` maps to your backend (e.g., `http://localhost:4000`), then `<Uploader />` works with no config.
228
- - Ensure CORS where applicable (S3 bucket CORS; and set `PLUGIN_ALLOWED_ORIGINS` on your Upfiles app for cross-origin Plugin API calls).
229
- - For cross-origin with cookies (NextAuth), set `withCredentials: true` and configure your server to allow credentials.
230
- Plugin API typically uses API keys instead of cookies.
231
-
232
- ### Plugin endpoints provided by this repo
233
-
234
- - `POST /api/plugin/upload/presigned-url` generate presigned S3 URL for upload
235
- - `GET /api/plugin/thumbnails?fileKey=...` list thumbnails for a file
236
- - `GET /api/plugin/files?folderPath=...` list project files (API key scoped), optional folder prefix
237
-
238
- ## Connect a project to get an API key
239
-
240
- This package ships a ready-made dialog built with Radix UI + Tailwind classes to help developers connect their project to your main Upfiles app and obtain an API key.
241
-
242
- ### Install
243
-
244
- Your app must have Tailwind configured. The dialog uses Radix primitives (shadcn/ui compatible). Ensure the peer dependency is available in the host app:
245
-
246
- ```bash
247
- bun add @thetechfossil/upfiles @radix-ui/react-dialog
248
- # or
249
- npm install @thetechfossil/upfiles @radix-ui/react-dialog
250
- ```
251
-
252
- ### `ConnectProjectDialog` (UI modal)
253
-
254
- Props:
255
-
256
- - `baseUrl`: your Upfiles app origin (e.g., `https://upfiles.example.com`).
257
- - `open`, `onOpenChange`: control the dialog.
258
- - `onConnected(apiKey, { projectId?, source })`: receives the plaintext API key and metadata.
259
-
260
- It presents three options:
261
-
262
- - Connect to existing project → lists projects via `GET /api/projects`, then creates a key via `POST /api/projects/:id/keys`.
263
- - Add API key manually → text input to paste an existing key.
264
- - Create new project `POST /api/projects`, then `POST /api/projects/:id/keys`.
265
-
266
- ```tsx
267
- import { useState } from 'react';
268
- import { ConnectProjectDialog } from '@thetechfossil/upfiles';
269
-
270
- export default function ConnectKeyButton() {
271
- const [open, setOpen] = useState(false);
272
- const [apiKey, setApiKey] = useState<string | null>(null);
273
-
274
- return (
275
- <div>
276
- <button className="px-3 py-2 rounded bg-blue-600 text-white" onClick={() => setOpen(true)}>
277
- Connect Upfiles
278
- </button>
279
-
280
- <ConnectProjectDialog
281
- baseUrl={process.env.NEXT_PUBLIC_UPFILES_APP_URL!}
282
- open={open}
283
- onOpenChange={setOpen}
284
- onConnected={(key, meta) => {
285
- setApiKey(key);
286
- // Persist the key in your own DB as needed (see below)
287
- console.log('Connected via', meta.source, 'projectId', meta.projectId);
288
- }}
289
- />
290
- </div>
291
- );
292
- }
293
- ```
294
-
295
- ### Store the key in your own DB
296
-
297
- You control persistence. Example Next.js route handler to store an encrypted key for the current user:
298
-
299
- ```ts
300
- // app/api/integrations/upfiles/key/route.ts
301
- import { NextRequest, NextResponse } from 'next/server';
302
- import { prisma } from '@/lib/prisma';
303
- import { getServerSession } from 'next-auth';
304
- import { authOptions } from '@/lib/auth';
305
-
306
- export async function POST(req: NextRequest) {
307
- const session = await getServerSession(authOptions as any);
308
- const userId = (session as any)?.user?.id as string | undefined;
309
- if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
310
-
311
- const { apiKey } = await req.json();
312
- if (!apiKey) return NextResponse.json({ error: 'apiKey required' }, { status: 400 });
313
-
314
- // TODO: encrypt before saving
315
- await prisma.user.update({ where: { id: userId }, data: { upfilesApiKey: apiKey } });
316
- return NextResponse.json({ ok: true });
317
- }
318
- ```
319
-
320
- From `onConnected`, call this route to persist:
321
-
322
- ```ts
323
- await fetch('/api/integrations/upfiles/key', {
324
- method: 'POST',
325
- headers: { 'content-type': 'application/json' },
326
- body: JSON.stringify({ apiKey })
327
- });
328
- ```
329
-
330
- ### Utility functions (no UI)
331
-
332
- If you prefer to build a custom UI, use the exported functions:
333
-
334
- ```ts
335
- import {
336
- listProjects,
337
- createProject,
338
- connectProject,
339
- addApiKeyManually,
340
- createClientWithKey,
341
- } from '@thetechfossil/upfiles';
342
-
343
- const baseUrl = 'https://upfiles.example.com';
344
-
345
- // 1) List existing projects (requires session cookie on baseUrl)
346
- const projects = await listProjects({ baseUrl });
347
-
348
- // 2) Create a new project and key
349
- const { apiKey, projectId } = await createProject({ baseUrl, name: 'My App' });
350
-
351
- // 3) Create a key for an existing project
352
- const key2 = await connectProject({ baseUrl, projectId: 'proj_123' });
353
-
354
- // 4) Manual
355
- const manual = addApiKeyManually('upk_...');
356
-
357
- // 5) Build an upload client with the key
358
- const client = createClientWithKey(baseUrl, apiKey);
359
- ```
360
-
361
- ### `<ImageManager />` props
362
-
363
- ```ts
364
- type ImageManagerProps = {
365
- open: boolean;
366
- onOpenChange: (open: boolean) => void;
367
- clientOptions: UpfilesClientOptions;
368
- projectId?: string;
369
- folderPath?: string;
370
- title?: string;
371
- description?: string;
372
- className?: string;
373
- gridClassName?: string;
374
- onSelect: (image: {
375
- url: string;
376
- key: string;
377
- originalName: string;
378
- size: number;
379
- contentType: string;
380
- thumbnails?: { id: string; key: string; url: string; size: number; sizeType?: string }[];
381
- }) => void;
382
- onDelete?: (key: string) => Promise<void>;
383
- deleteUrl?: string;
384
- autoRecordToDb?: boolean;
385
- fetchThumbnails?: boolean;
386
- maxFileSize?: number;
387
- maxFiles?: number;
388
- mode?: 'full' | 'browse' | 'upload'; // default: 'full'
389
- showDelete?: boolean; // default: true
390
- };
391
- ```
392
-
393
- ### Image picker modal (Browse Mode)
394
-
395
- You can use `ImageManager` in `browse` mode to let users select existing images without the upload tab:
396
-
397
- ```tsx
398
- import { useState } from 'react';
399
- import { ImageManager } from '@thetechfossil/upfiles';
400
-
401
- export default function PickImage() {
402
- const [open, setOpen] = useState(false);
403
- return (
404
- <div>
405
- <button className="px-3 py-2 rounded bg-blue-600 text-white" onClick={() => setOpen(true)}>
406
- Pick image
407
- </button>
408
- <ImageManager
409
- open={open}
410
- onOpenChange={setOpen}
411
- mode="browse"
412
- clientOptions={{
413
- baseUrl: process.env.NEXT_PUBLIC_UPFILES_APP_URL!,
414
- apiKey: process.env.NEXT_PUBLIC_UPFILES_API_KEY!,
415
- apiKeyHeader: 'authorization',
416
- }}
417
- // folderPath="my-plugin/images/" // optional
418
- onSelect={async (img) => {
419
- // Persist original image URL in your DB
420
- await fetch('/api/media/save', {
421
- method: 'POST',
422
- headers: { 'content-type': 'application/json' },
423
- body: JSON.stringify({ url: img.url, key: img.key }),
424
- });
425
- }}
426
- />
427
- </div>
428
- );
429
- }
430
- ```
431
-
432
- ## Reusing across multiple Next.js projects
433
-
434
- - Install `@thetechfossil/upfiles` and `@radix-ui/react-dialog` in each project.
435
- - Set an environment variable like `NEXT_PUBLIC_UPFILES_APP_URL` to point all consumers to your main Upfiles app.
436
- - Each consumer stores its own copy of the API key in its DB, obtained via `ConnectProjectDialog`.
437
-
438
- ## Troubleshooting
439
-
440
- - __401 Unauthorized when listing/creating projects__: The `projects` and `keys` endpoints require a signed-in session on the main app domain. Open the dialog from a page that can send cookies to `{baseUrl}` or run from the same origin; otherwise configure auth/CORS accordingly.
441
- - __CORS errors calling main app__: Ensure the main app allows your consumer origin in CORS and, if you use cookies, sets the correct `Access-Control-Allow-Credentials` headers and SameSite attributes.
442
- - __Uploads fail__: Verify S3 bucket CORS and that `POST /api/plugin/upload/presigned-url` is accessible from the consumer app.
443
- - __API key header__: Default is `Authorization: Bearer upk_...`. If your server expects a different header, set `apiKeyHeader: 'x-api-key' | 'x-up-api-key'` in `UpfilesClient` options.
1
+ # @thetechfossil/upfiles
2
+
3
+ Lightweight JavaScript client and React component to upload files via a presigned S3 flow. Similar to UploadThing-like DX.
4
+
5
+ ## Documentation
6
+
7
+ 📚 **Full documentation available at:** [https://ttf-upfiles-docs.netlify.app/](https://ttf-upfiles-docs.netlify.app/)
8
+
9
+ For detailed API reference, guides, examples, and more information, visit the documentation site.
10
+
11
+ - Client: get presigned URLs and PUT to S3
12
+ - React `<Uploader />`: drag/drop, progress, single/multiple, accepts/types, size limits
13
+ - React `<ProjectFilesWidget />`: list all files for a project (Plugin API), pick one, and optionally auto-save to your app
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ # Bun (recommended)
19
+ bun add @thetechfossil/upfiles
20
+
21
+ # npm
22
+ npm install @thetechfossil/upfiles
23
+
24
+ # pnpm
25
+ pnpm add @thetechfossil/upfiles
26
+
27
+ # yarn
28
+ yarn add @thetechfossil/upfiles
29
+ ```
30
+
31
+ ## Quickstart
32
+
33
+ ```tsx
34
+ import { Uploader, ConnectProjectDialog } from '@thetechfossil/upfiles';
35
+ import { useState } from 'react';
36
+
37
+ export default function Page() {
38
+ const [open, setOpen] = useState(false);
39
+ const [apiKey, setApiKey] = useState<string | null>(null);
40
+
41
+ return (
42
+ <div className="space-y-6">
43
+ <button className="px-3 py-2 rounded bg-blue-600 text-white" onClick={() => setOpen(true)}>
44
+ Connect to Upfiles
45
+ </button>
46
+
47
+ <Uploader
48
+ clientOptions={{
49
+ baseUrl: process.env.NEXT_PUBLIC_UPFILES_APP_URL!,
50
+ apiKey: apiKey ?? undefined, // set after connecting
51
+ apiKeyHeader: 'authorization',
52
+ }}
53
+ multiple
54
+ dropzoneClassName="border border-dashed rounded-md p-6 cursor-pointer"
55
+ buttonClassName="px-3 py-2 rounded bg-blue-600 text-white"
56
+ />
57
+
58
+ <ConnectProjectDialog
59
+ baseUrl={process.env.NEXT_PUBLIC_UPFILES_APP_URL!}
60
+ open={open}
61
+ onOpenChange={setOpen}
62
+ onConnected={(key) => setApiKey(key)}
63
+ />
64
+ </div>
65
+ );
66
+ }
67
+ ```
68
+
69
+ ## Server prerequisites
70
+
71
+ Your Upfiles app must expose the Plugin API presign endpoint:
72
+
73
+ - Method: `POST`
74
+ - Path: `/api/plugin/upload/presigned-url` (default; configurable)
75
+ - Body: `{ fileName, fileType, fileSize, folderPath?, projectId? }` (`fileSize` is required)
76
+ - Response: `{ presignedUrl, fileKey, publicUrl, apiKeyId?, projectId? }`
77
+
78
+ This repository already provides a Next.js route at `src/app/api/plugin/upload/presigned-url/route.ts`.
79
+
80
+ For plugins/packages calling across origins, authenticate using an API key header as documented below. CORS must allow your plugin origin.
81
+
82
+ ## Basic usage (React)
83
+
84
+ ```tsx
85
+ import { Uploader } from '@thetechfossil/upfiles';
86
+
87
+ export default function Page() {
88
+ return (
89
+ <Uploader
90
+ multiple
91
+ accept={["image/*", "application/pdf"]}
92
+ maxFileSize={100 * 1024 * 1024}
93
+ onComplete={(files) => {
94
+ console.log('uploaded:', files);
95
+ }}
96
+ onError={(err) => {
97
+ console.error(err);
98
+ }}
99
+ dropzoneClassName="border border-dashed rounded-md p-6 cursor-pointer"
100
+ buttonClassName="px-3 py-2 rounded bg-blue-600 text-white"
101
+ // Optional: pass clientOptions for cross-origin + API key auth
102
+ // clientOptions={{
103
+ // baseUrl: 'https://YOUR_APP_HOST',
104
+ // // or presignUrl: 'https://YOUR_APP_HOST/api/plugin/upload/presigned-url',
105
+ // apiKey: process.env.NEXT_PUBLIC_UPFILES_API_KEY!,
106
+ // apiKeyHeader: 'authorization', // or 'x-api-key' | 'x-up-api-key'
107
+ // }}
108
+ />
109
+ );
110
+ }
111
+ ```
112
+
113
+ ## Basic usage (vanilla JS)
114
+
115
+ ```ts
116
+ import { UpfilesClient } from '@thetechfossil/upfiles';
117
+
118
+ // Same-origin by default; only set these when needed:
119
+ const client = new UpfilesClient({
120
+ // presignUrl: 'https://YOUR_APP_HOST/api/plugin/upload/presigned-url', // full override
121
+ // baseUrl: 'https://YOUR_APP_HOST', // used with presignPath
122
+ // presignPath: '/api/plugin/upload/presigned-url', // default
123
+ // withCredentials: true, // for session routes (not typical for Plugin API)
124
+ // Provide API key for Plugin API auth:
125
+ // apiKey: 'upk_...'
126
+ // apiKeyHeader: 'authorization' // or 'x-api-key' | 'x-up-api-key'
127
+ });
128
+
129
+ async function upload(file) {
130
+ const { presignedUrl, publicUrl } = await client.getPresignedUrl({
131
+ fileName: file.name,
132
+ fileType: file.type,
133
+ fileSize: file.size, // required
134
+ folderPath: 'my-plugin/uploads/',
135
+ });
136
+ const res = await client.uploadToS3(presignedUrl, file);
137
+ if (!res.ok) throw new Error('Upload failed');
138
+ return publicUrl;
139
+ }
140
+ ```
141
+
142
+ ## API
143
+
144
+ - `new UpfilesClient(options)`
145
+ - `presignUrl` (optional): full absolute URL to presign endpoint. Highest priority.
146
+ - `baseUrl` (optional): API base origin. Used with `presignPath`.
147
+ - `presignPath` (optional): relative path, default `/api/plugin/upload/presigned-url`.
148
+ - `headers` (optional): extra headers to send.
149
+ - `apiKey` (optional): API key value (e.g., `upk_...`).
150
+ - `apiKeyHeader` (optional): one of `'authorization' | 'x-api-key' | 'x-up-api-key'` (default `'authorization'`). If `'authorization'`, `Bearer` prefix is auto-added for `upk_...`.
151
+ - `withCredentials` (optional): `true` to send cookies.
152
+ - Defaults: same-origin requests to `/api/plugin/upload/presigned-url`.
153
+ - `client.getPresignedUrl({ fileName, fileType, fileSize, projectId?, folderPath? })`
154
+ - `client.uploadToS3(presignedUrl, file)`
155
+ - `client.upload(file, { projectId?, folderPath?, fetchThumbnails? })` returns `{ publicUrl, fileKey, fileName, fileType, fileSize, projectId?, apiKeyId?, thumbnails? }`
156
+ - `client.getThumbnails(fileKey)` returns `Thumbnail[]`
157
+ - `client.getProjectFiles({ folderPath? })` returns `FileListItem[]`
158
+
159
+ - `<Uploader />` props
160
+ - `clientOptions` (optional): same as `UpfilesClient` options (only needed for cross-origin or auth customization)
161
+ - `multiple` (default true)
162
+ - `accept` (array of MIME patterns)
163
+ - `maxFileSize` (bytes, default 100MB)
164
+ - `maxFiles` (default 10)
165
+ - `fetchThumbnails` (boolean): if true, fetch thumbnails after upload via Plugin API
166
+ - `onComplete(files)` and `onError(error)`
167
+ - `className`, `buttonClassName`, `dropzoneClassName`
168
+ - `children`: custom dropzone inner content
169
+
170
+ ### Thumbnails usage
171
+
172
+ Your Upfiles app exposes `GET /api/plugin/thumbnails?fileKey=...` for plugins. Enable `fetchThumbnails` to auto-fetch after upload, or call `client.getThumbnails(fileKey)` yourself.
173
+
174
+ Example with `client.upload`:
175
+
176
+ ```ts
177
+ const result = await client.upload(file, { folderPath: 'my-plugin/', fetchThumbnails: true });
178
+ console.log(result.thumbnails);
179
+ ```
180
+
181
+ ### List project files (Plugin API)
182
+
183
+ Your Upfiles app exposes `GET /api/plugin/files?folderPath=...` for plugins (API key auth + CORS). The client can call it via `getProjectFiles`:
184
+
185
+ ```ts
186
+ import { UpfilesClient } from '@thetechfossil/upfiles';
187
+
188
+ const client = new UpfilesClient({
189
+ baseUrl: 'https://YOUR_APP_HOST',
190
+ apiKey: 'upk_...',
191
+ thumbnailsPath: '/api/plugin/thumbnails', // used to derive /api/plugin/files
192
+ });
193
+
194
+ const files = await client.getProjectFiles({ folderPath: 'optional/subfolder' });
195
+ // [{ key, originalName, size, contentType, uploadedAt, url }, ...]
196
+ ```
197
+
198
+ ### `<ProjectFilesWidget />`
199
+
200
+ Simple UI to fetch and select a file for the project tied to the API key. Emits the selection, and can optionally POST it to your backend.
201
+
202
+ ```tsx
203
+ import { ProjectFilesWidget } from '@thetechfossil/upfiles';
204
+
205
+ export default function PickFile() {
206
+ return (
207
+ <ProjectFilesWidget
208
+ clientOptions={{
209
+ baseUrl: 'https://YOUR_APP_HOST',
210
+ apiKey: process.env.NEXT_PUBLIC_UPFILES_API_KEY!,
211
+ apiKeyHeader: 'authorization',
212
+ thumbnailsPath: '/api/plugin/thumbnails',
213
+ }}
214
+ // Optional: filter within a folder
215
+ // folderPath="my-plugin/"
216
+
217
+ onSelect={(f) => {
218
+ // { name, key, url, size, contentType }
219
+ console.log('Selected:', f.name, f.key);
220
+ }}
221
+
222
+ // Optional: built-in save
223
+ // saveUrl="/api/files/save" // Your app route to persist selection
224
+ // onSave={async (f) => { await fetch('/api/files/save', { method: 'POST', body: JSON.stringify(f) }); }}
225
+ // onSaved={(result) => console.log('Saved!', result)}
226
+ />
227
+ );
228
+ }
229
+ ```
230
+
231
+ ## Notes
232
+
233
+ - Dev with Vite: configure a proxy so `/api/*` maps to your backend (e.g., `http://localhost:4000`), then `<Uploader />` works with no config.
234
+ - Ensure CORS where applicable (S3 bucket CORS; and set `PLUGIN_ALLOWED_ORIGINS` on your Upfiles app for cross-origin Plugin API calls).
235
+ - For cross-origin with cookies (NextAuth), set `withCredentials: true` and configure your server to allow credentials.
236
+ Plugin API typically uses API keys instead of cookies.
237
+
238
+ ### Plugin endpoints provided by this repo
239
+
240
+ - `POST /api/plugin/upload/presigned-url` generate presigned S3 URL for upload
241
+ - `GET /api/plugin/thumbnails?fileKey=...` – list thumbnails for a file
242
+ - `GET /api/plugin/files?folderPath=...` – list project files (API key scoped), optional folder prefix
243
+
244
+ ## Connect a project to get an API key
245
+
246
+ This package ships a ready-made dialog built with Radix UI + Tailwind classes to help developers connect their project to your main Upfiles app and obtain an API key.
247
+
248
+ ### Install
249
+
250
+ Your app must have Tailwind configured. The dialog uses Radix primitives (shadcn/ui compatible). Ensure the peer dependency is available in the host app:
251
+
252
+ ```bash
253
+ bun add @thetechfossil/upfiles @radix-ui/react-dialog
254
+ # or
255
+ npm install @thetechfossil/upfiles @radix-ui/react-dialog
256
+ ```
257
+
258
+ ### `ConnectProjectDialog` (UI modal)
259
+
260
+ Props:
261
+
262
+ - `baseUrl`: your Upfiles app origin (e.g., `https://upfiles.example.com`).
263
+ - `open`, `onOpenChange`: control the dialog.
264
+ - `onConnected(apiKey, { projectId?, source })`: receives the plaintext API key and metadata.
265
+
266
+ It presents three options:
267
+
268
+ - Connect to existing project → lists projects via `GET /api/projects`, then creates a key via `POST /api/projects/:id/keys`.
269
+ - Add API key manually → text input to paste an existing key.
270
+ - Create new project → `POST /api/projects`, then `POST /api/projects/:id/keys`.
271
+
272
+ ```tsx
273
+ import { useState } from 'react';
274
+ import { ConnectProjectDialog } from '@thetechfossil/upfiles';
275
+
276
+ export default function ConnectKeyButton() {
277
+ const [open, setOpen] = useState(false);
278
+ const [apiKey, setApiKey] = useState<string | null>(null);
279
+
280
+ return (
281
+ <div>
282
+ <button className="px-3 py-2 rounded bg-blue-600 text-white" onClick={() => setOpen(true)}>
283
+ Connect Upfiles
284
+ </button>
285
+
286
+ <ConnectProjectDialog
287
+ baseUrl={process.env.NEXT_PUBLIC_UPFILES_APP_URL!}
288
+ open={open}
289
+ onOpenChange={setOpen}
290
+ onConnected={(key, meta) => {
291
+ setApiKey(key);
292
+ // Persist the key in your own DB as needed (see below)
293
+ console.log('Connected via', meta.source, 'projectId', meta.projectId);
294
+ }}
295
+ />
296
+ </div>
297
+ );
298
+ }
299
+ ```
300
+
301
+ ### Store the key in your own DB
302
+
303
+ You control persistence. Example Next.js route handler to store an encrypted key for the current user:
304
+
305
+ ```ts
306
+ // app/api/integrations/upfiles/key/route.ts
307
+ import { NextRequest, NextResponse } from 'next/server';
308
+ import { prisma } from '@/lib/prisma';
309
+ import { getServerSession } from 'next-auth';
310
+ import { authOptions } from '@/lib/auth';
311
+
312
+ export async function POST(req: NextRequest) {
313
+ const session = await getServerSession(authOptions as any);
314
+ const userId = (session as any)?.user?.id as string | undefined;
315
+ if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
316
+
317
+ const { apiKey } = await req.json();
318
+ if (!apiKey) return NextResponse.json({ error: 'apiKey required' }, { status: 400 });
319
+
320
+ // TODO: encrypt before saving
321
+ await prisma.user.update({ where: { id: userId }, data: { upfilesApiKey: apiKey } });
322
+ return NextResponse.json({ ok: true });
323
+ }
324
+ ```
325
+
326
+ From `onConnected`, call this route to persist:
327
+
328
+ ```ts
329
+ await fetch('/api/integrations/upfiles/key', {
330
+ method: 'POST',
331
+ headers: { 'content-type': 'application/json' },
332
+ body: JSON.stringify({ apiKey })
333
+ });
334
+ ```
335
+
336
+ ### Utility functions (no UI)
337
+
338
+ If you prefer to build a custom UI, use the exported functions:
339
+
340
+ ```ts
341
+ import {
342
+ listProjects,
343
+ createProject,
344
+ connectProject,
345
+ addApiKeyManually,
346
+ createClientWithKey,
347
+ } from '@thetechfossil/upfiles';
348
+
349
+ const baseUrl = 'https://upfiles.example.com';
350
+
351
+ // 1) List existing projects (requires session cookie on baseUrl)
352
+ const projects = await listProjects({ baseUrl });
353
+
354
+ // 2) Create a new project and key
355
+ const { apiKey, projectId } = await createProject({ baseUrl, name: 'My App' });
356
+
357
+ // 3) Create a key for an existing project
358
+ const key2 = await connectProject({ baseUrl, projectId: 'proj_123' });
359
+
360
+ // 4) Manual
361
+ const manual = addApiKeyManually('upk_...');
362
+
363
+ // 5) Build an upload client with the key
364
+ const client = createClientWithKey(baseUrl, apiKey);
365
+ ```
366
+
367
+ ### `<ImageManager />` props
368
+
369
+ ```ts
370
+ type ImageManagerProps = {
371
+ open: boolean;
372
+ onOpenChange: (open: boolean) => void;
373
+ clientOptions: UpfilesClientOptions;
374
+ projectId?: string;
375
+ folderPath?: string;
376
+ title?: string;
377
+ description?: string;
378
+ className?: string;
379
+ gridClassName?: string;
380
+ onSelect: (image: {
381
+ url: string;
382
+ key: string;
383
+ originalName: string;
384
+ size: number;
385
+ contentType: string;
386
+ thumbnails?: { id: string; key: string; url: string; size: number; sizeType?: string }[];
387
+ }) => void;
388
+ onDelete?: (key: string) => Promise<void>;
389
+ deleteUrl?: string;
390
+ autoRecordToDb?: boolean;
391
+ fetchThumbnails?: boolean;
392
+ maxFileSize?: number;
393
+ maxFiles?: number;
394
+ mode?: 'full' | 'browse' | 'upload'; // default: 'full'
395
+ showDelete?: boolean; // default: true
396
+ };
397
+ ```
398
+
399
+ ### Image picker modal (Browse Mode)
400
+
401
+ You can use `ImageManager` in `browse` mode to let users select existing images without the upload tab:
402
+
403
+ ```tsx
404
+ import { useState } from 'react';
405
+ import { ImageManager } from '@thetechfossil/upfiles';
406
+
407
+ export default function PickImage() {
408
+ const [open, setOpen] = useState(false);
409
+ return (
410
+ <div>
411
+ <button className="px-3 py-2 rounded bg-blue-600 text-white" onClick={() => setOpen(true)}>
412
+ Pick image
413
+ </button>
414
+ <ImageManager
415
+ open={open}
416
+ onOpenChange={setOpen}
417
+ mode="browse"
418
+ clientOptions={{
419
+ baseUrl: process.env.NEXT_PUBLIC_UPFILES_APP_URL!,
420
+ apiKey: process.env.NEXT_PUBLIC_UPFILES_API_KEY!,
421
+ apiKeyHeader: 'authorization',
422
+ }}
423
+ // folderPath="my-plugin/images/" // optional
424
+ onSelect={async (img) => {
425
+ // Persist original image URL in your DB
426
+ await fetch('/api/media/save', {
427
+ method: 'POST',
428
+ headers: { 'content-type': 'application/json' },
429
+ body: JSON.stringify({ url: img.url, key: img.key }),
430
+ });
431
+ }}
432
+ />
433
+ </div>
434
+ );
435
+ }
436
+ ```
437
+
438
+ ## Reusing across multiple Next.js projects
439
+
440
+ - Install `@thetechfossil/upfiles` and `@radix-ui/react-dialog` in each project.
441
+ - Set an environment variable like `NEXT_PUBLIC_UPFILES_APP_URL` to point all consumers to your main Upfiles app.
442
+ - Each consumer stores its own copy of the API key in its DB, obtained via `ConnectProjectDialog`.
443
+
444
+ ## Troubleshooting
445
+
446
+ - __401 Unauthorized when listing/creating projects__: The `projects` and `keys` endpoints require a signed-in session on the main app domain. Open the dialog from a page that can send cookies to `{baseUrl}` or run from the same origin; otherwise configure auth/CORS accordingly.
447
+ - __CORS errors calling main app__: Ensure the main app allows your consumer origin in CORS and, if you use cookies, sets the correct `Access-Control-Allow-Credentials` headers and SameSite attributes.
448
+ - __Uploads fail__: Verify S3 bucket CORS and that `POST /api/plugin/upload/presigned-url` is accessible from the consumer app.
449
+ - __API key header__: Default is `Authorization: Bearer upk_...`. If your server expects a different header, set `apiKeyHeader: 'x-api-key' | 'x-up-api-key'` in `UpfilesClient` options.
package/dist/index.d.mts CHANGED
@@ -34,6 +34,19 @@ type FileListItem = {
34
34
  uploadedAt: string;
35
35
  url: string;
36
36
  };
37
+ /**
38
+ * Upfiles Client - JavaScript client for Upfiles Plugin API
39
+ *
40
+ * 📚 Full documentation: https://ttf-upfiles-docs.netlify.app/
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const client = new UpfilesClient({
45
+ * baseUrl: 'https://your-upfiles.example.com',
46
+ * apiKey: 'upk_...',
47
+ * });
48
+ * ```
49
+ */
37
50
  type UpfilesClientOptions = {
38
51
  baseUrl?: string;
39
52
  presignPath?: string;
@@ -44,6 +57,21 @@ type UpfilesClientOptions = {
44
57
  apiKeyHeader?: 'authorization' | 'x-api-key' | 'x-up-api-key';
45
58
  thumbnailsPath?: string;
46
59
  };
60
+ /**
61
+ * UpfilesClient - Main client class for interacting with Upfiles Plugin API
62
+ *
63
+ * 📚 Documentation: https://ttf-upfiles-docs.netlify.app/
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * const client = new UpfilesClient({
68
+ * baseUrl: 'https://your-upfiles.example.com',
69
+ * apiKey: 'upk_...',
70
+ * });
71
+ *
72
+ * const result = await client.upload(file, { folderPath: 'uploads/' });
73
+ * ```
74
+ */
47
75
  declare class UpfilesClient {
48
76
  private baseUrl?;
49
77
  private presignPath;
package/dist/index.d.ts CHANGED
@@ -34,6 +34,19 @@ type FileListItem = {
34
34
  uploadedAt: string;
35
35
  url: string;
36
36
  };
37
+ /**
38
+ * Upfiles Client - JavaScript client for Upfiles Plugin API
39
+ *
40
+ * 📚 Full documentation: https://ttf-upfiles-docs.netlify.app/
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const client = new UpfilesClient({
45
+ * baseUrl: 'https://your-upfiles.example.com',
46
+ * apiKey: 'upk_...',
47
+ * });
48
+ * ```
49
+ */
37
50
  type UpfilesClientOptions = {
38
51
  baseUrl?: string;
39
52
  presignPath?: string;
@@ -44,6 +57,21 @@ type UpfilesClientOptions = {
44
57
  apiKeyHeader?: 'authorization' | 'x-api-key' | 'x-up-api-key';
45
58
  thumbnailsPath?: string;
46
59
  };
60
+ /**
61
+ * UpfilesClient - Main client class for interacting with Upfiles Plugin API
62
+ *
63
+ * 📚 Documentation: https://ttf-upfiles-docs.netlify.app/
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * const client = new UpfilesClient({
68
+ * baseUrl: 'https://your-upfiles.example.com',
69
+ * apiKey: 'upk_...',
70
+ * });
71
+ *
72
+ * const result = await client.upload(file, { folderPath: 'uploads/' });
73
+ * ```
74
+ */
47
75
  declare class UpfilesClient {
48
76
  private baseUrl?;
49
77
  private presignPath;
package/package.json CHANGED
@@ -1,43 +1,45 @@
1
- {
2
- "name": "@thetechfossil/upfiles",
3
- "version": "1.0.0",
4
- "description": "Lightweight client and React components for Upfiles Plugin API (presigned S3)",
5
- "license": "MIT",
6
- "author": "UpFiles",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/your-org/upfiles.git"
10
- },
11
- "main": "dist/index.cjs",
12
- "module": "dist/index.mjs",
13
- "types": "dist/index.d.ts",
14
- "exports": {
15
- ".": {
16
- "import": "./dist/index.mjs",
17
- "require": "./dist/index.cjs"
18
- }
19
- },
20
- "files": [
21
- "dist"
22
- ],
23
- "publishConfig": {
24
- "access": "public"
25
- },
26
- "sideEffects": false,
27
- "scripts": {
28
- "build": "tsup src/index.ts --format cjs,esm --dts --clean",
29
- "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
30
- "typecheck": "tsc -p tsconfig.json --noEmit",
31
- "prepublishOnly": "bun run build"
32
- },
33
- "peerDependencies": {
34
- "react": ">=18",
35
- "@radix-ui/react-dialog": ">=1.0.0"
36
- },
37
- "devDependencies": {
38
- "@radix-ui/react-dialog": "^1.1.15",
39
- "@types/react": "^19",
40
- "tsup": "^8.3.0",
41
- "typescript": "^5.6.2"
42
- }
43
- }
1
+ {
2
+ "name": "@thetechfossil/upfiles",
3
+ "version": "1.0.2",
4
+ "description": "Lightweight client and React components for Upfiles Plugin API (presigned S3)",
5
+ "license": "MIT",
6
+ "author": "UpFiles",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/your-org/upfiles.git"
10
+ },
11
+ "homepage": "https://ttf-upfiles-docs.netlify.app/",
12
+ "documentation": "https://ttf-upfiles-docs.netlify.app/",
13
+ "main": "dist/index.cjs",
14
+ "module": "dist/index.mjs",
15
+ "types": "dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.mjs",
19
+ "require": "./dist/index.cjs"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "sideEffects": false,
29
+ "scripts": {
30
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
31
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
32
+ "typecheck": "tsc -p tsconfig.json --noEmit",
33
+ "prepublishOnly": "bun run build"
34
+ },
35
+ "peerDependencies": {
36
+ "react": ">=18",
37
+ "@radix-ui/react-dialog": ">=1.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "@radix-ui/react-dialog": "^1.1.15",
41
+ "@types/react": "^19",
42
+ "tsup": "^8.3.0",
43
+ "typescript": "^5.6.2"
44
+ }
45
+ }