Created
September 20, 2026 14:24
-
-
Save qianlifeng/8299ba9cd0478ef75a22537b9ffd5353 to your computer and use it in GitHub Desktop.
Wox.Plugin.RandomDataGenerator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // { | |
| // "Id": "cd22fbe8-af21-47c9-8ead-9484ad5abc2b", | |
| // "Name": "i18n:plugin_name", | |
| // "Author": "qianlifeng", | |
| // "Version": "1.0.0", | |
| // "MinWoxVersion": "2.4.2", | |
| // "Runtime": "NODEJS", | |
| // "Description": "i18n:plugin_description", | |
| // "Icon": "svg:<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='12' fill='#312e81'/><rect x='10' y='10' width='28' height='28' rx='6' fill='#4f46e5'/><circle cx='18' cy='18' r='2.6' fill='#fbbf24'/><circle cx='30' cy='18' r='2.6' fill='#fbbf24'/><circle cx='24' cy='24' r='2.6' fill='#fbbf24'/><circle cx='18' cy='30' r='2.6' fill='#fbbf24'/><circle cx='30' cy='30' r='2.6' fill='#fbbf24'/></svg>", | |
| // "TriggerKeywords": ["random", "rd"], | |
| // "SupportedOS": ["Windows", "Linux", "Macos"], | |
| // "Commands": [ | |
| // { "Command": "number", "Aliases": ["num", "int"], "Description": "i18n:cmd_number" }, | |
| // { "Command": "uuid", "Aliases": ["guid"], "Description": "i18n:cmd_uuid" }, | |
| // { "Command": "password", "Aliases": ["pwd", "pass"], "Description": "i18n:cmd_password" }, | |
| // { "Command": "email", "Description": "i18n:cmd_email" }, | |
| // { "Command": "name", "Description": "i18n:cmd_name" }, | |
| // { "Command": "phone", "Description": "i18n:cmd_phone" }, | |
| // { "Command": "color", "Aliases": ["hexcolor"], "Description": "i18n:cmd_color" }, | |
| // { "Command": "date", "Description": "i18n:cmd_date" }, | |
| // { "Command": "ip", "Description": "i18n:cmd_ip" }, | |
| // { "Command": "mac", "Description": "i18n:cmd_mac" }, | |
| // { "Command": "url", "Description": "i18n:cmd_url" }, | |
| // { "Command": "bool", "Aliases": ["boolean"], "Description": "i18n:cmd_bool" }, | |
| // { "Command": "hex", "Description": "i18n:cmd_hex" }, | |
| // { "Command": "lorem", "Description": "i18n:cmd_lorem" }, | |
| // { "Command": "words", "Aliases": ["word"], "Description": "i18n:cmd_words" }, | |
| // { "Command": "sentences", "Aliases": ["sentence"], "Description": "i18n:cmd_sentences" }, | |
| // { "Command": "paragraphs", "Aliases": ["paragraph", "para"], "Description": "i18n:cmd_paragraphs" }, | |
| // { "Command": "country", "Description": "i18n:cmd_country" } | |
| // ], | |
| // "SettingDefinitions": [ | |
| // { | |
| // "Type": "textbox", | |
| // "Value": { | |
| // "Key": "default_count", | |
| // "Label": "i18n:setting_default_count", | |
| // "Tooltip": "i18n:setting_default_count_tip", | |
| // "DefaultValue": "1", | |
| // "MaxLines": 1, | |
| // "Validators": [{ "Type": "is_number", "Value": { "IsInteger": true, "IsFloat": false } }], | |
| // "Style": { "Width": 160 } | |
| // }, | |
| // "IsPlatformSpecific": false | |
| // }, | |
| // { | |
| // "Type": "textbox", | |
| // "Value": { | |
| // "Key": "number_min", | |
| // "Label": "i18n:setting_number_min", | |
| // "Tooltip": "i18n:setting_number_min_tip", | |
| // "DefaultValue": "1", | |
| // "MaxLines": 1, | |
| // "Validators": [{ "Type": "is_number", "Value": { "IsInteger": false, "IsFloat": true } }], | |
| // "Style": { "Width": 160 } | |
| // }, | |
| // "IsPlatformSpecific": false | |
| // }, | |
| // { | |
| // "Type": "textbox", | |
| // "Value": { | |
| // "Key": "number_max", | |
| // "Label": "i18n:setting_number_max", | |
| // "Tooltip": "i18n:setting_number_max_tip", | |
| // "DefaultValue": "100", | |
| // "MaxLines": 1, | |
| // "Validators": [{ "Type": "is_number", "Value": { "IsInteger": false, "IsFloat": true } }], | |
| // "Style": { "Width": 160 } | |
| // }, | |
| // "IsPlatformSpecific": false | |
| // }, | |
| // { | |
| // "Type": "textbox", | |
| // "Value": { | |
| // "Key": "password_length", | |
| // "Label": "i18n:setting_password_length", | |
| // "Tooltip": "i18n:setting_password_length_tip", | |
| // "DefaultValue": "16", | |
| // "MaxLines": 1, | |
| // "Validators": [{ "Type": "is_number", "Value": { "IsInteger": true, "IsFloat": false } }], | |
| // "Style": { "Width": 160 } | |
| // }, | |
| // "IsPlatformSpecific": false | |
| // }, | |
| // { | |
| // "Type": "select", | |
| // "Value": { | |
| // "Key": "password_charset", | |
| // "Label": "i18n:setting_password_charset", | |
| // "Tooltip": "i18n:setting_password_charset_tip", | |
| // "DefaultValue": "all", | |
| // "IsMulti": false, | |
| // "Options": [ | |
| // { "Label": "i18n:charset_all", "Value": "all" }, | |
| // { "Label": "i18n:charset_alnum", "Value": "alnum" }, | |
| // { "Label": "i18n:charset_letters", "Value": "letters" }, | |
| // { "Label": "i18n:charset_digits", "Value": "digits" } | |
| // ] | |
| // }, | |
| // "IsPlatformSpecific": false | |
| // }, | |
| // { | |
| // "Type": "select", | |
| // "Value": { | |
| // "Key": "date_format", | |
| // "Label": "i18n:setting_date_format", | |
| // "Tooltip": "i18n:setting_date_format_tip", | |
| // "DefaultValue": "iso", | |
| // "IsMulti": false, | |
| // "Options": [ | |
| // { "Label": "i18n:date_iso", "Value": "iso" }, | |
| // { "Label": "i18n:date_datetime", "Value": "datetime" }, | |
| // { "Label": "i18n:date_unix", "Value": "unix" } | |
| // ] | |
| // }, | |
| // "IsPlatformSpecific": false | |
| // } | |
| // ], | |
| // "I18n": { | |
| // "en_US": { | |
| // "plugin_name": "Random Data Generator", | |
| // "plugin_description": "Generate random numbers, UUIDs, passwords, emails, names, colors, and more. Add a count, e.g. random number 10", | |
| // "cmd_number": "Random integers (count and optional range, e.g. number 10 1-100)", | |
| // "cmd_uuid": "Random UUID v4 values", | |
| // "cmd_password": "Random passwords (count and optional length)", | |
| // "cmd_email": "Random email addresses", | |
| // "cmd_name": "Random people names", | |
| // "cmd_phone": "Random phone numbers", | |
| // "cmd_color": "Random hex colors", | |
| // "cmd_date": "Random dates", | |
| // "cmd_ip": "Random IP addresses", | |
| // "cmd_mac": "Random MAC addresses", | |
| // "cmd_url": "Random URLs", | |
| // "cmd_bool": "Random true/false values", | |
| // "cmd_hex": "Random hex strings", | |
| // "cmd_lorem": "Random lorem text (words, sentences, or paragraphs)", | |
| // "cmd_words": "Random lorem words", | |
| // "cmd_sentences": "Random lorem sentences", | |
| // "cmd_paragraphs": "Random lorem paragraphs", | |
| // "cmd_country": "Random country names", | |
| // "setting_default_count": "Default count", | |
| // "setting_default_count_tip": "How many values to generate when no count is typed (1-100)", | |
| // "setting_number_min": "Number minimum", | |
| // "setting_number_min_tip": "Default lower bound for random number", | |
| // "setting_number_max": "Number maximum", | |
| // "setting_number_max_tip": "Default upper bound for random number", | |
| // "setting_password_length": "Password length", | |
| // "setting_password_length_tip": "Default password length (4-128)", | |
| // "setting_password_charset": "Password characters", | |
| // "setting_password_charset_tip": "Character set used when generating passwords", | |
| // "setting_date_format": "Date format", | |
| // "setting_date_format_tip": "How random dates are printed", | |
| // "charset_all": "Letters, digits, symbols", | |
| // "charset_alnum": "Letters and digits", | |
| // "charset_letters": "Letters only", | |
| // "charset_digits": "Digits only", | |
| // "date_iso": "YYYY-MM-DD", | |
| // "date_datetime": "YYYY-MM-DD HH:mm:ss", | |
| // "date_unix": "Unix timestamp", | |
| // "unknown_title": "Unknown format: %s", | |
| // "unknown_sub": "Try number, uuid, password, email, name, phone, color, date, ip, mac, url, bool, hex, lorem, words, sentences, paragraphs, country", | |
| // "capped_sub": "Count capped at %s", | |
| // "action_select": "Select", | |
| // "action_copy": "Copy", | |
| // "action_copy_json": "Copy JSON", | |
| // "action_copy_csv": "Copy comma-separated", | |
| // "action_regenerate": "Regenerate", | |
| // "notify_copied": "Copied to clipboard", | |
| // "notify_copy_failed": "Failed to copy", | |
| // "tool_generate": "Generate random values of a given format" | |
| // }, | |
| // "zh_CN": { | |
| // "plugin_name": "随机数据生成", | |
| // "plugin_description": "生成随机数字、UUID、密码、邮箱、姓名、颜色等。可指定数量,例如 random number 10", | |
| // "cmd_number": "随机整数(数量和可选范围,如 number 10 1-100)", | |
| // "cmd_uuid": "随机 UUID v4", | |
| // "cmd_password": "随机密码(数量和可选长度)", | |
| // "cmd_email": "随机邮箱", | |
| // "cmd_name": "随机姓名", | |
| // "cmd_phone": "随机电话号码", | |
| // "cmd_color": "随机十六进制颜色", | |
| // "cmd_date": "随机日期", | |
| // "cmd_ip": "随机 IP 地址", | |
| // "cmd_mac": "随机 MAC 地址", | |
| // "cmd_url": "随机 URL", | |
| // "cmd_bool": "随机真/假", | |
| // "cmd_hex": "随机十六进制字符串", | |
| // "cmd_lorem": "随机 Lorem 文本(单词、句子或段落)", | |
| // "cmd_words": "随机 Lorem 单词", | |
| // "cmd_sentences": "随机 Lorem 句子", | |
| // "cmd_paragraphs": "随机 Lorem 段落", | |
| // "cmd_country": "随机国家/地区", | |
| // "setting_default_count": "默认数量", | |
| // "setting_default_count_tip": "未输入数量时生成多少条(1-100)", | |
| // "setting_number_min": "数字下限", | |
| // "setting_number_min_tip": "随机数字的默认最小值", | |
| // "setting_number_max": "数字上限", | |
| // "setting_number_max_tip": "随机数字的默认最大值", | |
| // "setting_password_length": "密码长度", | |
| // "setting_password_length_tip": "默认密码长度(4-128)", | |
| // "setting_password_charset": "密码字符集", | |
| // "setting_password_charset_tip": "生成密码时使用的字符", | |
| // "setting_date_format": "日期格式", | |
| // "setting_date_format_tip": "随机日期的输出格式", | |
| // "charset_all": "字母、数字、符号", | |
| // "charset_alnum": "字母和数字", | |
| // "charset_letters": "仅字母", | |
| // "charset_digits": "仅数字", | |
| // "date_iso": "YYYY-MM-DD", | |
| // "date_datetime": "YYYY-MM-DD HH:mm:ss", | |
| // "date_unix": "Unix 时间戳", | |
| // "unknown_title": "未知格式:%s", | |
| // "unknown_sub": "可用 number、uuid、password、email、name、phone、color、date、ip、mac、url、bool、hex、lorem、words、sentences、paragraphs、country", | |
| // "capped_sub": "数量已限制为 %s", | |
| // "action_select": "选择", | |
| // "action_copy": "复制", | |
| // "action_copy_json": "复制 JSON", | |
| // "action_copy_csv": "复制逗号分隔", | |
| // "action_regenerate": "重新生成", | |
| // "notify_copied": "已复制到剪贴板", | |
| // "notify_copy_failed": "复制失败", | |
| // "tool_generate": "按指定格式生成随机值" | |
| // } | |
| // } | |
| // } | |
| /** | |
| * Random Data Generator — single-file Node.js SDK plugin. | |
| * | |
| * MRU is skipped: each query is a one-shot sample. Restoring a previous | |
| * UUID or password on the start page would either replay stale secrets or | |
| * silently generate a different value. | |
| * | |
| * MinWoxVersion stays 2.4.2 (single-file floor). Plugin Tools and | |
| * GetThemeColors register/load only when the running Wox exposes them (2.4.5+). | |
| */ | |
| const crypto = require("crypto") | |
| const MAX_COUNT = 100 | |
| const MIN_PASSWORD_LENGTH = 4 | |
| const MAX_PASSWORD_LENGTH = 128 | |
| const MIN_HEX_LENGTH = 2 | |
| const MAX_HEX_LENGTH = 128 | |
| const DEFAULT_COUNT = 1 | |
| const DEFAULT_NUMBER_MIN = 1 | |
| const DEFAULT_NUMBER_MAX = 100 | |
| const DEFAULT_PASSWORD_LENGTH = 16 | |
| const DEFAULT_PASSWORD_CHARSET = "all" | |
| const DEFAULT_DATE_FORMAT = "iso" | |
| const SETTING_DEFAULT_COUNT = "default_count" | |
| const SETTING_NUMBER_MIN = "number_min" | |
| const SETTING_NUMBER_MAX = "number_max" | |
| const SETTING_PASSWORD_LENGTH = "password_length" | |
| const SETTING_PASSWORD_CHARSET = "password_charset" | |
| const SETTING_DATE_FORMAT = "date_format" | |
| const RESULT_ICON = { | |
| ImageType: "svg", | |
| ImageData: "<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='12' fill='#312e81'/><rect x='10' y='10' width='28' height='28' rx='6' fill='#4f46e5'/><circle cx='18' cy='18' r='2.6' fill='#fbbf24'/><circle cx='30' cy='18' r='2.6' fill='#fbbf24'/><circle cx='24' cy='24' r='2.6' fill='#fbbf24'/><circle cx='18' cy='30' r='2.6' fill='#fbbf24'/><circle cx='30' cy='30' r='2.6' fill='#fbbf24'/></svg>" | |
| } | |
| const ACTION_COPY_ICON = { | |
| ImageType: "svg", | |
| ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"8\" y=\"8\" width=\"12\" height=\"12\" rx=\"2\"/><path d=\"M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2\"/></svg>" | |
| } | |
| const ACTION_EXECUTE_ICON = { | |
| ImageType: "svg", | |
| ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M13 2 4.5 13.5h5.5L9 22l10-13h-6z\"/></svg>" | |
| } | |
| const ACTION_REGENERATE_ICON = ACTION_EXECUTE_ICON | |
| const FIRST_NAMES = [ | |
| "Ava", "Noah", "Mia", "Liam", "Zoe", "Ethan", "Luna", "Owen", "Ivy", "Caleb", | |
| "Nora", "Julian", "Chloe", "Leo", "Hannah", "Miles", "Ruby", "Felix", "Ella", "Kai", | |
| "Sofia", "Hugo", "Alice", "Theo", "Grace", "Nolan", "Clara", "Adrian", "Quinn", "Iris" | |
| ] | |
| const LAST_NAMES = [ | |
| "Walker", "Nguyen", "Patel", "Garcia", "Kim", "Silva", "Andersen", "Rossi", "Müller", "Sato", | |
| "Cohen", "Dubois", "Khan", "Okafor", "Berg", "Costa", "Novak", "Ibrahim", "Larsen", "Moreau", | |
| "Singh", "Nakamura", "Almeida", "Petrov", "Johansson", "Fernandez", "O'Neil", "Brooks", "Hayes", "Reed" | |
| ] | |
| const EMAIL_DOMAINS = ["example.com", "example.org", "example.net", "mail.test", "inbox.dev"] | |
| const URL_HOSTS = ["example.com", "example.org", "demo.test", "sample.dev"] | |
| const URL_PATHS = ["alpha", "bravo", "catalog", "docs", "items", "profile", "search", "status"] | |
| const LOREM_WORDS = [ | |
| "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", | |
| "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", | |
| "minim", "veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", | |
| "ea", "commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", | |
| "esse", "cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non" | |
| ] | |
| const COUNTRIES = [ | |
| { name: "United States", code: "US" }, | |
| { name: "China", code: "CN" }, | |
| { name: "Japan", code: "JP" }, | |
| { name: "Germany", code: "DE" }, | |
| { name: "United Kingdom", code: "GB" }, | |
| { name: "France", code: "FR" }, | |
| { name: "Canada", code: "CA" }, | |
| { name: "Australia", code: "AU" }, | |
| { name: "Brazil", code: "BR" }, | |
| { name: "India", code: "IN" }, | |
| { name: "South Korea", code: "KR" }, | |
| { name: "Italy", code: "IT" }, | |
| { name: "Spain", code: "ES" }, | |
| { name: "Netherlands", code: "NL" }, | |
| { name: "Sweden", code: "SE" }, | |
| { name: "Norway", code: "NO" }, | |
| { name: "Singapore", code: "SG" }, | |
| { name: "Mexico", code: "MX" }, | |
| { name: "South Africa", code: "ZA" }, | |
| { name: "New Zealand", code: "NZ" } | |
| ] | |
| const CHARSETS = { | |
| all: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*_-+=?", | |
| alnum: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", | |
| letters: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", | |
| digits: "0123456789" | |
| } | |
| const FORMAT_ALIASES = { | |
| number: "number", | |
| num: "number", | |
| int: "number", | |
| integer: "number", | |
| uuid: "uuid", | |
| guid: "uuid", | |
| password: "password", | |
| pwd: "password", | |
| pass: "password", | |
| email: "email", | |
| mail: "email", | |
| name: "name", | |
| phone: "phone", | |
| tel: "phone", | |
| color: "color", | |
| hexcolor: "color", | |
| colour: "color", | |
| date: "date", | |
| ip: "ip", | |
| ipv4: "ip", | |
| ipv6: "ip", | |
| mac: "mac", | |
| url: "url", | |
| bool: "bool", | |
| boolean: "bool", | |
| hex: "hex", | |
| lorem: "lorem", | |
| ipsum: "lorem", | |
| words: "words", | |
| word: "words", | |
| sentences: "sentences", | |
| sentence: "sentences", | |
| paragraphs: "paragraphs", | |
| paragraph: "paragraphs", | |
| para: "paragraphs", | |
| country: "country" | |
| } | |
| const FORMAT_LABELS = { | |
| number: "number", | |
| uuid: "UUID", | |
| password: "password", | |
| email: "email", | |
| name: "name", | |
| phone: "phone", | |
| color: "color", | |
| date: "date", | |
| ip: "IP", | |
| mac: "MAC", | |
| url: "URL", | |
| bool: "boolean", | |
| hex: "hex", | |
| lorem: "lorem", | |
| words: "words", | |
| sentences: "sentences", | |
| paragraphs: "paragraphs", | |
| country: "country" | |
| } | |
| const CATALOG_FORMATS = ["number", "uuid", "password", "email", "name", "color", "phone", "date", "words", "sentences", "paragraphs"] | |
| function resultTails(request) { | |
| if (request && request.countSpecified && request.count > 1) { | |
| return [{ Type: "text", Text: `x${request.count}` }] | |
| } | |
| return [] | |
| } | |
| const FORMAT_ENUM = Object.keys(FORMAT_LABELS) | |
| const COMMAND_ENTRIES = (() => { | |
| const byFormat = new Map() | |
| for (const [alias, format] of Object.entries(FORMAT_ALIASES)) { | |
| let entry = byFormat.get(format) | |
| if (!entry) { | |
| entry = { command: format, aliases: [], format } | |
| byFormat.set(format, entry) | |
| } | |
| if (alias !== format && !entry.aliases.includes(alias)) { | |
| entry.aliases.push(alias) | |
| } | |
| } | |
| return Array.from(byFormat.values()) | |
| })() | |
| function commandMatches(item, needle) { | |
| if (item.command.startsWith(needle)) { | |
| return true | |
| } | |
| if ((FORMAT_LABELS[item.format] || "").toLowerCase().startsWith(needle)) { | |
| return true | |
| } | |
| return item.aliases.some(alias => alias.startsWith(needle)) | |
| } | |
| function filterCommands(token) { | |
| const needle = String(token || "").trim().toLowerCase() | |
| if (!needle) { | |
| return COMMAND_ENTRIES.slice() | |
| } | |
| return COMMAND_ENTRIES.filter(item => commandMatches(item, needle)) | |
| } | |
| function defaultRng() { | |
| return { | |
| int(min, max) { | |
| const lo = Math.trunc(min) | |
| const hi = Math.trunc(max) | |
| if (hi < lo) { | |
| return crypto.randomInt(hi, lo + 1) | |
| } | |
| if (lo === hi) { | |
| return lo | |
| } | |
| return crypto.randomInt(lo, hi + 1) | |
| }, | |
| bytes(n) { | |
| return crypto.randomBytes(n) | |
| }, | |
| uuid() { | |
| return crypto.randomUUID() | |
| } | |
| } | |
| } | |
| function clamp(value, min, max) { | |
| return Math.min(max, Math.max(min, value)) | |
| } | |
| function parseInteger(text, fallback) { | |
| const value = Number.parseInt(String(text ?? "").trim(), 10) | |
| if (!Number.isFinite(value)) { | |
| return fallback | |
| } | |
| return value | |
| } | |
| function parseNumber(text, fallback) { | |
| const value = Number(String(text ?? "").trim()) | |
| if (!Number.isFinite(value)) { | |
| return fallback | |
| } | |
| return value | |
| } | |
| function resolveFormat(token) { | |
| const key = String(token || "").trim().toLowerCase() | |
| return FORMAT_ALIASES[key] || "" | |
| } | |
| function argumentValue(hint, id) { | |
| const elements = hint && Array.isArray(hint.Elements) ? hint.Elements : [] | |
| const match = elements.find(item => item && item.Id === id && item.Kind === "argument") | |
| return match && match.Value ? String(match.Value).trim() : "" | |
| } | |
| function parseRangeToken(text) { | |
| const raw = String(text || "").trim() | |
| const match = raw.match(/^(-?\d+(?:\.\d+)?)\s*(?:-|~|\.\.|to)\s*(-?\d+(?:\.\d+)?)$/i) | |
| if (!match) { | |
| return null | |
| } | |
| const min = Number(match[1]) | |
| const max = Number(match[2]) | |
| if (!Number.isFinite(min) || !Number.isFinite(max)) { | |
| return null | |
| } | |
| const isFloat = match[1].includes(".") || match[2].includes(".") | |
| return { min: Math.min(min, max), max: Math.max(min, max), isFloat } | |
| } | |
| function parseDateToken(text) { | |
| const raw = String(text || "").trim() | |
| if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) { | |
| const ms = Date.parse(`${raw}T00:00:00Z`) | |
| return Number.isFinite(ms) ? ms : null | |
| } | |
| if (/^\d{4}$/.test(raw)) { | |
| const ms = Date.parse(`${raw}-01-01T00:00:00Z`) | |
| return Number.isFinite(ms) ? ms : null | |
| } | |
| return null | |
| } | |
| function isCountToken(text) { | |
| return /^\d+$/.test(String(text || "").trim()) | |
| } | |
| function clampCount(value, fallback) { | |
| const parsed = parseInteger(value, fallback) | |
| if (!Number.isFinite(parsed) || parsed < 1) { | |
| return { count: fallback, capped: false } | |
| } | |
| if (parsed > MAX_COUNT) { | |
| return { count: MAX_COUNT, capped: true } | |
| } | |
| return { count: parsed, capped: false } | |
| } | |
| function defaultSettings() { | |
| return { | |
| defaultCount: DEFAULT_COUNT, | |
| numberMin: DEFAULT_NUMBER_MIN, | |
| numberMax: DEFAULT_NUMBER_MAX, | |
| passwordLength: DEFAULT_PASSWORD_LENGTH, | |
| passwordCharset: DEFAULT_PASSWORD_CHARSET, | |
| dateFormat: DEFAULT_DATE_FORMAT | |
| } | |
| } | |
| function normalizeSettings(raw) { | |
| const settings = defaultSettings() | |
| const count = clampCount(raw && raw.defaultCount, DEFAULT_COUNT) | |
| settings.defaultCount = count.count | |
| let min = parseNumber(raw && raw.numberMin, DEFAULT_NUMBER_MIN) | |
| let max = parseNumber(raw && raw.numberMax, DEFAULT_NUMBER_MAX) | |
| if (min > max) { | |
| const swap = min | |
| min = max | |
| max = swap | |
| } | |
| settings.numberMin = min | |
| settings.numberMax = max | |
| settings.passwordLength = clamp(parseInteger(raw && raw.passwordLength, DEFAULT_PASSWORD_LENGTH), MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH) | |
| const charset = String(raw && raw.passwordCharset || DEFAULT_PASSWORD_CHARSET).toLowerCase() | |
| settings.passwordCharset = CHARSETS[charset] ? charset : DEFAULT_PASSWORD_CHARSET | |
| const dateFormat = String(raw && raw.dateFormat || DEFAULT_DATE_FORMAT).toLowerCase() | |
| settings.dateFormat = ["iso", "datetime", "unix"].includes(dateFormat) ? dateFormat : DEFAULT_DATE_FORMAT | |
| return settings | |
| } | |
| function parseRequest(query, settings) { | |
| const normalized = normalizeSettings(settings) | |
| const command = String(query && query.Command || "").trim() | |
| const search = String(query && query.Search || "").trim() | |
| const hint = query && query.QueryHint | |
| const hintCount = argumentValue(hint, "count") | |
| const hintRange = argumentValue(hint, "range") | |
| const hintLength = argumentValue(hint, "length") | |
| const tokens = search ? search.split(/\s+/).filter(Boolean) : [] | |
| let formatId = resolveFormat(command) | |
| let rest = tokens | |
| if (!formatId && tokens.length) { | |
| const fromSearch = resolveFormat(tokens[0]) | |
| if (fromSearch) { | |
| formatId = fromSearch | |
| rest = tokens.slice(1) | |
| } | |
| } | |
| if (!formatId) { | |
| if (tokens.length && isCountToken(tokens[0])) { | |
| formatId = "number" | |
| rest = tokens | |
| } else if (!tokens.length && !command) { | |
| return { kind: "catalog" } | |
| } else { | |
| const token = tokens[0] || command | |
| const matches = filterCommands(token) | |
| if (matches.length && !command) { | |
| return { kind: "commands", token, matches } | |
| } | |
| return { kind: "unknown", token } | |
| } | |
| } | |
| return parseFormatArgs(formatId, rest, { hintCount, hintRange, hintLength }, normalized) | |
| } | |
| function parseFormatArgs(formatId, tokens, hints, settings) { | |
| let index = 0 | |
| let capped = false | |
| let count = settings.defaultCount | |
| let countSpecified = false | |
| if (hints.hintCount && isCountToken(hints.hintCount)) { | |
| const parsed = clampCount(hints.hintCount, settings.defaultCount) | |
| count = parsed.count | |
| capped = parsed.capped | |
| countSpecified = true | |
| } else if (tokens[0] && isCountToken(tokens[0])) { | |
| const parsed = clampCount(tokens[0], settings.defaultCount) | |
| count = parsed.count | |
| capped = parsed.capped | |
| countSpecified = true | |
| index = 1 | |
| } | |
| const rest = tokens.slice(index) | |
| const request = { | |
| kind: "generate", | |
| format: formatId, | |
| count, | |
| countSpecified, | |
| capped, | |
| min: settings.numberMin, | |
| max: settings.numberMax, | |
| isFloat: false, | |
| length: settings.passwordLength, | |
| charset: settings.passwordCharset, | |
| uuidStyle: "standard", | |
| nameStyle: "full", | |
| ipVersion: "v4", | |
| loremUnit: formatId === "words" || formatId === "sentences" || formatId === "paragraphs" ? formatId : "sentences", | |
| dateFormat: settings.dateFormat, | |
| startMs: Date.parse("2000-01-01T00:00:00Z"), | |
| endMs: Date.now() | |
| } | |
| if (formatId === "number") { | |
| applyNumberArgs(request, rest, hints.hintRange) | |
| } else if (formatId === "password" || formatId === "hex") { | |
| applyLengthArgs(request, rest, hints.hintLength, formatId) | |
| } else if (formatId === "uuid") { | |
| applyUuidArgs(request, rest) | |
| } else if (formatId === "name") { | |
| applyNameArgs(request, rest) | |
| } else if (formatId === "ip") { | |
| applyIpArgs(request, rest) | |
| } else if (formatId === "lorem" || formatId === "words" || formatId === "sentences" || formatId === "paragraphs") { | |
| applyLoremArgs(request, rest) | |
| } else if (formatId === "date") { | |
| applyDateArgs(request, rest) | |
| } | |
| return request | |
| } | |
| function applyNumberArgs(request, rest, hintRange) { | |
| const hinted = parseRangeToken(hintRange) | |
| if (hinted) { | |
| request.min = hinted.min | |
| request.max = hinted.max | |
| request.isFloat = hinted.isFloat | |
| } | |
| if (rest.length === 1) { | |
| const range = parseRangeToken(rest[0]) | |
| if (range) { | |
| request.min = range.min | |
| request.max = range.max | |
| request.isFloat = range.isFloat | |
| } else if (rest[0].toLowerCase() === "float") { | |
| request.isFloat = true | |
| } | |
| } else if (rest.length >= 2) { | |
| const joined = parseRangeToken(`${rest[0]}-${rest[1]}`) | |
| if (joined) { | |
| request.min = joined.min | |
| request.max = joined.max | |
| request.isFloat = joined.isFloat | |
| } | |
| if (rest.some(token => token.toLowerCase() === "float")) { | |
| request.isFloat = true | |
| } | |
| } | |
| if (request.min === request.max) { | |
| request.isFloat = false | |
| } | |
| } | |
| function applyLengthArgs(request, rest, hintLength, formatId) { | |
| const min = formatId === "hex" ? MIN_HEX_LENGTH : MIN_PASSWORD_LENGTH | |
| const max = formatId === "hex" ? MAX_HEX_LENGTH : MAX_PASSWORD_LENGTH | |
| const hinted = parseInteger(hintLength, 0) | |
| if (hinted >= min) { | |
| request.length = clamp(hinted, min, max) | |
| } | |
| if (rest[0] && isCountToken(rest[0])) { | |
| request.length = clamp(parseInteger(rest[0], request.length), min, max) | |
| } | |
| const charsetToken = rest.find(token => CHARSETS[String(token).toLowerCase()]) | |
| if (charsetToken) { | |
| request.charset = String(charsetToken).toLowerCase() | |
| } | |
| } | |
| function applyUuidArgs(request, rest) { | |
| const token = (rest[0] || "").toLowerCase() | |
| if (token === "n" || token === "nodash" || token === "compact") { | |
| request.uuidStyle = "nodash" | |
| } else if (token === "braces" || token === "b") { | |
| request.uuidStyle = "braces" | |
| } else if (token === "urn") { | |
| request.uuidStyle = "urn" | |
| } | |
| } | |
| function applyNameArgs(request, rest) { | |
| const token = (rest[0] || "").toLowerCase() | |
| if (token === "first" || token === "given") { | |
| request.nameStyle = "first" | |
| } else if (token === "last" || token === "family" || token === "surname") { | |
| request.nameStyle = "last" | |
| } | |
| } | |
| function applyIpArgs(request, rest) { | |
| const token = (rest[0] || "").toLowerCase() | |
| if (token === "v6" || token === "ipv6" || token === "6") { | |
| request.ipVersion = "v6" | |
| } | |
| } | |
| function applyLoremArgs(request, rest) { | |
| const token = (rest[0] || "").toLowerCase() | |
| if (token === "word" || token === "words") { | |
| request.loremUnit = "words" | |
| } else if (token === "paragraph" || token === "paragraphs") { | |
| request.loremUnit = "paragraphs" | |
| } else if (token === "sentence" || token === "sentences") { | |
| request.loremUnit = "sentences" | |
| } | |
| } | |
| function applyDateArgs(request, rest) { | |
| if (rest[0] && ["iso", "datetime", "unix"].includes(rest[0].toLowerCase())) { | |
| request.dateFormat = rest[0].toLowerCase() | |
| rest = rest.slice(1) | |
| } | |
| if (rest.length === 1) { | |
| const range = String(rest[0]).split(/[/:]/) | |
| if (range.length === 2) { | |
| const start = parseDateToken(range[0]) | |
| const end = parseDateToken(range[1]) | |
| if (start != null && end != null) { | |
| request.startMs = Math.min(start, end) | |
| request.endMs = Math.max(start, end) | |
| } | |
| } | |
| } else if (rest.length >= 2) { | |
| const start = parseDateToken(rest[0]) | |
| const end = parseDateToken(rest[1]) | |
| if (start != null && end != null) { | |
| request.startMs = Math.min(start, end) | |
| request.endMs = Math.max(start, end) | |
| } | |
| } | |
| if (request.endMs < request.startMs) { | |
| const swap = request.startMs | |
| request.startMs = request.endMs | |
| request.endMs = swap | |
| } | |
| } | |
| function pick(rng, list) { | |
| return list[rng.int(0, list.length - 1)] | |
| } | |
| function randomString(rng, alphabet, length) { | |
| let out = "" | |
| for (let i = 0; i < length; i += 1) { | |
| out += alphabet[rng.int(0, alphabet.length - 1)] | |
| } | |
| return out | |
| } | |
| function pad2(value) { | |
| return String(value).padStart(2, "0") | |
| } | |
| function formatDateValue(ms, dateFormat) { | |
| const date = new Date(ms) | |
| const year = date.getUTCFullYear() | |
| const month = pad2(date.getUTCMonth() + 1) | |
| const day = pad2(date.getUTCDate()) | |
| const hour = pad2(date.getUTCHours()) | |
| const minute = pad2(date.getUTCMinutes()) | |
| const second = pad2(date.getUTCSeconds()) | |
| if (dateFormat === "unix") { | |
| return String(Math.floor(ms / 1000)) | |
| } | |
| if (dateFormat === "datetime") { | |
| return `${year}-${month}-${day} ${hour}:${minute}:${second}` | |
| } | |
| return `${year}-${month}-${day}` | |
| } | |
| function formatUuid(value, style) { | |
| if (style === "nodash") { | |
| return value.replace(/-/g, "") | |
| } | |
| if (style === "braces") { | |
| return `{${value}}` | |
| } | |
| if (style === "urn") { | |
| return `urn:uuid:${value}` | |
| } | |
| return value | |
| } | |
| function generateOne(format, request, rng) { | |
| switch (format) { | |
| case "number": { | |
| if (request.isFloat) { | |
| const span = request.max - request.min | |
| const ratio = rng.int(0, 1000000) / 1000000 | |
| return String(Number((request.min + span * ratio).toFixed(4))) | |
| } | |
| return String(rng.int(Math.round(request.min), Math.round(request.max))) | |
| } | |
| case "uuid": | |
| return formatUuid(rng.uuid(), request.uuidStyle) | |
| case "password": | |
| return randomString(rng, CHARSETS[request.charset] || CHARSETS.all, request.length) | |
| case "email": { | |
| const first = pick(rng, FIRST_NAMES).toLowerCase() | |
| const last = pick(rng, LAST_NAMES).toLowerCase().replace(/[^a-z]/g, "") | |
| const n = rng.int(1, 99) | |
| return `${first}.${last}${n}@${pick(rng, EMAIL_DOMAINS)}` | |
| } | |
| case "name": { | |
| if (request.nameStyle === "first") { | |
| return pick(rng, FIRST_NAMES) | |
| } | |
| if (request.nameStyle === "last") { | |
| return pick(rng, LAST_NAMES) | |
| } | |
| return `${pick(rng, FIRST_NAMES)} ${pick(rng, LAST_NAMES)}` | |
| } | |
| case "phone": { | |
| const area = rng.int(200, 999) | |
| const prefix = rng.int(200, 999) | |
| const line = rng.int(1000, 9999) | |
| return `+1 ${area} ${prefix} ${line}` | |
| } | |
| case "color": { | |
| const bytes = rng.bytes(3) | |
| return `#${bytes.toString("hex")}` | |
| } | |
| case "date": { | |
| const start = Math.floor(request.startMs) | |
| const end = Math.floor(request.endMs) | |
| const ms = rng.int(start, end) | |
| return formatDateValue(ms, request.dateFormat) | |
| } | |
| case "ip": { | |
| if (request.ipVersion === "v6") { | |
| const parts = [] | |
| const raw = rng.bytes(16) | |
| for (let i = 0; i < 8; i += 1) { | |
| parts.push(raw.readUInt16BE(i * 2).toString(16)) | |
| } | |
| return parts.join(":") | |
| } | |
| const raw = rng.bytes(4) | |
| return `${raw[0]}.${raw[1]}.${raw[2]}.${raw[3]}` | |
| } | |
| case "mac": { | |
| const raw = rng.bytes(6) | |
| return [...raw].map(byte => byte.toString(16).padStart(2, "0")).join(":") | |
| } | |
| case "url": | |
| return `https://${pick(rng, URL_HOSTS)}/${pick(rng, URL_PATHS)}/${rng.int(10, 9999)}` | |
| case "bool": | |
| return rng.int(0, 1) === 1 ? "true" : "false" | |
| case "hex": | |
| return randomString(rng, CHARSETS.digits + "abcdef", request.length) | |
| case "lorem": | |
| case "words": | |
| case "sentences": | |
| case "paragraphs": | |
| return generateLorem(request, rng) | |
| case "country": { | |
| const country = pick(rng, COUNTRIES) | |
| return `${country.name} (${country.code})` | |
| } | |
| default: | |
| return "" | |
| } | |
| } | |
| function generateLorem(request, rng) { | |
| if (request.loremUnit === "words") { | |
| return pick(rng, LOREM_WORDS) | |
| } | |
| if (request.loremUnit === "paragraphs") { | |
| const sentences = [] | |
| const sentenceCount = rng.int(3, 5) | |
| for (let i = 0; i < sentenceCount; i += 1) { | |
| sentences.push(loremSentence(rng)) | |
| } | |
| return sentences.join(" ") | |
| } | |
| return loremSentence(rng) | |
| } | |
| function loremSentence(rng) { | |
| const count = rng.int(8, 14) | |
| const words = [] | |
| for (let i = 0; i < count; i += 1) { | |
| words.push(pick(rng, LOREM_WORDS)) | |
| } | |
| words[0] = words[0].charAt(0).toUpperCase() + words[0].slice(1) | |
| return `${words.join(" ")}.` | |
| } | |
| function generateValues(request, rng) { | |
| const engine = rng || defaultRng() | |
| const values = [] | |
| for (let i = 0; i < request.count; i += 1) { | |
| values.push(generateOne(request.format, request, engine)) | |
| } | |
| return values | |
| } | |
| function joinValues(values, style) { | |
| if (style === "json") { | |
| return JSON.stringify(values.length === 1 ? values[0] : values) | |
| } | |
| if (style === "csv") { | |
| return values.join(", ") | |
| } | |
| return values.join("\n") | |
| } | |
| function escapeHtml(text) { | |
| return String(text) | |
| .replace(/&/g, "&") | |
| .replace(/</g, "<") | |
| .replace(/>/g, ">") | |
| } | |
| function defaultThemeColors() { | |
| return { | |
| Background: "#1E1E1E", | |
| Text: "#E6E6E6", | |
| SecondaryText: "#A0A0A0", | |
| Border: "#3A3A3A", | |
| Accent: "#818CF8", | |
| AccentText: "#FFFFFF", | |
| Selection: "#312E81", | |
| Dark: true | |
| } | |
| } | |
| function cssColor(value, fallback) { | |
| const raw = String(value || "") | |
| if (/^#[0-9A-Fa-f]{6}$/.test(raw)) { | |
| return raw | |
| } | |
| return fallback | |
| } | |
| function valuesPreviewHtml(values, format, colors = defaultThemeColors()) { | |
| const dark = Boolean(colors.Dark) | |
| const background = cssColor(colors.Background, dark ? "#1E1E1E" : "#F5F5F5") | |
| const textColor = cssColor(colors.Text, dark ? "#E6E6E6" : "#1A1A1A") | |
| const secondary = cssColor(colors.SecondaryText, dark ? "#A0A0A0" : "#5C5C5C") | |
| const border = cssColor(colors.Border, dark ? "#3A3A3A" : "#D4D4D4") | |
| const accent = cssColor(colors.Accent, dark ? "#818CF8" : "#4F46E5") | |
| const rows = values.map((value, index) => { | |
| const swatch = format === "color" && /^#[0-9A-Fa-f]{6}$/.test(value) | |
| ? `<span class="swatch" style="background:${value}"></span>` | |
| : "" | |
| return `<div class="row">${swatch}<span class="idx">${index + 1}</span><code class="val">${escapeHtml(value)}</code></div>` | |
| }).join("") | |
| return `<!doctype html> | |
| <html> | |
| <head> | |
| <meta charset="utf-8"> | |
| <style> | |
| html, body { | |
| margin: 0; | |
| background: ${background}; | |
| color: ${textColor}; | |
| color-scheme: ${dark ? "dark" : "light"}; | |
| font: 13px/1.5 ui-monospace, "Cascadia Code", Consolas, "Segoe UI Mono", monospace; | |
| } | |
| body { padding: 10px 12px 12px; } | |
| .row { | |
| display: flex; | |
| align-items: center; | |
| gap: 8px; | |
| padding: 5px 0; | |
| border-bottom: 1px solid ${border}; | |
| } | |
| .row:last-child { border-bottom: none; } | |
| .idx { | |
| color: ${secondary}; | |
| min-width: 1.6em; | |
| text-align: right; | |
| flex: 0 0 auto; | |
| } | |
| .val { | |
| font: inherit; | |
| color: ${textColor}; | |
| white-space: pre-wrap; | |
| word-break: break-word; | |
| } | |
| .swatch { | |
| width: 14px; | |
| height: 14px; | |
| border-radius: 4px; | |
| border: 1px solid ${accent}; | |
| flex: 0 0 auto; | |
| } | |
| </style> | |
| </head> | |
| <body>${rows}</body> | |
| </html>` | |
| } | |
| function valuesPreview(values, format, colors = defaultThemeColors()) { | |
| const theme = colors && colors.Background ? colors : defaultThemeColors() | |
| const body = valuesPreviewHtml(values, format, theme) | |
| return { | |
| PreviewType: "webview", | |
| PreviewData: JSON.stringify({ | |
| html: body | |
| }) | |
| } | |
| } | |
| class RandomDataGeneratorPlugin { | |
| constructor() { | |
| this.api = null | |
| this.settings = defaultSettings() | |
| this.init = this.init.bind(this) | |
| this.query = this.query.bind(this) | |
| } | |
| async init(ctx, params) { | |
| this.api = params.API | |
| await this.loadSettings(ctx) | |
| if (this.api && typeof this.api.OnSettingChanged === "function") { | |
| await this.api.OnSettingChanged(ctx, async (_ctx, key, value) => { | |
| this.applySetting(key, value) | |
| }) | |
| } | |
| await this.registerTools(ctx) | |
| } | |
| applySetting(key, value) { | |
| if (key === SETTING_DEFAULT_COUNT) { | |
| this.settings.defaultCount = clampCount(value, DEFAULT_COUNT).count | |
| } else if (key === SETTING_NUMBER_MIN) { | |
| this.settings.numberMin = parseNumber(value, DEFAULT_NUMBER_MIN) | |
| } else if (key === SETTING_NUMBER_MAX) { | |
| this.settings.numberMax = parseNumber(value, DEFAULT_NUMBER_MAX) | |
| } else if (key === SETTING_PASSWORD_LENGTH) { | |
| this.settings.passwordLength = clamp(parseInteger(value, DEFAULT_PASSWORD_LENGTH), MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH) | |
| } else if (key === SETTING_PASSWORD_CHARSET) { | |
| const charset = String(value || "").toLowerCase() | |
| this.settings.passwordCharset = CHARSETS[charset] ? charset : DEFAULT_PASSWORD_CHARSET | |
| } else if (key === SETTING_DATE_FORMAT) { | |
| const format = String(value || "").toLowerCase() | |
| this.settings.dateFormat = ["iso", "datetime", "unix"].includes(format) ? format : DEFAULT_DATE_FORMAT | |
| } | |
| this.settings = normalizeSettings(this.settings) | |
| } | |
| async loadSettings(ctx) { | |
| if (!this.api || typeof this.api.GetSetting !== "function") { | |
| return | |
| } | |
| const [defaultCount, numberMin, numberMax, passwordLength, passwordCharset, dateFormat] = await Promise.all([ | |
| this.api.GetSetting(ctx, SETTING_DEFAULT_COUNT), | |
| this.api.GetSetting(ctx, SETTING_NUMBER_MIN), | |
| this.api.GetSetting(ctx, SETTING_NUMBER_MAX), | |
| this.api.GetSetting(ctx, SETTING_PASSWORD_LENGTH), | |
| this.api.GetSetting(ctx, SETTING_PASSWORD_CHARSET), | |
| this.api.GetSetting(ctx, SETTING_DATE_FORMAT) | |
| ]) | |
| this.settings = normalizeSettings({ | |
| defaultCount, | |
| numberMin, | |
| numberMax, | |
| passwordLength, | |
| passwordCharset, | |
| dateFormat | |
| }) | |
| } | |
| async loadThemeColors(ctx) { | |
| if (!this.api || typeof this.api.GetThemeColors !== "function") { | |
| return defaultThemeColors() | |
| } | |
| try { | |
| const colors = await this.api.GetThemeColors(ctx, {}) | |
| if (colors && colors.Background && colors.Text) { | |
| return colors | |
| } | |
| } catch { | |
| // Wox builds before 2.4.5 do not expose GetThemeColors. | |
| } | |
| return defaultThemeColors() | |
| } | |
| async registerTools(ctx) { | |
| if (!this.api || typeof this.api.RegisterPluginTool !== "function") { | |
| return | |
| } | |
| try { | |
| const result = await this.api.RegisterPluginTool(ctx, { | |
| Tool: { | |
| Name: "generate_random_data", | |
| Description: "i18n:tool_generate", | |
| InputSchema: { | |
| type: "object", | |
| properties: { | |
| format: { type: "string", enum: FORMAT_ENUM }, | |
| count: { type: "integer", minimum: 1, maximum: MAX_COUNT }, | |
| min: { type: "number" }, | |
| max: { type: "number" }, | |
| length: { type: "integer", minimum: MIN_PASSWORD_LENGTH, maximum: MAX_PASSWORD_LENGTH } | |
| }, | |
| required: ["format"] | |
| }, | |
| OutputSchema: { | |
| type: "object", | |
| properties: { | |
| format: { type: "string" }, | |
| values: { type: "array", items: { type: "string" } } | |
| }, | |
| required: ["format", "values"] | |
| }, | |
| Annotations: { ReadOnly: true, Destructive: false, Idempotent: false, RequiresUI: false } | |
| }, | |
| Handler: async (_ctx, option) => this.handleGenerateTool(option.Arguments || {}) | |
| }) | |
| if (result && result.Error) { | |
| await this.log(ctx, "Warning", `plugin tool generate_random_data was not registered: ${result.Error.Message || result.Error.Code}`) | |
| } | |
| } catch (err) { | |
| await this.log(ctx, "Warning", `plugin tool generate_random_data unavailable: ${err && err.message ? err.message : err}`) | |
| } | |
| } | |
| handleGenerateTool(args) { | |
| const format = resolveFormat(args.format) | |
| if (!format) { | |
| return { Error: { Code: "INVALID_ARGUMENTS", Message: `Unknown format: ${args.format || ""}` } } | |
| } | |
| const settings = { ...this.settings } | |
| if (args.min !== undefined) { | |
| settings.numberMin = Number(args.min) | |
| } | |
| if (args.max !== undefined) { | |
| settings.numberMax = Number(args.max) | |
| } | |
| if (args.length !== undefined) { | |
| settings.passwordLength = Number(args.length) | |
| } | |
| const countText = args.count === undefined ? "" : String(args.count) | |
| const request = parseFormatArgs(format, countText ? [countText] : [], {}, normalizeSettings(settings)) | |
| return { Output: { format, values: generateValues(request) } } | |
| } | |
| async query(ctx, query) { | |
| const request = parseRequest(query, this.settings) | |
| if (request.kind === "catalog") { | |
| return { Results: this.catalogResults() } | |
| } | |
| if (request.kind === "commands") { | |
| return { Results: this.commandResults(query, request.matches) } | |
| } | |
| if (request.kind === "unknown") { | |
| const title = (await this.translate(ctx, "unknown_title")).replace("%s", request.token || "") | |
| return { | |
| Results: [{ | |
| Title: title, | |
| Icon: RESULT_ICON, | |
| Score: 10 | |
| }] | |
| } | |
| } | |
| const values = generateValues(request) | |
| await this.log(ctx, "Info", `generated format=${request.format} count=${values.length}`) | |
| return { Results: this.valueResults(request, values) } | |
| } | |
| catalogResults() { | |
| const samples = [] | |
| for (const format of CATALOG_FORMATS) { | |
| const request = parseFormatArgs(format, [], {}, this.settings) | |
| request.count = 1 | |
| request.countSpecified = false | |
| samples.push(this.valueResult({ | |
| id: `catalog-${format}`, | |
| request, | |
| values: generateValues(request), | |
| score: 80 | |
| })) | |
| } | |
| return samples | |
| } | |
| commandResults(query, matches) { | |
| const trigger = String(query && query.TriggerKeyword || "random").trim() || "random" | |
| return matches.map((item, index) => ({ | |
| Id: `command-${item.command}`, | |
| Title: item.command, | |
| Icon: RESULT_ICON, | |
| Score: 100 - index, | |
| Actions: [{ | |
| Id: `use-${item.command}`, | |
| Name: "i18n:action_select", | |
| Icon: ACTION_EXECUTE_ICON, | |
| IsDefault: true, | |
| PreventHideAfterAction: true, | |
| Action: async (ctx) => { | |
| if (this.api && typeof this.api.ChangeQuery === "function") { | |
| await this.api.ChangeQuery(ctx, { | |
| QueryType: "input", | |
| QueryText: `${trigger} ${item.command} ` | |
| }) | |
| } | |
| } | |
| }] | |
| })) | |
| } | |
| valueResults(request, values) { | |
| return [this.valueResult({ | |
| id: `${request.format}-0`, | |
| request, | |
| values, | |
| score: 100 | |
| })] | |
| } | |
| valueResult(item) { | |
| const values = item.values | |
| const example = values[0] | |
| const label = FORMAT_LABELS[item.request.format] || item.request.format | |
| const copyText = values.length === 1 ? example : joinValues(values, "newline") | |
| return { | |
| Id: item.id, | |
| Title: label, | |
| SubTitle: example, | |
| Icon: RESULT_ICON, | |
| Score: item.score, | |
| Tails: resultTails(item.request), | |
| Actions: [ | |
| this.copyAction({ id: `${item.id}-copy`, name: "i18n:action_copy", text: copyText, isDefault: true }), | |
| this.copyAction({ id: `${item.id}-json`, name: "i18n:action_copy_json", text: joinValues(values, "json"), isDefault: false }), | |
| values.length > 1 ? this.copyAction({ id: `${item.id}-csv`, name: "i18n:action_copy_csv", text: joinValues(values, "csv"), isDefault: false }) : null, | |
| this.regenerateAction() | |
| ].filter(Boolean) | |
| } | |
| } | |
| copyAction(item) { | |
| return { | |
| Id: item.id, | |
| Name: item.name, | |
| Icon: ACTION_COPY_ICON, | |
| IsDefault: item.isDefault, | |
| Action: async (ctx) => { | |
| try { | |
| await this.api.Copy(ctx, { type: "text", text: item.text }) | |
| await this.api.Notify(ctx, await this.translate(ctx, "notify_copied")) | |
| } catch (err) { | |
| await this.log(ctx, "Error", `copy failed: ${err && err.message ? err.message : err}`) | |
| await this.api.Notify(ctx, await this.translate(ctx, "notify_copy_failed")) | |
| } | |
| } | |
| } | |
| } | |
| regenerateAction() { | |
| return { | |
| Id: "regenerate", | |
| Name: "i18n:action_regenerate", | |
| Icon: ACTION_REGENERATE_ICON, | |
| PreventHideAfterAction: true, | |
| Action: async (ctx) => { | |
| if (this.api && typeof this.api.RefreshQuery === "function") { | |
| await this.api.RefreshQuery(ctx, { PreserveSelectedIndex: true }) | |
| } | |
| } | |
| } | |
| } | |
| async translate(ctx, key) { | |
| if (this.api && typeof this.api.GetTranslation === "function") { | |
| try { | |
| const value = await this.api.GetTranslation(ctx, key) | |
| if (value) { | |
| return value | |
| } | |
| } catch { | |
| // Fall through to English copy. | |
| } | |
| } | |
| const fallback = { | |
| unknown_title: "Unknown format: %s", | |
| capped_sub: "Count capped at %s", | |
| notify_copied: "Copied to clipboard", | |
| notify_copy_failed: "Failed to copy" | |
| } | |
| return fallback[key] || key | |
| } | |
| async log(ctx, level, message) { | |
| if (this.api && typeof this.api.Log === "function") { | |
| await this.api.Log(ctx, level, message) | |
| } | |
| } | |
| } | |
| const plugin = new RandomDataGeneratorPlugin() | |
| module.exports = { | |
| plugin, | |
| RandomDataGeneratorPlugin, | |
| parseRequest, | |
| parseFormatArgs, | |
| parseRangeToken, | |
| resolveFormat, | |
| filterCommands, | |
| generateValues, | |
| generateOne, | |
| joinValues, | |
| clampCount, | |
| normalizeSettings, | |
| valuesPreview, | |
| valuesPreviewHtml, | |
| resultTails, | |
| defaultThemeColors, | |
| defaultRng, | |
| FORMAT_ENUM, | |
| MAX_COUNT, | |
| CATALOG_FORMATS | |
| } |
qianlifeng
commented
Sep 20, 2026
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment