@veap/storage 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.
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,134 @@
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)
3
+ [![Version](https://img.shields.io/npm/v/@veap/storage?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/@veap/storage)
2
4
 
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.
5
+ # @veap/storage
6
+
7
+ Unified file storage abstraction supporting local filesystem and cloud object
8
+ storage providers for Veap and Next.js applications.
9
+
10
+ ## Overview
11
+
12
+ `@veap/storage` simplifies file uploads, media management, and asset delivery.
13
+ It abstracts physical disk storage and cloud bucket drivers behind a consistent
14
+ `StorageService` API. It includes filename sanitization, automatic MIME-type
15
+ and extension validation, deduplication hashing, and driver routing.
16
+
17
+ ## Features
18
+
19
+ - **Multi-driver architecture**: Pluggable `StorageProvider` interface
20
+ allowing concurrent drivers (for example, local disk for uploads, S3 for archives).
21
+ - **Default local provider**: Ready-to-use `LocalFileProvider` saving files to
22
+ configurable public or private application directories.
23
+ - **Security & validation**: Built-in file extension sanitization, MIME-type
24
+ checks, and path traversal protection.
25
+ - **Clean IoC integration**: `StorageServiceProvider` automatically registers
26
+ the default provider and binds `StorageService` into the kernel container.
27
+ - **Next.js & standard web `File` support**: Works seamlessly with web standard
28
+ `File` and `FormData` objects from Server Actions and Route Handlers.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ # Using bun
34
+ bun add @veap/storage @veap/kernel
35
+
36
+ # Using pnpm
37
+ pnpm add @veap/storage @veap/kernel
38
+
39
+ # Using npm
40
+ npm install @veap/storage @veap/kernel
41
+ ```
42
+
43
+ ## Configuration
44
+
45
+ Configure the local storage directory using environment variables or
46
+ `ConfigService`:
47
+
48
+ | Environment Variable | Description | Default |
49
+ | --------------------- | -------------------------------------- | ---------------- |
50
+ | `FILE_STORAGE_FOLDER` | Destination folder on disk for uploads | `public/uploads` |
51
+
52
+ ## Usage
53
+
54
+ ### Register in Application Builder
55
+
56
+ Include `StorageServiceProvider` in your application composition root:
57
+
58
+ ```ts
59
+ import { Application } from "@veap/kernel";
60
+ import { StorageServiceProvider } from "@veap/storage";
61
+
62
+ export const app = Application.configure().use(StorageServiceProvider).create();
63
+ ```
64
+
65
+ ### Handling Uploads in Next.js Server Actions
66
+
67
+ Upload files directly from forms using `StorageService` resolved via IoC:
68
+
69
+ ```ts
70
+ "use server";
71
+
72
+ import { app } from "@veap/kernel";
73
+ import { StorageService } from "@veap/storage";
74
+
75
+ export async function uploadAvatar(formData: FormData) {
76
+ const file = formData.get("avatar") as File;
77
+ if (!file) {
78
+ throw new Error("No file provided");
79
+ }
80
+
81
+ const storage = await app(StorageService);
82
+ const result = await storage.upload(file, "local");
83
+
84
+ if ("error" in result) {
85
+ throw new Error(result.error);
86
+ }
87
+
88
+ return { url: result.url, path: result.path };
89
+ }
90
+ ```
91
+
92
+ ### Implementing a Custom Storage Driver
93
+
94
+ Create custom cloud storage drivers (for example, AWS S3 or Cloudflare R2) by
95
+ implementing the `StorageProvider` interface:
96
+
97
+ ```ts
98
+ import type { StorageProvider, StorageFile, UploadResult } from "@veap/storage";
99
+
100
+ export class S3StorageProvider implements StorageProvider {
101
+ public id = "s3";
102
+
103
+ async upload(file: StorageFile): Promise<UploadResult> {
104
+ // Perform upload to S3 bucket
105
+ return {
106
+ url: `https://my-bucket.s3.amazonaws.com/${file.name}`,
107
+ path: `uploads/${file.name}`,
108
+ };
109
+ }
110
+
111
+ async delete(filePath: string): Promise<boolean> {
112
+ // Delete file from S3 bucket
113
+ return true;
114
+ }
115
+ }
116
+ ```
117
+
118
+ ## Subpath Exports
119
+
120
+ | Export Path | Content |
121
+ | --------------- | -------------------------------------------------------------------------- |
122
+ | `@veap/storage` | `StorageService`, `StorageServiceProvider`, `LocalFileProvider`, and types |
123
+
124
+ ## Documentation
125
+
126
+ For full guides and storage driver configuration, visit:
127
+
128
+ - **Official Website**: [https://veap.pl](https://veap.pl)
129
+ - **Documentation**: [https://veap.pl/docs](https://veap.pl/docs)
130
+ - **GitHub Repository**: [https://github.com/veapjs/veap-storage](https://github.com/veapjs/veap-storage)
131
+
132
+ ## License
133
+
134
+ MIT
@@ -0,0 +1,4 @@
1
+ export * from "./provider.js";
2
+ export * from "./providers/local.js";
3
+ export * from "./storage.service.js";
4
+ export * from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./provider.js";
2
+ export * from "./providers/local.js";
3
+ export * from "./storage.service.js";
4
+ export * from "./types.js";
@@ -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,28 @@
1
+ import { ConfigService, ServiceProvider } from "@veap/kernel";
2
+ import { LocalFileProvider } from "./providers/local.js";
3
+ import { StorageService } from "./storage.service.js";
4
+ import { STORAGE_SERVICE } from "./types.js";
5
+ export class StorageServiceProvider extends ServiceProvider {
6
+ register() {
7
+ this.container.register({
8
+ token: StorageService,
9
+ useClass: StorageService,
10
+ singleton: true,
11
+ });
12
+ this.container.register({
13
+ token: STORAGE_SERVICE,
14
+ useFactory: (service) => service,
15
+ inject: [StorageService],
16
+ singleton: true,
17
+ });
18
+ }
19
+ async boot() {
20
+ const storageService = await this.container.resolve(StorageService);
21
+ const config = await this.container.resolve(ConfigService);
22
+ if (storageService.getProviders().length === 0) {
23
+ const local = new LocalFileProvider(config);
24
+ storageService.registerProvider(local);
25
+ storageService.setDefaultProvider(local.id);
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,12 @@
1
+ import { ConfigService } from "@veap/kernel";
2
+ import type { IStorageProvider, StorageResult } from "../types.js";
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,142 @@
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
+ await fs.promises.mkdir(/*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
+ await fs.promises.writeFile(
86
+ /*turbopackIgnore: true*/ filePath, Buffer.from(buffer));
87
+ const rawUrl = `${storageFolder}/${name}`.replace("public", "");
88
+ const url = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
89
+ return {
90
+ name: name,
91
+ url,
92
+ type: file.type,
93
+ size: file.size,
94
+ service: "local",
95
+ serviceId: filePath,
96
+ };
97
+ }
98
+ catch (error) {
99
+ warn("veap:storage", `Error uploading file: ${error}`);
100
+ return { error: "Error uploading file" };
101
+ }
102
+ }
103
+ async delete(keyOrUrl) {
104
+ try {
105
+ const storageFolder = this.getStorageFolder();
106
+ let filePath = keyOrUrl;
107
+ // If it is a web path (starting with /), we map it back to the local storage path.
108
+ if (keyOrUrl.startsWith("/")) {
109
+ const relativeStorageFolder = storageFolder.startsWith("public")
110
+ ? storageFolder.replace("public", "") // e.g. "/storage"
111
+ : storageFolder;
112
+ if (keyOrUrl.startsWith(relativeStorageFolder)) {
113
+ filePath = path.join(
114
+ /*turbopackIgnore: true*/ storageFolder, keyOrUrl.substring(relativeStorageFolder.length));
115
+ }
116
+ else {
117
+ filePath = path.join(/*turbopackIgnore: true*/ "public", keyOrUrl);
118
+ }
119
+ }
120
+ const absolutePath = path.isAbsolute(filePath)
121
+ ? filePath
122
+ : path.resolve(/*turbopackIgnore: true*/ filePath);
123
+ const absoluteStorageFolder = path.resolve(
124
+ /*turbopackIgnore: true*/ storageFolder);
125
+ // Security check: ensure filePath is strictly inside the storage folder to prevent directory traversal
126
+ const relative = path.relative(absoluteStorageFolder, absolutePath);
127
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
128
+ warn("veap:storage", `Directory traversal attempt blocked: ${absolutePath}`);
129
+ return false;
130
+ }
131
+ if (fs.existsSync(/*turbopackIgnore: true*/ absolutePath)) {
132
+ await fs.promises.unlink(/*turbopackIgnore: true*/ absolutePath);
133
+ return true;
134
+ }
135
+ return false;
136
+ }
137
+ catch (error) {
138
+ warn("veap:storage", `Error deleting file: ${error}`);
139
+ return false;
140
+ }
141
+ }
142
+ }
@@ -0,0 +1,18 @@
1
+ import { type ILogger } from "@veap/kernel";
2
+ import type { IStorageProvider, IStorageService, StorageResult } from "./types.js";
3
+ export declare class StorageService implements IStorageService {
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
+ getDefaultProviderId(): string | null;
12
+ upload(file: File, providerId?: string): Promise<StorageResult>;
13
+ delete(keyOrUrl: string, providerId?: string): Promise<boolean>;
14
+ getProviders(): Array<{
15
+ id: string;
16
+ name: string;
17
+ }>;
18
+ }
@@ -0,0 +1,86 @@
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
+ getDefaultProviderId() {
44
+ return this.defaultProviderId;
45
+ }
46
+ async upload(file, providerId) {
47
+ let id = providerId || this.defaultProviderId;
48
+ if (!id || !this.providers.has(id)) {
49
+ id = "local";
50
+ }
51
+ const provider = this.providers.get(id);
52
+ if (!provider) {
53
+ this.logger.warn("veap:storage", "No storage provider available (local fallback failed)");
54
+ return { error: "No storage provider available (local fallback failed)" };
55
+ }
56
+ return await provider.upload(file);
57
+ }
58
+ async delete(keyOrUrl, providerId) {
59
+ let id = providerId || this.defaultProviderId;
60
+ if (!id || !this.providers.has(id)) {
61
+ id = "local";
62
+ }
63
+ const provider = this.providers.get(id);
64
+ if (!provider) {
65
+ this.logger.warn("veap:storage", "No storage provider available for deletion (local fallback failed)");
66
+ return false;
67
+ }
68
+ if (!provider.delete) {
69
+ this.logger.warn("veap:storage", `Storage provider "${id}" does not support deletion`);
70
+ return false;
71
+ }
72
+ return await provider.delete(keyOrUrl);
73
+ }
74
+ getProviders() {
75
+ return Array.from(this.providers.values()).map((p) => ({
76
+ id: p.id,
77
+ name: p.name,
78
+ }));
79
+ }
80
+ };
81
+ StorageService = __decorate([
82
+ Injectable(),
83
+ __param(0, Inject(LOGGER)),
84
+ __metadata("design:paramtypes", [Object])
85
+ ], StorageService);
86
+ export { StorageService };
@@ -0,0 +1,32 @@
1
+ import type { Token } from "@veap/kernel";
2
+ export interface StorageData {
3
+ name: string;
4
+ url: string;
5
+ type: string;
6
+ size: number;
7
+ service: string;
8
+ serviceId: string;
9
+ }
10
+ export interface StorageError {
11
+ error: string;
12
+ }
13
+ export type StorageResult = StorageData | StorageError;
14
+ export interface IStorageProvider {
15
+ id: string;
16
+ name: string;
17
+ upload(file: File, options?: any): Promise<StorageResult>;
18
+ delete?(serviceId: string): Promise<boolean>;
19
+ }
20
+ export interface IStorageService {
21
+ registerProvider(provider: IStorageProvider): void;
22
+ unregisterProvider(id: string): void;
23
+ setDefaultProvider(id: string): void;
24
+ getDefaultProviderId(): string | null;
25
+ upload(file: File, providerId?: string): Promise<StorageResult>;
26
+ delete(keyOrUrl: string, providerId?: string): Promise<boolean>;
27
+ getProviders(): Array<{
28
+ id: string;
29
+ name: string;
30
+ }>;
31
+ }
32
+ export declare const STORAGE_SERVICE: Token<IStorageService>;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export const STORAGE_SERVICE = Symbol.for("veap:storage:service");
package/package.json CHANGED
@@ -1,6 +1,47 @@
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.1",
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
+ "./providers/local": {
20
+ "types": "./dist/providers/local.d.ts",
21
+ "default": "./dist/providers/local.js"
22
+ },
23
+ "./types": {
24
+ "types": "./dist/types.d.ts",
25
+ "default": "./dist/types.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "scripts": {
33
+ "clean": "rimraf dist",
34
+ "build": "rimraf dist && tsc",
35
+ "dev": "tsc --watch",
36
+ "test": "vitest run"
37
+ },
38
+ "dependencies": {
39
+ "@veap/kernel": "0.1.1"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.20.2",
43
+ "rimraf": "^6.1.3",
44
+ "typescript": "6.0.3",
45
+ "vitest": "^5.0.0"
46
+ }
47
+ }