@pplethai/cli 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pplethai/cli",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -102,6 +102,18 @@ Where the token comes from:
102
102
  - **Notifications**: the shape that makes the audience required is in
103
103
  `shared/api.ts`; read the rules that come with naming recipients before
104
104
  changing anything there.
105
+ - **Interactive Notifications**: `sendNotification` takes an optional
106
+ `interaction` and returns `notificationId`; `closeInteraction` closes it
107
+ early. Keep `linkPath` as the fallback. `interaction.liveActivity: true`
108
+ asks for a Live Activity on capable iPhones: urgent questions closing
109
+ within 8 h only, and never rely on it being seen. Answers (Notification
110
+ Responses) arrive at `notificationResponse` on the default export (`src/index.ts`,
111
+ type in `src/notification-response.ts`): dedupe on `event.id`, pick a winner
112
+ by `respondedAt` then `id` (answers can come after a close), return `410` to
113
+ stop answers, do slow work in `ctx.waitUntil`. The responder is
114
+ `event.responder.sub` only. Try the question with `pple notify test` (it
115
+ reaches only you; its answers reach no handler). Full guide: the
116
+ `pple-platform` Skill, mini-app reference.
105
117
  - **Mobile-first layout** uses the layout classes in `web/app.css`.
106
118
  - **Add a DB table** by writing a new migration and running
107
119
  `npm run db:migrate:local`.
@@ -91,5 +91,11 @@ you, so a freshly created app is ready to `npm run dev` straight away.)
91
91
  audience — everyone this app can reach, or the people it names by PPLE ID
92
92
  `sub` or mobile number. Naming only ever narrows that set: someone who has
93
93
  never opened this app receives nothing.
94
+ - **Ask a question in a notification:** pass `interaction` to `notify()`, keep
95
+ `linkPath` as the fallback, and add `notificationResponse` to the default
96
+ export to receive the answers (dedupe on `id`; `410` stops them; slow work
97
+ in `ctx.waitUntil`). `closeInteraction()` stops answers early. See a sample
98
+ in `test/notification-response.test.ts`. `pple notify test <file.json | ->`
99
+ shows the question on your own phone; its answers reach no handler.
94
100
 
95
101
  The demo cards (Notes / Files / Notify) are examples — replace them.
@@ -157,6 +157,104 @@ export const NotificationAudienceSchema = z.discriminatedUnion("kind", [
157
157
  ]);
158
158
  export type NotificationAudience = z.infer<typeof NotificationAudienceSchema>;
159
159
 
160
+ /**
161
+ * The names an Action may take as its `icon`: PPLE Today's fixed allowlist.
162
+ * Anything else is refused by PPLE Today, not here.
163
+ */
164
+ export type InteractionIconName =
165
+ | "check"
166
+ | "x"
167
+ | "thumbs-up"
168
+ | "thumbs-down"
169
+ | "calendar-check"
170
+ | "calendar-x"
171
+ | "clock"
172
+ | "send"
173
+ | "heart"
174
+ | "star"
175
+ | "flag"
176
+ | "user-check"
177
+ | "user-x"
178
+ | "help";
179
+
180
+ export interface InteractionOption {
181
+ id: string;
182
+ label: string;
183
+ }
184
+
185
+ /** One input an Interactive Notification asks for, above its actions. */
186
+ export type InteractionField =
187
+ | {
188
+ id: string;
189
+ type: "text";
190
+ label: string;
191
+ description?: string;
192
+ required?: boolean;
193
+ placeholder?: string;
194
+ multiline?: boolean;
195
+ maxLength?: number;
196
+ minLength?: number;
197
+ }
198
+ | {
199
+ id: string;
200
+ type: "radio";
201
+ label: string;
202
+ description?: string;
203
+ required?: boolean;
204
+ options: InteractionOption[];
205
+ default?: string;
206
+ }
207
+ | {
208
+ id: string;
209
+ type: "checkbox";
210
+ label: string;
211
+ description?: string;
212
+ required?: boolean;
213
+ options: InteractionOption[];
214
+ min?: number;
215
+ max?: number;
216
+ default?: string[];
217
+ };
218
+
219
+ /** A button that submits the answer. Every interaction has one to three. */
220
+ export interface InteractionAction {
221
+ id: string;
222
+ label: string;
223
+ icon?: InteractionIconName;
224
+ style?: "primary" | "outline" | "destructive";
225
+ /** Field ids this action needs filled, on top of fields marked `required`. */
226
+ requires?: string[];
227
+ confirm?: { title: string; message?: string };
228
+ }
229
+
230
+ /**
231
+ * What an Interactive Notification asks its recipients. Passed to PPLE Today
232
+ * exactly as written: PPLE Today owns the rules (id format, limits, expiry),
233
+ * and a broken one comes back as `invalid_interaction` naming the failing
234
+ * path. The type is here so an editor can help; it is not a validator.
235
+ */
236
+ export interface Interaction {
237
+ /** Opaque to the platform; echoed back with the answer. At most 200 chars. */
238
+ ref?: string;
239
+ /** ISO date-time with `Z` or an offset, in the future, at most 30 days out. */
240
+ expiresAt?: string;
241
+ fields?: InteractionField[];
242
+ actions: InteractionAction[];
243
+ /** `false` keeps action buttons off the OS notification. Default `true`. */
244
+ tray?: boolean;
245
+ /**
246
+ * Asks for a Live Activity on capable iPhones: the buttons stay on the Lock
247
+ * Screen and in the Dynamic Island, with no long press. For urgent questions
248
+ * only. Everyone else gets the ordinary notification, and every recipient
249
+ * still has the question in PPLE Today. PPLE Today refuses it (as
250
+ * `invalid_interaction`) unless `expiresAt` is set and at most 8 h ahead,
251
+ * `tray` is not `false`, and the question shows buttons on the phone: no
252
+ * `radio`, `checkbox` or `required` field, and not a lone `text` field with
253
+ * one action (the reply box) unless that action has `confirm`.
254
+ */
255
+ liveActivity?: boolean;
256
+ }
257
+
160
258
  /**
161
259
  * A notification to send. The privacy model in one line: this app can reach
162
260
  * the people who already use it — and now say which of them it means — and no
@@ -185,6 +283,13 @@ export const NotificationSchema = z.object({
185
283
  * recipient list of a different length is a conflict, not a replay.
186
284
  */
