@pplethai/cli 0.22.0 → 0.24.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 (118) hide show
  1. package/README.md +12 -14
  2. package/dist/bin.js +109 -109
  3. package/package.json +3 -6
  4. package/templates/golden-path/.dev.vars.example +0 -33
  5. package/templates/golden-path/.env.example +0 -10
  6. package/templates/golden-path/.github/workflows/ci.yml +0 -22
  7. package/templates/golden-path/AGENTS.md +0 -1
  8. package/templates/golden-path/CLAUDE.md +0 -191
  9. package/templates/golden-path/README.md +0 -121
  10. package/templates/golden-path/gitignore +0 -17
  11. package/templates/golden-path/index.html +0 -16
  12. package/templates/golden-path/migrations/0001_init.sql +0 -10
  13. package/templates/golden-path/overlay-mtime.mjs +0 -30
  14. package/templates/golden-path/package-lock.json +0 -4318
  15. package/templates/golden-path/package.json +0 -41
  16. package/templates/golden-path/scripts/assert-dev-compiled-out.mjs +0 -45
  17. package/templates/golden-path/shared/api.ts +0 -325
  18. package/templates/golden-path/src/auth.ts +0 -230
  19. package/templates/golden-path/src/call-service.ts +0 -147
  20. package/templates/golden-path/src/dataset-query.ts +0 -470
  21. package/templates/golden-path/src/dataset-schema.ts +0 -398
  22. package/templates/golden-path/src/db.ts +0 -32
  23. package/templates/golden-path/src/dev-call-service.ts +0 -392
  24. package/templates/golden-path/src/dev-personas.ts +0 -186
  25. package/templates/golden-path/src/dev-read-dataset.ts +0 -444
  26. package/templates/golden-path/src/dev-registry.ts +0 -294
  27. package/templates/golden-path/src/email.ts +0 -49
  28. package/templates/golden-path/src/entry-name.ts +0 -114
  29. package/templates/golden-path/src/env.ts +0 -38
  30. package/templates/golden-path/src/files.ts +0 -38
  31. package/templates/golden-path/src/identity-header.ts +0 -17
  32. package/templates/golden-path/src/index.ts +0 -282
  33. package/templates/golden-path/src/legal-identity.ts +0 -180
  34. package/templates/golden-path/src/levels.ts +0 -132
  35. package/templates/golden-path/src/notification-response.ts +0 -55
  36. package/templates/golden-path/src/notify.ts +0 -311
  37. package/templates/golden-path/src/party-email.ts +0 -183
  38. package/templates/golden-path/src/payment.ts +0 -676
  39. package/templates/golden-path/src/read-dataset.ts +0 -490
  40. package/templates/golden-path/src/registry.ts +0 -128
  41. package/templates/golden-path/src/vite-env.d.ts +0 -27
  42. package/templates/golden-path/test/apply-migrations.ts +0 -4
  43. package/templates/golden-path/test/call-service.test.ts +0 -288
  44. package/templates/golden-path/test/dev-call-service.test.ts +0 -455
  45. package/templates/golden-path/test/dev-read-dataset.test.ts +0 -379
  46. package/templates/golden-path/test/dev-registry.test.ts +0 -404
  47. package/templates/golden-path/test/effective-sub.test.ts +0 -101
  48. package/templates/golden-path/test/email-offline.test.ts +0 -51
  49. package/templates/golden-path/test/email.test.ts +0 -117
  50. package/templates/golden-path/test/env.d.ts +0 -17
  51. package/templates/golden-path/test/fixtures/overlay/branch-list/entry.md +0 -85
  52. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/audience.json +0 -3
  53. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/named.json +0 -3
  54. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/offices.json +0 -6
  55. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/roster.json +0 -3
  56. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/summary.json +0 -1
  57. package/templates/golden-path/test/fixtures/overlay/catalog/entry.md +0 -8
  58. package/templates/golden-path/test/fixtures/overlay/catalog/mocks/responses.json +0 -7
  59. package/templates/golden-path/test/fixtures/overlay/election/2027/score/entry.md +0 -11
  60. package/templates/golden-path/test/fixtures/overlay/election/2027/score/mocks/responses.json +0 -7
  61. package/templates/golden-path/test/fixtures/overlay/election/results/entry.md +0 -24
  62. package/templates/golden-path/test/fixtures/overlay/election/results/mocks/turnout.json +0 -1
  63. package/templates/golden-path/test/fixtures/overlay/orders/entry.md +0 -12
  64. package/templates/golden-path/test/fixtures/overlay/orders/mocks/responses.json +0 -36
  65. package/templates/golden-path/test/fixtures/overlay/platform/email/entry.md +0 -12
  66. package/templates/golden-path/test/fixtures/overlay/platform/email/mocks/responses.json +0 -11
  67. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/entry.md +0 -8
  68. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/mocks/responses.json +0 -13
  69. package/templates/golden-path/test/fixtures/overlay/platform/payments/entry.md +0 -12
  70. package/templates/golden-path/test/fixtures/overlay/platform/payments/mocks/responses.json +0 -98
  71. package/templates/golden-path/test/fixtures/overlay/platform/sms/entry.md +0 -10
  72. package/templates/golden-path/test/fixtures/overlay/platform/sms/mocks/responses.json +0 -7
  73. package/templates/golden-path/test/fixtures/overlay/score/entry.md +0 -10
  74. package/templates/golden-path/test/fixtures/overlay/score/mocks/responses.json +0 -7
  75. package/templates/golden-path/test/harness.ts +0 -153
  76. package/templates/golden-path/test/interaction.test.ts +0 -230
  77. package/templates/golden-path/test/legal-identity.test.ts +0 -323
  78. package/templates/golden-path/test/membership.test.ts +0 -105
  79. package/templates/golden-path/test/notification-response.test.ts +0 -79
  80. package/templates/golden-path/test/payment-app.test.ts +0 -211
  81. package/templates/golden-path/test/payment-offline.test.ts +0 -91
  82. package/templates/golden-path/test/payment.test.ts +0 -518
  83. package/templates/golden-path/test/payments-offline.ts +0 -33
  84. package/templates/golden-path/test/read-dataset.test.ts +0 -387
  85. package/templates/golden-path/test/service-call.test.ts +0 -166
  86. package/templates/golden-path/test/smoke.test.ts +0 -464
  87. package/templates/golden-path/tsconfig.json +0 -20
  88. package/templates/golden-path/tsconfig.worker.json +0 -21
  89. package/templates/golden-path/vite.config.ts +0 -12
  90. package/templates/golden-path/vitest.config.ts +0 -28
  91. package/templates/golden-path/web/App.tsx +0 -478
  92. package/templates/golden-path/web/app.css +0 -83
  93. package/templates/golden-path/web/main.tsx +0 -51
  94. package/templates/golden-path/web/pple.ts +0 -124
  95. package/templates/golden-path/web/vite-env.d.ts +0 -10
  96. package/templates/golden-path/wrangler.jsonc +0 -89
  97. package/templates/payment-bridge/.github/workflows/ci.yml +0 -21
  98. package/templates/payment-bridge/CLAUDE.md +0 -9
  99. package/templates/payment-bridge/README.md +0 -57
  100. package/templates/payment-bridge/docs/verify-webhook.md +0 -80
  101. package/templates/payment-bridge/docs/verify-webhook.ts +0 -29
  102. package/templates/payment-bridge/gitignore +0 -5
  103. package/templates/payment-bridge/package-lock.json +0 -4198
  104. package/templates/payment-bridge/package.json +0 -21
  105. package/templates/payment-bridge/src/bridge-key.ts +0 -18
  106. package/templates/payment-bridge/src/env.ts +0 -14
  107. package/templates/payment-bridge/src/index.ts +0 -39
  108. package/templates/payment-bridge/src/platform.ts +0 -49
  109. package/templates/payment-bridge/src/webhook.ts +0 -86
  110. package/templates/payment-bridge/test/docs.test.ts +0 -9
  111. package/templates/payment-bridge/test/fixtures/payments-responses.json +0 -98
  112. package/templates/payment-bridge/test/harness.ts +0 -78
  113. package/templates/payment-bridge/test/inbound.test.ts +0 -138
  114. package/templates/payment-bridge/test/webhook.test.ts +0 -174
  115. package/templates/payment-bridge/tsconfig.json +0 -22
  116. package/templates/payment-bridge/vitest.config.ts +0 -8
  117. package/templates/payment-bridge/wrangler.jsonc +0 -15
  118. package/templates/payment-bridge.version +0 -1
