@open-wa/create 0.0.0-stage → 5.9.7

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/LICENSE.md ADDED
@@ -0,0 +1,67 @@
1
+ ### Copyright (c) 2020 Mohammed Shah
2
+
3
+ # Hippocratic + Do Not Harm (H-DNH) Version 1.1
4
+
5
+ ## Preamble
6
+
7
+ Most software today is developed with little to no thought of how it will be used, or the consequences for our society and planet.
8
+
9
+ As software developers, we engineer the infrastructure of the 21st century. We recognise that our infrastructure has great power to shape the world and the lives of those we share it with, and we choose to consciously take responsibility for the social and environmental impacts of what we build.
10
+
11
+ We envisage a world free from injustice, inequality, and the reckless destruction of lives and our planet. We reject slavery in all its forms, whether by force, indebtedness, or by algorithms that hack human vulnerabilities. We seek a world where humankind is at peace with our neighbours, nature, and ourselves. We want our work to enrich the physical, mental and spiritual wellbeing of all society.
12
+
13
+ We build software to further this vision of a just world, or at the very least, to not put that vision further from reach.
14
+
15
+ ## Terms
16
+
17
+ Licensor hereby grants permission by this license ("License"), free of charge, to any person or entity (the "Licensee") obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
18
+
19
+ 1. All redistribution of source code or binary form, including any modifications must be under these terms. You must inform recipients that the code is governed by these conditions, and how they can obtain a copy of this license. You may not attempt to alter the conditions of who may/may not use this software.
20
+
21
+ 2. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
22
+
23
+ 3. This software must not be used by any organisation, website, product or service that:
24
+
25
+ a) lobbies for, promotes, or derives a majority of income from actions that support or contribute to:
26
+ * sex trafficking
27
+ * human trafficking
28
+ * slavery
29
+ * indentured servitude
30
+ * gambling
31
+ * tobacco
32
+ * adversely addictive behaviours
33
+ * nuclear energy
34
+ * warfare
35
+ * weapons manufacturing
36
+ * war crimes
37
+ * settler colonialism
38
+ * apartheid
39
+ * vaccine misinformation
40
+ * climate misinformation
41
+ * child endangerment
42
+ * violence (except when required to protect public safety)
43
+ * burning of forests
44
+ * deforestation
45
+ * hate speech or discrimination based on age, gender, gender identity, race, sexuality, religion, nationality
46
+
47
+ b) lobbies against, or derives a majority of income from actions that discourage or frustrate:
48
+ * peace
49
+ * access to the rights set out in the Universal Declaration of Human Rights and the Convention on the Rights of the Child
50
+ * peaceful assembly and association (including worker associations)
51
+ * a safe environment or action to curtail the use of fossil fuels or prevent climate change
52
+ * democratic processes
53
+
54
+
55
+ 4. Compliance with Human Rights Laws and Human Rights Principles:
56
+
57
+ a. **Human Rights Laws**. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any applicable laws, regulations, or rules that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights (the "Human Rights Laws"). Where the Human Rights Laws of more than one jurisdiction are applicable to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
58
+
59
+ b. **Human Rights Principles**. Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights (https://www.un.org/en/universal-declaration-human-rights/) and the United Nations Global Compact (https://www.unglobalcompact.org/ what-is-gc/mission/principles) that define recognized principles of international human rights (the "Human Rights Principles"). It is Licensor's express intent that all use of the Software be consistent with Human Rights Principles. If Licensor receives notification or otherwise learns of an alleged violation of any Human Rights Principles relating to Licensee's use of the Software, Licensor may in its discretion and without obligation (i) (a) notify Licensee of such allegation and (b) allow Licensee 90 days from notification under (i)(a) to investigate and respond to Licensor regarding the allegation and (ii) (a) after the earlier of 90 days from notification under (i)(a), or Licensee's response under (i)(b), notify Licensee of License termination and (b) allow Licensee an additional 90 days from notification under (ii)(a) to cease use of the Software.
60
+
61
+ c. **Indemnity**. Licensee shall hold harmless and indemnify Licensor against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor's reasonable attorneys' fees, arising out of or relating to Licensee's non-compliance with this License or use of the Software in violation of Human Rights Laws or Human Rights Principles. 
62
+
63
+ 5. Enforceability: If any portion or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by applicable law, the court may modify this License to affect the original intent of the parties as closely as possible. The section headings are for convenience only and are not intended to affect the construction or interpretation of this License. Any rule of construction to the effect that ambiguities are to be resolved against the drafting party shall not apply in interpreting this License. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
64
+
65
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
66
+
67
+ This license is an extension of the Hippocratic License - an Ethical Source license (https://ethicalsource.dev) and the Do Not Harm License - (https://github.com/raisely/NoHarm)
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # Create an open-wa project
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```bash
4
+ npm init @open-wa@latest my-bot
5
+ cd my-bot
6
+ npm start
7
+ ```
8
+
9
+ Use Node.js 22.21.1 or newer. The wizard lets you choose Easy API or SDK,
10
+ JavaScript or TypeScript, a browser, and optional Voxtral, Webhook or Chatwoot
11
+ plugins. Missing choices are interactive; `--yes` uses defaults.
12
+
13
+ Configure the same options in the [project builder](https://openwa.dev/new) to
14
+ preview the exact generated files and copy a repeatable command:
15
+
16
+ ```bash
17
+ npm init @open-wa@latest voice-bot -- --mode easy-api --language ts --browser chrome --plugins voxtral --voxtral-mode both --yes
18
+ ```
19
+
20
+ Copy `.env.example` to `.env` when it is generated and fill in the selected
21
+ integrations' credentials. Browser and plugin downloads happen only when needed
22
+ at startup and are cached for reuse. The initializer never overwrites existing
23
+ destination files. `--no-install` generates the project without running npm.
24
+
25
+ The CLI, builder and file preview share `src/options.js` and `src/templates.js`.
26
+ The existing `wa-automate init` command delegates to this package.
27
+
28
+ See the [setup guide](https://openwa.dev/docs/getting-started/initializer) for
29
+ all flags and generated files.
package/bin/create.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { initProject } from '../src/index.js';
3
+
4
+ initProject(process.argv.slice(2)).catch(error => {
5
+ console.error(`Could not create the project: ${error instanceof Error ? error.message : String(error)}`);
6
+ process.exitCode = 1;
7
+ });
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@open-wa/create",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "5.9.7",
4
+ "description": "Create an open-wa Easy API or SDK project",
5
+ "type": "module",
6
+ "bin": {
7
+ "create-open-wa": "./bin/create.js"
8
+ },
9
+ "types": "./src/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./src/index.d.ts",
13
+ "default": "./src/index.js"
14
+ },
15
+ "./options": {
16
+ "types": "./src/options.d.ts",
17
+ "default": "./src/options.js"
18
+ },
19
+ "./templates": {
20
+ "types": "./src/templates.d.ts",
21
+ "default": "./src/templates.js"
22
+ },
23
+ "./browser": {
24
+ "types": "./src/browser.d.ts",
25
+ "default": "./src/browser.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "bin",
30
+ "src",
31
+ "LICENSE.md",
32
+ "README.md"
33
+ ],
34
+ "engines": {
35
+ "node": ">=22.21.1"
36
+ },
37
+ "dependencies": {
38
+ "@clack/prompts": "1.8.1"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "https://github.com/open-wa/wa-automate-nodejs.git"
46
+ },
47
+ "license": "SEE LICENSE IN LICENSE.md"
6
48
  }
@@ -0,0 +1 @@
1
+ export function findSystemBrowser(kind: 'chrome' | 'chromium'): Promise<string | undefined>;
package/src/browser.js ADDED
@@ -0,0 +1,26 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, stat } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { delimiter, join } from 'node:path';
5
+
6
+ /** @param {'chrome' | 'chromium'} kind @returns {Promise<string | undefined>} */
7
+ export async function findSystemBrowser(kind) {
8
+ const app = kind === 'chrome' ? 'Google Chrome' : 'Chromium';
9
+ const names = process.platform === 'win32' ? ['chrome.exe']
10
+ : kind === 'chrome' ? ['google-chrome-stable', 'google-chrome', 'chrome'] : ['chromium', 'chromium-browser'];
11
+ const candidates = process.platform === 'darwin'
12
+ ? ['/Applications', join(homedir(), 'Applications')].map(root => join(root, `${app}.app`, 'Contents', 'MacOS', app))
13
+ : process.platform === 'win32'
14
+ ? [process.env.LOCALAPPDATA, process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)']].filter(Boolean)
15
+ .map(root => kind === 'chrome' ? join(root, 'Google', 'Chrome', 'Application', 'chrome.exe') : join(root, 'Chromium', 'Application', 'chrome.exe'))
16
+ : kind === 'chrome' ? ['/opt/google/chrome/chrome'] : [];
17
+ candidates.push(...(process.env.PATH ?? '').split(delimiter).filter(Boolean).flatMap(root => names.map(name => join(root, name))));
18
+ for (const candidate of candidates) {
19
+ try {
20
+ if (!(await stat(candidate)).isFile()) continue;
21
+ await access(candidate, constants.X_OK);
22
+ return candidate;
23
+ } catch { }
24
+ }
25
+ return undefined;
26
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export function initProject(args?: string[]): Promise<void>;
package/src/index.js ADDED
@@ -0,0 +1,122 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { lstat, mkdir, unlink, writeFile } from 'node:fs/promises';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { choices, defaults, flags, normalizeOptions, optionErrors, pluginChoices } from './options.js';
6
+ import { renderProject } from './templates.js';
7
+ import { findSystemBrowser } from './browser.js';
8
+
9
+ async function exists(path) {
10
+ try { await lstat(path); return true; }
11
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
12
+ }
13
+
14
+ async function install(directory) {
15
+ const npmPath = process.env.npm_execpath;
16
+ const npmCli = npmPath && /[\\/]npm-cli\.js$/.test(npmPath) ? npmPath
17
+ : process.platform === 'win32' ? resolve(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js') : undefined;
18
+ const args = ['install', '--no-audit', '--no-fund'];
19
+ await new Promise((accept, reject) => {
20
+ const child = spawn(npmCli ? process.execPath : 'npm', npmCli ? [npmCli, ...args] : args, { cwd: directory, stdio: 'inherit' });
21
+ child.once('error', () => reject(new Error('npm could not start. Keep the generated files and run npm install inside the project.')));
22
+ child.once('exit', code => code === 0 ? accept() : reject(new Error('Dependency installation did not finish. Keep the generated files, resolve the npm error, then run npm install inside the project.')));
23
+ });
24
+ }
25
+
26
+ /** @param {string[]} args */
27
+ export async function initProject(args = process.argv.slice(2)) {
28
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
29
+ ...Object.fromEntries(Object.keys(flags).map(key => [key, { type: 'string' }])),
30
+ yes: { type: 'boolean', short: 'y' }, help: { type: 'boolean', short: 'h' },
31
+ install: { type: 'boolean' }, 'no-install': { type: 'boolean' },
32
+ } });
33
+ if (values.help) {
34
+ console.log(`Usage: npm init @open-wa@latest [directory] -- [options]\n\n${Object.entries(flags).map(([key, flag]) => ` --${key.padEnd(15)} ${flag.description}`).join('\n')}\n --yes, -y Use defaults for missing choices\n --no-install Write files without installing dependencies\n\nConfigure visually: https://openwa.dev/new`);
35
+ return;
36
+ }
37
+ if (positionals.length > 1) throw new Error('Choose one project directory.');
38
+ if (values.install && values['no-install']) throw new Error('Choose either --install or --no-install.');
39
+ const partial = {};
40
+ for (const [flag, definition] of Object.entries(flags)) {
41
+ if (values[flag] === undefined) continue;
42
+ partial[definition.key] = flag === 'plugins' ? values[flag] === 'none' ? [] : values[flag].split(',').filter(Boolean) : values[flag];
43
+ }
44
+ if (positionals[0]) partial.directory = positionals[0];
45
+ if (values['no-install'] || values.install) partial.install = !values['no-install'];
46
+ let options = normalizeOptions(partial);
47
+ const initialErrors = optionErrors(options);
48
+ if (initialErrors.length) throw new Error(initialErrors.join('\n'));
49
+ const missing = ['directory', 'mode', 'language', 'browser', 'plugins'].filter(key => partial[key] === undefined);
50
+ if (!values.yes && !process.stdin.isTTY && (missing.length || (options.plugins.includes('voxtral') && partial.voxtralMode === undefined))) {
51
+ throw new Error('An interactive terminal is required for missing choices. Pass --yes to use defaults, or copy a complete command from https://openwa.dev/new.');
52
+ }
53
+ if (!values.yes && process.stdin.isTTY) {
54
+ const p = await import('@clack/prompts');
55
+ p.intro('Create your open-wa project');
56
+ const ask = async pending => {
57
+ const value = await pending;
58
+ if (p.isCancel(value)) { p.cancel('Setup cancelled.'); return undefined; }
59
+ return value;
60
+ };
61
+ if (partial.directory === undefined) {
62
+ const directory = await ask(p.text({ message: 'Project folder', initialValue: options.directory,
63
+ validate: value => optionErrors({ ...options, directory: value ?? '' })[0] }));
64
+ if (directory === undefined) return;
65
+ options.directory = directory;
66
+ }
67
+ for (const key of ['mode', 'language', 'browser']) {
68
+ if (partial[key] !== undefined) continue;
69
+ const detected = key === 'browser' ? await findSystemBrowser('chrome') : undefined;
70
+ if (detected) p.log.info(`Chrome found: ${detected}`);
71
+ const value = await ask(p.select({ message: { mode: 'What would you like to create?', language: 'Which language?', browser: 'Which browser should this project use?' }[key],
72
+ initialValue: key === 'browser' && !detected ? 'chrome' : options[key],
73
+ options: choices[key].map(choice => ({ value: choice.value, label: choice.label, hint: choice.description,
74
+ disabled: choice.value === 'system-chrome' && !detected })) }));
75
+ if (value === undefined) return;
76
+ options[key] = value;
77
+ }
78
+ if (partial.plugins === undefined) {
79
+ const plugins = await ask(p.multiselect({ message: 'Which plugins would you like to set up?', required: false,
80
+ options: pluginChoices.map(plugin => ({ value: plugin.value, label: plugin.label,
81
+ hint: plugin.modes.includes(options.mode) ? plugin.description : 'Needs Easy API', disabled: !plugin.modes.includes(options.mode) })) }));
82
+ if (plugins === undefined) return;
83
+ options.plugins = plugins;
84
+ }
85
+ if (options.plugins.includes('voxtral') && partial.voxtralMode === undefined) {
86
+ const mode = await ask(p.select({ message: 'What should Voxtral handle?', initialValue: options.voxtralMode,
87
+ options: choices.voxtralMode.map(choice => ({ value: choice.value, label: choice.label, hint: choice.description })) }));
88
+ if (mode === undefined) return;
89
+ options.voxtralMode = mode;
90
+ }
91
+ if (partial.install === undefined) {
92
+ const shouldInstall = await ask(p.confirm({ message: 'Install project dependencies now?', initialValue: true }));
93
+ if (shouldInstall === undefined) return;
94
+ options.install = shouldInstall;
95
+ }
96
+ }
97
+ const errors = optionErrors(options);
98
+ if (errors.length) throw new Error(errors.join('\n'));
99
+ if (options.browser === 'system-chrome' && !await findSystemBrowser('chrome')) {
100
+ throw new Error('Chrome was not found. Install Chrome or choose --browser chrome or --browser chromium to download a browser at startup.');
101
+ }
102
+ const directory = resolve(options.directory);
103
+ const files = renderProject(options);
104
+ const conflicts = [];
105
+ for (const file of Object.keys(files)) if (await exists(resolve(directory, file))) conflicts.push(file);
106
+ if (conflicts.length) throw new Error(`These files already exist: ${conflicts.join(', ')}. Choose another folder. No files were changed.`);
107
+ await mkdir(directory, { recursive: true });
108
+ const created = [];
109
+ try {
110
+ for (const [name, content] of Object.entries(files)) {
111
+ const path = resolve(directory, name);
112
+ await writeFile(path, content, { flag: 'wx' });
113
+ created.push(path);
114
+ }
115
+ } catch (error) {
116
+ await Promise.all(created.map(path => unlink(path)));
117
+ throw error;
118
+ }
119
+ console.log(`Created ${directory}\n${Object.keys(files).map(file => ` ${file}`).join('\n')}`);
120
+ if (options.install) await install(directory);
121
+ console.log(`\nNext:\n cd ${options.directory}\n${options.install ? '' : ' npm install\n'}${files['.env.example'] ? ' Copy .env.example to .env and fill in your integration settings\n' : ''} npm start\n\nBrowsers and configured plugins are downloaded only when needed at startup.\n`);
122
+ }
@@ -0,0 +1,18 @@
1
+ export interface SetupOptions {
2
+ directory: string;
3
+ mode: 'easy-api' | 'sdk';
4
+ language: 'js' | 'ts';
5
+ browser: 'auto' | 'system-chrome' | 'chrome' | 'chromium';
6
+ plugins: string[];
7
+ voxtralMode: 'voice-notes' | 'calls' | 'both';
8
+ install: boolean;
9
+ }
10
+ export interface Choice<T extends string = string> { value: T; label: string; description: string }
11
+ export const choices: { [K in 'mode' | 'language' | 'browser' | 'voxtralMode']: Choice<SetupOptions[K]>[] };
12
+ export const pluginChoices: (Choice & { package: string; modes: string[] })[];
13
+ export const defaults: SetupOptions;
14
+ export const flags: Record<string, { key: keyof SetupOptions; description: string }>;
15
+ export function normalizeOptions(input?: Partial<SetupOptions>): SetupOptions;
16
+ export function optionErrors(options: SetupOptions): string[];
17
+ export function buildCommand(options: SetupOptions): string;
18
+ export function readBuilderSearch(search: Record<string, unknown>): SetupOptions;
package/src/options.js ADDED
@@ -0,0 +1,92 @@
1
+ /** @typedef {'easy-api' | 'sdk'} ProjectMode */
2
+ /** @typedef {'js' | 'ts'} Language */
3
+ /** @typedef {'auto' | 'system-chrome' | 'chrome' | 'chromium'} Browser */
4
+ /** @typedef {'voice-notes' | 'calls' | 'both'} VoxtralMode */
5
+ /** @typedef {{directory: string, mode: ProjectMode, language: Language, browser: Browser, plugins: string[], voxtralMode: VoxtralMode, install: boolean}} SetupOptions */
6
+
7
+ export const choices = {
8
+ mode: [
9
+ { value: 'easy-api', label: 'Easy API', description: 'HTTP API and the Neo dashboard.' },
10
+ { value: 'sdk', label: 'SDK', description: 'A persistent bot you control in code.' },
11
+ ],
12
+ language: [
13
+ { value: 'js', label: 'JavaScript', description: 'Plain .js files, ready to run with Node.js.' },
14
+ { value: 'ts', label: 'TypeScript', description: '.ts files with editor types; Node.js runs them directly.' },
15
+ ],
16
+ browser: [
17
+ { value: 'auto', label: 'Detect at startup', description: 'Reuse Chrome or a cached browser; ask if none is available.' },
18
+ { value: 'system-chrome', label: 'Use installed Chrome', description: 'Find Chrome on this computer. Never download a browser.' },
19
+ { value: 'chrome', label: 'Download Chrome', description: 'Download and cache Chrome for Testing when needed. Recommended for calls and media.' },
20
+ { value: 'chromium', label: 'Download Chromium', description: 'Download and cache Chromium. Some audio/video codecs may be unavailable.' },
21
+ ],
22
+ voxtralMode: [
23
+ { value: 'voice-notes', label: 'Voice notes', description: 'Answer incoming voice notes with spoken replies.' },
24
+ { value: 'calls', label: 'Calls', description: 'Answer live audio calls. Requires an open-wa calling license.' },
25
+ { value: 'both', label: 'Voice notes and calls', description: 'Share the assistant and recent context across both.' },
26
+ ],
27
+ };
28
+
29
+ export const pluginChoices = [
30
+ { value: 'voxtral', label: 'Voxtral', description: 'A conversational voice assistant using your Mistral account.', package: '@open-wa/integration-voxtral', modes: ['easy-api', 'sdk'] },
31
+ { value: 'webhook', label: 'Webhooks', description: 'Forward WhatsApp events to your HTTP endpoint.', package: '@open-wa/integration-webhook', modes: ['easy-api', 'sdk'] },
32
+ { value: 'chatwoot', label: 'Chatwoot', description: 'Connect a Chatwoot inbox through Easy API webhook routes.', package: '@open-wa/integration-chatwoot', modes: ['easy-api'] },
33
+ ];
34
+
35
+ /** @type {SetupOptions} */
36
+ export const defaults = { directory: 'my-bot', mode: 'easy-api', language: 'js', browser: 'auto', plugins: [], voxtralMode: 'voice-notes', install: true };
37
+
38
+ export const flags = {
39
+ mode: { key: 'mode', description: 'easy-api or sdk' },
40
+ language: { key: 'language', description: 'js or ts' },
41
+ browser: { key: 'browser', description: 'auto, system-chrome, chrome or chromium' },
42
+ plugins: { key: 'plugins', description: 'Comma-separated voxtral, webhook, chatwoot; or none' },
43
+ 'voxtral-mode': { key: 'voxtralMode', description: 'voice-notes, calls or both' },
44
+ };
45
+
46
+ /** @param {Partial<SetupOptions>} input @returns {SetupOptions} */
47
+ export function normalizeOptions(input = {}) {
48
+ return { ...defaults, ...input, plugins: [...new Set(input.plugins ?? defaults.plugins)] };
49
+ }
50
+
51
+ /** @param {SetupOptions} options @returns {string[]} */
52
+ export function optionErrors(options) {
53
+ const errors = [];
54
+ if (!options.directory || options.directory.startsWith('-') || !/^[a-zA-Z0-9._/\\-]+$/.test(options.directory)) errors.push('Use a folder name or path containing letters, numbers, dots, dashes, underscores or slashes; it must not start with a dash.');
55
+ for (const key of ['mode', 'language', 'browser', 'voxtralMode']) {
56
+ if (!choices[key].some(choice => choice.value === options[key])) errors.push(`Choose a supported ${key}.`);
57
+ }
58
+ for (const id of options.plugins) {
59
+ const plugin = pluginChoices.find(item => item.value === id);
60
+ if (!plugin) errors.push(`Unknown plugin: ${id}.`);
61
+ else if (!plugin.modes.includes(options.mode)) errors.push(`${plugin.label} needs Easy API webhook routes. Choose Easy API or remove ${plugin.label}.`);
62
+ }
63
+ return errors;
64
+ }
65
+
66
+ /** @param {SetupOptions} options */
67
+ export function buildCommand(options) {
68
+ const errors = optionErrors(options);
69
+ if (errors.length) throw new Error(errors.join(' '));
70
+ const args = ['npm init @open-wa@latest', options.directory, '--'];
71
+ for (const [flag, definition] of Object.entries(flags)) {
72
+ if (flag === 'voxtral-mode' && !options.plugins.includes('voxtral')) continue;
73
+ const value = options[definition.key];
74
+ args.push(`--${flag}`, Array.isArray(value) ? value.join(',') || 'none' : String(value));
75
+ }
76
+ if (!options.install) args.push('--no-install');
77
+ args.push('--yes');
78
+ return args.join(' ');
79
+ }
80
+
81
+ /** @param {Record<string, unknown>} search @returns {SetupOptions} */
82
+ export function readBuilderSearch(search) {
83
+ const options = normalizeOptions();
84
+ if (typeof search.directory === 'string' && /^[a-zA-Z0-9._/\\-]+$/.test(search.directory)) options.directory = search.directory;
85
+ for (const key of ['mode', 'language', 'browser', 'voxtralMode']) {
86
+ if (choices[key].some(choice => choice.value === search[key])) options[key] = search[key];
87
+ }
88
+ const plugins = Array.isArray(search.plugins) ? search.plugins : typeof search.plugins === 'string' ? search.plugins.split(',') : [];
89
+ options.plugins = pluginChoices.filter(plugin => plugins.includes(plugin.value)).map(plugin => plugin.value);
90
+ if (search.install === false || search.install === 'false') options.install = false;
91
+ return options;
92
+ }
@@ -0,0 +1,2 @@
1
+ import type { SetupOptions } from './options.js';
2
+ export function renderProject(options: SetupOptions): Record<string, string>;
@@ -0,0 +1,58 @@
1
+ import packageJson from '../package.json' with { type: 'json' };
2
+ import { normalizeOptions, optionErrors, pluginChoices } from './options.js';
3
+
4
+ /** @param {import('./options.js').SetupOptions} input @returns {Record<string, string>} */
5
+ export function renderProject(input) {
6
+ const options = normalizeOptions(input);
7
+ const errors = optionErrors(options);
8
+ if (errors.length) throw new Error(errors.join(' '));
9
+ const ext = options.language;
10
+ const name = options.directory.split(/[/\\]/).filter(Boolean).at(-1)?.toLowerCase().replace(/[^a-z0-9-]/g, '-') || 'my-bot';
11
+ const projectName = /^[a-z0-9]/.test(name) ? name : 'my-bot';
12
+ const configName = `wa.config.${ext}`;
13
+ const calling = options.plugins.includes('voxtral') && options.voxtralMode !== 'voice-notes';
14
+ const env = options.mode === 'easy-api' ? ['# Optional API key. Use at least 8 characters when setting it.', 'WA_API_KEY='] : [];
15
+ const config = [` sessionId: ${JSON.stringify(projectName)},`];
16
+ if (options.mode === 'easy-api') config.push(" host: '127.0.0.1',", ' apiKey: process.env.WA_API_KEY || undefined,');
17
+ if (options.browser === 'auto') config.push(" browser: { source: 'auto' },");
18
+ else if (options.browser === 'system-chrome') config.push(" browser: { source: 'system', kind: 'chrome', download: 'never' },");
19
+ else config.push(` browser: { source: 'managed', kind: '${options.browser}', download: 'auto' },`);
20
+ if (calling) { config.push(' licenseKey: process.env.OPENWA_LICENSE_KEY || undefined,'); env.push('# Calling-enabled open-wa license', 'OPENWA_LICENSE_KEY='); }
21
+ if (options.plugins.length) {
22
+ config.push(` plugins: ${JSON.stringify(options.plugins.map(id => pluginChoices.find(plugin => plugin.value === id).package))},`, ' pluginConfig: {');
23
+ for (const id of options.plugins) {
24
+ if (id === 'voxtral') { config.push(` voxtral: { mode: '${options.voxtralMode}' },`); env.push('# Mistral API key for Voxtral', 'MISTRAL_API_KEY='); }
25
+ if (id === 'webhook') {
26
+ config.push(" webhook: { url: process.env.WEBHOOK_URL, events: ['message.received'] },");
27
+ env.push('# HTTPS endpoint receiving WhatsApp message events', 'WEBHOOK_URL=');
28
+ }
29
+ if (id === 'chatwoot') {
30
+ config.push(' chatwoot: {', ' chatwootUrl: process.env.CHATWOOT_URL,', ' chatwootApiAccessToken: process.env.CHATWOOT_API_ACCESS_TOKEN,', ' apiHost: process.env.OPENWA_PUBLIC_URL,', ' },');
31
+ env.push('# Chatwoot account URL, e.g. https://app.chatwoot.com/api/v1/accounts/123', 'CHATWOOT_URL=', 'CHATWOOT_API_ACCESS_TOKEN=', '# Your reachable Easy API URL for Chatwoot callbacks', 'OPENWA_PUBLIC_URL=');
32
+ }
33
+ }
34
+ config.push(' },');
35
+ }
36
+ const typeImport = ext === 'ts' ? "import type { CreateOptions } from '@open-wa/wa-automate';\n" : '';
37
+ const configSource = `import { existsSync } from 'node:fs';\n${typeImport}\nif (existsSync('.env')) process.loadEnvFile('.env');\n\nexport default {\n${config.join('\n')}\n}${ext === 'ts' ? ' satisfies CreateOptions' : ''};\n`;
38
+ const entry = options.mode === 'easy-api' ? undefined : `import { create } from '@open-wa/wa-automate';\nimport config from './${configName}';\n\nconst client = await create(config);\nconsole.log('WhatsApp is ready. Send !ping from another account.');\n\nclient.onMessage(async message => {\n if (!message.fromMe && message.body === '!ping') {\n await client.sendText(message.from, 'pong');\n }\n});\n\nfor (const signal of ['SIGINT', 'SIGTERM']${ext === 'ts' ? ' as const' : ''}) {\n process.once(signal, () => {\n void client.stop(signal).catch(console.error);\n });\n}\n`;
39
+ const manifest = {
40
+ name: projectName, version: '0.0.0', private: true, type: 'module',
41
+ scripts: { start: options.mode === 'easy-api' ? 'wa-automate' : `node index.${ext}` },
42
+ engines: { node: '>=22.21.1' },
43
+ dependencies: { '@open-wa/wa-automate': packageJson.version },
44
+ ...(ext === 'ts' ? { devDependencies: { '@types/node': '^22.0.0', typescript: '^5.9.0' } } : {}),
45
+ };
46
+ const readme = `# ${projectName}\n\n${options.mode === 'easy-api' ? 'An open-wa Easy API project with the Neo dashboard.' : 'A persistent open-wa SDK bot. Send !ping to receive pong.'}\n\n## Start\n\nUse Node.js 22.21.1 or newer. ${options.install ? 'Dependencies are installed by the initializer.' : 'Run npm install first.'}\n${env.length ? '\nCopy .env.example to .env and fill in the values for your selected integrations.\n' : ''}\n\`\`\`bash\nnpm start\n\`\`\`\n\nLink WhatsApp using the QR code. Stop with Ctrl+C.\n${options.mode === 'easy-api' ? '\nOpen http://127.0.0.1:8080/dashboard/ for Neo and http://127.0.0.1:8080/api-docs/ for the HTTP API.\n' : '\nAdd your handlers in index.' + ext + '. SDK mode runs your code without an HTTP server or Neo dashboard. Choose Easy API if you want those controls.\n'}\n## Configuration\n\nEdit ${configName}. ${options.mode === 'sdk' ? 'The bot imports this file and passes its settings to create().' : 'Easy API discovers this file automatically.'}\n\nThe browser choice is ${options.browser}. Browser downloads and selected plugins are installed only when needed at startup and reused later.\n${calling ? '\nVoxtral calls require a calling-enabled open-wa license in OPENWA_LICENSE_KEY.\n' : ''}\nLocal .env files, dependency folders and session data are ignored by Git.\n\n[Setup guide](https://openwa.dev/docs/getting-started/initializer) · [Configure a project](https://openwa.dev/new)\n`;
47
+ /** @type {Record<string, string>} */
48
+ const files = {
49
+ 'package.json': `${JSON.stringify(manifest, null, 2)}\n`,
50
+ [configName]: configSource,
51
+ ...(entry ? { [`index.${ext}`]: entry } : {}),
52
+ ...(ext === 'ts' ? { 'tsconfig.json': `${JSON.stringify({ compilerOptions: { target: 'ES2022', module: 'NodeNext', moduleResolution: 'NodeNext', strict: true, noEmit: true, allowImportingTsExtensions: true, skipLibCheck: true, types: ['node'] }, include: ['*.ts'] }, null, 2)}\n` } : {}),
53
+ '.gitignore': '/node_modules/\n/.open-wa/\n/_IGNORE_*/\n/*.data.json\n.env\n.env.*\n!.env.example\n',
54
+ ...(env.length ? { '.env.example': `${env.join('\n')}\n` } : {}),
55
+ 'README.md': readme,
56
+ };
57
+ return files;
58
+ }