187
285
  idempotencyKey: z.string().trim().min(1).optional(),
286
+ /**
287
+ * Makes this an Interactive Notification. Only checked to be an object here;
288
+ * PPLE Today validates it and names the failing path.
289
+ */
290
+ interaction: z
291
+ .custom<Interaction>((v) => typeof v === "object" && v !== null && !Array.isArray(v))
292
+ .optional(),
188
293
  });
189
294
  export type Notification = z.infer<typeof NotificationSchema>;
190
295
 
@@ -11,7 +11,7 @@ import { addNote, listNotes } from "./db";
11
11
  import type { Env } from "./env";
12
12
  import { devWorkerFetch } from "./dev-registry";
13
13
  import { getFile, listFiles, putFile } from "./files";
14
- import { sendNotification } from "./notify";
14
+ import { closeInteraction, sendNotification } from "./notify";
15
15
  import type { PpleWorker, RegistryFetch, RegistryMap } from "./registry";
16
16
 
17
17
  /** Test seam: real fetch by default, an injected fake in tests. */
@@ -101,17 +101,33 @@ export function createApp(overrides: AppOverrides = {}) {
101
101
  const result = await sendNotification(c.env, parsed.data, fetchImpl);
102
102
  if (!result.ok) {
103
103
  return c.json(
104
- { error: result.error, ...(result.quota ? { quota: result.quota } : {}) },
104
+ {
105
+ error: result.error,
106
+ ...(result.message ? { message: result.message } : {}),
107
+ ...(result.quota ? { quota: result.quota } : {}),
108
+ },
105
109
  result.status as ContentfulStatusCode,
106
110
  );
107
111
  }
108
112
  // A Direct send answers for each recipient it named; a Broadcast names no
109
113
  // one, so there is nothing to enumerate.
114
+ const notificationId = result.notificationId ? { notificationId: result.notificationId } : {};
110
115
  return c.json(
111
- result.audience === "direct" ? { ok: true, results: result.results } : { ok: true },
116
+ result.audience === "direct"
117
+ ? { ok: true, results: result.results, ...notificationId }
118
+ : { ok: true, ...notificationId },
112
119
  );
113
120
  });
114
121
 
122
+ // Close an Interactive Notification early, by the id its send returned.
123
+ app.post("/notify/:notificationId/close", async (c) => {
124
+ const result = await closeInteraction(c.env, c.req.param("notificationId"), fetchImpl);
125
+ if (!result.ok) {
126
+ return c.json({ error: result.error }, result.status as ContentfulStatusCode);
127
+ }
128
+ return c.json({ ok: true, ...(result.closedAt ? { closedAt: result.closedAt } : {}) });
129
+ });
130
+
115
131
  return app;
