@vibes.diy/prompts 14.3.265 → 14.3.267

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/llms/backend.md CHANGED
@@ -173,8 +173,12 @@ const gh = await ctx.github.fetch("/repos/acme/site/issues", { method: "POST", b
173
173
  const routes = await ctx.github.routes(); // [{ repo, accountLogin, binderHandle, installationId }] — who connected which repo; no GitHub call
174
174
  const session = await ctx.stripe.fetch("/v1/checkout/sessions", { method: "POST", body: form, mode: "test" }); // the owner's connected Stripe account
175
175
  const stripe = await ctx.stripe.status(); // { test: { available, state }, live: { available, state } }
176
+ const yt = await ctx.youtube.fetch("/channels?part=statistics&forHandle=@name"); // public YouTube Data API on the platform's key — no owner setup
177
+ const budget = await ctx.youtube.status(); // { available, unitsLeftToday, dailyUnits } — spends nothing
176
178
  ```
177
179
 
180
+ - An app that reads YouTube numbers loads the `youtube` skill: `ctx.youtube.fetch` for `channels`, `videos`, `playlistItems` and `playlists`, the app's daily unit budget and its `over_budget` refusal, and the evening-and-morning sampling behind an overnight recap.
181
+
178
182
  - An app that takes money loads the `stripe` skill (one-time charges) or the `stripe-subscriptions` skill (recurring): the Connect Stripe setup item, `ctx.stripe.fetch` with the order's `mode` on every call, hosted Checkout and a complete example.
179
183
  - The account a charge uses is the owner's per-app choice, a `setup:live` document the owner writes from the Setup screen; `ctx.stripe.status()` says which accounts are ready, and a ready live account alone leaves the app in test. The `stripe` skill carries that choice, the Setup screen and the sweep for buyers who never come back.
180
184
 
@@ -29,7 +29,7 @@ last two are always the same:
29
29
 
30
30
  - Open this vibe's **Settings** tab,
31
31
  `https://vibes.diy/vibes/mine/<ownerHandle>/<appSlug>/settings`, and under
32
- **Secrets** enter the name (`YOUTUBE_API_KEY`, in so many words), paste the
32
+ **Secrets** enter the name (`SPOTIFY_CLIENT_SECRET`, in so many words), paste the
33
33
  value, and save. From a terminal: `npx vibes-diy secrets set <NAME> --vibe <ownerHandle>/<appSlug>`.
34
34
  - Come back to the app: it works the moment the key is saved, with no redeploy.
35
35
 
package/llms/youtube.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export const youtubeConfig = {
2
2
  name: "youtube",
3
3
  label: "YouTube channel stats",
4
- description: "YouTube on a page: playing videos, playlists and a channel's uploads in YouTube's own player, which needs no key and no setup; and channel stats dashboards on the owner's own YouTube Data API v3 key: the setup steps the app shows when the key is missing, keeping the key in backend.js, resolving a channel from a handle or URL, reading videos through the uploads playlist instead of the 100-unit search endpoint, daily snapshots to chart change over time, and labeling the numbers an API key cannot see",
4
+ description: "YouTube on a page: playing videos, playlists and a channel's uploads in YouTube's own player, which needs no key and no setup; and channel stats on the platform's key with no key for the owner to create: ctx.youtube.fetch in backend.js and its daily unit budget, resolving a channel from a handle or URL, reading videos through the uploads playlist, evening and morning samples compared into a 9 a.m. overnight recap pushed with ctx.notify, 28-day sample retention, and labeling the numbers an API key cannot see",
5
5
  cues: [
6
6
  "youtube",
7
7
  "my channel",
@@ -13,8 +13,8 @@ export const youtubeConfig = {
13
13
  "youtube video",
14
14
  "youtube playlist",
15
15
  ],
16
- needs: ["owner-secret", "third-party-embed"],
17
- credential: "owner-secret",
16
+ needs: ["third-party-embed"],
17
+ credential: "platform",
18
18
  egress: [
19
19
  { url: "https://www.googleapis.com/youtube/v3/channels?part=statistics", via: "platform" },
20
20
  { url: "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ", via: "frame" },
@@ -1 +1 @@
1
- {"version":3,"file":"youtube.js","sourceRoot":"","sources":["../../jsr/llms/youtube.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,aAAa,GAAc;IACtC,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,uBAAuB;IAC9B,WAAW,EACT,wfAAwf;IAC1f,IAAI,EAAE;QACJ,SAAS;QACT,YAAY;QACZ,kBAAkB;QAClB,aAAa;QACb,aAAa;QACb,eAAe;QACf,mBAAmB;QACnB,eAAe;QACf,kBAAkB;KACnB;IAED,KAAK,EAAE,CAAC,cAAc,EAAE,mBAAmB,CAAC;IAC5C,UAAU,EAAE,cAAc;IAC1B,MAAM,EAAE;QACN,EAAE,GAAG,EAAE,gEAAgE,EAAE,GAAG,EAAE,UAAU,EAAE;QAC1F,EAAE,GAAG,EAAE,oDAAoD,EAAE,GAAG,EAAE,OAAO,EAAE;QAC3E,EAAE,GAAG,EAAE,gFAAgF,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE;KAC9H;CACF,CAAC"}
1
+ {"version":3,"file":"youtube.js","sourceRoot":"","sources":["../../jsr/llms/youtube.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,aAAa,GAAc;IACtC,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,uBAAuB;IAC9B,WAAW,EACT,kgBAAkgB;IACpgB,IAAI,EAAE;QACJ,SAAS;QACT,YAAY;QACZ,kBAAkB;QAClB,aAAa;QACb,aAAa;QACb,eAAe;QACf,mBAAmB;QACnB,eAAe;QACf,kBAAkB;KACnB;IAGD,KAAK,EAAE,CAAC,mBAAmB,CAAC;IAC5B,UAAU,EAAE,UAAU;IACtB,MAAM,EAAE;QAGN,EAAE,GAAG,EAAE,gEAAgE,EAAE,GAAG,EAAE,UAAU,EAAE;QAC1F,EAAE,GAAG,EAAE,oDAAoD,EAAE,GAAG,EAAE,OAAO,EAAE;QAC3E,EAAE,GAAG,EAAE,gFAAgF,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE;KAC9H;CACF,CAAC"}
package/llms/youtube.md CHANGED
@@ -1,13 +1,14 @@
1
- # YouTube — play videos with no key, chart a channel with the owner's own
1
+ # YouTube — play videos with no key, read a channel's numbers with no setup
2
2
 
3
3
  Two different asks share the name. **Playing** a video, a playlist or a
4
4
  channel's uploads inside the page needs no key, no backend and no setup: it is
5
5
  YouTube's own player in a frame, and section 0 is all of it. **Counting** a
6
- channel (subscribers, views, which videos are picking up) is the **YouTube Data
7
- API v3** on a key the owner supplies, a `backend.js` feature, and sections 1–7
8
- are the recipe that keeps the key safe, the quota survivable and the numbers
9
- honest. Build the first for "show our videos", "my band's page", "a playlist of
10
- clips"; build the second only when the ask is about the numbers.
6
+ channel (subscribers, views, which videos picked up overnight) is the **YouTube
7
+ Data API v3**, read from `backend.js` with `ctx.youtube.fetch`. Vibes holds the
8
+ key, so the owner pastes a channel link and the numbers arrive; sections 1–8 are
9
+ the recipe that keeps the budget comfortable and the numbers honest. Build the
10
+ first for "show our videos", "my band's page", "a playlist of clips"; build the
11
+ second when the ask is about the numbers.
11
12
 
12
13
  ## 0. Play a video: no key at all
13
14
 
@@ -43,85 +44,80 @@ function youtubeEmbedSrc(link) {
43
44
 
44
45
  - A **channel's uploads** play as one playlist: its id is the channel id with
45
46
  `UC` turned into `UU`. Only a `/channel/UC…` link carries that id; an
46
- `@handle` link does not, and turning a handle into an id costs a key, so ask
47
- for a video or playlist link, or the channel's `/channel/` address.
47
+ `@handle` link is turned into the id by one backend call (section 3), so a
48
+ page that only plays videos asks for a video or playlist link, or the
49
+ channel's `/channel/` address.
48
50
  - The title and thumbnail come from YouTube's keyless oEmbed endpoint,
49
51
  `https://www.youtube.com/oembed`, read once when the link is added.
50
52
  - Under each player, "Watch on YouTube" links the original
51
53
  `https://www.youtube.com/watch?v=<id>` (the shared link-out rule).
52
- - None of this touches the Data API, so none of the key sections below apply
53
- to a page that only plays videos.
54
+ - None of this touches the Data API, so a page that only plays videos needs
55
+ nothing from the sections below.
54
56
 
55
- **The stats half is the owner's dashboard:** the key and quota are the owner's,
56
- and every visitor sees the *owner's* channel. A visitor's own channel is a
57
- connection, never a pasted token (the owner-key rules below).
57
+ ## 1. `ctx.youtube.fetch`: the numbers with nothing to set up
58
58
 
59
- ## 1. The setup item: the owner's YouTube Data API key
59
+ Every YouTube Data API call is made in backend.js with ctx.youtube.fetch, which carries the platform's key, so the app asks its owner for no key and App.jsx never calls googleapis.com.
60
60
 
61
- The owner gets a key from Google, once. The Setup surface the item lands on —
62
- the owner-only entry in the app's navigation, the verdict from `/setup`, the
63
- re-read on focus that unlocks the dashboard in place — is the use-vibe docs'
64
- *Some apps need setup before they work*; this recipe contributes one item to
65
- it. The YouTube item is the API key: the backend answers missing-key while ctx.secrets.YOUTUBE_API_KEY is absent, and its steps link the Google Cloud console's YouTube Data API v3 library page and its Credentials page by URL and name YOUTUBE_API_KEY in so many words.
66
- The steps are written for someone who has never opened the console, so each
67
- one is a link to the exact page and uses the words that page uses:
68
-
69
- 1. Open the **YouTube Data API v3** page in the Google Cloud console:
70
- <https://console.cloud.google.com/apis/library/youtube.googleapis.com>
71
- (sign in with a Google account; create a project when it asks) and press
72
- **Enable**.
73
- 2. Open **Credentials**: <https://console.cloud.google.com/apis/credentials>.
74
- Press **Create credentials**, choose **API key**, and copy the key. Then
75
- open the key, and under **API restrictions** choose **Restrict key**, tick
76
- **YouTube Data API v3**, and save.
77
- 3. Save it under **Secrets** on this vibe's Settings tab as `YOUTUBE_API_KEY`,
78
- then come back: the owner-key steps every item ends with.
79
-
80
- In the consumer flow, a dashboard whose key is not set reads *Channel stats are
81
- not open yet*.
61
+ ```js
62
+ const res = await ctx.youtube.fetch("/channels?part=snippet,statistics,contentDetails&forHandle=@name");
63
+ const body = await res.json(); // Google's own JSON, Google's own status
64
+ ```
82
65
 
83
- ## 2. The key never reaches the browser
66
+ - The argument is a path rooted at the v3 resource (`/videos?part=statistics&id=a,b`)
67
+ or a full `https://www.googleapis.com/youtube/v3/…` URL. Leave `key=` off: the
68
+ platform adds its own.
69
+ - It reads `channels`, `videos`, `playlistItems` and `playlists`, with `GET`. Those
70
+ four answer every public-numbers question a channel app asks.
71
+ - It resolves a normal `Response`. A Google error (`quotaExceeded`, a bad
72
+ `part`) arrives as a `Response` with Google's status and `error` body, so
73
+ `res.ok` and `await res.json()` work as they do for any fetch.
74
+ - When the platform declines a call, the promise rejects with an Error whose
75
+ `reason` names why: `over_budget` (this app's units for the day are spent),
76
+ `unmodeled_endpoint` (a resource outside the four), `not_available` (this
77
+ deployment has no YouTube key right now), `unsupported_method`,
78
+ `invalid_path`, `body_too_large`, `upstream_error`.
79
+ - `await ctx.youtube.status()` answers `{ available, unitsLeftToday, dailyUnits }`
80
+ and spends nothing.
81
+
82
+ A YouTube stats app has no Setup item: there is no key to create and no Secrets step, so no page of the app asks for YOUTUBE_API_KEY.
83
+
84
+ The owner's first step is the app's own first screen: paste the channel link,
85
+ press **Track**, and the first readings land within the minute.
86
+
87
+ ## 2. A daily budget per app
88
+
89
+ Each app spends from its own budget of **2,000 units a day**, counted in UTC.
90
+ Every call to the four resources costs 1 unit. That is generous for one
91
+ channel: the overnight recap in section 5 spends about 110 units a day on a
92
+ 500-video channel.
93
+
94
+ When ctx.youtube refuses over_budget, the app keeps its last readings on screen and says sampling resumes at midnight UTC.
95
+
96
+ Write the moment down (a `status` doc with `resumesAt`), finish the tick
97
+ without writing a sample, and let the page say *Today's readings are in; the
98
+ next ones arrive after midnight UTC* with the local time beside it. The first
99
+ sample that lands after the reset deletes the `status` doc, and the page reads
100
+ a `status` whose `resumesAt` has passed as no status at all. Google's own
101
+ `quotaExceeded` (a 403 that reaches the app) pauses the same way, until
102
+ Google's reset at midnight Pacific.
84
103
 
85
- Every YouTube request is made in backend.js with ctx.fetch and ctx.secrets.YOUTUBE_API_KEY; App.jsx never calls googleapis.com.
104
+ ### The `/_api` routes are the second door
86
105
 
87
- A restricted key is still the owner's quota to spend.
106
+ A handler that calls YouTube on every request lets a visitor's refresh button
107
+ spend the app's units.
88
108
 
89
- ### The `/_api` routes are the second door
109
+ Live YouTube calls are made only by the scheduled tick or for the vibe owner; every other visitor is served from the stored samples, so a stranger can never spend the app's daily budget.
90
110
 
91
- A handler that calls Google on every request hands a stranger the owner's
92
- 10,000 daily units and a refresh button.
93
-
94
- Live YouTube calls are made only for the vibe owner; every other visitor is served from the stored snapshot, so a stranger can never spend the owner's quota.
95
-
96
- The owner gate is one comparison at the top of the handler (`isOwnerCall`).
97
- Everyone else is answered from the daily snapshot docs section 5 already writes —
98
- `{ ok: true, source: "snapshot", asOf: <day>, ... }`, so the client can say "as of
99
- Tuesday" instead of implying the numbers are live — and
100
- `{ ok: false, reason: "no-snapshot-yet" }` before the first tick has run. Nothing
101
- about a visitor's request reaches googleapis.com.
102
-
103
- Working out *which* channel the visitor meant has to be free too. Snapshots are
104
- stored under the resolved `UC…` id, and a visitor arrives with `?q=@handle` — so
105
- comparing the raw `q` against a stored id matches nothing, and resolving the
106
- handle with Google is the quota spend this gate exists to stop. The tracked
107
- channel doc (`type: "channel"`) therefore carries an `aliases` array: every
108
- spelling that names this channel — the `UC…` id, the `@handle` from
109
- `snippet.customUrl`, and any legacy username the owner connected it with — each
110
- lowercased. The visitor path normalizes `q` through the same `channelQuery`
111
- helper the owner path uses, lowercases what comes out, and looks for it among the
112
- tracked channels' aliases. That is a comparison against documents the app already
113
- holds, not a call.
114
-
115
- An empty `q` is not a failure either: it is the owner's dashboard as visitors see
116
- it, so answer with the newest snapshot of every tracked channel.
111
+ The owner gate is one comparison at the top of the `fetch` handler
112
+ (`isOwner`). Everyone else is answered from the docs the tick already wrote,
113
+ with `source: "stored"` and the time they were taken, so the page can say *as
114
+ of 7:58 a.m.* instead of implying the numbers are live.
117
115
 
118
116
  That visitor read happens on the `fetch` lane, which reads nothing for an
119
117
  anonymous caller and cannot read an access-fn-bound database until the
120
118
  backend opts in, so the recipe declares
121
119
  `config.fetch.unfilteredReads = { dbs: ["youtube"], why: ... }` (see the
122
- backend docs). The obligation that comes with it is small here: the snapshot
123
- docs hold only a channel's public numbers, and the handler serves nothing else
124
- from that database.
120
+ backend docs). The docs it serves hold only a channel's public numbers.
125
121
 
126
122
  ## 3. Resolve a channel from whatever the person pastes
127
123
 
@@ -129,118 +125,103 @@ People arrive with a handle, a URL, or a raw id. Normalize before you call:
129
125
 
130
126
  | What they paste | What you call |
131
127
  | --- | --- |
132
- | `UC…` (24 chars, starts `UC`) | `channels?id=UC…` |
133
- | `@handle`, or `youtube.com/@handle` | `channels?forHandle=@handle` |
134
- | `youtube.com/channel/UC…` | `channels?id=UC…` |
135
- | `youtube.com/user/name` (legacy) | `channels?forUsername=name` |
128
+ | `UC…` (24 chars, starts `UC`) | `/channels?id=UC…` |
129
+ | `@handle`, or `youtube.com/@handle` | `/channels?forHandle=@handle` |
130
+ | `youtube.com/channel/UC…` | `/channels?id=UC…` |
131
+ | `youtube.com/user/name` (legacy) | `/channels?forUsername=name` |
136
132
 
137
- The request:
138
-
139
- ```
140
- GET https://www.googleapis.com/youtube/v3/channels
141
- ?part=snippet,statistics,contentDetails
142
- &forHandle=@name
143
- &key=<YOUTUBE_API_KEY>
144
- ```
145
-
146
- `snippet` carries the title, description and thumbnails; `statistics` carries
133
+ Ask for `part=snippet,statistics,contentDetails`. `snippet` carries the title,
134
+ the `@handle` (`customUrl`) and thumbnails; `statistics` carries
147
135
  `subscriberCount`, `viewCount`, `videoCount` and `hiddenSubscriberCount`;
148
- `contentDetails.relatedPlaylists.uploads` is the uploads playlist id you need
149
- for the video list. An empty `items` array means no such channel — say that, and
150
- keep the input on screen so the person can fix it.
136
+ `contentDetails.relatedPlaylists.uploads` is the uploads playlist id the video
137
+ list comes from. An empty `items` array means no channel matched: keep the input
138
+ on screen with *No channel by that name — try the link from the channel page*.
151
139
 
152
- ## 4. Video performance without burning quota
140
+ ## 4. Video performance through the uploads playlist
153
141
 
154
142
  Read videos through the uploads playlist (playlistItems, then videos?part=statistics) and never through search, which costs 100 quota units per call.
155
143
 
156
- The default daily quota is 10,000 units, and `channels`,
157
- `playlistItems` and `videos` cost 1 unit each, so a full refresh of a channel
158
- with 50 recent videos costs about 3 units. One `search` call costs 100 and
159
- returns less.
144
+ `ctx.youtube` offers the two that cost 1 unit each:
160
145
 
161
146
  ```
162
- GET .../youtube/v3/playlistItems?part=contentDetails&playlistId=<uploads>&maxResults=50&key=…
163
- GET .../youtube/v3/videos?part=snippet,statistics&id=<up to 50 comma-joined ids>&key=…
147
+ /playlistItems?part=contentDetails&playlistId=<uploads>&maxResults=50&pageToken=<next>
148
+ /videos?part=snippet,statistics&id=<up to 50 comma-joined ids>
164
149
  ```
165
150
 
166
- "Gaining attention" is a comparison, not a field: take each video's current
167
- `viewCount` and subtract the `viewCount` the previous snapshot stored for the
168
- same video id. Rank by that delta, and label the list with the window it covers
169
- ("since yesterday's snapshot"). With one snapshot on file there is no delta yet —
170
- say "first snapshot saved, changes appear tomorrow" rather than showing zeros.
151
+ The uploads playlist lists newest first. A full catalog is pages of 50 until
152
+ `nextPageToken` runs out (stop at 500 videos), then `videos` in batches of 50;
153
+ the latest uploads are one `playlistItems` page with `maxResults=10` and one
154
+ `videos` call.
171
155
 
172
156
  Counts arrive as strings. `Number(stats.viewCount ?? 0)` before you do arithmetic.
173
157
 
174
- ## 5. A daily snapshot the app can chart
158
+ ## 5. The overnight recap: sample, compare, push
175
159
 
176
- The scheduled tick writes one snapshot doc per channel per day under a fixed _id, and skips the write when nothing changed.
160
+ "Which video picked up overnight" is a comparison between two readings, so the
161
+ recipe is a schedule of samples:
177
162
 
178
- The fixed `_id` is what makes the tick idempotent: it can run every hour, and the day's row is written once and
179
- then left alone.
163
+ - **Full catalog** (up to 500 videos): once when the owner presses Track, every
164
+ **evening** (9 p.m. in the owner's time zone) and every **morning** (7 a.m.).
165
+ Each full reading also re-reads the channel (1 unit) and saves its
166
+ subscribers, views and video count, so the totals on screen move with it.
167
+ - **Latest 10 uploads**: every hour, so a new video's first day is charted
168
+ closely.
169
+ - **The recap**: at 9 a.m., compare the morning sample with last evening's and
170
+ push the owner the winner.
180
171
 
181
172
  ```js
182
173
  export const config = { scheduled: { interval: "1h" } };
183
174
  ```
184
175
 
185
- The doc:
176
+ One doc per sample, under a fixed `_id` per slot so a tick that runs twice
177
+ writes once:
186
178
 
187
179
  ```js
188
180
  {
189
- _id: `snapshot-${channelId}-${day}`, // day is YYYY-MM-DD
190
- type: "snapshot",
191
- channelDay: `${channelId}|${day}`, // one channel's history, readable by prefix
192
- day,
181
+ _id: `sample-${channelId}-${day}-morning`, // or -evening, -setup, -hour-07
182
+ type: "sample",
183
+ kind: "full", // or "recent"
193
184
  channelId,
194
- title, // so a visitor's snapshot answer can name the channel
195
- subscribers,
196
- views,
197
- videoCount,
198
- videos: [{ id, title, views, likes, comments }],
185
+ takenAt: "2026-11-04T07:58:12.000Z",
186
+ views: { [videoId]: 1234 }, // one number per video
187
+ titles: { [videoId]: "Title" },
199
188
  }
200
189
  ```
201
190
 
202
- Beside them sits one tracked-channel doc per channel — the list the tick sweeps
203
- and the list a visitor's `q` is resolved against:
191
+ Compare sample to sample, and name the window the two samples actually span.
204
192
 
205
- ```js
206
- {
207
- _id: `channel-${channelId}`,
208
- type: "channel",
209
- channelId,
210
- aliases: ["uc…", "@handle", "legacyname"], // lowercased, from section 2
211
- }
212
- ```
193
+ A recap that says *between 9:02 p.m. and 7:58 a.m.* reads true; one that says
194
+ *overnight* about a sample the tick took at noon does not. Take both times from
195
+ `takenAt`.
213
196
 
214
- `channelDay` is what keeps the reads channel-selective. Asking for
215
- `{ field: "type", key: "snapshot", limit: 200 }` and filtering in the handler
216
- reads every channel's whole history to answer about one of them, and goes blind
217
- as soon as the app tracks more days than the page holds. Ask for the rows you
218
- want instead:
197
+ A video first seen in the later sample is never ranked against zero.
198
+
199
+ It was published inside the window, so its whole count is new, not gained;
200
+ list it as *new since last night* beside the ranking instead.
201
+
202
+ The push is one `ctx.notify` to the owner, keyed by the day so a repeated tick
203
+ delivers once:
219
204
 
220
205
  ```js
221
- const page = await ctx.db.query({ db: DB, field: "channelDay", prefix: `${channelId}|`, limit: 100, after });
206
+ await ctx.notify({
207
+ toHandle: ctx.appInfo.ownerHandle,
208
+ body: `"${title}" gained ${gained.toLocaleString()} views between 9:02 p.m. and 7:58 a.m.`,
209
+ dedupeKey: `recap-${day}`,
210
+ path: `#recap-${day}`,
211
+ });
222
212
  ```
223
213
 
224
- and walk `after = page.next` to the end before picking the largest `day`. The
225
- tracked-channel read walks the same cursor. A filtered page can come back
226
- **empty and still carry `next`**, so the loop condition is the cursor, never
227
- emptiness (the backend docs spell this out).
214
+ Keep the recap as a doc (`type: "recap"`) as well, so the app's own screen
215
+ shows every morning's winner. Stamp it `deliveredAt` only after `ctx.notify`
216
+ succeeds: a tick that finds a recap without `deliveredAt` sends it again, and
217
+ the `dedupeKey` keeps a retry from reaching the owner twice.
228
218
 
229
- Point-read the existing doc by that `_id`, compare the tracked fields **and the
230
- per-video rows** — id, title, views, likes and comments — and return without
231
- writing when they all match. A channel whose subscriber and view totals sat still
232
- overnight can still have picked up likes, comments or a retitled video, and
233
- comparing only the channel totals would throw that day's change away. A tick that
234
- genuinely changes nothing writes nothing, which is the zero-churn rule from the
235
- backend docs.
219
+ Samples older than 28 days are deleted by the tick, because YouTube's developer policy keeps stored API data fresh for 28 days when the channel has not authorized the app.
236
220
 
237
- When the channel call succeeds but the video call fails, keep the rows the last
238
- snapshot stored and mark the doc `videosStale: true`. Writing `videos: []` over
239
- real rows lets one upstream blip erase a day of video history, and tomorrow's
240
- delta then reads every video as brand new.
241
-
242
- The client charts the history with `useLiveQuery("type", { key: "snapshot" })`,
243
- sorts by `day`, and draws subscribers and views over time.
221
+ The recap only ever needs last night's pair, and the chart reads well over four
222
+ weeks. Recap docs carry titles and view counts too, so the same sweep deletes a
223
+ recap once its `to` reading is older than 28 days, and the channel totals once
224
+ their `refreshedAt` is.
244
225
 
245
226
  ## 6. Label what an API key cannot see
246
227
 
@@ -249,9 +230,10 @@ An API key reads public data.
249
230
  Watch time, revenue, impressions, traffic sources and demographics need YouTube Analytics with OAuth and are labeled "Not available with an API key", never shown as zero.
250
231
 
251
232
  Give them their own section in the UI with that label, so the owner sees the
252
- boundary instead of believing the channel earned nothing.
233
+ boundary instead of believing the channel earned nothing. YouTube Studio shows
234
+ them, and they settle 48–72 hours after the fact.
253
235
 
254
- Two more honest labels:
236
+ Three more honest labels:
255
237
 
256
238
  - `statistics.hiddenSubscriberCount === true` means the channel hides the
257
239
  number. Show "hidden by the channel", not `0`.
@@ -263,77 +245,81 @@ Two more honest labels:
263
245
 
264
246
  ## 7. Errors keep their reason
265
247
 
266
- Google answers a refusal with `error.errors[0].reason`. Classify on it and pass
267
- the reason through:
248
+ Each answer has its own words:
268
249
 
269
- - `quotaExceeded` — "Daily quota used; resets at midnight Pacific."
270
- - `keyInvalid` or `API_KEY_INVALID` — say so, and point the owner at the Setup
271
- entry: the item reads *Done* because a value is present, and the value is wrong.
272
- - `accessNotConfigured` — "Enable YouTube Data API v3 on this key's project."
250
+ - `over_budget` (a refusal) — *Today's readings are in; the next ones arrive
251
+ after midnight UTC.*
252
+ - `quotaExceeded` (Google's 403) — YouTube's own daily quota for Vibes is
253
+ spent; same words, same keep-the-last-readings behavior.
254
+ - `not_available` (a refusal) — *Channel numbers are taking a short break;
255
+ your saved readings are all here.*
273
256
  - anything else — show the API's own `error.message`.
274
257
 
275
- The four cases above each have a different fix, so each keeps its own words.
258
+ ## 8. When an app outgrows its daily units
259
+
260
+ Almost no app does: one channel's recap spends about a twentieth of the
261
+ budget. An app that tracks dozens of channels can read with the owner's own
262
+ Google Cloud key instead: the owner saves it in Settings → Secrets as
263
+ `YOUTUBE_API_KEY`, and backend.js calls `https://www.googleapis.com/youtube/v3/…`
264
+ with `ctx.fetch`, adding `key=` from `ctx.secrets`, exactly as the owner-key
265
+ services do. Build it that way only when the app's own numbers ask for it.
276
266
 
277
267
  ## Complete backend.js
278
268
 
279
269
  ### `backend.js`
280
- ```js app=youtube-dashboard
270
+ ```js app=youtube-recap
281
271
  export const config = {
282
272
  scheduled: { interval: "1h" },
283
- // The visitor path below reads the snapshot docs on the fetch lane, which
284
- // reads nothing for a caller with no session unless the db is named here.
285
- // The snapshots hold only public channel numbers, so the obligation is light.
286
- fetch: { unfilteredReads: { dbs: ["youtube"], why: "serves public channel snapshots to visitors" } },
273
+ // Visitors read the stored samples and recaps on the fetch lane, which reads nothing for a caller
274
+ // with no session unless the db is named here. The docs hold only public channel numbers.
275
+ fetch: { unfilteredReads: { dbs: ["youtube"], why: "serves the channel's public readings to visitors" } },
287
276
  };
288
277
 
289
- const API = "https://www.googleapis.com/youtube/v3";
290
278
  const DB = "youtube";
279
+ const FULL_CATALOG_LIMIT = 500;
280
+ const EVENING_HOUR = 21;
281
+ const MORNING_HOUR = 7;
282
+ const RECAP_HOUR = 9;
283
+ const KEEP_DAYS = 28;
284
+
285
+ /** One Data API read. Google's errors carry their reason; ctx.youtube's refusals already do. */
286
+ async function yt(ctx, path) {
287
+ const res = await ctx.youtube.fetch(path);
288
+ const body = await res.json().catch(() => null);
289
+ if (res.ok && body) return body;
290
+ const err = new Error(body?.error?.message ?? `YouTube answered ${res.status}`);
291
+ err.reason = body?.error?.errors?.[0]?.reason ?? "unknown";
292
+ throw err;
293
+ }
294
+
295
+ /** Run one step; a refusal comes back as `{ ok: false, reason }` instead of ending the tick. */
296
+ async function attempt(work) {
297
+ try {
298
+ return { ok: true, value: await work() };
299
+ } catch (err) {
300
+ return { ok: false, reason: err?.reason ?? "unknown", message: err?.message ?? String(err) };
301
+ }
302
+ }
291
303
 
292
304
  function channelQuery(raw) {
293
305
  const q = String(raw ?? "").trim();
294
- const url = /^https?:\/\//i.test(q) ? q : "";
295
- const path = url ? new URL(url).pathname : q;
306
+ const typed = /^https?:\/\//i.test(q) ? new URL(q).pathname : q;
307
+ let path = typed; // decoded, so youtube.com/@caf%C3%A9 reads as @café
308
+ try { path = decodeURIComponent(typed); } catch { /* a stray % keeps the path as typed */ }
296
309
  const byId = /(?:^|\/)(UC[\w-]{22})(?:\/|$)/.exec(path);
297
- if (byId) return { forHandle: null, id: byId[1], forUsername: null };
298
- const byHandle = /(?:^|\/)@([\w.-]+)/.exec(path);
299
- if (byHandle) return { id: null, forHandle: `@${byHandle[1]}`, forUsername: null };
310
+ if (byId) return `id=${byId[1]}`;
300
311
  const byUser = /\/user\/([\w-]+)/.exec(path);
301
- if (byUser) return { id: null, forHandle: null, forUsername: byUser[1] };
302
- return { id: null, forHandle: `@${q.replace(/^@/, "")}`, forUsername: null };
303
- }
304
-
305
- const aliasKey = (value) => String(value ?? "").trim().toLowerCase();
306
-
307
- /** Every spelling that names this channel — the id, the @handle, and what the owner pasted. */
308
- function channelAliases(channel, raw) {
309
- const asked = channelQuery(raw);
310
- const all = [channel.channelId, channel.handle, asked.id, asked.forHandle, asked.forUsername, raw];
311
- return [...new Set(all.map(aliasKey).filter(Boolean))];
312
- }
313
-
314
- async function callYouTube(ctx, resource, params) {
315
- const key = ctx.secrets.YOUTUBE_API_KEY;
316
- if (!key) return { ok: false, reason: "missing-key" };
317
- const url = new URL(`${API}/${resource}`);
318
- for (const [k, v] of Object.entries(params)) if (v != null) url.searchParams.set(k, String(v));
319
- url.searchParams.set("key", key);
320
- const res = await ctx.fetch(url.toString(), { headers: { accept: "application/json" } });
321
- const body = await res.json().catch(() => null);
322
- if (res.status === 200 && body) return { ok: true, body };
323
- const failure = body?.error?.errors?.[0]?.reason ?? "unknown";
324
- return { ok: false, reason: failure, message: body?.error?.message ?? `HTTP ${res.status}` };
312
+ if (byUser) return `forUsername=${encodeURIComponent(byUser[1])}`;
313
+ const handle = /(?:^|\/)@([^/?#\s]+)/u.exec(path)?.[1] ?? q.replace(/^@/, ""); // any Unicode handle
314
+ return `forHandle=${encodeURIComponent(`@${handle}`)}`;
325
315
  }
326
316
 
327
317
  async function loadChannel(ctx, raw) {
328
- const result = await callYouTube(ctx, "channels", {
329
- part: "snippet,statistics,contentDetails",
330
- ...channelQuery(raw),
331
- });
332
- if (!result.ok) return result;
333
- const item = result.body.items?.[0];
334
- if (!item) return { ok: false, reason: "not-found", message: "No channel matches that handle or URL." };
318
+ const body = await yt(ctx, `/channels?part=snippet,statistics,contentDetails&${channelQuery(raw)}`);
319
+ const item = body.items?.[0];
320
+ if (!item) return null;
335
321
  const stats = item.statistics ?? {};
336
- const channel = {
322
+ return {
337
323
  channelId: item.id,
338
324
  title: item.snippet?.title ?? item.id,
339
325
  handle: item.snippet?.customUrl ?? null,
@@ -344,353 +330,323 @@ async function loadChannel(ctx, raw) {
344
330
  views: Number(stats.viewCount ?? 0),
345
331
  videoCount: Number(stats.videoCount ?? 0),
346
332
  };
347
- // The client stores these on the tracked-channel doc, so a visitor's `?q=@handle` resolves
348
- // against a document instead of costing a `channels?forHandle=` call.
349
- channel.aliases = channelAliases(channel, raw);
350
- return { ok: true, channel };
351
333
  }
352
334
 
353
- async function loadVideos(ctx, uploads) {
354
- const list = await callYouTube(ctx, "playlistItems", {
355
- part: "contentDetails",
356
- playlistId: uploads,
357
- maxResults: 50,
358
- });
359
- if (!list.ok) return list;
360
- const ids = (list.body.items ?? []).map((i) => i.contentDetails?.videoId).filter(Boolean);
361
- if (ids.length === 0) return { ok: true, videos: [] };
362
- const detail = await callYouTube(ctx, "videos", { part: "snippet,statistics", id: ids.join(",") });
363
- if (!detail.ok) return detail;
364
- const videos = (detail.body.items ?? []).map((v) => ({
365
- id: v.id,
366
- title: v.snippet?.title ?? v.id,
367
- published: v.snippet?.publishedAt ?? null,
368
- views: Number(v.statistics?.viewCount ?? 0),
369
- likes: v.statistics?.likeCount == null ? null : Number(v.statistics.likeCount),
370
- comments: v.statistics?.commentCount == null ? null : Number(v.statistics.commentCount),
371
- }));
372
- return { ok: true, videos };
373
- }
374
-
375
- /** Every page of a keyed read. `next` rides on the array, so take it before any array operation. */
376
- async function readAll(ctx, query) {
377
- const rows = [];
378
- let after;
335
+ /** Newest-first video ids from the uploads playlist, 50 a page, up to `limit`. */
336
+ async function uploadIds(ctx, uploads, limit) {
337
+ const ids = [];
338
+ let pageToken = "";
379
339
  do {
380
- const page = await ctx.db.query({ ...query, after });
381
- after = page.next;
382
- rows.push(...page);
383
- } while (after);
384
- return rows;
340
+ const size = Math.min(50, limit - ids.length);
341
+ const page = await yt(
342
+ ctx,
343
+ `/playlistItems?part=contentDetails&playlistId=${uploads}&maxResults=${size}${pageToken ? `&pageToken=${pageToken}` : ""}`,
344
+ );
345
+ ids.push(...(page.items ?? []).map((i) => i.contentDetails?.videoId).filter(Boolean));
346
+ pageToken = page.nextPageToken ?? "";
347
+ } while (pageToken && ids.length < limit);
348
+ return ids;
385
349
  }
386
350
 
387
- async function trackedChannels(ctx) {
388
- return readAll(ctx, { db: DB, field: "type", key: "channel", limit: 20 });
351
+ /** View counts and titles for `ids`, 50 per `videos` call. */
352
+ async function readViews(ctx, ids) {
353
+ const views = {};
354
+ const titles = {};
355
+ for (let i = 0; i < ids.length; i += 50) {
356
+ const body = await yt(ctx, `/videos?part=snippet,statistics&id=${ids.slice(i, i + 50).join(",")}`);
357
+ for (const v of body.items ?? []) {
358
+ views[v.id] = Number(v.statistics?.viewCount ?? 0);
359
+ titles[v.id] = v.snippet?.title ?? v.id;
360
+ }
361
+ }
362
+ return { views, titles };
389
363
  }
390
364
 
391
- /** One channel's history, selected by prefix rather than paged whole and filtered in the handler. */
392
- async function newestSnapshot(ctx, channelId) {
393
- const rows = await readAll(ctx, { db: DB, field: "channelDay", prefix: `${channelId}|`, limit: 100 });
394
- return rows.sort((a, b) => String(b.day).localeCompare(String(a.day)))[0] ?? null;
365
+ /** The local calendar day and hour in the owner's time zone. */
366
+ function localTime(ms, timeZone) {
367
+ const parts = Object.fromEntries(
368
+ new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hourCycle: "h23" })
369
+ .formatToParts(new Date(ms))
370
+ .map((p) => [p.type, p.value]),
371
+ );
372
+ return { day: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour) };
395
373
  }
396
374
 
397
- /** Does this tracked channel answer to what the visitor pasted? Comparison only — no call. */
398
- function matchesPastedQuery(row, raw) {
399
- const asked = channelQuery(raw);
400
- const wanted = [asked.id, asked.forHandle, asked.forUsername, raw].map(aliasKey).filter(Boolean);
401
- const aliases = (row.aliases ?? [row.channelId]).map(aliasKey);
402
- return wanted.some((w) => aliases.includes(w));
375
+ function clock(iso, timeZone) {
376
+ return new Date(iso).toLocaleTimeString("en-US", { timeZone, hour: "numeric", minute: "2-digit" });
403
377
  }
404
378
 
405
- function snapshotChannel(row) {
406
- return {
407
- channelId: row.channelId,
408
- title: row.title ?? row.channelId,
409
- subscribers: row.subscribers,
410
- views: row.views,
411
- videoCount: row.videoCount,
412
- };
379
+ /** Take one sample under a fixed slot id; a slot already taken is left alone. */
380
+ async function takeSample(ctx, settings, { slot, kind, limit }) {
381
+ const _id = `sample-${settings.channelId}-${slot}`;
382
+ if (await ctx.db.get(_id, { db: DB })) return { ok: true, skipped: true };
383
+ return attempt(async () => {
384
+ const ids = await uploadIds(ctx, settings.uploads, limit);
385
+ const { views, titles } = await readViews(ctx, ids);
386
+ const doc = { _id, type: "sample", kind, channelId: settings.channelId, takenAt: new Date().toISOString(), views, titles };
387
+ await ctx.db.put(doc, { db: DB });
388
+ return doc;
389
+ });
413
390
  }
414
391
 
415
- function json(payload, status = 200) {
416
- return new Response(JSON.stringify(payload), {
417
- status,
418
- headers: { "content-type": "application/json" },
419
- });
392
+ /** Rank last evening → this morning. A video missing from the earlier sample is new, never a gain from zero. */
393
+ function rankWindow(earlier, later) {
394
+ const gains = [];
395
+ const fresh = [];
396
+ for (const [id, now] of Object.entries(later.views)) {
397
+ if (earlier.views[id] === undefined) fresh.push({ id, title: later.titles[id], views: now });
398
+ else gains.push({ id, title: later.titles[id], gained: now - earlier.views[id] });
399
+ }
400
+ gains.sort((a, b) => b.gained - a.gained);
401
+ return { gains, fresh };
420
402
  }
421
403
 
422
- export async function fetch(request, ctx) {
423
- const url = new URL(request.url);
424
- if (request.method !== "GET") return new Response("method not allowed", { status: 405, headers: { allow: "GET" } });
404
+ async function sendRecap(ctx, settings, day, yesterday) {
405
+ const recapId = `recap-${day}`;
406
+ const existing = await ctx.db.get(recapId, { db: DB });
407
+ if (existing?.deliveredAt) return; // pushed already; an undelivered recap is sent again
408
+ const earlier = await ctx.db.get(`sample-${settings.channelId}-${yesterday}-evening`, { db: DB });
409
+ const later = await ctx.db.get(`sample-${settings.channelId}-${day}-morning`, { db: DB });
410
+ if (!earlier || !later) return; // the pair is not complete yet; the next tick looks again
411
+ const { gains, fresh } = rankWindow(earlier, later);
412
+ const top = gains[0];
413
+ const window = `between ${clock(earlier.takenAt, settings.timeZone)} and ${clock(later.takenAt, settings.timeZone)}`;
414
+ const body = top
415
+ ? `"${top.title}" gained ${top.gained.toLocaleString()} views ${window}.`
416
+ : `Your readings ${window} are in.`;
417
+ const recap = { _id: recapId, type: "recap", day, from: earlier.takenAt, to: later.takenAt, top: gains.slice(0, 5), fresh, body, deliveredAt: null };
418
+ await ctx.db.put(recap, { db: DB }); // the screen shows it now, pushed or not
419
+ await deliverRecap(ctx, recap);
420
+ }
425
421
 
426
- const isOwner = ctx.userInfo?.userHandle != null && ctx.userInfo.userHandle === ctx.appInfo.ownerHandle;
422
+ /** Push a stored recap; it is stamped deliveredAt only once ctx.notify succeeds, and the dedupeKey makes a retry safe. */
423
+ async function deliverRecap(ctx, recap) {
424
+ const sent = await attempt(() =>
425
+ ctx.notify({ toHandle: ctx.appInfo.ownerHandle, body: recap.body, dedupeKey: recap._id, path: `#${recap._id}` }),
426
+ );
427
+ if (!sent.ok) return ctx.log("warn", "recap push failed; the next tick sends it again", { id: recap._id, reason: sent.reason });
428
+ await ctx.db.put({ ...recap, deliveredAt: new Date().toISOString() }, { db: DB });
429
+ }
427
430
 
428
- // The setup verdict: ready for everyone, the item (and the handle + slug the Setup screen links
429
- // with) for the owner alone. No live call, so it sits in front of the owner gate.
430
- if (url.pathname === "/setup") {
431
- const items = [{ id: "youtube-key", label: "YouTube Data API v3 key", done: Boolean(ctx.secrets.YOUTUBE_API_KEY) }];
432
- const ready = items.every((item) => item.done);
433
- if (isOwner) return json({ ok: true, ready, owner: isOwner, items, ownerHandle: ctx.appInfo.ownerHandle, appSlug: ctx.appInfo.appSlug });
434
- return json({ ok: true, ready, owner: isOwner });
435
- }
436
-
437
- // Anyone who is not the owner is answered from what the tick already stored, and the channel they
438
- // asked for is resolved against the tracked docs' aliases. Nothing here reaches googleapis.com, so
439
- // a stranger with a refresh button cannot spend the owner's daily quota.
440
- if (!isOwner) {
441
- const asked = url.searchParams.get("channelId") ?? url.searchParams.get("q") ?? "";
442
- const tracked = await trackedChannels(ctx);
443
- const wanted = asked.trim() === "" ? tracked : tracked.filter((row) => matchesPastedQuery(row, asked));
444
- const newest = [];
445
- for (const row of wanted) {
446
- const snapshot = await newestSnapshot(ctx, row.channelId);
447
- if (snapshot) newest.push(snapshot);
448
- }
449
- if (newest.length === 0) return json({ ok: false, reason: "no-snapshot-yet" });
450
- if (url.pathname === "/channel") {
451
- return json({
452
- ok: true,
453
- source: "snapshot",
454
- asOf: newest.map((r) => String(r.day)).sort().at(-1),
455
- channel: snapshotChannel(newest[0]),
456
- channels: newest.map(snapshotChannel),
457
- });
458
- }
459
- if (url.pathname === "/videos") {
460
- return json({
461
- ok: true,
462
- source: "snapshot",
463
- asOf: newest[0].day,
464
- videos: newest[0].videos ?? [],
465
- videosStale: newest[0].videosStale === true,
466
- });
467
- }
468
- return new Response("not found", { status: 404 });
431
+ /**
432
+ * Samples and recaps older than 28 days go, so stored readings stay inside YouTube's freshness
433
+ * window. A sample is dated by `takenAt`, a recap by `to`, the channel totals by `refreshedAt`.
434
+ */
435
+ async function pruneOldReadings(ctx, nowMs) {
436
+ const cutoff = new Date(nowMs - KEEP_DAYS * 24 * 3600 * 1000).toISOString();
437
+ const settings = await ctx.db.get("settings", { db: DB });
438
+ if (settings?.channel && String(settings.channel.refreshedAt) < cutoff) await ctx.db.put({ ...settings, channel: null }, { db: DB });
439
+ for (const [type, dateField] of [["sample", "takenAt"], ["recap", "to"]]) {
440
+ let after;
441
+ do {
442
+ const page = await ctx.db.query({ db: DB, field: "type", key: type, limit: 100, after });
443
+ after = page.next;
444
+ for (const doc of page) if (String(doc[dateField]) < cutoff) await ctx.db.delete(doc._id, { db: DB });
445
+ } while (after);
469
446
  }
447
+ }
470
448
 
471
- if (url.pathname === "/channel") {
472
- const result = await loadChannel(ctx, url.searchParams.get("q"));
473
- return json(result.ok ? { ...result, source: "live" } : result);
474
- }
449
+ // The UTC hour each budget resets: the app's own at midnight UTC (over_budget), Google's project
450
+ // quota at midnight Pacific (quotaExceeded, a 403 that ctx.youtube passes through).
451
+ const RESET_UTC_HOUR = { over_budget: 0, quotaExceeded: 8 };
475
452
 
476
- if (url.pathname === "/videos") {
477
- const channel = await loadChannel(ctx, url.searchParams.get("channelId"));
478
- if (!channel.ok) return json(channel);
479
- if (!channel.channel.uploads) return json({ ok: true, source: "live", videos: [] });
480
- const videos = await loadVideos(ctx, channel.channel.uploads);
481
- return json(videos.ok ? { ...videos, source: "live" } : videos);
482
- }
453
+ async function notePause(ctx, nowMs, reason) {
454
+ const resumesAt = new Date(nowMs);
455
+ resumesAt.setUTCHours(RESET_UTC_HOUR[reason], 0, 0, 0);
456
+ if (resumesAt.getTime() <= nowMs) resumesAt.setUTCDate(resumesAt.getUTCDate() + 1);
457
+ await ctx.db.put({ _id: "status", type: "status", reason, resumesAt: resumesAt.toISOString() }, { db: DB });
458
+ }
483
459
 
484
- return new Response("not found", { status: 404 });
460
+ /** A sample landed, so the budget is back: the "resumes at midnight" note comes down. */
461
+ async function clearStatus(ctx) {
462
+ if (await ctx.db.get("status", { db: DB })) await ctx.db.delete("status", { db: DB });
485
463
  }
486
464
 
487
- /** Stable across key order and list order, so only a real change looks like one. */
488
- function videoFingerprint(videos) {
489
- return JSON.stringify(
490
- (videos ?? [])
491
- .map((v) => [v.id, v.title, v.views, v.likes, v.comments])
492
- .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
493
- );
465
+ /** The stored note, unless its resumesAt has passed. */
466
+ async function currentStatus(ctx) {
467
+ const status = await ctx.db.get("status", { db: DB });
468
+ return status && Date.parse(status.resumesAt) > Date.now() ? status : null;
494
469
  }
495
470
 
496
- function sameSnapshot(existing, next) {
497
- if (!existing) return false;
498
- const totals = ["subscribers", "views", "videoCount"].every((k) => existing[k] === next[k]);
499
- return totals && videoFingerprint(existing.videos) === videoFingerprint(next.videos);
471
+ /** Channel totals ride along with each full reading (1 unit), so subscribers and views keep moving. */
472
+ async function refreshChannel(ctx, settings) {
473
+ const fresh = await attempt(() => loadChannel(ctx, settings.channelId));
474
+ if (fresh.ok && fresh.value) {
475
+ await ctx.db.put({ ...settings, channel: { ...fresh.value, refreshedAt: new Date().toISOString() } }, { db: DB });
476
+ }
477
+ return fresh;
500
478
  }
501
479
 
502
480
  export async function scheduled(event, ctx) {
503
- const tracked = await trackedChannels(ctx);
504
- const day = new Date(event.scheduledTime ?? Date.now()).toISOString().slice(0, 10);
505
- for (const row of tracked) {
506
- const channel = await loadChannel(ctx, row.channelId);
507
- if (!channel.ok) {
508
- ctx.log("warn", "youtube refresh failed", { channelId: row.channelId, reason: channel.reason });
509
- continue;
510
- }
511
- const videos = channel.channel.uploads ? await loadVideos(ctx, channel.channel.uploads) : { ok: true, videos: [] };
512
- const id = `snapshot-${channel.channel.channelId}-${day}`;
513
- const existing = await ctx.db.get(id, { db: DB });
514
- // A failed video call keeps the last good rows. Writing `videos: []` over them would erase a
515
- // day of history for one upstream blip, and tomorrow's delta would read every video as new.
516
- const lastGood = existing?.videos ?? (await newestSnapshot(ctx, channel.channel.channelId))?.videos ?? [];
517
- const next = {
518
- _id: id,
519
- type: "snapshot",
520
- channelDay: `${channel.channel.channelId}|${day}`,
521
- day,
522
- channelId: channel.channel.channelId,
523
- title: channel.channel.title,
524
- subscribers: channel.channel.subscribers,
525
- views: channel.channel.views,
526
- videoCount: channel.channel.videoCount,
527
- videos: videos.ok
528
- ? videos.videos.map((v) => ({ id: v.id, title: v.title, views: v.views, likes: v.likes, comments: v.comments }))
529
- : lastGood,
530
- };
531
- if (!videos.ok) {
532
- next.videosStale = true;
533
- ctx.log("warn", "youtube videos refresh failed; keeping the last good rows", {
534
- channelId: channel.channel.channelId,
535
- reason: videos.reason,
536
- });
481
+ const settings = await ctx.db.get("settings", { db: DB });
482
+ if (!settings?.uploads) return; // nothing tracked yet
483
+ const nowMs = event.scheduledTime ? new Date(event.scheduledTime).getTime() : Date.now();
484
+ const { day, hour } = localTime(nowMs, settings.timeZone);
485
+ const yesterday = localTime(nowMs - 24 * 3600 * 1000, settings.timeZone).day;
486
+
487
+ const steps = [{ slot: `${day}-hour-${String(hour).padStart(2, "0")}`, kind: "recent", limit: 10 }];
488
+ if (hour >= MORNING_HOUR && hour < EVENING_HOUR) steps.push({ slot: `${day}-morning`, kind: "full", limit: FULL_CATALOG_LIMIT });
489
+ if (hour >= EVENING_HOUR) steps.push({ slot: `${day}-evening`, kind: "full", limit: FULL_CATALOG_LIMIT });
490
+ for (const step of steps) {
491
+ const taken = await takeSample(ctx, settings, step);
492
+ // A full reading that just landed re-reads the channel too; its refusal is handled like the sample's.
493
+ const outcome = taken.ok && !taken.skipped && step.kind === "full" ? await refreshChannel(ctx, settings) : taken;
494
+ if (!outcome.ok && Object.hasOwn(RESET_UTC_HOUR, outcome.reason)) {
495
+ await notePause(ctx, nowMs, outcome.reason); // over_budget or quotaExceeded: keep the last readings, say when the next arrive
496
+ break;
537
497
  }
538
- if (sameSnapshot(existing, next)) continue;
539
- await ctx.db.put(next, { db: DB });
498
+ if (!outcome.ok) ctx.log("warn", "youtube read failed", { slot: step.slot, reason: outcome.reason });
499
+ if (taken.ok && !taken.skipped) await clearStatus(ctx);
500
+ }
501
+ if (hour >= RECAP_HOUR) await sendRecap(ctx, settings, day, yesterday);
502
+ const late = await ctx.db.get(`recap-${yesterday}`, { db: DB }); // yesterday's push, if it never went out
503
+ if (late && !late.deliveredAt) await deliverRecap(ctx, late);
504
+ await pruneOldReadings(ctx, nowMs);
505
+ }
506
+
507
+ function json(payload, status = 200) {
508
+ return new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });
509
+ }
510
+
511
+ /** Every stored recap, newest first: at most 28 days of them, since the sweep removes older ones. */
512
+ async function recapHistory(ctx) {
513
+ const rows = [];
514
+ let after;
515
+ do {
516
+ const page = await ctx.db.query({ db: DB, field: "type", key: "recap", limit: 100, after });
517
+ after = page.next;
518
+ rows.push(...page);
519
+ } while (after);
520
+ return rows.sort((a, b) => String(b.day).localeCompare(String(a.day)));
521
+ }
522
+
523
+ export async function fetch(request, ctx) {
524
+ const url = new URL(request.url);
525
+ const isOwner = ctx.userInfo?.userHandle != null && ctx.userInfo.userHandle === ctx.appInfo.ownerHandle;
526
+
527
+ // Everyone but the owner reads what the tick already stored. Nothing here reaches YouTube, so a
528
+ // visitor's refresh button never spends the app's daily units.
529
+ if (!isOwner) {
530
+ const settings = await ctx.db.get("settings", { db: DB });
531
+ const status = await currentStatus(ctx);
532
+ return json({ ok: true, owner: false, source: "stored", channel: settings?.channel ?? null, recaps: await recapHistory(ctx), status });
533
+ }
534
+
535
+ if (request.method === "POST" && url.pathname === "/track") {
536
+ const { link, timeZone } = await request.json();
537
+ const found = await attempt(() => loadChannel(ctx, link));
538
+ if (!found.ok) return json({ ok: false, reason: found.reason, message: found.message });
539
+ if (!found.value) return json({ ok: false, reason: "not-found", message: "No channel by that name — try the link from the channel page." });
540
+ const channel = { ...found.value, refreshedAt: new Date().toISOString() };
541
+ const settings = { _id: "settings", type: "settings", channelId: channel.channelId, uploads: channel.uploads, timeZone: timeZone || "UTC", channel };
542
+ await ctx.db.put(settings, { db: DB });
543
+ const first = await takeSample(ctx, settings, { slot: `setup-${Date.now()}`, kind: "full", limit: FULL_CATALOG_LIMIT });
544
+ if (!first.ok && Object.hasOwn(RESET_UTC_HOUR, first.reason)) await notePause(ctx, Date.now(), first.reason);
545
+ // Tracking is saved either way; firstSample tells the page whether the first readings are in yet.
546
+ return json({ ok: true, owner: true, source: "live", channel, firstSample: first.ok ? "saved" : first.reason });
540
547
  }
548
+
549
+ const settings = await ctx.db.get("settings", { db: DB });
550
+ return json({
551
+ ok: true,
552
+ owner: true,
553
+ source: "stored",
554
+ channel: settings?.channel ?? null,
555
+ recaps: await recapHistory(ctx),
556
+ status: await currentStatus(ctx),
557
+ budget: await ctx.youtube.status(), // spends nothing
558
+ });
541
559
  }
542
560
  ```
543
561
 
544
562
  ## App.jsx sketch
545
563
 
546
564
  ### `App.jsx`
547
- ```jsx app=youtube-dashboard
548
- import React, { useEffect, useRef, useState } from "react";
549
- import { useFireproof } from "use-fireproof";
565
+ ```jsx app=youtube-recap
566
+ import React, { useEffect, useState } from "react";
550
567
  import { apiFetch } from "use-vibes";
551
- import { Badge, Button, Field, Heading, Input, Row, Stack, Text } from "@vibes.diy/ui";
568
+ import { Button, Field, Heading, Input, Row, Stack, Text } from "@vibes.diy/ui";
552
569
 
553
- // The setup verdict, read on mount and again whenever the app comes back into view: the owner
554
- // sets the key in another tab and returns, and the dashboard unlocks without a reload.
555
- function useSetup() {
556
- const [setup, setSetup] = useState(null); // { ready, owner, items?, ownerHandle?, appSlug? }
557
- const latest = useRef(0);
558
- useEffect(() => {
559
- // Mount, focus and visibility reads overlap; only the latest one may land, or a slow stale
560
- // answer overwrites a fresh one.
561
- const load = () => {
562
- const n = ++latest.current;
563
- apiFetch("/setup").then((r) => r.json()).catch(() => ({ ready: false, owner: false })).then((s) => { if (n === latest.current) setSetup(s); });
564
- };
565
- load();
566
- const onVisible = () => { if (document.visibilityState === "visible") load(); };
567
- document.addEventListener("visibilitychange", onVisible);
568
- window.addEventListener("focus", load);
569
- return () => { document.removeEventListener("visibilitychange", onVisible); window.removeEventListener("focus", load); };
570
- }, []);
571
- return setup;
572
- }
570
+ export default function App() {
571
+ // Owner and visitor alike read the backend's answer, which carries the recap history.
572
+ const [view, setView] = useState(null); // { owner, channel, recaps, status, budget }
573
+ const [link, setLink] = useState("");
574
+ const [note, setNote] = useState(null);
573
575
 
574
- // The Setup surface, the owner's alone: one item, every step a link to the exact page in that
575
- // page's own words, with this vibe's real handle and slug filled in.
576
- function SetupScreen({ setup }) {
577
- const vibe = `${setup.ownerHandle}/${setup.appSlug}`;
578
- const settingsUrl = `https://vibes.diy/vibes/mine/${vibe}/settings`;
579
- const key = setup.items.find((item) => item.id === "youtube-key");
580
- return (
581
- <Stack>
582
- <Heading>Setup</Heading>
583
- <Row gap={2}>
584
- <Text>{key.label}</Text>
585
- <Badge tone={key.done ? "up" : "info"}>{key.done ? "Done" : "To do"}</Badge>
586
- </Row>
587
- <ol>
588
- <li>
589
- Open the <a href="https://console.cloud.google.com/apis/library/youtube.googleapis.com" target="_blank" rel="noreferrer">YouTube Data API v3 page</a> in the Google Cloud console
590
- (use your Google account; create a project when it asks) and press <b>Enable</b>.
591
- </li>
592
- <li>
593
- Open <a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noreferrer">Credentials</a>, press <b>Create credentials</b>, choose <b>API key</b>, and copy it.
594
- Then open the key, and under <b>API restrictions</b> choose <b>Restrict key</b>, tick <b>YouTube Data API v3</b>, and save.
595
- </li>
596
- <li>
597
- Open <a href={settingsUrl} target="_blank" rel="noreferrer">this vibe's Settings tab</a> (My Vibes → this vibe → Settings).
598
- Under <b>Secrets</b>, enter the key <code>YOUTUBE_API_KEY</code>, paste the value, and save.
599
- From a terminal instead: <code>npx vibes-diy secrets set YOUTUBE_API_KEY --vibe {vibe}</code>.
600
- </li>
601
- <li>Come back here: the dashboard works as soon as the key is saved. The key stays on the server.</li>
602
- </ol>
603
- </Stack>
604
- );
605
- }
576
+ const load = () => apiFetch("/").then((r) => r.json()).then(setView).catch(() => setView({ owner: false }));
577
+ useEffect(() => { load(); }, []);
606
578
 
607
- export default function App() {
608
- const { useLiveQuery, database } = useFireproof("youtube");
609
- const { docs: snapshots } = useLiveQuery("type", { key: "snapshot" });
610
- const setup = useSetup();
611
- const [screen, setScreen] = useState("dashboard");
612
- const [input, setInput] = useState("");
613
- const [channel, setChannel] = useState(null);
614
- const [problem, setProblem] = useState(null);
615
- const [source, setSource] = useState(null);
616
- const [asOf, setAsOf] = useState(null);
617
- const ready = setup?.ready === true;
618
-
619
- const connect = async () => {
620
- const res = await fetch(`/_api/channel?q=${encodeURIComponent(input)}`);
579
+ const track = async () => {
580
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
581
+ const res = await apiFetch("/track", { method: "POST", body: JSON.stringify({ link, timeZone }) });
621
582
  const data = await res.json();
622
- if (!data.ok) {
623
- setProblem(data);
624
- return;
625
- }
626
- setProblem(null);
627
- setChannel(data.channel);
628
- setSource(data.source);
629
- setAsOf(data.asOf ?? null);
630
- await database.put({
631
- _id: `channel-${data.channel.channelId}`,
632
- type: "channel",
633
- channelId: data.channel.channelId,
634
- aliases: data.channel.aliases ?? [data.channel.channelId.toLowerCase()],
635
- });
583
+ if (!data.ok) setNote(data.message);
584
+ else if (data.firstSample === "saved") setNote("Tracking. Your first recap arrives tomorrow at 9 a.m.");
585
+ else setNote("Tracking. The first readings arrive with the next scheduled reading.");
586
+ load();
636
587
  };
637
588
 
638
- const history = snapshots.slice().sort((a, b) => a.day.localeCompare(b.day));
589
+ // The pause note holds only until its resumesAt; a timer drops it from an open page at the reset.
590
+ const resumesAt = view?.status ? Date.parse(view.status.resumesAt) : NaN;
591
+ const [now, setNow] = useState(Date.now());
592
+ useEffect(() => {
593
+ if (!(resumesAt > Date.now())) return undefined;
594
+ const timer = setTimeout(() => setNow(Date.now()), resumesAt - Date.now() + 1000);
595
+ return () => clearTimeout(timer);
596
+ }, [resumesAt]);
597
+ const resting = resumesAt > now;
598
+ const history = view?.recaps ?? [];
639
599
 
640
600
  return (
641
601
  <Stack>
642
- <Row gap={2}>
643
- <Button variant="quiet" onClick={() => setScreen("dashboard")}>Dashboard</Button>
644
- {/* The Setup entry: the owner's alone, highlighted while the item is still to do, quiet once done. */}
645
- {setup?.owner && (
646
- <Button variant={ready ? "quiet" : "solid"} onClick={() => setScreen("setup")}>
647
- Setup{ready ? "" : " · to do"}
648
- </Button>
649
- )}
650
- </Row>
651
-
652
- {screen === "setup" && setup?.owner ? (
653
- <SetupScreen setup={setup} />
654
- ) : (
655
- <Stack>
656
- {ready ? (
657
- <Row gap={2} align="top">
658
- <Field label="Channel">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={input} onChange={setInput} placeholder="@handle or channel URL" />}</Field>
659
- <Button type="button" onClick={connect}>Connect channel</Button>
660
- </Row>
661
- ) : (
662
- <Text muted>Channel stats are not open yet.</Text>
663
- )}
664
-
665
- {problem?.reason === "no-snapshot-yet" && <Text>The first daily snapshot has not been saved yet.</Text>}
666
- {problem && problem.reason !== "no-snapshot-yet" && <Text role="alert">{problem.message}</Text>}
667
-
668
- {channel && (
669
- <section>
670
- <h2>{channel.title}</h2>
671
- <p>{channel.subscribersHidden ? "Subscribers hidden by the channel" : `${channel.subscribers} subscribers`}</p>
672
- <small>YouTube rounds public subscriber counts.</small>
673
- <p>{channel.views} total views across {channel.videoCount} videos</p>
674
- {source === "snapshot" && <small>As of {asOf} — live numbers are refreshed for the channel owner.</small>}
675
- </section>
676
- )}
677
-
678
- <section>
679
- <h3>Not available with an API key</h3>
680
- <p>Watch time, revenue, impressions, traffic sources and demographics come from YouTube Analytics with OAuth.</p>
681
- </section>
682
-
683
- <section>
684
- <h3>Daily snapshots</h3>
685
- {history.length === 0 ? <p>First snapshot saves within the hour.</p> : <Chart rows={history} />}
686
- </section>
687
- </Stack>
602
+ <Heading>{view?.channel?.title ?? "Overnight recap"}</Heading>
603
+
604
+ {view?.owner && !view.channel && (
605
+ <Row gap={2} align="top">
606
+ <Field label="Your channel">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={link} onChange={setLink} placeholder="@handle or channel link" />}</Field>
607
+ <Button type="button" onClick={track}>Track</Button>
608
+ </Row>
688
609
  )}
610
+ {note && <Text role="status">{note}</Text>}
611
+
612
+ {resting && (
613
+ <Text muted>
614
+ Today's readings are in; the next ones arrive after{" "}
615
+ {view.status.reason === "over_budget" ? "midnight UTC" : "YouTube's midnight Pacific reset"} ({new Date(resumesAt).toLocaleTimeString()} your time).
616
+ </Text>
617
+ )}
618
+
619
+ {view?.channel && (
620
+ <section>
621
+ <p>{view.channel.subscribersHidden ? "Subscribers hidden by the channel" : `${view.channel.subscribers.toLocaleString()} subscribers`}</p>
622
+ <small>YouTube rounds public subscriber counts.</small>
623
+ </section>
624
+ )}
625
+
626
+ <section>
627
+ <h3>Every morning's winner</h3>
628
+ {history.length === 0 ? (
629
+ <p>The first recap lands at 9 a.m. after an evening and a morning reading.</p>
630
+ ) : (
631
+ history.map((r) => (
632
+ <article key={r._id} id={r._id}>
633
+ <h4>{r.day}</h4>
634
+ <p>{r.body}</p>
635
+ {r.fresh?.length > 0 && <small>New since last night: {r.fresh.map((v) => v.title).join(", ")}</small>}
636
+ </article>
637
+ ))
638
+ )}
639
+ </section>
640
+
641
+ <section>
642
+ <h3>Not available with an API key</h3>
643
+ <p>Watch time, revenue, impressions, traffic sources and demographics live in YouTube Studio, which settles them 48–72 hours later.</p>
644
+ </section>
689
645
  </Stack>
690
646
  );
691
647
  }
692
648
  ```
693
649
 
694
- Chart the `history` rows with whichever chart surface the app already uses:
695
- `day` on the x axis, `subscribers` and `views` as two series, and the per-video
696
- deltas between the last two snapshots as the "gaining attention" list.
650
+ Chart the samples with whichever chart surface the app already uses: `takenAt`
651
+ on the x axis and one series per video from `views`, so the owner sees the
652
+ evening-to-morning climb behind each recap.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibes.diy/prompts",
3
- "version": "14.3.265",
3
+ "version": "14.3.267",
4
4
  "type": "module",
5
5
  "main": "./index.js",
6
6
  "exports": {
@@ -39,10 +39,10 @@
39
39
  "license": "Apache-2.0",
40
40
  "dependencies": {
41
41
  "@adviser/cement": "~0.5.34",
42
- "@vibes.diy/api-types": "14.3.265",
43
- "@vibes.diy/call-ai-v2": "14.3.265",
44
- "@vibes.diy/identity": "14.3.265",
45
- "@vibes.diy/use-vibes-types": "14.3.265",
42
+ "@vibes.diy/api-types": "14.3.267",
43
+ "@vibes.diy/call-ai-v2": "14.3.267",
44
+ "@vibes.diy/identity": "14.3.267",
45
+ "@vibes.diy/use-vibes-types": "14.3.267",
46
46
  "arktype": "~2.2.8",
47
47
  "json-schema-faker": "~0.6.3"
48
48
  },