hp-shared Library

website·Indexed 30 days ago

https://feawaris.github.io/hp-shared

A shared library providing utility modules such as BaseEnv, _console, and _Number. Supports installation via command line, CDN, or Tampermonkey, with compatibility for ESM, CJS, and Python environments.

Tokens
3.6K
Snippets
28
Records
30
Agent score
25%

What's inside hp-shared

  1. Include hp-shared via CDN

    You can include hp-shared in a browser environment using unpkg or jsdelivr. For global mounting (e.g., for Tampermonkey-style usage), include the index-tampermonkey.js script.
    <!-- Using unpkg -->
    <script src="https://unpkg.com/hp-shared"></script>
    <script src="https://unpkg.com/hp-shared/dist/browser/index-tampermonkey.js"></script>
    
    <!-- Using jsdelivr -->
    <script src="https://cdn.jsdelivr.net/npm/hp-shared"></script>
    <script src="https://cdn.jsdelivr.net/npm/hp-shared/dist/browser/index-tampermonkey.js"></script>
  2. Install hp-shared via package managers

    The hp-shared library can be installed using various package managers depending on your environment (Node.js, HarmonyOS, or Python).
    # npm
    npm i hp-shared
    
    # pnpm
    pnpm i hp-shared
    
    # yarn
    yarn add hp-shared
    
    # ohpm (HarmonyOS)
    ohpm i hp-shared
    
    # pip (Python)
    pip install hp-shared
  3. Use _Reflect for object introspection

    The _Reflect module provides utilities that complement the native Reflect API, specifically ownValues and ownEntries, which serve as counterparts to Reflect.ownKeys.
    import { _Reflect } from 'hp-shared';
  4. Manipulate objects with _Object utilities

    The _Object module provides extended object manipulation methods beyond the standard JavaScript Object API:

    • keys, values, entries: Extended versions of standard Object methods with additional option handling.
    • getOwner: Retrieves the nearest object where a property is defined (including inherited properties).
    • getPropertyDescriptor / getPropertyDescriptors: Extended versions of standard descriptor methods.
    • assign / deepAssign: Performs shallow or deep merges, specifically handling properties with lazy evaluation (get/set) via re-definition.
    • filter: Filters object properties (see _Object.filter record).
    • bindThis: Binds this context to function properties of an object, useful for frameworks like Vue (e.g., @click="formInfo.click").
  5. Use cross-platform Web Storage utilities

    The _sessionStorage and _localStorage objects provide a unified interface for browser-like storage across Browser, Node.js, and WeChat. These utilities automatically handle JSON conversion for values during storage and retrieval.
    import { _sessionStorage, _localStorage } from 'hp-shared';
    
    // Store a value (automatically JSON stringified)
    _sessionStorage.setItem('a', 1);
    
    // Retrieve a value (automatically JSON parsed)
    const a = _sessionStorage.getItem('a');
    console.log(a);
  6. Use the cross-platform clipboard utility

    The clipboard module provides a unified API for copying and pasting text across Browser, Node.js, WeChat Mini Programs (wx), and Python environments. It supports both asynchronous and synchronous methods (where available).
    // Browser / WeChat
    import { clipboard } from 'hp-shared';
    await clipboard.copy('test');
    const text = await clipboard.paste();
    
    // Node.js
    const { clipboard } = require('hp-shared');
    await clipboard.copy('test');
    const text = await clipboard.paste();
    
    // Python
    from hp_shared.storage import clipboard
    import asyncio
    
    async def test():
        await clipboard.copy('test')
        text = await clipboard.paste()
        print(text)
    
    asyncio.run(test())
  7. Filter object properties using _Object.filter

    _Object.filter(target, options) allows for picking or omitting specific properties from an object, serving as a concise alternative to manual destructuring and re-collection.

    • pick: An array of keys to keep (additive).
    • omit: An array of keys to remove (subtractive).
    import { _Object } from 'hp-shared';
    
    const data = { a: 1, b: 2, c: 3, d: 4, e: 5 };
    
    // Pick specific properties
    const obj1 = _Object.filter(data, { pick: ['a', 'b', 'c'] }); // { a: 1, b: 2, c: 3 }
    
    // Omit specific properties
    const obj2 = _Object.filter(data, { omit: ['d', 'e'] }); // { a: 1, b: 2, c: 3 }
  8. Use cross-platform console and input utilities

    The _console instance (based on BaseConsole) and _input function provide a unified interface for logging and user input across Browser, Node.js, HarmonyOS, and Python.

    • _console: A default instance of BaseConsole for output. Supports standard methods like .log(), .warn(), .error(), and extended methods like .success() and .end() (though some may have limited support on HarmonyOS).
    • _input: A utility for capturing user input. Supported in Browser, Node.js, and Python; not supported in HarmonyOS or WeChat Mini Programs.
    • _print: An alias for _console.log, preferred for Python-style coding.
    // ESM
    import { _console, _input } from 'hp-shared';
    const text = _input('输入内容:');
    _console.log(text);
    
    // CommonJS
    const { _console, _input } = require('hp-shared');
    (async function () {
      const text = await _input('输入内容:');
      _console.log(text);
    })();
    # Python
    from hp_shared.base import _console, _input
    text = _input('输入内容:')
    _console.log(text)
  9. Manage Web Cookies with BaseCookie

    The BaseCookie class provides a standardized way to handle cookies across Browser, Node.js, and WeChat environments. In Node.js/Koa, you instantiate NodeCookie by passing the request and response objects.
    // Node.js
    const { NodeCookie } = require('hp-shared');
    http.createServer((req, res) => {
      const cookie = new NodeCookie(req, res);
    });
    
    // Koa
    const { NodeCookie } = require('hp-shared');
    router.get('/test', (ctx) => {
      const cookie = new NodeCookie(ctx.req, ctx.res);
    });
  10. Use function utilities from _Function

    The _Function module provides functional programming helpers:

    • pipe: Implements a pipeline operation (e.g., x |> f1 |> f2).
    • NOOP: A standard empty function.
    • RAW: A function that returns the input value unchanged.
    • TRUE / FALSE: Functions that consistently return true or false respectively.
    import { _Function } from 'hp-shared';
  11. Cross-platform environment utilities in BaseEnv

    The BaseEnv module provides a unified way to handle environment-specific actions like exiting or restarting the application across different platforms.