@raoufb3n/claude-code-wrapped 0.0.0-stage → 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.
Files changed (22) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -2
  3. package/bin/cli.mjs +31 -0
  4. package/package.json +32 -4
  5. package/plugins/tokens-wrapped/skills/wrapped/assets/fonts/OFL-EncodeSansExpanded.txt +93 -0
  6. package/plugins/tokens-wrapped/skills/wrapped/assets/fonts/OFL-Figtree.txt +93 -0
  7. package/plugins/tokens-wrapped/skills/wrapped/assets/fonts/encode-sans-expanded-latin-500-normal.woff2 +0 -0
  8. package/plugins/tokens-wrapped/skills/wrapped/assets/fonts/encode-sans-expanded-latin-800-normal.woff2 +0 -0
  9. package/plugins/tokens-wrapped/skills/wrapped/assets/fonts/encode-sans-expanded-latin-900-normal.woff2 +0 -0
  10. package/plugins/tokens-wrapped/skills/wrapped/assets/fonts/figtree-latin-400-normal.woff2 +0 -0
  11. package/plugins/tokens-wrapped/skills/wrapped/assets/fonts/figtree-latin-700-normal.woff2 +0 -0
  12. package/plugins/tokens-wrapped/skills/wrapped/assets/fonts/widths.json +1 -0
  13. package/plugins/tokens-wrapped/skills/wrapped/assets/glow/artist-card.webp +0 -0
  14. package/plugins/tokens-wrapped/skills/wrapped/assets/glow/artist-photo.webp +0 -0
  15. package/plugins/tokens-wrapped/skills/wrapped/assets/glow/bg-artist.jpg +0 -0
  16. package/plugins/tokens-wrapped/skills/wrapped/assets/glow/bg-lime.jpg +0 -0
  17. package/plugins/tokens-wrapped/skills/wrapped/assets/glow/bg-purple.jpg +0 -0
  18. package/plugins/tokens-wrapped/skills/wrapped/assets/glow/bg-twin.jpg +0 -0
  19. package/plugins/tokens-wrapped/skills/wrapped/assets/glow/title-tokens.png +0 -0
  20. package/plugins/tokens-wrapped/skills/wrapped/scripts/cards.mjs +239 -0
  21. package/plugins/tokens-wrapped/skills/wrapped/scripts/stats.mjs +183 -0
  22. package/plugins/tokens-wrapped/skills/wrapped/scripts/wrapped.mjs +180 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abderraouf
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ # Claude Code Wrapped
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Your year in Claude Code as **Spotify Wrapped–style** images. One command totals the tokens you burned from your **local** Claude Code session logs and drafts shareable cards in the look of Spotify Wrapped 2026:
4
+
5
+ - **Story** 1080×1920 (Instagram / LinkedIn stories)
6
+ - **Post** 1080×1080 (LinkedIn / X / Instagram feed)
7
+
8
+ | Style | Card |
9
+ | --- | --- |
10
+ | `glow` | **My Tokens Burned**: your total, lime glow |
11
+ | `glow-streak` | **My Longest Streak**: days in a row, violet glow |
12
+ | `model-twin` | **My Model Twin**: main model, peak hour, streak, top project, favourite day |
13
+ | `top-artist` | **My Top Artist**: Claude as your #1 artist, with tokens and sessions on the trading card |
14
+
15
+ ![Preview of all styles with sample data](docs/preview.jpg)
16
+
17
+ Nothing is uploaded. The plugin reads `~/.claude/projects/**/*.jsonl` and writes files to a folder on your machine.
18
+
19
+ ## Quick start: one command, no install
20
+
21
+ Have Node.js 18+ and some Claude Code history on this computer? Run:
22
+
23
+ ```bash
24
+ npx @raoufb3n/claude-code-wrapped
25
+ ```
26
+
27
+ It reads your local Claude Code logs, prints your numbers, saves the cards to `./claude-wrapped-<year>` and opens the gallery. Add `--demo` for sample data or `--help` for every option.
28
+
29
+ ## Use it inside Claude Code
30
+
31
+ With the plugin, Claude also writes a recap of your year and can draft a caption for your post.
32
+
33
+ ```bash
34
+ # load for one session straight from this folder
35
+ claude --plugin-dir ./plugins/tokens-wrapped
36
+ ```
37
+
38
+ Then in Claude Code:
39
+
40
+ ```
41
+ /tokens-wrapped:wrapped
42
+ /tokens-wrapped:wrapped 2026 --styles glow --hide-projects
43
+ /tokens-wrapped:wrapped --demo # preview with sample data
44
+ ```
45
+
46
+ Or install from this marketplace:
47
+
48
+ ```
49
+ /plugin marketplace add raoufb3n/claude-code-wrapped
50
+ /plugin install tokens-wrapped@claude-code-wrapped
51
+ ```
52
+
53
+ From a clone you can also run `node bin/cli.mjs`.
54
+
55
+ ## Options
56
+
57
+ | Flag | What it does |
58
+ | --- | --- |
59
+ | `2026` or `--year 2026` | Year to wrap (default: current year) |
60
+ | `--styles glow,model-twin` | Pick styles (default: all four) |
61
+ | `--formats story,post` | Pick sizes (default: both) |
62
+ | `--hide-projects` | Keep project names off the images |
63
+ | `--tagline "line one\|line **two**"` | Replace the line under the number on the glow card |
64
+ | `--title "My Tokens Burned"` | Glow card title |
65
+ | `--handle "@you"` | Footer text |
66
+ | `--out DIR` | Output folder (default `./claude-wrapped-<year>`) |
67
+ | `--no-png` | Skip PNG export |
68
+ | `--open` | Open the gallery when done |
69
+ | `--demo` | Use sample data |
70
+ | `--json` | Print the stats only |
71
+
72
+ PNGs are exported with headless Chrome, Edge, Brave or Chromium if one is installed. Otherwise open `index.html` and use the **Download PNG** buttons.
73
+
74
+ ## What's counted
75
+
76
+ Every assistant response in your transcripts records its usage: input, output, cache writes and cache reads. The headline number is the sum of all four. Cache reads are usually most of it in agentic coding; the JSON output and `stats.json` show the split. Responses split across several log lines are counted once.
77
+
78
+ ## Heads up: keep a full year of history
79
+
80
+ Claude Code deletes session logs older than `cleanupPeriodDays` (30 days by default). If your Wrapped only covers the last month, add this to `~/.claude/settings.json` so next year's covers everything:
81
+
82
+ ```json
83
+ { "cleanupPeriodDays": 400 }
84
+ ```
85
+
86
+ ## Requirements
87
+
88
+ Node.js 18+. No npm dependencies. PNG export uses Chrome, Edge, Brave or Chromium if installed.
89
+
90
+ ## Credits
91
+
92
+ Designs adapted from the *Spotify Wrapped 2026 – 33 Editable Designs* Figma Community file. Fonts: Encode Sans Expanded and Figtree, under the SIL Open Font License (see `skills/wrapped/assets/fonts`).
93
+
94
+ Not affiliated with, endorsed by or sponsored by Spotify or Anthropic. "Spotify" and "Wrapped" belong to Spotify; the cards use no Spotify logo.
package/bin/cli.mjs ADDED
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ // npx entry point: same as the plugin's script, but prints a readable summary
3
+ // and opens the gallery. Usage: npx @raoufb3n/claude-code-wrapped [options]
4
+ const [major] = process.versions.node.split(".").map(Number);
5
+ if (major < 18) {
6
+ console.error(`Claude Code Wrapped needs Node.js 18 or later (you have ${process.versions.node}).`);
7
+ process.exit(1);
8
+ }
9
+ const args = process.argv.slice(2);
10
+ if (args.includes("--help") || args.includes("-h")) {
11
+ console.log(`Claude Code Wrapped: your year in Claude Code as Spotify Wrapped-style cards.
12
+
13
+ Reads your local Claude Code logs (~/.claude/projects). Nothing is uploaded.
14
+
15
+ Usage: npx @raoufb3n/claude-code-wrapped [year] [options]
16
+
17
+ --styles glow,glow-streak,model-twin,top-artist pick cards (default: all)
18
+ --formats story,post story 1080x1920, post 1080x1080 (default: both)
19
+ --hide-projects keep project names off the images
20
+ --handle "@you" footer text
21
+ --tagline "a|**b**" line under the number on the glow card
22
+ --out DIR output folder (default ./claude-wrapped-<year>)
23
+ --no-png skip PNG export (needs Chrome, Edge or Chromium)
24
+ --no-open don't open the gallery
25
+ --demo sample data
26
+ --json print the stats as JSON only`);
27
+ process.exit(0);
28
+ }
29
+ process.argv.push("--pretty");
30
+ if (!args.includes("--no-open") && !args.includes("--json")) process.argv.push("--open");
31
+ await import("../plugins/tokens-wrapped/skills/wrapped/scripts/wrapped.mjs");
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@raoufb3n/claude-code-wrapped",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Your year in Claude Code as Spotify Wrapped-style images, from your local session logs.",
5
+ "type": "module",
6
+ "bin": {
7
+ "claude-code-wrapped": "bin/cli.mjs"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "plugins/tokens-wrapped/skills/wrapped/scripts/",
12
+ "plugins/tokens-wrapped/skills/wrapped/assets/"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/raoufb3n/claude-code-wrapped.git"
20
+ },
21
+ "homepage": "https://github.com/raoufb3n/claude-code-wrapped",
22
+ "author": "Abderraouf",
23
+ "license": "MIT",
24
+ "keywords": [
25
+ "claude-code",
26
+ "wrapped",
27
+ "spotify-wrapped",
28
+ "tokens",
29
+ "year-in-review"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ }
34
+ }
@@ -0,0 +1,93 @@
1
+ Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans". EncodeSansExpanded-ExtraLight.ttf: Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans". EncodeSansExpanded-Light.ttf: Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans". EncodeSansExpanded-Regular.ttf: Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans". EncodeSansExpanded-Medium.ttf: Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans". EncodeSansExpanded-SemiBold.ttf: Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans". EncodeSansExpanded-Bold.ttf: Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans". EncodeSansExpanded-ExtraBold.ttf: Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans". EncodeSansExpanded-Black.ttf: Copyright 2012 The Encode Project Authors (impallari@gmail.com), with Reserved Font Name "Encode Sans".
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Copyright 2022 The Figtree Project Authors (https://github.com/erikdkennedy/figtree) Figtree-Italic[wght].ttf: Copyright 2022 The Figtree Project Authors (https://github.com/erikdkennedy/figtree)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1 @@
1
+ {"ese900":{" ":0.292,"!":0.368,"\"":0.565,"#":0.72,"$":0.689,"%":1.26,"&":0.923,"'":0.29,"(":0.417,")":0.417,"*":0.558,"+":0.598,",":0.348,"-":0.575,".":0.348,"/":0.529,"0":0.787,"1":0.536,"2":0.641,"3":0.645,"4":0.746,"5":0.651,"6":0.736,"7":0.612,"8":0.787,"9":0.736,":":0.348,";":0.348,"<":0.598,"=":0.598,">":0.598,"?":0.594,"@":1.216,"A":0.88,"B":0.761,"C":0.744,"D":0.9,"E":0.749,"F":0.737,"G":0.839,"H":0.897,"I":0.368,"J":0.368,"K":0.773,"L":0.681,"M":1.088,"N":0.902,"O":0.946,"P":0.764,"Q":0.946,"R":0.789,"S":0.689,"T":0.766,"U":0.878,"V":0.87,"W":1.374,"X":0.796,"Y":0.766,"Z":0.741,"[":0.417,"\\":0.529,"]":0.417,"^":0.72,"_":0.724,"`":0.6,"a":0.672,"b":0.745,"c":0.597,"d":0.745,"e":0.663,"f":0.49,"g":0.745,"h":0.731,"i":0.348,"j":0.348,"k":0.728,"l":0.348,"m":1.063,"n":0.731,"o":0.732,"p":0.745,"q":0.745,"r":0.479,"s":0.604,"t":0.512,"u":0.726,"v":0.712,"w":1.075,"x":0.678,"y":0.712,"z":0.637,"{":0.437,"|":0.34,"}":0.437,"~":0.598,"\u2019":0.348,"\u2026":1.024,"\u2013":0.5,"\u00b7":0.348},"ese800":{" ":0.2895,"!":0.3505,"\"":0.5375,"#":0.703,"$":0.673,"%":1.213,"&":0.907,"'":0.2795,"(":0.408,")":0.408,"*":0.5435,"+":0.592,",":0.3305,"-":0.5585,".":0.3305,"/":0.4975,"0":0.772,"1":0.5165,"2":0.626,"3":0.63,"4":0.7295,"5":0.6365,"6":0.719,"7":0.596,"8":0.772,"9":0.719,":":0.3305,";":0.3305,"<":0.592,"=":0.592,">":0.592,"?":0.577,"@":1.1915,"A":0.8575,"B":0.7485,"C":0.7285,"D":0.881,"E":0.734,"F":0.7205,"G":0.826,"H":0.8815,"I":0.3515,"J":0.3515,"K":0.7575,"L":0.667,"M":1.066,"N":0.888,"O":0.9235,"P":0.749,"Q":0.9235,"R":0.777,"S":0.673,"T":0.7455,"U":0.863,"V":0.8455,"W":1.34,"X":0.78,"Y":0.7455,"Z":0.725,"[":0.408,"\\":0.4985,"]":0.408,"^":0.703,"_":0.708,"`":0.6,"a":0.655,"b":0.7265,"c":0.5795,"d":0.7265,"e":0.6485,"f":0.4755,"g":0.7265,"h":0.7155,"i":0.3315,"j":0.3315,"k":0.7015,"l":0.3315,"m":1.041,"n":0.7155,"o":0.7135,"p":0.7265,"q":0.7265,"r":0.4665,"s":0.5885,"t":0.496,"u":0.7105,"v":0.6915,"w":1.0505,"x":0.6595,"y":0.6915,"z":0.617,"{":0.428,"|":0.3275,"}":0.428,"~":0.592,"\u2019":0.3305,"\u2026":0.972,"\u2013":0.5,"\u00b7":0.3305},"fig400":{" ":0.247,"!":0.298,"\"":0.32,"#":0.629,"$":0.563,"%":0.786,"&":0.644,"'":0.2,"(":0.352,")":0.352,"*":0.481,"+":0.623,",":0.226,"-":0.417,".":0.208,"/":0.389,"0":0.641,"1":0.413,"2":0.559,"3":0.544,"4":0.621,"5":0.575,"6":0.566,"7":0.537,"8":0.614,"9":0.566,":":0.253,";":0.259,"<":0.623,"=":0.623,">":0.623,"?":0.504,"@":0.989,"A":0.677,"B":0.611,"C":0.721,"D":0.688,"E":0.592,"F":0.543,"G":0.76,"H":0.751,"I":0.271,"J":0.515,"K":0.61,"L":0.52,"M":0.846,"N":0.774,"O":0.776,"P":0.579,"Q":0.78,"R":0.626,"S":0.614,"T":0.552,"U":0.707,"V":0.693,"W":0.96,"X":0.614,"Y":0.604,"Z":0.641,"[":0.324,"\\":0.389,"]":0.324,"^":0.551,"_":0.438,"`":0.221,"a":0.51,"b":0.586,"c":0.541,"d":0.586,"e":0.546,"f":0.369,"g":0.587,"h":0.558,"i":0.232,"j":0.269,"k":0.485,"l":0.22,"m":0.851,"n":0.558,"o":0.58,"p":0.591,"q":0.578,"r":0.338,"s":0.466,"t":0.378,"u":0.558,"v":0.52,"w":0.784,"x":0.475,"y":0.526,"z":0.491,"{":0.385,"|":0.257,"}":0.385,"~":0.567,"\u2019":0.181,"\u2026":0.613,"\u2013":0.55,"\u00b7":0.254},"fig700":{" ":0.238,"!":0.312,"\"":0.412,"#":0.631,"$":0.554,"%":0.813,"&":0.647,"'":0.245,"(":0.382,")":0.382,"*":0.488,"+":0.632,",":0.257,"-":0.408,".":0.248,"/":0.432,"0":0.648,"1":0.422,"2":0.579,"3":0.556,"4":0.633,"5":0.581,"6":0.58,"7":0.556,"8":0.612,"9":0.58,":":0.301,";":0.305,"<":0.632,"=":0.632,">":0.632,"?":0.513,"@":0.992,"A":0.714,"B":0.612,"C":0.725,"D":0.7,"E":0.589,"F":0.554,"G":0.743,"H":0.75,"I":0.289,"J":0.552,"K":0.666,"L":0.537,"M":0.857,"N":0.773,"O":0.787,"P":0.603,"Q":0.789,"R":0.645,"S":0.607,"T":0.584,"U":0.704,"V":0.722,"W":0.985,"X":0.679,"Y":0.647,"Z":0.632,"[":0.344,"\\":0.432,"]":0.344,"^":0.581,"_":0.434,"`":0.263,"a":0.533,"b":0.596,"c":0.546,"d":0.595,"e":0.554,"f":0.393,"g":0.601,"h":0.57,"i":0.262,"j":0.291,"k":0.538,"l":0.246,"m":0.872,"n":0.568,"o":0.581,"p":0.601,"q":0.592,"r":0.379,"s":0.466,"t":0.402,"u":0.568,"v":0.556,"w":0.835,"x":0.536,"y":0.576,"z":0.477,"{":0.394,"|":0.256,"}":0.394,"~":0.667,"\u2019":0.219,"\u2026":0.709,"\u2013":0.55,"\u00b7":0.26}}
@@ -0,0 +1,239 @@
1
+ // Renders Spotify Wrapped-style cards as standalone SVG (fonts embedded, so they rasterize anywhere).
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const FONT_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "fonts");
7
+ const FONTS = {
8
+ "ese-500": ["Wrapped Sans", 500, "encode-sans-expanded-latin-500-normal.woff2"],
9
+ "ese-800": ["Wrapped Sans", 800, "encode-sans-expanded-latin-800-normal.woff2"],
10
+ "ese-900": ["Wrapped Sans", 900, "encode-sans-expanded-latin-900-normal.woff2"],
11
+ "fig-400": ["Wrapped Body", 400, "figtree-latin-400-normal.woff2"],
12
+ "fig-700": ["Wrapped Body", 700, "figtree-latin-700-normal.woff2"],
13
+ };
14
+ const fontCache = {};
15
+ function fontFaces(keys) {
16
+ return keys.map((k) => {
17
+ const [family, weight, file] = FONTS[k];
18
+ fontCache[k] ??= fs.readFileSync(path.join(FONT_DIR, file)).toString("base64");
19
+ return `@font-face{font-family:'${family}';font-weight:${weight};src:url(data:font/woff2;base64,${fontCache[k]}) format('woff2');}`;
20
+ }).join("");
21
+ }
22
+ const SANS = "'Wrapped Sans', 'Arial Black', sans-serif";
23
+
24
+ export const STYLES = ["glow", "glow-streak", "model-twin", "top-artist"];
25
+ export const FORMATS = { story: [1080, 1920], post: [1080, 1080] };
26
+
27
+ // ---------- helpers ----------
28
+ export function compact(n) {
29
+ const units = [[1e12, "T"], [1e9, "B"], [1e6, "M"], [1e3, "K"]];
30
+ for (const [v, u] of units) {
31
+ if (n >= v) {
32
+ const x = n / v;
33
+ return (x >= 100 ? Math.round(x) : x >= 10 ? Math.round(x) : Math.round(x * 10) / 10) + u;
34
+ }
35
+ }
36
+ return String(Math.round(n));
37
+ }
38
+ const full = (n) => Math.round(n).toLocaleString("en-US");
39
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" }[c]));
40
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
41
+ const niceDate = (k) => { const [, m, d] = k.split("-").map(Number); return `${MONTHS[m - 1]} ${d}`; };
42
+ const hourLabel = (h) => (h == null ? "–" : `${h % 12 || 12} ${h < 12 ? "AM" : "PM"}`);
43
+ // War and Peace: ~587k words, roughly 780k tokens.
44
+ const warAndPeace = (t) => Math.max(1, Math.round(t / 780000));
45
+
46
+ // Two-line body with **bold** support. Lines separated by "|".
47
+ function richLines(str) {
48
+ return str.split("|").map((line) => line.trim().split(/(\*\*[^*]+\*\*)/).filter(Boolean)
49
+ .map((part) => part.startsWith("**") ? { b: true, t: part.slice(2, -2) } : { b: false, t: part }));
50
+ }
51
+ function svg(W, H, fonts, body, defs = "") {
52
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
53
+ `<defs><style>${fontFaces(fonts)}</style>${defs}</defs>${body}</svg>`;
54
+ }
55
+ function defaultBody(s, o) {
56
+ if (o.tagline) return o.tagline;
57
+ const since = s.coverage.partial && s.coverage.from ? ` since ${niceDate(s.coverage.from)}` : ` in ${s.year}`;
58
+ return `That's about **${full(warAndPeace(s.totals.total))} copies** of War and Peace, across **${full(s.sessions)} sessions**${since}.`;
59
+ }
60
+
61
+ // ---------- style 1: glow (the user's Figma design, frames "Story/minutes" and "Story/listening-age") ----------
62
+ const ASSET_DIR = path.join(FONT_DIR, "..", "glow");
63
+ const assetCache = {};
64
+ const asset = (file, mime) => (assetCache[file] ??= `data:${mime};base64,${fs.readFileSync(path.join(ASSET_DIR, file)).toString("base64")}`);
65
+ const WIDTHS = JSON.parse(fs.readFileSync(path.join(FONT_DIR, "widths.json"), "utf8"));
66
+ const textW = (t, font, size, tracking = 0) => [...String(t)].reduce((w, ch) => w + (WIDTHS[font][ch] ?? 0.6) * size + tracking, 0) - tracking;
67
+
68
+ // Word-wrap rich text (parts with bold flags) into lines no wider than maxW.
69
+ function wrapRich(str, size, maxW, tracking) {
70
+ const words = [];
71
+ for (const line of richLines(str)) {
72
+ line.forEach((p) => p.t.split(/(\s+)/).filter((x) => x).forEach((w) => words.push({ b: p.b, t: w })));
73
+ words.push({ br: true });
74
+ }
75
+ const lines = [[]];
76
+ let w = 0;
77
+ for (const word of words) {
78
+ if (word.br) { if (lines.at(-1).length) { lines.push([]); w = 0; } continue; }
79
+ const ww = textW(word.t, word.b ? "fig700" : "fig400", size, tracking);
80
+ if (w + ww > maxW && word.t.trim() && lines.at(-1).length) { lines.push([]); w = 0; }
81
+ if (!lines.at(-1).length && !word.t.trim()) continue;
82
+ lines.at(-1).push(word); w += ww;
83
+ }
84
+ return lines.map((l) => { while (l.length && !l.at(-1).t.trim()) l.pop(); return l; }).filter((l) => l.length);
85
+ }
86
+
87
+ // Pixel mascot from the footer of the design, drawn on a 131-unit grid.
88
+ const MASCOT = [[17, 28, 97, 64], [1, 60, 129, 16], [25, 92, 8, 17], [42, 92, 8, 17], [82, 92, 8, 17], [98, 92, 8, 17]];
89
+ const mascot = (x, y, fill, bg) => `<g transform="translate(${x} ${y})">${MASCOT.map(([a, b, w, h]) => `<rect x="${a}" y="${b}" width="${w}" height="${h}" fill="${fill}"/>`).join("")}` +
90
+ `<rect x="33" y="44" width="8" height="15" fill="${bg}"/><rect x="90" y="44" width="8" height="15" fill="${bg}"/></g>`;
91
+
92
+ function glowFilter(id, rgb, layers) {
93
+ return `<filter id="${id}" x="-40%" y="-60%" width="180%" height="220%">` +
94
+ layers.map(([sd, a], i) => `<feGaussianBlur in="SourceAlpha" stdDeviation="${sd}" result="b${i}"/><feFlood flood-color="rgb(${rgb})" flood-opacity="${a}"/><feComposite in2="b${i}" operator="in" result="s${i}"/>`).join("") +
95
+ `<feMerge>${layers.map((_, i) => `<feMergeNode in="s${layers.length - 1 - i}"/>`).join("")}<feMergeNode in="SourceGraphic"/></feMerge></filter>`;
96
+ }
97
+
98
+ const GLOW_THEMES = {
99
+ lime: { bg: "bg-lime.jpg", title: "#d5ed8f", number: "#d2ea84", body: "#d5ed8f", rgb: "204,235,117",
100
+ layers: [[6, 0.08], [30, 0.3], [60, 0.5]], titleImg: "title-tokens.png",
101
+ titleY: 679, numTop: 767.44, numLH: 378, numSize: 274.92, numTrack: -5.8, bodyTop: 1173, mascot: true, mascotX: 54 },
102
+ purple: { bg: "bg-purple.jpg", title: "#a8a7fb", number: "#a3a1f3", body: "#a8a7fb", rgb: "163,161,249",
103
+ layers: [[6, 0.1], [60, 0.75]], titleTop: 573.61, titleLH: 76, titleSize: 63.42,
104
+ numTop: 586.42, numLH: 708, numSize: 515.02, numTrack: -18, bodyTop: 1235.27, mascot: true, mascotX: 51,
105
+ // the square post has no Figma frame for this card, so the number is scaled down to fit
106
+ post: { titleTop: 535, numTop: 600, numLH: 500, numSize: 380, bodyTop: 1150 } },
107
+ };
108
+ // Spotify Mix Ultra is narrower than Encode Sans Expanded Black, so the number is squeezed horizontally to match.
109
+ const NUM_SQUEEZE = 0.85;
110
+
111
+ function glowCard(theme, { title, value, body }, o, W, H) {
112
+ const post = H === W;
113
+ const t = { ...GLOW_THEMES[theme], ...(post ? GLOW_THEMES[theme].post : {}) };
114
+ const dy = post ? -390 : 0; // the LinkedIn frame moves content up 390px
115
+ const bgY = post ? -260 : 0; // and the background 260px
116
+ const footY = post ? 920 : 1758.6;
117
+ const fid = `ng-${theme}`;
118
+ const out = [];
119
+ out.push(`<rect width="${W}" height="${H}" fill="#1f1f1f"/><image href="${asset(t.bg, "image/jpeg")}" x="0" y="${bgY}" width="1080" height="1920" preserveAspectRatio="none"/>`);
120
+
121
+ // title
122
+ const useImg = t.titleImg && !o.title && theme === "lime";
123
+ if (useImg) {
124
+ out.push(`<image href="${asset(t.titleImg, "image/png")}" x="113.5" y="${t.titleY + dy}" width="853" height="58"/>`);
125
+ } else {
126
+ const tt = o.title && theme === "lime" ? o.title : title;
127
+ const size = Math.min(t.titleSize || 63.42, 900 / Math.max(1, textW(tt, "ese800", 1, -0.01)));
128
+ const top = (t.titleTop ?? t.titleY - 8) + dy, lh = t.titleLH || 76;
129
+ out.push(`<text x="540" y="${top + lh / 2 + size * 0.37}" text-anchor="middle" font-family="${SANS}" font-weight="800" font-size="${size.toFixed(2)}" letter-spacing="-0.6" fill="${t.title}">${esc(tt)}</text>`);
130
+ }
131
+
132
+ // big number
133
+ let size = t.numSize;
134
+ const natural = textW(value, "ese900", size, t.numTrack) * NUM_SQUEEZE;
135
+ if (natural > 960) size *= 960 / natural;
136
+ const baseline = t.numTop + dy + t.numLH / 2 + (t.numSize * 0.74) / 2 - (t.numSize - size) * 0.37;
137
+ out.push(`<g transform="translate(540 ${baseline.toFixed(1)}) scale(${NUM_SQUEEZE} 1)"><text x="0" y="0" text-anchor="middle" font-family="${SANS}" font-weight="900" font-size="${size.toFixed(2)}" letter-spacing="${t.numTrack}" fill="${t.number}" filter="url(#${fid})">${esc(value)}</text></g>`);
138
+
139
+ // body
140
+ const bSize = 47.32, bLH = 65, track = -0.667;
141
+ const lines = wrapRich(body, bSize, 854, track);
142
+ lines.forEach((ln, i) => {
143
+ const y = t.bodyTop + dy + bLH / 2 + bSize * 0.35 + i * bLH;
144
+ out.push(`<text x="540" y="${y.toFixed(1)}" text-anchor="middle" font-family="'Wrapped Body', sans-serif" font-size="${bSize}" letter-spacing="${track}" fill="${t.body}" xml:space="preserve">${
145
+ ln.map((w) => `<tspan font-weight="${w.b ? 700 : 400}">${esc(w.t)}</tspan>`).join("")}</text>`);
146
+ });
147
+
148
+ // footer
149
+ const foot = (o.handle || "CLAUDE CODE/WRAPPED").toUpperCase();
150
+ const fSize = Math.min(48.06, 640 / Math.max(1, textW(foot, "fig700", 1, -0.024)));
151
+ out.push(`<text x="1014.19" y="${(footY + 45.3 + 28.75 + 48.06 * 0.35).toFixed(1)}" text-anchor="end" font-family="'Wrapped Body', sans-serif" font-weight="700" font-size="${fSize.toFixed(2)}" letter-spacing="-1.167" fill="${t.body}">${esc(foot)}</text>`);
152
+ if (t.mascot) out.push(mascot(t.mascotX, footY + 9.4, t.body, "#1f1f1f"));
153
+
154
+ return svg(W, H, ["ese-800", "ese-900", "fig-400", "fig-700"], out.join("\n"), glowFilter(fid, t.rgb, t.layers));
155
+ }
156
+
157
+ function glow(s, o, W, H) {
158
+ return glowCard("lime", { title: "My Tokens Burned", value: compact(s.totals.total), body: defaultBody(s, o) }, o, W, H);
159
+ }
160
+ function glowStreak(s, o, W, H) {
161
+ const n = s.longestStreak;
162
+ return glowCard("purple", { title: "My Longest Streak", value: String(n),
163
+ body: `That's **${n} day${n === 1 ? "" : "s"}** in a row of building.` }, o, W, H);
164
+ }
165
+
166
+ // Shared footer: CLAUDE CODE/WRAPPED (or --handle) on the right, pixel mascot on the left.
167
+ function footer(o, fill, footY, mascotY) {
168
+ const foot = (o.handle || "CLAUDE CODE/WRAPPED").toUpperCase();
169
+ const fSize = Math.min(48.06, 640 / Math.max(1, textW(foot, "fig700", 1, -0.024)));
170
+ return `<text x="1014.19" y="${(footY + 45.3 + 28.75 + 48.06 * 0.35).toFixed(1)}" text-anchor="end" font-family="'Wrapped Body', sans-serif" font-weight="700" font-size="${fSize.toFixed(2)}" letter-spacing="-1.167" fill="${fill}">${esc(foot)}</text>` +
171
+ mascot(54, mascotY, fill, "#1f1f1f");
172
+ }
173
+ // One line of text centered on x, with its Figma line box starting at `top`.
174
+ const line = (x, top, lh, size, txt, { family = "'Wrapped Body', sans-serif", weight = 400, fill, track = 0, anchor = "middle" } = {}) =>
175
+ `<text x="${x}" y="${(top + lh / 2 + size * 0.35).toFixed(1)}" text-anchor="${anchor}" font-family="${family}" font-weight="${weight}" font-size="${size.toFixed(2)}" letter-spacing="${track}" fill="${fill}" xml:space="preserve">${esc(txt)}</text>`;
176
+ const shrink = (txt, font, size, maxW, track = 0) => Math.min(size, size * maxW / Math.max(1, textW(txt, font, size, track)));
177
+
178
+ // ---------- style 3: model-twin (Figma frame "Story/audio-twin") ----------
179
+ function modelTwin(s, o, W, H) {
180
+ const post = H === W;
181
+ const fill = "#d5ed8f";
182
+ const model = (s.models[0]?.name || "Claude").toUpperCase();
183
+ const project = s.topProjects[0]?.name;
184
+ const cells = [
185
+ ["Peak Hour", hourLabel(s.peakHour), 305, 859],
186
+ ["Longest Streak", `${s.longestStreak} day${s.longestStreak === 1 ? "" : "s"}`, 774, 859],
187
+ project ? ["Top Project", project, 305, 1031] : ["Busiest Day", s.busiestDay ? niceDate(s.busiestDay.date) : "–", 305, 1031],
188
+ ["Favourite Day", s.favWeekday || "–", 774, 1031],
189
+ ];
190
+ const c = [];
191
+ c.push(line(540, 528.69, 57.5, 47.8, "My Model Twin", { weight: 700, fill }));
192
+ c.push(line(540, 650.69, 48.5, 35.44, "Spent the most time with:", { fill, track: -0.312 }));
193
+ c.push(line(540, 717.58, 76.5, shrink(model, "fig700", 63.66, 900), model, { weight: 700, fill, track: -0.778 }));
194
+ for (const [label, value, x, top] of cells) {
195
+ c.push(line(x, top, 48.5, 35.5, label, { fill, track: -0.3 }));
196
+ c.push(line(x, top + 65, 58, shrink(value, "ese800", 48.5, 420, -0.5), value, { family: SANS, weight: 800, fill, track: -0.5 }));
197
+ }
198
+ // The square post has no Figma frame: the story layout is scaled to fit between the twin icon and the footer.
199
+ const body = post ? `<g transform="translate(108 -52) scale(0.8)">${c.join("")}</g>` : c.join("");
200
+ const footY = post ? 920 : 1760.6;
201
+ return svg(W, H, ["ese-800", "fig-400", "fig-700"],
202
+ `<rect width="${W}" height="${H}" fill="#1f1f1f"/><image href="${asset("bg-twin.jpg", "image/jpeg")}" x="0" y="${post ? -120 : 0}" width="1080" height="1920" preserveAspectRatio="none"/>` +
203
+ body + footer(o, fill, footY, footY + 14.4));
204
+ }
205
+
206
+ // ---------- style 4: top-artist (Figma frame "Story/artist-1", ArtistCard) ----------
207
+ function topArtist(s, o, W, H) {
208
+ const post = H === W;
209
+ const fill = "#a8a7fb", white = "#f9fdfe", ink = "#111";
210
+ const wide = SANS;
211
+ const sessions = full(s.sessions);
212
+ const card = [
213
+ `<image href="${asset("artist-card.webp", "image/webp")}" x="0" y="0" width="900" height="1260"/>`,
214
+ `<image href="${asset("artist-photo.webp", "image/webp")}" x="69.5" y="70" width="602" height="602"/>`,
215
+ line(45, 765.59, 203.54, 169.62, "CLAUDE", { weight: 700, fill: white, track: -2, anchor: "start" }),
216
+ line(45, 1061.31, 30.9, 25.75, "TOKENS BURNED", { family: wide, weight: 800, fill: white, track: -1.125, anchor: "start" }),
217
+ line(45, 1093.05, 98.11, 81.76, compact(s.totals.total), { family: wide, weight: 800, fill: white, track: -1.75, anchor: "start" }),
218
+ line(342, 1061.27, 30.71, 25.59, "SESSIONS", { family: wide, weight: 800, fill: white, track: -1, anchor: "start" }),
219
+ line(342, 1093.53, 95.75, shrink(sessions, "ese800", 79.79, 400, -1), sessions, { family: wide, weight: 800, fill: white, track: -1, anchor: "start" }),
220
+ // vertical labels on the card's right edge, read top to bottom
221
+ `<text transform="translate(833.4 637.15) rotate(90)" font-family="${wide}" font-weight="500" font-size="25.68" letter-spacing="-0.462" fill="${ink}">1ST TOP ARTIST</text>`,
222
+ `<text transform="translate(835.4 1143.8) rotate(90)" text-anchor="middle" font-family="'Wrapped Body', sans-serif" font-weight="700" font-size="25.68" letter-spacing="-0.5" fill="${ink}">${esc(String(s.activeDays))}</text>`,
223
+ ].join("");
224
+ const content =
225
+ line(540, 146.59, 57, 47.4, "My Top Artist", { family: wide, weight: 800, fill, track: 0.25 }) +
226
+ // card is 900x1260, centered in its 951.97x1296.58 Figma box and tilted 2.4°
227
+ `<g transform="translate(539.5 947.5) rotate(2.4) translate(-450 -630)">${card}</g>`;
228
+ const body = post ? `<g transform="translate(226.8 -24.7) scale(0.58)">${content}</g>` : content;
229
+ const footY = post ? 920 : 1760;
230
+ return svg(W, H, ["ese-500", "ese-800", "fig-400", "fig-700"],
231
+ `<rect width="${W}" height="${H}" fill="#1f1f1f"/><image href="${asset("bg-artist.jpg", "image/jpeg")}" x="0" y="${post ? -420 : 0}" width="1080" height="1920" preserveAspectRatio="none"/>` +
232
+ body + footer(o, fill, footY, footY + 8));
233
+ }
234
+
235
+ const RENDER = { glow, "glow-streak": glowStreak, "model-twin": modelTwin, "top-artist": topArtist };
236
+ export function renderCard(style, format, stats, opts = {}) {
237
+ const [W, H] = FORMATS[format];
238
+ return RENDER[style](stats, opts, W, H);
239
+ }
@@ -0,0 +1,183 @@
1
+ // Reads Claude Code session transcripts and totals token usage for one year.
2
+ // Transcripts live in <config>/projects/<project>/<session>.jsonl (plus subagent
3
+ // transcripts in nested folders). Each assistant line carries message.usage.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import readline from "node:readline";
8
+
9
+ export function configDirs() {
10
+ const dirs = [];
11
+ if (process.env.CLAUDE_CONFIG_DIR) {
12
+ for (const d of process.env.CLAUDE_CONFIG_DIR.split(path.delimiter)) if (d) dirs.push(d);
13
+ }
14
+ dirs.push(path.join(os.homedir(), ".claude"));
15
+ dirs.push(path.join(os.homedir(), ".config", "claude"));
16
+ return [...new Set(dirs.map((d) => path.resolve(d)))].filter((d) => fs.existsSync(d));
17
+ }
18
+
19
+ function walkJsonl(dir, out = []) {
20
+ let entries;
21
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
22
+ for (const e of entries) {
23
+ const p = path.join(dir, e.name);
24
+ if (e.isDirectory()) walkJsonl(p, out);
25
+ else if (e.isFile() && e.name.endsWith(".jsonl")) out.push(p);
26
+ }
27
+ return out;
28
+ }
29
+
30
+ export function readCleanupPeriodDays(dirs) {
31
+ for (const d of dirs) {
32
+ try {
33
+ const s = JSON.parse(fs.readFileSync(path.join(d, "settings.json"), "utf8"));
34
+ if (typeof s.cleanupPeriodDays === "number") return s.cleanupPeriodDays;
35
+ } catch { /* no settings file */ }
36
+ }
37
+ return null; // Claude Code default is 30 days
38
+ }
39
+
40
+ export function prettyModel(id) {
41
+ if (!id) return "Unknown";
42
+ let m = id.match(/claude-(opus|sonnet|haiku|fable)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?/i);
43
+ if (m) return `${cap(m[1])} ${m[2]}${m[3] ? "." + m[3] : ""}`;
44
+ m = id.match(/claude-(\d+)(?:-(\d))?-(opus|sonnet|haiku)/i);
45
+ if (m) return `${cap(m[3])} ${m[1]}${m[2] ? "." + m[2] : ""}`;
46
+ return id.replace(/^claude-/, "");
47
+ }
48
+ const cap = (s) => s[0].toUpperCase() + s.slice(1).toLowerCase();
49
+
50
+ const dayKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
51
+
52
+ export async function collect({ year, dirs = configDirs() }) {
53
+ const files = dirs.flatMap((d) => walkJsonl(path.join(d, "projects")));
54
+ // message.id + requestId -> merged record. Claude Code writes one line per content
55
+ // block of a response, each repeating the usage, so we dedupe and keep the max.
56
+ const calls = new Map();
57
+ let earliestAny = null;
58
+
59
+ for (const file of files) {
60
+ const rl = readline.createInterface({ input: fs.createReadStream(file, "utf8"), crlfDelay: Infinity });
61
+ for await (const line of rl) {
62
+ if (!line.includes('"usage"')) continue;
63
+ let o;
64
+ try { o = JSON.parse(line); } catch { continue; }
65
+ const msg = o.message;
66
+ const u = msg && msg.usage;
67
+ if (!u || !o.timestamp) continue;
68
+ if (msg.model === "<synthetic>") continue;
69
+ const t = new Date(o.timestamp);
70
+ if (isNaN(t)) continue;
71
+ if (!earliestAny || t < earliestAny) earliestAny = t;
72
+ if (t.getFullYear() !== year) continue;
73
+ const key = msg.id || o.requestId ? `${msg.id || ""}:${o.requestId || ""}` : `${file}:${o.uuid}`;
74
+ const rec = calls.get(key) || {
75
+ t, model: msg.model, session: o.sessionId || path.basename(file, ".jsonl"),
76
+ project: o.cwd ? path.basename(o.cwd) : path.basename(path.dirname(file)),
77
+ input: 0, output: 0, cacheWrite: 0, cacheRead: 0,
78
+ };
79
+ rec.input = Math.max(rec.input, u.input_tokens || 0);
80
+ rec.output = Math.max(rec.output, u.output_tokens || 0);
81
+ rec.cacheWrite = Math.max(rec.cacheWrite, u.cache_creation_input_tokens || 0);
82
+ rec.cacheRead = Math.max(rec.cacheRead, u.cache_read_input_tokens || 0);
83
+ calls.set(key, rec);
84
+ }
85
+ }
86
+ return summarize([...calls.values()], { year, files: files.length, earliestAny, cleanupPeriodDays: readCleanupPeriodDays(dirs) });
87
+ }
88
+
89
+ export function summarize(records, { year, files = 0, earliestAny = null, cleanupPeriodDays = null }) {
90
+ const totals = { input: 0, output: 0, cacheWrite: 0, cacheRead: 0, total: 0 };
91
+ const sessions = new Set();
92
+ const days = new Map();
93
+ const projects = new Map();
94
+ const models = new Map();
95
+ const hours = new Array(24).fill(0);
96
+ const weekdays = new Array(7).fill(0);
97
+ let first = null, last = null;
98
+
99
+ for (const r of records) {
100
+ const sum = r.input + r.output + r.cacheWrite + r.cacheRead;
101
+ totals.input += r.input; totals.output += r.output;
102
+ totals.cacheWrite += r.cacheWrite; totals.cacheRead += r.cacheRead; totals.total += sum;
103
+ sessions.add(r.session);
104
+ const dk = dayKey(r.t);
105
+ days.set(dk, (days.get(dk) || 0) + sum);
106
+ projects.set(r.project, (projects.get(r.project) || 0) + sum);
107
+ const m = prettyModel(r.model);
108
+ models.set(m, (models.get(m) || 0) + sum);
109
+ hours[r.t.getHours()] += 1;
110
+ weekdays[r.t.getDay()] += 1;
111
+ if (!first || r.t < first) first = r.t;
112
+ if (!last || r.t > last) last = r.t;
113
+ }
114
+
115
+ const sortDesc = (map) => [...map.entries()].sort((a, b) => b[1] - a[1]);
116
+ const dayList = [...days.keys()].sort();
117
+ let streak = 0, run = 0, prev = null;
118
+ for (const d of dayList) {
119
+ const cur = new Date(d + "T12:00:00");
120
+ run = prev && (cur - prev) / 864e5 === 1 ? run + 1 : 1;
121
+ streak = Math.max(streak, run);
122
+ prev = cur;
123
+ }
124
+ const busiest = sortDesc(days)[0] || null;
125
+ const peakHour = records.length ? hours.indexOf(Math.max(...hours)) : null;
126
+ const wdNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
127
+ const favWeekday = records.length ? wdNames[weekdays.indexOf(Math.max(...weekdays))] : null;
128
+
129
+ // Coverage: Claude Code deletes transcripts older than cleanupPeriodDays (default 30),
130
+ // so the data may only reach back part of the year.
131
+ const startOfYear = new Date(year, 0, 1);
132
+ const partial = !!first && (first - startOfYear) / 864e5 > 14;
133
+
134
+ return {
135
+ year,
136
+ generatedAt: new Date().toISOString(),
137
+ filesScanned: files,
138
+ apiCalls: records.length,
139
+ totals,
140
+ sessions: sessions.size,
141
+ activeDays: days.size,
142
+ longestStreak: streak,
143
+ busiestDay: busiest ? { date: busiest[0], tokens: busiest[1] } : null,
144
+ peakHour,
145
+ favWeekday,
146
+ topProjects: sortDesc(projects).slice(0, 5).map(([name, tokens]) => ({ name, tokens })),
147
+ projectCount: projects.size,
148
+ models: sortDesc(models).map(([name, tokens]) => ({ name, tokens, share: totals.total ? tokens / totals.total : 0 })),
149
+ daily: Object.fromEntries([...days.entries()].sort()),
150
+ coverage: {
151
+ from: first ? dayKey(first) : null,
152
+ to: last ? dayKey(last) : null,
153
+ partial,
154
+ earliestTranscript: earliestAny ? dayKey(earliestAny) : null,
155
+ cleanupPeriodDays,
156
+ },
157
+ };
158
+ }
159
+
160
+ // Sample data for previews and tests (no real logs needed).
161
+ export function demoStats(year) {
162
+ const recs = [];
163
+ let seed = 7;
164
+ const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
165
+ const projects = ["nafida-design-system", "portfolio-site", "content-library", "api-gateway", "dotfiles"];
166
+ const models = ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"];
167
+ for (let d = 0; d < 340; d++) {
168
+ if (rnd() < 0.25) continue;
169
+ const day = new Date(year, 0, 1 + d);
170
+ const n = Math.floor(rnd() * 60) + 5;
171
+ for (let i = 0; i < n; i++) {
172
+ const t = new Date(day); t.setHours(9 + Math.floor(rnd() * 14), Math.floor(rnd() * 60));
173
+ const p = projects[Math.min(4, Math.floor(rnd() * rnd() * 6))];
174
+ const m = models[rnd() < 0.62 ? 0 : rnd() < 0.85 ? 1 : 2];
175
+ recs.push({ t, model: m, session: `${d}-${Math.floor(i / 12)}`, project: p,
176
+ input: Math.floor(rnd() * 400), output: Math.floor(rnd() * 2500),
177
+ cacheWrite: Math.floor(rnd() * 9000), cacheRead: Math.floor(rnd() * 55000) });
178
+ }
179
+ }
180
+ const s = summarize(recs, { year, files: 0, cleanupPeriodDays: 365 });
181
+ s.demo = true;
182
+ return s;
183
+ }
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env node
2
+ // Claude Code Wrapped: totals your Claude Code token usage for a year and renders
3
+ // Spotify Wrapped-style story (1080x1920) and post (1080x1080) cards.
4
+ // Usage: node wrapped.mjs [--year 2026] [--out DIR] [--styles glow,glow-streak,model-twin,top-artist]
5
+ // [--formats story,post] [--hide-projects] [--tagline "line one|line **two**"]
6
+ // [--title "My Tokens Burned"] [--handle "@you"] [--no-png] [--open] [--demo] [--json]
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import os from "node:os";
10
+ import { execFileSync, spawn } from "node:child_process";
11
+ import { collect, demoStats } from "./stats.mjs";
12
+ import { renderCard, STYLES, FORMATS, compact } from "./cards.mjs";
13
+
14
+ function parseArgs(argv) {
15
+ const o = { year: new Date().getFullYear(), styles: STYLES, formats: Object.keys(FORMATS), png: true };
16
+ // Claude may pass all arguments as one string; split it shell-style.
17
+ const toks = [];
18
+ for (const a of argv) {
19
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g; let m;
20
+ while ((m = re.exec(a))) toks.push(m[1] ?? m[2] ?? m[3]);
21
+ }
22
+ for (let i = 0; i < toks.length; i++) {
23
+ const a = toks[i], next = () => toks[++i];
24
+ if (/^\d{4}$/.test(a)) o.year = Number(a);
25
+ else if (a === "--year") o.year = Number(next());
26
+ else if (a === "--out") o.out = next();
27
+ else if (a === "--styles" || a === "--style") o.styles = next().split(",").filter((x) => STYLES.includes(x));
28
+ else if (a === "--formats" || a === "--format") o.formats = next().split(",").filter((x) => x in FORMATS);
29
+ else if (a === "--hide-projects") o.hideProjects = true;
30
+ else if (a === "--tagline") o.tagline = next();
31
+ else if (a === "--title") o.title = next();
32
+ else if (a === "--handle") o.handle = next();
33
+ else if (a === "--no-png") o.png = false;
34
+ else if (a === "--open") o.open = true;
35
+ else if (a === "--demo") o.demo = true;
36
+ else if (a === "--json") o.json = true;
37
+ else if (a === "--pretty") o.pretty = true;
38
+ }
39
+ if (!o.styles.length) o.styles = STYLES;
40
+ if (!o.formats.length) o.formats = Object.keys(FORMATS);
41
+ return o;
42
+ }
43
+
44
+ function findChrome() {
45
+ const c = [
46
+ process.env.CHROME_PATH,
47
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
48
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
49
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
50
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
51
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
52
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
53
+ "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
54
+ ].filter(Boolean);
55
+ for (const p of c) if (fs.existsSync(p)) return p;
56
+ for (const bin of ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"]) {
57
+ try { return execFileSync("which", [bin], { encoding: "utf8" }).trim(); } catch { /* not found */ }
58
+ }
59
+ return null;
60
+ }
61
+
62
+ function toPng(chrome, svgFile, pngFile, W, H) {
63
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "wrapped-chrome-"));
64
+ try {
65
+ execFileSync(chrome, ["--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
66
+ `--user-data-dir=${profile}`, `--window-size=${W},${H}`, "--force-device-scale-factor=1",
67
+ `--screenshot=${pngFile}`, "file://" + svgFile], { stdio: "ignore", timeout: 60000 });
68
+ return fs.existsSync(pngFile);
69
+ } catch { return false; } finally { fs.rmSync(profile, { recursive: true, force: true }); }
70
+ }
71
+
72
+ function gallery(stats, cards) {
73
+ const cov = stats.coverage;
74
+ const note = stats.demo ? "Sample data, not your real usage."
75
+ : cov.partial
76
+ ? `Your logs only go back to ${cov.from}. Claude Code deletes transcripts after ${cov.cleanupPeriodDays ?? 30} days by default, so raise <code>cleanupPeriodDays</code> in ~/.claude/settings.json to keep next year's full history.`
77
+ : `Covers ${cov.from} to ${cov.to}.`;
78
+ const items = cards.map((c) => `
79
+ <figure class="${c.format}">
80
+ <img src="data:image/svg+xml;base64,${Buffer.from(c.svg).toString("base64")}" width="${c.W}" height="${c.H}" alt="${c.style} ${c.format}">
81
+ <figcaption><span>${c.style} · ${c.format}</span>
82
+ <button onclick="png(this, ${c.W}, ${c.H}, '${c.name}.png')">Download PNG</button></figcaption>
83
+ </figure>`).join("");
84
+ return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
85
+ <title>Claude Code Wrapped ${stats.year}</title>
86
+ <style>
87
+ body{margin:0;background:#0f0f0e;color:#ecebe6;font:16px/1.5 system-ui,sans-serif}
88
+ header{max-width:1100px;margin:0 auto;padding:40px 24px 8px}
89
+ h1{margin:0 0 4px;font-size:32px} .note{color:#a9a89f;margin:0}
90
+ .stats{display:flex;flex-wrap:wrap;gap:24px;margin:16px 0 0;color:#cdf564;font-weight:600}
91
+ main{max-width:1100px;margin:0 auto;padding:24px;display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:28px}
92
+ figure{margin:0} img{width:100%;height:auto;border-radius:14px;display:block;box-shadow:0 8px 30px #0008}
93
+ figcaption{display:flex;justify-content:space-between;align-items:center;margin-top:10px;color:#a9a89f;text-transform:capitalize}
94
+ button{background:#cdf564;color:#141414;border:0;border-radius:99px;padding:7px 14px;font-weight:700;cursor:pointer}
95
+ </style></head><body>
96
+ <header><h1>Your ${stats.year} Claude Code Wrapped</h1><p class="note">${note}</p>
97
+ <div class="stats"><span>${compact(stats.totals.total)} tokens</span><span>${stats.sessions} sessions</span><span>${stats.activeDays} active days</span><span>${stats.longestStreak}-day streak</span></div></header>
98
+ <main>${items}</main>
99
+ <script>
100
+ async function png(btn, w, h, name){
101
+ const img = btn.closest('figure').querySelector('img');
102
+ const i = new Image(); i.src = img.src; await i.decode();
103
+ const c = document.createElement('canvas'); c.width = w; c.height = h;
104
+ c.getContext('2d').drawImage(i, 0, 0, w, h);
105
+ c.toBlob(b => { const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = name; a.click(); }, 'image/png');
106
+ }
107
+ </script></body></html>`;
108
+ }
109
+
110
+ // Human-readable summary for the npx command.
111
+ function pretty(s, out, html, cards, chrome, wantPng) {
112
+ const n = (x) => Math.round(x).toLocaleString("en-US");
113
+ const hour = s.peakHour == null ? "–" : `${s.peakHour % 12 || 12} ${s.peakHour < 12 ? "AM" : "PM"}`;
114
+ const L = [
115
+ "",
116
+ ` Claude Code Wrapped ${s.year}${s.demo ? " (sample data)" : ""}`,
117
+ "",
118
+ ` Tokens burned ${compact(s.totals.total)} (${n(s.totals.total)})`,
119
+ ` Sessions ${n(s.sessions)} over ${s.activeDays} active days`,
120
+ ` Longest streak ${s.longestStreak} days`,
121
+ s.busiestDay ? ` Busiest day ${s.busiestDay.date} (${compact(s.busiestDay.tokens)} tokens)` : null,
122
+ ` Peak hour ${hour}`,
123
+ s.models[0] ? ` Main model ${s.models[0].name}` : null,
124
+ s.topProjects[0] ? ` Top project ${s.topProjects[0].name}` : null,
125
+ "",
126
+ ` Cache reads are ${Math.round((100 * s.totals.cacheRead) / Math.max(1, s.totals.total))}% of the total.`,
127
+ ];
128
+ if (s.coverage?.partial) L.push(` Only covers ${s.coverage.from} to ${s.coverage.to}: Claude Code deletes logs after cleanupPeriodDays`,
129
+ ` (30 by default). Set "cleanupPeriodDays": 400 in ~/.claude/settings.json to keep a full year.`);
130
+ L.push("", ` ${cards.length} cards in ${out}`, ` Gallery: ${html}`);
131
+ if (wantPng && !chrome) L.push(" No Chrome/Edge found for PNGs: open the gallery and use the Download PNG buttons.");
132
+ return L.filter((x) => x !== null).join("\n") + "\n";
133
+ }
134
+
135
+ async function main() {
136
+ const o = parseArgs(process.argv.slice(2));
137
+ const stats = o.demo ? demoStats(o.year) : await collect({ year: o.year });
138
+ if (o.hideProjects) stats.topProjects = [];
139
+ if (o.json) { console.log(JSON.stringify(stats, null, 2)); return; }
140
+ if (!stats.apiCalls) {
141
+ if (o.pretty) {
142
+ console.error(`No Claude Code usage found for ${o.year} in ~/.claude/projects. Try --demo to see the cards with sample data.`);
143
+ process.exitCode = 2; return;
144
+ }
145
+ console.log(JSON.stringify({ error: `No Claude Code usage found for ${o.year}.`, filesScanned: stats.filesScanned, coverage: stats.coverage }, null, 2));
146
+ process.exitCode = 2; return;
147
+ }
148
+ const out = path.resolve(o.out || path.join(process.cwd(), `claude-wrapped-${o.year}`));
149
+ fs.mkdirSync(out, { recursive: true });
150
+ const chrome = o.png ? findChrome() : null;
151
+ const cards = [];
152
+ for (const style of o.styles) for (const format of o.formats) {
153
+ const [W, H] = FORMATS[format];
154
+ const name = `${style}-${format}`;
155
+ const svg = renderCard(style, format, stats, o);
156
+ const svgFile = path.join(out, name + ".svg");
157
+ fs.writeFileSync(svgFile, svg);
158
+ let pngFile = null;
159
+ if (chrome && toPng(chrome, svgFile, path.join(out, name + ".png"), W, H)) pngFile = path.join(out, name + ".png");
160
+ cards.push({ style, format, name, W, H, svg, svgFile, pngFile });
161
+ }
162
+ const { daily, ...rest } = stats;
163
+ fs.writeFileSync(path.join(out, "stats.json"), JSON.stringify(stats, null, 2));
164
+ const html = path.join(out, "index.html");
165
+ fs.writeFileSync(html, gallery(stats, cards));
166
+ if (o.open) {
167
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
168
+ const args = process.platform === "win32" ? ["/c", "start", "", html] : [html];
169
+ try { spawn(cmd, args, { detached: true, stdio: "ignore" }).unref(); } catch { /* ignore */ }
170
+ }
171
+ if (o.pretty) { console.log(pretty(stats, out, html, cards, chrome, o.png)); return; }
172
+ console.log(JSON.stringify({
173
+ outputDir: out, gallery: html,
174
+ pngs: cards.filter((c) => c.pngFile).map((c) => c.pngFile),
175
+ pngNote: chrome ? undefined : "No Chrome/Edge found for PNG export; open the gallery and use the Download PNG buttons.",
176
+ summary: { ...rest, totalCompact: compact(stats.totals.total), topProjects: stats.topProjects.slice(0, 3) },
177
+ }, null, 2));
178
+ }
179
+
180
+ main().catch((e) => { console.error(e.stack || String(e)); process.exit(1); });