@open-wa/schema 5.0.0-alpha.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE.md +67 -0
  3. package/README.md +19 -0
  4. package/client_migration_doc.md +467 -0
  5. package/codecs_and_params_plan.md +936 -0
  6. package/migration_plan_doc.md +223 -0
  7. package/package.json +90 -0
  8. package/scripts/gen-client-implementation.ts +129 -0
  9. package/scripts/gen-client-reference-docs.ts +621 -0
  10. package/scripts/gen-openapi.ts +96 -0
  11. package/scripts/gen-types.ts +43 -0
  12. package/scripts/verify-v5-pipeline.ts +85 -0
  13. package/src/__tests__/generators.contract.test.ts +181 -0
  14. package/src/__tests__/registry.contract.test.ts +81 -0
  15. package/src/client-config.ts +30 -0
  16. package/src/codecs.test.ts +41 -0
  17. package/src/codecs.ts +191 -0
  18. package/src/common-types.ts +280 -0
  19. package/src/config.ts +47 -0
  20. package/src/enums.ts +63 -0
  21. package/src/events/groups.ts +33 -0
  22. package/src/events/index.ts +4 -0
  23. package/src/events/messaging.ts +72 -0
  24. package/src/events/registry.ts +114 -0
  25. package/src/events/state.ts +59 -0
  26. package/src/generated/AliasMap.ts +214 -0
  27. package/src/generated/BaseClient.ts +868 -0
  28. package/src/generated/BaseNamespacedClient.ts +212 -0
  29. package/src/generated/index.ts +5 -0
  30. package/src/generated/openapi.json +7799 -0
  31. package/src/generated/types.ts +377 -0
  32. package/src/http-manifest.ts +97 -0
  33. package/src/implementor.test.ts +88 -0
  34. package/src/implementor.ts +75 -0
  35. package/src/index.ts +43 -0
  36. package/src/methods/business.ts +51 -0
  37. package/src/methods/chats.ts +263 -0
  38. package/src/methods/communities.ts +119 -0
  39. package/src/methods/contacts.ts +158 -0
  40. package/src/methods/groups.ts +376 -0
  41. package/src/methods/index.ts +33 -0
  42. package/src/methods/labels.ts +86 -0
  43. package/src/methods/media.ts +36 -0
  44. package/src/methods/messaging.ts +828 -0
  45. package/src/methods/session.ts +261 -0
  46. package/src/methods/status.ts +120 -0
  47. package/src/open-wa-utils.d.ts +4 -0
  48. package/src/parameters.ts +237 -0
  49. package/src/registry.test.ts +30 -0
  50. package/src/registry.ts +601 -0
  51. package/tsconfig.generated.json +11 -0
  52. package/tsconfig.json +15 -0
  53. package/tsdown.config.ts +16 -0
  54. package/vitest.config.ts +10 -0
