@pplethai/cli 0.22.0 → 0.23.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 +102 -102
  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,392 +0,0 @@
1
- // Offline Consumer calls (ADR-0026). Active only where `import.meta.env.DEV`
2
- // is true and `DEV_PERSONA` is not `"none"` — `vite dev`, not vitest and not
3
- // the production build. `callService` reaches this module only from that
4
- // branch, so `vite build` drops it the same way it drops the Persona bypass
5
- // (ADR-0011).
6
- //
7
- // The overlay is `.pple/registry/<full name>/`, written by the CLI (ADR-0031,
8
- // ADR-0032: an entry is named by its full name, so `election/2027/score` is
9
- // nested folders; the Provider is not part of the path).
10
- // Vite's `import.meta.glob` skips a dot-folder unless the dot sits in the
11
- // pattern's fixed base, so the glob below keeps `.pple/registry` in that
12
- // base. CI has no overlay; tests pass a fixture glob to `answerFromOverlay`
13
- // and never read `.pple/`.
14
- //
15
- // Offline the app is granted, at least Beta, and the entry is listed.
16
- // Platform refusals come only from `DEV_REGISTRY_ERROR`. `getLegalIdentity`
17
- // does not use this module: its built-in Persona answer stays in front of
18
- // `callService`.
19
-
20
- import type { PlatformErrorCode } from "./call-service";
21
- import { isEntryName, entryNameError, overlayEntryFile } from "./entry-name";
22
- import { DEV_PERSONAS, DEFAULT_DEV_PERSONA, resolveDevPersona } from "./dev-personas";
23
-
24
- /** Statuses for every platform code. Keyed by the union, so a new code fails typecheck here. */
25
- const PLATFORM_ERROR_STATUS: Record<PlatformErrorCode, number> = {
26
- invalid_app_key: 401,
27
- not_listed: 404,
28
- not_granted: 403,
29
- needs_beta: 403,
30
- user_token_invalid: 401,
31
- identity_unavailable: 503,
32
- provider_unavailable: 502,
33
- provider_timeout: 504,
34
- method_not_allowed: 405,
35
- not_found: 404,
36
- invalid_query: 400,
37
- level_not_met: 403,
38
- renamed: 410,
39
- };
40
-
41
- const MOCK_HEADER = "x-pple-mock";
42
- const ERROR_HEADER = "x-pple-error";
43
-
44
- /** Statuses that must not carry a body. A mock that sets one still answers. */
45
- const NULL_BODY = new Set([101, 204, 205, 304]);
46
-
47
- export interface MockCase {
48
- method?: string;
49
- path?: string;
50
- persona?: string | readonly string[];
51
- status?: number;
52
- headers?: Readonly<Record<string, string>>;
53
- body?: unknown;
54
- }
55
-
56
- export interface OverlayCall {
57
- entry: string;
58
- /** Path tail `callService` received, query included. The query is not matched. */
59
- path: string;
60
- method?: string;
61
- userToken?: string;
62
- /** Active Persona name. A name the Builder added matches only unscoped cases. */
63
- persona: string;
64
- devRegistryError?: string;
65
- /** Where the overlay starts in `files`' keys. Omitted: `.pple/registry/`. Tests with a fixture folder set it. */
66
- overlayRoot?: string;
67
- }
68
-
69
- interface IndexedEntry {
70
- userToken: "required" | "none" | null;
71
- cases: unknown[];
72
- }
73
-
74
- /**
75
- * The first case that matches, or null. `method` and `persona` are optional
76
- * on a case and then match anything. An omitted `path` matches any path — a
77
- * root route has to say `"/"` or it would match every tail. `"/"` is the
78
- * empty tail. `:param` is one segment. A final `*` segment matches one or
79
- * more remaining segments. The query is ignored.
80
- */
81
- export function matchMockCase(
82
- cases: readonly unknown[],
83
- method: string,
84
- path: string,
85
- persona: string,
86
- ): MockCase | null {
87
- for (const item of cases) {
88
- if (item === null || typeof item !== "object" || Array.isArray(item)) continue;
89
- const record = item as Record<string, unknown>;
90
- if (!methodMatches("method" in record ? record.method : undefined, method)) continue;
91
- if (!pathMatches("path" in record ? record.path : undefined, path)) continue;
92
- if (!personaMatches("persona" in record ? record.persona : undefined, persona)) continue;
93
- return record as MockCase;
94
- }
95
- return null;
96
- }
97
-
98
- /**
99
- * The response a Builder observes for one offline call. `files` is an
100
- * `import.meta.glob` result (path → raw text), either the overlay or a
101
- * fixture.
102
- */
103
- export function answerFromOverlay(
104
- files: Readonly<Record<string, unknown>>,
105
- call: OverlayCall,
106
- ): Response {
107
- const forced = forcedError(call.devRegistryError, call.entry);
108
- if (forced) return platformRefusal(forced);
109
-
110
- const entry = indexOverlay(files, call.overlayRoot).get(call.entry);
111
- if (!entry) return noMock(missingEntryMessage(call.entry));
112
-
113
- if (entry.userToken === "required" && !hasToken(call.userToken)) {
114
- return platformRefusal("user_token_invalid");
115
- }
116
-
117
- const method = call.method?.trim() || "GET";
118
- const matched = matchMockCase(entry.cases, method, call.path, call.persona);
119
- if (!matched) return noMock(missingRouteMessage(call.entry, method, call.path));
120
- return mockResponse(call.entry, matched);
121
- }
122
-
123
- /** `npm run dev` entry. Reads the overlay glob and the active Persona. */
124
- export function answerOfflineCall(
125
- env: { DEV_PERSONA?: string; DEV_REGISTRY_ERROR?: string },
126
- entry: string,
127
- path: string,
128
- init: RequestInit = {},
129
- options: { userToken?: string } = {},
130
- ): Response {
131
- return answerFromOverlay(overlayFiles(), {
132
- entry,
133
- path,
134
- method: init.method,
135
- userToken: options.userToken,
136
- persona: activePersonaName(env.DEV_PERSONA),
137
- devRegistryError: env.DEV_REGISTRY_ERROR,
138
- });
139
- }
140
-
141
- function overlayFiles(): Record<string, unknown> {
142
- // Production inlines DEV as false and drops the glob, including any
143
- // overlay files that happen to be on disk at build time. The dot-folder
144
- // is in the fixed base (ADR-0026).
145
- if (!import.meta.env.DEV) return {};
146
- return import.meta.glob("../.pple/registry/**/*", {
147
- eager: true,
148
- query: "?raw",
149
- import: "default",
150
- });
151
- }
152
-
153
- function activePersonaName(configured: string | undefined): string {
154
- const key = configured?.trim() || DEFAULT_DEV_PERSONA;
155
- if (Object.hasOwn(DEV_PERSONAS, key)) return key;
156
- // Unknown names warn and sign in as the default, same as the rest of local dev.
157
- resolveDevPersona(configured);
158
- return DEFAULT_DEV_PERSONA;
159
- }
160
-
161
- function indexOverlay(files: Readonly<Record<string, unknown>>, root?: string): Map<string, IndexedEntry> {
162
- const found = new Map<string, { entryMd?: string; responses?: string }>();
163
- for (const [file, value] of Object.entries(files)) {
164
- const text = asText(value);
165
- if (text === null) continue;
166
- const at = overlayEntryFile(file, root);
167
- if (!at) continue;
168
- const row = found.get(at.name) ?? {};
169
- if (at.inside === "entry.md") row.entryMd = text;
170
- else if (at.inside === "mocks/responses.json") row.responses = text;
171
- else continue;
172
- found.set(at.name, row);
173
- }
174
-
175
- const entries = new Map<string, IndexedEntry>();
176
- for (const [id, row] of found) {
177
- entries.set(id, {
178
- userToken: row.entryMd ? declaredUserToken(row.entryMd) : null,
179
- cases: row.responses ? parseCases(id, row.responses) : [],
180
- });
181
- }
182
- return entries;
183
- }
184
-
185
- function asText(value: unknown): string | null {
186
- if (typeof value === "string") return value;
187
- if (value !== null && typeof value === "object" && "default" in value) {
188
- const inner = (value as { default: unknown }).default;
189
- if (typeof inner === "string") return inner;
190
- }
191
- return null;
192
- }
193
-
194
- function declaredUserToken(entryMd: string): "required" | "none" | null {
195
- const fence = entryMd.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
196
- const front = fence?.[1];
197
- if (!front) return null;
198
- for (const line of front.split(/\r?\n/)) {
199
- const match = /^userToken:\s*(.*?)\s*$/.exec(line);
200
- if (!match) continue;
201
- const value = (match[1] ?? "").replace(/^["']|["']$/g, "");
202
- if (value === "required" || value === "none") return value;
203
- return null;
204
- }
205
- return null;
206
- }
207
-
208
- function parseCases(entry: string, text: string): unknown[] {
209
- try {
210
- const parsed = JSON.parse(text) as unknown;
211
- if (Array.isArray(parsed)) return parsed;
212
- } catch {
213
- // Fall through to the warning. A broken file is "no case matched".
214
- }
215
- console.warn(
216
- `callService could not read .pple/registry/${entry}/mocks/responses.json. Run pple registry to refresh it.`,
217
- );
218
- return [];
219
- }
220
-
221
- function hasToken(userToken: string | undefined): boolean {
222
- return userToken !== undefined && userToken.trim() !== "";
223
- }
224
-
225
- /**
226
- * A per-entry `<full name>=<code>` wins over a bare `<code>`. An
227
- * unknown code is ignored, so a bad per-entry rule falls through to the
228
- * global one. Checked before the missing-token refusal: `not_granted` and
229
- * `needs_beta` are answers the platform gives before it looks at the token.
230
- */
231
- export function forcedError(spec: string | undefined, entry: string): PlatformErrorCode | null {
232
- if (spec === undefined || spec.trim() === "") return null;
233
- const rules: { entry: string | null; code: string }[] = [];
234
- for (const part of spec.split(",")) {
235
- const item = part.trim();
236
- if (item === "") continue;
237
- const eq = item.indexOf("=");
238
- if (eq === -1) {
239
- rules.push({ entry: null, code: item });
240
- continue;
241
- }
242
- const id = item.slice(0, eq).trim();
243
- const code = item.slice(eq + 1).trim();
244
- if (id === "" || code === "") {
245
- console.warn(`DEV_REGISTRY_ERROR ignores "${item}".`);
246
- continue;
247
- }
248
- if (!isEntryName(id)) {
249
- console.warn(`DEV_REGISTRY_ERROR ignores "${item}": ${entryNameError(id)}.`);
250
- continue;
251
- }
252
- rules.push({ entry: id, code });
253
- }
254
-
255
- const known = rules.filter((rule) => {
256
- if (isPlatformCode(rule.code)) return true;
257
- console.warn(`DEV_REGISTRY_ERROR ignores unknown code "${rule.code}".`);
258
- return false;
259
- });
260
- const specific = known.find((rule) => rule.entry === entry);
261
- if (specific) return specific.code as PlatformErrorCode;
262
- const global = known.find((rule) => rule.entry === null);
263
- return global ? (global.code as PlatformErrorCode) : null;
264
- }
265
-
266
- function isPlatformCode(code: string): code is PlatformErrorCode {
267
- return Object.prototype.hasOwnProperty.call(PLATFORM_ERROR_STATUS, code);
268
- }
269
-
270
- export function platformRefusal(code: PlatformErrorCode): Response {
271
- return Response.json(
272
- { error: code },
273
- { status: PLATFORM_ERROR_STATUS[code], headers: { [ERROR_HEADER]: code } },
274
- );
275
- }
276
-
277
- function noMock(message: string): Response {
278
- return Response.json(
279
- { error: "no_mock", message },
280
- { status: 404, headers: { [ERROR_HEADER]: "no_mock" } },
281
- );
282
- }
283
-
284
- function missingEntryMessage(entry: string): string {
285
- return `ไม่มี ${entry} ใน .pple/registry/ — รัน pple registry เพื่อดึงข้อมูลจำลอง`;
286
- }
287
-
288
- function missingRouteMessage(entry: string, method: string, path: string): string {
289
- const tail = path === "" ? "/" : path;
290
- return `${entry} ไม่มีข้อมูลจำลองสำหรับ ${method.toUpperCase()} ${tail} — รัน pple registry เพื่อรีเฟรช`;
291
- }
292
-
293
- function mockResponse(entry: string, matched: MockCase): Response {
294
- const headers = new Headers();
295
- const raw = matched.headers;
296
- if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
297
- for (const [name, value] of Object.entries(raw)) {
298
- if (typeof value !== "string") continue;
299
- if (name.toLowerCase().startsWith("x-pple-")) continue;
300
- headers.set(name, value);
301
- }
302
- }
303
- headers.set(MOCK_HEADER, entry);
304
-
305
- const status = httpStatus(matched.status);
306
- if (NULL_BODY.has(status)) return new Response(null, { status, headers });
307
-
308
- const body = matched.body;
309
- if (body === undefined) return new Response(null, { status, headers });
310
- // A string is text (issue #230). Every other JSON value is a JSON body.
311
- if (typeof body === "string") {
312
- if (!headers.has("content-type")) headers.set("content-type", "text/plain;charset=UTF-8");
313
- return new Response(body, { status, headers });
314
- }
315
- if (!headers.has("content-type")) headers.set("content-type", "application/json");
316
- return new Response(JSON.stringify(body), { status, headers });
317
- }
318
-
319
- function httpStatus(value: unknown): number {
320
- if (typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599) {
321
- return value;
322
- }
323
- return 200;
324
- }
325
-
326
- const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]);
327
- const LITERAL_SEGMENT = /^[A-Za-z0-9._~-]+$/;
328
- const PARAM_SEGMENT = /^:[A-Za-z_][A-Za-z0-9_-]*$/;
329
-
330
- function methodMatches(pattern: unknown, method: string): boolean {
331
- if (pattern === undefined) return true;
332
- if (typeof pattern !== "string" || !METHODS.has(pattern.toUpperCase())) return false;
333
- return pattern.toUpperCase() === method.toUpperCase();
334
- }
335
-
336
- function personaMatches(pattern: unknown, persona: string): boolean {
337
- if (pattern === undefined) return true;
338
- if (typeof pattern === "string") return pattern === persona;
339
- if (!Array.isArray(pattern) || pattern.length === 0) return false;
340
- if (!pattern.every((item) => typeof item === "string" && item !== "")) return false;
341
- return pattern.includes(persona);
342
- }
343
-
344
- function pathMatches(pattern: unknown, requestPath: string): boolean {
345
- if (pattern === undefined) return true;
346
- if (typeof pattern !== "string") return false;
347
- const wanted = patternSegments(pattern);
348
- if (wanted === null) return false;
349
- const got = requestSegments(requestPath);
350
- const wildcard = wanted.at(-1) === "*";
351
- const fixed = wildcard ? wanted.slice(0, -1) : wanted;
352
- if (wildcard ? got.length <= fixed.length : got.length !== fixed.length) return false;
353
- for (let i = 0; i < fixed.length; i++) {
354
- const want = fixed[i];
355
- const have = got[i];
356
- if (want === undefined || have === undefined || have === "") return false;
357
- if (want.startsWith(":")) continue;
358
- if (want !== have) return false;
359
- }
360
- return !wildcard || got.slice(fixed.length).every((segment) => segment !== "");
361
- }
362
-
363
- /** Same path language as the entry validator. `"/"` is the empty tail. Null means the pattern is not that language. */
364
- function patternSegments(path: string): string[] | null {
365
- if (path === "/") return [];
366
- if (path.includes("?") || path.includes("#") || path.includes("\\") || path.includes(" ")) return null;
367
- const body = path.startsWith("/") ? path.slice(1) : path;
368
- if (body === "" || body.endsWith("/")) return null;
369
- const segments = body.split("/");
370
- for (let i = 0; i < segments.length; i++) {
371
- const segment = segments[i];
372
- if (segment === undefined || segment === "") return null;
373
- if (segment === "*") {
374
- if (i !== segments.length - 1) return null;
375
- continue;
376
- }
377
- if (segment.includes("*")) return null;
378
- if (segment.startsWith(":")) {
379
- if (!PARAM_SEGMENT.test(segment)) return null;
380
- continue;
381
- }
382
- if (!LITERAL_SEGMENT.test(segment)) return null;
383
- }
384
- return segments;
385
- }
386
-
387
- function requestSegments(path: string): string[] {
388
- const head = path.split("?")[0]?.split("#")[0] ?? "";
389
- if (head === "" || head === "/") return [];
390
- const body = head.startsWith("/") ? head.slice(1) : head;
391
- return body.split("/");
392
- }
@@ -1,186 +0,0 @@
1
- // Mock identities for local development (`npm run dev`).
2
- //
3
- // Pick one with DEV_PERSONA in .dev.vars (default "hq-staff"); add your own by
4
- // appending to DEV_PERSONAS. Each persona is a real Identity shape, so what
5
- // works against a persona works against a real PPLE ID user in production.
6
- //
7
- // This whole module is compiled out of the deployed Worker: it is only reached
8
- // from `import.meta.env.DEV` branches (the Persona bypass in src/auth.ts, the
9
- // offline Legal Identity answer, offline callService, offline readDataset,
10
- // and the registry dev wrapper), which
11
- // `vite build` eliminates (docs/adr/0011). Nothing here can run in production.
12
- //
13
- // The rule your app code must follow (docs/adr/0012): gate authorization on
14
- // `effective`, use `actor` for audit/display only, and honor
15
- // `effective.isDelegated`.
16
- import type { Identity, KycStatus } from "../shared/api";
17
-
18
- export const DEFAULT_DEV_PERSONA = "hq-staff";
19
-
20
- /** An active member: verified through membership, not a national-ID check. */
21
- function memberKyc(verifiedAt: string): KycStatus {
22
- return { status: "verified", verified: true, verifiedAt, source: "membership" };
23
- }
24
-
25
- /** `YYYY-MM-DD` from the same day as this Persona's KYC date. */
26
- function activeMembership(memberSince: string): Identity["actor"]["membership"] {
27
- return { memberSince };
28
- }
29
-
30
- /** A person acting as themselves: effective.sub is their own actor sub. */
31
- function own(sub: string): Identity["effective"] {
32
- return {
33
- isDelegated: false,
34
- sub,
35
- activeRole: "",
36
- eligibleRoles: [],
37
- provinces: [],
38
- extraRoles: [],
39
- };
40
- }
41
-
42
- export const DEV_PERSONAS: Record<string, Identity> = {
43
- // Party HQ staff: every province in scope, no special capabilities. Default.
44
- "hq-staff": {
45
- actor: {
46
- sub: "dev-hq-staff",
47
- name: "Local Dev (HQ)",
48
- mobile: "0800000001",
49
- kyc: memberKyc("2024-01-01T00:00:00.000Z"),
50
- membership: activeMembership("2024-01-01"),
51
- },
52
- effective: {
53
- isDelegated: false,
54
- sub: "dev-hq-staff",
55
- activeRole: "hq",
56
- eligibleRoles: ["hq"],
57
- provinces: ["all"],
58
- extraRoles: [],
59
- },
60
- },
61
-
62
- // A province coordinator: scoped to a single province.
63
- "province-coordinator": {
64
- actor: {
65
- sub: "dev-province-coordinator",
66
- name: "Local Dev (จังหวัด)",
67
- mobile: "0800000002",
68
- kyc: memberKyc("2024-02-01T00:00:00.000Z"),
69
- membership: activeMembership("2024-02-01"),
70
- },
71
- effective: {
72
- isDelegated: false,
73
- sub: "dev-province-coordinator",
74
- activeRole: "province",
75
- eligibleRoles: ["province"],
76
- provinces: ["เชียงใหม่"],
77
- extraRoles: ["province_co"],
78
- },
79
- },
80
-
81
- // Carries the platform:admin extra-role (may work the platform admin queue).
82
- "platform-admin": {
83
- actor: {
84
- sub: "dev-platform-admin",
85
- name: "Local Dev (Admin)",
86
- mobile: "0800000003",
87
- kyc: memberKyc("2024-03-01T00:00:00.000Z"),
88
- membership: activeMembership("2024-03-01"),
89
- },
90
- effective: {
91
- isDelegated: false,
92
- sub: "dev-platform-admin",
93
- activeRole: "hq",
94
- eligibleRoles: ["hq"],
95
- provinces: ["all"],
96
- extraRoles: ["platform:admin"],
97
- },
98
- },
99
-
100
- // A delegate acting for the province coordinator: effective.* are the
101
- // SUPERVISOR's role, scope, and sub. actor.* is the delegate human, and
102
- // isDelegated is true. KYC Status is the delegate's own.
103
- delegate: {
104
- actor: {
105
- sub: "dev-delegate",
106
- name: "Local Dev (ผู้รับมอบ)",
107
- mobile: "0800000004",
108
- kyc: memberKyc("2024-04-01T00:00:00.000Z"),
109
- membership: activeMembership("2024-04-01"),
110
- },
111
- effective: {
112
- isDelegated: true,
113
- sub: "dev-province-coordinator",
114
- activeRole: "province",
115
- eligibleRoles: ["province"],
116
- provinces: ["เชียงใหม่"],
117
- extraRoles: [],
118
- },
119
- },
120
-
121
- // No KYC Status at all.
122
- unverified: {
123
- actor: {
124
- sub: "dev-unverified",
125
- name: "Local Dev (ยังไม่ยืนยัน)",
126
- mobile: "0800000005",
127
- kyc: { status: "none", verified: false, verifiedAt: null, source: null },
128
- membership: null,
129
- },
130
- effective: own("dev-unverified"),
131
- },
132
-
133
- // Submitted a national ID and waiting on review.
134
- "kyc-pending": {
135
- actor: {
136
- sub: "dev-kyc-pending",
137
- name: "Local Dev (รอตรวจ)",
138
- mobile: "0800000006",
139
- kyc: { status: "pending_review", verified: false, verifiedAt: null, source: null },
140
- membership: null,
141
- },
142
- effective: own("dev-kyc-pending"),
143
- },
144
-
145
- // Verified with a national ID, and not a party member.
146
- "kyc-verified-nonmember": {
147
- actor: {
148
- sub: "dev-kyc-verified",
149
- name: "Local Dev (ยืนยันด้วยบัตร)",
150
- mobile: "0800000007",
151
- kyc: {
152
- status: "verified",
153
- verified: true,
154
- verifiedAt: "2024-05-01T00:00:00.000Z",
155
- source: "kyc",
156
- },
157
- membership: null,
158
- },
159
- effective: own("dev-kyc-verified"),
160
- },
161
-
162
- // A party member with no Role. member and internal differ offline (ADR-0028).
163
- member: {
164
- actor: {
165
- sub: "dev-member",
166
- name: "Local Dev (สมาชิก)",
167
- mobile: "0800000008",
168
- kyc: memberKyc("2024-06-01T00:00:00.000Z"),
169
- membership: activeMembership("2024-06-01"),
170
- },
171
- effective: own("dev-member"),
172
- },
173
- };
174
-
175
- /** Resolve the configured persona; an unknown name warns and falls back to the
176
- * default so a typo never breaks local dev. */
177
- export function resolveDevPersona(name: string | undefined): Identity {
178
- const key = name?.trim() || DEFAULT_DEV_PERSONA;
179
- const persona = DEV_PERSONAS[key];
180
- if (persona) return persona;
181
- console.warn(
182
- `Unknown DEV_PERSONA "${key}"; using "${DEFAULT_DEV_PERSONA}". ` +
183
- `Valid personas: ${Object.keys(DEV_PERSONAS).join(", ")}.`,
184
- );
185
- return DEV_PERSONAS[DEFAULT_DEV_PERSONA] as Identity;
186
- }