37 Commits

Author SHA1 Message Date
c919507375 update description 2024-05-29 14:13:46 +02:00
68e4d9cc74 update tsconfig 2024-04-14 17:44:47 +02:00
19b723146b update npmextra.json: githost 2024-04-01 21:35:40 +02:00
cc540ad39e update npmextra.json: githost 2024-04-01 19:58:32 +02:00
0b53a9514a update npmextra.json: githost 2024-03-30 21:47:30 +01:00
a2b408a7bf 1.0.18 2024-02-14 01:56:00 +01:00
67fdcf0362 fix(core): update 2024-02-14 01:56:00 +01:00
c3f840e1be 1.0.17 2023-12-03 23:32:48 +01:00
6840d94517 fix(core): update 2023-12-03 23:32:47 +01:00
4600cde549 1.0.16 2023-12-03 23:30:58 +01:00
33e8ba5f30 fix(core): update 2023-12-03 23:30:58 +01:00
8566c5f57f 1.0.15 2023-12-03 23:09:49 +01:00
4cc5accff1 fix(core): update 2023-12-03 23:09:48 +01:00
2b82a4b74a 1.0.14 2023-12-03 19:04:37 +01:00
499b7e5f42 fix(core): update 2023-12-03 19:04:36 +01:00
6b1948d834 1.0.13 2023-12-03 18:57:45 +01:00
7b340ea783 fix(core): update 2023-12-03 18:57:44 +01:00
063905bfaa 1.0.12 2023-12-03 18:41:44 +01:00
f1ad45289a fix(core): update 2023-12-03 18:41:43 +01:00
193e174fd7 1.0.11 2023-12-03 18:10:36 +01:00
703d21c426 fix(core): update 2023-12-03 18:10:35 +01:00
2d83ebac4d 1.0.10 2023-12-03 16:35:52 +01:00
7454a52d03 fix(core): update 2023-12-03 16:35:51 +01:00
1e93429186 1.0.9 2023-12-03 16:32:53 +01:00
ee926e18a7 fix(core): update 2023-12-03 16:32:52 +01:00
02a6656869 1.0.8 2023-11-24 20:21:13 +01:00
b07aba76e9 fix(core): update 2023-11-24 20:21:12 +01:00
7fdeed160a 1.0.7 2023-11-24 20:09:24 +01:00
c6cd1dc38f fix(core): update 2023-11-24 20:09:23 +01:00
d2a47f403e 1.0.6 2023-11-24 20:08:49 +01:00
c8ab607959 fix(core): update 2023-11-24 20:08:48 +01:00
8170877c55 switch to new org scheme 2023-07-11 00:51:43 +02:00
99182bdb69 switch to new org scheme 2023-07-10 02:56:32 +02:00
d1393c5128 1.0.5 2023-01-09 18:19:51 +01:00
fc92f0f3e8 fix(core): update 2023-01-09 18:19:50 +01:00
5110d4cfd6 1.0.4 2023-01-09 18:17:34 +01:00
746447ec44 fix(core): update 2023-01-09 18:17:33 +01:00
22 changed files with 7093 additions and 2293 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

4
.gitignore vendored
View File

@ -15,8 +15,6 @@ node_modules/
# builds # builds
dist/ dist/
dist_web/ dist_*/
dist_serve/
dist_ts_web/
# custom # custom

View File

