@warlock.js/core 5.2.3 → 5.3.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/CHANGELOG.md +6 -0
- package/esm/application/application.d.mts.map +1 -1
- package/esm/application/application.mjs.map +1 -1
- package/esm/benchmark/benchmark-snapshots.d.mts.map +1 -1
- package/esm/benchmark/benchmark.d.mts.map +1 -1
- package/esm/benchmark/channels/console.channel.mjs.map +1 -1
- package/esm/benchmark/channels/noop.channel.d.mts.map +1 -1
- package/esm/benchmark/profiler.d.mts.map +1 -1
- package/esm/benchmark/profiler.mjs.map +1 -1
- package/esm/bootstrap/setup.d.mts.map +1 -1
- package/esm/bootstrap/setup.mjs.map +1 -1
- package/esm/bootstrap.d.mts.map +1 -1
- package/esm/cache/database-cache-driver.d.mts.map +1 -1
- package/esm/cache/database-cache-driver.mjs.map +1 -1
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/cli-commands.utils.mjs.map +1 -1
- package/esm/cli/commands/doctor/boot-for-diagnostics.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/connectors.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/handler-signature.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/health.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/routes.check.mjs.map +1 -1
- package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/templates/stubs.mjs +13 -14
- package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/name-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/prompt.mjs.map +1 -1
- package/esm/cli/commands/routes/diff-page-routes.mjs.map +1 -1
- package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
- package/esm/cli/commands/routes/route-row.mjs.map +1 -1
- package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -1
- package/esm/cli/commands/routes/routes-diff.action.mjs.map +1 -1
- package/esm/cli/commands/storage-put.action.mjs.map +1 -1
- package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
- package/esm/cli/commands-loader.mjs.map +1 -1
- package/esm/cli/start.mjs.map +1 -1
- package/esm/cli/string-similarity.mjs.map +1 -1
- package/esm/commands/cli-command.mjs.map +1 -1
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/config/config-setter.d.mts.map +1 -1
- package/esm/config/load-config-files.mjs.map +1 -1
- package/esm/connectors/access-connector.d.mts.map +1 -1
- package/esm/connectors/ai-connector.d.mts.map +1 -1
- package/esm/connectors/assert-no-reserved-connector-names.mjs.map +1 -1
- package/esm/connectors/assert-unique-connector-names.mjs.map +1 -1
- package/esm/connectors/base-connector.d.mts.map +1 -1
- package/esm/connectors/base-connector.mjs.map +1 -1
- package/esm/connectors/cache-connector.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/database-connector.d.mts.map +1 -1
- package/esm/connectors/describe-server-address.mjs.map +1 -1
- package/esm/connectors/herald-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/logger-connector.d.mts.map +1 -1
- package/esm/connectors/mail-connector.d.mts.map +1 -1
- package/esm/connectors/notifications-connector.d.mts.map +1 -1
- package/esm/connectors/register-configured-connectors.mjs.map +1 -1
- package/esm/connectors/socket-connector.d.mts.map +1 -1
- package/esm/connectors/socket-connector.mjs.map +1 -1
- package/esm/connectors/storage.connector.d.mts.map +1 -1
- package/esm/container/index.d.mts.map +1 -1
- package/esm/database/create-database-action.mjs.map +1 -1
- package/esm/database/drop-tables-action.mjs.map +1 -1
- package/esm/database/migrate-action.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/database/seeds/seed-records-table-migration.mjs.map +1 -1
- package/esm/database/seeds/seeders.manager.mjs.map +1 -1
- package/esm/database/seeds/seeds-table-migration.mjs.map +1 -1
- package/esm/dev-server/check-for-updates.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.d.mts.map +1 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/file-event-handler.mjs.map +1 -1
- package/esm/dev-server/file-manager.d.mts.map +1 -1
- package/esm/dev-server/file-manager.mjs.map +1 -1
- package/esm/dev-server/file-operations.d.mts.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/files-watcher.mjs.map +1 -1
- package/esm/dev-server/health-checker/checkers/eslint-health-checker.mjs.map +1 -1
- package/esm/dev-server/health-checker/checkers/typescript-health-checker.mjs.map +1 -1
- package/esm/dev-server/health-checker/file-health-result.d.mts.map +1 -1
- package/esm/dev-server/health-checker/file-health-result.mjs.map +1 -1
- package/esm/dev-server/health-checker/files-healthcare.manager.mjs.map +1 -1
- package/esm/dev-server/layer-executor.mjs.map +1 -1
- package/esm/dev-server/loader/hook-thread.d.mts.map +1 -1
- package/esm/dev-server/loader/own-resolver.mjs.map +1 -1
- package/esm/dev-server/loader/register-loader.mjs.map +1 -1
- package/esm/dev-server/loader/resolve-hook.mjs.map +1 -1
- package/esm/dev-server/loader/source-slug.mjs.map +1 -1
- package/esm/dev-server/loader/transpile-cache.mjs.map +1 -1
- package/esm/dev-server/loader/version-registry.mjs.map +1 -1
- package/esm/dev-server/manifest-manager.d.mts.map +1 -1
- package/esm/dev-server/manifest-manager.mjs.map +1 -1
- package/esm/dev-server/module-loader.mjs.map +1 -1
- package/esm/dev-server/package-json-manager.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/dev-server/ready-block.mjs.map +1 -1
- package/esm/dev-server/special-files-collector.d.mts.map +1 -1
- package/esm/dev-server/special-files-collector.mjs.map +1 -1
- package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/dev-server/utils.mjs.map +1 -1
- package/esm/encryption/encrypt.mjs.map +1 -1
- package/esm/encryption/hash.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/shadcn.feature.mjs.map +1 -1
- package/esm/generations/features/shared/migration-timestamp.mjs.map +1 -1
- package/esm/generations/features/tailwind.feature.mjs.map +1 -1
- package/esm/generations/features/web.feature.mjs +2 -1
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/generations/stubs.mjs +53 -54
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/boot-port-preflight.d.mts.map +1 -1
- package/esm/http/context/request-context.d.mts.map +1 -1
- package/esm/http/context/request-context.mjs.map +1 -1
- package/esm/http/context/request-memo.d.mts.map +1 -1
- package/esm/http/context/request-memo.mjs.map +1 -1
- package/esm/http/createHttpApplication.d.mts.map +1 -1
- package/esm/http/createHttpApplication.mjs.map +1 -1
- package/esm/http/health.d.mts.map +1 -1
- package/esm/http/index.d.mts +1 -1
- package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +2 -21
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
- package/esm/http/ready-report.d.mts.map +1 -1
- package/esm/http/request-controller.d.mts.map +1 -1
- package/esm/http/request.d.mts +25 -6
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +48 -0
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +3 -3
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server.d.mts.map +1 -1
- package/esm/http/server.mjs.map +1 -1
- package/esm/http/types.d.mts +36 -5
- package/esm/http/types.d.mts.map +1 -1
- package/esm/http/uploaded-file.d.mts.map +1 -1
- package/esm/http/uploaded-file.mjs.map +1 -1
- package/esm/http/uploads-config.d.mts.map +1 -1
- package/esm/image/image.d.mts.map +1 -1
- package/esm/image/image.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/logger/logger.mjs.map +1 -1
- package/esm/mail/config.d.mts.map +1 -1
- package/esm/mail/events.d.mts.map +1 -1
- package/esm/mail/mail.d.mts.map +1 -1
- package/esm/mail/mail.mjs.map +1 -1
- package/esm/mail/mailer-pool.d.mts.map +1 -1
- package/esm/mail/mailer-pool.mjs.map +1 -1
- package/esm/mail/send-mail.mjs.map +1 -1
- package/esm/mail/test-mailbox.d.mts.map +1 -1
- package/esm/mail/test-mailbox.mjs.map +1 -1
- package/esm/production/assert-generated-imports.mjs.map +1 -1
- package/esm/production/build-app-production.mjs.map +1 -1
- package/esm/production/dist-build-manifest.mjs.map +1 -1
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/promote-dist.mjs.map +1 -1
- package/esm/production/resolve-build-config.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-adapter.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-adapter.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/repositories/repository.manager.d.mts.map +1 -1
- package/esm/repositories/repository.manager.mjs.map +1 -1
- package/esm/resource/register-resource.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.mjs.map +1 -1
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/restful/restful.d.mts.map +1 -1
- package/esm/restful/restful.mjs.map +1 -1
- package/esm/router/log-request-lifecycle.mjs.map +1 -1
- package/esm/router/normalize-route-path.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
- package/esm/router/route-registry.d.mts.map +1 -1
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs.map +1 -1
- package/esm/socket/utils.d.mts.map +1 -1
- package/esm/storage/config.d.mts.map +1 -1
- package/esm/storage/context/storage-driver-context.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
- package/esm/storage/drivers/do-spaces-driver.d.mts.map +1 -1
- package/esm/storage/drivers/local-driver.d.mts.map +1 -1
- package/esm/storage/drivers/local-driver.mjs.map +1 -1
- package/esm/storage/drivers/r2-driver.d.mts.map +1 -1
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage-file.d.mts.map +1 -1
- package/esm/storage/storage-file.mjs.map +1 -1
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/tests/start-http-development-server.d.mts.map +1 -1
- package/esm/tests/test-connectors-selection.mjs.map +1 -1
- package/esm/tests/test-helpers.d.mts.map +1 -1
- package/esm/tests/test-setup-timeout.mjs.map +1 -1
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/esm/updater/update-warlock-packages.mjs.map +1 -1
- package/esm/use-cases/use-case-broadcast.d.mts.map +1 -1
- package/esm/use-cases/use-case-events.d.mts.map +1 -1
- package/esm/use-cases/use-case-pipeline.d.mts.map +1 -1
- package/esm/use-cases/use-case.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.mjs.map +1 -1
- package/esm/utils/database-log.d.mts.map +1 -1
- package/esm/utils/database-log.mjs.map +1 -1
- package/esm/utils/environment.d.mts.map +1 -1
- package/esm/utils/framework-vesion.mjs.map +1 -1
- package/esm/utils/get-localized.mjs.map +1 -1
- package/esm/utils/load-environment.mjs.map +1 -1
- package/esm/utils/normalized-path.d.mts.map +1 -1
- package/esm/utils/paths.d.mts.map +1 -1
- package/esm/utils/promise-all-object.d.mts.map +1 -1
- package/esm/utils/promise-all-object.mjs.map +1 -1
- package/esm/utils/sluggable.mjs.map +1 -1
- package/esm/utils/version-compare.mjs.map +1 -1
- package/esm/validation/database/exists-except-current-id.mjs.map +1 -1
- package/esm/validation/database/exists-except-current-user.mjs.map +1 -1
- package/esm/validation/database/unique-except-current-id.mjs.map +1 -1
- package/esm/validation/plugins/file-plugin.mjs.map +1 -1
- package/esm/validation/plugins/localized-plugin.mjs +2 -2
- package/esm/validation/plugins/localized-plugin.mjs.map +1 -1
- package/esm/validation/types.d.mts +17 -4
- package/esm/validation/types.d.mts.map +1 -1
- package/esm/validation/validators/file-validator.mjs.map +1 -1
- package/esm/vite/lower-stage3-decorators.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
- package/llms-full.txt +113 -87
- package/llms.txt +2 -2
- package/package.json +12 -12
- package/skills/README.md +2 -2
- package/skills/create-controller/SKILL.md +9 -9
- package/skills/send-response/SKILL.md +51 -37
- package/skills/store-file/SKILL.md +8 -3
- package/skills/upload-file/SKILL.md +9 -7
- package/skills/use-app-context/SKILL.md +2 -2
- package/skills/use-localization/SKILL.md +6 -2
- package/skills/use-repository/SKILL.md +2 -2
- package/skills/use-request-locals/SKILL.md +3 -3
- package/skills/validate-input/SKILL.md +2 -2
- package/skills/warlock-conventions/SKILL.md +2 -2
- package/skills/wire-socket/SKILL.md +2 -2
- package/skills/write-cli-command/SKILL.md +4 -1
- package/skills/write-middleware/SKILL.md +13 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-driver.mjs","names":[],"sources":["../../../../../../../../core/src/storage/drivers/local-driver.ts"],"sourcesContent":["import {\n directoryExistsAsync,\n ensureDirectoryAsync,\n fileExistsAsync,\n removeDirectoryAsync,\n unlinkAsync,\n} from \"@warlock.js/fs\";\nimport { ltrim } from \"@mongez/reinforcements\";\nimport crypto from \"crypto\";\nimport { createReadStream, createWriteStream } from \"fs\";\nimport { copyFile, readFile, readdir, rename, stat, writeFile } from \"fs/promises\";\nimport { dirname, join, resolve } from \"path\";\nimport type { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { UploadedFile } from \"../../http\";\nimport { storagePath } from \"../../utils/paths\";\nimport { url } from \"../../utils/urls\";\nimport { storageDriverContext } from \"../context/storage-driver-context\";\nimport { resolveWithinRoot } from \"../utils/contain-path\";\nimport type {\n DeleteManyResult,\n ListOptions,\n LocalStorageDriverOptions,\n PutOptions,\n StorageDriverContract,\n StorageDriverType,\n StorageFileData,\n StorageFileInfo,\n TemporaryTokenPayload,\n TemporaryTokenValidation,\n} from \"../types\";\nimport { getMimeType } from \"../utils/mime\";\n\n/**\n * Local filesystem storage driver\n *\n * Stores files on the local filesystem with support for:\n * - File operations (put, get, delete, copy, move)\n * - Stream operations for large files\n * - Batch operations\n * - Signed temporary URLs\n */\nexport class LocalDriver implements StorageDriverContract {\n /**\n * Driver name\n */\n public readonly name: StorageDriverType = \"local\";\n\n /**\n * Root path for storage\n */\n protected root: string;\n\n /**\n * URL prefix for file URLs\n */\n protected urlPrefix: string = \"\";\n\n /**\n * URL prefix for temporary file URLs\n */\n protected temporaryUrlPrefix: string;\n\n /**\n * Secret key for signing temporary URLs\n */\n protected signatureKey?: string;\n\n /**\n * Cached Storage File Metadata\n */\n protected _metadata = new Map<string, StorageFileInfo>();\n\n public constructor(public options: LocalStorageDriverOptions = {}) {\n // Resolve the root to an absolute, normalized path up front so the\n // path-traversal containment check (resolveWithinRoot) has a stable\n // anchor to compare resolved locations against.\n this.root = resolve(options.root ?? storagePath());\n this.urlPrefix = options.urlPrefix ?? \"\";\n this.temporaryUrlPrefix = options.temporaryUrlPrefix ?? \"/temp-files\";\n this.signatureKey = options.signatureKey;\n }\n\n // ============================================================\n // Prefix Operations\n // ============================================================\n\n /**\n * Apply prefix to location path\n *\n * Priority: context prefix > driver options prefix > no prefix\n * This allows multi-tenant scenarios where context overrides driver config.\n *\n * @param location - Original location path\n * @returns Location with prefix applied if one exists\n */\n public applyPrefix(location: string): string {\n // Check context prefix first (highest priority)\n const contextPrefix = storageDriverContext.getPrefix();\n const prefix = contextPrefix || this.options.prefix;\n\n if (!prefix) {\n return location;\n }\n\n const cleanPrefix = prefix.replace(/\\/+$/, \"\");\n const cleanLocation = location.replace(/^\\/+/, \"\");\n\n // Avoid double-prefixing\n if (cleanLocation.startsWith(cleanPrefix + \"/\") || cleanLocation === cleanPrefix) {\n return cleanLocation;\n }\n\n return `${cleanPrefix}/${cleanLocation}`;\n }\n\n // ============================================================\n // Core File Operations\n // ============================================================\n\n /**\n * Put file to local storage\n */\n public async put(\n file: Buffer | string | UploadedFile,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFileData> {\n const absolutePath = this.getAbsolutePath(location);\n\n await ensureDirectoryAsync(dirname(absolutePath));\n\n const fileBuffer = await this.toBuffer(file);\n const hash = this.calculateHash(fileBuffer);\n\n await writeFile(absolutePath, new Uint8Array(fileBuffer));\n\n // Invalidate any stale cached metadata for this location.\n this._metadata.delete(location);\n\n const stats = await stat(absolutePath);\n const mimeType = options?.mimeType || this.guessMimeType(location);\n\n return {\n path: location,\n url: this.url(location),\n size: stats.size,\n hash,\n mimeType,\n driver: this.name,\n };\n }\n\n /**\n * Put file from a readable stream (for large files)\n */\n public async putStream(\n stream: Readable,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFileData> {\n const absolutePath = this.getAbsolutePath(location);\n\n await ensureDirectoryAsync(dirname(absolutePath));\n\n // Create write stream and pipe\n const writeStream = createWriteStream(absolutePath);\n await pipeline(stream, writeStream);\n\n // Invalidate any stale cached metadata for this location.\n this._metadata.delete(location);\n\n // Calculate hash and get stats\n const fileBuffer = await readFile(absolutePath);\n const hash = this.calculateHash(fileBuffer);\n const stats = await stat(absolutePath);\n const mimeType = options?.mimeType || this.guessMimeType(location);\n\n return {\n path: location,\n url: this.url(location),\n size: stats.size,\n hash,\n mimeType,\n driver: this.name,\n };\n }\n\n /**\n * Get file contents as Buffer\n */\n public async get(location: string): Promise<Buffer> {\n const absolutePath = this.getAbsolutePath(location);\n\n if (!(await fileExistsAsync(absolutePath))) {\n throw new Error(`File not found: ${location}`);\n }\n\n return readFile(absolutePath);\n }\n\n /**\n * Get file as a readable stream (for large files)\n */\n public async getStream(location: string): Promise<Readable> {\n const absolutePath = this.getAbsolutePath(location);\n\n if (!(await fileExistsAsync(absolutePath))) {\n throw new Error(`File not found: ${location}`);\n }\n\n return createReadStream(absolutePath);\n }\n\n /**\n * Delete a file\n */\n public async delete(location: string): Promise<boolean> {\n const absolutePath = this.getAbsolutePath(location);\n\n if (!(await fileExistsAsync(absolutePath))) {\n return false;\n }\n\n await unlinkAsync(absolutePath);\n\n // Invalidate any stale cached metadata for this location.\n this._metadata.delete(location);\n\n return true;\n }\n\n /**\n * Delete multiple files at once\n */\n public async deleteMany(locations: string[]): Promise<DeleteManyResult[]> {\n const results: DeleteManyResult[] = [];\n\n for (const location of locations) {\n try {\n const deleted = await this.delete(location);\n results.push({ location, deleted });\n } catch (error) {\n results.push({\n location,\n deleted: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n }\n }\n\n return results;\n }\n\n /**\n * Delete directory\n *\n * The directory path is resolved through {@link getAbsolutePath} so it is\n * contained within the storage root — the raw, caller-supplied argument is\n * never handed to the filesystem (preventing `../` traversal deletes).\n */\n public async deleteDirectory(directoryPath: string) {\n const absolutePath = this.getAbsolutePath(directoryPath);\n\n await removeDirectoryAsync(absolutePath);\n\n return true;\n }\n\n /**\n * Check if file exists\n */\n public async exists(location: string): Promise<boolean> {\n const absolutePath = this.getAbsolutePath(location);\n return Boolean(await fileExistsAsync(absolutePath));\n }\n\n // ============================================================\n // URL Operations\n // ============================================================\n\n /**\n * Get public URL for file\n */\n public url(location: string): string {\n return url(this.urlPrefix + \"/\" + ltrim(location, \"/\"));\n }\n\n /**\n * Get a temporary signed URL that expires\n * Returns a clean URL with encoded token: {temporaryUrlPrefix}/{token}\n *\n * @param location - File path\n * @param expiresIn - Seconds until expiration (default: 3600)\n */\n public async temporaryUrl(location: string, expiresIn = 3600): Promise<string> {\n if (!this.signatureKey) {\n throw new Error(\n \"Temporary URLs require a signatureKey in LocalDriver options. \" +\n \"Configure storage.drivers.local.signatureKey in your config.\",\n );\n }\n\n const token = this.encodeTemporaryToken(location, expiresIn);\n return `${this.temporaryUrlPrefix}/${token}`;\n }\n\n /**\n * Encode a temporary token containing path, expiry, and signature\n *\n * @param location - File path\n * @param expiresIn - Seconds until expiration\n */\n public encodeTemporaryToken(location: string, expiresIn: number): string {\n if (!this.signatureKey) {\n throw new Error(\"Temporary tokens require a signatureKey\");\n }\n\n const exp = Math.floor(Date.now() / 1000) + expiresIn;\n const sig = crypto\n .createHmac(\"sha256\", this.signatureKey)\n .update(`${location}:${exp}`)\n .digest(\"hex\");\n\n const payload: TemporaryTokenPayload = { path: location, exp, sig };\n const json = JSON.stringify(payload);\n\n // Use base64url encoding (URL-safe base64)\n return Buffer.from(json).toString(\"base64url\");\n }\n\n /**\n * Validate a temporary URL token\n * Returns a result object with validation status, file info, and convenience methods\n *\n * @param token - The token from the URL\n */\n public async validateTemporaryToken(token: string): Promise<TemporaryTokenValidation> {\n // Check signature key\n if (!this.signatureKey) {\n return { valid: false, error: \"missing_key\" };\n }\n\n // Decode token\n let payload: TemporaryTokenPayload;\n try {\n const json = Buffer.from(token, \"base64url\").toString(\"utf-8\");\n payload = JSON.parse(json);\n } catch {\n return { valid: false, error: \"invalid_token\" };\n }\n\n // Validate payload structure\n if (!payload.path || !payload.exp || !payload.sig) {\n return { valid: false, error: \"invalid_token\" };\n }\n\n // Check expiration\n const now = Math.floor(Date.now() / 1000);\n if (payload.exp < now) {\n return { valid: false, error: \"expired\" };\n }\n\n // Verify signature\n const expectedSig = crypto\n .createHmac(\"sha256\", this.signatureKey)\n .update(`${payload.path}:${payload.exp}`)\n .digest(\"hex\");\n\n const sigBuffer = Buffer.from(payload.sig, \"hex\");\n const expectedBuffer = Buffer.from(expectedSig, \"hex\");\n\n if (sigBuffer.length !== expectedBuffer.length) {\n return { valid: false, error: \"invalid_signature\" };\n }\n\n const isValidSig = crypto.timingSafeEqual(\n new Uint8Array(sigBuffer),\n new Uint8Array(expectedBuffer),\n );\n\n if (!isValidSig) {\n return { valid: false, error: \"invalid_signature\" };\n }\n\n // Check file exists\n const absolutePath = this.getAbsolutePath(payload.path);\n if (!(await fileExistsAsync(absolutePath))) {\n return { valid: false, error: \"file_not_found\" };\n }\n\n // Build successful result with convenience methods\n const result: TemporaryTokenValidation = {\n valid: true,\n path: payload.path,\n absolutePath,\n expiresAt: new Date(payload.exp * 1000),\n mimeType: this.guessMimeType(payload.path),\n driver: this,\n getFile: () => this.get(payload.path),\n getStream: () => this.getStream(payload.path),\n };\n\n return result;\n }\n\n // ============================================================\n // Metadata Operations\n // ============================================================\n\n /**\n * Get file info/metadata without downloading\n */\n public async metadata(location: string): Promise<StorageFileInfo> {\n if (this._metadata.has(location)) {\n return this._metadata.get(location)!;\n }\n\n const absolutePath = this.getAbsolutePath(location);\n\n if (!(await fileExistsAsync(absolutePath))) {\n throw new Error(`File not found: ${absolutePath}`);\n }\n\n const stats = await stat(absolutePath);\n const name = location.split(\"/\").pop() || \"\";\n\n this._metadata.set(location, {\n path: location,\n name,\n size: stats.size,\n isDirectory: stats.isDirectory(),\n lastModified: stats.mtime,\n mimeType: this.guessMimeType(location),\n });\n\n return this._metadata.get(location)!;\n }\n\n /**\n * Get file size in bytes (shortcut for metadata().size)\n */\n public async size(location: string): Promise<number> {\n const metadata = await this.metadata(location);\n return metadata.size;\n }\n\n // ============================================================\n // File Operations\n // ============================================================\n\n /**\n * Copy file to a new location\n */\n public async copy(from: string, to: string): Promise<StorageFileData> {\n const fromPath = this.getAbsolutePath(from);\n const toPath = this.getAbsolutePath(to);\n\n if (!(await fileExistsAsync(fromPath))) {\n throw new Error(`Source file not found: ${from}`);\n }\n\n await ensureDirectoryAsync(dirname(toPath));\n await copyFile(fromPath, toPath);\n\n // Invalidate any stale cached metadata for the destination.\n this._metadata.delete(to);\n\n const fileBuffer = await readFile(toPath);\n const hash = this.calculateHash(fileBuffer);\n const stats = await stat(toPath);\n\n return {\n path: to,\n url: this.url(to),\n size: stats.size,\n hash,\n mimeType: this.guessMimeType(to),\n driver: this.name,\n };\n }\n\n /**\n * Move file to a new location\n */\n public async move(from: string, to: string): Promise<StorageFileData> {\n const fromPath = this.getAbsolutePath(from);\n const toPath = this.getAbsolutePath(to);\n\n if (!(await fileExistsAsync(fromPath))) {\n throw new Error(`Source file not found: ${from}`);\n }\n\n await ensureDirectoryAsync(dirname(toPath));\n await rename(fromPath, toPath);\n\n // Invalidate any stale cached metadata for both source and destination.\n this._metadata.delete(from);\n this._metadata.delete(to);\n\n const fileBuffer = await readFile(toPath);\n const hash = this.calculateHash(fileBuffer);\n const stats = await stat(toPath);\n\n return {\n path: to,\n url: this.url(to),\n size: stats.size,\n hash,\n mimeType: this.guessMimeType(to),\n driver: this.name,\n };\n }\n\n /**\n * List files in a directory\n */\n public async list(directory: string, options?: ListOptions): Promise<StorageFileInfo[]> {\n const absolutePath = this.getAbsolutePath(directory);\n const files: StorageFileInfo[] = [];\n\n // A listing target is a DIRECTORY, so guard with `directoryExistsAsync`.\n // `fileExistsAsync` resolves `false` for a folder, which would make `list`\n // always return [] for a real, populated directory.\n if (!(await directoryExistsAsync(absolutePath))) {\n return files;\n }\n\n const entries = await readdir(absolutePath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = join(directory, entry.name);\n const entryStats = await stat(this.getAbsolutePath(entryPath));\n\n files.push({\n path: entryPath,\n name: entry.name,\n size: entryStats.size,\n isDirectory: entry.isDirectory(),\n lastModified: entryStats.mtime,\n mimeType: entry.isFile() ? this.guessMimeType(entry.name) : undefined,\n });\n\n // Recursively list subdirectories if requested\n if (options?.recursive && entry.isDirectory()) {\n const subFiles = await this.list(entryPath, options);\n files.push(...subFiles);\n }\n\n // Respect limit\n if (options?.limit && files.length >= options.limit) {\n break;\n }\n }\n\n return files;\n }\n\n // ============================================================\n // Path Operations\n // ============================================================\n\n /**\n * Get absolute filesystem path for a location\n */\n public path(location: string): string {\n return this.getAbsolutePath(location);\n }\n\n /**\n * Get the storage root directory\n */\n public getRoot(): string {\n return this.root;\n }\n\n // ============================================================\n // Utilities\n // ============================================================\n\n /**\n * Get absolute file path\n *\n * Routes through {@link resolveWithinRoot} so a location can never escape\n * the configured storage root via `..` traversal, an absolute path, or a\n * prefix breakout.\n */\n protected getAbsolutePath(location: string): string {\n const prefixedLocation = this.applyPrefix(location);\n return resolveWithinRoot(this.root, prefixedLocation);\n }\n\n /**\n * Convert various input types to Buffer\n */\n protected async toBuffer(file: Buffer | string | UploadedFile): Promise<Buffer> {\n if (Buffer.isBuffer(file)) {\n return file;\n }\n\n if (typeof file === \"string\") {\n return readFile(file);\n }\n\n return file.buffer();\n }\n\n /**\n * Calculate SHA-256 hash\n */\n protected calculateHash(buffer: Buffer): string {\n return crypto.createHash(\"sha256\").update(new Uint8Array(buffer)).digest(\"hex\");\n }\n\n /**\n * Guess MIME type from file extension\n */\n protected guessMimeType(location: string): string {\n return getMimeType(location);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0CA,IAAa,cAAb,MAA0D;CA+B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O,OAAO,WAAW,QAAQ,EAAE,OAAO,IAAI,WAAW,MAAM,CAAC,EAAE,OAAO,KAAK;CAChF;;;;CAKA,AAAU,cAAc,UAA0B;EAChD,OAAO,YAAY,QAAQ;CAC7B;AACF"}
|
|
1
|
+
{"version":3,"file":"local-driver.mjs","names":[],"sources":["../../../../../../../../core/src/storage/drivers/local-driver.ts"],"sourcesContent":["import {\n directoryExistsAsync,\n ensureDirectoryAsync,\n fileExistsAsync,\n removeDirectoryAsync,\n unlinkAsync,\n} from \"@warlock.js/fs\";\nimport { ltrim } from \"@mongez/reinforcements\";\nimport crypto from \"crypto\";\nimport { createReadStream, createWriteStream } from \"fs\";\nimport { copyFile, readFile, readdir, rename, stat, writeFile } from \"fs/promises\";\nimport { dirname, join, resolve } from \"path\";\nimport type { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { UploadedFile } from \"../../http\";\nimport { storagePath } from \"../../utils/paths\";\nimport { url } from \"../../utils/urls\";\nimport { storageDriverContext } from \"../context/storage-driver-context\";\nimport { resolveWithinRoot } from \"../utils/contain-path\";\nimport type {\n DeleteManyResult,\n ListOptions,\n LocalStorageDriverOptions,\n PutOptions,\n StorageDriverContract,\n StorageDriverType,\n StorageFileData,\n StorageFileInfo,\n TemporaryTokenPayload,\n TemporaryTokenValidation,\n} from \"../types\";\nimport { getMimeType } from \"../utils/mime\";\n\n/**\n * Local filesystem storage driver\n *\n * Stores files on the local filesystem with support for:\n * - File operations (put, get, delete, copy, move)\n * - Stream operations for large files\n * - Batch operations\n * - Signed temporary URLs\n */\nexport class LocalDriver implements StorageDriverContract {\n /**\n * Driver name\n */\n public readonly name: StorageDriverType = \"local\";\n\n /**\n * Root path for storage\n */\n protected root: string;\n\n /**\n * URL prefix for file URLs\n */\n protected urlPrefix: string = \"\";\n\n /**\n * URL prefix for temporary file URLs\n */\n protected temporaryUrlPrefix: string;\n\n /**\n * Secret key for signing temporary URLs\n */\n protected signatureKey?: string;\n\n /**\n * Cached Storage File Metadata\n */\n protected _metadata = new Map<string, StorageFileInfo>();\n\n public constructor(public options: LocalStorageDriverOptions = {}) {\n // Resolve the root to an absolute, normalized path up front so the\n // path-traversal containment check (resolveWithinRoot) has a stable\n // anchor to compare resolved locations against.\n this.root = resolve(options.root ?? storagePath());\n this.urlPrefix = options.urlPrefix ?? \"\";\n this.temporaryUrlPrefix = options.temporaryUrlPrefix ?? \"/temp-files\";\n this.signatureKey = options.signatureKey;\n }\n\n // ============================================================\n // Prefix Operations\n // ============================================================\n\n /**\n * Apply prefix to location path\n *\n * Priority: context prefix > driver options prefix > no prefix\n * This allows multi-tenant scenarios where context overrides driver config.\n *\n * @param location - Original location path\n * @returns Location with prefix applied if one exists\n */\n public applyPrefix(location: string): string {\n // Check context prefix first (highest priority)\n const contextPrefix = storageDriverContext.getPrefix();\n const prefix = contextPrefix || this.options.prefix;\n\n if (!prefix) {\n return location;\n }\n\n const cleanPrefix = prefix.replace(/\\/+$/, \"\");\n const cleanLocation = location.replace(/^\\/+/, \"\");\n\n // Avoid double-prefixing\n if (cleanLocation.startsWith(cleanPrefix + \"/\") || cleanLocation === cleanPrefix) {\n return cleanLocation;\n }\n\n return `${cleanPrefix}/${cleanLocation}`;\n }\n\n // ============================================================\n // Core File Operations\n // ============================================================\n\n /**\n * Put file to local storage\n */\n public async put(\n file: Buffer | string | UploadedFile,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFileData> {\n const absolutePath = this.getAbsolutePath(location);\n\n await ensureDirectoryAsync(dirname(absolutePath));\n\n const fileBuffer = await this.toBuffer(file);\n const hash = this.calculateHash(fileBuffer);\n\n await writeFile(absolutePath, new Uint8Array(fileBuffer));\n\n // Invalidate any stale cached metadata for this location.\n this._metadata.delete(location);\n\n const stats = await stat(absolutePath);\n const mimeType = options?.mimeType || this.guessMimeType(location);\n\n return {\n path: location,\n url: this.url(location),\n size: stats.size,\n hash,\n mimeType,\n driver: this.name,\n };\n }\n\n /**\n * Put file from a readable stream (for large files)\n */\n public async putStream(\n stream: Readable,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFileData> {\n const absolutePath = this.getAbsolutePath(location);\n\n await ensureDirectoryAsync(dirname(absolutePath));\n\n // Create write stream and pipe\n const writeStream = createWriteStream(absolutePath);\n await pipeline(stream, writeStream);\n\n // Invalidate any stale cached metadata for this location.\n this._metadata.delete(location);\n\n // Calculate hash and get stats\n const fileBuffer = await readFile(absolutePath);\n const hash = this.calculateHash(fileBuffer);\n const stats = await stat(absolutePath);\n const mimeType = options?.mimeType || this.guessMimeType(location);\n\n return {\n path: location,\n url: this.url(location),\n size: stats.size,\n hash,\n mimeType,\n driver: this.name,\n };\n }\n\n /**\n * Get file contents as Buffer\n */\n public async get(location: string): Promise<Buffer> {\n const absolutePath = this.getAbsolutePath(location);\n\n if (!(await fileExistsAsync(absolutePath))) {\n throw new Error(`File not found: ${location}`);\n }\n\n return readFile(absolutePath);\n }\n\n /**\n * Get file as a readable stream (for large files)\n */\n public async getStream(location: string): Promise<Readable> {\n const absolutePath = this.getAbsolutePath(location);\n\n if (!(await fileExistsAsync(absolutePath))) {\n throw new Error(`File not found: ${location}`);\n }\n\n return createReadStream(absolutePath);\n }\n\n /**\n * Delete a file\n */\n public async delete(location: string): Promise<boolean> {\n const absolutePath = this.getAbsolutePath(location);\n\n if (!(await fileExistsAsync(absolutePath))) {\n return false;\n }\n\n await unlinkAsync(absolutePath);\n\n // Invalidate any stale cached metadata for this location.\n this._metadata.delete(location);\n\n return true;\n }\n\n /**\n * Delete multiple files at once\n */\n public async deleteMany(locations: string[]): Promise<DeleteManyResult[]> {\n const results: DeleteManyResult[] = [];\n\n for (const location of locations) {\n try {\n const deleted = await this.delete(location);\n results.push({ location, deleted });\n } catch (error) {\n results.push({\n location,\n deleted: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n }\n }\n\n return results;\n }\n\n /**\n * Delete directory\n *\n * The directory path is resolved through {@link getAbsolutePath} so it is\n * contained within the storage root — the raw, caller-supplied argument is\n * never handed to the filesystem (preventing `../` traversal deletes).\n */\n public async deleteDirectory(directoryPath: string) {\n const absolutePath = this.getAbsolutePath(directoryPath);\n\n await removeDirectoryAsync(absolutePath);\n\n return true;\n }\n\n /**\n * Check if file exists\n */\n public async exists(location: string): Promise<boolean> {\n const absolutePath = this.getAbsolutePath(location);\n return Boolean(await fileExistsAsync(absolutePath));\n }\n\n // ============================================================\n // URL Operations\n // ============================================================\n\n /**\n * Get public URL for file\n */\n public url(location: string): string {\n return url(this.urlPrefix + \"/\" + ltrim(location, \"/\"));\n }\n\n /**\n * Get a temporary signed URL that expires\n * Returns a clean URL with encoded token: {temporaryUrlPrefix}/{token}\n *\n * @param location - File path\n * @param expiresIn - Seconds until expiration (default: 3600)\n */\n public async temporaryUrl(location: string, expiresIn = 3600): Promise<string> {\n if (!this.signatureKey) {\n throw new Error(\n \"Temporary URLs require a signatureKey in LocalDriver options. \" +\n \"Configure storage.drivers.local.signatureKey in your config.\",\n );\n }\n\n const token = this.encodeTemporaryToken(location, expiresIn);\n return `${this.temporaryUrlPrefix}/${token}`;\n }\n\n /**\n * Encode a temporary token containing path, expiry, and signature\n *\n * @param location - File path\n * @param expiresIn - Seconds until expiration\n */\n public encodeTemporaryToken(location: string, expiresIn: number): string {\n if (!this.signatureKey) {\n throw new Error(\"Temporary tokens require a signatureKey\");\n }\n\n const exp = Math.floor(Date.now() / 1000) + expiresIn;\n const sig = crypto\n .createHmac(\"sha256\", this.signatureKey)\n .update(`${location}:${exp}`)\n .digest(\"hex\");\n\n const payload: TemporaryTokenPayload = { path: location, exp, sig };\n const json = JSON.stringify(payload);\n\n // Use base64url encoding (URL-safe base64)\n return Buffer.from(json).toString(\"base64url\");\n }\n\n /**\n * Validate a temporary URL token\n * Returns a result object with validation status, file info, and convenience methods\n *\n * @param token - The token from the URL\n */\n public async validateTemporaryToken(token: string): Promise<TemporaryTokenValidation> {\n // Check signature key\n if (!this.signatureKey) {\n return { valid: false, error: \"missing_key\" };\n }\n\n // Decode token\n let payload: TemporaryTokenPayload;\n try {\n const json = Buffer.from(token, \"base64url\").toString(\"utf-8\");\n payload = JSON.parse(json);\n } catch {\n return { valid: false, error: \"invalid_token\" };\n }\n\n // Validate payload structure\n if (!payload.path || !payload.exp || !payload.sig) {\n return { valid: false, error: \"invalid_token\" };\n }\n\n // Check expiration\n const now = Math.floor(Date.now() / 1000);\n if (payload.exp < now) {\n return { valid: false, error: \"expired\" };\n }\n\n // Verify signature\n const expectedSig = crypto\n .createHmac(\"sha256\", this.signatureKey)\n .update(`${payload.path}:${payload.exp}`)\n .digest(\"hex\");\n\n const sigBuffer = Buffer.from(payload.sig, \"hex\");\n const expectedBuffer = Buffer.from(expectedSig, \"hex\");\n\n if (sigBuffer.length !== expectedBuffer.length) {\n return { valid: false, error: \"invalid_signature\" };\n }\n\n const isValidSig = crypto.timingSafeEqual(\n new Uint8Array(sigBuffer),\n new Uint8Array(expectedBuffer),\n );\n\n if (!isValidSig) {\n return { valid: false, error: \"invalid_signature\" };\n }\n\n // Check file exists\n const absolutePath = this.getAbsolutePath(payload.path);\n if (!(await fileExistsAsync(absolutePath))) {\n return { valid: false, error: \"file_not_found\" };\n }\n\n // Build successful result with convenience methods\n const result: TemporaryTokenValidation = {\n valid: true,\n path: payload.path,\n absolutePath,\n expiresAt: new Date(payload.exp * 1000),\n mimeType: this.guessMimeType(payload.path),\n driver: this,\n getFile: () => this.get(payload.path),\n getStream: () => this.getStream(payload.path),\n };\n\n return result;\n }\n\n // ============================================================\n // Metadata Operations\n // ============================================================\n\n /**\n * Get file info/metadata without downloading\n */\n public async metadata(location: string): Promise<StorageFileInfo> {\n if (this._metadata.has(location)) {\n return this._metadata.get(location)!;\n }\n\n const absolutePath = this.getAbsolutePath(location);\n\n if (!(await fileExistsAsync(absolutePath))) {\n throw new Error(`File not found: ${absolutePath}`);\n }\n\n const stats = await stat(absolutePath);\n const name = location.split(\"/\").pop() || \"\";\n\n this._metadata.set(location, {\n path: location,\n name,\n size: stats.size,\n isDirectory: stats.isDirectory(),\n lastModified: stats.mtime,\n mimeType: this.guessMimeType(location),\n });\n\n return this._metadata.get(location)!;\n }\n\n /**\n * Get file size in bytes (shortcut for metadata().size)\n */\n public async size(location: string): Promise<number> {\n const metadata = await this.metadata(location);\n return metadata.size;\n }\n\n // ============================================================\n // File Operations\n // ============================================================\n\n /**\n * Copy file to a new location\n */\n public async copy(from: string, to: string): Promise<StorageFileData> {\n const fromPath = this.getAbsolutePath(from);\n const toPath = this.getAbsolutePath(to);\n\n if (!(await fileExistsAsync(fromPath))) {\n throw new Error(`Source file not found: ${from}`);\n }\n\n await ensureDirectoryAsync(dirname(toPath));\n await copyFile(fromPath, toPath);\n\n // Invalidate any stale cached metadata for the destination.\n this._metadata.delete(to);\n\n const fileBuffer = await readFile(toPath);\n const hash = this.calculateHash(fileBuffer);\n const stats = await stat(toPath);\n\n return {\n path: to,\n url: this.url(to),\n size: stats.size,\n hash,\n mimeType: this.guessMimeType(to),\n driver: this.name,\n };\n }\n\n /**\n * Move file to a new location\n */\n public async move(from: string, to: string): Promise<StorageFileData> {\n const fromPath = this.getAbsolutePath(from);\n const toPath = this.getAbsolutePath(to);\n\n if (!(await fileExistsAsync(fromPath))) {\n throw new Error(`Source file not found: ${from}`);\n }\n\n await ensureDirectoryAsync(dirname(toPath));\n await rename(fromPath, toPath);\n\n // Invalidate any stale cached metadata for both source and destination.\n this._metadata.delete(from);\n this._metadata.delete(to);\n\n const fileBuffer = await readFile(toPath);\n const hash = this.calculateHash(fileBuffer);\n const stats = await stat(toPath);\n\n return {\n path: to,\n url: this.url(to),\n size: stats.size,\n hash,\n mimeType: this.guessMimeType(to),\n driver: this.name,\n };\n }\n\n /**\n * List files in a directory\n */\n public async list(directory: string, options?: ListOptions): Promise<StorageFileInfo[]> {\n const absolutePath = this.getAbsolutePath(directory);\n const files: StorageFileInfo[] = [];\n\n // A listing target is a DIRECTORY, so guard with `directoryExistsAsync`.\n // `fileExistsAsync` resolves `false` for a folder, which would make `list`\n // always return [] for a real, populated directory.\n if (!(await directoryExistsAsync(absolutePath))) {\n return files;\n }\n\n const entries = await readdir(absolutePath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = join(directory, entry.name);\n const entryStats = await stat(this.getAbsolutePath(entryPath));\n\n files.push({\n path: entryPath,\n name: entry.name,\n size: entryStats.size,\n isDirectory: entry.isDirectory(),\n lastModified: entryStats.mtime,\n mimeType: entry.isFile() ? this.guessMimeType(entry.name) : undefined,\n });\n\n // Recursively list subdirectories if requested\n if (options?.recursive && entry.isDirectory()) {\n const subFiles = await this.list(entryPath, options);\n files.push(...subFiles);\n }\n\n // Respect limit\n if (options?.limit && files.length >= options.limit) {\n break;\n }\n }\n\n return files;\n }\n\n // ============================================================\n // Path Operations\n // ============================================================\n\n /**\n * Get absolute filesystem path for a location\n */\n public path(location: string): string {\n return this.getAbsolutePath(location);\n }\n\n /**\n * Get the storage root directory\n */\n public getRoot(): string {\n return this.root;\n }\n\n // ============================================================\n // Utilities\n // ============================================================\n\n /**\n * Get absolute file path\n *\n * Routes through {@link resolveWithinRoot} so a location can never escape\n * the configured storage root via `..` traversal, an absolute path, or a\n * prefix breakout.\n */\n protected getAbsolutePath(location: string): string {\n const prefixedLocation = this.applyPrefix(location);\n return resolveWithinRoot(this.root, prefixedLocation);\n }\n\n /**\n * Convert various input types to Buffer\n */\n protected async toBuffer(file: Buffer | string | UploadedFile): Promise<Buffer> {\n if (Buffer.isBuffer(file)) {\n return file;\n }\n\n if (typeof file === \"string\") {\n return readFile(file);\n }\n\n return file.buffer();\n }\n\n /**\n * Calculate SHA-256 hash\n */\n protected calculateHash(buffer: Buffer): string {\n return crypto.createHash(\"sha256\").update(new Uint8Array(buffer)).digest(\"hex\");\n }\n\n /**\n * Guess MIME type from file extension\n */\n protected guessMimeType(location: string): string {\n return getMimeType(location);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0CA,IAAa,cAAb,MAA0D;CA+BxD,AAAO,YAAY,AAAO,UAAqC,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,QAAwB;EAC9C,OAAO,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,WAAW,MAAM,CAAC,CAAC,CAAC,OAAO,KAAK;CAChF;;;;CAKA,AAAU,cAAc,UAA0B;EAChD,OAAO,YAAY,QAAQ;CAC7B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"r2-driver.d.mts","names":[],"sources":["../../../../../../../../core/src/storage/drivers/r2-driver.ts"],"mappings":";;;;;;AA0BA;;;;;;;;;;;AAwB6B;;;;;;;;;cAxBhB,QAAA,SAAiB,WAAW,CAAC,sBAAA;;;;WAIxB,IAAA;;;;;;YAON,WAAA
|
|
1
|
+
{"version":3,"file":"r2-driver.d.mts","names":[],"sources":["../../../../../../../../core/src/storage/drivers/r2-driver.ts"],"mappings":";;;;;;AA0BA;;;;;;;;;;;AAwB6B;;;;;;;;;cAxBhB,QAAA,SAAiB,WAAW,CAAC,sBAAA;;;;WAIxB,IAAA;;;;;;YAON,WAAA;;;;;;;;;;EAaH,GAAA,CAAI,QAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scoped-storage.d.mts","names":[],"sources":["../../../../../../../core/src/storage/scoped-storage.ts"],"mappings":";;;;;;;;;AA0CA;;;;;;;;;;;;;;;;;;cAAa,aAAA,YAAyB,qBAAA;EAkJzB;;;;EAAA,UA7ID,OAAA,EAAS,qBAAA;EA0NyB;;;;;cAnNzB,MAAA,EAAQ,qBAAA;EAsR2B;;;;;EAAA,IAzQ3C,IAAA,
|
|
1
|
+
{"version":3,"file":"scoped-storage.d.mts","names":[],"sources":["../../../../../../../core/src/storage/scoped-storage.ts"],"mappings":";;;;;;;;;AA0CA;;;;;;;;;;;;;;;;;;cAAa,aAAA,YAAyB,qBAAA;EAkJzB;;;;EAAA,UA7ID,OAAA,EAAS,qBAAA;EA0NyB;;;;;cAnNzB,MAAA,EAAQ,qBAAA;EAsR2B;;;;;EAAA,IAzQ3C,IAAA,IA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fs"],"sources":["../../../../../../../core/src/storage/scoped-storage.ts"],"sourcesContent":["import { fileExistsAsync } from \"@warlock.js/fs\";\nimport { createReadStream } from \"fs\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type { Readable } from \"stream\";\nimport type { UploadedFile } from \"../http\";\nimport { StorageFile } from \"./storage-file\";\nimport type {\n DeleteManyResult,\n ListOptions,\n PutDirectoryOptions,\n PutDirectoryResult,\n PutFromUrlOptions,\n PutOptions,\n ScopedStorageContract,\n StorageDriverContract,\n StorageDriverType,\n StorageFileInfo,\n} from \"./types\";\nimport { safeFetchToBuffer } from \"./utils/safe-fetch\";\n\n/**\n * ScopedStorage - Base class for storage operations\n *\n * Wraps a storage driver and provides a consistent, developer-friendly API\n * that returns `StorageFile` instances instead of raw data objects.\n *\n * This class serves as the base for both direct driver usage and the\n * full `Storage` manager class.\n *\n * @example\n * ```typescript\n * // Using via storage.use()\n * const s3Storage = storage.use(\"s3\");\n * const file = await s3Storage.put(buffer, \"images/photo.jpg\");\n *\n * // file is a StorageFile instance with rich API\n * console.log(file.name); // \"photo.jpg\"\n * console.log(file.url); // \"https://...\"\n * await file.copy(\"backup/photo.jpg\");\n * ```\n */\nexport class ScopedStorage implements ScopedStorageContract {\n /**\n * The underlying storage driver instance\n * @internal\n */\n protected _driver: StorageDriverContract;\n\n /**\n * Create a new ScopedStorage instance\n *\n * @param driver - The storage driver to wrap\n */\n public constructor(driver: StorageDriverContract) {\n this._driver = driver;\n }\n\n // ============================================================\n // Properties\n // ============================================================\n\n /**\n * Get the driver name\n *\n * @returns The name identifier of the underlying driver (e.g., \"local\", \"s3\", \"r2\")\n */\n public get name(): StorageDriverType {\n return this.activeDriver.name;\n }\n\n /**\n * Get the default driver instance\n *\n * Use this for advanced operations that require direct driver access.\n *\n * @returns The raw storage driver\n */\n public get defaultDriver(): StorageDriverContract {\n return this._driver;\n }\n\n /**\n * Get the currently active driver\n *\n * Returns the driver being used for storage operations.\n * Can be overridden in subclasses for dynamic driver resolution (e.g., multi-tenant contexts).\n *\n * @returns The active storage driver\n */\n public get activeDriver(): StorageDriverContract {\n return this._driver;\n }\n\n // ============================================================\n // File Operations\n // ============================================================\n\n /**\n * Store a file in storage\n *\n * Accepts multiple input types and stores the file at the specified location.\n * Returns a `StorageFile` instance for further operations.\n *\n * @param file - File content as Buffer, string path, UploadedFile, or Readable stream\n * @param location - Destination path in storage (e.g., \"uploads/images/photo.jpg\")\n * @param options - Optional storage options\n * @returns StorageFile instance with cached metadata\n *\n * @example\n * ```typescript\n * // From buffer\n * const file = await storage.put(buffer, \"documents/report.pdf\");\n *\n * // From uploaded file\n * const file = await storage.put(uploadedFile, \"avatars/user-123.jpg\");\n *\n * // With options\n * const file = await storage.put(buffer, \"images/photo.jpg\", {\n * mimeType: \"image/jpeg\",\n * cacheControl: \"max-age=31536000\"\n * });\n * ```\n */\n public async put(\n file: UploadedFile | Buffer | string | Readable,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFile> {\n const buffer = await this.toBuffer(file);\n const data = await this.activeDriver.put(buffer, location, options);\n return StorageFile.fromData(data, this.activeDriver);\n }\n\n /**\n * Store a file from a readable stream\n *\n * Optimized for large files - streams data directly without full buffering.\n * Ideal for file uploads, remote file fetching, or processing pipelines.\n *\n * @param stream - Readable stream of file content\n * @param location - Destination path in storage\n * @param options - Optional storage options\n * @returns StorageFile instance with cached metadata\n *\n * @example\n * ```typescript\n * import { createReadStream } from \"fs\";\n *\n * const stream = createReadStream(\"./large-video.mp4\");\n * const file = await storage.putStream(stream, \"videos/upload.mp4\");\n * ```\n */\n public async putStream(\n stream: Readable,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFile> {\n const data = await this.activeDriver.putStream(stream, location, options);\n return StorageFile.fromData(data, this.activeDriver);\n }\n\n /**\n * Store a file from a URL\n *\n * Downloads the file from the URL and stores it. The download is\n * SSRF-guarded by default: the URL scheme must be https/http, the host\n * must not resolve to a private / loopback / link-local / cloud-metadata\n * address, the body is capped, and the request times out. Tune or relax\n * via the {@link PutFromUrlOptions} guard fields.\n *\n * @param url - URL to download from\n * @param location - Destination path in storage\n * @param options - Storage + outbound-download guard options\n * @returns StorageFile instance\n *\n * @example\n * ```typescript\n * const file = await storage.putFromUrl(\n * \"https://example.com/image.jpg\",\n * \"images/downloaded.jpg\"\n * );\n * ```\n */\n public async putFromUrl(\n url: string,\n location: string,\n options?: PutFromUrlOptions,\n ): Promise<StorageFile> {\n const { allowPrivateHosts, maxBytes, timeoutMs, allowedSchemes, ...putOptions } =\n options ?? {};\n\n const result = await safeFetchToBuffer(url, {\n allowPrivateHosts,\n maxBytes,\n timeoutMs,\n allowedSchemes,\n });\n\n if (!result.ok) {\n throw new Error(`Failed to fetch file from ${url}: ${result.statusText}`);\n }\n\n if (!result.contentType) {\n throw new Error(`Failed to fetch file from ${url}: missing content-type header`);\n }\n\n const mimeType = putOptions.mimeType || result.contentType;\n\n return this.put(result.buffer, location, { ...putOptions, mimeType });\n }\n\n /**\n * Store a file from base64 data URL\n *\n * @param dataUrl - Data URL (data:image/png;base64,iVBORw0KG...)\n * @param location - Destination path in storage\n * @param options - Optional storage options\n * @returns StorageFile instance\n *\n * @example\n * ```typescript\n * const file = await storage.putFromBase64(\n * \"data:image/png;base64,iVBORw0KGgoAAAANS...\",\n * \"images/upload.png\"\n * );\n * ```\n */\n public async putFromBase64(\n dataUrl: string,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFile> {\n // Parse data URL: data:image/png;base64,iVBORw0KG...\n const matches = dataUrl.match(/^data:([^;]+);base64,(.+)$/);\n\n if (!matches) {\n throw new Error(\"Invalid base64 data URL format. Expected: data:mime/type;base64,<data>\");\n }\n\n const [, mimeType, base64Data] = matches;\n const buffer = Buffer.from(base64Data, \"base64\");\n\n return this.put(buffer, location, {\n ...options,\n mimeType: options?.mimeType || mimeType,\n });\n }\n\n /**\n * Retrieve file contents as a Buffer\n *\n * Downloads the entire file into memory. For large files,\n * consider using `getStream()` instead.\n *\n * @param location - Path to the file in storage\n * @returns Buffer containing file contents\n * @throws Error if file not found\n *\n * @example\n * ```typescript\n * const buffer = await storage.get(\"documents/report.pdf\");\n * const content = buffer.toString(\"utf-8\");\n * ```\n */\n public async get(location: string): Promise<Buffer> {\n return this.activeDriver.get(location);\n }\n\n /**\n * Retrieve file contents as a readable stream\n *\n * Streams file data without loading entire file into memory.\n * Ideal for large files or when piping to a response.\n *\n * @param location - Path to the file in storage\n * @returns Readable stream of file contents\n * @throws Error if file not found\n *\n * @example\n * ```typescript\n * const stream = await storage.getStream(\"videos/large.mp4\");\n * stream.pipe(response.raw);\n * ```\n */\n public async getStream(location: string): Promise<Readable> {\n return this.activeDriver.getStream(location);\n }\n\n /**\n * Delete a file from storage\n *\n * @param location - Path to the file, or a StorageFile instance\n * @returns `true` if deleted, `false` if file not found\n *\n * @example\n * ```typescript\n * // By path\n * await storage.delete(\"temp/old-file.txt\");\n *\n * // From StorageFile instance\n * const file = await storage.put(buffer, \"temp/file.txt\");\n * await storage.delete(file);\n * ```\n */\n public async delete(location: string | StorageFile): Promise<boolean> {\n const path = typeof location === \"string\" ? location : location.path;\n return this.activeDriver.delete(path);\n }\n\n /**\n * Delete multiple files at once\n *\n * Performs batch deletion for efficiency. Returns results for each file\n * including success/failure status.\n *\n * @param locations - Array of file paths to delete\n * @returns Array of delete results with status for each file\n *\n * @example\n * ```typescript\n * const results = await storage.deleteMany([\n * \"temp/file1.txt\",\n * \"temp/file2.txt\",\n * \"temp/file3.txt\"\n * ]);\n *\n * for (const result of results) {\n * console.log(`${result.location}: ${result.deleted ? \"deleted\" : result.error}`);\n * }\n * ```\n */\n public async deleteMany(locations: string[]): Promise<DeleteManyResult[]> {\n return this.activeDriver.deleteMany(locations);\n }\n\n /**\n * Delete a directory\n *\n * @param directoryPath - Path to the directory\n */\n public async deleteDirectory(directoryPath: string): Promise<boolean> {\n return await this.activeDriver.deleteDirectory(directoryPath);\n }\n\n /**\n * Check if a file exists in storage\n *\n * @param location - Path to check\n * @returns `true` if file exists, `false` otherwise\n *\n * @example\n * ```typescript\n * if (await storage.exists(\"config/settings.json\")) {\n * const config = await storage.get(\"config/settings.json\");\n * }\n * ```\n */\n public async exists(location: string): Promise<boolean> {\n return this.activeDriver.exists(location);\n }\n\n /**\n * Copy a file to a new location\n *\n * Creates a copy of the file at the destination path.\n * The original file remains unchanged.\n *\n * @param from - Source path or StorageFile instance\n * @param to - Destination path\n * @returns StorageFile instance at the new location\n *\n * @example\n * ```typescript\n * // Copy by path\n * const backup = await storage.copy(\"documents/report.pdf\", \"backups/report.pdf\");\n *\n * // Copy from StorageFile\n * const original = await storage.file(\"documents/report.pdf\");\n * const backup = await storage.copy(original, \"backups/report.pdf\");\n * ```\n */\n public async copy(from: string | StorageFile, to: string): Promise<StorageFile> {\n const fromPath = typeof from === \"string\" ? from : from.path;\n const data = await this.activeDriver.copy(fromPath, to);\n return StorageFile.fromData(data, this.activeDriver);\n }\n\n /**\n * Move a file to a new location\n *\n * Moves the file to the destination path. The original file\n * is deleted after successful copy.\n *\n * @param from - Source path or StorageFile instance\n * @param to - Destination path\n * @returns StorageFile instance at the new location\n *\n * @example\n * ```typescript\n * // Move by path\n * const file = await storage.move(\"uploads/temp.jpg\", \"images/photo.jpg\");\n *\n * // Move from StorageFile\n * const temp = await storage.file(\"uploads/temp.jpg\");\n * const final = await storage.move(temp, \"images/photo.jpg\");\n * ```\n */\n public async move(from: string | StorageFile, to: string): Promise<StorageFile> {\n const fromPath = typeof from === \"string\" ? from : from.path;\n const data = await this.activeDriver.move(fromPath, to);\n return StorageFile.fromData(data, this.activeDriver);\n }\n\n /**\n * Copy an entire directory recursively\n *\n * Copies all files from the source directory to the destination directory,\n * preserving the directory structure.\n *\n * @param from - Source directory path\n * @param to - Destination directory path\n * @param options - Optional concurrency control\n * @returns Number of files copied\n *\n * @example\n * ```typescript\n * // Copy entire directory\n * const count = await storage.copyDirectory(\"uploads/temp\", \"uploads/final\");\n * console.log(`Copied ${count} files`);\n *\n * // With concurrency limit\n * const count = await storage.copyDirectory(\"large-dir\", \"backup\", {\n * concurrency: 10\n * });\n * ```\n */\n public async copyDirectory(\n from: string,\n to: string,\n options?: { concurrency?: number },\n ): Promise<number> {\n const concurrency = options?.concurrency || 5;\n\n // List all files recursively\n const files = await this.list(from, { recursive: true });\n const filesToCopy = files.filter((f) => !f.isDirectory);\n\n // Copy files in batches for efficiency\n let copied = 0;\n for (let i = 0; i < filesToCopy.length; i += concurrency) {\n const batch = filesToCopy.slice(i, i + concurrency);\n await Promise.all(\n batch.map(async (file) => {\n // Calculate relative path and new destination\n const relativePath = file.path.substring(from.length).replace(/^\\//, \"\");\n const newPath = `${to}/${relativePath}`;\n await this.copy(file.path, newPath);\n copied++;\n }),\n );\n }\n\n return copied;\n }\n\n /**\n * Move an entire directory recursively\n *\n * Moves all files from the source directory to the destination directory,\n * then deletes the source directory.\n *\n * @param from - Source directory path\n * @param to - Destination directory path\n * @param options - Optional concurrency control\n * @returns Number of files moved\n *\n * @example\n * ```typescript\n * const count = await storage.moveDirectory(\"uploads/temp\", \"uploads/final\");\n * console.log(`Moved ${count} files`);\n * ```\n */\n public async moveDirectory(\n from: string,\n to: string,\n options?: { concurrency?: number },\n ): Promise<number> {\n // Copy all files first\n const count = await this.copyDirectory(from, to, options);\n\n // Delete source directory\n await this.deleteDirectory(from);\n\n return count;\n }\n\n /**\n * Upload a local filesystem directory into storage\n *\n * Recursively walks the local directory, applies an optional filter, then\n * streams each file into storage. Uploads run in concurrent batches for\n * efficiency. Failures are collected — a single failed file never aborts\n * the entire operation (mirrors the contract of `deleteMany`).\n *\n * @param localDirPath - Absolute path of the local directory to upload\n * @param destination - Target prefix in storage (e.g. \"uploads/assets\")\n * @param options - Concurrency, filter, progress callback, put options\n * @returns - { uploaded, failed, total }\n *\n * @example\n * ```typescript\n * const result = await storage.putDirectory(\"./public/assets\", \"cdn/assets\", {\n * concurrency: 10,\n * filter: (_, rel) => !rel.startsWith(\".\"),\n * onProgress: (done, total) => console.log(`${done}/${total}`),\n * });\n *\n * console.log(`Uploaded: ${result.uploaded.length}, Failed: ${result.failed.length}`);\n * ```\n */\n public async putDirectory(\n localDirPath: string,\n destination: string,\n options?: PutDirectoryOptions,\n ): Promise<PutDirectoryResult> {\n const concurrency = options?.concurrency ?? 5;\n\n // Collect all local file paths recursively\n const localFiles = await this.walkLocalDirectory(localDirPath);\n\n // Apply the user-supplied filter if any\n const filteredFiles = options?.filter\n ? localFiles.filter(({ absolute, relative }) => options.filter!(absolute, relative))\n : localFiles;\n\n const total = filteredFiles.length;\n const uploaded: StorageFile[] = [];\n const failed: Array<{ localPath: string; error: Error }> = [];\n let doneCount = 0;\n\n // Upload in concurrent batches\n for (let i = 0; i < filteredFiles.length; i += concurrency) {\n const batch = filteredFiles.slice(i, i + concurrency);\n\n await Promise.all(\n batch.map(async ({ absolute, relative }) => {\n const storagePath = `${destination.replace(/\\/$/, \"\")}/${relative}`;\n\n try {\n const stream = createReadStream(absolute);\n const file = await this.putStream(stream, storagePath, options?.putOptions);\n uploaded.push(file);\n doneCount++;\n options?.onProgress?.(doneCount, total, file);\n } catch (err) {\n failed.push({\n localPath: absolute,\n error: err instanceof Error ? err : new Error(String(err)),\n });\n }\n }),\n );\n }\n\n return { uploaded, failed, total };\n }\n\n /**\n * Walk a local directory recursively and return all file paths\n *\n * @param dirPath - Absolute local directory path\n * @returns Array of { absolute, relative } file path pairs\n * @internal\n */\n private async walkLocalDirectory(\n dirPath: string,\n baseDir?: string,\n ): Promise<Array<{ absolute: string; relative: string }>> {\n const root = baseDir ?? dirPath;\n const entries = await fs.readdir(dirPath, { withFileTypes: true });\n const results: Array<{ absolute: string; relative: string }> = [];\n\n for (const entry of entries) {\n const absolute = path.join(dirPath, entry.name);\n const relative = path.relative(root, absolute).replace(/\\\\/g, \"/\");\n\n if (entry.isDirectory()) {\n const nested = await this.walkLocalDirectory(absolute, root);\n results.push(...nested);\n } else if (entry.isFile()) {\n results.push({ absolute, relative });\n }\n // Symlinks are intentionally skipped\n }\n\n return results;\n }\n\n /**\n * Empty a directory without deleting the directory itself\n *\n * Deletes all files within the directory but preserves the directory structure.\n *\n * @param path - Directory path to empty\n * @returns Number of files deleted\n *\n * @example\n * ```typescript\n * const count = await storage.emptyDirectory(\"uploads/temp\");\n * console.log(`Deleted ${count} files`);\n * ```\n */\n public async emptyDirectory(path: string): Promise<number> {\n // List all files in directory\n const files = await this.list(path, { recursive: true });\n const filePaths = files.filter((f) => !f.isDirectory).map((f) => f.path);\n\n if (filePaths.length === 0) {\n return 0;\n }\n\n // Delete all files\n await this.deleteMany(filePaths);\n\n return filePaths.length;\n }\n\n /**\n * List files in a directory\n *\n * Returns file information for all files in the specified directory.\n * Supports recursive listing and pagination.\n *\n * @param directory - Directory path (defaults to root)\n * @param options - List options (recursive, limit, cursor)\n * @returns Array of file information objects\n *\n * @example\n * ```typescript\n * // List all files in uploads\n * const files = await storage.list(\"uploads\");\n *\n * // Recursive listing with limit\n * const files = await storage.list(\"uploads\", {\n * recursive: true,\n * limit: 100\n * });\n * ```\n */\n public async list(directory?: string, options?: ListOptions): Promise<StorageFileInfo[]> {\n return this.activeDriver.list(directory || \"\", options);\n }\n\n // ============================================================\n // URL Operations\n // ============================================================\n\n /**\n * Get the public URL for a file\n *\n * Returns the URL where the file can be accessed. For local storage,\n * this is typically a path prefix. For cloud storage, this is the\n * bucket URL or CDN URL.\n *\n * @param location - File path\n * @returns Public URL string\n *\n * @example\n * ```typescript\n * const url = storage.url(\"images/photo.jpg\");\n * // Local: \"/uploads/images/photo.jpg\"\n * // S3: \"https://bucket.s3.amazonaws.com/images/photo.jpg\"\n * ```\n */\n public url(location: string): string {\n return this.activeDriver.url(location);\n }\n\n /**\n * Get a temporary signed URL with expiration\n *\n * Creates a URL that provides temporary access to the file.\n * For cloud storage, this uses presigned URLs.\n * For local storage, this uses HMAC-signed tokens.\n *\n * @param location - File path\n * @param expiresIn - Seconds until URL expires (default: 3600)\n * @returns Signed URL string\n *\n * @example\n * ```typescript\n * // URL valid for 1 hour\n * const url = await storage.temporaryUrl(\"private/document.pdf\");\n *\n * // URL valid for 24 hours\n * const url = await storage.temporaryUrl(\"private/document.pdf\", 86400);\n * ```\n */\n public async temporaryUrl(location: string, expiresIn?: number): Promise<string> {\n return this.activeDriver.temporaryUrl(location, expiresIn);\n }\n\n // ============================================================\n // Metadata Operations\n // ============================================================\n\n /**\n * Get file metadata without downloading the file\n *\n * Retrieves information about a file including size, last modified date,\n * and MIME type without downloading the file contents.\n *\n * @param location - File path\n * @returns File information object\n * @throws Error if file not found\n *\n * @example\n * ```typescript\n * const info = await storage.metadata(\"documents/report.pdf\");\n * console.log(`Size: ${info.size} bytes`);\n * console.log(`Type: ${info.mimeType}`);\n * console.log(`Modified: ${info.lastModified}`);\n * ```\n */\n public async metadata(location: string): Promise<StorageFileInfo> {\n return this.activeDriver.metadata(location);\n }\n\n /**\n * Get file size in bytes\n *\n * Shortcut for `metadata(location).size`.\n *\n * @param location - File path\n * @returns File size in bytes\n * @throws Error if file not found\n */\n public async size(location: string): Promise<number> {\n return this.activeDriver.size(location);\n }\n\n /**\n * Get a StorageFile instance for OOP-style operations\n *\n * Creates a `StorageFile` wrapper for the specified path,\n * allowing fluent method chaining for file operations.\n *\n * @param location - File path\n * @returns StorageFile instance\n *\n * @example\n * ```typescript\n * const file = await storage.file(\"uploads/image.jpg\");\n *\n * // Properties\n * console.log(file.name); // \"image.jpg\"\n * console.log(file.extension); // \"jpg\"\n *\n * // Operations\n * await file.copy(\"backup/image.jpg\");\n * await file.delete();\n * ```\n */\n public file(location: string): StorageFile {\n return new StorageFile(location, this.activeDriver);\n }\n\n // ============================================================\n // Utilities\n // ============================================================\n\n /**\n * Convert various input types to Buffer\n *\n * @param file - Input file in various formats\n * @returns Buffer containing file contents\n * @internal\n */\n protected async toBuffer(file: UploadedFile | Buffer | string | Readable): Promise<Buffer> {\n // Already a buffer\n if (Buffer.isBuffer(file)) {\n return file;\n }\n\n // Readable stream - collect into buffer\n if (this.isReadable(file)) {\n return this.streamToBuffer(file as Readable);\n }\n\n // String content\n if (typeof file === \"string\") {\n if (await fileExistsAsync(file)) {\n return fs.readFile(file);\n }\n\n return Buffer.from(file);\n }\n\n // UploadedFile\n return (file as UploadedFile).buffer();\n }\n\n /**\n * Check if value is a Readable stream\n *\n * @param value - Value to check\n * @returns True if value is a Readable stream\n * @internal\n */\n protected isReadable(value: unknown): value is Readable {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"pipe\" in value &&\n typeof (value as Readable).pipe === \"function\"\n );\n }\n\n /**\n * Convert a Readable stream to Buffer\n *\n * @param stream - Readable stream\n * @returns Buffer containing stream contents\n * @internal\n */\n protected async streamToBuffer(stream: Readable): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks as unknown as Uint8Array[]);\n }\n\n /**\n * Prepend a prefix to a location path\n *\n * Useful for organizing files into directories.\n *\n * @param prefix - Prefix to add (e.g., \"uploads\")\n * @param location - Original location path\n * @returns Combined path with prefix\n *\n * @example\n * ```typescript\n * storage.prepend(\"uploads\", \"image.jpg\"); // \"uploads/image.jpg\"\n * storage.prepend(\"uploads/\", \"/image.jpg\"); // \"uploads/image.jpg\"\n * ```\n */\n public prepend(prefix: string, location: string): string {\n return `${prefix.replace(/\\/$/, \"\")}/${location.replace(/^\\//, \"\")}`;\n }\n\n /**\n * Append a suffix to a location path (before extension)\n *\n * Useful for creating variants of files (thumbnails, etc.).\n *\n * @param location - Original location path\n * @param suffix - Suffix to add before extension\n * @returns Path with suffix added before extension\n *\n * @example\n * ```typescript\n * storage.append(\"image.jpg\", \"_thumb\"); // \"image_thumb.jpg\"\n * storage.append(\"document.pdf\", \"_v2\"); // \"document_v2.pdf\"\n * ```\n */\n public append(location: string, suffix: string): string {\n const lastDot = location.lastIndexOf(\".\");\n if (lastDot === -1) {\n return `${location}${suffix}`;\n }\n return `${location.substring(0, lastDot)}${suffix}${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QAAgB,UAA0B;EACvD,OAAO,GAAG,OAAO,QAAQ,OAAO,EAAE,EAAE,GAAG,SAAS,QAAQ,OAAO,EAAE;CACnE;;;;;;;;;;;;;;;;CAiBA,AAAO,OAAO,UAAkB,QAAwB;EACtD,MAAM,UAAU,SAAS,YAAY,GAAG;EACxC,IAAI,YAAY,IACd,OAAO,GAAG,WAAW;EAEvB,OAAO,GAAG,SAAS,UAAU,GAAG,OAAO,IAAI,SAAS,SAAS,UAAU,OAAO;CAChF;AACF"}
|
|
1
|
+
{"version":3,"file":"scoped-storage.mjs","names":["fs"],"sources":["../../../../../../../core/src/storage/scoped-storage.ts"],"sourcesContent":["import { fileExistsAsync } from \"@warlock.js/fs\";\nimport { createReadStream } from \"fs\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type { Readable } from \"stream\";\nimport type { UploadedFile } from \"../http\";\nimport { StorageFile } from \"./storage-file\";\nimport type {\n DeleteManyResult,\n ListOptions,\n PutDirectoryOptions,\n PutDirectoryResult,\n PutFromUrlOptions,\n PutOptions,\n ScopedStorageContract,\n StorageDriverContract,\n StorageDriverType,\n StorageFileInfo,\n} from \"./types\";\nimport { safeFetchToBuffer } from \"./utils/safe-fetch\";\n\n/**\n * ScopedStorage - Base class for storage operations\n *\n * Wraps a storage driver and provides a consistent, developer-friendly API\n * that returns `StorageFile` instances instead of raw data objects.\n *\n * This class serves as the base for both direct driver usage and the\n * full `Storage` manager class.\n *\n * @example\n * ```typescript\n * // Using via storage.use()\n * const s3Storage = storage.use(\"s3\");\n * const file = await s3Storage.put(buffer, \"images/photo.jpg\");\n *\n * // file is a StorageFile instance with rich API\n * console.log(file.name); // \"photo.jpg\"\n * console.log(file.url); // \"https://...\"\n * await file.copy(\"backup/photo.jpg\");\n * ```\n */\nexport class ScopedStorage implements ScopedStorageContract {\n /**\n * The underlying storage driver instance\n * @internal\n */\n protected _driver: StorageDriverContract;\n\n /**\n * Create a new ScopedStorage instance\n *\n * @param driver - The storage driver to wrap\n */\n public constructor(driver: StorageDriverContract) {\n this._driver = driver;\n }\n\n // ============================================================\n // Properties\n // ============================================================\n\n /**\n * Get the driver name\n *\n * @returns The name identifier of the underlying driver (e.g., \"local\", \"s3\", \"r2\")\n */\n public get name(): StorageDriverType {\n return this.activeDriver.name;\n }\n\n /**\n * Get the default driver instance\n *\n * Use this for advanced operations that require direct driver access.\n *\n * @returns The raw storage driver\n */\n public get defaultDriver(): StorageDriverContract {\n return this._driver;\n }\n\n /**\n * Get the currently active driver\n *\n * Returns the driver being used for storage operations.\n * Can be overridden in subclasses for dynamic driver resolution (e.g., multi-tenant contexts).\n *\n * @returns The active storage driver\n */\n public get activeDriver(): StorageDriverContract {\n return this._driver;\n }\n\n // ============================================================\n // File Operations\n // ============================================================\n\n /**\n * Store a file in storage\n *\n * Accepts multiple input types and stores the file at the specified location.\n * Returns a `StorageFile` instance for further operations.\n *\n * @param file - File content as Buffer, string path, UploadedFile, or Readable stream\n * @param location - Destination path in storage (e.g., \"uploads/images/photo.jpg\")\n * @param options - Optional storage options\n * @returns StorageFile instance with cached metadata\n *\n * @example\n * ```typescript\n * // From buffer\n * const file = await storage.put(buffer, \"documents/report.pdf\");\n *\n * // From uploaded file\n * const file = await storage.put(uploadedFile, \"avatars/user-123.jpg\");\n *\n * // With options\n * const file = await storage.put(buffer, \"images/photo.jpg\", {\n * mimeType: \"image/jpeg\",\n * cacheControl: \"max-age=31536000\"\n * });\n * ```\n */\n public async put(\n file: UploadedFile | Buffer | string | Readable,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFile> {\n const buffer = await this.toBuffer(file);\n const data = await this.activeDriver.put(buffer, location, options);\n return StorageFile.fromData(data, this.activeDriver);\n }\n\n /**\n * Store a file from a readable stream\n *\n * Optimized for large files - streams data directly without full buffering.\n * Ideal for file uploads, remote file fetching, or processing pipelines.\n *\n * @param stream - Readable stream of file content\n * @param location - Destination path in storage\n * @param options - Optional storage options\n * @returns StorageFile instance with cached metadata\n *\n * @example\n * ```typescript\n * import { createReadStream } from \"fs\";\n *\n * const stream = createReadStream(\"./large-video.mp4\");\n * const file = await storage.putStream(stream, \"videos/upload.mp4\");\n * ```\n */\n public async putStream(\n stream: Readable,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFile> {\n const data = await this.activeDriver.putStream(stream, location, options);\n return StorageFile.fromData(data, this.activeDriver);\n }\n\n /**\n * Store a file from a URL\n *\n * Downloads the file from the URL and stores it. The download is\n * SSRF-guarded by default: the URL scheme must be https/http, the host\n * must not resolve to a private / loopback / link-local / cloud-metadata\n * address, the body is capped, and the request times out. Tune or relax\n * via the {@link PutFromUrlOptions} guard fields.\n *\n * @param url - URL to download from\n * @param location - Destination path in storage\n * @param options - Storage + outbound-download guard options\n * @returns StorageFile instance\n *\n * @example\n * ```typescript\n * const file = await storage.putFromUrl(\n * \"https://example.com/image.jpg\",\n * \"images/downloaded.jpg\"\n * );\n * ```\n */\n public async putFromUrl(\n url: string,\n location: string,\n options?: PutFromUrlOptions,\n ): Promise<StorageFile> {\n const { allowPrivateHosts, maxBytes, timeoutMs, allowedSchemes, ...putOptions } =\n options ?? {};\n\n const result = await safeFetchToBuffer(url, {\n allowPrivateHosts,\n maxBytes,\n timeoutMs,\n allowedSchemes,\n });\n\n if (!result.ok) {\n throw new Error(`Failed to fetch file from ${url}: ${result.statusText}`);\n }\n\n if (!result.contentType) {\n throw new Error(`Failed to fetch file from ${url}: missing content-type header`);\n }\n\n const mimeType = putOptions.mimeType || result.contentType;\n\n return this.put(result.buffer, location, { ...putOptions, mimeType });\n }\n\n /**\n * Store a file from base64 data URL\n *\n * @param dataUrl - Data URL (data:image/png;base64,iVBORw0KG...)\n * @param location - Destination path in storage\n * @param options - Optional storage options\n * @returns StorageFile instance\n *\n * @example\n * ```typescript\n * const file = await storage.putFromBase64(\n * \"data:image/png;base64,iVBORw0KGgoAAAANS...\",\n * \"images/upload.png\"\n * );\n * ```\n */\n public async putFromBase64(\n dataUrl: string,\n location: string,\n options?: PutOptions,\n ): Promise<StorageFile> {\n // Parse data URL: data:image/png;base64,iVBORw0KG...\n const matches = dataUrl.match(/^data:([^;]+);base64,(.+)$/);\n\n if (!matches) {\n throw new Error(\"Invalid base64 data URL format. Expected: data:mime/type;base64,<data>\");\n }\n\n const [, mimeType, base64Data] = matches;\n const buffer = Buffer.from(base64Data, \"base64\");\n\n return this.put(buffer, location, {\n ...options,\n mimeType: options?.mimeType || mimeType,\n });\n }\n\n /**\n * Retrieve file contents as a Buffer\n *\n * Downloads the entire file into memory. For large files,\n * consider using `getStream()` instead.\n *\n * @param location - Path to the file in storage\n * @returns Buffer containing file contents\n * @throws Error if file not found\n *\n * @example\n * ```typescript\n * const buffer = await storage.get(\"documents/report.pdf\");\n * const content = buffer.toString(\"utf-8\");\n * ```\n */\n public async get(location: string): Promise<Buffer> {\n return this.activeDriver.get(location);\n }\n\n /**\n * Retrieve file contents as a readable stream\n *\n * Streams file data without loading entire file into memory.\n * Ideal for large files or when piping to a response.\n *\n * @param location - Path to the file in storage\n * @returns Readable stream of file contents\n * @throws Error if file not found\n *\n * @example\n * ```typescript\n * const stream = await storage.getStream(\"videos/large.mp4\");\n * stream.pipe(response.raw);\n * ```\n */\n public async getStream(location: string): Promise<Readable> {\n return this.activeDriver.getStream(location);\n }\n\n /**\n * Delete a file from storage\n *\n * @param location - Path to the file, or a StorageFile instance\n * @returns `true` if deleted, `false` if file not found\n *\n * @example\n * ```typescript\n * // By path\n * await storage.delete(\"temp/old-file.txt\");\n *\n * // From StorageFile instance\n * const file = await storage.put(buffer, \"temp/file.txt\");\n * await storage.delete(file);\n * ```\n */\n public async delete(location: string | StorageFile): Promise<boolean> {\n const path = typeof location === \"string\" ? location : location.path;\n return this.activeDriver.delete(path);\n }\n\n /**\n * Delete multiple files at once\n *\n * Performs batch deletion for efficiency. Returns results for each file\n * including success/failure status.\n *\n * @param locations - Array of file paths to delete\n * @returns Array of delete results with status for each file\n *\n * @example\n * ```typescript\n * const results = await storage.deleteMany([\n * \"temp/file1.txt\",\n * \"temp/file2.txt\",\n * \"temp/file3.txt\"\n * ]);\n *\n * for (const result of results) {\n * console.log(`${result.location}: ${result.deleted ? \"deleted\" : result.error}`);\n * }\n * ```\n */\n public async deleteMany(locations: string[]): Promise<DeleteManyResult[]> {\n return this.activeDriver.deleteMany(locations);\n }\n\n /**\n * Delete a directory\n *\n * @param directoryPath - Path to the directory\n */\n public async deleteDirectory(directoryPath: string): Promise<boolean> {\n return await this.activeDriver.deleteDirectory(directoryPath);\n }\n\n /**\n * Check if a file exists in storage\n *\n * @param location - Path to check\n * @returns `true` if file exists, `false` otherwise\n *\n * @example\n * ```typescript\n * if (await storage.exists(\"config/settings.json\")) {\n * const config = await storage.get(\"config/settings.json\");\n * }\n * ```\n */\n public async exists(location: string): Promise<boolean> {\n return this.activeDriver.exists(location);\n }\n\n /**\n * Copy a file to a new location\n *\n * Creates a copy of the file at the destination path.\n * The original file remains unchanged.\n *\n * @param from - Source path or StorageFile instance\n * @param to - Destination path\n * @returns StorageFile instance at the new location\n *\n * @example\n * ```typescript\n * // Copy by path\n * const backup = await storage.copy(\"documents/report.pdf\", \"backups/report.pdf\");\n *\n * // Copy from StorageFile\n * const original = await storage.file(\"documents/report.pdf\");\n * const backup = await storage.copy(original, \"backups/report.pdf\");\n * ```\n */\n public async copy(from: string | StorageFile, to: string): Promise<StorageFile> {\n const fromPath = typeof from === \"string\" ? from : from.path;\n const data = await this.activeDriver.copy(fromPath, to);\n return StorageFile.fromData(data, this.activeDriver);\n }\n\n /**\n * Move a file to a new location\n *\n * Moves the file to the destination path. The original file\n * is deleted after successful copy.\n *\n * @param from - Source path or StorageFile instance\n * @param to - Destination path\n * @returns StorageFile instance at the new location\n *\n * @example\n * ```typescript\n * // Move by path\n * const file = await storage.move(\"uploads/temp.jpg\", \"images/photo.jpg\");\n *\n * // Move from StorageFile\n * const temp = await storage.file(\"uploads/temp.jpg\");\n * const final = await storage.move(temp, \"images/photo.jpg\");\n * ```\n */\n public async move(from: string | StorageFile, to: string): Promise<StorageFile> {\n const fromPath = typeof from === \"string\" ? from : from.path;\n const data = await this.activeDriver.move(fromPath, to);\n return StorageFile.fromData(data, this.activeDriver);\n }\n\n /**\n * Copy an entire directory recursively\n *\n * Copies all files from the source directory to the destination directory,\n * preserving the directory structure.\n *\n * @param from - Source directory path\n * @param to - Destination directory path\n * @param options - Optional concurrency control\n * @returns Number of files copied\n *\n * @example\n * ```typescript\n * // Copy entire directory\n * const count = await storage.copyDirectory(\"uploads/temp\", \"uploads/final\");\n * console.log(`Copied ${count} files`);\n *\n * // With concurrency limit\n * const count = await storage.copyDirectory(\"large-dir\", \"backup\", {\n * concurrency: 10\n * });\n * ```\n */\n public async copyDirectory(\n from: string,\n to: string,\n options?: { concurrency?: number },\n ): Promise<number> {\n const concurrency = options?.concurrency || 5;\n\n // List all files recursively\n const files = await this.list(from, { recursive: true });\n const filesToCopy = files.filter((f) => !f.isDirectory);\n\n // Copy files in batches for efficiency\n let copied = 0;\n for (let i = 0; i < filesToCopy.length; i += concurrency) {\n const batch = filesToCopy.slice(i, i + concurrency);\n await Promise.all(\n batch.map(async (file) => {\n // Calculate relative path and new destination\n const relativePath = file.path.substring(from.length).replace(/^\\//, \"\");\n const newPath = `${to}/${relativePath}`;\n await this.copy(file.path, newPath);\n copied++;\n }),\n );\n }\n\n return copied;\n }\n\n /**\n * Move an entire directory recursively\n *\n * Moves all files from the source directory to the destination directory,\n * then deletes the source directory.\n *\n * @param from - Source directory path\n * @param to - Destination directory path\n * @param options - Optional concurrency control\n * @returns Number of files moved\n *\n * @example\n * ```typescript\n * const count = await storage.moveDirectory(\"uploads/temp\", \"uploads/final\");\n * console.log(`Moved ${count} files`);\n * ```\n */\n public async moveDirectory(\n from: string,\n to: string,\n options?: { concurrency?: number },\n ): Promise<number> {\n // Copy all files first\n const count = await this.copyDirectory(from, to, options);\n\n // Delete source directory\n await this.deleteDirectory(from);\n\n return count;\n }\n\n /**\n * Upload a local filesystem directory into storage\n *\n * Recursively walks the local directory, applies an optional filter, then\n * streams each file into storage. Uploads run in concurrent batches for\n * efficiency. Failures are collected — a single failed file never aborts\n * the entire operation (mirrors the contract of `deleteMany`).\n *\n * @param localDirPath - Absolute path of the local directory to upload\n * @param destination - Target prefix in storage (e.g. \"uploads/assets\")\n * @param options - Concurrency, filter, progress callback, put options\n * @returns - { uploaded, failed, total }\n *\n * @example\n * ```typescript\n * const result = await storage.putDirectory(\"./public/assets\", \"cdn/assets\", {\n * concurrency: 10,\n * filter: (_, rel) => !rel.startsWith(\".\"),\n * onProgress: (done, total) => console.log(`${done}/${total}`),\n * });\n *\n * console.log(`Uploaded: ${result.uploaded.length}, Failed: ${result.failed.length}`);\n * ```\n */\n public async putDirectory(\n localDirPath: string,\n destination: string,\n options?: PutDirectoryOptions,\n ): Promise<PutDirectoryResult> {\n const concurrency = options?.concurrency ?? 5;\n\n // Collect all local file paths recursively\n const localFiles = await this.walkLocalDirectory(localDirPath);\n\n // Apply the user-supplied filter if any\n const filteredFiles = options?.filter\n ? localFiles.filter(({ absolute, relative }) => options.filter!(absolute, relative))\n : localFiles;\n\n const total = filteredFiles.length;\n const uploaded: StorageFile[] = [];\n const failed: Array<{ localPath: string; error: Error }> = [];\n let doneCount = 0;\n\n // Upload in concurrent batches\n for (let i = 0; i < filteredFiles.length; i += concurrency) {\n const batch = filteredFiles.slice(i, i + concurrency);\n\n await Promise.all(\n batch.map(async ({ absolute, relative }) => {\n const storagePath = `${destination.replace(/\\/$/, \"\")}/${relative}`;\n\n try {\n const stream = createReadStream(absolute);\n const file = await this.putStream(stream, storagePath, options?.putOptions);\n uploaded.push(file);\n doneCount++;\n options?.onProgress?.(doneCount, total, file);\n } catch (err) {\n failed.push({\n localPath: absolute,\n error: err instanceof Error ? err : new Error(String(err)),\n });\n }\n }),\n );\n }\n\n return { uploaded, failed, total };\n }\n\n /**\n * Walk a local directory recursively and return all file paths\n *\n * @param dirPath - Absolute local directory path\n * @returns Array of { absolute, relative } file path pairs\n * @internal\n */\n private async walkLocalDirectory(\n dirPath: string,\n baseDir?: string,\n ): Promise<Array<{ absolute: string; relative: string }>> {\n const root = baseDir ?? dirPath;\n const entries = await fs.readdir(dirPath, { withFileTypes: true });\n const results: Array<{ absolute: string; relative: string }> = [];\n\n for (const entry of entries) {\n const absolute = path.join(dirPath, entry.name);\n const relative = path.relative(root, absolute).replace(/\\\\/g, \"/\");\n\n if (entry.isDirectory()) {\n const nested = await this.walkLocalDirectory(absolute, root);\n results.push(...nested);\n } else if (entry.isFile()) {\n results.push({ absolute, relative });\n }\n // Symlinks are intentionally skipped\n }\n\n return results;\n }\n\n /**\n * Empty a directory without deleting the directory itself\n *\n * Deletes all files within the directory but preserves the directory structure.\n *\n * @param path - Directory path to empty\n * @returns Number of files deleted\n *\n * @example\n * ```typescript\n * const count = await storage.emptyDirectory(\"uploads/temp\");\n * console.log(`Deleted ${count} files`);\n * ```\n */\n public async emptyDirectory(path: string): Promise<number> {\n // List all files in directory\n const files = await this.list(path, { recursive: true });\n const filePaths = files.filter((f) => !f.isDirectory).map((f) => f.path);\n\n if (filePaths.length === 0) {\n return 0;\n }\n\n // Delete all files\n await this.deleteMany(filePaths);\n\n return filePaths.length;\n }\n\n /**\n * List files in a directory\n *\n * Returns file information for all files in the specified directory.\n * Supports recursive listing and pagination.\n *\n * @param directory - Directory path (defaults to root)\n * @param options - List options (recursive, limit, cursor)\n * @returns Array of file information objects\n *\n * @example\n * ```typescript\n * // List all files in uploads\n * const files = await storage.list(\"uploads\");\n *\n * // Recursive listing with limit\n * const files = await storage.list(\"uploads\", {\n * recursive: true,\n * limit: 100\n * });\n * ```\n */\n public async list(directory?: string, options?: ListOptions): Promise<StorageFileInfo[]> {\n return this.activeDriver.list(directory || \"\", options);\n }\n\n // ============================================================\n // URL Operations\n // ============================================================\n\n /**\n * Get the public URL for a file\n *\n * Returns the URL where the file can be accessed. For local storage,\n * this is typically a path prefix. For cloud storage, this is the\n * bucket URL or CDN URL.\n *\n * @param location - File path\n * @returns Public URL string\n *\n * @example\n * ```typescript\n * const url = storage.url(\"images/photo.jpg\");\n * // Local: \"/uploads/images/photo.jpg\"\n * // S3: \"https://bucket.s3.amazonaws.com/images/photo.jpg\"\n * ```\n */\n public url(location: string): string {\n return this.activeDriver.url(location);\n }\n\n /**\n * Get a temporary signed URL with expiration\n *\n * Creates a URL that provides temporary access to the file.\n * For cloud storage, this uses presigned URLs.\n * For local storage, this uses HMAC-signed tokens.\n *\n * @param location - File path\n * @param expiresIn - Seconds until URL expires (default: 3600)\n * @returns Signed URL string\n *\n * @example\n * ```typescript\n * // URL valid for 1 hour\n * const url = await storage.temporaryUrl(\"private/document.pdf\");\n *\n * // URL valid for 24 hours\n * const url = await storage.temporaryUrl(\"private/document.pdf\", 86400);\n * ```\n */\n public async temporaryUrl(location: string, expiresIn?: number): Promise<string> {\n return this.activeDriver.temporaryUrl(location, expiresIn);\n }\n\n // ============================================================\n // Metadata Operations\n // ============================================================\n\n /**\n * Get file metadata without downloading the file\n *\n * Retrieves information about a file including size, last modified date,\n * and MIME type without downloading the file contents.\n *\n * @param location - File path\n * @returns File information object\n * @throws Error if file not found\n *\n * @example\n * ```typescript\n * const info = await storage.metadata(\"documents/report.pdf\");\n * console.log(`Size: ${info.size} bytes`);\n * console.log(`Type: ${info.mimeType}`);\n * console.log(`Modified: ${info.lastModified}`);\n * ```\n */\n public async metadata(location: string): Promise<StorageFileInfo> {\n return this.activeDriver.metadata(location);\n }\n\n /**\n * Get file size in bytes\n *\n * Shortcut for `metadata(location).size`.\n *\n * @param location - File path\n * @returns File size in bytes\n * @throws Error if file not found\n */\n public async size(location: string): Promise<number> {\n return this.activeDriver.size(location);\n }\n\n /**\n * Get a StorageFile instance for OOP-style operations\n *\n * Creates a `StorageFile` wrapper for the specified path,\n * allowing fluent method chaining for file operations.\n *\n * @param location - File path\n * @returns StorageFile instance\n *\n * @example\n * ```typescript\n * const file = await storage.file(\"uploads/image.jpg\");\n *\n * // Properties\n * console.log(file.name); // \"image.jpg\"\n * console.log(file.extension); // \"jpg\"\n *\n * // Operations\n * await file.copy(\"backup/image.jpg\");\n * await file.delete();\n * ```\n */\n public file(location: string): StorageFile {\n return new StorageFile(location, this.activeDriver);\n }\n\n // ============================================================\n // Utilities\n // ============================================================\n\n /**\n * Convert various input types to Buffer\n *\n * @param file - Input file in various formats\n * @returns Buffer containing file contents\n * @internal\n */\n protected async toBuffer(file: UploadedFile | Buffer | string | Readable): Promise<Buffer> {\n // Already a buffer\n if (Buffer.isBuffer(file)) {\n return file;\n }\n\n // Readable stream - collect into buffer\n if (this.isReadable(file)) {\n return this.streamToBuffer(file as Readable);\n }\n\n // String content\n if (typeof file === \"string\") {\n if (await fileExistsAsync(file)) {\n return fs.readFile(file);\n }\n\n return Buffer.from(file);\n }\n\n // UploadedFile\n return (file as UploadedFile).buffer();\n }\n\n /**\n * Check if value is a Readable stream\n *\n * @param value - Value to check\n * @returns True if value is a Readable stream\n * @internal\n */\n protected isReadable(value: unknown): value is Readable {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"pipe\" in value &&\n typeof (value as Readable).pipe === \"function\"\n );\n }\n\n /**\n * Convert a Readable stream to Buffer\n *\n * @param stream - Readable stream\n * @returns Buffer containing stream contents\n * @internal\n */\n protected async streamToBuffer(stream: Readable): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks as unknown as Uint8Array[]);\n }\n\n /**\n * Prepend a prefix to a location path\n *\n * Useful for organizing files into directories.\n *\n * @param prefix - Prefix to add (e.g., \"uploads\")\n * @param location - Original location path\n * @returns Combined path with prefix\n *\n * @example\n * ```typescript\n * storage.prepend(\"uploads\", \"image.jpg\"); // \"uploads/image.jpg\"\n * storage.prepend(\"uploads/\", \"/image.jpg\"); // \"uploads/image.jpg\"\n * ```\n */\n public prepend(prefix: string, location: string): string {\n return `${prefix.replace(/\\/$/, \"\")}/${location.replace(/^\\//, \"\")}`;\n }\n\n /**\n * Append a suffix to a location path (before extension)\n *\n * Useful for creating variants of files (thumbnails, etc.).\n *\n * @param location - Original location path\n * @param suffix - Suffix to add before extension\n * @returns Path with suffix added before extension\n *\n * @example\n * ```typescript\n * storage.append(\"image.jpg\", \"_thumb\"); // \"image_thumb.jpg\"\n * storage.append(\"document.pdf\", \"_v2\"); // \"document_v2.pdf\"\n * ```\n */\n public append(location: string, suffix: string): string {\n const lastDot = location.lastIndexOf(\".\");\n if (lastDot === -1) {\n return `${location}${suffix}`;\n }\n return `${location.substring(0, lastDot)}${suffix}${location.substring(lastDot)}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,IAAa,gBAAb,MAA4D;;;;;;CAY1D,AAAO,YAAY,QAA+B;EAChD,KAAK,UAAU;CACjB;;;;;;CAWA,IAAW,OAA0B;EACnC,OAAO,KAAK,aAAa;CAC3B;;;;;;;;CASA,IAAW,gBAAuC;EAChD,OAAO,KAAK;CACd;;;;;;;;;CAUA,IAAW,eAAsC;EAC/C,OAAO,KAAK;CACd;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCA,MAAa,IACX,MACA,UACA,SACsB;EACtB,MAAM,SAAS,MAAM,KAAK,SAAS,IAAI;EACvC,MAAM,OAAO,MAAM,KAAK,aAAa,IAAI,QAAQ,UAAU,OAAO;EAClE,OAAO,YAAY,SAAS,MAAM,KAAK,YAAY;CACrD;;;;;;;;;;;;;;;;;;;;CAqBA,MAAa,UACX,QACA,UACA,SACsB;EACtB,MAAM,OAAO,MAAM,KAAK,aAAa,UAAU,QAAQ,UAAU,OAAO;EACxE,OAAO,YAAY,SAAS,MAAM,KAAK,YAAY;CACrD;;;;;;;;;;;;;;;;;;;;;;;CAwBA,MAAa,WACX,KACA,UACA,SACsB;EACtB,MAAM,EAAE,mBAAmB,UAAU,WAAW,gBAAgB,GAAG,eACjE,WAAW,CAAC;EAEd,MAAM,SAAS,MAAM,kBAAkB,KAAK;GAC1C;GAC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AI;EACzB;EAGA,OAAQ,KAAsB,OAAO;CACvC;;;;;;;;CASA,AAAU,WAAW,OAAmC;EACtD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,OAAQ,MAAmB,SAAS;CAExC;;;;;;;;CASA,MAAgB,eAAe,QAAmC;EAChE,MAAM,SAAmB,CAAC;EAC1B,WAAW,MAAM,SAAS,QACxB,OAAO,KAAK,OAAO,SAAS,KAAK,IAAI,QAAQ,OAAO,KAAK,KAAK,CAAC;EAEjE,OAAO,OAAO,OAAO,MAAiC;CACxD;;;;;;;;;;;;;;;;CAiBA,AAAO,QAAQ,QAAgB,UAA0B;EACvD,OAAO,GAAG,OAAO,QAAQ,OAAO,EAAE,EAAE,GAAG,SAAS,QAAQ,OAAO,EAAE;CACnE;;;;;;;;;;;;;;;;CAiBA,AAAO,OAAO,UAAkB,QAAwB;EACtD,MAAM,UAAU,SAAS,YAAY,GAAG;EACxC,IAAI,YAAY,IACd,OAAO,GAAG,WAAW;EAEvB,OAAO,GAAG,SAAS,UAAU,GAAG,OAAO,IAAI,SAAS,SAAS,UAAU,OAAO;CAChF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-file.d.mts","names":[],"sources":["../../../../../../../core/src/storage/storage-file.ts"],"mappings":";;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;cAAa,WAAA;EA6P6B;;;EAAA,UAzP9B,KAAA;EAkS8C;;;EAAA,UA7R9C,OAAA,EAAS,qBAAA;EA4VX;;;EAAA,UAvVE,KAAA,GAAQ,eAAA;EAgWe;;;EAAA,UA3VvB,QAAA;EAmXQ;;;;;;;cA1WC,IAAA,UAAc,MAAA,EAAQ,qBAAA,EAAuB,IAAA,GAAO,eAAA;EAnB7D;;;EAAA,IAgCC,IAAA
|
|
1
|
+
{"version":3,"file":"storage-file.d.mts","names":[],"sources":["../../../../../../../core/src/storage/storage-file.ts"],"mappings":";;;;;;AAqCA;;;;;;;;;;;;;;;;;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AAA,CAAc,UAAA,EAAY,cAAA,GAAiB,OAAA;;;;;;EAgB3C,aAAA,IAAiB,OAAA,CAAQ,cAAA;;;;;;;EAgBzB,eAAA,CAAgB,YAAA,WAAuB,OAAA;;;;YAkB1C,gBAAA;;;;;;;SAYI,QAAA,CACZ,IAAA,EAAM,eAAA,GAAkB,oBAAA,EACxB,MAAA,EAAQ,qBAAA,GACP,WAAA;;;;EAOU,QAAA,IAAY,OAAA,CAAQ,eAAA;;;;EAQpB,OAAA,IAAO,OAAA;;;;EAQP,UAAA,IAAU,OAAA;;;;EAQV,KAAA,IAAK,OAAA;;;;EAQL,OAAA,IAAO,OAAA;;;;EAYP,KAAA,IAAK,OAAA;;;;EAaL,OAAA,IAAO,OAAA;;;;EAQP,OAAA,IAAO,OAAA;;;;EAQb,MAAA;IACL,IAAA;IACA,IAAA;IACA,SAAA;IACA,MAAA;IACA,GAAA;IACA,IAAA;IACA,IAAA;IACA,QAAA;EAAA;;;;EAiBK,QAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-file.mjs","names":[],"sources":["../../../../../../../core/src/storage/storage-file.ts"],"sourcesContent":["import { basename, dirname, extname } from \"path\";\nimport type { Readable } from \"stream\";\nimport type {\n CloudStorageDriverContract,\n CloudStorageFileData,\n FileVisibility,\n StorageDriverContract,\n StorageFileData,\n StorageFileInfo,\n} from \"./types\";\n\n/**\n * StorageFile class - OOP wrapper for storage file operations\n *\n * Provides a fluent interface for working with files in storage,\n * wrapping the underlying driver operations.\n *\n * @example\n * ```typescript\n * const file = await storage.put(buffer, \"uploads/image.jpg\");\n *\n * // Properties (sync, from cached data)\n * file.name // \"image.jpg\"\n * file.extension // \"jpg\"\n * file.path // \"uploads/image.jpg\"\n * file.hash // \"sha256:abc123...\"\n *\n * // Operations\n * await file.copy(\"uploads/backup.jpg\")\n * await file.move(\"archive/image.jpg\")\n * await file.delete()\n *\n * // Content\n * const buffer = await file.contents();\n * const stream = await file.stream();\n * ```\n */\nexport class StorageFile {\n /**\n * Relative file path\n */\n protected _path: string;\n\n /**\n * The driver instance\n */\n protected _driver: StorageDriverContract;\n\n /**\n * Cached file data (from put operations or lazy loaded)\n */\n protected _data?: StorageFileData;\n\n /**\n * Whether the file has been deleted\n */\n protected _deleted = false;\n\n /**\n * Create a new StorageFile instance\n *\n * @param path - Relative file path\n * @param driver - Driver instance\n * @param data - Optional initial data from put/copy operations\n */\n public constructor(path: string, driver: StorageDriverContract, data?: StorageFileData) {\n this._path = path;\n this._driver = driver;\n this._data = data;\n }\n\n // ============================================================\n // Properties\n // ============================================================\n\n /**\n * Get the relative file path\n */\n public get path(): string {\n return this._path;\n }\n\n /**\n * Get the file name (with extension)\n */\n public get name(): string {\n return basename(this._path);\n }\n\n /**\n * Get the file extension (without dot)\n */\n public get extension(): string {\n return extname(this._path).slice(1).toLowerCase();\n }\n\n /**\n * Get the directory path\n */\n public get directory(): string {\n return dirname(this._path);\n }\n\n /**\n * Get the driver name\n */\n public get driver(): string {\n return this._driver.name;\n }\n\n /**\n * Check if file has been deleted\n */\n public get isDeleted(): boolean {\n return this._deleted;\n }\n\n /**\n * Get public URL (sync if data cached, otherwise computed)\n */\n public get url(): string {\n this.ensureNotDeleted();\n return this._data?.url || this._driver.url(this._path);\n }\n\n /**\n * Get the absolute filesystem path (local driver only)\n */\n public get absolutePath(): string | undefined {\n this.ensureNotDeleted();\n if (\"path\" in this._driver && typeof this._driver.path === \"function\") {\n return this._driver.path(this._path);\n }\n\n return undefined;\n }\n\n /**\n * Get file hash (SHA-256, available from put operations)\n */\n public get hash(): string | undefined {\n return this._data?.hash;\n }\n\n // ============================================================\n // Data Methods (Lazy Loaded)\n // ============================================================\n\n /**\n * Get cached file data, or fetch it if not available\n */\n public async data(): Promise<StorageFileData> {\n this.ensureNotDeleted();\n if (!this._data) {\n // Fetch info and construct data\n const info = await this.metadata();\n this._data = {\n path: info.path,\n url: this._driver.url(this._path),\n size: info.size,\n hash: \"\", // Not available from metadata\n mimeType: info.mimeType || \"application/octet-stream\",\n driver: this._driver.name,\n };\n }\n return this._data;\n }\n\n /**\n * Get file size in bytes\n */\n public async size(): Promise<number> {\n const data = await this.data();\n return data.size;\n }\n\n /**\n * Get MIME type\n */\n public async mimeType(): Promise<string> {\n const data = await this.data();\n return data.mimeType;\n }\n\n /**\n * Get last modified date (fetches from driver)\n */\n public async lastModified(): Promise<Date | undefined> {\n this.ensureNotDeleted();\n const info = await this.metadata();\n return info.lastModified;\n }\n\n /**\n * Get ETag (cloud drivers, fetches from driver)\n */\n public async etag(): Promise<string | undefined> {\n this.ensureNotDeleted();\n const info = await this.metadata();\n return info.etag;\n }\n\n // ============================================================\n // Content Methods\n // ============================================================\n\n /**\n * Get file contents as Buffer\n */\n public async contents(): Promise<Buffer> {\n this.ensureNotDeleted();\n return this._driver.get(this._path);\n }\n\n /**\n * Get file contents as readable stream\n */\n public async stream(): Promise<Readable> {\n this.ensureNotDeleted();\n return this._driver.getStream(this._path);\n }\n\n /**\n * Get file contents as UTF-8 text\n */\n public async text(): Promise<string> {\n const buffer = await this.contents();\n return buffer.toString(\"utf-8\");\n }\n\n /**\n * Get file contents as base64 string\n */\n public async base64(): Promise<string> {\n const buffer = await this.contents();\n return buffer.toString(\"base64\");\n }\n\n /**\n * Get file contents as data URL\n */\n public async dataUrl(): Promise<string> {\n const [buffer, data] = await Promise.all([this.contents(), this.data()]);\n return `data:${data.mimeType};base64,${buffer.toString(\"base64\")}`;\n }\n\n // ============================================================\n // URL Methods\n // ============================================================\n\n /**\n * Get a temporary signed URL\n *\n * @param expiresIn - Seconds until expiration (default: 3600)\n */\n public async temporaryUrl(expiresIn = 3600): Promise<string> {\n this.ensureNotDeleted();\n return this._driver.temporaryUrl(this._path, expiresIn);\n }\n\n // ============================================================\n // File Operations\n // ============================================================\n\n /**\n * Check if the file exists\n */\n public async exists(): Promise<boolean> {\n if (this._deleted) return false;\n return this._driver.exists(this._path);\n }\n\n /**\n * Copy the file to a new location\n *\n * @param destination - Destination path\n * @returns New StorageFile instance at destination\n */\n public async copy(destination: string): Promise<StorageFile> {\n this.ensureNotDeleted();\n const result = await this._driver.copy(this._path, destination);\n return new StorageFile(destination, this._driver, result);\n }\n\n /**\n * Move the file to a new location\n *\n * @param destination - Destination path\n * @returns This StorageFile instance with updated path\n */\n public async move(destination: string): Promise<this> {\n this.ensureNotDeleted();\n const result = await this._driver.move(this._path, destination);\n this._path = destination;\n this._data = result; // Update cached data\n return this;\n }\n\n /**\n * Rename the file (move within same directory)\n *\n * @param newName - New file name\n * @returns This StorageFile instance with updated path\n */\n public async rename(newName: string): Promise<this> {\n const newPath = this.directory === \".\" ? newName : `${this.directory}/${newName}`;\n return this.move(newPath);\n }\n\n /**\n * Delete the file\n *\n * @returns true if deleted, false if not found\n */\n public async delete(): Promise<boolean> {\n this.ensureNotDeleted();\n const result = await this._driver.delete(this._path);\n this._deleted = true;\n return result;\n }\n\n // ============================================================\n // Cloud-Specific Methods\n // ============================================================\n\n /**\n * Set file visibility (cloud drivers only)\n *\n * @param visibility - \"public\" or \"private\"\n * @throws Error if driver doesn't support visibility\n */\n public async setVisibility(visibility: FileVisibility): Promise<this> {\n this.ensureNotDeleted();\n\n if (!(\"setVisibility\" in this._driver)) {\n throw new Error(\"setVisibility is only available for cloud storage drivers\");\n }\n\n await (this._driver as CloudStorageDriverContract).setVisibility(this._path, visibility);\n return this;\n }\n\n /**\n * Get file visibility (cloud drivers only)\n *\n * @throws Error if driver doesn't support visibility\n */\n public async getVisibility(): Promise<FileVisibility> {\n this.ensureNotDeleted();\n\n if (!(\"getVisibility\" in this._driver)) {\n throw new Error(\"getVisibility is only available for cloud storage drivers\");\n }\n\n return (this._driver as CloudStorageDriverContract).getVisibility(this._path);\n }\n\n /**\n * Set storage class (cloud drivers only)\n *\n * @param storageClass - Storage class (e.g., \"STANDARD\", \"GLACIER\")\n * @throws Error if driver doesn't support storage class\n */\n public async setStorageClass(storageClass: string): Promise<this> {\n this.ensureNotDeleted();\n\n if (!(\"setStorageClass\" in this._driver)) {\n throw new Error(\"setStorageClass is only available for cloud storage drivers\");\n }\n\n await (this._driver as CloudStorageDriverContract).setStorageClass(this._path, storageClass);\n return this;\n }\n\n // ============================================================\n // Utilities\n // ============================================================\n\n /**\n * Ensure the file has not been deleted\n */\n protected ensureNotDeleted(): void {\n if (this._deleted) {\n throw new Error(`File \"${this._path}\" has been deleted`);\n }\n }\n\n /**\n * Create a StorageFile instance from StorageFileData\n *\n * @param data - Storage file data from put/copy/move operations\n * @param driver - Driver instance\n */\n public static fromData(\n data: StorageFileData | CloudStorageFileData,\n driver: StorageDriverContract,\n ): StorageFile {\n return new StorageFile(data.path, driver, data);\n }\n\n /**\n * Get file metadata\n */\n public async metadata(): Promise<StorageFileInfo> {\n this.ensureNotDeleted();\n return this._driver.metadata(this._path);\n }\n\n /**\n * Determine if this file is an image type\n */\n public async isImage() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"image/\");\n }\n\n /**\n * Determine if this file is a document type\n */\n public async isDocument() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"application/\");\n }\n\n /**\n * Determine if this file is a pdf type\n */\n public async isPdf() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"application/pdf\");\n }\n\n /**\n * Determine if this file is an excel file (any support excel file)\n */\n public async isExcel() {\n const metadata = await this.metadata();\n return (\n metadata.mimeType!.startsWith(\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n ) || metadata.mimeType!.startsWith(\"application/vnd.ms-excel\")\n );\n }\n\n /**\n * Determine if this file is a doc file\n */\n public async isDoc() {\n const metadata = await this.metadata();\n return (\n metadata.mimeType!.startsWith(\"application/msword\") ||\n metadata.mimeType!.startsWith(\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n )\n );\n }\n\n /**\n * Determine if this file is an audio type\n */\n public async isAudio() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"audio/\");\n }\n\n /**\n * Determine if this file is a video type\n */\n public async isVideo() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"video/\");\n }\n\n /**\n * Convert to plain object (returns cached data or constructs it)\n */\n public toJSON(): {\n path: string;\n name: string;\n extension: string;\n driver: string;\n url: string;\n hash?: string;\n size?: number;\n mimeType?: string;\n } {\n return {\n path: this._path,\n name: this.name,\n extension: this.extension,\n driver: this._driver.name,\n url: this._deleted ? \"\" : this.url,\n hash: this._data?.hash,\n size: this._data?.size,\n mimeType: this._data?.mimeType,\n };\n }\n\n /**\n * String representation\n */\n public toString(): string {\n return this._path;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,cAAb,MAAa,YAAY;;;;;;;;CA4BvB,AAAO,YAAY,MAAc,QAA+B,MAAwB;kBATnE;EAUnB,KAAK,QAAQ;EACb,KAAK,UAAU;EACf,KAAK,QAAQ;CACf;;;;CASA,IAAW,OAAe;EACxB,OAAO,KAAK;CACd;;;;CAKA,IAAW,OAAe;EACxB,OAAO,SAAS,KAAK,KAAK;CAC5B;;;;CAKA,IAAW,YAAoB;EAC7B,OAAO,QAAQ,KAAK,KAAK,EAAE,MAAM,CAAC,EAAE,YAAY;CAClD;;;;CAKA,IAAW,YAAoB;EAC7B,OAAO,QAAQ,KAAK,KAAK;CAC3B;;;;CAKA,IAAW,SAAiB;EAC1B,OAAO,KAAK,QAAQ;CACtB;;;;CAKA,IAAW,YAAqB;EAC9B,OAAO,KAAK;CACd;;;;CAKA,IAAW,MAAc;EACvB,KAAK,iBAAiB;EACtB,OAAO,KAAK,OAAO,OAAO,KAAK,QAAQ,IAAI,KAAK,KAAK;CACvD;;;;CAKA,IAAW,eAAmC;EAC5C,KAAK,iBAAiB;EACtB,IAAI,UAAU,KAAK,WAAW,OAAO,KAAK,QAAQ,SAAS,YACzD,OAAO,KAAK,QAAQ,KAAK,KAAK,KAAK;CAIvC;;;;CAKA,IAAW,OAA2B;EACpC,OAAO,KAAK,OAAO;CAC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;;;;CAKA,AAAO,WAAmB;EACxB,OAAO,KAAK;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"storage-file.mjs","names":[],"sources":["../../../../../../../core/src/storage/storage-file.ts"],"sourcesContent":["import { basename, dirname, extname } from \"path\";\nimport type { Readable } from \"stream\";\nimport type {\n CloudStorageDriverContract,\n CloudStorageFileData,\n FileVisibility,\n StorageDriverContract,\n StorageFileData,\n StorageFileInfo,\n} from \"./types\";\n\n/**\n * StorageFile class - OOP wrapper for storage file operations\n *\n * Provides a fluent interface for working with files in storage,\n * wrapping the underlying driver operations.\n *\n * @example\n * ```typescript\n * const file = await storage.put(buffer, \"uploads/image.jpg\");\n *\n * // Properties (sync, from cached data)\n * file.name // \"image.jpg\"\n * file.extension // \"jpg\"\n * file.path // \"uploads/image.jpg\"\n * file.hash // \"sha256:abc123...\"\n *\n * // Operations\n * await file.copy(\"uploads/backup.jpg\")\n * await file.move(\"archive/image.jpg\")\n * await file.delete()\n *\n * // Content\n * const buffer = await file.contents();\n * const stream = await file.stream();\n * ```\n */\nexport class StorageFile {\n /**\n * Relative file path\n */\n protected _path: string;\n\n /**\n * The driver instance\n */\n protected _driver: StorageDriverContract;\n\n /**\n * Cached file data (from put operations or lazy loaded)\n */\n protected _data?: StorageFileData;\n\n /**\n * Whether the file has been deleted\n */\n protected _deleted = false;\n\n /**\n * Create a new StorageFile instance\n *\n * @param path - Relative file path\n * @param driver - Driver instance\n * @param data - Optional initial data from put/copy operations\n */\n public constructor(path: string, driver: StorageDriverContract, data?: StorageFileData) {\n this._path = path;\n this._driver = driver;\n this._data = data;\n }\n\n // ============================================================\n // Properties\n // ============================================================\n\n /**\n * Get the relative file path\n */\n public get path(): string {\n return this._path;\n }\n\n /**\n * Get the file name (with extension)\n */\n public get name(): string {\n return basename(this._path);\n }\n\n /**\n * Get the file extension (without dot)\n */\n public get extension(): string {\n return extname(this._path).slice(1).toLowerCase();\n }\n\n /**\n * Get the directory path\n */\n public get directory(): string {\n return dirname(this._path);\n }\n\n /**\n * Get the driver name\n */\n public get driver(): string {\n return this._driver.name;\n }\n\n /**\n * Check if file has been deleted\n */\n public get isDeleted(): boolean {\n return this._deleted;\n }\n\n /**\n * Get public URL (sync if data cached, otherwise computed)\n */\n public get url(): string {\n this.ensureNotDeleted();\n return this._data?.url || this._driver.url(this._path);\n }\n\n /**\n * Get the absolute filesystem path (local driver only)\n */\n public get absolutePath(): string | undefined {\n this.ensureNotDeleted();\n if (\"path\" in this._driver && typeof this._driver.path === \"function\") {\n return this._driver.path(this._path);\n }\n\n return undefined;\n }\n\n /**\n * Get file hash (SHA-256, available from put operations)\n */\n public get hash(): string | undefined {\n return this._data?.hash;\n }\n\n // ============================================================\n // Data Methods (Lazy Loaded)\n // ============================================================\n\n /**\n * Get cached file data, or fetch it if not available\n */\n public async data(): Promise<StorageFileData> {\n this.ensureNotDeleted();\n if (!this._data) {\n // Fetch info and construct data\n const info = await this.metadata();\n this._data = {\n path: info.path,\n url: this._driver.url(this._path),\n size: info.size,\n hash: \"\", // Not available from metadata\n mimeType: info.mimeType || \"application/octet-stream\",\n driver: this._driver.name,\n };\n }\n return this._data;\n }\n\n /**\n * Get file size in bytes\n */\n public async size(): Promise<number> {\n const data = await this.data();\n return data.size;\n }\n\n /**\n * Get MIME type\n */\n public async mimeType(): Promise<string> {\n const data = await this.data();\n return data.mimeType;\n }\n\n /**\n * Get last modified date (fetches from driver)\n */\n public async lastModified(): Promise<Date | undefined> {\n this.ensureNotDeleted();\n const info = await this.metadata();\n return info.lastModified;\n }\n\n /**\n * Get ETag (cloud drivers, fetches from driver)\n */\n public async etag(): Promise<string | undefined> {\n this.ensureNotDeleted();\n const info = await this.metadata();\n return info.etag;\n }\n\n // ============================================================\n // Content Methods\n // ============================================================\n\n /**\n * Get file contents as Buffer\n */\n public async contents(): Promise<Buffer> {\n this.ensureNotDeleted();\n return this._driver.get(this._path);\n }\n\n /**\n * Get file contents as readable stream\n */\n public async stream(): Promise<Readable> {\n this.ensureNotDeleted();\n return this._driver.getStream(this._path);\n }\n\n /**\n * Get file contents as UTF-8 text\n */\n public async text(): Promise<string> {\n const buffer = await this.contents();\n return buffer.toString(\"utf-8\");\n }\n\n /**\n * Get file contents as base64 string\n */\n public async base64(): Promise<string> {\n const buffer = await this.contents();\n return buffer.toString(\"base64\");\n }\n\n /**\n * Get file contents as data URL\n */\n public async dataUrl(): Promise<string> {\n const [buffer, data] = await Promise.all([this.contents(), this.data()]);\n return `data:${data.mimeType};base64,${buffer.toString(\"base64\")}`;\n }\n\n // ============================================================\n // URL Methods\n // ============================================================\n\n /**\n * Get a temporary signed URL\n *\n * @param expiresIn - Seconds until expiration (default: 3600)\n */\n public async temporaryUrl(expiresIn = 3600): Promise<string> {\n this.ensureNotDeleted();\n return this._driver.temporaryUrl(this._path, expiresIn);\n }\n\n // ============================================================\n // File Operations\n // ============================================================\n\n /**\n * Check if the file exists\n */\n public async exists(): Promise<boolean> {\n if (this._deleted) return false;\n return this._driver.exists(this._path);\n }\n\n /**\n * Copy the file to a new location\n *\n * @param destination - Destination path\n * @returns New StorageFile instance at destination\n */\n public async copy(destination: string): Promise<StorageFile> {\n this.ensureNotDeleted();\n const result = await this._driver.copy(this._path, destination);\n return new StorageFile(destination, this._driver, result);\n }\n\n /**\n * Move the file to a new location\n *\n * @param destination - Destination path\n * @returns This StorageFile instance with updated path\n */\n public async move(destination: string): Promise<this> {\n this.ensureNotDeleted();\n const result = await this._driver.move(this._path, destination);\n this._path = destination;\n this._data = result; // Update cached data\n return this;\n }\n\n /**\n * Rename the file (move within same directory)\n *\n * @param newName - New file name\n * @returns This StorageFile instance with updated path\n */\n public async rename(newName: string): Promise<this> {\n const newPath = this.directory === \".\" ? newName : `${this.directory}/${newName}`;\n return this.move(newPath);\n }\n\n /**\n * Delete the file\n *\n * @returns true if deleted, false if not found\n */\n public async delete(): Promise<boolean> {\n this.ensureNotDeleted();\n const result = await this._driver.delete(this._path);\n this._deleted = true;\n return result;\n }\n\n // ============================================================\n // Cloud-Specific Methods\n // ============================================================\n\n /**\n * Set file visibility (cloud drivers only)\n *\n * @param visibility - \"public\" or \"private\"\n * @throws Error if driver doesn't support visibility\n */\n public async setVisibility(visibility: FileVisibility): Promise<this> {\n this.ensureNotDeleted();\n\n if (!(\"setVisibility\" in this._driver)) {\n throw new Error(\"setVisibility is only available for cloud storage drivers\");\n }\n\n await (this._driver as CloudStorageDriverContract).setVisibility(this._path, visibility);\n return this;\n }\n\n /**\n * Get file visibility (cloud drivers only)\n *\n * @throws Error if driver doesn't support visibility\n */\n public async getVisibility(): Promise<FileVisibility> {\n this.ensureNotDeleted();\n\n if (!(\"getVisibility\" in this._driver)) {\n throw new Error(\"getVisibility is only available for cloud storage drivers\");\n }\n\n return (this._driver as CloudStorageDriverContract).getVisibility(this._path);\n }\n\n /**\n * Set storage class (cloud drivers only)\n *\n * @param storageClass - Storage class (e.g., \"STANDARD\", \"GLACIER\")\n * @throws Error if driver doesn't support storage class\n */\n public async setStorageClass(storageClass: string): Promise<this> {\n this.ensureNotDeleted();\n\n if (!(\"setStorageClass\" in this._driver)) {\n throw new Error(\"setStorageClass is only available for cloud storage drivers\");\n }\n\n await (this._driver as CloudStorageDriverContract).setStorageClass(this._path, storageClass);\n return this;\n }\n\n // ============================================================\n // Utilities\n // ============================================================\n\n /**\n * Ensure the file has not been deleted\n */\n protected ensureNotDeleted(): void {\n if (this._deleted) {\n throw new Error(`File \"${this._path}\" has been deleted`);\n }\n }\n\n /**\n * Create a StorageFile instance from StorageFileData\n *\n * @param data - Storage file data from put/copy/move operations\n * @param driver - Driver instance\n */\n public static fromData(\n data: StorageFileData | CloudStorageFileData,\n driver: StorageDriverContract,\n ): StorageFile {\n return new StorageFile(data.path, driver, data);\n }\n\n /**\n * Get file metadata\n */\n public async metadata(): Promise<StorageFileInfo> {\n this.ensureNotDeleted();\n return this._driver.metadata(this._path);\n }\n\n /**\n * Determine if this file is an image type\n */\n public async isImage() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"image/\");\n }\n\n /**\n * Determine if this file is a document type\n */\n public async isDocument() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"application/\");\n }\n\n /**\n * Determine if this file is a pdf type\n */\n public async isPdf() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"application/pdf\");\n }\n\n /**\n * Determine if this file is an excel file (any support excel file)\n */\n public async isExcel() {\n const metadata = await this.metadata();\n return (\n metadata.mimeType!.startsWith(\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n ) || metadata.mimeType!.startsWith(\"application/vnd.ms-excel\")\n );\n }\n\n /**\n * Determine if this file is a doc file\n */\n public async isDoc() {\n const metadata = await this.metadata();\n return (\n metadata.mimeType!.startsWith(\"application/msword\") ||\n metadata.mimeType!.startsWith(\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n )\n );\n }\n\n /**\n * Determine if this file is an audio type\n */\n public async isAudio() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"audio/\");\n }\n\n /**\n * Determine if this file is a video type\n */\n public async isVideo() {\n const metadata = await this.metadata();\n return metadata.mimeType!.startsWith(\"video/\");\n }\n\n /**\n * Convert to plain object (returns cached data or constructs it)\n */\n public toJSON(): {\n path: string;\n name: string;\n extension: string;\n driver: string;\n url: string;\n hash?: string;\n size?: number;\n mimeType?: string;\n } {\n return {\n path: this._path,\n name: this.name,\n extension: this.extension,\n driver: this._driver.name,\n url: this._deleted ? \"\" : this.url,\n hash: this._data?.hash,\n size: this._data?.size,\n mimeType: this._data?.mimeType,\n };\n }\n\n /**\n * String representation\n */\n public toString(): string {\n return this._path;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,cAAb,MAAa,YAAY;;;;;;;;CA4BvB,AAAO,YAAY,MAAc,QAA+B,MAAwB;kBATnE;EAUnB,KAAK,QAAQ;EACb,KAAK,UAAU;EACf,KAAK,QAAQ;CACf;;;;CASA,IAAW,OAAe;EACx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AK,SAAS,EACtB,CAAC,SAAU,WAAW,iBAAiB;CACxD;;;;CAKA,MAAa,UAAU;EACrB,MAAM,WAAW,MAAM,KAAK,SAAS;EACrC,OACE,SAAS,SAAU,WACjB,mEACF,KAAK,SAAS,SAAU,WAAW,0BAA0B;CAEjE;;;;CAKA,MAAa,QAAQ;EACnB,MAAM,WAAW,MAAM,KAAK,SAAS;EACrC,OACE,SAAS,SAAU,WAAW,oBAAoB,KAClD,SAAS,SAAU,WACjB,yEACF;CAEJ;;;;CAKA,MAAa,UAAU;EAErB,QAAO,MADgB,KAAK,SAAS,EACtB,CAAC,SAAU,WAAW,QAAQ;CAC/C;;;;CAKA,MAAa,UAAU;EAErB,QAAO,MADgB,KAAK,SAAS,EACtB,CAAC,SAAU,WAAW,QAAQ;CAC/C;;;;CAKA,AAAO,SASL;EACA,OAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,WAAW,KAAK;GAChB,QAAQ,KAAK,QAAQ;GACrB,KAAK,KAAK,WAAW,KAAK,KAAK;GAC/B,MAAM,KAAK,OAAO;GAClB,MAAM,KAAK,OAAO;GAClB,UAAU,KAAK,OAAO;EACxB;CACF;;;;CAKA,AAAO,WAAmB;EACxB,OAAO,KAAK;CACd;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.d.mts","names":[],"sources":["../../../../../../../core/src/storage/storage.ts"],"mappings":";;;;;;;;;;;AAiFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,OAAA,SAAgB,aAAA,YAAyB,sBAAA;EAgWjD;;;;EAAA,UA3VO,OAAA,EAAO,GAAA,SAAA,qBAAA;EAwbL;;;;EAAA,UAlbF,OAAA,EAAO,GAAA,SAAA,mBAAA;EAqed;;;;EAAA,UA/dO,iBAAA,EAAoB,iBAAA;EAohBqB;;;;EAAA,QA9gB3C,WAAA;EA+jBwC;;;;;;EAgDoB;;;;;EA9lBvD,IAAA,
|
|
1
|
+
{"version":3,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etch.ts"],"sourcesContent":["import { lookup } from \"node:dns/promises\";\nimport { isIP } from \"@warlock.js/seal\";\nimport { StorageError } from \"./storage-error\";\n\n/**\n * SSRF / resource-exhaustion guard for storage's outbound downloads\n * (`putFromUrl`).\n *\n * NOTE: this MIRRORS `@warlock.js/ai`'s `src/security/private-ip.ts` and\n * `src/security/outbound-policy.ts`. It is duplicated here intentionally\n * because `@warlock.js/core` cannot depend on `@warlock.js/ai`. Pending\n * extraction of a shared security package, keep the two copies in sync.\n */\n\n/** 50 MiB — default cap on a downloaded body (storage files run larger than AI payloads). */\nconst DEFAULT_MAX_BYTES = 50 * 1024 * 1024;\n/** 30s — default per-request timeout. */\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * Cap on the number of re-validated redirect hops. Mirrors\n * `@warlock.js/ai`'s `DEFAULT_MAX_REDIRECTS`\n * (ai/src/security/outbound-policy.ts:15).\n */\nconst DEFAULT_MAX_REDIRECTS = 5;\n\n/** 3xx statuses whose `Location` a follow re-issues — mirrors ai/src/security/outbound-policy.ts:18. */\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\n/**\n * Options controlling a guarded outbound fetch. Every field is optional;\n * {@link resolveFetchPolicy} fills safe defaults. The defaults are\n * deliberately strict (https+http, private-IP deny ON, 30s timeout,\n * 50 MiB cap) so a caller that does not tune them still gets a hardened\n * request.\n */\nexport type SafeFetchOptions = {\n /**\n * Whether to ALLOW private / loopback / link-local / metadata hosts.\n * Default `false` — the SSRF guard is on (private hosts are denied).\n */\n allowPrivateHosts?: boolean;\n /**\n * Maximum response body size in bytes. A declared `content-length` over\n * this fails fast; otherwise the body is read with a running cap and the\n * stream is aborted on overflow. Default `52_428_800` (50 MiB).\n */\n maxBytes?: number;\n /** Per-request timeout in milliseconds. Default `30_000`. */\n timeoutMs?: number;\n /**\n * URL schemes permitted for the request, compared case-insensitively.\n * Default `[\"https\", \"http\"]`.\n */\n allowedSchemes?: string[];\n /**\n * Injected `fetch` implementation (for tests or proxies). Defaults to the\n * global `fetch`.\n */\n fetch?: typeof fetch;\n};\n\n/** {@link SafeFetchOptions} with every default resolved — never partial. */\ntype ResolvedFetchPolicy = {\n allowPrivateHosts: boolean;\n maxBytes: number;\n timeoutMs: number;\n allowedSchemes: string[];\n fetch: typeof fetch;\n};\n\n/**\n * Fill a {@link SafeFetchOptions} with strict defaults: https+http,\n * private-IP deny on, 30s timeout, 50 MiB cap, global `fetch`.\n */\nfunction resolveFetchPolicy(options: SafeFetchOptions = {}): ResolvedFetchPolicy {\n return {\n allowPrivateHosts: options.allowPrivateHosts ?? false,\n maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n allowedSchemes: options.allowedSchemes ?? [\"https\", \"http\"],\n fetch: options.fetch ?? globalThis.fetch,\n };\n}\n\n/** Parse a dotted-quad into four octets, or `null` if malformed. */\nfunction parseIpv4(ip: string): [number, number, number, number] | null {\n const parts = ip.split(\".\");\n if (parts.length !== 4) {\n return null;\n }\n\n const octets = parts.map((part) => Number(part));\n if (octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) {\n return null;\n }\n\n return octets as [number, number, number, number];\n}\n\nfunction isPrivateIpv4(ip: string): boolean {\n const octets = parseIpv4(ip);\n if (!octets) {\n return true; // unparseable → refuse, fail closed\n }\n\n const [a, b] = octets;\n\n return (\n a === 0 || // 0.0.0.0/8 \"this network\"\n a === 10 || // 10.0.0.0/8 private\n a === 127 || // 127.0.0.0/8 loopback\n (a === 100 && b >= 64 && b <= 127) || // 100.64.0.0/10 CGNAT\n (a === 169 && b === 254) || // 169.254.0.0/16 link-local + metadata\n (a === 172 && b >= 16 && b <= 31) || // 172.16.0.0/12 private\n (a === 192 && b === 168) || // 192.168.0.0/16 private\n (a === 192 && b === 0) || // 192.0.0.0/24 + 192.0.2.0/24 (IETF/test)\n (a === 198 && (b === 18 || b === 19)) || // 198.18.0.0/15 benchmarking\n (a === 198 && b === 51) || // 198.51.100.0/24 test-net-2\n (a === 203 && b === 0) || // 203.0.113.0/24 test-net-3\n a >= 224 // 224.0.0.0/4 multicast + 240.0.0.0/4 reserved + 255.255.255.255\n );\n}\n\nfunction isPrivateIpv6(ip: string): boolean {\n const normalized = ip.toLowerCase().split(\"%\")[0]; // drop zone id\n\n // IPv4-mapped / -embedded (::ffff:a.b.c.d, ::a.b.c.d) — defer to the v4\n // check on the trailing dotted-quad so an inward-mapped address is caught.\n const v4 = normalized.match(/(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$/);\n if (v4) {\n return isPrivateIpv4(v4[1]);\n }\n\n if (normalized === \"::1\" || normalized === \"::\") {\n return true; // loopback / unspecified\n }\n\n // Expand only the leading group enough to classify the reserved blocks.\n const firstGroup = normalized.split(\":\")[0];\n const head = firstGroup === \"\" ? 0 : Number.parseInt(firstGroup, 16);\n\n // fc00::/7 unique-local (fc.. / fd..)\n if ((head & 0xfe00) === 0xfc00) {\n return true;\n }\n // fe80::/10 link-local\n if ((head & 0xffc0) === 0xfe80) {\n return true;\n }\n\n return false;\n}\n\n/**\n * True when `ip` is a private, loopback, link-local, unique-local,\n * carrier-grade-NAT, unspecified, or otherwise non-public address — the set\n * an SSRF guard must refuse. Accepts IPv4 and IPv6 literals (including\n * IPv4-mapped IPv6 like `::ffff:169.254.169.254`). A non-IP string returns\n * `false` (the caller resolves hostnames via DNS first).\n *\n * The cloud-metadata endpoint `169.254.169.254` is covered by the IPv4\n * link-local range `169.254.0.0/16`.\n */\nexport function isPrivateOrReservedIp(ip: string): boolean {\n const family = isIP(ip);\n if (family === 4) {\n return isPrivateIpv4(ip);\n }\n if (family === 6) {\n return isPrivateIpv6(ip);\n }\n return false;\n}\n\n/** Strip the `[ ]` IPv6 brackets `URL.hostname` keeps. */\nfunction stripBrackets(host: string): string {\n return host.startsWith(\"[\") && host.endsWith(\"]\") ? host.slice(1, -1) : host;\n}\n\n/**\n * Reject when `host` is — or resolves to — a private / reserved address.\n * IP literals are checked directly; hostnames are resolved via DNS and every\n * returned address is checked (a public name pointing inward is caught). A\n * resolution failure fails closed.\n */\nasync function assertHostNotPrivate(host: string, rawUrl: string): Promise<void> {\n if (isIP(host) !== 0) {\n if (isPrivateOrReservedIp(host)) {\n throw new StorageError(\n `outbound request blocked — \"${host}\" is a private/reserved address`,\n { context: { url: rawUrl, address: host } },\n );\n }\n return;\n }\n\n let addresses: Array<{ address: string }>;\n try {\n addresses = await lookup(host, { all: true });\n } catch (cause) {\n throw new StorageError(\n `outbound request blocked — could not resolve host \"${host}\" to verify it is public`,\n { cause, context: { url: rawUrl, host } },\n );\n }\n\n for (const { address } of addresses) {\n if (isPrivateOrReservedIp(address)) {\n throw new StorageError(\n `outbound request blocked — host \"${host}\" resolves to a private/reserved address (${address})`,\n { context: { url: rawUrl, host, address } },\n );\n }\n }\n}\n\n/**\n * Validate a URL against the policy BEFORE any network call: scheme\n * allowlist and (when private hosts are not allowed) a DNS resolution that\n * rejects private / loopback / link-local / metadata addresses — the SSRF\n * guard. Returns the parsed `URL` on success; throws {@link StorageError}\n * otherwise.\n */\nasync function assertUrlAllowed(rawUrl: string, policy: ResolvedFetchPolicy): Promise<URL> {\n let url: URL;\n try {\n url = new URL(rawUrl);\n } catch {\n throw new StorageError(`outbound request blocked — invalid URL: ${rawUrl}`, {\n context: { url: rawUrl },\n });\n }\n\n const scheme = url.protocol.replace(/:$/, \"\").toLowerCase();\n if (!policy.allowedSchemes.some((s) => s.toLowerCase() === scheme)) {\n throw new StorageError(\n `outbound request blocked — scheme \"${scheme}\" is not allowed (allowed: ${policy.allowedSchemes.join(\", \")})`,\n { context: { url: rawUrl, scheme } },\n );\n }\n\n if (!policy.allowPrivateHosts) {\n const host = stripBrackets(url.hostname);\n await assertHostNotPrivate(host, rawUrl);\n }\n\n return url;\n}\n\n/**\n * Result of {@link safeFetchToBuffer}: the (capped) body plus the response's\n * content-type, so callers can derive a MIME type and enforce a non-empty\n * content-type check.\n */\nexport type SafeFetchResult = {\n buffer: Buffer;\n contentType: string | null;\n status: number;\n statusText: string;\n ok: boolean;\n};\n\n/**\n * SSRF-guarded download: validates the URL (scheme allowlist + post-DNS\n * private-IP deny), performs the request with a timeout via\n * `AbortController`, then streams the body with a hard byte cap — aborting\n * the moment the running total exceeds `maxBytes`. A declared\n * `content-length` over the cap fails fast.\n *\n * Redirects are NEVER delegated to the platform: every hop is issued with\n * `redirect: \"manual\"` and its `Location` is re-run through\n * {@link assertUrlAllowed} — including the DNS-resolution private-IP check\n * — before being followed (capped at {@link DEFAULT_MAX_REDIRECTS}), so a\n * 3xx from an allowed host cannot smuggle the request to a private /\n * metadata target. Mirrors `@warlock.js/ai`'s `guardedFetch`\n * (ai/src/security/outbound-policy.ts:188-284); duplicated per this\n * module's file-header note since core cannot depend on ai.\n *\n * @throws {StorageError} On a blocked URL (initial or redirect target),\n * a redirect-hop bound overflow, timeout, or oversized body.\n */\nexport async function safeFetchToBuffer(\n rawUrl: string,\n options: SafeFetchOptions = {},\n): Promise<SafeFetchResult> {\n const policy = resolveFetchPolicy(options);\n let url = await assertUrlAllowed(rawUrl, policy);\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort(\n new StorageError(`outbound request timed out after ${policy.timeoutMs}ms`, {\n context: { url: rawUrl, timeoutMs: policy.timeoutMs },\n }),\n );\n }, policy.timeoutMs);\n\n try {\n let response: Response;\n\n for (let hop = 0; ; hop++) {\n response = await policy.fetch(url, { signal: controller.signal, redirect: \"manual\" });\n\n const location = response.headers.get(\"location\");\n if (!REDIRECT_STATUSES.has(response.status) || location === null) {\n break;\n }\n\n if (hop >= DEFAULT_MAX_REDIRECTS) {\n throw new StorageError(\n `outbound request blocked — more than ${DEFAULT_MAX_REDIRECTS} redirects`,\n { context: { url: rawUrl, maxRedirects: DEFAULT_MAX_REDIRECTS } },\n );\n }\n\n let target: URL;\n try {\n target = new URL(location, url);\n } catch {\n throw new StorageError(`outbound request blocked — invalid redirect Location: ${location}`, {\n context: { url: url.toString(), location },\n });\n }\n\n // Discard the interim body so the connection can be reused.\n if (response.body) {\n await response.body.cancel().catch(() => undefined);\n }\n\n // The redirect target gets the SAME scheme + private-IP validation\n // (incl. DNS resolution) as the initial URL — this is what closes\n // the redirect-based SSRF bypass: a 302 from an allowed host to\n // 169.254.169.254 is re-validated here, not blindly followed.\n url = await assertUrlAllowed(target.toString(), policy);\n }\n\n const declared = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > policy.maxBytes) {\n throw new StorageError(\n `outbound response body too large — declared ${declared} bytes exceeds the ${policy.maxBytes}-byte cap`,\n { context: { url: rawUrl, declared, maxBytes: policy.maxBytes } },\n );\n }\n\n const buffer = await readBodyCapped(response, policy.maxBytes, rawUrl);\n\n return {\n buffer,\n contentType: response.headers.get(\"content-type\"),\n status: response.status,\n statusText: response.statusText,\n ok: response.ok,\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Read a response body into a Buffer with a hard byte cap. The stream is\n * read chunk-by-chunk and cancelled the moment the running total exceeds\n * `maxBytes`. Throws {@link StorageError} on overflow.\n */\nasync function readBodyCapped(\n response: Response,\n maxBytes: number,\n rawUrl: string,\n): Promise<Buffer> {\n if (!response.body) {\n const arrayBuffer = await response.arrayBuffer();\n if (arrayBuffer.byteLength > maxBytes) {\n throw new StorageError(\n `outbound response body exceeded the ${maxBytes}-byte cap`,\n { context: { url: rawUrl, maxBytes } },\n );\n }\n return Buffer.from(arrayBuffer);\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (!value) {\n continue;\n }\n\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw new StorageError(\n `outbound response body exceeded the ${maxBytes}-byte cap`,\n { context: { url: rawUrl, maxBytes } },\n );\n }\n chunks.push(value);\n }\n\n return Buffer.concat(chunks);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA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E,KAAK;IAAQ;GAAS,EAAE,CACvC;EACF;EACA,OAAO,KAAK,KAAK;CACnB;CAEA,OAAO,OAAO,OAAO,MAAM;AAC7B"}
|
|
1
|
+
{"version":3,"file":"safe-fetch.mjs","names":[],"sources":["../../../../../../../../core/src/storage/utils/safe-fetch.ts"],"sourcesContent":["import { lookup } from \"node:dns/promises\";\nimport { isIP } from \"@warlock.js/seal\";\nimport { StorageError } from \"./storage-error\";\n\n/**\n * SSRF / resource-exhaustion guard for storage's outbound downloads\n * (`putFromUrl`).\n *\n * NOTE: this MIRRORS `@warlock.js/ai`'s `src/security/private-ip.ts` and\n * `src/security/outbound-policy.ts`. It is duplicated here intentionally\n * because `@warlock.js/core` cannot depend on `@warlock.js/ai`. Pending\n * extraction of a shared security package, keep the two copies in sync.\n */\n\n/** 50 MiB — default cap on a downloaded body (storage files run larger than AI payloads). */\nconst DEFAULT_MAX_BYTES = 50 * 1024 * 1024;\n/** 30s — default per-request timeout. */\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * Cap on the number of re-validated redirect hops. Mirrors\n * `@warlock.js/ai`'s `DEFAULT_MAX_REDIRECTS`\n * (ai/src/security/outbound-policy.ts:15).\n */\nconst DEFAULT_MAX_REDIRECTS = 5;\n\n/** 3xx statuses whose `Location` a follow re-issues — mirrors ai/src/security/outbound-policy.ts:18. */\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\n/**\n * Options controlling a guarded outbound fetch. Every field is optional;\n * {@link resolveFetchPolicy} fills safe defaults. The defaults are\n * deliberately strict (https+http, private-IP deny ON, 30s timeout,\n * 50 MiB cap) so a caller that does not tune them still gets a hardened\n * request.\n */\nexport type SafeFetchOptions = {\n /**\n * Whether to ALLOW private / loopback / link-local / metadata hosts.\n * Default `false` — the SSRF guard is on (private hosts are denied).\n */\n allowPrivateHosts?: boolean;\n /**\n * Maximum response body size in bytes. A declared `content-length` over\n * this fails fast; otherwise the body is read with a running cap and the\n * stream is aborted on overflow. Default `52_428_800` (50 MiB).\n */\n maxBytes?: number;\n /** Per-request timeout in milliseconds. Default `30_000`. */\n timeoutMs?: number;\n /**\n * URL schemes permitted for the request, compared case-insensitively.\n * Default `[\"https\", \"http\"]`.\n */\n allowedSchemes?: string[];\n /**\n * Injected `fetch` implementation (for tests or proxies). Defaults to the\n * global `fetch`.\n */\n fetch?: typeof fetch;\n};\n\n/** {@link SafeFetchOptions} with every default resolved — never partial. */\ntype ResolvedFetchPolicy = {\n allowPrivateHosts: boolean;\n maxBytes: number;\n timeoutMs: number;\n allowedSchemes: string[];\n fetch: typeof fetch;\n};\n\n/**\n * Fill a {@link SafeFetchOptions} with strict defaults: https+http,\n * private-IP deny on, 30s timeout, 50 MiB cap, global `fetch`.\n */\nfunction resolveFetchPolicy(options: SafeFetchOptions = {}): ResolvedFetchPolicy {\n return {\n allowPrivateHosts: options.allowPrivateHosts ?? false,\n maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n allowedSchemes: options.allowedSchemes ?? [\"https\", \"http\"],\n fetch: options.fetch ?? globalThis.fetch,\n };\n}\n\n/** Parse a dotted-quad into four octets, or `null` if malformed. */\nfunction parseIpv4(ip: string): [number, number, number, number] | null {\n const parts = ip.split(\".\");\n if (parts.length !== 4) {\n return null;\n }\n\n const octets = parts.map((part) => Number(part));\n if (octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) {\n return null;\n }\n\n return octets as [number, number, number, number];\n}\n\nfunction isPrivateIpv4(ip: string): boolean {\n const octets = parseIpv4(ip);\n if (!octets) {\n return true; // unparseable → refuse, fail closed\n }\n\n const [a, b] = octets;\n\n return (\n a === 0 || // 0.0.0.0/8 \"this network\"\n a === 10 || // 10.0.0.0/8 private\n a === 127 || // 127.0.0.0/8 loopback\n (a === 100 && b >= 64 && b <= 127) || // 100.64.0.0/10 CGNAT\n (a === 169 && b === 254) || // 169.254.0.0/16 link-local + metadata\n (a === 172 && b >= 16 && b <= 31) || // 172.16.0.0/12 private\n (a === 192 && b === 168) || // 192.168.0.0/16 private\n (a === 192 && b === 0) || // 192.0.0.0/24 + 192.0.2.0/24 (IETF/test)\n (a === 198 && (b === 18 || b === 19)) || // 198.18.0.0/15 benchmarking\n (a === 198 && b === 51) || // 198.51.100.0/24 test-net-2\n (a === 203 && b === 0) || // 203.0.113.0/24 test-net-3\n a >= 224 // 224.0.0.0/4 multicast + 240.0.0.0/4 reserved + 255.255.255.255\n );\n}\n\nfunction isPrivateIpv6(ip: string): boolean {\n const normalized = ip.toLowerCase().split(\"%\")[0]; // drop zone id\n\n // IPv4-mapped / -embedded (::ffff:a.b.c.d, ::a.b.c.d) — defer to the v4\n // check on the trailing dotted-quad so an inward-mapped address is caught.\n const v4 = normalized.match(/(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$/);\n if (v4) {\n return isPrivateIpv4(v4[1]);\n }\n\n if (normalized === \"::1\" || normalized === \"::\") {\n return true; // loopback / unspecified\n }\n\n // Expand only the leading group enough to classify the reserved blocks.\n const firstGroup = normalized.split(\":\")[0];\n const head = firstGroup === \"\" ? 0 : Number.parseInt(firstGroup, 16);\n\n // fc00::/7 unique-local (fc.. / fd..)\n if ((head & 0xfe00) === 0xfc00) {\n return true;\n }\n // fe80::/10 link-local\n if ((head & 0xffc0) === 0xfe80) {\n return true;\n }\n\n return false;\n}\n\n/**\n * True when `ip` is a private, loopback, link-local, unique-local,\n * carrier-grade-NAT, unspecified, or otherwise non-public address — the set\n * an SSRF guard must refuse. Accepts IPv4 and IPv6 literals (including\n * IPv4-mapped IPv6 like `::ffff:169.254.169.254`). A non-IP string returns\n * `false` (the caller resolves hostnames via DNS first).\n *\n * The cloud-metadata endpoint `169.254.169.254` is covered by the IPv4\n * link-local range `169.254.0.0/16`.\n */\nexport function isPrivateOrReservedIp(ip: string): boolean {\n const family = isIP(ip);\n if (family === 4) {\n return isPrivateIpv4(ip);\n }\n if (family === 6) {\n return isPrivateIpv6(ip);\n }\n return false;\n}\n\n/** Strip the `[ ]` IPv6 brackets `URL.hostname` keeps. */\nfunction stripBrackets(host: string): string {\n return host.startsWith(\"[\") && host.endsWith(\"]\") ? host.slice(1, -1) : host;\n}\n\n/**\n * Reject when `host` is — or resolves to — a private / reserved address.\n * IP literals are checked directly; hostnames are resolved via DNS and every\n * returned address is checked (a public name pointing inward is caught). A\n * resolution failure fails closed.\n */\nasync function assertHostNotPrivate(host: string, rawUrl: string): Promise<void> {\n if (isIP(host) !== 0) {\n if (isPrivateOrReservedIp(host)) {\n throw new StorageError(\n `outbound request blocked — \"${host}\" is a private/reserved address`,\n { context: { url: rawUrl, address: host } },\n );\n }\n return;\n }\n\n let addresses: Array<{ address: string }>;\n try {\n addresses = await lookup(host, { all: true });\n } catch (cause) {\n throw new StorageError(\n `outbound request blocked — could not resolve host \"${host}\" to verify it is public`,\n { cause, context: { url: rawUrl, host } },\n );\n }\n\n for (const { address } of addresses) {\n if (isPrivateOrReservedIp(address)) {\n throw new StorageError(\n `outbound request blocked — host \"${host}\" resolves to a private/reserved address (${address})`,\n { context: { url: rawUrl, host, address } },\n );\n }\n }\n}\n\n/**\n * Validate a URL against the policy BEFORE any network call: scheme\n * allowlist and (when private hosts are not allowed) a DNS resolution that\n * rejects private / loopback / link-local / metadata addresses — the SSRF\n * guard. Returns the parsed `URL` on success; throws {@link StorageError}\n * otherwise.\n */\nasync function assertUrlAllowed(rawUrl: string, policy: ResolvedFetchPolicy): Promise<URL> {\n let url: URL;\n try {\n url = new URL(rawUrl);\n } catch {\n throw new StorageError(`outbound request blocked — invalid URL: ${rawUrl}`, {\n context: { url: rawUrl },\n });\n }\n\n const scheme = url.protocol.replace(/:$/, \"\").toLowerCase();\n if (!policy.allowedSchemes.some((s) => s.toLowerCase() === scheme)) {\n throw new StorageError(\n `outbound request blocked — scheme \"${scheme}\" is not allowed (allowed: ${policy.allowedSchemes.join(\", \")})`,\n { context: { url: rawUrl, scheme } },\n );\n }\n\n if (!policy.allowPrivateHosts) {\n const host = stripBrackets(url.hostname);\n await assertHostNotPrivate(host, rawUrl);\n }\n\n return url;\n}\n\n/**\n * Result of {@link safeFetchToBuffer}: the (capped) body plus the response's\n * content-type, so callers can derive a MIME type and enforce a non-empty\n * content-type check.\n */\nexport type SafeFetchResult = {\n buffer: Buffer;\n contentType: string | null;\n status: number;\n statusText: string;\n ok: boolean;\n};\n\n/**\n * SSRF-guarded download: validates the URL (scheme allowlist + post-DNS\n * private-IP deny), performs the request with a timeout via\n * `AbortController`, then streams the body with a hard byte cap — aborting\n * the moment the running total exceeds `maxBytes`. A declared\n * `content-length` over the cap fails fast.\n *\n * Redirects are NEVER delegated to the platform: every hop is issued with\n * `redirect: \"manual\"` and its `Location` is re-run through\n * {@link assertUrlAllowed} — including the DNS-resolution private-IP check\n * — before being followed (capped at {@link DEFAULT_MAX_REDIRECTS}), so a\n * 3xx from an allowed host cannot smuggle the request to a private /\n * metadata target. Mirrors `@warlock.js/ai`'s `guardedFetch`\n * (ai/src/security/outbound-policy.ts:188-284); duplicated per this\n * module's file-header note since core cannot depend on ai.\n *\n * @throws {StorageError} On a blocked URL (initial or redirect target),\n * a redirect-hop bound overflow, timeout, or oversized body.\n */\nexport async function safeFetchToBuffer(\n rawUrl: string,\n options: SafeFetchOptions = {},\n): Promise<SafeFetchResult> {\n const policy = resolveFetchPolicy(options);\n let url = await assertUrlAllowed(rawUrl, policy);\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort(\n new StorageError(`outbound request timed out after ${policy.timeoutMs}ms`, {\n context: { url: rawUrl, timeoutMs: policy.timeoutMs },\n }),\n );\n }, policy.timeoutMs);\n\n try {\n let response: Response;\n\n for (let hop = 0; ; hop++) {\n response = await policy.fetch(url, { signal: controller.signal, redirect: \"manual\" });\n\n const location = response.headers.get(\"location\");\n if (!REDIRECT_STATUSES.has(response.status) || location === null) {\n break;\n }\n\n if (hop >= DEFAULT_MAX_REDIRECTS) {\n throw new StorageError(\n `outbound request blocked — more than ${DEFAULT_MAX_REDIRECTS} redirects`,\n { context: { url: rawUrl, maxRedirects: DEFAULT_MAX_REDIRECTS } },\n );\n }\n\n let target: URL;\n try {\n target = new URL(location, url);\n } catch {\n throw new StorageError(`outbound request blocked — invalid redirect Location: ${location}`, {\n context: { url: url.toString(), location },\n });\n }\n\n // Discard the interim body so the connection can be reused.\n if (response.body) {\n await response.body.cancel().catch(() => undefined);\n }\n\n // The redirect target gets the SAME scheme + private-IP validation\n // (incl. DNS resolution) as the initial URL — this is what closes\n // the redirect-based SSRF bypass: a 302 from an allowed host to\n // 169.254.169.254 is re-validated here, not blindly followed.\n url = await assertUrlAllowed(target.toString(), policy);\n }\n\n const declared = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > policy.maxBytes) {\n throw new StorageError(\n `outbound response body too large — declared ${declared} bytes exceeds the ${policy.maxBytes}-byte cap`,\n { context: { url: rawUrl, declared, maxBytes: policy.maxBytes } },\n );\n }\n\n const buffer = await readBodyCapped(response, policy.maxBytes, rawUrl);\n\n return {\n buffer,\n contentType: response.headers.get(\"content-type\"),\n status: response.status,\n statusText: response.statusText,\n ok: response.ok,\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Read a response body into a Buffer with a hard byte cap. The stream is\n * read chunk-by-chunk and cancelled the moment the running total exceeds\n * `maxBytes`. Throws {@link StorageError} on overflow.\n */\nasync function readBodyCapped(\n response: Response,\n maxBytes: number,\n rawUrl: string,\n): Promise<Buffer> {\n if (!response.body) {\n const arrayBuffer = await response.arrayBuffer();\n if (arrayBuffer.byteLength > maxBytes) {\n throw new StorageError(\n `outbound response body exceeded the ${maxBytes}-byte cap`,\n { context: { url: rawUrl, maxBytes } },\n );\n }\n return Buffer.from(arrayBuffer);\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (!value) {\n continue;\n }\n\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw new StorageError(\n `outbound response body exceeded the ${maxBytes}-byte cap`,\n { context: { url: rawUrl, maxBytes } },\n );\n }\n chunks.push(value);\n }\n\n return Buffer.concat(chunks);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAM,oBAAoB,KAAK,OAAO;;AAEtC,MAAM,qBAAqB;;;;;;AAM3B,MAAM,wBAAwB;;AAG9B,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;;;;;AAgD3D,SAAS,mBAAmB,UAA4B,CAAC,GAAwB;CAC/E,OAAO;EACL,mBAAmB,QAAQ,qBAAqB;EAChD,UAAU,QAAQ,YAAY;EAC9B,WAAW,QAAQ,aAAa;EAChC,gBAAgB,QAAQ,kBAAkB,CAAC,SAAS,MAAM;EAC1D,OAAO,QAAQ,SAAS,WAAW;CACrC;AACF;;AAGA,SAAS,UAAU,IAAqD;CACtE,MAAM,QAAQ,GAAG,MAAM,GAAG;CAC1B,IAAI,MAAM,WAAW,GACnB,OAAO;CAGT,MAAM,SAAS,MAAM,KAAK,SAAS,OAAO,IAAI,CAAC;CAC/C,IAAI,OAAO,MAAM,MAAM,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,KAAK,IAAI,GAAG,GAC7D,OAAO;CAGT,OAAO;AACT;AAEA,SAAS,cAAc,IAAqB;CAC1C,MAAM,SAAS,UAAU,EAAE;CAC3B,IAAI,CAAC,QACH,OAAO;CAGT,MAAM,CAAC,GAAG,KAAK;CAEf,OACE,MAAM,KACN,MAAM,MACN,MAAM,OACL,MAAM,OAAO,KAAK,MAAM,KAAK,OAC7B,MAAM,OAAO,MAAM,OACnB,MAAM,OAAO,KAAK,MAAM,KAAK,MAC7B,MAAM,OAAO,MAAM,OACnB,MAAM,OAAO,MAAM,KACnB,MAAM,QAAQ,MAAM,MAAM,MAAM,OAChC,MAAM,OAAO,MAAM,MACnB,MAAM,OAAO,MAAM,KACpB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ACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;EAC1C,IAAI,MACF;EAEF,IAAI,CAAC,OACH;EAGF,SAAS,MAAM;EACf,IAAI,QAAQ,UAAU;GACpB,MAAM,OAAO,OAAO;GACpB,MAAM,IAAI,aACR,uCAAuC,SAAS,YAChD,EAAE,SAAS;IAAE,KAAK;IAAQ;GAAS,EAAE,CACvC;EACF;EACA,OAAO,KAAK,KAAK;CACnB;CAEA,OAAO,OAAO,OAAO,MAAM;AAC7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-http-development-server.d.mts","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"mappings":";KAwBY,0BAAA;EAAA;;;;AAON;AA4EN;EA5EE,IAAI;AAAA;;;;;;AA8EI;AAoFV;;iBAtFsB,mBAAA,CACpB,OAAA,GAAS,0BAAA,GACR,OAAO;;AAoFyC;AA6BnD;;iBA7BsB,kBAAA,
|
|
1
|
+
{"version":3,"file":"start-http-development-server.d.mts","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"mappings":";KAwBY,0BAAA;EAAA;;;;AAON;AA4EN;EA5EE,IAAI;AAAA;;;;;;AA8EI;AAoFV;;iBAtFsB,mBAAA,CACpB,OAAA,GAAS,0BAAA,GACR,OAAO;;AAoFyC;AA6BnD;;iBA7BsB,kBAAA,IAAsB,OAAO;;AA6BhB;;iBAAnB,mBAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-connectors-selection.mjs","names":[],"sources":["../../../../../../../core/src/tests/test-connectors-selection.ts"],"sourcesContent":["/**\n * Effective connector selection for the worker test lifecycle.\n *\n * Owns one decision: given what the caller passed and what the project\n * configured, which connectors does `setupTest` actually start? The precedence\n * is ratified in `contracts/2026-08-12-test-worker-lifecycle.md`:\n *\n * explicit non-`undefined` setupTest option > tests.connectors config > true\n */\nimport type { GenericObject } from \"@mongez/reinforcements\";\nimport { config } from \"../config\";\nimport type { ConnectorName } from \"../connectors\";\n\n/**\n * What a test runtime was asked to start.\n *\n * - `false` — bootstrap the runtime, start no connectors.\n * - `true` — start the framework's default connector set.\n * - an array — start exactly those. Order is not promised; lifecycle priority\n * decides the real boot/shutdown order.\n */\nexport type TestConnectorsSelection = boolean | ConnectorName[];\n\n/**\n * A caller's request, before the lower precedence layers are consulted.\n *\n * The distinction that matters is \"did the caller supply a value at all\", not\n * \"what value\" — `setupTest({ connectors: undefined })` must fall through to\n * project config exactly like `setupTest()` does, so an optional variable\n * holding `undefined` can never silently erase a project's configuration.\n */\nexport type RequestedTestConnectors =\n | { readonly isExplicit: true; readonly selection: TestConnectorsSelection }\n | { readonly isExplicit: false };\n\n/**\n * Classify the caller's `connectors` option as explicit or deferred.\n */\nexport function readRequestedConnectors(\n selection: TestConnectorsSelection | undefined,\n): RequestedTestConnectors {\n if (selection === undefined) {\n return { isExplicit: false };\n }\n\n return { isExplicit: true, selection };\n}\n\n/**\n * Read the `tests.connectors` config layer, or `undefined` when the project has\n * not configured one.\n *\n * Only meaningful once config files are loaded — before that, every project\n * looks like a project without a `tests` config.\n */\nexport function readConfiguredConnectors(): TestConnectorsSelection | undefined {\n // The default matters: `config.get` resolves an absent key to its default, and\n // ITS default is `null` — not `{}`. `warlock add test` does not generate\n // `src/config/tests.ts`, so reading `.connectors` off the result threw\n // \"Cannot read properties of null\" on the generated default path.\n const testsConfig = config.get<GenericObject>(\"tests\", {});\n\n // Cast at the config boundary: `GenericObject` values are untyped, and this is\n // the one place the untyped value becomes a typed selection.\n return testsConfig?.connectors as TestConnectorsSelection | undefined;\n}\n\n/**\n * Apply the ratified precedence:\n *\n * explicit non-`undefined` setupTest option > tests.connectors config > true\n *\n * ⚠ This is the reverse of 4.13, where config won over the parameter. Explicit\n * call-site intent beats a project default; a call that supplied nothing is not\n * intent, which is why \"omitted\" and \"explicitly `undefined`\" both defer.\n */\nexport function resolveEffectiveConnectors(\n requested: RequestedTestConnectors,\n): TestConnectorsSelection {\n if (requested.isExplicit) {\n return requested.selection;\n }\n\n const configured = readConfiguredConnectors();\n\n if (configured !== undefined) {\n return configured;\n }\n\n return true;\n}\n\n/**\n * Deduplicate a connector list and put it in a stable order.\n *\n * Two callers naming the same connectors in a different order asked for the same\n * thing, so the lifecycle must not treat them as a conflict.\n */\nexport function normalizeConnectorNames(names: ConnectorName[]): ConnectorName[] {\n return [...new Set(names)].sort();\n}\n\n/**\n * Compare two selections by normalized semantics — arrays as deduplicated sets,\n * never by caller order.\n */\nexport function isSameConnectorsSelection(\n left: TestConnectorsSelection,\n right: TestConnectorsSelection,\n): boolean {\n if (Array.isArray(left) && Array.isArray(right)) {\n const normalizedLeft = normalizeConnectorNames(left);\n const normalizedRight = normalizeConnectorNames(right);\n\n return (\n normalizedLeft.length === normalizedRight.length &&\n normalizedLeft.every((name, index) => name === normalizedRight[index])\n );\n }\n\n return left === right;\n}\n\n/**\n * Render a selection for an error message a caller can act on.\n */\nexport function describeConnectorsSelection(selection: TestConnectorsSelection): string {\n if (selection === true) {\n return \"the default connector set (`connectors: true`)\";\n }\n\n if (selection === false) {\n return \"no connectors (`connectors: false`)\";\n }\n\n const names = normalizeConnectorNames(selection)\n .map((name) => `\"${name}\"`)\n .join(\", \");\n\n return `\\`connectors: [${names}]\\``;\n}\n"],"mappings":";;;;;;;AAsCA,SAAgB,wBACd,WACyB;CACzB,IAAI,cAAc,QAChB,OAAO,EAAE,YAAY,MAAM;CAG7B,OAAO;EAAE,YAAY;EAAM;CAAU;AACvC;;;;;;;;AASA,SAAgB,2BAAgE;CAS9E,OAJoB,OAAO,IAAmB,SAAS,CAAC,CAIvC,
|
|
1
|
+
{"version":3,"file":"test-connectors-selection.mjs","names":[],"sources":["../../../../../../../core/src/tests/test-connectors-selection.ts"],"sourcesContent":["/**\n * Effective connector selection for the worker test lifecycle.\n *\n * Owns one decision: given what the caller passed and what the project\n * configured, which connectors does `setupTest` actually start? The precedence\n * is ratified in `contracts/2026-08-12-test-worker-lifecycle.md`:\n *\n * explicit non-`undefined` setupTest option > tests.connectors config > true\n */\nimport type { GenericObject } from \"@mongez/reinforcements\";\nimport { config } from \"../config\";\nimport type { ConnectorName } from \"../connectors\";\n\n/**\n * What a test runtime was asked to start.\n *\n * - `false` — bootstrap the runtime, start no connectors.\n * - `true` — start the framework's default connector set.\n * - an array — start exactly those. Order is not promised; lifecycle priority\n * decides the real boot/shutdown order.\n */\nexport type TestConnectorsSelection = boolean | ConnectorName[];\n\n/**\n * A caller's request, before the lower precedence layers are consulted.\n *\n * The distinction that matters is \"did the caller supply a value at all\", not\n * \"what value\" — `setupTest({ connectors: undefined })` must fall through to\n * project config exactly like `setupTest()` does, so an optional variable\n * holding `undefined` can never silently erase a project's configuration.\n */\nexport type RequestedTestConnectors =\n | { readonly isExplicit: true; readonly selection: TestConnectorsSelection }\n | { readonly isExplicit: false };\n\n/**\n * Classify the caller's `connectors` option as explicit or deferred.\n */\nexport function readRequestedConnectors(\n selection: TestConnectorsSelection | undefined,\n): RequestedTestConnectors {\n if (selection === undefined) {\n return { isExplicit: false };\n }\n\n return { isExplicit: true, selection };\n}\n\n/**\n * Read the `tests.connectors` config layer, or `undefined` when the project has\n * not configured one.\n *\n * Only meaningful once config files are loaded — before that, every project\n * looks like a project without a `tests` config.\n */\nexport function readConfiguredConnectors(): TestConnectorsSelection | undefined {\n // The default matters: `config.get` resolves an absent key to its default, and\n // ITS default is `null` — not `{}`. `warlock add test` does not generate\n // `src/config/tests.ts`, so reading `.connectors` off the result threw\n // \"Cannot read properties of null\" on the generated default path.\n const testsConfig = config.get<GenericObject>(\"tests\", {});\n\n // Cast at the config boundary: `GenericObject` values are untyped, and this is\n // the one place the untyped value becomes a typed selection.\n return testsConfig?.connectors as TestConnectorsSelection | undefined;\n}\n\n/**\n * Apply the ratified precedence:\n *\n * explicit non-`undefined` setupTest option > tests.connectors config > true\n *\n * ⚠ This is the reverse of 4.13, where config won over the parameter. Explicit\n * call-site intent beats a project default; a call that supplied nothing is not\n * intent, which is why \"omitted\" and \"explicitly `undefined`\" both defer.\n */\nexport function resolveEffectiveConnectors(\n requested: RequestedTestConnectors,\n): TestConnectorsSelection {\n if (requested.isExplicit) {\n return requested.selection;\n }\n\n const configured = readConfiguredConnectors();\n\n if (configured !== undefined) {\n return configured;\n }\n\n return true;\n}\n\n/**\n * Deduplicate a connector list and put it in a stable order.\n *\n * Two callers naming the same connectors in a different order asked for the same\n * thing, so the lifecycle must not treat them as a conflict.\n */\nexport function normalizeConnectorNames(names: ConnectorName[]): ConnectorName[] {\n return [...new Set(names)].sort();\n}\n\n/**\n * Compare two selections by normalized semantics — arrays as deduplicated sets,\n * never by caller order.\n */\nexport function isSameConnectorsSelection(\n left: TestConnectorsSelection,\n right: TestConnectorsSelection,\n): boolean {\n if (Array.isArray(left) && Array.isArray(right)) {\n const normalizedLeft = normalizeConnectorNames(left);\n const normalizedRight = normalizeConnectorNames(right);\n\n return (\n normalizedLeft.length === normalizedRight.length &&\n normalizedLeft.every((name, index) => name === normalizedRight[index])\n );\n }\n\n return left === right;\n}\n\n/**\n * Render a selection for an error message a caller can act on.\n */\nexport function describeConnectorsSelection(selection: TestConnectorsSelection): string {\n if (selection === true) {\n return \"the default connector set (`connectors: true`)\";\n }\n\n if (selection === false) {\n return \"no connectors (`connectors: false`)\";\n }\n\n const names = normalizeConnectorNames(selection)\n .map((name) => `\"${name}\"`)\n .join(\", \");\n\n return `\\`connectors: [${names}]\\``;\n}\n"],"mappings":";;;;;;;AAsCA,SAAgB,wBACd,WACyB;CACzB,IAAI,cAAc,QAChB,OAAO,EAAE,YAAY,MAAM;CAG7B,OAAO;EAAE,YAAY;EAAM;CAAU;AACvC;;;;;;;;AASA,SAAgB,2BAAgE;CAS9E,OAJoB,OAAO,IAAmB,SAAS,CAAC,CAIvC,CAAC,EAAE;AACtB;;;;;;;;;;AAWA,SAAgB,2BACd,WACyB;CACzB,IAAI,UAAU,YACZ,OAAO,UAAU;CAGnB,MAAM,aAAa,yBAAyB;CAE5C,IAAI,eAAe,QACjB,OAAO;CAGT,OAAO;AACT;;;;;;;AAQA,SAAgB,wBAAwB,OAAyC;CAC/E,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK;AAClC;;;;;AAMA,SAAgB,0BACd,MACA,OACS;CACT,IAAI,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,KAAK,GAAG;EAC/C,MAAM,iBAAiB,wBAAwB,IAAI;EACnD,MAAM,kBAAkB,wBAAwB,KAAK;EAErD,OACE,eAAe,WAAW,gBAAgB,UAC1C,eAAe,OAAO,MAAM,UAAU,SAAS,gBAAgB,MAAM;CAEzE;CAEA,OAAO,SAAS;AAClB;;;;AAKA,SAAgB,4BAA4B,WAA4C;CACtF,IAAI,cAAc,MAChB,OAAO;CAGT,IAAI,cAAc,OAChB,OAAO;CAOT,OAAO,kBAJO,wBAAwB,SAAS,CAAC,CAC7C,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAC1B,KAAK,IAEqB,EAAE;AACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-helpers.d.mts","names":[],"sources":["../../../../../../../core/src/tests/test-helpers.ts"],"mappings":";;AAYA;;;;AAAgC;AAehC;;AAfgC,iBAAhB,gBAAA
|
|
1
|
+
{"version":3,"file":"test-helpers.d.mts","names":[],"sources":["../../../../../../../core/src/tests/test-helpers.ts"],"mappings":";;AAYA;;;;AAAgC;AAehC;;AAfgC,iBAAhB,gBAAA;;;;;iBAeM,WAAA,CAAY,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;;iBAgD9D,OAAA,CAAQ,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;AAhDY;iBAuDtE,QAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;;;iBAOW,OAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;;;iBAOW,UAAA,CAAW,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;;iBAO7D,SAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;AAxC6E;AAOxF;iBAwCsB,iBAAA,IAAqB,QAAA,EAAU,QAAA,GAAW,OAAA,CAAQ,CAAA;;;;iBAOlD,UAAA,IAAc,QAAA,EAAU,QAAA,EAAU,cAAA,YAAuB,OAAA,CAAQ,CAAA"}
|