@@ -1,294 +0,0 @@
1
- // Offline Provider development (ADR-0026). Active only where
2
- // `import.meta.env.DEV` is true — `vite dev` and the template tests. The
3
- // production build drops this module the same way it drops the Persona
4
- // bypass (ADR-0011).
5
- //
6
- // `npm run dev` has no platform wrapper and no platform-call secret, so a
7
- // Builder can curl `/.pple/registry/<name>/…` directly. This delivers that
8
- // request to `registry[name]` the way the platform wrapper does: the tail
9
- // path, the method and body, and the `x-pple-*` facts. Incoming `x-pple-*`
10
- // headers are never trusted. Public traffic has them stripped before app
11
- // code, so dev and production agree that a Builder cannot invent platform
12
- // facts.
13
- //
14
- // Identity choice. An unset `DEV_PERSONA` uses the default Persona, as the
15
- // rest of local dev does. `DEV_PERSONA=none` sends no `x-pple-identity`,
16
- // which is what the platform does for an entry that declares
17
- // `userToken: none`. A name that is not a Persona does the same, and does
18
- // not fall back to the default: a registry call must not invent a caller.
19
- // `/api` still falls back, so a typo does not lock the Builder out of the
20
- // app. The Consumer is `DEV_CONSUMER`, or `dev-consumer`. `x-pple-entry` is
21
- // the `registry` key. For a bare entry that is the name the platform sends
22
- // (ADR-0031). For a namespaced entry the key is its local path (`2027/score`),
23
- // because the Provider never sees the Namespace (ADR-0032), so the platform's
24
- // header carries the full name while this one carries the path. The Provider is
25
- // not part of it: the local app is the dev Provider, `dev-provider`, because it
26
- // has no App Slug until the platform creates it.
27
- //
28
- // The registry path names an entry by its local path, which may run several
29
- // folders (`/.pple/registry/2027/score/<tail>`). No key is a segment-prefix of
30
- // another in one app (ADR-0032), so the key that leads the path is the entry.
31
- //
32
- // A Dataset value is an object of page functions. `/.pple/registry/<name>/<objectType>`
33
- // calls that function with `{ cursor }` and answers with its page. A value with
34
- // no fetch-shaped handler, and a page map with no function for the segment,
35
- // throws `registry handler missing`, the error the platform wrapper throws.
36
- // `pple-services` turns that throw
37
- // into `provider_unavailable` (502). Nothing here invents that response:
38
- // locally there is no gateway in front of the handler, and the 502 is a
39
- // Consumer-facing answer the Provider's code never sees. Other `/.pple/`
40
- // paths (cron, the deploy probe) are not emulated; they reach app code with
41
- // platform headers stripped.
42
-
43
- import type { Identity } from "../shared/api";
44
- import { DEV_PERSONAS, DEFAULT_DEV_PERSONA } from "./dev-personas";
45
- import type { Env } from "./env";
46
- import { encodeIdentityHeader } from "./identity-header";
47
- import {
48
- CONSUMER_HEADER,
49
- ENTRY_HEADER,
50
- IDENTITY_HEADER,
51
- type DatasetPages,
52
- type RegistryFetch,
53
- type RegistryMap,
54
- } from "./registry";
55
-
56
- export const DEFAULT_DEV_CONSUMER = "dev-consumer";
57
-
58
- /** Local stand-in for the Provider's App Slug. It is never joined into the entry name. */
59
- export const DEV_PROVIDER_SLUG = "dev-provider";
60
-
61
- const REGISTRY_PATH_PREFIX = "/.pple/registry/";
62
-
63
- const HOP_BY_HOP = new Set([
64
- "host",
65
- "connection",
66
- "keep-alive",
67
- "transfer-encoding",
68
- "te",
69
- "trailer",
70
- "upgrade",
71
- ]);
72
-
73
- export interface DevWorker {
74
- fetch: RegistryFetch;
75
- registry?: RegistryMap;
76
- }
77
-
78
- export interface CallRegistryOptions {
79
- /**
80
- * Persona for `x-pple-identity`. `"none"` or an unknown name sends none.
81
- * Omit to use the env's `DEV_PERSONA`.
82
- */
83
- persona?: string;
84
- /** Consumer slug. Omit to use `DEV_CONSUMER`, then `dev-consumer`. */
85
- consumer?: string;
86
- /**
87
- * Method and body, which the platform preserves. `x-pple-*`, Authorization
88
- * and Cookie here are dropped: the call sets the platform facts itself.
89
- */
90
- init?: RequestInit;
91
- }
92
-
93
- /** The Identity a dev registry call carries, or null for `userToken: none`. */
94
- export function devRegistryIdentity(name: string | undefined): Identity | null {
95
- const key = name?.trim() || DEFAULT_DEV_PERSONA;
96
- if (key === "none") return null;
97
- const persona = DEV_PERSONAS[key];
98
- if (persona) return persona;
99
- console.warn(
100
- `Unknown DEV_PERSONA "${key}" on the emulated registry path; sending no Identity ` +
101
- `(userToken: none). Valid personas: ${Object.keys(DEV_PERSONAS).join(", ")}.`,
102
- );
103
- return null;
104
- }
105
-
106
- export function devConsumerSlug(value: string | undefined): string {
107
- const slug = value?.trim();
108
- return slug ? slug : DEFAULT_DEV_CONSUMER;
109
- }
110
-
111
- /**
112
- * Dev entry. Registry calls go to `user.registry`. Everything else is public
113
- * traffic: `x-pple-*` is removed, then `user.fetch` runs.
114
- */
115
- export async function devWorkerFetch(
116
- user: DevWorker,
117
- request: Request,
118
- env: Env,
119
- ctx: ExecutionContext,
120
- ): Promise<Response> {
121
- const url = new URL(request.url);
122
- const parsed = parseRegistryPath(url.pathname, user.registry);
123
- if (!parsed) return user.fetch(stripPlatformHeaders(request), env, ctx);
124
- if (!parsed.name) return emptyRegistryResponse();
125
-
126
- const pages = datasetPages(user.registry, parsed.name);
127
- if (pages) return runDatasetPage(pages, parsed.tail, request, env, ctx);
128
-
129
- const headers = handlerHeaders(
130
- request.headers,
131
- registryFacts(parsed.name, devConsumerSlug(env.DEV_CONSUMER), devRegistryIdentity(env.DEV_PERSONA)),
132
- );
133
- const target = new URL(request.url);
134
- target.pathname = parsed.tail;
135
- return handlerFor(user.registry, parsed.name)(
136
- forwardedRequest(target, request.method, headers, request.body),
137
- env,
138
- ctx,
139
- );
140
- }
141
-
142
- /**
143
- * Call `registry[name]` the way the platform wrapper does. See the file
144
- * comment for a missing handler: this throws `registry handler missing`.
145
- */
146
- export async function callRegistry(
147
- user: DevWorker,
148
- env: Env,
149
- ctx: ExecutionContext,
150
- name: string,
151
- path: string,
152
- options: CallRegistryOptions = {},
153
- ): Promise<Response> {
154
- if (!name) return emptyRegistryResponse();
155
- const personaName = options.persona !== undefined ? options.persona : env.DEV_PERSONA;
156
- const consumerName = options.consumer !== undefined ? options.consumer : env.DEV_CONSUMER;
157
- const headers = handlerHeaders(
158
- new Headers(options.init?.headers),
159
- registryFacts(name, devConsumerSlug(consumerName), devRegistryIdentity(personaName)),
160
- );
161
- const method = options.init?.method ?? "GET";
162
- const body = options.init?.body ?? null;
163
- // No incoming Host: the pathname and query are the tail the platform sets.
164
- const request = forwardedRequest(tailUrl(path), method, headers, body);
165
- const pages = datasetPages(user.registry, name);
166
- if (pages) return runDatasetPage(pages, new URL(request.url).pathname, request, env, ctx);
167
- return handlerFor(user.registry, name)(request, env, ctx);
168
- }
169
-
170
- function registryFacts(
171
- name: string,
172
- consumer: string,
173
- identity: Identity | null,
174
- ): { consumer: string; entry: string; identity: Identity | null } {
175
- return { consumer, entry: name, identity };
176
- }
177
-
178
- /** What the handler sees. Matches pple-services' header filter, minus the secret. */
179
- function handlerHeaders(
180
- incoming: Headers,
181
- facts: { consumer: string; entry: string; identity: Identity | null },
182
- ): Headers {
183
- const headers = new Headers();
184
- for (const [key, value] of incoming) {
185
- const lower = key.toLowerCase();
186
- if (
187
- lower === "authorization" ||
188
- lower === "cookie" ||
189
- lower.startsWith("x-pple-") ||
190
- HOP_BY_HOP.has(lower)
191
- ) {
192
- continue;
193
- }
194
- headers.set(key, value);
195
- }
196
- headers.set(CONSUMER_HEADER, facts.consumer);
197
- headers.set(ENTRY_HEADER, facts.entry);
198
- if (facts.identity) headers.set(IDENTITY_HEADER, encodeIdentityHeader(facts.identity));
199
- return headers;
200
- }
201
-
202
- function datasetPages(registry: RegistryMap | undefined, name: string): DatasetPages | null {
203
- const value = registry?.[name];
204
- if (typeof value !== "object" || value === null || typeof value.fetch === "function") return null;
205
- return value as DatasetPages;
206
- }
207
-
208
- /**
209
- * A Dataset page function is `{ cursor }` in, a page out. The path's single
210
- * segment is the Object Type. No segment, or no function by that name, is
211
- * the same missing-handler failure as a Service with nothing fetch-shaped.
212
- */
213
- async function runDatasetPage(
214
- pages: DatasetPages,
215
- tail: string,
216
- request: Request,
217
- env: Env,
218
- ctx: ExecutionContext,
219
- ): Promise<Response> {
220
- const objectType = tail.startsWith("/") ? tail.slice(1) : tail;
221
- const fn = objectType.includes("/") || objectType === "" ? undefined : pages[objectType];
222
- if (typeof fn !== "function") throw new Error("registry handler missing");
223
- let cursor: string | null = null;
224
- if (request.method !== "GET" && request.method !== "HEAD" && request.body) {
225
- try {
226
- const body = (await request.json()) as { cursor?: unknown };
227
- if (body && typeof body.cursor === "string") cursor = body.cursor;
228
- } catch {
229
- cursor = null;
230
- }
231
- }
232
- return Response.json(await fn({ cursor }, env, ctx));
233
- }
234
-
235
- function handlerFor(registry: RegistryMap | undefined, name: string): RegistryFetch {
236
- const value = registry?.[name];
237
- if (typeof value === "function") return value;
238
- if (value && typeof value === "object" && typeof value.fetch === "function") {
239
- const app = value as { fetch: RegistryFetch };
240
- return (request, env, ctx) => app.fetch(request, env, ctx);
241
- }
242
- throw new Error("registry handler missing");
243
- }
244
-
245
- function parseRegistryPath(
246
- pathname: string,
247
- registry: RegistryMap | undefined,
248
- ): { name: string; tail: string } | null {
249
- if (pathname !== "/.pple/registry" && !pathname.startsWith(REGISTRY_PATH_PREFIX)) return null;
250
- const restPath = pathname.startsWith(REGISTRY_PATH_PREFIX)
251
- ? pathname.slice(REGISTRY_PATH_PREFIX.length)
252
- : "";
253
- // A nested local path (`2027/score`) is a key that leads the path at a
254
- // segment boundary. Otherwise the first segment, so a missing handler
255
- // throws as before.
256
- const key = Object.keys(registry ?? {}).find(
257
- (candidate) => candidate.includes("/") && (restPath === candidate || restPath.startsWith(`${candidate}/`)),
258
- );
259
- if (key) return { name: key, tail: restPath.slice(key.length) || "/" };
260
- const slash = restPath.indexOf("/");
261
- const name = slash === -1 ? restPath : restPath.slice(0, slash);
262
- const tail = slash === -1 ? "/" : restPath.slice(slash) || "/";
263
- return { name, tail };
264
- }
265
-
266
- function tailUrl(path: string): URL {
267
- const raw = path.startsWith("/") ? path : `/${path}`;
268
- return new URL(raw, "https://provider.invalid");
269
- }
270
-
271
- function forwardedRequest(url: URL, method: string, headers: Headers, body: BodyInit | null): Request {
272
- const init: RequestInit & { duplex?: "half" } = { method, headers };
273
- if (method !== "GET" && method !== "HEAD" && body != null) {
274
- init.body = body;
275
- init.duplex = "half";
276
- }
277
- return new Request(url, init);
278
- }
279
-
280
- function stripPlatformHeaders(request: Request): Request {
281
- const headers = new Headers(request.headers);
282
- let changed = false;
283
- for (const key of [...headers.keys()]) {
284
- if (key.toLowerCase().startsWith("x-pple-")) {
285
- headers.delete(key);
286
- changed = true;
287
- }
288
- }
289
- return changed ? new Request(request, { headers }) : request;
290
- }
291
-
292
- function emptyRegistryResponse(): Response {
293
- return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
294
- }
@@ -1,49 +0,0 @@
1
- // Email: the party's layout, safe HTML building, and sending through
2
- // `platform/email` (needs its Use Grant and at least Beta).
3
- //
4
- // import { html, partyEmail, sendEmail } from "./email";
5
- //
6
- // const email = partyEmail({
7
- // heading: "ยืนยันการลงทะเบียน",
8
- // content: html`<p>สวัสดีคุณ ${name}</p><p>คุณลงทะเบียนงาน ${event} แล้ว</p>`,
9
- // text: `สวัสดีคุณ ${name}\nคุณลงทะเบียนงาน ${event} แล้ว`,
10
- // button: { label: "ดูรายละเอียด", url: "https://my-app.ppleth.ai/events/1" },
11
- // });
12
- // await sendEmail(env, { to: address, subject: "ยืนยันการลงทะเบียน", ...email });
13
- //
14
- // ESCAPE WHAT PEOPLE TYPED. A value put into HTML with a plain template string
15
- // (`<p>${name}</p>`) becomes HTML: a name containing `<a href=…>` puts a link
16
- // in an email sent under the party's name. The platform removes scripts and
17
- // the like, but not links or images: only your code can tell your markup from
18
- // your users' text. Build HTML with the `html` tag, which escapes every
19
- // value it is given; `raw()` is the deliberate way to insert markup you wrote.
20
- //
21
- // The layout and the `html` tag live in `./party-email` (the platform's own
22
- // Receipt email uses the same file) and are re-exported here.
23
-
24
- import { callService, type CallServiceEnv } from "./call-service";
25
-
26
- export { escapeHtml, html, PARTY, partyEmail, raw, safeUrl, SafeHtml, type PartyEmailInput } from "./party-email";
27
-
28
- export interface SendEmailResult {
29
- status: number;
30
- /** Set when the platform refused before the Service ran (`not_granted`, `needs_beta`, …). */
31
- platformError: string | null;
32
- body: unknown;
33
- }
34
-
35
- /** POST /platform/email. Pass `html`, `body` (plain text), or both. See `pple registry show platform/email`. */
36
- export async function sendEmail(
37
- env: CallServiceEnv,
38
- message: { to: string | string[]; subject: string; html?: string; body?: string },
39
- fetchImpl?: typeof fetch,
40
- ): Promise<SendEmailResult> {
41
- const res = await callService(
42
- env,
43
- "platform/email",
44
- "",
45
- { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(message) },
46
- fetchImpl ? { fetchImpl } : {},
47
- );
48
- return { status: res.status, platformError: res.headers.get("x-pple-error"), body: await res.json().catch(() => null) };
49
- }
@@ -1,114 +0,0 @@
1
- // A Registry Entry is named by its full name: one bare segment (`branch-list`),
2
- // or a Namespace (กลุ่มชื่อ) plus one to three more segments (`election/score`,
3
- // `election/2027/score`). The Provider is not part of the name (ADR-0031,
4
- // ADR-0032). The platform's own entries all sit under the Namespace `platform`:
5
- // `platform/sms`, `platform/legal-identity`.
6
- //
7
- // A copy of the name rules in workers/src/shared/registry/validate.ts. This
8
- // file is copied into a Builder App, which cannot import the platform
9
- // package. cli/test/registry-entry-name.test.ts keeps the two in step.
10
- //
11
- // `platform` is reserved for apps: no app may use it as a bare name or a
12
- // Namespace. That is why `platform/<x>` is the platform's name and never an
13
- // app's. A Consumer calls it by that name, so it passes here; the bare
14
- // `platform` does not.
15
-
16
- /** The slug shape of one segment: lowercase words joined by single hyphens. */
17
- const SEGMENT = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
18
- /** The longest one segment may be. */
19
- const SEGMENT_MAX = 63;
20
- /** The longest a full name may be, slashes included. */
21
- export const ENTRY_FULL_NAME_MAX = 128;
22
- /** A Namespace plus at most three path segments. */
23
- export const ENTRY_NAME_MAX_SEGMENTS = 4;
24
- /** The Namespace of every platform entry (`platform/sms`). The platform holds it; no app may. */
25
- export const PLATFORM_NAMESPACE = "platform";
26
- /** Names the platform keeps for itself. Rejected as a bare name and as an app's Namespace. */
27
- export const RESERVED_ENTRY_NAMES: ReadonlySet<string> = new Set(["health", "overlay", "platform"]);
28
-
29
- /**
30
- * Why `name` is not an entry name, or null when it is one. Reserved first
31
- * segments are reported apart from other shape problems so a caller can say
32
- * more about them. `platform/<path>` is an entry name: the platform's own
33
- * Namespace, which only the platform publish holds. The bare `platform` is not.
34
- */
35
- export function entryNameProblem(name: string): "shape" | "reserved" | null {
36
- if (name.length > ENTRY_FULL_NAME_MAX) return "shape";
37
- const segments = name.split("/");
38
- if (segments.length > ENTRY_NAME_MAX_SEGMENTS) return "shape";
39
- if (!segments.every((segment) => segment.length <= SEGMENT_MAX && SEGMENT.test(segment))) return "shape";
40
- const top = segments[0] ?? "";
41
- if (top === PLATFORM_NAMESPACE && segments.length > 1) return null;
42
- return RESERVED_ENTRY_NAMES.has(top) ? "reserved" : null;
43
- }
44
-
45
- /** True when `name` is one an entry may have. */
46
- export function isEntryName(name: string): boolean {
47
- return entryNameProblem(name) === null;
48
- }
49
-
50
- /** Why `name` is refused, in a sentence. Null when it is fine. */
51
- export function entryNameError(name: string): string | null {
52
- const problem = entryNameProblem(name);
53
- if (problem === null) return null;
54
- if (problem === "reserved") {
55
- const top = name.split("/")[0] ?? name;
56
- if (top === PLATFORM_NAMESPACE) {
57
- return `"${name}" is not an entry name: "platform" belongs to the platform, and its entries are named under it, such as "platform/sms"`;
58
- }
59
- return `"${top}" is reserved by the platform and cannot start an entry name`;
60
- }
61
- return (
62
- `"${name}" is not an entry name: use one bare name such as "branch-list", or a Namespace and up to ` +
63
- `${ENTRY_NAME_MAX_SEGMENTS - 1} more names such as "election/2027/score" ` +
64
- `(lowercase letters, digits and hyphens; at most ${ENTRY_FULL_NAME_MAX} characters)`
65
- );
66
- }
67
-
68
- /**
69
- * Throws unless `entry` is an entry name. `fn` is the public function that
70
- * received it, so the message names the call the Builder wrote.
71
- */
72
- export function assertEntryName(fn: string, entry: string): void {
73
- const error = entryNameError(entry);
74
- if (error) throw new Error(`${fn} entry ${error}`);
75
- }
76
-
77
- /** Where the workspace overlay lives. The CLI writes one folder per entry under it. */
78
- export const OVERLAY_ROOT = ".pple/registry/";
79
-
80
- /**
81
- * `file` (a glob key or a path) relative to the overlay root, posix, or null
82
- * when it is not under `root`. The root must start at a path boundary, so
83
- * `x.pple/registry/` is not a root. Tests pass their own `root` for a fixture
84
- * folder, because CI has no `.pple/`.
85
- */
86
- export function overlayRelative(file: string, root: string = OVERLAY_ROOT): string | null {
87
- const path = file.split("?")[0]?.replaceAll("\\", "/") ?? file;
88
- let from = 0;
89
- for (;;) {
90
- const at = path.indexOf(root, from);
91
- if (at === -1) return null;
92
- if (at === 0 || path[at - 1] === "/") return path.slice(at + root.length);
93
- from = at + 1;
94
- }
95
- }
96
-
97
- /**
98
- * The entry full name a file under the overlay belongs to, with the file's
99
- * place inside that entry's folder (`entry.md`, `mocks/orders.json`). An entry
100
- * folder is nested for a namespaced entry, so the name is every folder above
101
- * `entry.md` or `mocks/`. Null for a file that is neither.
102
- */
103
- export function overlayEntryFile(
104
- file: string,
105
- root: string = OVERLAY_ROOT,
106
- ): { name: string; inside: string } | null {
107
- const relative = overlayRelative(file, root);
108
- if (relative === null) return null;
109
- const entryMd = /^(.+)\/(entry\.md)$/.exec(relative);
110
- if (entryMd?.[1] && entryMd[2]) return { name: entryMd[1], inside: entryMd[2] };
111
- const mock = /^(.+)\/(mocks\/[^/]+\.json)$/.exec(relative);
112
- if (mock?.[1] && mock[2]) return { name: mock[1], inside: mock[2] };
113
- return null;
114
- }
@@ -1,38 +0,0 @@
1
- // Everything the Worker needs from its environment. The platform injects the
2
- // real bindings and secrets at deploy time; local defaults live in
3
- // wrangler.jsonc and .dev.vars.
4
- export interface Env {
5
- // Your app's private database and file storage.
6
- DB: D1Database;
7
- FILES: R2Bucket;
8
-
9
- // PPLE ID — the Worker validates bearer tokens against this base URL.
10
- SSO_BASE_URL: string;
11
-
12
- // Audience-bound notifications (see src/notify.ts). Base is a var; the key
13
- // is a platform-provisioned secret. Both may be empty locally.
14
- NOTIFY_API_BASE: string;
15
- NOTIFY_API_KEY?: string;
16
-
17
- // Platform Services (ADR-0022). The App Key is a secret; the URL is plain.
18
- // Both are empty until the platform binds them. `callService` reads them
19
- // (src/call-service.ts); the Builder does not put the App Key on a request.
20
- PPLE_SERVICES_URL?: string;
21
- PPLE_APP_KEY?: string;
22
-
23
- // Local development only: which mock persona to sign in as (src/dev-personas.ts).
24
- // Unset means the default persona; "none" turns the bypass off. Never set in
25
- // production — the dev bypass is compiled out of the deployed Worker anyway.
26
- DEV_PERSONA?: string;
27
-
28
- // Local development only: make offline `callService` and `readDataset`
29
- // return a platform refusal instead of a mock (`not_granted`,
30
- // `level_not_met`, `renamed`, …). A bare code applies to every entry;
31
- // `<name>=<code>` wins for that entry. Comma-separated.
32
- // Compiled out with the offline path.
33
- DEV_REGISTRY_ERROR?: string;
34
-
35
- // Local development only: the Consumer slug on the emulated registry path.
36
- // Unset means `dev-consumer`. Compiled out with the dev wrapper.
37
- DEV_CONSUMER?: string;
38
- }
@@ -1,38 +0,0 @@
1
- // R2 (object storage) upload example. R2 is your app's private bucket for
2
- // files — images, PDFs, exports. Store the human-facing filename in custom
3
- // metadata so listings can show it; the object key itself is a random id.
4
- import type { UploadedFile } from "../shared/api";
5
-
6
- function toUploaded(
7
- key: string,
8
- name: string,
9
- size: number,
10
- uploaded: Date,
11
- ): UploadedFile {
12
- return { key, name, size, uploadedAt: uploaded.toISOString() };
13
- }
14
-
15
- export async function putFile(
16
- bucket: R2Bucket,
17
- name: string,
18
- body: ReadableStream | ArrayBuffer | string,
19
- contentType?: string,
20
- ): Promise<UploadedFile> {
21
- const key = crypto.randomUUID();
22
- const obj = await bucket.put(key, body, {
23
- httpMetadata: contentType ? { contentType } : undefined,
24
- customMetadata: { name },
25
- });
26
- return toUploaded(obj.key, name, obj.size, obj.uploaded);
27
- }
28
-
29
- export async function listFiles(bucket: R2Bucket): Promise<UploadedFile[]> {
30
- const listed = await bucket.list({ limit: 50, include: ["customMetadata"] });
31
- return listed.objects.map((o) =>
32
- toUploaded(o.key, o.customMetadata?.name ?? o.key, o.size, o.uploaded),
33
- );
34
- }
35
-
36
- export function getFile(bucket: R2Bucket, key: string): Promise<R2ObjectBody | null> {
37
- return bucket.get(key);
38
- }
@@ -1,17 +0,0 @@
1
- // How a Provider test and the dev server build `x-pple-identity` (ADR-0024).
2
- //
3
- // Base64url (RFC 4648 §5, no padding) of the UTF-8 JSON `{ actor, effective }`.
4
- // A Thai name is not a reliable raw header value. `serviceCall` decodes this
5
- // exact encoding. The platform's copy is
6
- // `workers/src/services/identity-header.ts`; a test keeps the two strings
7
- // equal. One function, so the dev wrapper and `callRegistry` cannot drift.
8
-
9
- import type { Identity } from "../shared/api";
10
-
11
- /** Base64url of the Identity JSON. ASCII, so it survives an HTTP header. */
12
- export function encodeIdentityHeader(identity: Identity): string {
13
- const bytes = new TextEncoder().encode(JSON.stringify(identity));
14
- let binary = "";
15
- for (const byte of bytes) binary += String.fromCharCode(byte);
16
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
17
- }