@ -12,29 +12,38 @@ stages:
- release - release
- metadata - metadata
before_script:
- pnpm install -g pnpm
- pnpm install -g @shipzone/npmci
- npmci npm prepare
# ==================== # ====================
# security stage # security stage
# ==================== # ====================
mirror: # ====================
# security stage
# ====================
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security stage: security
script: script:
- npmci git mirror - npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --prod
tags: tags:
- lossless - lossless
- docker - docker
- notpriv allow_failure: true
snyk: auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:snyk image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security stage: security
script: script:
- npmci npm prepare - npmci command npm config set registry https://registry.npmjs.org
- npmci command npm install --ignore-scripts - npmci command pnpm audit --audit-level=high --dev
- npmci command snyk test
tags: tags:
- lossless - lossless
- docker - docker
- notpriv allow_failure: true
# ==================== # ====================
# test stage # test stage
@ -43,28 +52,22 @@ snyk:
testStable: testStable:
stage: test stage: test
script: script:
- npmci npm prepare
- npmci node install stable - npmci node install stable
- npmci npm install - npmci npm install
- npmci npm test - npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- lossless
- docker - docker
- priv
testBuild: testBuild:
stage: test stage: test
script: script:
- npmci npm prepare
- npmci node install stable - npmci node install stable
- npmci npm install - npmci npm install
- npmci command npm run build - npmci npm build
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- lossless
- docker - docker
- notpriv
release: release:
stage: release stage: release
@ -84,11 +87,12 @@ release:
codequality: codequality:
stage: metadata stage: metadata
allow_failure: true allow_failure: true
only:
- tags
script: script:
- npmci command npm install -g tslint typescript - npmci command npm install -g typescript
- npmci npm prepare - npmci npm prepare
- npmci npm install - npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags: tags:
- lossless - lossless
- docker - docker
@ -108,11 +112,9 @@ trigger:
pages: pages:
stage: metadata stage: metadata
script: script:
- npmci node install lts - npmci node install stable
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install - npmci npm install
- npmci command tsdoc - npmci command npm run buildDocs
tags: tags:
- lossless - lossless
- docker - docker

24
.vscode/launch.json vendored
View File

@ -2,28 +2,10 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"name": "current file", "command": "npm test",
"type": "node", "name": "Run npm test",
"request": "launch", "request": "launch",
"args": [ "type": "node-terminal"
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
} }
] ]
} }

View File

@ -15,7 +15,7 @@
"properties": { "properties": {
"projectType": { "projectType": {
"type": "string", "type": "string",
"enum": ["website", "element", "service", "npm"] "enum": ["website", "element", "service", "npm", "wcc"]
} }
} }
} }

View File

@ -2,17 +2,33 @@
"gitzone": { "gitzone": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "code.foss.global",
"gitscope": "pushrocks", "gitscope": "push.rocks",
"gitrepo": "smartjimp", "gitrepo": "smartjimp",
"shortDescription": "a tool fr working with images in TypeScript", "description": "A TypeScript library for image processing combining both sharp and jimp libraries.",
"npmPackagename": "@pushrocks/smartjimp", "npmPackagename": "@push.rocks/smartjimp",
"license": "MIT", "license": "MIT",
"projectDomain": "push.rocks" "projectDomain": "push.rocks",
"keywords": [
"image processing",
"TypeScript",
"sharp",
"jimp",
"resize image",
"convert image format",
"image caching",
"buffer manipulation",
"AVIF",
"WEBP",
"PNG"
]
} }
}, },
"npmci": { "npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
} }
} }

2174
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,37 +1,69 @@
{ {
"name": "@pushrocks/smartjimp", "name": "@push.rocks/smartjimp",
"version": "1.0.3", "version": "1.0.18",
"private": false, "private": false,
"description": "a tool fr working with images in TypeScript", "description": "A TypeScript library for image processing combining both sharp and jimp libraries.",
"main": "dist/index.js", "main": "dist_ts/index.js",
"typings": "dist/index.d.ts", "typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/)",
"build": "(tsbuild)", "build": "(tsbuild --allowimplicitany)",
"format": "(gitzone format)" "buildDocs": "tsdoc",
"localPublish": "gitzone commit && pnpm run build && pnpm publish && pnpm publish --access public --registry=\"https://registry.npmjs.org\""
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.0.22", "@git.zone/tsbuild": "^2.1.72",
"@gitzone/tstest": "^1.0.15", "@git.zone/tsrun": "^1.2.44",
"@pushrocks/tapbundle": "^3.0.7", "@git.zone/tstest": "^1.0.86",
"@types/node": "^10.11.7", "@push.rocks/tapbundle": "^5.0.8",
"tslint": "^5.11.0", "@types/node": "^20.11.17"
"tslint-config-prettier": "^1.15.0"
}, },
"dependencies": { "dependencies": {
"jimp": "^0.9.3" "@push.rocks/levelcache": "^3.0.8",
"@push.rocks/smartfile": "^11.0.4",
"@push.rocks/smarthash": "^3.0.4",
"@push.rocks/smartpath": "^5.0.5",
"@push.rocks/smartrequest": "^2.0.15",
"jimp": "^0.22.10",
"sharp": "^0.33.2"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
"ts_web/**/*", "ts_web/**/*",
"dist/**/*", "dist/**/*",
"dist_web/**/*", "dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*", "dist_ts_web/**/*",
"assets/**/*", "assets/**/*",
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
],
"type": "module",
"browserslist": [
"last 1 chrome versions"
],
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartjimp.git"
},
"bugs": {
"url": "https://gitlab.com/push.rocks/smartjimp/issues"
},
"homepage": "https://code.foss.global/push.rocks/smartjimp",
"keywords": [
"image processing",
"TypeScript",
"sharp",
"jimp",
"resize image",
"convert image format",
"image caching",
"buffer manipulation",
"AVIF",
"WEBP",
"PNG"
] ]
} }

