@foliwake/server 0.9.0 → 0.10.2

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/CHANGELOG.md CHANGED
@@ -7,6 +7,61 @@ minor release may break; breaking changes are marked **BREAKING**.
7
7
 
8
8
  Entries are written from the changesets of each pull request (`.changeset/`, CONTRIBUTING.md), newest first.
9
9
 
10
+ ## 0.10.2
11
+
12
+ ### Patch Changes
13
+
14
+ - 964b5e5: Links point to the public documentation on foliwake.org (`docs.foliwake.org`, `sdk.foliwake.org`); the config
15
+ schemas' `$id` is under `https://foliwake.org/schemas/`.
16
+ - Updated dependencies [964b5e5]
17
+ - @foliwake/blocks-contract@0.10.2
18
+
19
+ ## 0.10.1
20
+
21
+ ### Patch Changes
22
+
23
+ - 55ffb45: Site code may have an `editor/` folder: data that authoring tools read, such as a palette or block metadata. The
24
+ code proxy (`codeRoute` / `codeHandler`) now serves its files like the other site code, and `site-check` counts it
25
+ as site code. Pages never load it.
26
+ - 44822ad: The hook trims leading and trailing whitespace and newlines from the secret read from `secretEnv` and
27
+ `previousSecretEnv` (a secret pasted with a trailing newline used to fail every signature), warns once naming the
28
+ variable (never the value), and treats an all-whitespace value as unset. New: `hookSecretsFrom` in
29
+ `@foliwake/server/hook-endpoint`. The docs make the secret with `openssl rand -hex 32 | tr -d '\n'`.
30
+ - @foliwake/blocks-contract@0.10.1
31
+
32
+ ## 0.10.0
33
+
34
+ ### Minor Changes
35
+
36
+ - 339fb47: A page's code release names its blocks module. `readEnvelope` reads `X-Foliwake-Blocks`
37
+ (`entry="scripts/blocks.js", contract=2, prefix="demo"`) into `envelope.blocks`; with a version 3 config without
38
+ `app.blocks`, `preparePage` mounts that entry with its contract and event prefix (`app.blocks` still wins, and a
39
+ version 2 config is unchanged). Preload hints follow the page's entry. `FoliwakePageData.title` is the text of the
40
+ body's first `<h1>`. `@foliwake/site-check` accepts and checks the optional `blocks` key of
41
+ `components/components.json` with the engine's rule (an entry under scripts, components or _foliwake ending in .js
42
+ that exists, a contract major, an event prefix).
43
+ - 69caab7: Configure an app by one address. `@foliwake/server/discovery` reads a site's `/.well-known/foliwake.json`
44
+ (no redirects, 5 s, one retry, at most 16 KiB; `live.url` must be the origin it was read from; the discovery format
45
+ and the plain contract are checked). `@foliwake/server/resolve` builds the app config from `FOLIWAKE_URL` and the
46
+ optional `foliwake.remote.json` version 3 (overrides only: pages, revalidate, proxies, media, blocks, auth by
47
+ variable name; schema `schemas/remote-3.schema.json`, also shipped in `@foliwake/next`). Defaults: pages `/**`
48
+ (required explicitly when live uses a service token), proxies `/foliwake/code` and `/foliwake/media`, preview
49
+ read with Basic `preview` and `FOLIWAKE_PREVIEW_TOKEN`. A version 2 file without `FOLIWAKE_URL` works unchanged.
50
+ `FoliwakeAppConfig.version` is now `2 | 3` and `app.blocks` has `fromRelease`. The compatibility metadata is
51
+ `remoteConfig: 3, discovery: 1`.
52
+ - df85d39: `@foliwake/server/handler`: `createFoliwakeHandler()` serves every Foliwake route of an app as one
53
+ `(request: Request) => Promise<Response>` on the Web Fetch API, for any framework: the code and media proxies under
54
+ the config's prefixes (`/foliwake/code`, `/foliwake/media` by default), `POST /foliwake/hook` (secret in
55
+ `FOLIWAKE_HOOK_SECRET`, `onDelivery` for the app's caches) and `GET /foliwake/health`. Preview is off unless
56
+ `authorizePreview` is given. The config is read on the first request (`FOLIWAKE_URL`), or passed as `config`.
57
+ The hook endpoint core moved from `@foliwake/next` to `@foliwake/server/hook-endpoint` (`createHookEndpoint`);
58
+ a ping of the Next route still answers `@foliwake/next/<version>`. New guide: "Any framework: one handler".
59
+
60
+ ### Patch Changes
61
+
62
+ - Updated dependencies [339fb47]
63
+ - @foliwake/blocks-contract@0.10.0
64
+
10
65
  ## 0.9.0
