@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,936 @@
1
+ # Codecs and Parameters Implementation Plan
2
+
3
+ ## Overview
4
+
5
+ This document outlines the implementation plan for adding Zod codecs and reusable parameters to the `@open-wa/schema` package. The goal is to create intelligent, bi-directional transformations for common WhatsApp data types and provide a library of reusable, well-documented parameters.
6
+
7
+ ## Background
8
+
9
+ Zod 4.1+ introduces **codecs** - schemas that define bi-directional transformations between input and output types:
10
+ - **Forward (decode)**: Convert user-friendly input → internal representation
11
+ - **Backward (encode)**: Convert internal representation → user-friendly output
12
+
13
+ This is perfect for WhatsApp API parameters where we want to accept flexible inputs (e.g., just a phone number) and automatically transform them to the required format (e.g., `447123456789@c.us`).
14
+
15
+ ## File Structure
16
+
17
+ ```
18
+ packages/schema/src/
19
+ ├── codecs.ts # Bi-directional transformation codecs
20
+ ├── parameters.ts # Reusable parameter schemas with metadata
21
+ ├── enums.ts # Existing enums
22
+ ├── registry.ts # Existing registry
23
+ ├── implementor.ts # Existing implementor
24
+ ├── methods.ts # Updated to use parameters.ts
25
+ └── index.ts # Export codecs and parameters
26
+ ```
27
+
28
+ ---
29
+
30
+ ## Part 1: Codecs (`codecs.ts`)
31
+
32
+ ### 1.1 Chat ID Codec
33
+
34
+ **Purpose**: Intelligently convert phone numbers to proper WhatsApp chat IDs.
35
+
36
+ **Logic**:
37
+ - Input: Phone number (with or without suffix)
38
+ - Output: Properly formatted ChatId
39
+
40
+ **Rules**:
41
+ 1. If input already has `@c.us`, `@g.us`, or `@lid` → pass through
42
+ 2. Count digits in the number:
43
+ - **18 digits** → Group chat → append `@g.us`
44
+ - **14 digits** → Could be LID or Indonesian number
45
+ - If starts with `62` (Indonesia) → append `@c.us`
46
+ - Otherwise → append `@lid`
47
+ - **< 14 digits** → Regular contact → append `@c.us`
48
+
49
+ **Implementation**:
50
+
51
+ ```typescript
52
+ export const chatIdCodec = z.codec(
53
+ z.string(), // Input: flexible string
54
+ z.string(), // Output: formatted ChatId
55
+ {
56
+ decode: (input) => {
57
+ // Already formatted
58
+ if (input.includes('@')) return input;
59
+
60
+ // Extract just digits
61
+ const digits = input.replace(/\D/g, '');
62
+ const digitCount = digits.length;
63
+
64
+ // Determine suffix
65
+ if (digitCount === 18) {
66
+ return `${digits}@g.us`;
67
+ } else if (digitCount === 14) {
68
+ // Check if Indonesian
69
+ if (digits.startsWith('62')) {
70
+ return `${digits}@c.us`;
71
+ }
72
+ return `${digits}@lid`;
73
+ } else {
74
+ // Regular contact (< 14 digits)
75
+ return `${digits}@c.us`;
76
+ }
77
+ },
78
+ encode: (chatId) => {
79
+ // For encoding, just return as-is (already formatted)
80
+ return chatId;
81
+ }
82
+ }
83
+ );
84
+ ```
85
+
86
+ **Usage**:
87
+ ```typescript
88
+ chatIdCodec.decode("447123456789"); // => "447123456789@c.us"
89
+ chatIdCodec.decode("447123456789@c.us"); // => "447123456789@c.us"
90
+ chatIdCodec.decode("123456789012345678"); // => "123456789012345678@g.us"
91
+ chatIdCodec.decode("62812345678901"); // => "62812345678901@c.us" (Indonesian)
92
+ chatIdCodec.decode("12345678901234"); // => "12345678901234@lid" (non-Indonesian 14 digits)
93
+ ```
94
+
95
+ ---
96
+
97
+ ### 1.2 Contact ID Codec
98
+
99
+ **Purpose**: Convert phone numbers to contact IDs (always `@c.us`).
100
+
101
+ ```typescript
102
+ export const contactIdCodec = z.codec(
103
+ z.string(),
104
+ z.string(),
105
+ {
106
+ decode: (input) => {
107
+ if (input.includes('@c.us')) return input;
108
+ const digits = input.replace(/\D/g, '');
109
+ return `${digits}@c.us`;
110
+ },
111
+ encode: (contactId) => contactId
112
+ }
113
+ );
114
+ ```
115
+
116
+ ---
117
+
118
+ ### 1.3 Group ID Codec
119
+
120
+ **Purpose**: Convert to group chat IDs (always `@g.us`).
121
+
122
+ ```typescript
123
+ export const groupIdCodec = z.codec(
124
+ z.string(),
125
+ z.string(),
126
+ {
127
+ decode: (input) => {
128
+ if (input.includes('@g.us')) return input;
129
+ const digits = input.replace(/\D/g, '');
130
+ return `${digits}@g.us`;
131
+ },
132
+ encode: (groupId) => groupId
133
+ }
134
+ );
135
+ ```
136
+
137
+ ---
138
+
139
+ ### 1.4 File Input Codec
140
+
141
+ **Purpose**: Accept flexible file inputs and convert to the desired output format.
142
+
143
+ **Supported Inputs**:
144
+ - DataURL (`data:image/png;base64,...`)
145
+ - Base64 string
146
+ - File path (relative or absolute)
147
+ - URL (http/https)
148
+ - Buffer
149
+
150
+ **Output Types**:
151
+ - `DATA_URL`
152
+ - `BASE_64`
153
+ - `BUFFER`
154
+ - `TEMP_FILE_PATH`
155
+ - `READ_STREAM`
156
+
157
+ **Implementation Strategy**:
158
+
159
+ Since the file codec needs to support multiple output types, we'll create a **factory function** that generates codecs for each output type:
160
+
161
+ ```typescript
162
+ import { AdvancedFile } from '@open-wa/core/api/model';
163
+ import { assertFile, FileOutputTypes } from '@open-wa/core/utils/tools';
164
+
165
+ /**
166
+ * Creates a file codec that transforms various file inputs to a specific output type
167
+ */
168
+ export const createFileCodec = (outputType: keyof typeof FileOutputTypes) => {
169
+ return z.codec(
170
+ z.union([
171
+ z.string(), // DataURL, Base64, FilePath, or URL
172
+ z.instanceof(Buffer)
173
+ ]),
174
+ z.union([
175
+ z.string(), // For DATA_URL, BASE_64, TEMP_FILE_PATH
176
+ z.instanceof(Buffer), // For BUFFER
177
+ z.any() // For READ_STREAM (Readable)
178
+ ]),
179
+ {
180
+ decode: async (input, ctx) => {
181
+ try {
182
+ // Use the existing assertFile utility
183
+ return await assertFile(input, 'file', outputType);
184
+ } catch (err: any) {
185
+ ctx.issues.push({
186
+ code: 'custom',
187
+ message: err.message,
188
+ path: []
189
+ });
190
+ return z.NEVER;
191
+ }
192
+ },
193
+ encode: (output) => output
194
+ }
195
+ );
196
+ };
197
+
198
+ // Pre-built codecs for common use cases
199
+ export const fileToDataUrlCodec = createFileCodec(FileOutputTypes.DATA_URL);
200
+ export const fileToBase64Codec = createFileCodec(FileOutputTypes.BASE_64);
201
+ export const fileToBufferCodec = createFileCodec(FileOutputTypes.BUFFER);
202
+ export const fileToTempPathCodec = createFileCodec(FileOutputTypes.TEMP_FILE_PATH);
203
+ export const fileToStreamCodec = createFileCodec(FileOutputTypes.READ_STREAM);
204
+ ```
205
+
206
+ **Usage**:
207
+ ```typescript
208
+ // Accept any file format, output as DataURL
209
+ await fileToDataUrlCodec.decode("./image.png");
210
+ await fileToDataUrlCodec.decode("https://example.com/image.png");
211
+ await fileToDataUrlCodec.decode("data:image/png;base64,...");
212
+ await fileToDataUrlCodec.decode(Buffer.from(...));
213
+ ```
214
+
215
+ ---
216
+
217
+ ### 1.5 Message ID Codec
218
+
219
+ **Purpose**: Validate and normalize message IDs.
220
+
221
+ **Format**: `{boolean}_{ChatId}_{randomString}`
222
+
223
+ ```typescript
224
+ export const messageIdCodec = z.codec(
225
+ z.string(),
226
+ z.string(),
227
+ {
228
+ decode: (input) => {
229
+ // Validate format
230
+ const parts = input.split('_');
231
+ if (parts.length !== 3) {
232
+ throw new Error('Invalid message ID format');
233
+ }
234
+ if (!['true', 'false'].includes(parts[0])) {
235
+ throw new Error('Invalid message ID: first part must be boolean');
236
+ }
237
+ return input;
238
+ },
239
+ encode: (messageId) => messageId
240
+ }
241
+ );
242
+ ```
243
+
244
+ ---
245
+
246
+ ### 1.6 Additional Useful Codecs
247
+
248
+ #### Base64 to DataURL Codec
249
+
250
+ ```typescript
251
+ export const base64ToDataUrlCodec = z.codec(
252
+ z.string(), // Base64 string
253
+ z.string(), // DataURL
254
+ {
255
+ decode: (base64, ctx) => {
256
+ // Detect mime type or use default
257
+ const mimeType = 'application/octet-stream'; // Could be enhanced
258
+ return `data:${mimeType};base64,${base64}`;
259
+ },
260
+ encode: (dataUrl) => {
261
+ // Extract base64 part
262
+ return dataUrl.split(',')[1];
263
+ }
264
+ }
265
+ );
266
+ ```
267
+
268
+ #### URL to DataURL Codec
269
+
270
+ ```typescript
271
+ export const urlToDataUrlCodec = z.codec(
272
+ z.url(),
273
+ z.string(), // DataURL
274
+ {
275
+ decode: async (url, ctx) => {
276
+ try {
277
+ // Use existing getDUrl utility
278
+ const { getDUrl } = await import('@open-wa/core/utils/tools');
279
+ return await getDUrl(url);
280
+ } catch (err: any) {
281
+ ctx.issues.push({
282
+ code: 'custom',
283
+ message: `Failed to fetch URL: ${err.message}`,
284
+ path: []
285
+ });
286
+ return z.NEVER;
287
+ }
288
+ },
289
+ encode: (dataUrl) => {
290
+ // Can't reliably convert back to URL
291
+ throw new Error('Cannot encode DataURL back to URL');
292
+ }
293
+ }
294
+ );
295
+ ```
296
+
297
+ ---
298
+
299
+ ## Part 2: Parameters (`parameters.ts`)
300
+
301
+ ### 2.1 Purpose
302
+
303
+ Create a library of reusable, well-documented parameter schemas that can be imported and used across method definitions.
304
+
305
+ ### 2.2 Structure
306
+
307
+ Each parameter should:
308
+ 1. Have a descriptive name
309
+ 2. Use appropriate codecs for transformation
310
+ 3. Include metadata (examples, descriptions)
311
+ 4. Be registered with `parameterRegistry`
312
+
313
+ ### 2.3 Parameter Definitions
314
+
315
+ Based on `aliases.ts`, here are the key parameters:
316
+
317
+ #### Chat & Contact Parameters
318
+
319
+ ```typescript
320
+ import { chatIdCodec, contactIdCodec, groupIdCodec, messageIdCodec } from './codecs';
321
+ import { parameterRegistry } from './registry';
322
+
323
+ /**
324
+ * Chat ID parameter - accepts phone numbers or formatted chat IDs
325
+ * Automatically converts to proper format (e.g., "447123456789" → "447123456789@c.us")
326
+ */
327
+ export const chatIdParam = chatIdCodec.describe('Chat ID (phone number or formatted ID)');
328
+ parameterRegistry.set(chatIdParam, {
329
+ example: '447123456789@c.us'
330
+ });
331
+
332
+ /**
333
+ * Contact ID parameter - always formats as @c.us
334
+ */
335
+ export const contactIdParam = contactIdCodec.describe('Contact ID (phone number)');
336
+ parameterRegistry.set(contactIdParam, {
337
+ example: '447123456789@c.us'
338
+ });
339
+
340
+ /**
341
+ * Group chat ID parameter - always formats as @g.us
342
+ */
343
+ export const groupIdParam = groupIdCodec.describe('Group chat ID');
344
+ parameterRegistry.set(groupIdParam, {
345
+ example: '447123456789-1445627445@g.us'
346
+ });
347
+
348
+ /**
349
+ * Message ID parameter
350
+ */
351
+ export const messageIdParam = messageIdCodec.describe('Message ID');
352
+ parameterRegistry.set(messageIdParam, {
353
+ example: 'false_447123456789@c.us_9C4D0965EA5C09D591334AB6BDB07FEB'
354
+ });
355
+
356
+ /**
357
+ * Generic "to" parameter - accepts any chat ID
358
+ */
359
+ export const toParam = chatIdParam.describe('Recipient chat ID');
360
+ parameterRegistry.set(toParam, {
361
+ example: '447123456789@c.us'
362
+ });
363
+ ```
364
+
365
+ #### Content Parameters
366
+
367
+ ```typescript
368
+ /**
369
+ * Message content/text
370
+ */
371
+ export const contentParam = z.string().min(1).describe('Message content');
372
+ parameterRegistry.set(contentParam, {
373
+ example: 'Hello, world!'
374
+ });
375
+
376
+ /**
377
+ * Caption for media messages
378
+ */
379
+ export const captionParam = z.string().optional().describe('Media caption');
380
+ parameterRegistry.set(captionParam, {
381
+ example: 'Check out this image!'
382
+ });
383
+
384
+ /**
385
+ * Filename parameter
386
+ */
387
+ export const filenameParam = z.string().optional().describe('Filename with extension');
388
+ parameterRegistry.set(filenameParam, {
389
+ example: 'document.pdf'
390
+ });
391
+ ```
392
+
393
+ #### File Parameters
394
+
395
+ ```typescript
396
+ import { fileToDataUrlCodec, fileToBase64Codec } from './codecs';
397
+
398
+ /**
399
+ * Image data - accepts file path, URL, DataURL, or Base64
400
+ * Automatically converts to DataURL
401
+ */
402
+ export const imageDataParam = fileToDataUrlCodec.describe('Image file (path, URL, DataURL, or Base64)');
403
+ parameterRegistry.set(imageDataParam, {
404
+ example: 'data:image/png;base64,iVBORw0KGgo...'
405
+ });
406
+
407
+ /**
408
+ * Generic file data parameter
409
+ */
410
+ export const fileDataParam = fileToDataUrlCodec.describe('File (path, URL, DataURL, Base64, or Buffer)');
411
+ parameterRegistry.set(fileDataParam, {
412
+ example: 'data:application/pdf;base64,JVBERi0xLjQK...'
413
+ });
414
+
415
+ /**
416
+ * Audio data parameter
417
+ */
418
+ export const audioDataParam = fileToDataUrlCodec.describe('Audio file (path, URL, DataURL, or Base64)');
419
+ parameterRegistry.set(audioDataParam, {
420
+ example: 'data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAA...'
421
+ });
422
+
423
+ /**
424
+ * Video data parameter
425
+ */
426
+ export const videoDataParam = fileToDataUrlCodec.describe('Video file (path, URL, DataURL, or Base64)');
427
+ parameterRegistry.set(videoDataParam, {
428
+ example: 'data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21...'
429
+ });
430
+
431
+ /**
432
+ * Document data parameter
433
+ */
434
+ export const documentDataParam = fileToDataUrlCodec.describe('Document file (path, URL, DataURL, or Base64)');
435
+ parameterRegistry.set(documentDataParam, {
436
+ example: 'data:application/pdf;base64,JVBERi0xLjQK...'
437
+ });
438
+
439
+ /**
440
+ * Sticker data parameter
441
+ */
442
+ export const stickerDataParam = fileToDataUrlCodec.describe('Sticker file (path, URL, DataURL, or Base64)');
443
+ parameterRegistry.set(stickerDataParam, {
444
+ example: 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAw...'
445
+ });
446
+ ```
447
+
448
+ #### Location Parameters
449
+
450
+ ```typescript
451
+ /**
452
+ * Latitude parameter
453
+ */
454
+ export const latitudeParam = z.union([z.number(), z.string()]).describe('Latitude coordinate');
455
+ parameterRegistry.set(latitudeParam, {
456
+ example: 51.5074
457
+ });
458
+
459
+ /**
460
+ * Longitude parameter
461
+ */
462
+ export const longitudeParam = z.union([z.number(), z.string()]).describe('Longitude coordinate');
463
+ parameterRegistry.set(longitudeParam, {
464
+ example: -0.1278
465
+ });
466
+
467
+ /**
468
+ * Location name/description
469
+ */
470
+ export const locationNameParam = z.string().optional().describe('Location name or description');
471
+ parameterRegistry.set(locationNameParam, {
472
+ example: 'London, UK'
473
+ });
474
+ ```
475
+
476
+ #### Boolean & Option Parameters
477
+
478
+ ```typescript
479
+ /**
480
+ * Wait for message ID to be returned
481
+ */
482
+ export const waitForIdParam = z.boolean().optional().default(false).describe('Wait for message ID');
483
+ parameterRegistry.set(waitForIdParam, {
484
+ example: true
485
+ });
486
+
487
+ /**
488
+ * Include own messages
489
+ */
490
+ export const includeMeParam = z.boolean().optional().default(true).describe('Include own messages');
491
+ parameterRegistry.set(includeMeParam, {
492
+ example: true
493
+ });
494
+
495
+ /**
496
+ * Include notifications
497
+ */
498
+ export const includeNotificationsParam = z.boolean().optional().default(false).describe('Include notification messages');
499
+ parameterRegistry.set(includeNotificationsParam, {
500
+ example: false
501
+ });
502
+
503
+ /**
504
+ * Only local deletion (don't delete for everyone)
505
+ */
506
+ export const onlyLocalParam = z.boolean().optional().default(false).describe('Delete only locally');
507
+ parameterRegistry.set(onlyLocalParam, {
508
+ example: false
509
+ });
510
+
511
+ /**
512
+ * Skip own messages when forwarding
513
+ */
514
+ export const skipMyMessagesParam = z.boolean().optional().default(false).describe('Skip own messages');
515
+ parameterRegistry.set(skipMyMessagesParam, {
516
+ example: false
517
+ });
518
+
519
+ /**
520
+ * Only get chats with new messages
521
+ */
522
+ export const withNewMessagesOnlyParam = z.boolean().optional().default(false).describe('Only chats with unread messages');
523
+ parameterRegistry.set(withNewMessagesOnlyParam, {
524
+ example: false
525
+ });
526
+ ```
527
+
528
+ #### Array Parameters
529
+
530
+ ```typescript
531
+ /**
532
+ * Array of message IDs
533
+ */
534
+ export const messageIdsParam = z.union([
535
+ z.array(messageIdParam),
536
+ messageIdParam
537
+ ]).describe('Message ID(s) to process');
538
+ parameterRegistry.set(messageIdsParam, {
539
+ example: ['false_447123456789@c.us_ABC123', 'false_447123456789@c.us_DEF456']
540
+ });
541
+
542
+ /**
543
+ * Mentioned user IDs
544
+ */
545
+ export const mentionedJidListParam = z.array(contactIdParam).optional().describe('List of mentioned contact IDs');
546
+ parameterRegistry.set(mentionedJidListParam, {
547
+ example: ['447123456789@c.us', '441234567890@c.us']
548
+ });
549
+ ```
550
+
551
+ #### Generic Options Parameter
552
+
553
+ ```typescript
554
+ /**
555
+ * Generic message options (for flexibility)
556
+ */
557
+ export const messageOptionsParam = z.any().optional().describe('Additional message options');
558
+ parameterRegistry.set(messageOptionsParam, {
559
+ example: { quotedMsg: 'messageId', mentionedJidList: ['447123456789@c.us'] }
560
+ });
561
+ ```
562
+
563
+ ---
564
+
565
+ ## Part 3: Update `methods.ts`
566
+
567
+ ### 3.1 Before (Current)
568
+
569
+ ```typescript
570
+ const imgDataSchema = z.string().describe('Base64 data or URL');
571
+ parameterRegistry.set(imgDataSchema, { example: 'data:image/png;base64,iVBORw0KGgo...' });
572
+
573
+ export const sendImageV2 = defineMethodV2('sendImage', {
574
+ meta: { /* ... */ },
575
+ input: z.object({
576
+ to: z.string().describe('The chat id to send to'),
577
+ imgData: imgDataSchema,
578
+ filename: z.string().optional().describe('Filename for the image'),
579
+ caption: z.string().optional().describe('Caption for the image'),
580
+ id: z.string().optional().describe('Quoted message ID'),
581
+ waitForId: z.boolean().optional().default(false)
582
+ }),
583
+ parameterOrder: ['to', 'imgData', 'filename', 'caption', 'id', 'waitForId'],
584
+ output: MessageIdReturnSchema.or(z.boolean()).or(z.string())
585
+ });
586
+ ```
587
+
588
+ ### 3.2 After (Using Parameters)
589
+
590
+ ```typescript
591
+ import {
592
+ toParam,
593
+ imageDataParam,
594
+ filenameParam,
595
+ captionParam,
596
+ messageIdParam,
597
+ waitForIdParam
598
+ } from './parameters';
599
+
600
+ export const sendImageV2 = defineMethodV2('sendImage', {
601
+ meta: {
602
+ description: 'Sends an image to a chat',
603
+ action: 'send',
604
+ namespace: 'messages',
605
+ license: 'none',
606
+ functionality: 'both',
607
+ httpMethod: 'POST',
608
+ },
609
+ input: z.object({
610
+ to: toParam,
611
+ imgData: imageDataParam,
612
+ filename: filenameParam,
613
+ caption: captionParam,
614
+ id: messageIdParam.optional(),
615
+ waitForId: waitForIdParam
616
+ }),
617
+ parameterOrder: ['to', 'imgData', 'filename', 'caption', 'id', 'waitForId'],
618
+ output: MessageIdReturnSchema.or(z.boolean()).or(z.string())
619
+ });
620
+ ```
621
+
622
+ **Benefits**:
623
+ - ✅ No need to redefine schemas
624
+ - ✅ Consistent parameter definitions across methods
625
+ - ✅ Automatic transformations (phone number → chat ID, file path → DataURL)
626
+ - ✅ Centralized metadata and examples
627
+ - ✅ Easier to maintain and update
628
+
629
+ ---
630
+
631
+ ## Part 4: Additional Codec Suggestions
632
+
633
+ ### 4.1 Timestamp Codecs
634
+
635
+ ```typescript
636
+ // ISO datetime string to Date
637
+ export const isoDatetimeToDate = z.codec(z.iso.datetime(), z.date(), {
638
+ decode: (isoString) => new Date(isoString),
639
+ encode: (date) => date.toISOString(),
640
+ });
641
+
642
+ // Unix timestamp (seconds) to Date
643
+ export const unixSecondsToDate = z.codec(z.int().min(0), z.date(), {
644
+ decode: (seconds) => new Date(seconds * 1000),
645
+ encode: (date) => Math.floor(date.getTime() / 1000),
646
+ });
647
+
648
+ // Unix timestamp (milliseconds) to Date
649
+ export const unixMillisToDate = z.codec(z.int().min(0), z.date(), {
650
+ decode: (millis) => new Date(millis),
651
+ encode: (date) => date.getTime(),
652
+ });
653
+ ```
654
+
655
+ ### 4.2 Color Codec (for stories, etc.)
656
+
657
+ ```typescript
658
+ // Hex color with/without # to normalized hex
659
+ export const hexColorCodec = z.codec(
660
+ z.string().regex(/^#?([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/),
661
+ z.string(),
662
+ {
663
+ decode: (input) => {
664
+ // Remove # if present, ensure uppercase
665
+ return input.replace('#', '').toUpperCase();
666
+ },
667
+ encode: (hex) => hex
668
+ }
669
+ );
670
+ ```
671
+
672
+ ### 4.3 JSON String Codec
673
+
674
+ ```typescript
675
+ // JSON string to parsed object
676
+ export const jsonStringCodec = <T extends z.ZodType>(schema: T) =>
677
+ z.codec(z.string(), schema, {
678
+ decode: (jsonString, ctx) => {
679
+ try {
680
+ return JSON.parse(jsonString);
681
+ } catch (err: any) {
682
+ ctx.issues.push({
683
+ code: 'invalid_format',
684
+ format: 'json',
685
+ input: jsonString,
686
+ message: err.message,
687
+ });
688
+ return z.NEVER;
689
+ }
690
+ },
691
+ encode: (value) => JSON.stringify(value),
692
+ });
693
+ ```
694
+
695
+ ---
696
+
697
+ ## Part 5: Implementation Checklist
698
+
699
+ ### Phase 1: Core Codecs
700
+ - [ ] Create `src/codecs.ts`
701
+ - [ ] Implement `chatIdCodec` with digit counting logic
702
+ - [ ] Implement `contactIdCodec`
703
+ - [ ] Implement `groupIdCodec`
704
+ - [ ] Implement `messageIdCodec`
705
+ - [ ] Implement file codec factory (`createFileCodec`)
706
+ - [ ] Export pre-built file codecs
707
+ - [ ] Add unit tests for each codec
708
+
709
+ ### Phase 2: Parameters Library
710
+ - [ ] Create `src/parameters.ts`
711
+ - [ ] Define chat/contact parameters using codecs
712
+ - [ ] Define content parameters
713
+ - [ ] Define file parameters (image, audio, video, document, sticker)
714
+ - [ ] Define location parameters
715
+ - [ ] Define boolean/option parameters
716
+ - [ ] Define array parameters
717
+ - [ ] Register all parameters with `parameterRegistry`
718
+
719
+ ### Phase 3: Additional Codecs
720
+ - [ ] Implement timestamp codecs (ISO, Unix seconds, Unix millis)
721
+ - [ ] Implement color codec for hex colors
722
+ - [ ] Implement JSON string codec
723
+ - [ ] Implement base64 ↔ DataURL codec
724
+ - [ ] Implement URL → DataURL codec
725
+
726
+ ### Phase 4: Update Methods
727
+ - [ ] Update `sendTextV2` to use parameters
728
+ - [ ] Update `sendImageV2` to use parameters
729
+ - [ ] Update all other V2 methods to use parameters
730
+ - [ ] Remove inline parameter definitions
731
+
732
+ ### Phase 5: Documentation & Testing
733
+ - [ ] Add JSDoc comments to all codecs
734
+ - [ ] Add JSDoc comments to all parameters
735
+ - [ ] Create usage examples in comments
736
+ - [ ] Write comprehensive unit tests
737
+ - [ ] Update package exports in `index.ts`
738
+ - [ ] Create migration guide for existing code
739
+
740
+ ---
741
+
742
+ ## Part 6: Usage Examples
743
+
744
+ ### Example 1: Using Chat ID Codec Directly
745
+
746
+ ```typescript
747
+ import { chatIdCodec } from '@open-wa/schema';
748
+
749
+ // Decode: flexible input → formatted output
750
+ const chatId1 = chatIdCodec.decode("447123456789");
751
+ // => "447123456789@c.us"
752
+
753
+ const chatId2 = chatIdCodec.decode("447123456789-1445627445");
754
+ // => "447123456789-1445627445@g.us" (18 digits)
755
+
756
+ const chatId3 = chatIdCodec.decode("12345678901234");
757
+ // => "12345678901234@lid" (14 digits, non-Indonesian)
758
+
759
+ // Already formatted? No problem
760
+ const chatId4 = chatIdCodec.decode("447123456789@c.us");
761
+ // => "447123456789@c.us"
762
+ ```
763
+
764
+ ### Example 2: Using File Codec
765
+
766
+ ```typescript
767
+ import { fileToDataUrlCodec } from '@open-wa/schema';
768
+
769
+ // All of these work!
770
+ const dataUrl1 = await fileToDataUrlCodec.decode("./image.png");
771
+ const dataUrl2 = await fileToDataUrlCodec.decode("https://example.com/image.png");
772
+ const dataUrl3 = await fileToDataUrlCodec.decode("data:image/png;base64,...");
773
+ const dataUrl4 = await fileToDataUrlCodec.decode(Buffer.from(...));
774
+
775
+ // All return: "data:image/png;base64,..."
776
+ ```
777
+
778
+ ### Example 3: Using Parameters in Method Definitions
779
+
780
+ ```typescript
781
+ import { defineMethodV2 } from './registry';
782
+ import { toParam, contentParam, messageOptionsParam } from './parameters';
783
+
784
+ export const sendTextV2 = defineMethodV2('sendText', {
785
+ meta: {
786
+ description: 'Sends a text message',
787
+ action: 'send',
788
+ namespace: 'messages',
789
+ license: 'none',
790
+ functionality: 'both',
791
+ httpMethod: 'POST',
792
+ },
793
+ input: z.object({
794
+ to: toParam, // Automatically converts phone numbers
795
+ content: contentParam, // Pre-configured with validation
796
+ options: messageOptionsParam
797
+ }),
798
+ parameterOrder: ['to', 'content', 'options'],
799
+ output: MessageIdReturnSchema
800
+ });
801
+ ```
802
+
803
+ ### Example 4: Client Usage (End User)
804
+
805
+ ```typescript
806
+ import { Client } from '@open-wa/wa-automate';
807
+
808
+ const client = new Client();
809
+
810
+ // User can pass just a phone number - codec handles the rest!
811
+ await client.sendText("447123456789", "Hello!");
812
+ // Internally converted to: "447123456789@c.us"
813
+
814
+ // Or use the full format
815
+ await client.sendText("447123456789@c.us", "Hello!");
816
+
817
+ // Send image with flexible file input
818
+ await client.sendImage("447123456789", "./photo.jpg", "photo.jpg", "Check this out!");
819
+ // File path automatically converted to DataURL
820
+ ```
821
+
822
+ ---
823
+
824
+ ## Part 7: Benefits Summary
825
+
826
+ ### For Developers
827
+ - ✅ **Reusable**: Define once, use everywhere
828
+ - ✅ **Type-safe**: Full TypeScript support
829
+ - ✅ **Validated**: Automatic validation on decode
830
+ - ✅ **Documented**: Centralized examples and descriptions
831
+ - ✅ **Maintainable**: Update in one place, affects all methods
832
+
833
+ ### For End Users
834
+ - ✅ **Flexible**: Accept multiple input formats
835
+ - ✅ **Intuitive**: Just pass a phone number, not `447123456789@c.us`
836
+ - ✅ **Forgiving**: File paths, URLs, DataURLs all work
837
+ - ✅ **Validated**: Clear error messages when input is invalid
838
+
839
+ ### For API Design
840
+ - ✅ **Consistent**: Same parameters across all methods
841
+ - ✅ **Smart**: Automatic transformations reduce boilerplate
842
+ - ✅ **Extensible**: Easy to add new codecs and parameters
843
+ - ✅ **Backward Compatible**: Existing code still works
844
+
845
+ ---
846
+
847
+ ## Part 8: Testing Strategy
848
+
849
+ ### Unit Tests for Codecs
850
+
851
+ ```typescript
852
+ describe('chatIdCodec', () => {
853
+ it('should convert phone number to contact ID', () => {
854
+ expect(chatIdCodec.decode('447123456789')).toBe('447123456789@c.us');
855
+ });
856
+
857
+ it('should convert 18-digit number to group ID', () => {
858
+ expect(chatIdCodec.decode('123456789012345678')).toBe('123456789012345678@g.us');
859
+ });
860
+
861
+ it('should convert 14-digit non-Indonesian to LID', () => {
862
+ expect(chatIdCodec.decode('12345678901234')).toBe('12345678901234@lid');
863
+ });
864
+
865
+ it('should convert 14-digit Indonesian to contact ID', () => {
866
+ expect(chatIdCodec.decode('62812345678901')).toBe('62812345678901@c.us');
867
+ });
868
+
869
+ it('should pass through already formatted IDs', () => {
870
+ expect(chatIdCodec.decode('447123456789@c.us')).toBe('447123456789@c.us');
871
+ expect(chatIdCodec.decode('123@g.us')).toBe('123@g.us');
872
+ expect(chatIdCodec.decode('123@lid')).toBe('123@lid');
873
+ });
874
+ });
875
+ ```
876
+
877
+ ### Integration Tests
878
+
879
+ ```typescript
880
+ describe('sendImageV2 with file codec', () => {
881
+ it('should accept file path', async () => {
882
+ const result = await sendImageV2.parse([{
883
+ to: '447123456789',
884
+ imgData: './test.png',
885
+ filename: 'test.png'
886
+ }]);
887
+ expect(result.to).toBe('447123456789@c.us');
888
+ expect(result.imgData).toMatch(/^data:image\/png;base64,/);
889
+ });
890
+
891
+ it('should accept URL', async () => {
892
+ const result = await sendImageV2.parse([{
893
+ to: '447123456789',
894
+ imgData: 'https://example.com/image.png',
895
+ filename: 'image.png'
896
+ }]);
897
+ expect(result.imgData).toMatch(/^data:image\/png;base64,/);
898
+ });
899
+ });
900
+ ```
901
+
902
+ ---
903
+
904
+ ## Part 9: Migration Path
905
+
906
+ ### For Existing Code
907
+
908
+ 1. **No Breaking Changes**: Existing methods continue to work
909
+ 2. **Gradual Adoption**: Migrate methods one at a time to use parameters
910
+ 3. **Backward Compatible**: Old parameter definitions still valid
911
+
912
+ ### Migration Example
913
+
914
+ **Before**:
915
+ ```typescript
916
+ client.sendText("447123456789@c.us", "Hello");
917
+ ```
918
+
919
+ **After** (still works!):
920
+ ```typescript
921
+ client.sendText("447123456789", "Hello"); // Codec handles conversion
922
+ client.sendText("447123456789@c.us", "Hello"); // Still works
923
+ ```
924
+
925
+ ---
926
+
927
+ ## Conclusion
928
+
929
+ This implementation will provide:
930
+ - **Smart parameter handling** with automatic transformations
931
+ - **Reusable, well-documented parameters** for consistency
932
+ - **Flexible input formats** for better developer experience
933
+ - **Type-safe, validated** inputs with clear error messages
934
+ - **Backward compatibility** with existing code
935
+
936
+ The codec system leverages Zod 4.1's bi-directional transformation capabilities to create an intelligent, user-friendly API that "just works" while maintaining type safety and validation.