@@ -0,0 +1,223 @@
1
+ # Schema Package v2 Migration Plan
2
+
3
+ This document outlines the steps to refactor the `@open-wa/wa-automate/schema` package to support "Dual-Mode" inputs (Positional Arguments + Named Objects), rich metadata for RBAC/Automation, and a runtime implementation bridge.
4
+
5
+ ## Goals
6
+ 1. **Dual-Mode Inputs**: Support `method(a, b)` AND `method({ a: val, b: val })` automatically.
7
+ 2. **Rich Metadata**: Embed RBAC actions (`read`, `send`), licensing tiers, and functionality scopes directly into the Zod schema.
8
+ 3. **Runtime Normalization**: Provide a standard way to "implement" these schemas that automatically resolves mixed arguments into a single typed object.
9
+ 4. **Automatic WAPI Bridge**: Default implementation automatically bridges calls to `WAPI` via `this.pup`.
10
+
11
+ ---
12
+
13
+ ## Phase 1: Define Core Metadata Enums
14
+ Create `src/enums.ts`. These will drive the metadata validation.
15
+
16
+ 1. **`ActionEnum`**: `read`, `send`, `update`, `delete`.
17
+ 2. **`LicenseEnum`**: `none`, `insiders`, `restricted`.
18
+ 3. **`FunctionalityEnum`**: `both`, `business-only`, `personal-only`.
19
+ 4. **`HttpMethodEnum`**: `GET`, `POST`, `PUT`, `DELETE`, `AUTO`.
20
+
21
+ ---
22
+
23
+ ## Phase 2: Update Registry Infrastructure
24
+ Refactor `src/registry.ts`.
25
+
26
+ ### 1. Switch to Native Zod Registry
27
+ Replace the custom `Registry` class with Zod's `z.registry()`.
28
+
29
+ ```typescript
30
+ // src/registry.ts
31
+ import { z } from 'zod';
32
+
33
+ // Define the shape of our custom metadata
34
+ export interface ClientFunctionMetadata {
35
+ functionName?: string;
36
+ namespace?: string;
37
+ action?: ActionEnum;
38
+ description?: string;
39
+ license?: LicenseEnum;
40
+ parameterOrder?: string[]; // Critical for mapping positional args to object keys
41
+ // ... other fields from PoC
42
+ }
43
+
44
+ // Global registry for client capabilities
45
+ export const clientRegistry = z.registry<ClientFunctionMetadata, z.ZodFunction>();
46
+ ```
47
+
48
+ ### 2. Add `zObjectToTuple` Helper
49
+ Add the utility function that converts a Zod Object shape into a Zod Tuple based on an array of keys.
50
+
51
+ ```typescript
52
+ // Helper to convert object shape to tuple based on key order
53
+ export function zObjectToTuple<Shape extends z.ZodRawShape, Keys extends readonly [keyof Shape, ...Array<keyof Shape>]>(
54
+ zodObj: z.ZodObject<Shape>,
55
+ keys: Keys
56
+ ): z.ZodTuple<...> { ... }
57
+ ```
58
+
59
+ ---
60
+
61
+ ## Phase 3: The `defineMethod` Factory
62
+ Refactor `defineMethod` in `src/registry.ts` (or `src/dsl.ts`).
63
+
64
+ This function is the "Magic Maker". It takes a simple Object definition and returns a complex `z.function` that accepts **Both** formats.
65
+
66
+ **Input**:
67
+ - `name`: string
68
+ - `input`: z.ZodObject (The named parameters)
69
+ - `args`: Array of strings (The order of keys for positional arguments)
70
+ - `meta`: Metadata object
71
+
72
+ **Output**:
73
+ - A `z.function` schema where the `input` is a `z.union` of:
74
+ 1. `z.tuple` (derived from `input` + `args` order)
75
+ 2. `z.tuple([input])` (The object passed as a single argument)
76
+
77
+ ```typescript
78
+ // Pseudo-implementation
79
+ export const defineMethod = <T extends z.ZodObject<any>>(
80
+ name: string,
81
+ params: {
82
+ meta: ClientFunctionMetadata,
83
+ input: T,
84
+ parameterOrder: Array<keyof T['shape']>, // Type-safe keys
85
+ output: z.ZodTypeAny
86
+ }
87
+ ) => {
88
+ // 1. Create Tuple Schema from Object + Order
89
+ const tupleSchema = zObjectToTuple(params.input, params.parameterOrder);
90
+
91
+ // 2. Create the Union Input: (ParamsObject) | (...PositionalArgs)
92
+ const inputUnion = z.union([
93
+ z.tuple([params.input]), // Case A: func({ a: 1, b: 2 })
94
+ tupleSchema // Case B: func(1, 2)
95
+ ]);
96
+
97
+ // 3. Create Function Schema
98
+ const funcSchema = z.function()
99
+ .args(inputUnion as any) // Cast needed for complex union
100
+ .returns(params.output);
101
+
102
+ // 4. Register Metadata
103
+ return funcSchema.register(clientRegistry, {
104
+ functionName: name,
105
+ parameterOrder: params.parameterOrder,
106
+ ...params.meta
107
+ });
108
+ }
109
+ ```
110
+
111
+ ---
112
+
113
+ ## Phase 4: Runtime Implementation Helper (`implementAsync`)
114
+ Create `src/implementor.ts`.
115
+
116
+ We need a generic wrapper that the **Client** package will use to implement these schemas without boilerplate. It should support a default execution strategy (via `this.pup` -> `WAPI`) while allowing overrides.
117
+
118
+ ```typescript
119
+ import { z } from 'zod';
120
+ import { clientRegistry } from './registry';
121
+
122
+ /**
123
+ * Creates a runtime method from a Zod Schema.
124
+ * It handles the argument normalization (Positional -> Object) automatically.
125
+ */
126
+ export function implementMethod<
127
+ Schema extends z.ZodFunction,
128
+ ParamsObj = z.infer<Schema['parameters']['items'][0]>[0] // Extract the Object type
129
+ >(
130
+ schema: Schema,
131
+ // Optional override. If omitted, defaults to generic WAPI call via this.pup
132
+ implementation?: (params: ParamsObj) => Promise<z.infer<Schema['returnType']>>
133
+ ) {
134
+ // Use a regular function (not arrow) to preserve 'this' context
135
+ return schema.implementAsync(async function(this: any, ...args) {
136
+ const meta = clientRegistry.get(schema);
137
+ let resolvedParams: any = {};
138
+
139
+ // 1. Detect if called with a single Object argument
140
+ if (args.length === 1 && typeof args[0] === 'object' && !Array.isArray(args[0])) {
141
+ // It's the object style
142
+ resolvedParams = args[0];
143
+ } else {
144
+ // 2. It's positional arguments -> Map to keys using metadata
145
+ resolvedParams = args.reduce((acc, arg, index) => ({
146
+ ...acc,
147
+ [meta.parameterOrder![index]]: arg
148
+ }), {});
149
+ }
150
+
151
+ // 3. Custom Implementation (if provided)
152
+ if (implementation) {
153
+ // Call with 'this' bound, in case the override needs class properties
154
+ return implementation.call(this, resolvedParams);
155
+ }
156
+
157
+ // 4. Default Fallback: Execute via this.pup()
158
+ // This assumes the class instance has a 'pup' method
159
+ if (!this.pup) {
160
+ throw new Error('Default implementation requires this.pup() method');
161
+ }
162
+
163
+ // Dynamically call WAPI on the browser side
164
+ return await this.pup(
165
+ (params: any) => (window as any).WAPI[meta.functionName!](params),
166
+ resolvedParams
167
+ );
168
+ });
169
+ }
170
+ ```
171
+
172
+ ---
173
+
174
+ ## Phase 5: Refactor `methods.ts`
175
+ Convert existing methods to the new format.
176
+
177
+ **Example: `sendText`**
178
+
179
+ ```typescript
180
+ export const sendText = defineMethod('sendText', {
181
+ meta: {
182
+ description: 'Sends a text message',
183
+ action: ActionEnum.SEND,
184
+ functionality: FunctionalityEnum.BOTH
185
+ },
186
+ // Define params as a standard Object
187
+ input: z.object({
188
+ to: z.string(),
189
+ content: z.string(),
190
+ options: z.any().optional()
191
+ }),
192
+ // Explicitly define the positional order
193
+ parameterOrder: ['to', 'content', 'options'],
194
+ output: MessageIdReturnSchema
195
+ });
196
+ ```
197
+
198
+ ## Phase 6: Client Usage (Future)
199
+ When the `@open-wa/wa-automate` client imports this, it can use the default behavior or override it.
200
+
201
+ ```typescript
202
+ import { sendText, implementMethod } from '@open-wa/schema';
203
+
204
+ class Client {
205
+
206
+ // 1. Default Implementation:
207
+ // Automatically maps to: await this.pup((p) => WAPI.sendText(p), params)
208
+ sendText = implementMethod(sendText);
209
+
210
+ // 2. Custom Override:
211
+ // useful for methods that need node-side logic before/after
212
+ sendImage = implementMethod(sendImage, async (params) => {
213
+ const base64 = await convertToBase64(params.file);
214
+ // Manually call pup or do logic
215
+ return this.pup((p) => WAPI.sendImage(p), { ...params, imgData: base64 });
216
+ });
217
+
218
+ // The bridge method required by the default implementation
219
+ async pup(func: Function, args: any) {
220
+ // Implementation that sends function to browser
221
+ }
222
+ }
223
+ ```
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "@open-wa/schema",
3
+ "version": "5.0.0-alpha.0",
4
+ "type": "module",
5
+ "description": "Zod-based schema definitions for open-wa",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.mjs",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "require": {
12
+ "types": "./dist/index.d.cts",
13
+ "default": "./dist/index.cjs"
14
+ },
15
+ "import": {
16
+ "types": "./dist/index.d.mts",
17
+ "default": "./dist/index.mjs"
18
+ }
19
+ },
20
+ "./generated": {
21
+ "require": {
22
+ "types": "./dist/generated/index.d.cts",
23
+ "default": "./dist/generated/index.cjs"
24
+ },
25
+ "import": {
26
+ "types": "./dist/generated/index.d.mts",
27
+ "default": "./dist/generated/index.mjs"
28
+ }
29
+ },
30
+ "./implementor": {
31
+ "require": {
32
+ "types": "./dist/implementor.d.cts",
33
+ "default": "./dist/implementor.cjs"
34
+ },
35
+ "import": {
36
+ "types": "./dist/implementor.d.mts",
37
+ "default": "./dist/implementor.mjs"
38
+ }
39
+ },
40
+ "./methods": {
41
+ "require": {
42
+ "types": "./dist/methods/index.d.cts",
43
+ "default": "./dist/methods/index.cjs"
44
+ },
45
+ "import": {
46
+ "types": "./dist/methods/index.d.mts",
47
+ "default": "./dist/methods/index.mjs"
48
+ }
49
+ },
50
+ "./http-manifest": {
51
+ "require": {
52
+ "types": "./dist/http-manifest.d.cts",
53
+ "default": "./dist/http-manifest.cjs"
54
+ },
55
+ "import": {
56
+ "types": "./dist/http-manifest.d.mts",
57
+ "default": "./dist/http-manifest.mjs"
58
+ }
59
+ }
60
+ },
61
+ "dependencies": {
62
+ "@asteasolutions/zod-to-openapi": "^8.5.0",
63
+ "zod": "^4.2.1",
64
+ "zod-to-json-schema": "^3.22.3",
65
+ "@open-wa/utils": "5.0.0-alpha.0",
66
+ "@open-wa/config": "5.0.0-alpha.0"
67
+ },
68
+ "devDependencies": {
69
+ "ts-node": "^10.9.1",
70
+ "typescript": "^6.0.3",
71
+ "vitest": "4.1.2"
72
+ },
73
+ "publishConfig": {
74
+ "access": "public"
75
+ },
76
+ "repository": {
77
+ "type": "git",
78
+ "url": "https://github.com/open-wa/wa-automate-nodejs.git"
79
+ },
80
+ "scripts": {
81
+ "generate": "tsx scripts/gen-openapi.ts && tsx scripts/gen-types.ts && tsx scripts/gen-client-implementation.ts && tsx scripts/gen-client-reference-docs.ts",
82
+ "build": "pnpm generate && tsdown",
83
+ "dev": "tsdown --watch",
84
+ "lint": "oxlint src scripts",
85
+ "test": "vitest run",
86
+ "test:contracts": "pnpm generate && vitest run src/__tests__/*.contract.test.ts",
87
+ "verify": "tsx scripts/verify-v5-pipeline.ts",
88
+ "ci": "pnpm verify && pnpm test:contracts && pnpm build"
89
+ }
90
+ }
@@ -0,0 +1,129 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { clientRegistry } from '../src/registry';
5
+
6
+ import '../src/methods';
7
+
8
+ const generatedDir = path.join(fileURLToPath(new URL('.', import.meta.url)), '../src/generated');
9
+ if (!fs.existsSync(generatedDir)) {
10
+ fs.mkdirSync(generatedDir, { recursive: true });
11
+ }
12
+
13
+ type MethodMeta = ReturnType<typeof clientRegistry.getAll>[number]['meta'];
14
+
15
+ function sortStrings(values: string[]) {
16
+ return [...values].sort((left, right) => left.localeCompare(right));
17
+ }
18
+
19
+ function buildFlatAliasDocs(meta: MethodMeta): string {
20
+ const aliases = sortStrings((meta.allAliases ?? []).filter((alias) => !alias.includes('.')));
21
+ return aliases.length > 0 ? ` * @aliases ${aliases.join(', ')}\n` : '';
22
+ }
23
+
24
+ function buildFlatAliasProperties(methods: ReturnType<typeof clientRegistry.getAll>): string {
25
+ const lines: string[] = [];
26
+
27
+ for (const def of methods) {
28
+ const flatAliases = sortStrings((def.meta.allAliases ?? []).filter((alias) => !alias.includes('.')));
29
+
30
+ for (const alias of flatAliases) {
31
+ const deprecated = (def.meta.deprecatedAliases ?? []).includes(alias);
32
+ const doc = deprecated
33
+ ? ` /**\n * @deprecated Use ${def.meta.functionName} instead.\n * Deprecated alias of ${def.meta.functionName}.\n */\n`
34
+ : ` /**\n * Alias of ${def.meta.functionName}.\n */\n`;
35
+
36
+ lines.push(`${doc} public ${alias} = this.${def.meta.functionName};\n`);
37
+ }
38
+ }
39
+
40
+ return lines.join('\n');
41
+ }
42
+
43
+ function buildNamespacedSurface(methods: ReturnType<typeof clientRegistry.getAll>): string {
44
+ const namespaceMembers = new Map<string, Map<string, string>>();
45
+
46
+ for (const def of methods) {
47
+ const namespace = def.meta.namespace;
48
+ if (!namespace) {
49
+ continue;
50
+ }
51
+
52
+ const members = namespaceMembers.get(namespace) ?? new Map<string, string>();
53
+ for (const alias of sortStrings((def.meta.allAliases ?? []).filter((entry) => entry.includes('.')))) {
54
+ const [aliasNamespace, ...rest] = alias.split('.');
55
+ if (aliasNamespace !== namespace) {
56
+ continue;
57
+ }
58
+
59
+ members.set(rest.join('.'), def.meta.functionName);
60
+ }
61
+
62
+ namespaceMembers.set(namespace, members);
63
+ }
64
+
65
+ return sortStrings(Array.from(namespaceMembers.keys()))
66
+ .map((namespace) => {
67
+ const members = namespaceMembers.get(namespace)!;
68
+ const body = sortStrings(Array.from(members.keys()))
69
+ .map((member) => ` ${member}: this.${members.get(member)}`)
70
+ .join(',\n');
71
+
72
+ return ` public ${namespace} = {\n${body}\n };\n`;
73
+ })
74
+ .join('\n');
75
+ }
76
+
77
+ const methods = clientRegistry.getAll();
78
+
79
+ let baseClientOutput = `/* eslint-disable */
80
+ /**
81
+ * This file was automatically generated by packages/schema/scripts/gen-client-implementation.ts
82
+ * Do not edit this file manually.
83
+ */
84
+ import { implementMethod } from '../implementor';
85
+ import * as Methods from '../methods';
86
+
87
+ export abstract class BaseClient {
88
+ protected abstract execute(method: string, args: any): Promise<any>;
89
+
90
+ protected async pup(_func: any, args: any): Promise<any> {
91
+ throw new Error('BaseClient.pup is not available without a runtime implementation.');
92
+ }
93
+
94
+ `;
95
+
96
+ for (const def of methods) {
97
+ baseClientOutput += ` /**\n * ${def.meta.description || def.meta.functionName}\n${buildFlatAliasDocs(def.meta)} */\n public ${def.meta.functionName} = implementMethod(Methods.${def.meta.functionName});\n\n`;
98
+ }
99
+
100
+ baseClientOutput += `${buildFlatAliasProperties(methods)}}\n`;
101
+
102
+ const namespacedOutput = `/* eslint-disable */
103
+ /**
104
+ * This file was automatically generated by packages/schema/scripts/gen-client-implementation.ts
105
+ * Do not edit this file manually.
106
+ */
107
+ import { BaseClient } from './BaseClient';
108
+
109
+ export abstract class BaseNamespacedClient extends BaseClient {
110
+ ${buildNamespacedSurface(methods)}}
111
+ `;
112
+
113
+ const aliasMapOutput = `/* eslint-disable */
114
+ /**
115
+ * This file was automatically generated by packages/schema/scripts/gen-client-implementation.ts
116
+ * Do not edit this file manually.
117
+ */
118
+ export const clientMethodAliasMap = ${JSON.stringify(clientRegistry.getAliasMap(), null, 2)} as const;
119
+ `;
120
+
121
+ fs.writeFileSync(path.join(generatedDir, 'BaseClient.ts'), baseClientOutput);
122
+ fs.writeFileSync(path.join(generatedDir, 'BaseNamespacedClient.ts'), namespacedOutput);
123
+ fs.writeFileSync(path.join(generatedDir, 'AliasMap.ts'), aliasMapOutput);
124
+ fs.writeFileSync(
125
+ path.join(generatedDir, 'index.ts'),
126
+ `/* eslint-disable */\nexport * from './AliasMap';\nexport * from './BaseClient';\nexport * from './BaseNamespacedClient';\nexport * from './types';\n`
127
+ );
128
+
129
+ console.log('Successfully generated BaseClient.ts, BaseNamespacedClient.ts, and AliasMap.ts');