11
66
 
12
67
  ### Minor Changes
package/README.md CHANGED
@@ -19,7 +19,12 @@ directly with another server framework (a Vite or Remix server, Hono, Express wi
19
19
  | `@foliwake/server/csp` | `foliwakeCsp` |
20
20
  | `@foliwake/server/preload` | `preloadHints`: modulepreload and stylesheet hints for a page's blocks |
21
21
  | `@foliwake/server/hook` | `verifyFoliwakeSignature`, `parseFoliwakeHook`: the signed hook a Foliwake server sends after a change |
22
- | `@foliwake/server/schemas/remote-2.schema.json` | the JSON Schema of the config file |
22
+ | `@foliwake/server/handler` | `createFoliwakeHandler`: every Foliwake route of an app (code, media, hook, health) as one `(request) => Promise<Response>` |
23
+ | `@foliwake/server/hook-endpoint` | `createHookEndpoint`: the hook endpoint without a framework (verify, parse, expire, answer) |
24
+ | `@foliwake/server/discovery` | `fetchDiscovery`, `parseDiscovery`: the site's `/.well-known/foliwake.json` |
25
+ | `@foliwake/server/resolve` | `loadAppConfig`, `readConfigSnapshot`, `configFromSnapshot`: `FOLIWAKE_URL` + discovery + the optional version 3 file, or a version 2 file |
26
+ | `@foliwake/server/schemas/remote-2.schema.json` | the JSON Schema of the config file (version 2) |
27
+ | `@foliwake/server/schemas/remote-3.schema.json` | the JSON Schema of the optional version 3 file (overrides) |
23
28
 
24
29
  ## Install
25
30
 
@@ -38,7 +43,7 @@ The config file sits in the app's root and holds no secrets, only the names of t
38
43
  "version": 2,
39
44
  "site": "mysite",
40
45
  "live": { "url": "https://mysite.example.org" },
41
- "preview": { "url": "https://preview.mysite.example.org", "auth": { "type": "basic", "username": "app", "passwordEnv": "MYSITE_PREVIEW_PASSWORD" } },
46
+ "preview": { "url": "https://preview.mysite.example.org", "auth": { "type": "basic", "username": "preview", "passwordEnv": "MYSITE_PREVIEW_TOKEN" } },
42
47
  "app": {
43
48
  "pages": ["/**"],
44
49
  "proxies": { "code": "/foliwake-code", "media": "/foliwake-media", "pages": null },
@@ -424,7 +429,7 @@ interface BasicAuth
424
429
 
425
430
  #### `FoliwakeAppConfig`
426
431
 
427
- A parsed and validated `foliwake.remote.json` (version 2). It holds credential variable names, never secrets.
432
+ A validated app config: a `foliwake.remote.json` version 2, or (version 3) the site's discovery document merged with the optional version 3 file. It holds credential variable names, never secrets.
428
433
 
429
434
  ```ts
430
435
  interface FoliwakeAppConfig
@@ -432,7 +437,7 @@ interface FoliwakeAppConfig
432
437
 
433
438
  | Member | Type | Description |
434
439
  | --- | --- | --- |
435
- | `version` | `2` | |
440
+ | `version` | `2 \| 3` | |
436
441
  | `site` | `string` | |
437
442
  | `live` | `FoliwakeEndpoint \| null` | |
438
443
  | `preview` | `FoliwakeEndpoint \| null` | |
@@ -451,7 +456,7 @@ interface FoliwakeAppSettings
451
456
  | --- | --- | --- |
452
457
  | `pages` | `readonly string[]` | Page globs the app may read. |
453
458
  | `proxies` | `{ code: string; media: string; pages: null; }` | App-origin URL prefixes of the proxies. |
454
- | `blocks` | `{ entry: string \| null; contract: string; major: number; eventPrefix: string; }` | Where `mountBlocks` lives in a code release; null: bodies stay static. |
459
+ | `blocks` | `{ entry: string \| null; contract: string; major: number; eventPrefix: string; fromRelease: boolean; }` | Where `mountBlocks` lives in a code release; null: bodies stay static. `fromRelease`: the config names no blocks (version 3), so each page's code release names them (`X-Foliwake-Blocks`); false for version 2. |
455
460
  | `media` | `{ base: string; transform: 'cloudflare-images' \| null; } \| null` | Live media through a transforming host; null: media through the proxy. |
456
461
  | `revalidate` | `number` | Seconds before a cached envelope is stale (stale-while-revalidate). |
457
462
 
@@ -591,17 +596,38 @@ interface OriginRequestOptions
591
596
 
592
597
  #### `blocksUrlOf()`
593
598
 
594
- The same-origin URL of the blocks module, or null when the config names no blocks entry.
599
+ The same-origin URL of the blocks module, or null without an entry.
595
600
 
596
601
  ```ts
597
- function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId): {
602
+ function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId, entry?: string | null): {
598
603
  base: string;
599
604
  url: string;
600
605
  } | null
601
606
  ```
602
607
 
608
+ | Parameter | Type | Description |
609
+ | --- | --- | --- |
610
+ | `config` | `FoliwakeAppConfig` | |
611
+ | `channel` | `ChannelName` | |
612
+ | `codeRelease` | `CodeReleaseId` | |
613
+ | `entry?` | `string \| null` | The module inside the code release; default the config's `app.blocks.entry`. |
614
+
603
615
  **Returns** `{ base: string; url: string; } \| null`
604
616
 
617
+ #### `pageBlocksOf()`
618
+
619
+ The blocks a page mounts: the config's, or (version 3 without `app.blocks`) the ones its code release names.
620
+
621
+ ```ts
622
+ function pageBlocksOf(config: FoliwakeAppConfig, envelope: PageEnvelope): {
623
+ entry: string | null;
624
+ major: number;
625
+ eventPrefix: string;
626
+ }
627
+ ```
628
+
629
+ **Returns** `{ entry: string \| null; major: number; eventPrefix: string; }`
630
+
605
631
  #### `plainPath()`
606
632
 
607
633
  The origin URL path of a page's body (`/` → `/index.plain.html`).
@@ -1219,8 +1245,363 @@ Why a signature was refused.
1219
1245
  type SignatureFailure = 'malformed' | 'expired' | 'mismatch' | 'no_secret'
1220
1246
  ```
1221
1247
 
1248
+ ### `@foliwake/server/handler`
1249
+
1250
+ **Functions and components**
1251
+
1252
+ #### `createFoliwakeHandler()`
1253
+
1254
+ The Foliwake routes of an app as one `(request) => Promise<Response>`. The config is read on the first request (FOLIWAKE_URL and its discovery document, unless `config` is given) and kept; a failed read is tried again on the next request and answers 503 meanwhile.
1255
+
1256
+ ```ts
1257
+ function createFoliwakeHandler(opts?: FoliwakeHandlerOptions): FoliwakeFetchHandler
1258
+ ```
1259
+
1260
+ | Parameter | Type | Description |
1261
+ | --- | --- | --- |
1262
+ | `opts?` | `FoliwakeHandlerOptions` | `config`, `base`, `authorizePreview` (default false), `hook`, `env`, `fetch`, `log`. |
1263
+
1264
+ **Returns** `FoliwakeFetchHandler`
1265
+
1266
+ **Constants**
1267
+
1268
+ #### `HANDLER_BASE`
1269
+
1270
+ Where the handler is mounted by default: `/foliwake/hook`, `/foliwake/health`.
1271
+
1272
+ ```ts
1273
+ const HANDLER_BASE = "/foliwake"
1274
+ ```
1275
+
1276
+ #### `HOOK_SECRET_ENV`
1277
+
1278
+ The variable the hook's shared secret is read from by default.
1279
+
1280
+ ```ts
1281
+ const HOOK_SECRET_ENV = "FOLIWAKE_HOOK_SECRET"
1282
+ ```
1283
+
1284
+ **Interfaces**
1285
+
1286
+ #### `FoliwakeHandlerOptions`
1287
+
1288
+ Options of `createFoliwakeHandler`.
1289
+
1290
+ ```ts
1291
+ interface FoliwakeHandlerOptions
1292
+ ```
1293
+
1294
+ | Member | Type | Description |
1295
+ | --- | --- | --- |
1296
+ | `config?` | `FoliwakeAppConfig \| (() => FoliwakeAppConfig \| Promise<FoliwakeAppConfig>)` | The app config, or how to get it; default loadAppConfig() (FOLIWAKE_URL + the optional file), once. |
1297
+ | `base?` | `string` | The app path of the hook and health routes; default `/foliwake`. |
1298
+ | `authorizePreview?` | `AuthorizePreview` | The app's author check for preview files; default `false` (preview answers 404). |
1299
+ | `hook?` | `false \| FoliwakeHookOptions` | The hook endpoint's options; `false` answers 404 on `<base>/hook`. |
1300
+ | `env?` | `NodeJS.ProcessEnv` | Where secrets and FOLIWAKE_URL are read; default process.env. |
1301
+ | `fetch?` | `typeof fetch` | A fetch implementation (tests); default globalThis.fetch. |
1302
+ | `log?` | `Pick<Console, 'warn' \| 'error'>` | |
1303
+
1304
+ #### `FoliwakeHookOptions`
1305
+
1306
+ The hook endpoint of the handler.
1307
+
1308
+ ```ts
1309
+ interface FoliwakeHookOptions
1310
+ ```
1311
+
1312
+ | Member | Type | Description |
1313
+ | --- | --- | --- |
1314
+ | `secretEnv?` | `string` | The variable holding the shared secret; default FOLIWAKE_HOOK_SECRET. |
1315
+ | `previousSecretEnv?` | `string` | While the secret is rotated: the variable holding the previous one, also accepted. |
1316
+ | `onDelivery?` | `(payload: FoliwakeDeliveryPayload) => void \| Promise<void>` | Called for every delivery (expire your own caches here); a throw answers 500 and the server retries. |
1317
+ | `toleranceS?` | `number` | The allowed clock distance of the signature, in seconds; default 300. |
1318
+ | `endpoint?` | `(request: Request) => Promise<Response>` | Replaces the endpoint (a framework adapter's own, such as Next's tag expiry). |
1319
+
1320
+ **Types**
1321
+
1322
+ #### `FoliwakeFetchHandler`
1323
+
1324
+ A request handler on the Web Fetch API.
1325
+
1326
+ ```ts
1327
+ type FoliwakeFetchHandler = (request: Request) => Promise<Response>
1328
+ ```
1329
+
1330
+ ### `@foliwake/server/hook-endpoint`
1331
+
1332
+ **Functions and components**
1333
+
1334
+ #### `createHookEndpoint()`
1335
+
1336
+ The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a body that is not a payload or names another site, 200 otherwise.
1337
+
1338
+ ```ts
1339
+ function createHookEndpoint(deps: HookEndpointDeps): (request: Request) => Promise<Response>
1340
+ ```
1341
+
1342
+ **Returns** `(request: Request) => Promise<Response>`
1343
+
1344
+ #### `deliveryTags()`
1345
+
1346
+ The tags a delivery expires: the site's live tag on `all`, else one tag per listed path.
1347
+
1348
+ ```ts
1349
+ function deliveryTags(payload: FoliwakeDeliveryPayload, liveTag: (path?: string) => string): string[]
1350
+ ```
1351
+
1352
+ **Returns** `string[]`
1353
+
1354
+ #### `hookSecretsFrom()`
1355
+
1356
+ The `secrets()` of the hook endpoint read from environment variables: each value is trimmed of leading and trailing whitespace and newlines (a secret pasted from `openssl rand -hex 32` often ends in one), and an all-whitespace value counts as unset. The first time trimming changes a variable's value, one warning names the variable, never the value.
1357
+
1358
+ ```ts
1359
+ function hookSecretsFrom(source: HookSecretSource): () => (string | undefined)[]
1360
+ ```
1361
+
1362
+ **Returns** `() => (string \| undefined)[]`
1363
+
1364
+ #### `warmPaths()`
1365
+
1366
+ The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT.
1367
+
1368
+ ```ts
1369
+ function warmPaths(payload: FoliwakeDeliveryPayload): string[]
1370
+ ```
1371
+
1372
+ **Returns** `string[]`
1373
+
1374
+ **Constants**
1375
+
1376
+ #### `WARM_LIMIT`
1377
+
1378
+ At most this many pages are read again right after a delivery (`warm`); never on `all`.
1379
+
1380
+ ```ts
1381
+ const WARM_LIMIT = 20
1382
+ ```
1383
+
1384
+ **Interfaces**
1385
+
1386
+ #### `HookEndpointDeps`
1387
+
1388
+ What the endpoint needs from the framework and from the app.
1389
+
1390
+ ```ts
1391
+ interface HookEndpointDeps
1392
+ ```
1393
+
1394
+ | Member | Type | Description |
1395
+ | --- | --- | --- |
1396
+ | `site` | `string` | The configured site. |
1397
+ | `sdk` | `string` | What a `ping` answers as `sdk`: the package and its version (`@foliwake/next/0.9.0`). |
1398
+ | `secrets()` | `() => (string \| undefined)[]` | The accepted secrets, read per request (current, then previous). |
1399
+ | `liveTag()` | `(path?: string) => string` | The live tag of the site (no path) or of one path. |
1400
+ | `expire()` | `(tag: string) => void` | Expires one tag (revalidateTag with the chosen profile). |
1401
+ | `warm()` | `(path: string) => Promise<unknown>` | Reads one page into the cache again. |
1402
+ | `schedule()` | `(task: () => Promise<void>) => void` | Runs work after the response is sent. |
1403
+ | `warmPages` | `boolean` | Whether pages are read again after a delivery. |
1404
+ | `onDelivery?` | `(payload: FoliwakeDeliveryPayload) => void \| Promise<void>` | |
1405
+ | `toleranceS?` | `number` | |
1406
+ | `now?` | `() => number` | |
1407
+ | `log` | `Pick<Console, 'warn' \| 'error'>` | |
1408
+
1409
+ #### `HookSecretSource`
1410
+
1411
+ Where `hookSecretsFrom` reads and what it warns on.
1412
+
1413
+ ```ts
1414
+ interface HookSecretSource
1415
+ ```
1416
+
1417
+ | Member | Type | Description |
1418
+ | --- | --- | --- |
1419
+ | `names` | `readonly (string \| undefined)[]` | The variables, current first, then the previous one while it is rotated; undefined entries are skipped. |
1420
+ | `env?` | `NodeJS.ProcessEnv` | Where the variables are read, per call; default process.env. |
1421
+ | `log` | `Pick<Console, 'warn'>` | |
1422
+
1423
+ ### `@foliwake/server/discovery`
1424
+
1425
+ **Functions and components**
1426
+
1427
+ #### `fetchDiscovery()`
1428
+
1429
+ Reads and validates the discovery document of the site at `siteUrl` (FOLIWAKE_URL: https, or http for loopback hosts; origin only). 5 s per attempt, one retry, no redirects, at most 16 KiB of JSON.
1430
+
1431
+ ```ts
1432
+ function fetchDiscovery(siteUrl: string, opts?: FetchDiscoveryOptions): Promise<FoliwakeDiscovery>
1433
+ ```
1434
+
1435
+ **Returns** `Promise<FoliwakeDiscovery>`
1436
+
1437
+ #### `parseDiscovery()`
1438
+
1439
+ Validates a discovery document read from `origin` (the scheme, host and port of FOLIWAKE_URL). Throws FoliwakeConfigError naming the field.
1440
+
1441
+ ```ts
1442
+ function parseDiscovery(value: unknown, origin: string): FoliwakeDiscovery
1443
+ ```
1444
+
1445
+ **Returns** `FoliwakeDiscovery`
1446
+
1447
+ **Constants**
1448
+
1449
+ #### `DISCOVERY_LIMIT`
1450
+
1451
+ The largest discovery document read, in bytes.
1452
+
1453
+ ```ts
1454
+ const DISCOVERY_LIMIT: number
1455
+ ```
1456
+
1457
+ #### `DISCOVERY_PATH`
1458
+
1459
+ Where a site serves its discovery document, on each of its hosts.
1460
+
1461
+ ```ts
1462
+ const DISCOVERY_PATH = "/.well-known/foliwake.json"
1463
+ ```
1464
+
1465
+ #### `DISCOVERY_VERSION`
1466
+
1467
+ The major of the discovery format this package reads.
1468
+
1469
+ ```ts
1470
+ const DISCOVERY_VERSION = 1
1471
+ ```
1472
+
1473
+ #### `PLAIN_CONTRACT`
1474
+
1475
+ The plain HTML contract this package reads (`X-Code-Release` on `.plain.html`).
1476
+
1477
+ ```ts
1478
+ const PLAIN_CONTRACT = 2
1479
+ ```
1480
+
1481
+ #### `URL_ENV`
1482
+
1483
+ The environment variable with the site's live origin.
1484
+
1485
+ ```ts
1486
+ const URL_ENV = "FOLIWAKE_URL"
1487
+ ```
1488
+
1489
+ **Interfaces**
1490
+
1491
+ #### `FetchDiscoveryOptions`
1492
+
1493
+ Options of `fetchDiscovery`.
1494
+
1495
+ ```ts
1496
+ interface FetchDiscoveryOptions
1497
+ ```
1498
+
1499
+ | Member | Type | Description |
1500
+ | --- | --- | --- |
1501
+ | `fetch?` | `typeof fetch` | A fetch implementation (tests); default globalThis.fetch. |
1502
+ | `timeoutMs?` | `number` | Per attempt; default 5000. |
1503
+
1504
+ #### `FoliwakeDiscovery`
1505
+
1506
+ A validated discovery document. Unknown keys are ignored, so a newer engine may add some.
1507
+
1508
+ ```ts
1509
+ interface FoliwakeDiscovery
1510
+ ```
1511
+
1512
+ | Member | Type | Description |
1513
+ | --- | --- | --- |
1514
+ | `site` | `string` | |
1515
+ | `live` | `{ url: string; }` | |
1516
+ | `preview` | `{ url: string; } \| null` | Null when the site has no preview host. Its Basic user is always `preview`. |
1517
+ | `media` | `{ cdn: string; } \| null` | The CDN that resizes live images (its origin), or null. |
1518
+ | `contracts` | `{ plain: number; html: number \| null; blocks: number \| null; hook: number \| null; }` | |
1519
+
1520
+ ### `@foliwake/server/resolve`
1521
+
1522
+ **Functions and components**
1523
+
1524
+ #### `configFromSnapshot()`
1525
+
1526
+ The app config of a snapshot (no I/O). Throws FoliwakeConfigError naming the field.
1527
+
1528
+ ```ts
1529
+ function configFromSnapshot(snapshot: FoliwakeConfigSnapshot): FoliwakeAppConfig
1530
+ ```
1531
+
1532
+ **Returns** `FoliwakeAppConfig`
1533
+
1534
+ #### `loadAppConfig()`
1535
+
1536
+ readConfigSnapshot, then configFromSnapshot.
1537
+
1538
+ ```ts
1539
+ function loadAppConfig(opts?: ReadSnapshotOptions): Promise<FoliwakeAppConfig>
1540
+ ```
1541
+
1542
+ **Returns** `Promise<FoliwakeAppConfig>`
1543
+
1544
+ #### `readConfigSnapshot()`
1545
+
1546
+ Reads the inputs: FOLIWAKE_URL and its discovery document (fetched now), and the config file when there is one (a file named explicitly or by FOLIWAKE_REMOTE must exist). Throws FoliwakeConfigError.
1547
+
1548
+ ```ts
1549
+ function readConfigSnapshot(opts?: ReadSnapshotOptions): Promise<FoliwakeConfigSnapshot>
1550
+ ```
1551
+
1552
+ **Returns** `Promise<FoliwakeConfigSnapshot>`
1553
+
1554
+ **Constants**
1555
+
1556
+ #### `PREVIEW_TOKEN_ENV`
1557
+
1558
+ The variable the default preview credential reads: Basic `preview:<site preview token>`.
1559
+
1560
+ ```ts
1561
+ const PREVIEW_TOKEN_ENV = "FOLIWAKE_PREVIEW_TOKEN"
1562
+ ```
1563
+
1564
+ **Interfaces**
1565
+
1566
+ #### `FoliwakeConfigSnapshot`
1567
+
1568
+ The inputs of an app's config, as plain JSON.
1569
+
1570
+ ```ts
1571
+ interface FoliwakeConfigSnapshot
1572
+ ```
1573
+
1574
+ | Member | Type | Description |
1575
+ | --- | --- | --- |
1576
+ | `url` | `string \| null` | FOLIWAKE_URL, or null. |
1577
+ | `discovery` | `FoliwakeDiscovery \| null` | The site's discovery document read from `url`, or null without it. |
1578
+ | `file` | `string \| null` | The config file's name (for messages) and text, or null when there is none. |
1579
+ | `text` | `string \| null` | |
1580
+
1581
+ #### `ReadSnapshotOptions`
1582
+
1583
+ Options of `readConfigSnapshot` and `loadAppConfig`.
1584
+
1585
+ ```ts
1586
+ interface ReadSnapshotOptions extends FetchDiscoveryOptions
1587
+ ```
1588
+
1589
+ | Member | Type | Description |
1590
+ | --- | --- | --- |
1591
+ | `cwd?` | `string` | |
1592
+ | `env?` | `NodeJS.ProcessEnv` | Default process.env: FOLIWAKE_URL, FOLIWAKE_REMOTE. |
1593
+ | `file?` | `string` | The config file (default FOLIWAKE_REMOTE, else ./foliwake.remote.json). |
1594
+
1595
+ **Also exported** (documented where they are defined)
1596
+
1597
+ - from `@foliwake/server/discovery`: `DISCOVERY_PATH`, `FoliwakeDiscovery`, `URL_ENV`
1598
+
1222
1599
  ### `@foliwake/server/schemas/remote-2.schema.json`
1223
1600
 
1224
1601
  A file, not a module: `schemas/remote-2.schema.json` in the package.
1225
1602
 
1603
+ ### `@foliwake/server/schemas/remote-3.schema.json`
1604
+
1605
+ A file, not a module: `schemas/remote-3.schema.json` in the package.
1606
+
1226
1607
  <!-- apistop -->
@@ -0,0 +1,5 @@
1
+ import type { ReleaseBlocks } from '@foliwake/blocks-contract/page';
2
+ /** The response header that names the blocks module of a page's code release. */
3
+ export declare const BLOCKS_HEADER = "x-foliwake-blocks";
4
+ /** The parsed header; null when the answer has none (the release names no blocks module). */
5
+ export declare function parseBlocksHeader(value: string | null): ReleaseBlocks | null;
@@ -0,0 +1,47 @@
1
+ import { ENTRY_SEGMENT, ENTRY_ROOTS, EVENT_PREFIX } from './config-parts.js';
2
+ import { FoliwakePageError } from './errors.js';
3
+ /** The response header that names the blocks module of a page's code release. */
4
+ export const BLOCKS_HEADER = 'x-foliwake-blocks';
5
+ const MEMBER = /^\s*([a-z*][a-z0-9_.*-]*)=("(?:[^"\\]|\\.)*"|-?\d{1,15})\s*$/;
6
+ const MAX_LENGTH = 512;
7
+ function invalid() {
8
+ return new FoliwakePageError('invalid', 'The origin answered an invalid X-Foliwake-Blocks.');
9
+ }
10
+ function membersOf(value) {
11
+ const members = new Map();
12
+ for (const part of value.split(',')) {
13
+ const match = MEMBER.exec(part);
14
+ if (!match)
15
+ throw invalid();
16
+ const raw = match[2];
17
+ members.set(match[1], raw.startsWith('"') ? raw.slice(1, -1).replace(/\\(.)/g, '$1') : Number(raw));
18
+ }
19
+ return members;
20
+ }
21
+ function isEntry(value) {
22
+ if (typeof value !== 'string' || !value.endsWith('.js'))
23
+ return false;
24
+ const segments = value.split('/');
25
+ if (segments.length < 2 || segments.length > 8 || !ENTRY_ROOTS.includes(segments[0]))
26
+ return false;
27
+ return segments.every((s) => ENTRY_SEGMENT.test(s) && !s.includes('..'));
28
+ }
29
+ function isContract(value) {
30
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 999;
31
+ }
32
+ /** The parsed header; null when the answer has none (the release names no blocks module). */
33
+ export function parseBlocksHeader(value) {
34
+ if (value === null)
35
+ return null;
36
+ if (value.length > MAX_LENGTH)
37
+ throw invalid();
38
+ const members = membersOf(value);
39
+ const entry = members.get('entry');
40
+ const contract = members.get('contract');
41
+ const eventPrefix = members.get('prefix');
42
+ if (!isEntry(entry) || !isContract(contract))
43
+ throw invalid();
44
+ if (typeof eventPrefix !== 'string' || !EVENT_PREFIX.test(eventPrefix))
45
+ throw invalid();
46
+ return { entry, contract, eventPrefix };
47
+ }
@@ -0,0 +1,9 @@
1
+ import type { ParseOptions } from './config.js';
2
+ /** True for 127.x, localhost, *.localhost and ::1. */
3
+ export declare function isLoopbackName(hostname: string): boolean;
4
+ /** A site origin: https (http only for loopback), no credentials, path, query or fragment. */
5
+ export declare function parseRemoteUrl(value: unknown, where: string): string;
6
+ /** Validates an environment variable NAME (never a value). */
7
+ export declare function checkEnvName(value: unknown, where: string, extra?: ParseOptions['envNameProblem']): string;
8
+ /** Validates a Basic user name (no `:` or control characters, at most 128 characters). */
9
+ export declare function checkUsername(value: unknown, where: string): string;
@@ -0,0 +1,53 @@
1
+ // Checks of single config values shared by the v2 and v3 parsers and the discovery reader: origins and variable
2
+ // names. Re-exported by ./config (the public module).
3
+ import { FoliwakeConfigError } from './errors.js';
4
+ import { basicEnvNameProblem } from './env-names.js';
5
+ /** True for 127.x, localhost, *.localhost and ::1. */
6
+ export function isLoopbackName(hostname) {
7
+ const name = hostname.toLowerCase().replace(/\.$/, '');
8
+ if (name === 'localhost' || name.endsWith('.localhost'))
9
+ return true;
10
+ if (name === '[::1]' || name === '::1')
11
+ return true;
12
+ return /^127(?:\.\d{1,3}){3}$/.test(name);
13
+ }
14
+ function safeUrlText(value) {
15
+ return value.replace(/\/\/[^/@]*@/, '//…@').slice(0, 200);
16
+ }
17
+ /** A site origin: https (http only for loopback), no credentials, path, query or fragment. */
18
+ export function parseRemoteUrl(value, where) {
19
+ if (typeof value !== 'string' || value.trim() === '')
20
+ throw new FoliwakeConfigError(`${where}: give the URL of the deployed site, e.g. "https://preview.example.org".`);
21
+ let url;
22
+ try {
23
+ url = new URL(value);
24
+ }
25
+ catch {
26
+ throw new FoliwakeConfigError(`${where}: "${safeUrlText(value)}" is not a valid URL.`);
27
+ }
28
+ if (url.username || url.password)
29
+ throw new FoliwakeConfigError(`${where}: the URL must not contain a user name or password; name the password's environment variable in "auth" instead.`);
30
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
31
+ throw new FoliwakeConfigError(`${where}: only https URLs are supported.`);
32
+ if (url.protocol === 'http:' && !isLoopbackName(url.hostname)) {
33
+ throw new FoliwakeConfigError(`${where}: ${url.origin} uses plain http; use https (http is accepted only for loopback hosts such as 127.0.0.1).`);
34
+ }
35
+ if (url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) {
36
+ throw new FoliwakeConfigError(`${where}: give the site origin only (scheme, host and port), without a path, query or fragment: ${url.origin}`);
37
+ }
38
+ return url.origin;
39
+ }
40
+ /** Validates an environment variable NAME (never a value). */
41
+ export function checkEnvName(value, where, extra) {
42
+ const problem = basicEnvNameProblem(value, where) ?? (extra ? extra(value, where) : null);
43
+ if (problem)
44
+ throw new FoliwakeConfigError(problem);
45
+ return value;
46
+ }
47
+ /** Validates a Basic user name (no `:` or control characters, at most 128 characters). */
48
+ export function checkUsername(value, where) {
49
+ if (typeof value !== 'string' || value === '' || value.length > 128 || /[:\u0000-\u001f\u007f]/.test(value)) {
50
+ throw new FoliwakeConfigError(`${where}: give a user name without ":" or control characters.`);
51
+ }
52
+ return value;
53
+ }
@@ -0,0 +1,50 @@
1
+ import type { BasicAuth, FoliwakeAppSettings, FoliwakeEndpoint, ParseOptions, RemoteAuth, ServiceTokenAuth } from './config.js';
2
+ export declare const SECRET_KEYS: RegExp;
3
+ export declare const ISSUER: RegExp;
4
+ export declare const KID: RegExp;
5
+ export declare const SITE: RegExp;
6
+ export declare const PREFIX: RegExp;
7
+ export declare const RESERVED_PREFIXES: string[];
8
+ export declare const ENTRY_SEGMENT: RegExp;
9
+ export declare const ENTRY_ROOTS: string[];
10
+ export declare const CONTRACT: RegExp;
11
+ export declare const EVENT_PREFIX: RegExp;
12
+ export declare const DEFAULTS: {
13
+ code: string;
14
+ media: string;
15
+ contract: string;
16
+ eventPrefix: string;
17
+ revalidate: number;
18
+ };
19
+ export type Obj = Record<string, unknown>;
20
+ export declare const isObject: (value: unknown) => value is Obj;
21
+ export declare function refuseSecrets(value: unknown, at: string, file: string): void;
22
+ export declare function onlyKeys(value: Obj, allowed: readonly string[], where: string): void;
23
+ export declare function parseEndpoint(value: unknown, where: string, opts: ParseOptions): FoliwakeEndpoint;
24
+ export declare const AUTH_SHAPES: string;
25
+ export declare function parseBasicAuth(auth: Obj, where: string, opts: ParseOptions): BasicAuth;
26
+ export declare function parseServiceTokenAuth(auth: Obj, where: string, opts: ParseOptions): ServiceTokenAuth;
27
+ export declare function parseAuth(auth: unknown, where: string, opts: ParseOptions): RemoteAuth;
28
+ export declare function parsePrefix(value: unknown, fallback: string, where: string): string;
29
+ /** The proxy prefixes of a config without `proxies`: version 2, and version 3 (`/foliwake/…`, one handler). */
30
+ export declare const PROXY_DEFAULTS: {
31
+ readonly 2: {
32
+ readonly code: string;
33
+ readonly media: string;
34
+ };
35
+ readonly 3: {
36
+ readonly code: "/foliwake/code";
37
+ readonly media: "/foliwake/media";
38
+ };
39
+ };
40
+ export declare function parseProxies(value: unknown, where: string, defaults?: {
41
+ code: string;
42
+ media: string;
43
+ }): FoliwakeAppSettings['proxies'];
44
+ export declare function parseEntry(value: unknown, where: string): string | null;
45
+ export declare function parseBlocks(value: unknown, where: string): FoliwakeAppSettings['blocks'];
46
+ export declare function parseMedia(value: unknown, where: string): FoliwakeAppSettings['media'];
47
+ export declare function parsePages(value: unknown, where: string): string[];
48
+ /** `app.revalidate`: whole seconds, 1–86400; default 300. */
49
+ export declare function parseRevalidate(value: unknown, where: string): number;
50
+ export declare function parseApp(value: unknown, where: string): FoliwakeAppSettings;