116
132
  }
117
133
 
@@ -0,0 +1,55 @@
1
+ // A Notification Response: one recipient's answer to an Interactive Notification
2
+ // your app sent (docs/adr/0035). today-v2 delivers it through the platform to
3
+ // `notificationResponse(event, env, ctx)` on the Worker default export, beside
4
+ // `fetch` and `registry`. Define it on `worker` in `src/index.ts`.
5
+ //
6
+ // What your handler does is the status today-v2 retries on:
7
+ //
8
+ // - not defined: the platform answers 404, and answers keep coming for about
9
+ // a day and a half, so there is time to ship one
10
+ // - returns nothing: 204, delivered
11
+ // - returns a `Response`: that status. Return `410` to say "stop sending me
12
+ // these", which ends delivery for good
13
+ // - throws: 500, and today-v2 tries again
14
+ //
15
+ // Delivery is at-least-once and unordered. Dedupe on `event.id`. If only the
16
+ // first answer should count ("first approver wins"), decide it yourself by
17
+ // `respondedAt`, then `id`. An answer can arrive after you closed the
18
+ // interaction.
19
+ //
20
+ // The platform answers when the handler returns. It does not wait for work
21
+ // handed to `ctx.waitUntil`, so do the slow part there, after the answer is
22
+ // acknowledged. today-v2 gives up on a call after about 10 s.
23
+ //
24
+ // The handler gets the parsed event only: no request, no headers. The
25
+ // responder is a PPLE ID `sub` and nothing else. If you need more about that
26
+ // person, call a Service you have been granted.
27
+
28
+ import type { Env } from "./env";
29
+
30
+ export interface NotificationResponseEvent {
31
+ type: "notification.response";
32
+ /** The response's own id. The same on every retry, so dedupe on it. */
33
+ id: string;
34
+ /** The notification that was answered. `notify()` returned it when you sent. */
35
+ notificationId: string;
36
+ /** Your own id for the question, as you sent it. Absent if you sent none. */
37
+ ref?: string;
38
+ app: { slug: string };
39
+ /** Who answered: their PPLE ID `sub`. */
40
+ responder: { sub: string };
41
+ /** The action the recipient chose. */
42
+ action: string;
43
+ /** The form fields they filled in, by field id. A tick-list is an array. */
44
+ values?: Record<string, string | string[]>;
45
+ /** ISO 8601 time they answered. */
46
+ respondedAt: string;
47
+ /** Which delivery attempt this is, from 1. */
48
+ attempt: number;
49
+ }
50
+
51
+ export type NotificationResponseHandler = (
52
+ event: NotificationResponseEvent,
53
+ env: Env,
54
+ ctx: ExecutionContext,
55
+ ) => void | Response | Promise<void | Response>;
@@ -49,6 +49,14 @@ interface NotifyEnv {
49
49
  * against the named count, so the call is rejected whole rather than
50
50
  * half-sent.
51
51
  * - `not_permitted` — this key may not use this route.
52
+ * - `invalid_interaction` — PPLE Today refused the `interaction`; `message`
53
+ * names the first failing path, e.g. `interaction.actions[1].requires[0]`.
54
+ * Nothing was sent.
55
+ * - `interaction_unavailable` — this app cannot send an interaction right now:
56
+ * no callback target yet, or the feature is switched off. Nothing was sent;
57
+ * retrying without `interaction` sends a plain notification.
58
+ * - `notification_not_found` — `closeInteraction` named an id that is not one
59
+ * of this app's notifications (PPLE Today answers the same for all of them).
52
60
  * - `send_failed` — anything else.
53
61
  */
54
62
  export type NotifyError =
@@ -58,6 +66,9 @@ export type NotifyError =
58
66
  | "idempotency_key_conflict"
59
67
  | "quota_exceeded"
60
68
  | "not_permitted"
69
+ | "invalid_interaction"
70
+ | "interaction_unavailable"
71
+ | "notification_not_found"
61
72
  | "send_failed";
62
73
 
63
74
  /**
@@ -73,10 +84,32 @@ export interface NotifyQuota {
73
84
  resetAt?: string;
74
85
  }
75
86
 
87
+ /**
88
+ * `notificationId` is PPLE Today's id for the send, the one `closeInteraction`
89
+ * takes. A replay of an `idempotencyKey` returns the original id. It is absent
90
+ * only if PPLE Today did not give one (for instance an audience that reached
91
+ * no one).
92
+ */
76
93
  export type NotifyResult =
77
- | { ok: true; audience: "all" }
78
- | { ok: true; audience: "direct"; results: NotificationDelivery[] }
79
- | { ok: false; status: number; error: NotifyError; quota?: NotifyQuota };
94
+ | { ok: true; audience: "all"; notificationId?: string }
95
+ | {
96
+ ok: true;
97
+ audience: "direct";
98
+ results: NotificationDelivery[];
99
+ notificationId?: string;
100
+ }
101
+ | {
102
+ ok: false;
103
+ status: number;
104
+ error: NotifyError;
105
+ /** PPLE Today's own words, kept for `invalid_interaction`. */
106
+ message?: string;
107
+ quota?: NotifyQuota;
108
+ };
109
+
110
+ export type CloseInteractionResult =
111
+ | { ok: true; closedAt?: string }
112
+ | { ok: false; status: number; error: NotifyError };
80
113
 
81
114
  export async function sendNotification(
82
115
  env: NotifyEnv,
@@ -103,23 +136,109 @@ export async function sendNotification(
103
136
  ...(input.idempotencyKey !== undefined
104
137
  ? { idempotencyKey: input.idempotencyKey }
105
138
  : {}),
139
+ // Passed on unchanged: PPLE Today owns its validation.
140
+ ...(input.interaction !== undefined ? { interaction: input.interaction } : {}),
106
141
  }),
107
142
  });
