waba-devtools 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -290,7 +290,7 @@ Typical flow: edit or `retrieve` the files → commit to git → `deploy` them s
290
290
  | [`check`](#check) | Tests the access to every WABA. Changes nothing. |
291
291
  | [`list`](#list) | Lists the templates of WABAs. Changes nothing, writes no files. |
292
292
  | [`compare`](#compare) | Compares two backups: added, removed and changed templates. |
293
- | [`backup`](#backup) | Saves a restore point of WABAs now, without deploying. |
293
+ | [`backup`](#backup) | Saves a manual backup of WABAs now, without deploying. |
294
294
  | [`retrieve`](#retrieve) | Downloads the templates of one WABA into files. |
295
295
  | [`import`](#import) | Turns a CSV file (Google Sheets) into template files. |
296
296
  | [`deploy`](#deploy) | Sends templates to WABAs (every WABA of a stage, or picked ones). |
@@ -393,7 +393,7 @@ waba list --from dev --json # for scripts
393
393
 
394
394
  ### `compare`
395
395
 
396
- Compares two backup sets (restore points) and lists which templates were **added**, **removed** and
396
+ Compares two backup sets and lists which templates were **added**, **removed** and
397
397
  **changed** — and for changed ones, which fields changed, with the value before and after. The older
398
398
  set is always "before", whatever order you give them in, so a deleted template never shows as added.
399
399
  Line-ending differences do not count. Two sets of different WABAs can be compared too (e.g. qa vs
@@ -440,7 +440,7 @@ waba compare backups/444…_2026-11-20T18-26-04-123Z_before backups/444…_2026-
440
440
 
441
441
  ### `backup`
442
442
 
443
- Saves a restore point **now**, without deploying anything: one backup set per WABA, named
443
+ Saves a manual backup **now**, without deploying anything: one backup set per WABA, named
444
444
  `<wabaId>_<time>_manual` (see [Backups](#backups)).
445
445
 
446
446
  ```bash
@@ -507,7 +507,11 @@ Good to know:
507
507
 
508
508
  - For a template file that already exists, only the parts the sheet has columns for are
509
509
  replaced (see [CSV columns](#csv-columns)); the category stays.
510
- - Rows with errors are listed with their row number. All other rows are still imported.
510
+ - Rows with errors are listed with their row number and left out; all other rows are still
511
+ imported. `deploy --csv --dry-run` shows the same list before anything is sent. With
512
+ `deploy --csv --stop-on-error` (library: `stopOnRowErrors: true`), one row with an error stops the
513
+ whole deploy: every target reports why, nothing is sent, and the report has
514
+ `stoppedByRowErrors: true`.
511
515
  - The file is cleaned up the same way sfmc-dataloader does it: empty rows are skipped, and empty
512
516
  columns on the right (no header, no values) are removed. A value in such a column is an error.
513
517
  The report says what was removed.
@@ -517,20 +521,20 @@ Good to know:
517
521
  Export from Google Sheets with **File → Download → Comma-separated values (.csv)**. Header names
518
522
  are not case-sensitive. Other columns (e.g. `Brand`) are ignored.
519
523
 
520
- | Column | Required | Content | Example |
521
- | ------------------------------- | --------------------------- | ---------------------------------------------------------- | -------------------------------- |
522
- | `Template name` | yes | Letters, digits, `_` | `order_shipped` |
523
- | `Category` | yes | `Utility` or `Marketing` (used when a template is created) | `Utility` |
524
- | `Language` | yes | Meta language code | `en_US`, `fr`, `it` |
525
- | `Body` (or `Meta Template`) | yes | Message text, variables as `{{1}}`, `{{2}}`, … | `Hi {{1}}, order {{2}} shipped.` |
526
- | `Body examples` (or `Examples`) | when the body has variables | One example per variable, separated by `\|` | `Jane\|A-1234` |
527
- | `Header` | no | Text header, at most one variable `{{1}}` | `Your order {{1}}` |
528
- | `Header example` | when the header has `{{1}}` | Example for the header variable | `A-1234` |
529
- | `Footer` | no | Short text, no variables | `Reply STOP to opt out` |
530
- | `Quick replies` | no | Button labels, separated by `\|` | `Yes\|No\|Later` |
531
- | `URL button` | no | `label\|URL`; the URL may end in `{{1}}` | `Track\|https://ex.com/t/{{1}}` |
532
- | `URL example` | when the URL has `{{1}}` | Example for the URL variable | `A-1234` |
533
- | `Call button` | no | `label\|phone number` with country code | `Call us\|+15550100` |
524
+ | Column | Required | Content | Example |
525
+ | ------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------- | -------------------------------- |
526
+ | `Template name` | yes | Letters, digits, `_` | `order_shipped` |
527
+ | `Category` | yes | `Utility` or `Marketing` (used when a template is created) | `Utility` |
528
+ | `Language` | yes | Meta language code | `en_US`, `fr`, `it` |
529
+ | `Body` (or `Meta Template`) | yes | Message text, variables as `{{1}}`, `{{2}}`, … or named | `Hi {{1}}, order {{2}} shipped.` |
530
+ | `Body examples` (or `Examples`) | yes; filled when the body has variables | One example per variable, separated by `\|` | `Jane\|A-1234` |
531
+ | `Header` | no | Text header, at most one variable (`{{1}}` or named) | `Your order {{1}}` |
532
+ | `Header example` | with `Header`; filled when the header has a variable | Example for the header variable | `A-1234` |
533
+ | `Footer` | no | Short text, no variables | `Reply STOP to opt out` |
534
+ | `Quick replies` | no | Button labels, separated by `\|` | `Yes\|No\|Later` |
535
+ | `URL button` | no | `label\|URL`; the URL may end in `{{1}}` | `Track\|https://ex.com/t/{{1}}` |
536
+ | `URL example` | with `URL button`; filled when the URL has `{{1}}` | Example for the URL variable | `A-1234` |
537
+ | `Call button` | no | `label\|phone number` with country code | `Call us\|+15550100` |
534
538
 
535
539
  - **Columns decide what is replaced** — for the whole sheet, by its header row. The sheet sets the
536
540
  body, plus the header, the footer and each kind of button **if it has that column**. Anything
@@ -540,8 +544,44 @@ are not case-sensitive. Other columns (e.g. `Brand`) are ignored.
540
544
  (`import`) and in WABAs (`deploy --csv`) alike.
541
545
  - Every cell is trimmed, and line breaks inside a cell are stored as plain `\n` (no Windows `\r\n`),
542
546
  so a re-import of the same sheet does not count as a change.
543
- - Not possible in a sheet: image, video or document headers, named variables, authentication and
544
- carousel templates.
547
+ - Not possible in a sheet: image, video or document headers, authentication and carousel templates.
548
+
549
+ #### Examples are checked
550
+
551
+ Meta accepts a template without examples, but WhatsApp Manager then refuses to edit it until examples
552
+ are added. So the example columns are required (`Body examples` always, `Header example` when the
553
+ sheet has `Header`, `URL example` when it has `URL button`), and every row is checked before anything
554
+ is sent:
555
+
556
+ - **Error, the row is left out:** a variable of the body, the header or the URL without an example.
557
+ One message per row names every missing one, e.g.
558
+ `row 7: Body examples: no example for {{2}}, {{3}} (one per variable in the order {{1}}, {{2}}, …)`.
559
+ - **Warning, the row is used:** examples no variable needs — more numbered examples than variables,
560
+ an unknown name (`{{city}} is not in the text`), a name given twice (the first one is used), a part
561
+ that is not `name=value`, or an example for a header or URL without a variable.
562
+
563
+ #### Named variables
564
+
565
+ A row may use **named** variables instead of numbers — Meta calls this the "Name" variable type. The
566
+ format is decided per row from its body and header:
567
+
568
+ | Variables in body and header | Result |
569
+ | ---------------------------------------------------------------------------- | --------------------------------- |
570
+ | none, or all numbered (`{{1}}`, `{{2}}`) | numbered (as before) |
571
+ | all named: lower-case letters, digits and `_`, starting with a letter | named (`parameter_format: NAMED`) |
572
+ | mixed, or a name with capitals, spaces or a leading digit (`{{First Name}}`) | row error |
573
+
574
+ With named variables, write the examples as `name=value`, separated by `|`, in any order — every
575
+ variable exactly once:
576
+
577
+ | Column | Example |
578
+ | ---------------- | ------------------------------------------------ |
579
+ | `Body` | `Hi {{first_name}}, order {{order_id}} shipped.` |
580
+ | `Body examples` | `order_id=A-1234\|first_name=Jane` |
581
+ | `Header` | `Order {{order_id}}` |
582
+ | `Header example` | `order_id=A-1234` |
583
+
584
+ The URL button keeps `{{1}}` in both formats.
545
585
 
546
586
  ### `deploy`
547
587
 
@@ -563,21 +603,24 @@ Where the templates come from:
563
603
  | Another WABA | `waba deploy --from dev --to qa` | No — live clone from WABA to WABA, files are not touched |
564
604
  | A CSV file | `waba deploy --csv sheet.csv --to qa` | No — reads the CSV, files are not touched |
565
605
 
566
- | Option | Meaning | Example |
567
- | ----------------------- | ------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
568
- | `--to <stage>` | Target: every WABA of this stage. | `--to qa` |
569
- | `--to-waba <id>` | Target: only this WABA. Repeat for more. No `--to` needed; with `--to` it must be in that stage. | `--to-waba 444444444444444` |
570
- | `--from <stage>` | Source: the WABA of this stage (instead of the files). | `--from dev` |
571
- | `--from-waba <id>` | Source: this WABA. No `--from` needed; required when the `--from` stage has several. | `--from-waba 333333333333333` |
572
- | `--csv <file>` | Take the templates from a CSV file (see [CSV columns](#csv-columns)). | `--csv sheet.csv` |
573
- | `-m, --template <name>` | Only this template (all its languages). Repeat for more. | `-m order_shipped` |
574
- | `--dry-run` | Only show what would happen, with each template's status at Meta. Sends nothing. | `--dry-run` |
575
- | `--prune` | Also delete templates that exist only in the target (only with `--yes`; preview with `--dry-run`). | `--prune` |
576
- | `--yes` | With `--prune`: really delete. | `--prune --yes` |
577
- | `--expect <file>` | Send only what a previous `--dry-run` showed (see [Confirmed preview](#confirmed-preview)). | `--expect preview.json` |
578
- | `--backup <folder>` | Before changing a WABA, save all its templates as a backup set in `<folder>` (see [Backups](#backups)). | `--backup backups` |
579
- | `--backup-after` | With `--backup`: also save each changed WABA after the changes (`…_after`). | `--backup backups --backup-after` |
580
- | `--from-dir <folder>` | Source: template files in this folder instead of `templates/` — e.g. a backup set. | `--from-dir backups/444…_2026-11-20T18-26-04-123Z` |
606
+ | Option | Meaning | Example |
607
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------- |
608
+ | `--to <stage>` | Target: every WABA of this stage. | `--to qa` |
609
+ | `--to-waba <id>` | Target: only this WABA. Repeat for more. No `--to` needed; with `--to` it must be in that stage. | `--to-waba 444444444444444` |
610
+ | `--from <stage>` | Source: the WABA of this stage (instead of the files). | `--from dev` |
611
+ | `--from-waba <id>` | Source: this WABA. No `--from` needed; required when the `--from` stage has several. | `--from-waba 333333333333333` |
612
+ | `--csv <file>` | Take the templates from a CSV file (see [CSV columns](#csv-columns)). | `--csv sheet.csv` |
613
+ | `--stop-on-error` | With `--csv`: when any row has an error, send nothing at all (default: leave those rows out, send the rest). | `--stop-on-error` |
614
+ | `-m, --template <name>` | Only this template (all its languages). Repeat for more. | `-m order_shipped` |
615
+ | `--dry-run` | Only show what would happen, with each template's status at Meta. Sends nothing. | `--dry-run` |
616
+ | `--prune` | Also delete templates that exist only in the target (only with `--yes`; preview with `--dry-run`). | `--prune` |
617
+ | `--yes` | With `--prune`: really delete. | `--prune --yes` |
618
+ | `--expect <file>` | Send only what a previous `--dry-run` showed (see [Confirmed preview](#confirmed-preview)). | `--expect preview.json` |
619
+ | `--backup <folder>` | Before changing a WABA, save all its templates as a backup set in `<folder>` (see [Backups](#backups)). | `--backup backups` |
620
+ | `--backup-after` | With `--backup`: also save each changed WABA after the changes (`…_after`). | `--backup backups --backup-after` |
621
+ | `--from-dir <folder>` | Source: template files in this folder instead of `templates/` — e.g. a backup set. | `--from-dir backups/444…_2026-11-20T18-26-04-123Z` |
622
+ | `--limit-percent <n>` | Share of Meta's limits to use, 1–100 (default 80). See [Hourly limits](#hourly-limits-and-batches). | `--limit-percent 50` |
623
+ | `--wait` | Keep running and send each batch when its time comes (not with `--dry-run` / `--expect`). | `--wait` |
581
624
 
582
625
  ```bash
583
626
  waba deploy --to qa --dry-run # preview
@@ -630,6 +673,49 @@ Good to know:
630
673
  [CSV columns](#csv-columns)).
631
674
  - One failing template does not stop the others. The report shows Meta's error.
632
675
 
676
+ #### Hourly limits and batches
677
+
678
+ Meta allows **100 template creates per WABA per hour** and throttles an app that calls its API too often
679
+ for a WABA. `waba` stays below both, by default at **80 %** (`--limit-percent <n>`, 1–100; a warning is
680
+ printed above 80):
681
+
682
+ - **Template creates:** at most `floor(100 × percent / 100)` creates per target WABA in any hour — 80
683
+ by default. Updates and deletes are not limited by this (they still count as API calls, see below).
684
+ Before writing, `waba` counts the WABA's templates whose `last_updated_time` (from Meta) is within
685
+ the last hour, so templates created by colleagues or other tools count too. Meta's list cannot tell a
686
+ create from an edit, so a template edited in the last hour counts as well — unless the caller logged
687
+ that edit (`recentWrites` with `action: 'update'`, as the desktop app does). The CLI keeps no log:
688
+ right after a big update run, its next run counts those edits and may wait longer than needed.
689
+ - **API usage:** Meta reports its usage in the `X-Business-Use-Case-Usage` header of every answer
690
+ (calls, CPU time, total time, in percent of the hourly allowance). The report shows the highest
691
+ values per WABA, with a warning from 50 %. When any of them reaches the limit percentage, or Meta
692
+ names a time to regain access, `waba` stops writing to that WABA. On Meta's throttle error `80008` it
693
+ stops too.
694
+
695
+ What does not fit is **deferred**: not sent, reported with the time it can go (`deferred until …`),
696
+ plus the batch schedule and the time to run again. The exit code is `1` while anything is deferred.
697
+ `--dry-run` shows the same schedule, so you know before you start:
698
+
699
+ ```text
700
+ qa — WABA 444444444444444:
701
+ hourly budget (80 %): 0 of 80 creates in the last hour, 80 left
702
+ schedule: 3 batches: 80 now, 80 at 15:05, 40 at 16:05
703
+ create welcome_1 (en_US)
704
+ …
705
+ create welcome_81 (en_US) deferred until 2026-11-27T14:05:12.000Z — hourly create limit used up
706
+ Deferred templates: run the same command again after 15:05 …
707
+ ```
708
+
709
+ To continue, run the **same command** again after that time: deploy only sends what is still missing
710
+ or different, so it picks up exactly the deferred templates. Or add `--wait`: `waba` then stays running,
711
+ prints how long it waits, and sends each batch when its time comes until nothing is deferred. Ctrl+C
712
+ is safe (each create is independent; rerun to continue). Mind CI job time limits — a 250-template
713
+ deploy takes about three hours. With `--backup`, every batch writes its own backup set.
714
+
715
+ Not visible to `waba`: a template that was created **and deleted again** within the hour (Meta lists it
716
+ no longer, but it still counts at Meta). Leave room for that with the default 80 %. The desktop app
717
+ keeps its own write log for this and passes it to the library as `recentWrites`.
718
+
633
719
  #### Backups
634
720
 
635
721
  Meta keeps no history of templates: once a template is updated, its old text is gone. With
@@ -673,7 +759,7 @@ waba deploy --from-dir backups/444444444444444_2026-11-20T18-26-04-123Z_before -
673
759
  - Media, authentication and carousel templates are saved, but cannot be restored (`skipped`).
674
760
  - `--backup` does nothing together with `--dry-run`; `--backup-after` needs `--backup`.
675
761
  - If the after-backup fails, the changes stay sent; the report shows a WARNING.
676
- - Restore points without a deployment: [`waba backup`](#backup) (sets named `…_manual`).
762
+ - Manual backups without a deployment: [`waba backup`](#backup) (sets named `…_manual`).
677
763
 
678
764
  #### Confirmed preview
679
765
 
@@ -715,11 +801,11 @@ waba deploy --from qa --to prod --expect preview.json
715
801
  `--json` prints the full report as JSON (for scripts and CI). Each source and target has `stage`
716
802
  (text) and `stages` (list) — a WABA found in several stages lists all of them in `stages`.
717
803
 
718
- | Exit code | Meaning |
719
- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
720
- | `0` | Everything succeeded. |
721
- | `1` | Something failed: a Meta error, a blocked template, a CSV row error, or a target WABA that could not be reached (incl. its token variable not being set). |
722
- | `2` | Wrong usage or configuration (unknown stage, missing option, invalid config, missing token for the source WABA, …). |
804
+ | Exit code | Meaning |
805
+ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
806
+ | `0` | Everything succeeded. |
807
+ | `1` | Something failed: a Meta error, a blocked template, a deferred template (hourly limit), a CSV row error, or a target WABA that could not be reached (incl. its token variable not being set). |
808
+ | `2` | Wrong usage or configuration (unknown stage, missing option, invalid config, missing token for the source WABA, …). |
723
809
 
724
810
  When a command stops with an error, `--json` prints `{ "command", "ok": false, "error" }`, plus a
725
811
  stable `code` where one exists, so scripts need not match the text: `TOKEN_INVALID`,
@@ -730,13 +816,40 @@ stable `code` where one exists, so scripts need not match the text: `TOKEN_INVAL
730
816
 
731
817
  - Every WABA reviews its templates on its own: the same template can be approved in one WABA and
732
818
  rejected or re-categorized in another.
733
- - Meta limits how many templates can be created per WABA per hour, and how often approved
734
- templates can be edited. Deploying only what changed keeps you well below these limits.
819
+ - Meta limits how many templates can be created per WABA per hour (100), and how often approved
820
+ templates can be edited. `deploy` only sends what changed and stays below the hourly limits (see
821
+ [Hourly limits and batches](#hourly-limits-and-batches)).
735
822
  - A template that is still in review (`PENDING`) cannot be edited — Meta refuses it, so `waba`
736
823
  shows it as `blocked` without sending.
737
824
  - Meta adds sample templates to new WABAs (`hello_world`, `jaspers_market_*`) and never lets you edit
738
825
  or delete them. `waba` shows a change to them as `skipped` and keeps them with `--prune`.
739
826
 
827
+ ## Using it as a library
828
+
829
+ The desktop app uses `waba-devtools` as a library (`import { deploy, … } from 'waba-devtools'`). Besides
830
+ the commands, 0.2.0 adds:
831
+
832
+ - `deploy({ …, limitPercent, recentWrites })` — `limitPercent` as `--limit-percent`; `recentWrites`
833
+ is the caller's own write log, `[{ wabaId, name, language, at, action? }]` (`action`: `'create'`,
834
+ the default, or `'update'`). Logged creates count when younger than an hour and not already
835
+ counted from Meta's list; a logged update keeps that template's recent `last_updated_time` from
836
+ counting. Each target in the report has
837
+ `budget: { limitPercent, limit, usedLastHour, left, countedAt, schedule }` (`countedAt`: the counted
838
+ writes, oldest first; `schedule`: `[{ at, count }]`), `usage: { callCount, totalCputime, totalTime,
839
+ regainAccessMinutes }` when Meta sent the header, and `throttled: { retryAfter, error }` when writing
840
+ stopped. Deferred actions have `result: 'deferred'`, `deferredReason` (`budget` or `throttled`) and
841
+ `retryAfter`; sent ones have `at`.
842
+ - `planBatches({ wanted, limit, countedAt, now })` → `[{ at, count }]` — the batch schedule. Slots
843
+ that free up less than a minute apart are one batch, sent when the last one it needs is free.
844
+ - `writeBudget({ limit, live, recentWrites, now })` → `{ limit, usedLastHour, left, times }` — the
845
+ creates of one WABA in the last hour, counted like `deploy` does, from its live templates (listed
846
+ with `last_updated_time`) and the caller's write log. For a usage overview without deploying.
847
+ - `writesPerHour(limitPercent)`, `META_CREATES_PER_HOUR`, `DEFAULT_LIMIT_PERCENT`.
848
+ - `templatesToCsv(templates)` → `{ csv, skipped: [{ name, language, reason }] }` — writes templates in
849
+ the [CSV columns](#csv-columns), so a sheet can be edited and imported again. Every row reads back as
850
+ the same template; what the columns cannot hold (media headers, carousels, authentication, other
851
+ button types, …) is listed in `skipped`.
852
+
740
853
  ## Not supported yet
741
854
 
742
855
  - Templates with an image, video or document header.
package/lib/budget.js ADDED
@@ -0,0 +1,275 @@
1
+ import { UsageError } from './errors.js';
2
+ import { templateKey } from './normalize.js';
3
+
4
+ /**
5
+ * Meta lets a WABA create at most 100 templates per hour.
6
+ */
7
+ export const META_CREATES_PER_HOUR = 100;
8
+
9
+ /**
10
+ * Share (percent) of Meta's limits `deploy` uses by default: of the template creates per hour and of
11
+ * the API allowance in `X-Business-Use-Case-Usage`. 80 stays 20 % below Meta's limits.
12
+ */
13
+ export const DEFAULT_LIMIT_PERCENT = 80;
14
+
15
+ /**
16
+ * Graph error code when Meta throttles the app for a WABA (business use case rate limit).
17
+ */
18
+ export const THROTTLED_CODE = 80_008;
19
+
20
+ /**
21
+ * Wait after error 80008 when Meta gives no estimate: its rate-limit window is one hour.
22
+ */
23
+ export const DEFAULT_THROTTLE_MINUTES = 60;
24
+
25
+ /**
26
+ * Reports warn about Meta's API usage from this percentage on (or from the limit, when lower).
27
+ */
28
+ export const USAGE_WARN_PERCENT = 50;
29
+
30
+ const HOUR = 3_600_000;
31
+
32
+ // Writes sent in one go free their slots one right after the other: slots less than a minute apart
33
+ // (the schedule shows minutes) are one batch, sent when the last of them is free.
34
+ const SAME_BATCH_GAP = 60_000;
35
+
36
+ /**
37
+ * Template creates per WABA and hour for a limit percentage: `floor(100 × percent / 100)`.
38
+ *
39
+ * @param {number} limitPercent - 1 to 100.
40
+ * @returns {number}
41
+ */
42
+ export function writesPerHour(limitPercent) {
43
+ return Math.floor((META_CREATES_PER_HOUR * validateLimitPercent(limitPercent)) / 100);
44
+ }
45
+
46
+ /**
47
+ * Why writing to a WABA must stop, from the highest usage Meta reported, or `undefined`: any
48
+ * percentage at or above the limit, or a time to regain access.
49
+ *
50
+ * @param {import('./graph.js').UsageInfo|undefined} usage
51
+ * @param {number} [limitPercent]
52
+ * @returns {string|undefined}
53
+ */
54
+ export function usageStopReason(usage, limitPercent = DEFAULT_LIMIT_PERCENT) {
55
+ if (!usage) {
56
+ return;
57
+ }
58
+ if (usage.regainAccessMinutes > 0) {
59
+ return `Meta throttles this WABA for about ${usage.regainAccessMinutes} min (X-Business-Use-Case-Usage)`;
60
+ }
61
+ const peak = Math.max(usage.callCount, usage.totalCputime, usage.totalTime);
62
+ return peak >= limitPercent
63
+ ? `Meta reports ${peak} % of the hourly API allowance used (stop at ${limitPercent} %)`
64
+ : undefined;
65
+ }
66
+
67
+ /**
68
+ * @typedef {object} RecentWrite
69
+ * @property {string} wabaId - WABA the template was created or edited in.
70
+ * @property {string} name
71
+ * @property {string} language
72
+ * @property {'create'|'update'} [action] - Default `create`. Only creates count against Meta's
73
+ * hourly limit; a logged `update` tells the budget that a recent `last_updated_time` was an edit.
74
+ * @property {string|number|Date} at - When it was sent: ISO text, `Date`, or Unix time in seconds
75
+ * or milliseconds.
76
+ */
77
+
78
+ /**
79
+ * @typedef {object} WriteBudget
80
+ * @property {number} limit - Creates allowed per hour.
81
+ * @property {number} usedLastHour - Creates counted in the last hour.
82
+ * @property {number} left - What may still be sent now (never below 0).
83
+ * @property {number[]} times - Time (ms) of every counted write, oldest first.
84
+ */
85
+
86
+ /**
87
+ * Time in milliseconds from Meta's `last_updated_time` (`2026-11-27T12:55:37+0000` or Unix seconds)
88
+ * or a logged write time.
89
+ *
90
+ * @param {unknown} value
91
+ * @returns {number} `NaN` when it is not a time.
92
+ */
93
+ export function parseTime(value) {
94
+ if (value instanceof Date) {
95
+ return value.getTime();
96
+ }
97
+ if (typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) {
98
+ const number = Number(value);
99
+ // Unix seconds until the year 33658; anything larger is milliseconds.
100
+ return number < 1e12 ? number * 1000 : number;
101
+ }
102
+ return typeof value === 'string' ? Date.parse(value) : NaN;
103
+ }
104
+
105
+ /**
106
+ * Checks the `recentWrites` option of `deploy`.
107
+ *
108
+ * @param {unknown} recentWrites
109
+ * @returns {RecentWrite[]}
110
+ */
111
+ export function validateRecentWrites(recentWrites) {
112
+ if (!Array.isArray(recentWrites)) {
113
+ throw new UsageError('recentWrites must be a list of {wabaId, name, language, at}.');
114
+ }
115
+ for (const [index, write] of recentWrites.entries()) {
116
+ const isValid =
117
+ typeof write?.wabaId === 'string' &&
118
+ typeof write.name === 'string' &&
119
+ typeof write.language === 'string' &&
120
+ Number.isFinite(parseTime(write.at)) &&
121
+ [undefined, 'create', 'update'].includes(write.action);
122
+ if (!isValid) {
123
+ throw new UsageError(
124
+ `recentWrites[${index}] needs wabaId, name, language, a valid time "at" and action "create" or "update" (optional).`,
125
+ );
126
+ }
127
+ }
128
+ return recentWrites;
129
+ }
130
+
131
+ /**
132
+ * Checks the `limitPercent` option of `deploy`.
133
+ *
134
+ * @param {unknown} value
135
+ * @returns {number}
136
+ */
137
+ export function validateLimitPercent(value) {
138
+ if (!Number.isSafeInteger(value) || value < 1 || value > 100) {
139
+ throw new UsageError('The limit must be a whole percentage from 1 to 100.');
140
+ }
141
+ return value;
142
+ }
143
+
144
+ /**
145
+ * How many creates a target WABA had in the last hour, and how many are left. Meta's list cannot tell
146
+ * a create from an edit, so every live template whose `last_updated_time` is within the hour counts,
147
+ * unless the caller logged an update of it in that hour (and no create). Logged creates within the
148
+ * hour whose name + language is not in the list count too (e.g. created and deleted again).
149
+ *
150
+ * @param {object} input
151
+ * @param {number} input.limit
152
+ * @param {object[]} input.live - Live templates of the target (with `last_updated_time`).
153
+ * @param {RecentWrite[]} [input.recentWrites] - Logged writes of this target WABA.
154
+ * @param {number} input.now - Milliseconds.
155
+ * @returns {WriteBudget}
156
+ */
157
+ export function writeBudget({ limit, live, recentWrites = [], now }) {
158
+ const isRecent = (time) => Number.isFinite(time) && time > now - HOUR && time <= now;
159
+ const server = live
160
+ .map((template) => ({
161
+ key: templateKey(template),
162
+ time: parseTime(template.last_updated_time),
163
+ }))
164
+ .filter(({ time }) => isRecent(time));
165
+ const writes = recentWrites
166
+ .map((write) => ({
167
+ key: templateKey(write),
168
+ time: parseTime(write.at),
169
+ isCreate: write.action !== 'update',
170
+ }))
171
+ .filter(({ time }) => isRecent(time));
172
+ const createdKeys = new Set(writes.filter(({ isCreate }) => isCreate).map(({ key }) => key));
173
+ const editedKeys = new Set(
174
+ writes
175
+ .filter(({ key, isCreate }) => !isCreate && !createdKeys.has(key))
176
+ .map(({ key }) => key),
177
+ );
178
+ const counted = server.filter(({ key }) => !editedKeys.has(key));
179
+ const serverKeys = new Set(server.map(({ key }) => key));
180
+ const logged = writes.filter(({ key, isCreate }) => isCreate && !serverKeys.has(key));
181
+ const times = [...counted, ...logged].map(({ time }) => time).toSorted((a, b) => a - b);
182
+ return {
183
+ limit,
184
+ usedLastHour: times.length,
185
+ left: Math.max(0, limit - times.length),
186
+ times,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * When the next batch can go: the last of the first slots that free up less than a minute apart, or
192
+ * the one that frees enough.
193
+ *
194
+ * @param {[number, number][]} window - Counted writes as [time, count], oldest first, not empty.
195
+ * @param {number} needed - Slots that must free up for everything still to send.
196
+ * @returns {number} Milliseconds.
197
+ */
198
+ function nextBatchTime(window, needed) {
199
+ let [last, freed] = window[0];
200
+ for (const [at, count] of window.slice(1)) {
201
+ if (freed >= needed || at - last >= SAME_BATCH_GAP) {
202
+ break;
203
+ }
204
+ freed += count;
205
+ last = at;
206
+ }
207
+ return last + HOUR;
208
+ }
209
+
210
+ /**
211
+ * Batch schedule for `wanted` creates under an hourly limit: send what fits now, then each
212
+ * time counted writes are one hour old, send as many as that frees. Slots that free up less than a
213
+ * minute apart are one batch, sent when the last one it needs is free. Pure; feed it a deploy
214
+ * report's `budget.limit` and `budget.countedAt`.
215
+ *
216
+ * @param {object} input
217
+ * @param {number} input.wanted - Writes still to send (whole number, 0 or more).
218
+ * @param {number} input.limit - Writes per hour (whole number, 1 or more).
219
+ * @param {(string|number|Date)[]} [input.countedAt] - Writes already counted in the last hour.
220
+ * @param {number|string|Date} [input.now] - Default: now.
221
+ * @returns {{at: string, count: number}[]} ISO time and number of writes per batch, earliest first.
222
+ */
223
+ export function planBatches({ wanted, limit, countedAt = [], now = Date.now() }) {
224
+ if (!Number.isSafeInteger(wanted) || wanted < 0) {
225
+ throw new UsageError('planBatches: wanted must be a whole number of 0 or more.');
226
+ }
227
+ if (!Number.isSafeInteger(limit) || limit < 1) {
228
+ throw new UsageError('planBatches: limit must be a whole number of 1 or more.');
229
+ }
230
+ let time = parseTime(now);
231
+ if (!Number.isFinite(time)) {
232
+ throw new UsageError('planBatches: now is not a valid time.');
233
+ }
234
+ // Counted writes as [time, count], oldest first.
235
+ let window = countedAt
236
+ .map((value) => parseTime(value))
237
+ .filter((value) => Number.isFinite(value) && value > time - HOUR)
238
+ .toSorted((a, b) => a - b)
239
+ .map((value) => [value, 1]);
240
+ const batches = [];
241
+ let remaining = wanted;
242
+ while (remaining > 0) {
243
+ window = window.filter(([at]) => at + HOUR > time);
244
+ const used = window.reduce((sum, [, count]) => sum + count, 0);
245
+ const count = Math.min(limit - used, remaining);
246
+ if (count > 0) {
247
+ batches.push({ at: new Date(time).toISOString(), count });
248
+ window.push([time, count]);
249
+ remaining -= count;
250
+ }
251
+ // never empty here: either this batch is in it or the limit is used up
252
+ const free = limit - used - Math.max(0, count);
253
+ time = nextBatchTime(window, remaining - free);
254
+ }
255
+ return batches;
256
+ }
257
+
258
+ /**
259
+ * Time of the batch that sends write number `index` (0-based) of a `planBatches` schedule; the last
260
+ * batch's time when the index is beyond the schedule.
261
+ *
262
+ * @param {{at: string, count: number}[]} schedule
263
+ * @param {number} index
264
+ * @returns {string|undefined} ISO time, or `undefined` for an empty schedule.
265
+ */
266
+ export function batchTime(schedule, index) {
267
+ let end = 0;
268
+ for (const batch of schedule) {
269
+ end += batch.count;
270
+ if (index < end) {
271
+ return batch.at;
272
+ }
273
+ }
274
+ return schedule.at(-1)?.at;
275
+ }