@veap/storage 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Damian Miller
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,133 @@
1
- # Temporary Holding Version
1
+ [![CI](https://github.com/veapjs/veap-storage/actions/workflows/ci.yml/badge.svg)](https://github.com/veapjs/veap-storage/actions/workflows/ci.yml)
2
+ [![Release](https://github.com/veapjs/veap-storage/actions/workflows/release.yml/badge.svg)](https://github.com/veapjs/veap-storage/actions/workflows/release.yml)
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ # @veap/storage
5
+
6
+ Unified file storage abstraction supporting local filesystem and cloud object
7
+ storage providers for Veap and Next.js applications.
8
+
9
+ ## Overview
10
+
11
+ `@veap/storage` simplifies file uploads, media management, and asset delivery.
12
+ It abstracts physical disk storage and cloud bucket drivers behind a consistent
13
+ `StorageService` API. It includes filename sanitization, automatic MIME-type
14
+ and extension validation, deduplication hashing, and driver routing.
15
+
16
+ ## Features
17
+
18
+ - **Multi-driver architecture**: Pluggable `StorageProvider` interface
19
+ allowing concurrent drivers (for example, local disk for uploads, S3 for archives).
20
+ - **Default local provider**: Ready-to-use `LocalFileProvider` saving files to
21
+ configurable public or private application directories.
22
+ - **Security & validation**: Built-in file extension sanitization, MIME-type
23
+ checks, and path traversal protection.
24
+ - **Clean IoC integration**: `StorageServiceProvider` automatically registers
25
+ the default provider and binds `StorageService` into the kernel container.
26
+ - **Next.js & standard web `File` support**: Works seamlessly with web standard
27
+ `File` and `FormData` objects from Server Actions and Route Handlers.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ # Using bun
33
+ bun add @veap/storage @veap/kernel
34
+
35
+ # Using pnpm
36
+ pnpm add @veap/storage @veap/kernel
37
+
38
+ # Using npm
39
+ npm install @veap/storage @veap/kernel
40
+ ```
41
+
42
+ ## Configuration
43
+
44
+ Configure the local storage directory using environment variables or
45
+ `ConfigService`:
46
+
47
+ | Environment Variable | Description | Default |
48
+ | --------------------- | -------------------------------------- | ---------------- |
49
+ | `FILE_STORAGE_FOLDER` | Destination folder on disk for uploads | `public/uploads` |
50
+
51
+ ## Usage
52
+
53
+ ### Register in Application Builder
54
+
55
+ Include `StorageServiceProvider` in your application composition root:
56
+
57
+ ```ts
58
+ import { Application } from "@veap/kernel";
59
+ import { StorageServiceProvider } from "@veap/storage";
60
+
61
+ export const app = Application.configure().use(StorageServiceProvider).create();
62
+ ```
63
+
64
+ ### Handling Uploads in Next.js Server Actions
65
+
66
+ Upload files directly from forms using `StorageService` resolved via IoC:
67
+
68
+ ```ts
69
+ "use server";
70
+
71
+ import { app } from "@veap/kernel";
72
+ import { StorageService } from "@veap/storage";
73
+
74
+ export async function uploadAvatar(formData: FormData) {
75
+ const file = formData.get("avatar") as File;
76
+ if (!file) {
77
+ throw new Error("No file provided");
78
+ }
79
+
80
+ const storage = await app(StorageService);
81
+ const result = await storage.upload(file, "local");
82
+
83
+ if ("error" in result) {
84
+ throw new Error(result.error);
85
+ }
86
+
87
+ return { url: result.url, path: result.path };
88
+ }
89
+ ```
90
+
91
+ ### Implementing a Custom Storage Driver
92
+
93
+ Create custom cloud storage drivers (for example, AWS S3 or Cloudflare R2) by
94
+ implementing the `StorageProvider` interface:
95
+
96
+ ```ts
97
+ import type { StorageProvider, StorageFile, UploadResult } from "@veap/storage";
98
+
99
+ export class S3StorageProvider implements StorageProvider {
100
+ public id = "s3";
101
+
102
+ async upload(file: StorageFile): Promise<UploadResult> {
103
+ // Perform upload to S3 bucket
104
+ return {
105
+ url: `https://my-bucket.s3.amazonaws.com/${file.name}`,
106
+ path: `uploads/${file.name}`,
107
+ };
108
+ }
109
+
110
+ async delete(filePath: string): Promise<boolean> {
111
+ // Delete file from S3 bucket
112
+ return true;
113
+ }
114
+ }
115
+ ```
116
+
117
+ ## Subpath Exports
118
+
119
+ | Export Path | Content |
120
+ | --------------- | -------------------------------------------------------------------------- |
121
+ | `@veap/storage` | `StorageService`, `StorageServiceProvider`, `LocalFileProvider`, and types |
122
+
123
+ ## Documentation
124
+
125
+ For full guides and storage driver configuration, visit:
126
+
127
+ - **Official Website**: [https://veap.pl](https://veap.pl)
128
+ - **Documentation**: [https://veap.pl/docs](https://veap.pl/docs)
129
+ - **GitHub Repository**: [https://github.com/veapjs/veap-storage](https://github.com/veapjs/veap-storage)
130
+
131
+ ## License
132
+
133
+ MIT
@@ -0,0 +1,4 @@
1
+ export * from "./provider";
2
+ export * from "./providers/local";
3
+ export * from "./storage.service";
4
+ export * from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./provider";
2
+ export * from "./providers/local";
3
+ export * from "./storage.service";
4
+ export * from "./types";
@@ -0,0 +1,5 @@
1
+ import { ServiceProvider } from "@veap/kernel";
2
+ export declare class StorageServiceProvider extends ServiceProvider {
3
+ register(): void;
4
+ boot(): Promise<void>;
5
+ }
@@ -0,0 +1,21 @@
1
+ import { ConfigService, ServiceProvider } from "@veap/kernel";
2
+ import { LocalFileProvider } from "./providers/local";
3
+ import { StorageService } from "./storage.service";
4
+ export class StorageServiceProvider extends ServiceProvider {
5
+ register() {
6
+ this.container.register({
7
+ token: StorageService,
8
+ useClass: StorageService,
9
+ singleton: true,
10
+ });
11
+ }
12
+ async boot() {
13
+ const storageService = await this.container.resolve(StorageService);
14
+ const config = await this.container.resolve(ConfigService);
15
+ if (storageService.getProviders().length === 0) {
16
+ const local = new LocalFileProvider(config);
17
+ storageService.registerProvider(local);
18
+ storageService.setDefaultProvider(local.id);
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,12 @@
1
+ import { ConfigService } from "@veap/kernel";
2
+ import type { IStorageProvider, StorageResult } from "../types";
3
+ export declare class LocalFileProvider implements IStorageProvider {
4
+ private config;
5
+ id: string;
6
+ name: string;
7
+ constructor(config: ConfigService);
8
+ private getStorageFolder;
9
+ private generateUniqueImageName;
10
+ upload(file: File): Promise<StorageResult>;
11
+ delete(keyOrUrl: string): Promise<boolean>;
12
+ }
@@ -0,0 +1,140 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { warn } from "@veap/kernel";
4
+ const DANGEROUS_EXTENSIONS = new Set([
5
+ ".html",
6
+ ".htm",
7
+ ".xhtml",
8
+ ".shtml",
9
+ ".svg",
10
+ ".xml",
11
+ ".php",
12
+ ".phtml",
13
+ ".php3",
14
+ ".php4",
15
+ ".php5",
16
+ ".phps",
17
+ ".asp",
18
+ ".aspx",
19
+ ".jsp",
20
+ ".jspx",
21
+ ".cgi",
22
+ ".pl",
23
+ ".py",
24
+ ".sh",
25
+ ".bash",
26
+ ".exe",
27
+ ".dll",
28
+ ".bat",
29
+ ".cmd",
30
+ ".ps1",
31
+ ".vbs",
32
+ ".js",
33
+ ".mjs",
34
+ ".cjs",
35
+ ".jsx",
36
+ ".ts",
37
+ ".tsx",
38
+ ".phar",
39
+ ".htaccess",
40
+ ".env",
41
+ ".config",
42
+ ]);
43
+ export class LocalFileProvider {
44
+ config;
45
+ id = "local";
46
+ name = "Local Filesystem";
47
+ constructor(config) {
48
+ this.config = config;
49
+ }
50
+ getStorageFolder() {
51
+ return (this.config.get("FILE_STORAGE_FOLDER") ||
52
+ (typeof process !== "undefined" && process.env?.FILE_STORAGE_FOLDER) ||
53
+ "public/uploads");
54
+ }
55
+ generateUniqueImageName(originalName) {
56
+ const rawName = path.basename(originalName || "file").replace(/\0/g, "");
57
+ const ext = path.extname(rawName).toLowerCase();
58
+ const baseWithoutExt = path
59
+ .basename(rawName, ext)
60
+ .replace(/[^a-zA-Z0-9_-]/g, "_")
61
+ .toLowerCase();
62
+ const cleanBase = baseWithoutExt || "file";
63
+ const suffix = `${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
64
+ return `${cleanBase}-${suffix}${ext}`;
65
+ }
66
+ async upload(file) {
67
+ try {
68
+ const rawName = path.basename(file.name || "file").replace(/\0/g, "");
69
+ const ext = path.extname(rawName).toLowerCase();
70
+ if (!ext || DANGEROUS_EXTENSIONS.has(ext)) {
71
+ warn("veap:storage", `Blocked file upload with disallowed or dangerous extension: "${ext}"`);
72
+ return {
73
+ error: `File type "${ext}" is not allowed for security reasons`,
74
+ };
75
+ }
76
+ const storageFolder = this.getStorageFolder();
77
+ if (!fs.existsSync(/*turbopackIgnore: true*/ storageFolder)) {
78
+ fs.mkdirSync(/*turbopackIgnore: true*/ storageFolder, {
79
+ recursive: true,
80
+ });
81
+ }
82
+ const name = this.generateUniqueImageName(rawName);
83
+ const filePath = path.join(/*turbopackIgnore: true*/ storageFolder, name);
84
+ const buffer = await file.arrayBuffer();
85
+ fs.writeFileSync(/*turbopackIgnore: true*/ filePath, Buffer.from(buffer));
86
+ const url = `${storageFolder}/${name}`.replace("public", "");
87
+ return {
88
+ name: name,
89
+ url,
90
+ type: file.type,
91
+ size: file.size,
92
+ service: "local",
93
+ serviceId: filePath,
94
+ };
95
+ }
96
+ catch (error) {
97
+ warn("veap:storage", `Error uploading file: ${error}`);
98
+ return { error: "Error uploading file" };
99
+ }
100
+ }
101
+ async delete(keyOrUrl) {
102
+ try {
103
+ const storageFolder = this.getStorageFolder();
104
+ let filePath = keyOrUrl;
105
+ // If it is a web path (starting with /), we map it back to the local storage path.
106
+ if (keyOrUrl.startsWith("/")) {
107
+ const relativeStorageFolder = storageFolder.startsWith("public")
108
+ ? storageFolder.replace("public", "") // e.g. "/storage"
109
+ : storageFolder;
110
+ if (keyOrUrl.startsWith(relativeStorageFolder)) {
111
+ filePath = path.join(
112
+ /*turbopackIgnore: true*/ storageFolder, keyOrUrl.substring(relativeStorageFolder.length));
113
+ }
114
+ else {
115
+ filePath = path.join(/*turbopackIgnore: true*/ "public", keyOrUrl);
116
+ }
117
+ }
118
+ const absolutePath = path.isAbsolute(filePath)
119
+ ? filePath
120
+ : path.resolve(/*turbopackIgnore: true*/ filePath);
121
+ const absoluteStorageFolder = path.resolve(
122
+ /*turbopackIgnore: true*/ storageFolder);
123
+ // Security check: ensure filePath is strictly inside the storage folder to prevent directory traversal
124
+ const relative = path.relative(absoluteStorageFolder, absolutePath);
125
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
126
+ warn("veap:storage", `Directory traversal attempt blocked: ${absolutePath}`);
127
+ return false;
128
+ }
129
+ if (fs.existsSync(/*turbopackIgnore: true*/ absolutePath)) {
130
+ fs.unlinkSync(/*turbopackIgnore: true*/ absolutePath);
131
+ return true;
132
+ }
133
+ return false;
134
+ }
135
+ catch (error) {
136
+ warn("veap:storage", `Error deleting file: ${error}`);
137
+ return false;
138
+ }
139
+ }
140
+ }
@@ -0,0 +1,17 @@
1
+ import { type ILogger } from "@veap/kernel";
2
+ import type { IStorageProvider, StorageResult } from "./types";
3
+ export declare class StorageService {
4
+ private providers;
5
+ private defaultProviderId;
6
+ private logger;
7
+ constructor(logger: ILogger);
8
+ registerProvider(provider: IStorageProvider): void;
9
+ unregisterProvider(id: string): void;
10
+ setDefaultProvider(id: string): void;
11
+ upload(file: File, providerId?: string): Promise<StorageResult>;
12
+ delete(keyOrUrl: string, providerId?: string): Promise<boolean>;
13
+ getProviders(): {
14
+ id: string;
15
+ name: string;
16
+ }[];
17
+ }
@@ -0,0 +1,83 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { Inject, Injectable, LOGGER } from "@veap/kernel";
14
+ let StorageService = class StorageService {
15
+ providers = new Map();
16
+ defaultProviderId = null;
17
+ logger;
18
+ constructor(logger) {
19
+ this.logger = logger;
20
+ }
21
+ registerProvider(provider) {
22
+ this.providers.set(provider.id, provider);
23
+ if (!this.defaultProviderId || this.defaultProviderId === "local") {
24
+ this.defaultProviderId = provider.id;
25
+ }
26
+ this.logger.info("veap:storage", `Provider registered: ${provider.id}`);
27
+ }
28
+ unregisterProvider(id) {
29
+ this.providers.delete(id);
30
+ if (this.defaultProviderId === id) {
31
+ this.defaultProviderId = this.providers.has("local")
32
+ ? "local"
33
+ : Array.from(this.providers.keys())[0] || null;
34
+ }
35
+ this.logger.info("veap:storage", `Provider unregistered: ${id}`);
36
+ }
37
+ setDefaultProvider(id) {
38
+ if (this.providers.has(id)) {
39
+ this.defaultProviderId = id;
40
+ this.logger.info("veap:storage", `Default provider set to: ${id}`);
41
+ }
42
+ }
43
+ async upload(file, providerId) {
44
+ let id = providerId || this.defaultProviderId;
45
+ if (!id || !this.providers.has(id)) {
46
+ id = "local";
47
+ }
48
+ const provider = this.providers.get(id);
49
+ if (!provider) {
50
+ this.logger.warn("veap:storage", "No storage provider available (local fallback failed)");
51
+ return { error: "No storage provider available (local fallback failed)" };
52
+ }
53
+ return await provider.upload(file);
54
+ }
55
+ async delete(keyOrUrl, providerId) {
56
+ let id = providerId || this.defaultProviderId;
57
+ if (!id || !this.providers.has(id)) {
58
+ id = "local";
59
+ }
60
+ const provider = this.providers.get(id);
61
+ if (!provider) {
62
+ this.logger.warn("veap:storage", "No storage provider available for deletion (local fallback failed)");
63
+ return false;
64
+ }
65
+ if (!provider.delete) {
66
+ this.logger.warn("veap:storage", `Storage provider "${id}" does not support deletion`);
67
+ return false;
68
+ }
69
+ return await provider.delete(keyOrUrl);
70
+ }
71
+ getProviders() {
72
+ return Array.from(this.providers.values()).map((p) => ({
73
+ id: p.id,
74
+ name: p.name,
75
+ }));
76
+ }
77
+ };
78
+ StorageService = __decorate([
79
+ Injectable(),
80
+ __param(0, Inject(LOGGER)),
81
+ __metadata("design:paramtypes", [Object])
82
+ ], StorageService);
83
+ export { StorageService };
@@ -0,0 +1,18 @@
1
+ export interface StorageData {
2
+ name: string;
3
+ url: string;
4
+ type: string;
5
+ size: number;
6
+ service: string;
7
+ serviceId: string;
8
+ }
9
+ export interface StorageError {
10
+ error: string;
11
+ }
12
+ export type StorageResult = StorageData | StorageError;
13
+ export interface IStorageProvider {
14
+ id: string;
15
+ name: string;
16
+ upload(file: File, options?: any): Promise<StorageResult>;
17
+ delete?(serviceId: string): Promise<boolean>;
18
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@veap/storage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "File storage service and local driver for Veap",
5
+ "bugs": "https://github.com/veapjs/veap-storage/issues",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/veapjs/veap-storage.git"
9
+ },
10
+ "type": "module",
11
+ "license": "MIT",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "clean": "rimraf dist",
26
+ "build": "rimraf dist && tsc",
27
+ "dev": "tsc --watch",
28
+ "test": "vitest run"
29
+ },
30
+ "dependencies": {
31
+ "@veap/kernel": "0.1.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^22.20.2",
35
+ "rimraf": "^6.1.3",
36
+ "typescript": "6.0.3",
37
+ "vitest": "^5.0.0"
38
+ }
39
+ }