108
143
 
109
144
  if (!res.ok) {
110
- const error = errorFor(res.status);
111
- const quota = error === "quota_exceeded" ? quotaOf(await readJson(res)) : undefined;
112
- return { ok: false, status: res.status, error, ...(quota ? { quota } : {}) };
145
+ const body = await readJson(res);
146
+ const code = codeOf(body);
147
+ const error = interactionErrorFor(code) ?? errorFor(res.status);
148
+ const quota = error === "quota_exceeded" ? quotaOf(body) : undefined;
149
+ const message = error === "invalid_interaction" ? messageOf(body) : undefined;
150
+ return {
151
+ ok: false,
152
+ status: res.status,
153
+ error,
154
+ ...(message ? { message } : {}),
155
+ ...(quota ? { quota } : {}),
156
+ };
113
157
  }
114
158
 
115
- if (input.audience.kind === "all") return { ok: true, audience: "all" };
159
+ const body = await readJson(res);
160
+ const id = (body as { notificationId?: unknown } | null)?.notificationId;
161
+ const notificationId = typeof id === "string" ? { notificationId: id } : {};
162
+ if (input.audience.kind === "all") return { ok: true, audience: "all", ...notificationId };
116
163
  return {
117
164
  ok: true,
118
165
  audience: "direct",
119
- results: zipResults(input.audience.recipients, await readJson(res)),
166
+ results: zipResults(input.audience.recipients, body),
167
+ ...notificationId,
120
168
  };
121
169
  }
122
170
 
