@shibam/sticker-maker 1.2.16 → 1.3.0-rc1

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/package.json CHANGED
@@ -1,51 +1,31 @@
1
- {
2
- "name": "@shibam/sticker-maker",
3
- "version": "1.2.16",
4
- "description": "A package for creating stickers",
5
- "main": "dist/index.js",
6
- "type": "module",
7
- "files": [
8
- "dist"
9
- ],
10
- "scripts": {
11
- "build": "tsc -p .",
12
- "lint": "eslint \"src/**/*.ts\"",
13
- "prepublish": "npm run build",
14
- "fmt": "prettier --config .prettierrc \"**/*.{ts,mjs}\" --write",
15
- "test": "mocha --timeout 60000 -r ts-node/register \"tests/**/*.test.ts\"",
16
- "clean:webp": "find ./ -name '*.webp' -delete",
17
- "release": "release-it"
18
- },
19
- "author": "Shibam Dey",
20
- "license": "MIT",
21
- "repository": {
22
- "type": "git",
23
- "url": "https://github.com/ShibamDey69/Sticker-Maker.git"
24
- },
25
- "keywords": [
26
- "stickers",
27
- "sticker maker",
28
- "image processing",
29
- "wa sticker maker",
30
- "wasticker",
31
- "nodejs",
32
- "typescript"
33
- ],
34
- "dependencies": {
35
- "canvas": "^2.11.2",
36
- "file-type": "^20.0.0",
37
- "fluent-ffmpeg": "^2.1.3",
38
- "fs-extra": "^11.3.0",
39
- "node-webpmux": "^3.2.0",
40
- "sharp": "0.30.0",
41
- "text-on-gif": "^2.0.13"
42
- },
43
- "devDependencies": {
44
- "@types/fluent-ffmpeg": "^2.1.27",
45
- "@types/fs-extra": "^11.0.4",
46
- "@types/node": "^20.17.14",
47
- "@types/sharp": "^0.28.5",
48
- "tsx": "^4.7.1",
49
- "typescript": "^5.4.5"
50
- }
51
- }
1
+ {
2
+ "name": "@shibam/sticker-maker",
3
+ "version": "1.3.0-rc1",
4
+ "description": "A package for creating stickers",
5
+ "main": "dist/index.js",
6
+ "type": "module",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {},
11
+ "author": "Shibam Dey",
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/ShibamDey69/Sticker-Maker.git"
16
+ },
17
+ "keywords": [
18
+ "stickers",
19
+ "sticker maker",
20
+ "image processing",
21
+ "wa sticker maker",
22
+ "wasticker",
23
+ "nodejs",
24
+ "typescript"
25
+ ],
26
+ "dependencies": {
27
+ "file-type": "^19.4.0",
28
+ "fs-extra": "^11.3.5",
29
+ "node-webpmux": "^3.2.0"
30
+ }
31
+ }
package/dist/index.js DELETED
@@ -1,156 +0,0 @@
1
- import fs from 'fs-extra';
2
- import Utils from './lib/utils.js';
3
- import convert from './lib/ToWebp.js';
4
- import { StickerTypes } from './types/StickerTypes.js';
5
- import MetaInfoChanger from './lib/changeMetaInfo.js';
6
- import extractMetaData from './lib/extractMetaData.js';
7
- /**
8
- * Sticker class for handling sticker creation, conversion, and metadata management
9
- */
10
- class Sticker {
11
- utils;
12
- buffer;
13
- outBuffer;
14
- mimeType;
15
- extType;
16
- isBufferProcessed;
17
- isMetaProcessed;
18
- data;
19
- metaInfo;
20
- /**
21
- * Creates a new Sticker instance
22
- * @param data The input data (Buffer, string path, or Readable stream)
23
- * @param metaInfo Optional metadata and configuration
24
- */
25
- constructor(data, metaInfo = {}) {
26
- this.utils = new Utils();
27
- this.buffer = Buffer.from([]);
28
- this.outBuffer = Buffer.from([]);
29
- this.mimeType = '';
30
- this.extType = '';
31
- this.isBufferProcessed = false;
32
- this.isMetaProcessed = false;
33
- this.data = data;
34
- this.metaInfo = this.initializeMetaInfo(metaInfo);
35
- }
36
- /**
37
- * Initialize default metadata values
38
- */
39
- initializeMetaInfo(metaInfo) {
40
- return {
41
- pack: '',
42
- author: '',
43
- type: StickerTypes.DEFAULT,
44
- quality: 100,
45
- background: '#FFFFFF00',
46
- text: '',
47
- ...metaInfo,
48
- // Ensure categories is always an array
49
- categories: metaInfo.categories || []
50
- };
51
- }
52
- /**
53
- * Initialize the Sticker instance with file data and metadata
54
- */
55
- async initialize() {
56
- try {
57
- // Convert input to buffer
58
- this.buffer = await this.utils.buffer(this.data);
59
- // Get file type information
60
- const fileType = await this.utils.getMimeType(this.buffer);
61
- if (!fileType) {
62
- throw new Error('Unable to determine file type');
63
- }
64
- this.mimeType = fileType.mime;
65
- this.extType = fileType.ext;
66
- // Set dynamic metadata values if not provided
67
- this.metaInfo = {
68
- ...this.metaInfo,
69
- id: this.metaInfo.id ?? this.utils.getId(),
70
- quality: this.metaInfo.quality ?? this.utils.getQuality(this.buffer)
71
- };
72
- }
73
- catch (error) {
74
- throw new Error(`Initialization failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
75
- }
76
- }
77
- /**
78
- * Convert input data to WebP buffer with metadata
79
- */
80
- async toBuffer() {
81
- try {
82
- await this.initialize();
83
- // Convert to WebP
84
- const convertedBuffer = await convert({
85
- buffer: this.buffer,
86
- metaInfo: {
87
- ...this.metaInfo,
88
- categories: this.metaInfo.categories // Map categories to category for compatibility
89
- },
90
- mimeExt: this.extType,
91
- mimeType: this.mimeType
92
- });
93
- // Add metadata
94
- this.outBuffer = await new MetaInfoChanger({
95
- ...this.metaInfo,
96
- categories: this.metaInfo.categories
97
- }).add(convertedBuffer);
98
- this.isBufferProcessed = true;
99
- return this.outBuffer;
100
- }
101
- catch (error) {
102
- this.isBufferProcessed = false;
103
- throw new Error(`Buffer conversion failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
104
- }
105
- }
106
- /**
107
- * Save the sticker to a file
108
- */
109
- async toFile(outputPath) {
110
- try {
111
- // Process buffer if needed
112
- if (!this.isBufferProcessed && !this.isMetaProcessed && this.extType?.includes('webp')) {
113
- await this.changeMetaInfo();
114
- }
115
- else {
116
- await this.toBuffer();
117
- }
118
- // Write to file
119
- await fs.writeFile(outputPath, this.outBuffer);
120
- }
121
- catch (error) {
122
- throw new Error(`File conversion failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
123
- }
124
- }
125
- /**
126
- * Update sticker metadata
127
- */
128
- async changeMetaInfo() {
129
- try {
130
- await this.initialize();
131
- this.outBuffer = await new MetaInfoChanger({
132
- ...this.metaInfo,
133
- categories: this.metaInfo.categories
134
- }).add(this.buffer);
135
- this.isMetaProcessed = true;
136
- return this.outBuffer;
137
- }
138
- catch (error) {
139
- this.isMetaProcessed = false;
140
- throw new Error(`Metadata update failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
141
- }
142
- }
143
- /**
144
- * Extract metadata from a buffer
145
- */
146
- async extractMetaData(data) {
147
- try {
148
- await this.initialize();
149
- return extractMetaData(data);
150
- }
151
- catch (error) {
152
- throw new Error(`Metadata extraction failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
153
- }
154
- }
155
- }
156
- export { Sticker, StickerTypes };
@@ -1,76 +0,0 @@
1
- import sharp from 'sharp';
2
- import { StickerTypes } from '../types/StickerTypes.js';
3
- import toGif from './toGif.js';
4
- import TextOnImg from './textOnImg.js';
5
- /**
6
- * Converts media (image/video) to WebP format with optional transformations
7
- * @param options Configuration options for the conversion
8
- * @returns Promise<Buffer> The resulting WebP buffer
9
- */
10
- const ToWebp = async ({ buffer, metaInfo, mimeExt, mimeType }) => {
11
- try {
12
- // Return early if already in WebP format
13
- if (mimeExt === 'webp') {
14
- return buffer;
15
- }
16
- const textOnImg = new TextOnImg();
17
- // Process initial buffer based on type and text requirements
18
- const processedBuffer = await (async () => {
19
- if (mimeType?.includes('video')) {
20
- return toGif({
21
- buffer,
22
- extType: mimeExt,
23
- type: metaInfo.type || StickerTypes.DEFAULT,
24
- text: metaInfo.text ?? ''
25
- });
26
- }
27
- if (metaInfo.text) {
28
- return textOnImg.drawText(buffer, metaInfo.text);
29
- }
30
- return buffer;
31
- })();
32
- // Determine if content is animated
33
- const isAnimated = mimeType?.includes('video') || mimeExt?.includes('gif');
34
- // Initialize sharp with processed buffer
35
- const sharpInstance = sharp(processedBuffer, { animated: isAnimated });
36
- // Apply transformations based on sticker type
37
- switch (metaInfo.type) {
38
- case StickerTypes.CIRCLE: {
39
- const circleSvg = Buffer.from('<svg width="512" height="512"><circle cx="256" cy="256" r="256" fill=""/></svg>');
40
- await sharpInstance
41
- .resize(512, 512, { fit: sharp.fit.cover })
42
- .composite([{
43
- input: circleSvg,
44
- blend: 'dest-in',
45
- gravity: 'northeast',
46
- tile: true
47
- }]);
48
- break;
49
- }
50
- case StickerTypes.SQUARE: {
51
- if (!mimeType?.includes('video')) {
52
- await sharpInstance.resize(512, 512, { fit: sharp.fit.fill });
53
- }
54
- break;
55
- }
56
- default: {
57
- await sharpInstance.resize(512, 512, {
58
- fit: sharp.fit.contain,
59
- background: { r: 0, g: 0, b: 0, alpha: 0 }
60
- });
61
- }
62
- }
63
- // Convert to WebP format with appropriate options
64
- return sharpInstance
65
- .toFormat('webp')
66
- .webp({
67
- quality: metaInfo.quality,
68
- lossless: mimeExt.includes('gif')
69
- })
70
- .toBuffer();
71
- }
72
- catch (error) {
73
- throw new Error(`WebP conversion failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
74
- }
75
- };
76
- export default ToWebp;
@@ -1,56 +0,0 @@
1
- import Image from 'node-webpmux';
2
- import { TextEncoder } from 'util';
3
- /**
4
- * The Exif class is responsible for handling the metadata (Exif data)
5
- * for sticker images, particularly those used in messaging applications.
6
- */
7
- export default class Exif {
8
- data = {};
9
- exif = null;
10
- /**
11
- * Constructs an Exif instance with the given options.
12
- * @param options - An object containing metadata for the sticker.
13
- */
14
- constructor(options) {
15
- this.data['sticker-pack-id'] = options.id || '';
16
- this.data['sticker-pack-name'] = options.pack || '';
17
- this.data['sticker-pack-publisher'] = options.author || '';
18
- this.data['emojis'] = options.category || ['😹'];
19
- }
20
- /**
21
- * Builds the Exif metadata as a Buffer.
22
- * @returns A Buffer containing the constructed Exif data.
23
- */
24
- build = () => {
25
- const data = JSON.stringify(this.data);
26
- const exif = Buffer.concat([
27
- Buffer.from([
28
- 0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00,
29
- 0x00, 0x16, 0x00, 0x00, 0x00
30
- ]),
31
- Buffer.from(data, 'utf-8')
32
- ]);
33
- exif.writeUIntLE(new TextEncoder().encode(data).length, 14, 4);
34
- return exif;
35
- };
36
- /**
37
- * Adds the Exif metadata to the given image.
38
- * @param image - A Buffer or Image instance representing the image to which Exif data should be added.
39
- * @returns A Promise that resolves to a Buffer containing the image with the added Exif data.
40
- */
41
- add = async (image) => {
42
- const exif = this.exif || this.build();
43
- // Load the image if it is not already an instance of Image.Image.
44
- image =
45
- image instanceof Image.Image
46
- ? image
47
- : await (async () => {
48
- const img = new Image.Image();
49
- await img.load(image);
50
- return img;
51
- })();
52
- // Set the Exif data on the image and save it.
53
- image.exif = exif;
54
- return await image.save(null);
55
- };
56
- }
@@ -1,12 +0,0 @@
1
- import Image from 'node-webpmux';
2
- /**
3
- * Extracts metadata from a WebP image.
4
- * @param {Buffer}image - The image buffer to extract metadata from
5
- */
6
- const extractMetadata = async (image) => {
7
- const img = new Image.Image();
8
- await img.load(image);
9
- const exif = img.exif?.toString('utf-8') ?? '{}';
10
- return JSON.parse(exif.substring(exif.indexOf('{'), exif.lastIndexOf('}') + 1) ?? '{}');
11
- };
12
- export default extractMetadata;
@@ -1,24 +0,0 @@
1
- import TextOnGif from 'text-on-gif';
2
- const textOnGif = async (fileName, text) => {
3
- return new Promise(async (resolve, reject) => {
4
- try {
5
- const gif = new TextOnGif({
6
- file_path: fileName,
7
- font_size: '32px',
8
- font_color: 'white',
9
- font_family: 'Arial',
10
- stroke_color: 'black',
11
- stroke_width: 3
12
- });
13
- const buff = await gif.textOnGif({
14
- text,
15
- get_as_buffer: true
16
- });
17
- resolve(buff);
18
- }
19
- catch (error) {
20
- reject(error);
21
- }
22
- });
23
- };
24
- export default textOnGif;
@@ -1,62 +0,0 @@
1
- import { createCanvas, loadImage } from 'canvas';
2
- export default class TextOnImage {
3
- fontSize;
4
- maxCharsPerLine;
5
- constructor(maxCharsPerLine = 25) {
6
- this.fontSize = 175;
7
- this.maxCharsPerLine = maxCharsPerLine;
8
- }
9
- wrapText(ctx, text) {
10
- const words = text.split(' ');
11
- let lines = [];
12
- let currentLine = words[0];
13
- for (let i = 1; i < words.length; i++) {
14
- const word = words[i];
15
- const testLine = `${currentLine} ${word}`;
16
- const { width: testWidth } = ctx.measureText(testLine);
17
- if (testWidth > ctx.canvas.width * 0.9) {
18
- lines.push(currentLine);
19
- currentLine = word;
20
- }
21
- else {
22
- currentLine = testLine;
23
- }
24
- }
25
- lines.push(currentLine);
26
- return lines;
27
- }
28
- async drawText(imageBuffer, text, padding = { x: 10, y: 10 }) {
29
- const image = await loadImage(imageBuffer);
30
- const canvas = createCanvas(image.width, image.height);
31
- const ctx = canvas.getContext('2d');
32
- // Draw the image on canvas
33
- ctx.drawImage(image, 0, 0);
34
- // Calculate font size based on image height
35
- this.fontSize = Math.floor(image.height / 10);
36
- ctx.font = `bold ${this.fontSize}px Arial`;
37
- ctx.fillStyle = 'white';
38
- ctx.textAlign = 'center';
39
- ctx.textBaseline = 'top';
40
- ctx.lineWidth = 4;
41
- ctx.strokeStyle = 'black';
42
- // Wrap the text to fit within the canvas width
43
- const lines = this.wrapText(ctx, text);
44
- const lineHeight = this.fontSize * 1.2;
45
- const totalTextHeight = lines.length * lineHeight;
46
- // If text height exceeds image height, adjust font size
47
- if (totalTextHeight + 2 * padding.y > canvas.height) {
48
- this.fontSize = Math.floor((canvas.height - 2 * padding.y) / (lines.length * 1.2));
49
- ctx.font = `bold ${this.fontSize}px Arial`;
50
- }
51
- // Start text positioning at the bottom, above padding
52
- let y = canvas.height - totalTextHeight - padding.y;
53
- // Draw each line of text with stroke and fill for better contrast
54
- lines.forEach((line) => {
55
- const x = canvas.width / 2;
56
- ctx.strokeText(line, x, y);
57
- ctx.fillText(line, x, y);
58
- y += lineHeight;
59
- });
60
- return canvas.toBuffer('image/png');
61
- }
62
- }
package/dist/lib/toGif.js DELETED
@@ -1,62 +0,0 @@
1
- import ffmpeg from 'fluent-ffmpeg';
2
- import { tmpdir } from 'os';
3
- import fs from 'fs-extra';
4
- import { join } from 'path';
5
- import { StickerTypes } from '../types/StickerTypes.js';
6
- import TextOnGif from './textOnGif.js';
7
- /**
8
- * Converts a video file to an animated GIF with optional text overlay
9
- * @param options Configuration options for the conversion
10
- * @returns Promise<Buffer> The resulting GIF as a buffer
11
- */
12
- const videoToGif = async ({ buffer, extType, type, text = '', maxDuration = 7, maxRetries = 3 }) => {
13
- const generateTempFilename = () => join(tmpdir(), `${Math.random().toString(36).slice(2)}`);
14
- const cleanupFiles = async (...files) => {
15
- await Promise.all(files.map(file => fs.unlink(file).catch(() => { })));
16
- };
17
- const processVideo = async (attempt) => {
18
- const inputFile = `${generateTempFilename()}.${extType}`;
19
- const outputFile = `${generateTempFilename()}.gif`;
20
- try {
21
- // Write input buffer to temporary file
22
- await fs.writeFile(inputFile, buffer);
23
- // Determine scaling and cropping parameters based on type
24
- const shape = type === StickerTypes.SQUARE
25
- ? 'scale=320:-1:flags=lanczos,fps=10,crop=min(iw\\,ih):min(iw\\,ih)'
26
- : 'scale=320:-1:flags=lanczos,fps=15';
27
- // Process video with ffmpeg
28
- await new Promise((resolve, reject) => {
29
- ffmpeg(inputFile)
30
- .inputFormat(extType)
31
- .outputOptions([
32
- '-vf', shape,
33
- '-loop', '0',
34
- '-t', maxDuration.toString(),
35
- '-preset', 'ultrafast'
36
- ])
37
- .toFormat('gif')
38
- .save(outputFile)
39
- .on('end', () => resolve())
40
- .on('error', reject);
41
- });
42
- // Add text to GIF if required, or return the GIF buffer directly
43
- const gifBuffer = text
44
- ? await TextOnGif(outputFile, text)
45
- : await fs.readFile(outputFile);
46
- // Clean up temporary files
47
- await cleanupFiles(inputFile, outputFile);
48
- return gifBuffer;
49
- }
50
- catch (error) {
51
- // Clean up temporary files
52
- await cleanupFiles(inputFile, outputFile);
53
- // Retry on failure up to the specified number of attempts
54
- if (attempt < maxRetries) {
55
- return processVideo(attempt + 1);
56
- }
57
- throw new Error(`Failed to convert video to GIF after ${maxRetries} attempts: ${error instanceof Error ? error.message : String(error)}`);
58
- }
59
- };
60
- return processVideo(1);
61
- };
62
- export default videoToGif;
package/dist/lib/utils.js DELETED
@@ -1,82 +0,0 @@
1
- import { Readable } from 'stream';
2
- import fs from 'fs-extra';
3
- export default class Utils {
4
- constructor() { }
5
- /**
6
- * Converts various types of input data to a Buffer.
7
- * @param data Input data as Buffer, string (file path), or Readable stream.
8
- * @returns Promise<Buffer> A Promise resolving to the converted Buffer.
9
- * @throws Error if conversion fails.
10
- */
11
- async buffer(data) {
12
- try {
13
- const buffer = typeof data === 'string'
14
- ? await fs.promises.readFile(data)
15
- : data instanceof Readable
16
- ? await this.streamToBuffer(data)
17
- : Buffer.from(data);
18
- return buffer;
19
- }
20
- catch (error) {
21
- throw new Error(`Error converting to buffer: ${error}`);
22
- }
23
- }
24
- /**
25
- * Converts a Readable stream to a Buffer.
26
- * @param stream Readable stream to convert.
27
- * @returns Promise<Buffer> A Promise resolving to the converted Buffer.
28
- */
29
- async streamToBuffer(stream) {
30
- const chunks = [];
31
- return new Promise((resolve, reject) => {
32
- stream.on('data', (chunk) => {
33
- if (Buffer.isBuffer(chunk)) {
34
- chunks.push(chunk);
35
- }
36
- else {
37
- chunks.push(Buffer.from(chunk));
38
- }
39
- });
40
- stream.on('end', () => {
41
- resolve(Buffer.concat(chunks));
42
- });
43
- stream.on('error', (err) => {
44
- reject(err);
45
- });
46
- });
47
- }
48
- /**
49
- * Determines the quality of the data based on its size.
50
- * @param data Buffer containing the data.
51
- * @returns number Quality value based on data size.
52
- */
53
- getQuality(data) {
54
- let buffer = Buffer.from(data);
55
- let bytes = buffer.length / 1024;
56
- let quality = bytes > 4 * 1024 ? 8 : bytes > 3 * 1024 ? 10 : bytes > 2 * 1024 ? 12 : 15;
57
- return quality;
58
- }
59
- /**
60
- * Determines the MIME type of the data buffer.
61
- * @param data Buffer containing the data.
62
- * @returns Promise<{ mime: string; ext: string }> A Promise resolving to an object with MIME type and extension.
63
- */
64
- async getMimeType(data) {
65
- try {
66
- const { fileTypeFromBuffer } = await import('file-type');
67
- const fileType = await fileTypeFromBuffer(data);
68
- return fileType;
69
- }
70
- catch (error) {
71
- console.error(`Error getting MIME type: ${error}`);
72
- return undefined;
73
- }
74
- }
75
- /**
76
- * Generates a random ID.
77
- * @returns string A random alphanumeric ID.
78
- */
79
- getId() {
80
- return [...Array(5)].map(() => Math.random().toString(36).substring(2, 15)).join('');
81
- }
82
- }
@@ -1,6 +0,0 @@
1
- export var StickerTypes;
2
- (function (StickerTypes) {
3
- StickerTypes[StickerTypes["DEFAULT"] = 0] = "DEFAULT";
4
- StickerTypes[StickerTypes["SQUARE"] = 1] = "SQUARE";
5
- StickerTypes[StickerTypes["CIRCLE"] = 2] = "CIRCLE";
6
- })(StickerTypes || (StickerTypes = {}));
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};