@ylsoo/core 1.0.0 → 2.0.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/README.md CHANGED
@@ -1,19 +1,94 @@
1
- # @ylsoo/core
1
+ <div align="center">
2
+ <h1>@ylsoo/core (v2.0 Enterprise)</h1>
3
+ <p><b>The official, enterprise-grade SDK powering advanced Ylsoo web and server products.</b></p>
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@ylsoo/core.svg?style=flat-square)](https://www.npmjs.com/package/@ylsoo/core)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
7
+ [![TypeScript Ready](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)](https://www.typescriptlang.org/)
8
+ [![Cross-Platform](https://img.shields.io/badge/Cross--Platform-Node.js%20%7C%20Browser-brightgreen?style=flat-square)](#)
9
+ </div>
2
10
 
3
- Core utility functions for Ylsoo projects.
11
+ <hr>
4
12
 
5
- ## Installation
13
+ ## 🚀 Overview
14
+
15
+ `@ylsoo/core` v2 has been completely rewritten into a powerful, modular architecture. It provides blazing-fast utility functions designed specifically for Ylsoo services. It runs identically on **modern browsers** and **Node.js** servers thanks to custom polyfills acting entirely natively, without a single external dependency!
16
+
17
+ ## 📦 Installation
6
18
 
7
19
  ```bash
8
20
  npm i @ylsoo/core
9
21
  ```
10
22
 
11
- ## Usage
23
+ ## 🛠️ API Reference
12
24
 
25
+ ### 1. 🔐 Distributed Security (`ylsoo.crypto`)
26
+ Leverages Web Crypto API natively to perform secure operations identically across browsers and servers.
13
27
  ```javascript
14
28
  const ylsoo = require('@ylsoo/core');
15
29
 
16
- ylsoo.log('Hello World');
17
- console.log(ylsoo.capitalize('hello'));
18
- console.log(ylsoo.isEmpty(''));
30
+ // 1. Generate Secure V4 UUIDs
31
+ const sessionID = ylsoo.crypto.uuid();
32
+
33
+ // 2. Hash strings natively
34
+ const secretHash = await ylsoo.crypto.hash('my_super_secret');
35
+
36
+ // 3. Encode/Decode Base64
37
+ const encoded = ylsoo.crypto.encodeBase64('user:pass');
38
+ ```
39
+
40
+ ### 2. ⚡ Event Bus (`ylsoo.events`)
41
+ An enterprise Publisher/Subscriber mechanism to handle inter-component state within Ylsoo frontends or microservices.
42
+ ```javascript
43
+ // Component A (Subscribes)
44
+ const unsubscribe = ylsoo.events.on('user:login', (user) => {
45
+ console.log('Welcome back,', user.name);
46
+ });
47
+
48
+ // Component B (Publishes)
49
+ ylsoo.events.emit('user:login', { name: 'Admin' });
50
+
51
+ // Listen exactly once
52
+ ylsoo.events.once('system:boot', bootFunction);
53
+ ```
54
+
55
+ ### 3. 🌐 Ylsoo Request Engine (`ylsoo.http`)
56
+ A robust wrapper around the versatile `fetch` API. It handles JSON stringification, applies custom headers, parses JSON, and safely formats errors automatically.
57
+ ```javascript
58
+ async function fetchUserData() {
59
+ try {
60
+ const data = await ylsoo.http.get('https://api.ylsoo.com/v1/user/me');
61
+ } catch (error) {
62
+ ylsoo.logger.error('Failed to fetch user', error);
63
+ }
64
+ }
65
+ ```
66
+
67
+ ### 4. 🧠 Ylsoo Memory Cache (`ylsoo.cache`)
68
+ A volatile in-memory Map structure featuring native Time-To-Live (TTL) functionality.
69
+ ```javascript
70
+ // Cache an object for 5000 ms (5 seconds)
71
+ ylsoo.cache.set('session', { id: 123 }, 5000);
72
+ const session = ylsoo.cache.get('session');
73
+ ```
74
+
75
+ ### 5. 🖥️ Ylsoo Console (`ylsoo.logger`)
76
+ Formatted console utility employing native ANSI escape codes specifically designed for local backends.
77
+ ```javascript
78
+ ylsoo.logger.info('System initializing...');
79
+ ylsoo.logger.success('Database connected successfully!');
80
+ ylsoo.logger.warn('Rate limit approaching.');
81
+ ylsoo.logger.error('Critical failure detected.');
19
82
  ```
83
+
84
+ ### 6. 🧰 Native Enterprise Utilies
85
+ - **`ylsoo.sleep(ms)`**: Promise-based execution halter.
86
+ - **`ylsoo.deepClone(obj)`**: Safely deep clones utilizing native modern standards like `structuredClone` when available.
87
+ - **`ylsoo.debounce(func, wait)`**: High performance throttling mechanics.
88
+ - **`ylsoo.isEmpty(val)`**: Semantic entity verification (detects empty Sets, Maps, Objects, Strings, Arrays).
89
+ - **`ylsoo.capitalize(str)`**: Automatic string standardizer.
90
+
91
+ ---
92
+ <div align="center">
93
+ <p>Built with ❤️ by <b>Ylsoo</b>.</p>
94
+ </div>
package/index.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * @ylsoo/core v2.0.0 Type Definitions
3
+ * Cross-platform Enterprise SDK
4
+ */
5
+
6
+ declare module '@ylsoo/core' {
7
+
8
+ // --- Core Modules ---
9
+
10
+ export class YlsooLogger {
11
+ info(message: string | any): void;
12
+ success(message: string | any): void;
13
+ warn(message: string | any): void;
14
+ error(message: string | any): void;
15
+ }
16
+
17
+ export class YlsooCache {
18
+ set(key: string, value: any, ttlMs?: number): void;
19
+ get<T = any>(key: string): T | null;
20
+ delete(key: string): boolean;
21
+ clear(): void;
22
+ }
23
+
24
+ export interface YlsooHttpOptions {
25
+ method?: string;
26
+ headers?: Record<string, string>;
27
+ body?: any;
28
+ [key: string]: any;
29
+ }
30
+
31
+ export class YlsooHttp {
32
+ request<T = any>(endpoint: string, options?: YlsooHttpOptions): Promise<T>;
33
+ get<T = any>(endpoint: string, headers?: Record<string, string>): Promise<T>;
34
+ post<T = any>(endpoint: string, body: any, headers?: Record<string, string>): Promise<T>;
35
+ }
36
+
37
+ // --- Security Modules ---
38
+
39
+ export class YlsooCrypto {
40
+ /** Base64 encodes a utf-8 string securely */
41
+ encodeBase64(str: string): string;
42
+
43
+ /** Base64 decodes a string */
44
+ decodeBase64(base64: string): string;
45
+
46
+ /** Natively generates a secure SHA-256 hash */
47
+ hash(str: string): Promise<string>;
48
+
49
+ /** Generates a cryptographically strong v4 UUID */
50
+ uuid(): string;
51
+ }
52
+
53
+ // --- Event Modules ---
54
+
55
+ export class YlsooEventBus {
56
+ /** Subscribe to an event. Returns an unsubscribe function. */
57
+ on(event: string, callback: (data?: any) => void): () => void;
58
+
59
+ /** Unsubscribe from an event. */
60
+ off(event: string, callback: (data?: any) => void): void;
61
+
62
+ /** Publish an event to all subscribers. */
63
+ emit(event: string, data?: any): void;
64
+
65
+ /** Subscribe to an event, un-subscribing immediately after first emission. */
66
+ once(event: string, callback: (data?: any) => void): void;
67
+
68
+ /** clear all event listeners */
69
+ clear(): void;
70
+ }
71
+
72
+ // --- Main Export ---
73
+
74
+ export class YlsooCore {
75
+ version: string;
76
+
77
+ // Systems
78
+ logger: YlsooLogger;
79
+ cache: YlsooCache;
80
+ http: YlsooHttp;
81
+ crypto: YlsooCrypto;
82
+ events: YlsooEventBus;
83
+
84
+ // Utilities
85
+ sleep(ms: number): Promise<void>;
86
+ deepClone<T>(obj: T): T;
87
+ debounce<T extends (...args: any[]) => any>(func: T, wait: number): (...args: Parameters<T>) => void;
88
+ isEmpty(value: any): boolean;
89
+ capitalize(str: string): string;
90
+ }
91
+
92
+ const ylsoo: YlsooCore;
93
+ export default ylsoo;
94
+ }
package/package.json CHANGED
@@ -1,17 +1,30 @@
1
1
  {
2
2
  "name": "@ylsoo/core",
3
- "version": "1.0.0",
4
- "description": "Core utility functions for Ylsoo projects",
5
- "main": "index.js",
3
+ "version": "2.0.0",
4
+ "description": "Enterprise cross-platform SDK for Ylsoo projects",
5
+ "main": "src/index.js",
6
+ "types": "index.d.ts",
7
+ "files": [
8
+ "src/",
9
+ "index.d.ts",
10
+ "README.md"
11
+ ],
6
12
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
13
+ "test": "node test.js"
8
14
  },
9
15
  "keywords": [
10
16
  "ylsoo",
11
17
  "core",
12
- "utilities"
18
+ "enterprise",
19
+ "sdk",
20
+ "fetch",
21
+ "logger",
22
+ "cache",
23
+ "crypto",
24
+ "uuid",
25
+ "events"
13
26
  ],
14
- "author": "",
15
- "license": "ISC",
27
+ "author": "Ylsoo",
28
+ "license": "MIT",
16
29
  "type": "commonjs"
17
30
  }
@@ -0,0 +1,31 @@
1
+ class YlsooCache {
2
+ constructor() {
3
+ this.store = new Map();
4
+ }
5
+
6
+ set(key, value, ttlMs = 0) {
7
+ const expiresAt = ttlMs > 0 ? Date.now() + ttlMs : null;
8
+ this.store.set(key, { value, expiresAt });
9
+ }
10
+
11
+ get(key) {
12
+ const item = this.store.get(key);
13
+ if (!item) return null;
14
+
15
+ if (item.expiresAt && Date.now() > item.expiresAt) {
16
+ this.store.delete(key);
17
+ return null;
18
+ }
19
+ return item.value;
20
+ }
21
+
22
+ delete(key) {
23
+ return this.store.delete(key);
24
+ }
25
+
26
+ clear() {
27
+ this.store.clear();
28
+ }
29
+ }
30
+
31
+ module.exports = { YlsooCache };
@@ -0,0 +1,39 @@
1
+ class YlsooLogger {
2
+ constructor() {
3
+ this.colors = {
4
+ reset: "\x1b[0m",
5
+ info: "\x1b[36m", // Cyan
6
+ success: "\x1b[32m", // Green
7
+ warn: "\x1b[33m", // Yellow
8
+ error: "\x1b[31m", // Red
9
+ ylsoo: "\x1b[35m" // Magenta
10
+ };
11
+ }
12
+
13
+ _format(level, message, color) {
14
+ // Only use colors in Node.js, not browsers. Check process briefly.
15
+ const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
16
+ if (isNode) {
17
+ return `${this.colors.ylsoo}[Ylsoo]${this.colors.reset} ${color}[${level.toUpperCase()}]${this.colors.reset} ${message}`;
18
+ }
19
+ return `[Ylsoo] [${level.toUpperCase()}] ${message}`;
20
+ }
21
+
22
+ info(message) {
23
+ console.log(this._format('info', message, this.colors.info));
24
+ }
25
+
26
+ success(message) {
27
+ console.log(this._format('success', message, this.colors.success));
28
+ }
29
+
30
+ warn(message) {
31
+ console.warn(this._format('warn', message, this.colors.warn));
32
+ }
33
+
34
+ error(message) {
35
+ console.error(this._format('error', message, this.colors.error));
36
+ }
37
+ }
38
+
39
+ module.exports = { YlsooLogger };
@@ -0,0 +1,69 @@
1
+ class YlsooEventBus {
2
+ constructor() {
3
+ this.events = {};
4
+ }
5
+
6
+ /**
7
+ * Subscribe to an event
8
+ * @param {string} event
9
+ * @param {Function} callback
10
+ * @returns {Function} Unsubscribe function
11
+ */
12
+ on(event, callback) {
13
+ if (!this.events[event]) {
14
+ this.events[event] = [];
15
+ }
16
+ this.events[event].push(callback);
17
+
18
+ // Return an un-subscriber
19
+ return () => this.off(event, callback);
20
+ }
21
+
22
+ /**
23
+ * Unsubscribe from an event
24
+ * @param {string} event
25
+ * @param {Function} callback
26
+ */
27
+ off(event, callback) {
28
+ if (!this.events[event]) return;
29
+ this.events[event] = this.events[event].filter(cb => cb !== callback);
30
+ }
31
+
32
+ /**
33
+ * Publish an event with optional payload
34
+ * @param {string} event
35
+ * @param {*} data
36
+ */
37
+ emit(event, data) {
38
+ if (!this.events[event]) return;
39
+ this.events[event].forEach(callback => {
40
+ try {
41
+ callback(data);
42
+ } catch (err) {
43
+ console.error(`[Ylsoo Event Bus] Error in callback for event "${event}":`, err);
44
+ }
45
+ });
46
+ }
47
+
48
+ /**
49
+ * Listen for an event exactly once
50
+ * @param {string} event
51
+ * @param {Function} callback
52
+ */
53
+ once(event, callback) {
54
+ const wrapper = (data) => {
55
+ this.off(event, wrapper);
56
+ callback(data);
57
+ };
58
+ this.on(event, wrapper);
59
+ }
60
+
61
+ /**
62
+ * Clear all events
63
+ */
64
+ clear() {
65
+ this.events = {};
66
+ }
67
+ }
68
+
69
+ module.exports = { YlsooEventBus };
@@ -0,0 +1,49 @@
1
+ class YlsooHttp {
2
+ async request(endpoint, options = {}) {
3
+ const defaultHeaders = {
4
+ 'Content-Type': 'application/json',
5
+ 'User-Agent': 'Ylsoo-Core/2.0'
6
+ };
7
+
8
+ const config = {
9
+ ...options,
10
+ headers: {
11
+ ...defaultHeaders,
12
+ ...options.headers
13
+ }
14
+ };
15
+
16
+ if (config.body && typeof config.body === 'object') {
17
+ config.body = JSON.stringify(config.body);
18
+ }
19
+
20
+ try {
21
+ const response = await fetch(endpoint, config);
22
+ const isJson = response.headers.get('content-type')?.includes('application/json');
23
+
24
+ const data = isJson ? await response.json() : await response.text();
25
+
26
+ if (!response.ok) {
27
+ throw {
28
+ status: response.status,
29
+ message: response.statusText,
30
+ data
31
+ };
32
+ }
33
+
34
+ return data;
35
+ } catch (error) {
36
+ throw new Error(`[Ylsoo HTTP Error]: ${error.message || JSON.stringify(error)}`);
37
+ }
38
+ }
39
+
40
+ get(endpoint, headers = {}) {
41
+ return this.request(endpoint, { method: 'GET', headers });
42
+ }
43
+
44
+ post(endpoint, body, headers = {}) {
45
+ return this.request(endpoint, { method: 'POST', body, headers });
46
+ }
47
+ }
48
+
49
+ module.exports = { YlsooHttp };
package/src/index.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @ylsoo/core v2.0.0
3
+ * Enterprise utilities for both Node.js and the Web.
4
+ */
5
+
6
+ const { YlsooHttp } = require('./http/client');
7
+ const { YlsooLogger } = require('./core/logger');
8
+ const { YlsooCache } = require('./core/cache');
9
+ const { YlsooCrypto } = require('./security/crypto');
10
+ const { YlsooEventBus } = require('./events/bus');
11
+ const { YlsooHelpers } = require('./utils/helpers');
12
+
13
+ class YlsooCore {
14
+ constructor() {
15
+ this.version = '2.0.0';
16
+
17
+ // Core Modules
18
+ this.http = new YlsooHttp();
19
+ this.logger = new YlsooLogger();
20
+ this.cache = new YlsooCache();
21
+
22
+ // Advanced Modules
23
+ this.crypto = new YlsooCrypto();
24
+ this.events = new YlsooEventBus();
25
+ this.helpers = new YlsooHelpers();
26
+ }
27
+
28
+ // --- Helper Proxies to keep backwards compatibility with v1.1.0 ---
29
+ sleep(ms) { return this.helpers.sleep(ms); }
30
+ deepClone(obj) { return this.helpers.deepClone(obj); }
31
+ debounce(func, wait) { return this.helpers.debounce(func, wait); }
32
+ isEmpty(val) { return this.helpers.isEmpty(val); }
33
+ capitalize(str) { return this.helpers.capitalize(str); }
34
+ }
35
+
36
+ module.exports = new YlsooCore();
@@ -0,0 +1,67 @@
1
+ class YlsooCrypto {
2
+ /**
3
+ * Base64 encode a string
4
+ * @param {string} str
5
+ * @returns {string}
6
+ */
7
+ encodeBase64(str) {
8
+ if (typeof globalThis.btoa === 'function') {
9
+ return globalThis.btoa(str);
10
+ }
11
+ return Buffer.from(str).toString('base64');
12
+ }
13
+
14
+ /**
15
+ * Base64 decode a string
16
+ * @param {string} base64
17
+ * @returns {string}
18
+ */
19
+ decodeBase64(base64) {
20
+ if (typeof globalThis.atob === 'function') {
21
+ return globalThis.atob(base64);
22
+ }
23
+ return Buffer.from(base64, 'base64').toString('utf-8');
24
+ }
25
+
26
+ /**
27
+ * Creates a SHA-256 hash of a string natively
28
+ * @param {string} str
29
+ * @returns {Promise<string>}
30
+ */
31
+ async hash(str) {
32
+ // Attempt standard Web Crypto API (Browser + Modern Node)
33
+ if (globalThis.crypto && globalThis.crypto.subtle) {
34
+ const msgBuffer = new TextEncoder().encode(str);
35
+ const hashBuffer = await globalThis.crypto.subtle.digest('SHA-256', msgBuffer);
36
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
37
+ return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
38
+ }
39
+
40
+ // Fallback for older Node.js contexts
41
+ try {
42
+ const crypto = require('crypto');
43
+ return crypto.createHash('sha256').update(str).digest('hex');
44
+ } catch(err) {
45
+ throw new Error('[Ylsoo Crypto Error] No secure hashing engine available on this platform.');
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Generate a secure random v4 UUID
51
+ * @returns {string}
52
+ */
53
+ uuid() {
54
+ if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {
55
+ return globalThis.crypto.randomUUID();
56
+ }
57
+
58
+ // Fallback UUID v4 generator
59
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
60
+ const r = Math.random() * 16 | 0;
61
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
62
+ return v.toString(16);
63
+ });
64
+ }
65
+ }
66
+
67
+ module.exports = { YlsooCrypto };
@@ -0,0 +1,43 @@
1
+ class YlsooHelpers {
2
+ sleep(ms) {
3
+ return new Promise(resolve => setTimeout(resolve, ms));
4
+ }
5
+
6
+ deepClone(obj) {
7
+ if (typeof structuredClone === 'function') {
8
+ return structuredClone(obj);
9
+ }
10
+ return JSON.parse(JSON.stringify(obj));
11
+ }
12
+
13
+ debounce(func, wait) {
14
+ let timeout;
15
+ return function executedFunction(...args) {
16
+ const later = () => {
17
+ clearTimeout(timeout);
18
+ func(...args);
19
+ };
20
+ clearTimeout(timeout);
21
+ timeout = setTimeout(later, wait);
22
+ };
23
+ }
24
+
25
+ isEmpty(value) {
26
+ if (value === null || value === undefined) return true;
27
+ if (typeof value === 'string' || Array.isArray(value)) return value.length === 0;
28
+ if (typeof value === 'object') {
29
+ if (value instanceof Map || value instanceof Set) return value.size === 0;
30
+ return Object.keys(value).length === 0;
31
+ }
32
+ return false;
33
+ }
34
+
35
+ capitalize(str) {
36
+ if (typeof str !== 'string' || str.length === 0) {
37
+ return str;
38
+ }
39
+ return str.charAt(0).toUpperCase() + str.slice(1);
40
+ }
41
+ }
42
+
43
+ module.exports = { YlsooHelpers };
package/index.js DELETED
@@ -1,43 +0,0 @@
1
- /**
2
- * Ylsoo Core - Basic utility functions
3
- */
4
-
5
- class YlsooCore {
6
- constructor() {
7
- this.version = '1.0.0';
8
- }
9
-
10
- /**
11
- * Logs a message with prefix
12
- * @param {string} message - The message to log
13
- */
14
- log(message) {
15
- console.log(`[Ylsoo Core] ${message}`);
16
- }
17
-
18
- /**
19
- * Simple utility to capitalize a string
20
- * @param {string} str - The string to capitalize
21
- * @returns {string} Capitalized string
22
- */
23
- capitalize(str) {
24
- if (typeof str !== 'string' || str.length === 0) {
25
- return str;
26
- }
27
- return str.charAt(0).toUpperCase() + str.slice(1);
28
- }
29
-
30
- /**
31
- * Simple utility to check if value is empty
32
- * @param {*} value - The value to check
33
- * @returns {boolean} True if empty
34
- */
35
- isEmpty(value) {
36
- if (value === null || value === undefined) return true;
37
- if (typeof value === 'string' || Array.isArray(value)) return value.length === 0;
38
- if (typeof value === 'object') return Object.keys(value).length === 0;
39
- return false;
40
- }
41
- }
42
-
43
- module.exports = new YlsooCore();