171
+ /**
172
+ * Stop accepting answers to one of this app's Interactive Notifications.
173
+ * Idempotent: closing again succeeds. Answers already in flight can still
174
+ * arrive after this returns, so an app that needs "first wins" settles it on
175
+ * its own side by `respondedAt`.
176
+ */
177
+ export async function closeInteraction(
178
+ env: NotifyEnv,
179
+ notificationId: string,
180
+ fetchImpl: typeof fetch = globalThis.fetch.bind(globalThis),
181
+ ): Promise<CloseInteractionResult> {
182
+ if (!env.NOTIFY_API_BASE || !env.NOTIFY_API_KEY) {
183
+ return { ok: false, status: 503, error: "notifications_not_configured" };
184
+ }
185
+
186
+ const res = await fetchImpl(
187
+ `${env.NOTIFY_API_BASE}/notifications/${encodeURIComponent(notificationId)}/interaction/close`,
188
+ { method: "POST", headers: { authorization: `Bearer ${env.NOTIFY_API_KEY}` } },
189
+ );
190
+
191
+ if (!res.ok) {
192
+ const code = codeOf(await readJson(res));
193
+ const error =
194
+ interactionErrorFor(code) ??
195
+ (res.status === 404
196
+ ? "notification_not_found"
197
+ : res.status === 401 || res.status === 403
198
+ ? "not_permitted"
199
+ : "send_failed");
200
+ return { ok: false, status: res.status, error };
201
+ }
202
+
203
+ const closedAt = (await readJson(res) as { closedAt?: unknown } | null)?.closedAt;
204
+ return { ok: true, ...(typeof closedAt === "string" ? { closedAt } : {}) };
205
+ }
206
+
207
+ /**
208
+ * PPLE Today's own codes for interaction refusals. These share status 400 with
209
+ * recipient refusals, so the code is read before the status is.
210
+ */
211
+ function interactionErrorFor(code: string): NotifyError | undefined {
212
+ switch (code) {
213
+ case "NOTIFICATION_INVALID_INTERACTION":
214
+ return "invalid_interaction";
215
+ case "NOTIFICATION_INTERACTION_NO_CALLBACK":
216
+ case "INTERACTIVE_NOTIFICATIONS_DISABLED":
217
+ return "interaction_unavailable";
218
+ default:
219
+ return undefined;
220
+ }
221
+ }
222
+
223
+ /** PPLE Today answers `{ error: { code, message } }`; tolerate a flat body too. */
224
+ function errorObject(body: unknown): Record<string, unknown> {
225
+ if (typeof body !== "object" || body === null) return {};
226
+ const { error } = body as { error?: unknown };
227
+ return typeof error === "object" && error !== null
228
+ ? (error as Record<string, unknown>)
229
+ : (body as Record<string, unknown>);
230
+ }
231
+
232
+ function codeOf(body: unknown): string {
233
+ const { code } = errorObject(body);
234
+ return typeof code === "string" ? code : "";
235
+ }
236
+
237
+ function messageOf(body: unknown): string | undefined {
238
+ const { message } = errorObject(body);
239
+ return typeof message === "string" ? message : undefined;
240
+ }
241
+
123
242
  /**
124
243
  * The platform splits its refusals: schema-level ones answer 422 (its whole
125
244
  * API validates uniformly, and this route does not get to be the exception),
@@ -14,6 +14,7 @@
14
14
 
15
15
  import { IdentitySchema, type Identity } from "../shared/api";
16
16
  import type { Env } from "./env";
17
+ import type { NotificationResponseHandler } from "./notification-response";
17
18
 
18
19
  export const CONSUMER_HEADER = "x-pple-consumer";
19
20
  export const ENTRY_HEADER = "x-pple-entry";
@@ -89,6 +90,8 @@ export type RegistryMap = Record<string, RegistryHandler | DatasetPages>;
89
90
  export interface PpleWorker {
90
91
  fetch(request: Request, env: Env, ctx: ExecutionContext): Response | Promise<Response>;
91
92
  registry?: RegistryMap;
93
+ /** Answers to your Interactive Notifications. See `./notification-response`. */
94
+ notificationResponse?: NotificationResponseHandler;
92
95
  }
93
96
 
94
97
  function decodeIdentity(value: string): Identity | null {
@@ -35,6 +35,8 @@ export interface Fakes {
35
35
  sso?: (req: Request) => Response | Promise<Response>;
36
36
  /** Handles POST {NOTIFY_API_BASE}/notifications */
37
37
  notify?: (req: Request) => Response | Promise<Response>;
38
+ /** Handles POST {NOTIFY_API_BASE}/notifications/:id/interaction/close */
39
+ close?: (req: Request) => Response | Promise<Response>;
38
40
  /**
39
41
  * Handles `{PPLE_SERVICES_URL}/<name>/…` for `callService` and
40
42
  * `readDataset`. Answer as the platform, or refuse with `serviceRefusal`
@@ -68,6 +70,7 @@ export function serviceRefusal(code: string, status: number): Response {
68
70
  export function makeHarness(fakes: Fakes = {}, envOverrides: Partial<Env> = {}) {
69
71
  const calls = {
70
72
  notify: [] as Request[],
73
+ close: [] as Request[],
71
74
  services: [] as RecordedServiceCall[],
72
75
  };
73
76
 
@@ -96,6 +99,10 @@ export function makeHarness(fakes: Fakes = {}, envOverrides: Partial<Env> = {})
96
99
  if (url.pathname.endsWith("/oidc/v1/userinfo")) {
97
100
  return fakes.sso ? fakes.sso(req) : new Response(null, { status: 502 });
98
101
  }
102
+ if (url.pathname.endsWith("/interaction/close")) {
103
+ calls.close.push(req.clone());
104
+ return fakes.close ? fakes.close(req) : new Response(null, { status: 502 });
105
+ }
99
106
  if (url.pathname.endsWith("/notifications")) {
100
107
  calls.notify.push(req.clone());
101
108
  return fakes.notify ? fakes.notify(req) : new Response(null, { status: 502 });