Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.
JavaScript agent-skillsai-agentsai-seoclaudeclaude-codeclaude-code-pluginclaude-skillscodexcontent-marketingconversion-rate-optimizationcopywritingcursoremail-marketinggenerative-engine-optimizationgrowth-marketingmarketingmarketing-automationsaas-marketingseoskill-md
feat(resend): preserve send retry identity with idempotency keys
Rudy Celekli59f0b8822f2c
diff --git a/tests/clis/resend-idempotency.test.cjs b/tests/clis/resend-idempotency.test.cjsnew file mode 100644index 0000000..ebdac89--- /dev/null+++ b/tests/clis/resend-idempotency.test.cjs@@ -0,0 +1,34 @@+const {test}=require('node:test')+const assert=require('node:assert/strict')+const {spawnSync}=require('node:child_process')+const path=require('node:path')+const cli=path.resolve(__dirname,'../../tools/clis/resend.js')+const send=['send','--from','[email protected]','--to','[email protected]','--subject','Welcome']+const batch=['batch','--emails','[{"from":"[email protected]","to":["[email protected]"],"subject":"Welcome"}]']+function run(args,network=true){+ const script=`global.fetch=async(url,options)=>{if(!${network})throw new Error('Unexpected network request');return {status:200,text:async()=>JSON.stringify({url,headers:options.headers,body:JSON.parse(options.body),id:'fixture-id'})}};process.argv=['node',${JSON.stringify(cli)},...${JSON.stringify(args)}];require(${JSON.stringify(cli)})`+ return spawnSync(process.execPath,['-e',script],{encoding:'utf8',timeout:5000,env:{PATH:process.env.PATH,RESEND_API_KEY:'fixture-secret'}})+}+function output(r){assert.equal(r.status,0,r.stderr);return JSON.parse(r.stdout)}+test('single and batch sends forward a caller-owned stable retry identity',()=>{+ for(const command of [send,batch]){+ const a=output(run([...command,'--idempotency-key','welcome/123']))+ const b=output(run([...command,'--idempotency-key','welcome/123']))+ assert.equal(a.headers['Idempotency-Key'],'welcome/123');assert.deepEqual(a,b)+ assert.equal(Object.hasOwn(a.body,'idempotency_key'),false)+ }+})+test('omission keeps existing requests and 256-character keys are accepted',()=>{+ assert.equal(Object.hasOwn(output(run(send)).headers,'Idempotency-Key'),false)+ assert.equal(output(run([...send,'--idempotency-key','a'.repeat(256)])).headers['Idempotency-Key'].length,256)+})+test('invalid keys and unsupported commands fail before a send',()=>{+ for(const args of [[...send,'--idempotency-key'],[...send,'--idempotency-key',''],[...batch,'--idempotency-key','x'.repeat(257)],[...send,'--idempotency-key','bad\r\nheader'],[...send,'--idempotency-key',' '],['emails','list','--idempotency-key','key']]){+ const r=run(args,false);assert.equal(r.status,1);assert.doesNotMatch(r.stderr,/Unexpected network request/)+ }+})+test('dry run exposes retry key without exposing credentials or fetching',()=>{+ const r=output(run([...send,'--idempotency-key','welcome/123','--dry-run'],false))+ assert.equal(r.headers['Idempotency-Key'],'welcome/123');assert.equal(r._dry_run,true)+ assert.equal(JSON.stringify(r).includes('fixture-secret'),false)+})diff --git a/tools/clis/resend.js b/tools/clis/resend.jsindex 555677b..e9c6687 100755--- a/tools/clis/resend.js+++ b/tools/clis/resend.js@@ -9,15 +9,16 @@ if ((!API_KEY) && rawArgs.length > 0) {process.exit(1)}-async function api(method, path, body) {+async function api(method, path, body, extraHeaders = {}) {if (args['dry-run']) {- return { _dry_run: true, method, url: `${BASE_URL}${path}`, headers: { Authorization: '***', 'Content-Type': 'application/json' }, body: body || undefined }+ return { _dry_run: true, method, url: `${BASE_URL}${path}`, headers: { Authorization: '***', 'Content-Type': 'application/json', ...extraHeaders }, body: body || undefined }}const res = await fetch(`${BASE_URL}${path}`, {method,headers: {'Authorization': `Bearer ${API_KEY}`,'Content-Type': 'application/json',+ ...extraHeaders,},body: body ? JSON.stringify(body) : undefined,})@@ -59,7 +60,19 @@ function booleanArg(name) {throw new Error(`--${name} must be true or false (or a bare flag for true)`)}+function idempotencyHeaders() {+ const key = args['idempotency-key']+ if (key === undefined) return {}+ if (typeof key !== 'string' || key.length < 1 || key.length > 256 || key !== key.trim() || /[\u0000-\u001f\u007f-\uffff]/.test(key)) {+ throw new Error('--idempotency-key must be 1–256 printable ASCII characters without surrounding whitespace')+ }+ return { 'Idempotency-Key': key }+}+async function main() {+ if (args['idempotency-key'] !== undefined && cmd !== 'send' && cmd !== 'batch') {+ throw new Error('--idempotency-key is supported only for send and batch')+ }let resultswitch (cmd) {@@ -76,7 +89,7 @@ async function main() {const [name, value] = t.split(':')return { name, value }})- result = await api('POST', '/emails', body)+ result = await api('POST', '/emails', body, idempotencyHeaders())break}@@ -236,7 +249,7 @@ async function main() {} catch (e) {result = { error: 'Invalid JSON for --emails: ' + e.message }; break}- result = await api('POST', '/emails/batch', emails)+ result = await api('POST', '/emails/batch', emails, idempotencyHeaders())break}@@ -355,14 +368,14 @@ async function main() {result = {error: 'Unknown command',usage: {- send: 'send --from <email> --to <email> --subject <subject> --html <html>',+ send: 'send --from <email> --to <email> --subject <subject> --html <html> [--idempotency-key <stable_key>]',emails: 'emails [list|get|cancel] [id]',domains: 'domains [list|get|create|verify|delete] [id] [--name <name>]','api-keys': 'api-keys [list|create|delete] [id] [--name <name>]',audiences: 'audiences [list|get|create|delete] [id] [--name <name>]',contacts: 'contacts <audience_id> [list|get|create|update|delete] [contact_id] [--email <email>] [--unsubscribed [true|false]]',webhooks: 'webhooks [list|get|create|delete] [id] [--endpoint <url>]',- batch: 'batch --emails <json_array>',+ batch: 'batch --emails <json_array> [--idempotency-key <stable_key>]',templates: 'templates [list|get|create|update|delete|publish|duplicate] [id] [--name <name>] [--html <html>] [--variables <json>]',broadcasts: 'broadcasts [list|get|create|send|delete] [id] [--segment-id <id>] [--from <email>] [--subject <subject>]',segments: 'segments [list|get|create|delete] [id] [--name <name>]',diff --git a/tools/integrations/resend.md b/tools/integrations/resend.mdindex 5489c46..689a032 100644--- a/tools/integrations/resend.md+++ b/tools/integrations/resend.md@@ -210,3 +210,13 @@ await resend.emails.send({- emails- onboarding++## Retry identity in the bundled CLI++For single `send` and whole `batch` operations, pass `--idempotency-key <stable_key>` to send the `Idempotency-Key` header. Use one key per logical send and retain the same payload/key when retrying; use a new key for a different send. The CLI accepts 1–256 printable ASCII characters, forwards the caller's key, and never generates a new key or retries automatically.++```bash+node tools/clis/resend.js send --from [email protected] --to [email protected] --subject Welcome --text Hello --idempotency-key welcome/user-123 --dry-run+```++Resend retains keys for 24 hours. Reusing a key with a different payload returns a conflict; once retention expires it cannot prevent duplicates. This is a provider feature, not permanent exactly-once delivery. See [Resend idempotency keys](https://resend.com/docs/dashboard/emails/idempotency-keys). Dry runs show the key with authentication redacted; contract tests use fixtures and send no email.