6513
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

115
readme.md
View File

@ -1,32 +1,105 @@
# @pushrocks/smartjimp # @push.rocks/smartjimp
a tool fr working with images in TypeScript a tool fr working with images in TypeScript
## Availabililty and Links ## Install
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartjimp)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartjimp)
* [github.com (source mirror)](https://github.com/pushrocks/smartjimp)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartjimp/)
## Status for master To install `@push.rocks/smartjimp`, use the following command in your project directory:
[![pipeline status](https://gitlab.com/pushrocks/smartjimp/badges/master/pipeline.svg)](https://gitlab.com/pushrocks/smartjimp/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartjimp/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartjimp/commits/master) ```bash
[![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartjimp.svg)](https://www.npmjs.com/package/@pushrocks/smartjimp) npm install @push.rocks/smartjimp --save
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartjimp/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartjimp) ```
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
## Usage ## Usage
Use TypeScript for best in class intellisense `@push.rocks/smartjimp` is a comprehensive TypeScript library for handling image processing with ease and efficiency. It leverages powerful image processing libraries such as `sharp` and `jimp`, providing a unified interface for performing common image manipulation tasks. This documentation aims to guide you through the installation and various functionalities of `@push.rocks/smartjimp`, ensuring you have the knowledge to integrate image processing capabilities into your TypeScript project effectively.
## Contribution ### Getting Started
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :) First, import the `SmartJimp` class from the package:
For further information read the linked docs at the top of this readme. ```typescript
import { SmartJimp } from '@push.rocks/smartjimp';
```
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) Next, create an instance of `SmartJimp` by specifying the preferred image processing mode (`sharp` or `jimp`):
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com) ```typescript
const imageProcessor = new SmartJimp({ mode: 'sharp' });
```
### Processing Images
#### From Buffer
You can process images from a buffer. This is particularly useful when you have image data already available in your application, such as uploaded images.
```typescript
import { SmartFile } from '@push.rocks/smartfile';
// Assuming you have an image buffer `imageBuffer`
let imageBuffer: Buffer;
// Convert the buffer to a SmartFile instance
const smartfileInstance = await SmartFile.fromBuffer(imageBuffer);
// Process the image, for example, resizing it to width 500px
const resizedImageBuffer = await imageProcessor.getFromSmartfile(smartfileInstance, {
width: 500,
});
```
#### Creating Specific Formats
`@push.rocks/smartjimp` supports creating images in various formats, including AVIF, WebP, and PNG.
```typescript
// For forcing a format, specify the `format` in the options, like 'png'
const pngBuffer = await imageProcessor.getFromSmartfile(smartfileInstance, {
width: 500,
format: 'png',
});
```
### Advanced Image Manipulation
#### Inversion
You can invert the colors of an image as follows:
```typescript
const invertedImageBuffer = await imageProcessor.getFromSmartfile(smartfileInstance, {
invert: true,
});
```
### Performance and Caching
`@push.rocks/smartjimp` employs caching mechanisms to enhance performance. Caching is handled internally, ensuring that repeated processing requests for the same image and settings are served faster by retrieving the processed image from the cache.
### Mode: Sharp vs. Jimp
- **Sharp**: Recommended for performance-critical applications. It is faster and supports a broader range of image formats. However, it relies on native libraries, which may need additional setup in certain environments.
- **Jimp**: A pure JavaScript image processing library. While not as fast as Sharp, it guarantees compatibility across all Node.js environments without the need for additional native dependencies.
### Conclusion
`@push.rocks/smartjimp` makes image processing in TypeScript applications highly accessible and efficient. Whether you need to resize, convert formats, or perform other image manipulations, `@push.rocks/smartjimp` provides a powerful yet simple API to accomplish these tasks with minimal effort. By abstracting away the complexities of direct interactions with libraries like `sharp` and `jimp`, it allows developers to focus more on building the core features of their applications.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -1,11 +1,27 @@
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, tap } from '@push.rocks/tapbundle';
import * as smartjimp from '../ts/index'; import * as smartjimp from '../ts/index.js';
import * as smartfile from '@push.rocks/smartfile';
let testSmartJimp: smartjimp.SmartJimp; let testSmartJimp: smartjimp.SmartJimp;
tap.test('first test', async () => { tap.test('first test', async () => {
testSmartJimp = new smartjimp.SmartJimp(); testSmartJimp = new smartjimp.SmartJimp({ mode: 'sharp'});
expect(testSmartJimp).to.be.instanceOf(smartjimp.SmartJimp); expect(testSmartJimp).toBeInstanceOf(smartjimp.SmartJimp);
}); });
tap.test('should be able to create a master', async () => {
const smartfileInstance = await smartfile.SmartFile.fromUrl('https://images.unsplash.com/photo-1673276628202-737bf3020ac2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=3774&q=80')
const convertedAsset = await testSmartJimp.getFromSmartfile(smartfileInstance, {width: 500});
(await smartfile.SmartFile.fromBuffer('.nogit/result.avif', convertedAsset)).write();
});
tap.test('should be able to use jimp', async () => {
const testSmartJimp = new smartjimp.SmartJimp({ mode: 'jimp'});
const smartfileInstance = await smartfile.SmartFile.fromUrl('https://images.unsplash.com/photo-1673276628202-737bf3020ac2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=3774&q=80')
const convertedAsset = await testSmartJimp.computeAssetVariation(smartfileInstance.contents, {
format: 'png',
});
(await smartfile.SmartFile.fromBuffer('.nogit/result2.png', convertedAsset)).write();
})
tap.start(); tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartjimp',
version: '1.0.18',
description: 'a tool fr working with images in TypeScript'
}

View File

@ -1 +1 @@
export * from './smartjimp.classes.smartjimp'; export * from './smartjimp.classes.smartjimp.js';

13
ts/plugins.ts Normal file
View File

@ -0,0 +1,13 @@
// node native
import * as path from 'path';
export { path };
// @pushrocks scope
import * as levelcache from '@push.rocks/levelcache';
import * as smartfile from '@push.rocks/smartfile';
import * as smarthash from '@push.rocks/smarthash';
import * as smartpath from '@push.rocks/smartpath';
import * as smartrequest from '@push.rocks/smartrequest';
export { levelcache, smartpath, smarthash, smartfile, smartrequest };

7
ts/plugins.typed.ts Normal file
View File

@ -0,0 +1,7 @@
import type * as sharpType from 'sharp';
export { type sharpType };
import type * as jimpType from 'jimp';
export { type jimpType };

View File

@ -1,5 +1,133 @@
import * as plugins from './smartjimp.plugins'; import * as plugins from './plugins.js';
import * as pluginsTyped from './plugins.typed.js';
export interface IAssetVariation {
format?: 'avif' | 'webp' | 'png';
width?: number;
height?: number;
invert?: boolean;
}
export interface ISmartJimpOptions {
mode: 'sharp' | 'jimp';
}
export class SmartJimp { export class SmartJimp {
public levelCache = new plugins.levelcache.LevelCache({
cacheId: 'mastercache',
maxMemoryStorageInMB: 100,
maxDiskStorageInMB: 5000,
});
public options: ISmartJimpOptions;
constructor(optionsArg: ISmartJimpOptions) {
this.options = optionsArg;
}
/**
* get a key that is unique for a wanted asset variation
*/
private getCacheKey(
sourceTypeArg: 'streamfile' | 'smartfile',
sourceIdArg: string,
assetVariationArg?: IAssetVariation
) {
return `${sourceTypeArg}_${sourceIdArg}_${
assetVariationArg
? `${assetVariationArg.width || 'auto'}x${assetVariationArg.height || 'auto'}`
: 'original'
}`;
}
sharpMod: typeof pluginsTyped.sharpType.default;
public async getSharpMod(): Promise<
typeof pluginsTyped.sharpType.default
> {
if (!this.sharpMod) {
this.sharpMod = (await import('sharp')).default;
}
return this.sharpMod;
}
jimpMod: typeof pluginsTyped.jimpType;
public async getJimpMod(): Promise<typeof pluginsTyped.jimpType.default> {
if (!this.jimpMod) {
this.jimpMod = await import('jimp');
}
return this.jimpMod.default;
}
public async computeAssetVariation(assetBufferArg: Buffer, assetVariationArg: IAssetVariation) {
if (this.options.mode === 'sharp') {
const sharp = await this.getSharpMod();
if (!assetVariationArg) {
return assetBufferArg;
}
let sharpImage = sharp(assetBufferArg);
sharpImage = sharpImage.resize(assetVariationArg.width, assetVariationArg.height);
const resultResize = sharpImage.resize(assetVariationArg.width, assetVariationArg.height);
if (assetVariationArg.invert) {
// TODO: implement invert
}
switch (assetVariationArg.format) {
case 'avif':
sharpImage = resultResize.avif();
case 'webp':
sharpImage = resultResize.webp();
case 'png':
sharpImage = resultResize.png();
}
return sharpImage.toBuffer();
} else if (this.options.mode === 'jimp') {
const jimp = await this.getJimpMod();
let jimpImage = await jimp.read(assetBufferArg);
if (assetVariationArg.width || assetVariationArg.height) {
jimpImage = jimpImage.resize(assetVariationArg.width, assetVariationArg.height);
}
if (assetVariationArg.invert) {
jimpImage = jimpImage.invert();
}
switch (assetVariationArg.format) {
case 'png':
return await jimpImage.getBufferAsync(jimp.MIME_PNG);
default:
return await jimpImage.getBufferAsync(jimp.MIME_JPEG);
}
}
}
public async getFromSmartfile(
smartfileArg: plugins.smartfile.SmartFile,
wantedDimensionsArg?: IAssetVariation
) {
const cacheKey = this.getCacheKey(
'smartfile',
await smartfileArg.getHash(),
wantedDimensionsArg
);
const existingCacheEntry = await this.levelCache.retrieveCacheEntryByKey(cacheKey);
if (existingCacheEntry) {
return existingCacheEntry.contents;
} else {
const computedAssetBuffer = await this.computeAssetVariation(
smartfileArg.contentBuffer,
wantedDimensionsArg
);
this.levelCache.storeCacheEntryByKey(
cacheKey,
new plugins.levelcache.CacheEntry({
contents: computedAssetBuffer,
ttl: 600000,
})
);
return computedAssetBuffer;
}
}
public async createAvifImageFromBuffer(bufferArg: Buffer) {
const sharp = await this.getSharpMod();
const sharpImage = sharp(bufferArg);
const result = await sharpImage.avif().toBuffer();
return result;
}
} }

4
ts/smartjimp.paths.ts Normal file
View File

@ -0,0 +1,4 @@
import * as plugins from './plugins.js';
export const packageDir = plugins.path.join(plugins.smartpath.get.dirnameFromImportMetaUrl(import.meta.url), '../');
export const nogitDir = plugins.path.join(packageDir, '.nogit/')

View File

@ -1,6 +0,0 @@
// third party scope
import jimp from 'jimp';
export {
jimp
}

14
tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}