@parrel/ledger 0.0.0-stage → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +793 -2
- package/dist/cli/commands.d.ts +51 -0
- package/dist/cli/commands.d.ts.map +1 -0
- package/dist/cli/commands.js +968 -0
- package/dist/cli/commands.js.map +1 -0
- package/dist/cli/index.d.ts +24 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +35 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/parrel.d.ts +3 -0
- package/dist/cli/parrel.d.ts.map +1 -0
- package/dist/cli/parrel.js +5 -0
- package/dist/cli/parrel.js.map +1 -0
- package/dist/cli/utils/angular-setup.d.ts +14 -0
- package/dist/cli/utils/angular-setup.d.ts.map +1 -0
- package/dist/cli/utils/angular-setup.js +96 -0
- package/dist/cli/utils/angular-setup.js.map +1 -0
- package/dist/cli/utils/api-tree-builder.d.ts +24 -0
- package/dist/cli/utils/api-tree-builder.d.ts.map +1 -0
- package/dist/cli/utils/api-tree-builder.js +146 -0
- package/dist/cli/utils/api-tree-builder.js.map +1 -0
- package/dist/cli/utils/bundle-reader.d.ts +185 -0
- package/dist/cli/utils/bundle-reader.d.ts.map +1 -0
- package/dist/cli/utils/bundle-reader.js +518 -0
- package/dist/cli/utils/bundle-reader.js.map +1 -0
- package/dist/cli/utils/collision-detector.d.ts +21 -0
- package/dist/cli/utils/collision-detector.d.ts.map +1 -0
- package/dist/cli/utils/collision-detector.js +53 -0
- package/dist/cli/utils/collision-detector.js.map +1 -0
- package/dist/cli/utils/map-fields.d.ts +42 -0
- package/dist/cli/utils/map-fields.d.ts.map +1 -0
- package/dist/cli/utils/map-fields.js +90 -0
- package/dist/cli/utils/map-fields.js.map +1 -0
- package/dist/cli/utils/map-validator.d.ts +42 -0
- package/dist/cli/utils/map-validator.d.ts.map +1 -0
- package/dist/cli/utils/map-validator.js +119 -0
- package/dist/cli/utils/map-validator.js.map +1 -0
- package/dist/cli/utils/media-file.d.ts +41 -0
- package/dist/cli/utils/media-file.d.ts.map +1 -0
- package/dist/cli/utils/media-file.js +72 -0
- package/dist/cli/utils/media-file.js.map +1 -0
- package/dist/cli/utils/media-validator.d.ts +10 -0
- package/dist/cli/utils/media-validator.d.ts.map +1 -0
- package/dist/cli/utils/media-validator.js +85 -0
- package/dist/cli/utils/media-validator.js.map +1 -0
- package/dist/cli/utils/mock-augmenter.d.ts +19 -0
- package/dist/cli/utils/mock-augmenter.d.ts.map +1 -0
- package/dist/cli/utils/mock-augmenter.js +102 -0
- package/dist/cli/utils/mock-augmenter.js.map +1 -0
- package/dist/cli/utils/mock-validator.d.ts +27 -0
- package/dist/cli/utils/mock-validator.d.ts.map +1 -0
- package/dist/cli/utils/mock-validator.js +214 -0
- package/dist/cli/utils/mock-validator.js.map +1 -0
- package/dist/cli/utils/project-dir.d.ts +24 -0
- package/dist/cli/utils/project-dir.d.ts.map +1 -0
- package/dist/cli/utils/project-dir.js +32 -0
- package/dist/cli/utils/project-dir.js.map +1 -0
- package/dist/cli/utils/schema-loader.d.ts +19 -0
- package/dist/cli/utils/schema-loader.d.ts.map +1 -0
- package/dist/cli/utils/schema-loader.js +101 -0
- package/dist/cli/utils/schema-loader.js.map +1 -0
- package/dist/cli/utils/server-entry.d.ts +34 -0
- package/dist/cli/utils/server-entry.d.ts.map +1 -0
- package/dist/cli/utils/server-entry.js +111 -0
- package/dist/cli/utils/server-entry.js.map +1 -0
- package/dist/cli/utils/sync.d.ts +116 -0
- package/dist/cli/utils/sync.d.ts.map +1 -0
- package/dist/cli/utils/sync.js +134 -0
- package/dist/cli/utils/sync.js.map +1 -0
- package/dist/client/index.d.ts +39 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +88 -0
- package/dist/client/index.js.map +1 -0
- package/dist/core/browser-session.d.ts +5 -0
- package/dist/core/browser-session.d.ts.map +1 -0
- package/dist/core/browser-session.js +12 -0
- package/dist/core/browser-session.js.map +1 -0
- package/dist/core/cache.d.ts +80 -0
- package/dist/core/cache.d.ts.map +1 -0
- package/dist/core/cache.js +95 -0
- package/dist/core/cache.js.map +1 -0
- package/dist/core/client.d.ts +64 -0
- package/dist/core/client.d.ts.map +1 -0
- package/dist/core/client.js +281 -0
- package/dist/core/client.js.map +1 -0
- package/dist/core/config.d.ts +20 -0
- package/dist/core/config.d.ts.map +1 -0
- package/dist/core/config.js +32 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/copy-read.d.ts +25 -0
- package/dist/core/copy-read.d.ts.map +1 -0
- package/dist/core/copy-read.js +123 -0
- package/dist/core/copy-read.js.map +1 -0
- package/dist/core/define-ledger.d.ts +38 -0
- package/dist/core/define-ledger.d.ts.map +1 -0
- package/dist/core/define-ledger.js +65 -0
- package/dist/core/define-ledger.js.map +1 -0
- package/dist/core/deprecated.d.ts +16 -0
- package/dist/core/deprecated.d.ts.map +1 -0
- package/dist/core/deprecated.js +14 -0
- package/dist/core/deprecated.js.map +1 -0
- package/dist/core/env.d.ts +103 -0
- package/dist/core/env.d.ts.map +1 -0
- package/dist/core/env.js +208 -0
- package/dist/core/env.js.map +1 -0
- package/dist/core/error-codes.generated.d.ts +12 -0
- package/dist/core/error-codes.generated.d.ts.map +1 -0
- package/dist/core/error-codes.generated.js +3 -0
- package/dist/core/error-codes.generated.js.map +1 -0
- package/dist/core/get-content.d.ts +62 -0
- package/dist/core/get-content.d.ts.map +1 -0
- package/dist/core/get-content.js +86 -0
- package/dist/core/get-content.js.map +1 -0
- package/dist/core/get-media.d.ts +58 -0
- package/dist/core/get-media.d.ts.map +1 -0
- package/dist/core/get-media.js +89 -0
- package/dist/core/get-media.js.map +1 -0
- package/dist/core/manifest.d.ts +38 -0
- package/dist/core/manifest.d.ts.map +1 -0
- package/dist/core/manifest.js +93 -0
- package/dist/core/manifest.js.map +1 -0
- package/dist/core/media-proxy.d.ts +41 -0
- package/dist/core/media-proxy.d.ts.map +1 -0
- package/dist/core/media-proxy.js +219 -0
- package/dist/core/media-proxy.js.map +1 -0
- package/dist/core/package-info.d.ts +34 -0
- package/dist/core/package-info.d.ts.map +1 -0
- package/dist/core/package-info.js +39 -0
- package/dist/core/package-info.js.map +1 -0
- package/dist/core/parrel-error.d.ts +160 -0
- package/dist/core/parrel-error.d.ts.map +1 -0
- package/dist/core/parrel-error.js +198 -0
- package/dist/core/parrel-error.js.map +1 -0
- package/dist/core/transform-content.d.ts +42 -0
- package/dist/core/transform-content.d.ts.map +1 -0
- package/dist/core/transform-content.js +185 -0
- package/dist/core/transform-content.js.map +1 -0
- package/dist/core/types.d.ts +406 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +11 -0
- package/dist/core/types.js.map +1 -0
- package/dist/errors/error-messages.generated.d.ts +5 -0
- package/dist/errors/error-messages.generated.d.ts.map +1 -0
- package/dist/errors/error-messages.generated.js +971 -0
- package/dist/errors/error-messages.generated.js.map +1 -0
- package/dist/errors/get-error-info.d.ts +29 -0
- package/dist/errors/get-error-info.d.ts.map +1 -0
- package/dist/errors/get-error-info.js +43 -0
- package/dist/errors/get-error-info.js.map +1 -0
- package/dist/errors/index.d.ts +4 -0
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/errors/index.js +4 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/errors/types.d.ts +19 -0
- package/dist/errors/types.d.ts.map +1 -0
- package/dist/errors/types.js +2 -0
- package/dist/errors/types.js.map +1 -0
- package/dist/generated.d.ts +29 -0
- package/dist/generated.d.ts.map +1 -0
- package/dist/generated.js +29 -0
- package/dist/generated.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/mock/dev-media.d.ts +15 -0
- package/dist/mock/dev-media.d.ts.map +1 -0
- package/dist/mock/dev-media.js +52 -0
- package/dist/mock/dev-media.js.map +1 -0
- package/dist/mock/file-store.d.ts +44 -0
- package/dist/mock/file-store.d.ts.map +1 -0
- package/dist/mock/file-store.js +170 -0
- package/dist/mock/file-store.js.map +1 -0
- package/dist/mock/index.d.ts +4 -0
- package/dist/mock/index.d.ts.map +1 -0
- package/dist/mock/index.js +3 -0
- package/dist/mock/index.js.map +1 -0
- package/dist/mock/media-fields.d.ts +25 -0
- package/dist/mock/media-fields.d.ts.map +1 -0
- package/dist/mock/media-fields.js +54 -0
- package/dist/mock/media-fields.js.map +1 -0
- package/dist/mock/mock-adapter.d.ts +65 -0
- package/dist/mock/mock-adapter.d.ts.map +1 -0
- package/dist/mock/mock-adapter.js +431 -0
- package/dist/mock/mock-adapter.js.map +1 -0
- package/dist/mock/mock-errors.d.ts +18 -0
- package/dist/mock/mock-errors.d.ts.map +1 -0
- package/dist/mock/mock-errors.js +56 -0
- package/dist/mock/mock-errors.js.map +1 -0
- package/dist/mock/node-import.d.ts +13 -0
- package/dist/mock/node-import.d.ts.map +1 -0
- package/dist/mock/node-import.js +16 -0
- package/dist/mock/node-import.js.map +1 -0
- package/dist/mock/seed-mock-store.d.ts +14 -0
- package/dist/mock/seed-mock-store.d.ts.map +1 -0
- package/dist/mock/seed-mock-store.js +106 -0
- package/dist/mock/seed-mock-store.js.map +1 -0
- package/dist/mock/shared-memory-store.d.ts +35 -0
- package/dist/mock/shared-memory-store.d.ts.map +1 -0
- package/dist/mock/shared-memory-store.js +46 -0
- package/dist/mock/shared-memory-store.js.map +1 -0
- package/dist/next/dev-rendering-helpers.d.ts +78 -0
- package/dist/next/dev-rendering-helpers.d.ts.map +1 -0
- package/dist/next/dev-rendering-helpers.js +103 -0
- package/dist/next/dev-rendering-helpers.js.map +1 -0
- package/dist/next/index.d.ts +35 -0
- package/dist/next/index.d.ts.map +1 -0
- package/dist/next/index.js +33 -0
- package/dist/next/index.js.map +1 -0
- package/dist/next/next-cache-adapter.d.ts +11 -0
- package/dist/next/next-cache-adapter.d.ts.map +1 -0
- package/dist/next/next-cache-adapter.js +12 -0
- package/dist/next/next-cache-adapter.js.map +1 -0
- package/dist/nuxt/index.d.ts +22 -0
- package/dist/nuxt/index.d.ts.map +1 -0
- package/dist/nuxt/index.js +57 -0
- package/dist/nuxt/index.js.map +1 -0
- package/dist/sveltekit/index.d.ts +35 -0
- package/dist/sveltekit/index.d.ts.map +1 -0
- package/dist/sveltekit/index.js +56 -0
- package/dist/sveltekit/index.js.map +1 -0
- package/dist/ui/content-editor.d.ts +9 -0
- package/dist/ui/content-editor.d.ts.map +1 -0
- package/dist/ui/content-editor.js +27 -0
- package/dist/ui/content-editor.js.map +1 -0
- package/dist/ui/index.d.ts +8 -0
- package/dist/ui/index.d.ts.map +1 -0
- package/dist/ui/index.js +8 -0
- package/dist/ui/index.js.map +1 -0
- package/dist/ui/ledger-overlay.d.ts +10 -0
- package/dist/ui/ledger-overlay.d.ts.map +1 -0
- package/dist/ui/ledger-overlay.js +27 -0
- package/dist/ui/ledger-overlay.js.map +1 -0
- package/dist/ui/media-uploader.d.ts +9 -0
- package/dist/ui/media-uploader.d.ts.map +1 -0
- package/dist/ui/media-uploader.js +27 -0
- package/dist/ui/media-uploader.js.map +1 -0
- package/package.json +134 -6
package/README.md
CHANGED
|
@@ -1,3 +1,794 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @parrel/ledger
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
*Documentation: [docs.parrel.dev/ledger](https://docs.parrel.dev/ledger). Error codes: [docs.parrel.dev/errors](https://docs.parrel.dev/errors).*
|
|
4
|
+
|
|
5
|
+
The SDK of **Parrel Ledger**: code-defined structured content and media for **Next.js, Nuxt, SvelteKit, React, Vue and Angular** apps. *A product of Digistra.*
|
|
6
|
+
|
|
7
|
+
You describe your content as JSON maps in your repository, edit it locally against a mock store, and read it in production from the Ledger service of your Parrel project. The generated `ledgerClient` gives you typed access to every map.
|
|
8
|
+
|
|
9
|
+
> Formerly `@parrel/cms`. Moving an existing app takes a few minutes and nothing breaks in between: see [Moving from @parrel/cms](#moving-from-parrelcms).
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @parrel/ledger @parrel/sentinel
|
|
15
|
+
# then scaffold the config, sample content and the media route for your framework:
|
|
16
|
+
npx parrel ledger init
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Reading content needs no sign-in: a read sends no token, and Ledger has no read token. Writing content and uploading media (`uploadContent`, `uploadMedia`) run in the **browser only**, with the session of the signed-in user from `@parrel/sentinel` (see [Writes need the browser session](#writes-need-the-browser-session)). `init` detects your framework, asks once for the slug of your Ledger service (from the Parrel portal) and writes the files described below.
|
|
20
|
+
|
|
21
|
+
## Configuration
|
|
22
|
+
|
|
23
|
+
Call `defineParrelLedger` once, server-side, before you read or write content. `npx parrel ledger init` writes this file for you:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// lib/ledger.ts (src/lib/ledger.ts in SvelteKit; server-side only)
|
|
27
|
+
import { defineParrelLedger } from "@parrel/ledger";
|
|
28
|
+
|
|
29
|
+
export const ledger = defineParrelLedger({
|
|
30
|
+
slug: "your-service-slug",
|
|
31
|
+
// Same-origin media proxy, scaffolded by `init` for Next.js, Nuxt and SvelteKit.
|
|
32
|
+
mediaProxyPath: "/api/cms-media",
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
| Option | Type | Default | Description |
|
|
37
|
+
| --- | --- | --- | --- |
|
|
38
|
+
| `slug` | `string` | (required) | Slug of your Ledger service, from the Parrel portal. |
|
|
39
|
+
| `mediaProxyPath` | `string` | none | Path of the same-origin media route. When set, `getMedia` returns a URL below this path instead of the Ledger service URL, so PDFs, SVGs, images and video embed without CORS or `X-Frame-Options` problems. |
|
|
40
|
+
| `cache.enabled` | `boolean` | `true` | `false` turns the cache off: every call asks the service. |
|
|
41
|
+
| `cache.ttlSeconds` | `number` | `300` | How long a copy of a resource, a media URL or a proxied file is fresh: returned without any request (see [Caching](#caching)). |
|
|
42
|
+
| `cache.manifestTtlSeconds` | `number` | `300` | How long one read of the manifest serves every copy that is checked. |
|
|
43
|
+
| `cache.maxAgeSeconds` | `number` | `86400` | How long a copy is kept at most after its download (24 hours), also when its hash did not change. |
|
|
44
|
+
| `cache.mediaCacheMaxBytes` | `number` | `52428800` (50 MB) | How many bytes of media the media proxy keeps in memory. `0` turns it off. |
|
|
45
|
+
| `mockDataDir` | `string` | `node_modules/.cache/parrel` | Where the mock adapter keeps its runtime store outside production. |
|
|
46
|
+
| `mockData` | `object` | none | The content of `parrel/ledger/mock.json`, for an app that runs only in a browser. See [React, Vue and Angular](#react-vue-and-angular-browser-only-apps). |
|
|
47
|
+
| `mockMediaPath` | `string` | `/parrel/ledger` | In a browser, the URL path below which the mock `getMedia` expects the media files. |
|
|
48
|
+
| `apiOrigin` | `string` | `PARREL_API_ORIGIN`, then `https://api.parrel.dev` | Origin of the Parrel API, for a local backend. See [API origin override](#api-origin-override). |
|
|
49
|
+
| `siteOrigin` | `string` | `PARREL_SITE_ORIGIN`, then none | The origin of your own site, which a read from a server sends as `Origin`. Needed on a server in production. See [Reading from a server](#reading-from-a-server). |
|
|
50
|
+
| `mode` | `"auto" \| "live"` | `"auto"` | `"live"` uses the Ledger service also in development. |
|
|
51
|
+
|
|
52
|
+
The production endpoint is `https://api.parrel.dev/cms/v1`. The path (`/cms/v1`) is fixed; only the origin can change, see [API origin override](#api-origin-override). Outside production (`NODE_ENV !== "production"`) the mock adapter is used automatically, so development needs no network and no keys. On a server it reads `parrel/ledger/mock.json`; an app that runs only in a browser (React, Vue, Angular) passes that content in as `mockData`, see [React, Vue and Angular](#react-vue-and-angular-browser-only-apps).
|
|
53
|
+
|
|
54
|
+
## API origin override
|
|
55
|
+
|
|
56
|
+
By default Ledger talks to the production Parrel API at `https://api.parrel.dev` (the Ledger path is `/cms/v1`). To test against a Ledger backend that runs on your own machine, change the origin. The path never changes.
|
|
57
|
+
|
|
58
|
+
| Setting | Where | Meaning |
|
|
59
|
+
| --- | --- | --- |
|
|
60
|
+
| `apiOrigin` | The `defineParrelLedger` configuration and `createParrelLedgerServerAdapter` | Origin of the Parrel API, for example `http://localhost:18700`. It wins over the environment variable. |
|
|
61
|
+
| `PARREL_API_ORIGIN` | Environment variable of the server and of the `parrel ledger sync` command | The same, when `apiOrigin` is not set. |
|
|
62
|
+
| `mode: "live"` | The `defineParrelLedger` configuration | Use the Parrel service also in development, instead of the mock content. |
|
|
63
|
+
| `PARREL_FORCE_LIVE=1` | Environment variable of the server | The same as `mode: "live"`. |
|
|
64
|
+
|
|
65
|
+
Outside production Ledger uses the mock content, even when `apiOrigin` is set. Add `PARREL_FORCE_LIVE=1` (or `mode: "live"`) to send the requests of `next dev`, `vite` or `nuxt dev` to the local backend:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
PARREL_API_ORIGIN=http://localhost:18700 PARREL_FORCE_LIVE=1 npm run dev
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
// lib/ledger.ts (src/lib/ledger.ts in SvelteKit)
|
|
73
|
+
import { defineParrelLedger } from "@parrel/ledger";
|
|
74
|
+
|
|
75
|
+
export const ledger = defineParrelLedger({
|
|
76
|
+
slug: "your-service-slug",
|
|
77
|
+
apiOrigin: "http://localhost:18700", // or leave it out and set PARREL_API_ORIGIN
|
|
78
|
+
mode: "live", // or set PARREL_FORCE_LIVE=1
|
|
79
|
+
});
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Browser code (React, Vue, Angular, and the client side of Next.js, Nuxt and SvelteKit) cannot read server environment variables. Pass the public variable of the framework as `apiOrigin`, and `mode` when you want the live service in development:
|
|
83
|
+
|
|
84
|
+
| Framework | Public variable | Config |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| Next.js (browser code) | `NEXT_PUBLIC_PARREL_API_ORIGIN` | `apiOrigin: process.env.NEXT_PUBLIC_PARREL_API_ORIGIN` |
|
|
87
|
+
| Vite (React, Vue) | `VITE_PARREL_API_ORIGIN` | `apiOrigin: import.meta.env.VITE_PARREL_API_ORIGIN` |
|
|
88
|
+
| Nuxt (browser code) | `VITE_PARREL_API_ORIGIN` | `apiOrigin: import.meta.env.VITE_PARREL_API_ORIGIN`, with the variable in `.env` at build time |
|
|
89
|
+
| SvelteKit (browser code) | `VITE_PARREL_API_ORIGIN` | `apiOrigin: import.meta.env.VITE_PARREL_API_ORIGIN` |
|
|
90
|
+
| Angular | `environment.ts` | `apiOrigin: environment.parrelApiOrigin` |
|
|
91
|
+
|
|
92
|
+
In Nuxt put `VITE_PARREL_API_ORIGIN` in `.env` (or in the environment of the build). Nuxt does not read `.env.production.local` the way Vite does, so a variable that only lives there reaches the client bundle as `undefined` and the browser uses the default origin. The Nitro server reads `PARREL_API_ORIGIN` from its environment at runtime, as in the other server frameworks.
|
|
93
|
+
|
|
94
|
+
In Nuxt 4 the app lives in `app/`, but `init` writes the config to `lib/` at the project root. Import it from the server and the app as `~~/lib/ledger` (`~~` is the project root; `~` is `app/`).
|
|
95
|
+
|
|
96
|
+
A new Angular app has no `src/environments/`. Run `npx ng generate environments` once, then add `parrelApiOrigin` to both environment files. `init` does that last step when the files exist: it adds `parrelApiOrigin: ""` and `production` where they are missing, adds `"resolveJsonModule": true` to `tsconfig.json` when the app needs it (see below), and never overwrites a value.
|
|
97
|
+
|
|
98
|
+
The same-origin media route fetches from the same origin. The origin comes from code or configuration only, never from the request, and the first one that is set wins:
|
|
99
|
+
|
|
100
|
+
1. the `apiOrigin` option of `createLedgerMediaRouteHandlers` (Next.js), `createLedgerMediaProxy` (SvelteKit and Nuxt) or `proxyLedgerMedia`;
|
|
101
|
+
2. the `apiOrigin` of `defineParrelLedger`, which only counts once that call has run in the server process;
|
|
102
|
+
3. `PARREL_API_ORIGIN`.
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
// app/api/cms-media/[...path]/route.ts
|
|
106
|
+
import { createLedgerMediaRouteHandlers } from "@parrel/ledger/next";
|
|
107
|
+
|
|
108
|
+
export const { GET } = createLedgerMediaRouteHandlers({ apiOrigin: "http://localhost:18700" });
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`createLedgerMediaRouteHandlers` is a shortcut for Next.js. In another server route, call the function yourself:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { proxyLedgerMedia } from "@parrel/ledger";
|
|
115
|
+
|
|
116
|
+
const response = await proxyLedgerMedia(segments, { apiOrigin: "http://localhost:18700" });
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`proxyLedgerMedia` is exported from the root entry of `@parrel/ledger` and is meant for server code only. When Ledger answers a media request with an error, the proxy returns the same status, the same JSON error body (with its `LE` code) and the same content type, with `Cache-Control: no-store`, so the browser can read the code. When Ledger cannot be reached, it answers `502` with a JSON error body and the code `SD01000003`.
|
|
120
|
+
|
|
121
|
+
`npx parrel ledger sync` reads `PARREL_API_ORIGIN` from the environment (for example `PARREL_API_ORIGIN=http://localhost:18700 npx parrel ledger sync`) and refuses a bad origin before it asks for the deployment token. The CLI has no `apiOrigin` option; it only reads the environment variable.
|
|
122
|
+
|
|
123
|
+
The package logs the origin once with `console.info` when it is not the default, and only outside production. `PARREL_LEDGER_SERVER_BASE_URL` is deprecated; it keeps the production value.
|
|
124
|
+
|
|
125
|
+
**Security rule.** The origin must be `https://`, except `http://` on `localhost`, `127.0.0.1` or `[::1]`. It must be an origin only: no path, no query and no user information. One trailing slash is accepted and removed. Anything else throws a `ParrelError` with the code [`SD00100008`](https://docs.parrel.dev/errors/SD00100008) before a request is sent, so a session cookie or a token never travels over plain HTTP to a remote host. The override changes where requests go; the backend still applies its own origin rules.
|
|
126
|
+
|
|
127
|
+
## Reading from a server
|
|
128
|
+
|
|
129
|
+
Ledger answers a read (the manifest, a resource or the URL of a media field) only from an allowed origin of your service (rulebook LED-11, LED-13). A browser sends its own `Origin` header, which a script cannot change. A server sends none by itself, and Ledger refuses a read from a public server without one with `403` and [`LE04000015`](https://docs.parrel.dev/errors/LE04000015). So on a server the package sends the origin of your own site, which you set once:
|
|
130
|
+
|
|
131
|
+
| Setting | Where | Meaning |
|
|
132
|
+
| --- | --- | --- |
|
|
133
|
+
| `siteOrigin` | `defineParrelLedger` and `createParrelLedgerServerAdapter` | The origin of your site, for example `https://shop.be`. It wins over the environment variable. |
|
|
134
|
+
| `PARREL_SITE_ORIGIN` | Environment variable of the server and of the build | The same, when `siteOrigin` is not set. It is read at the first read, so a value set after the import still counts. |
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
// lib/ledger.ts
|
|
138
|
+
export const ledger = defineParrelLedger({
|
|
139
|
+
slug: "your-service-slug",
|
|
140
|
+
siteOrigin: "https://shop.be", // or leave it out and set PARREL_SITE_ORIGIN
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
- **Which origin.** Give an origin that is on the list of your Ledger service in the Parrel portal. A domain and its `www.` version are one origin in the portal (rulebook MOD-8), but the package sends exactly what you set; it never reads the list of the service. The value is trimmed, a bare domain such as `shop.be` gets `https://`, and it is sent in lower case without a trailing slash. `localhost` is allowed with `http://` or `https://` on any port, for a local backend. Any other host must be `https://` without a port, a path or a query.
|
|
145
|
+
- **When it is sent.** On every read of the server adapter on a server: `getContent`, `getMedia` and the manifest. Never in a browser (the browser sets its own), never on a write (writes run in the browser, LED-8), never on the request of a media file by the media proxy (media is public by its URL, LED-12), and never by `parrel ledger sync` (it uses the deployment token). The media proxy sends it only on its manifest read, when it is set.
|
|
146
|
+
- **Missing.** A read on a server in production or live mode without `siteOrigin` or `PARREL_SITE_ORIGIN` throws [`SD00100019`](https://docs.parrel.dev/errors/SD00100019) before anything is sent. Development with the mock needs nothing, and a browser needs nothing.
|
|
147
|
+
- **Wrong.** A `siteOrigin` in another form throws [`SD00100018`](https://docs.parrel.dev/errors/SD00100018) when `defineParrelLedger` runs; a wrong `PARREL_SITE_ORIGIN` throws it at the first read, before anything is sent.
|
|
148
|
+
- **What Ledger answers.** The `403` errors of Ledger keep their own code, status and trace id: [`LE04000015`](https://docs.parrel.dev/errors/LE04000015) (no `Origin` was sent), [`LE04000016`](https://docs.parrel.dev/errors/LE04000016) (your service has no origins yet: add one in the portal) and [`LE04000017`](https://docs.parrel.dev/errors/LE04000017) (the origin you set is not on the list of the service: add it, or fix `siteOrigin`).
|
|
149
|
+
- **Next.js.** The package never calls `headers()`, so a page that reads Ledger stays static or ISR. A build that reads Ledger, for example on a CI machine, is a read from a server too: set `PARREL_SITE_ORIGIN` in the environment of the CI job that runs `next build`. The same holds for a prerendered SvelteKit or Nuxt page.
|
|
150
|
+
- **Rate limits.** A read from a server counts on the address of that server, 600 per minute for each service (rulebook LIM-3, SEC-33); see [Caching](#caching).
|
|
151
|
+
|
|
152
|
+
## Load the configuration on the server
|
|
153
|
+
|
|
154
|
+
A server only knows the Ledger configuration after the file with `defineParrelLedger` has run. Next.js loads `lib/ledger.ts` when a page imports it. SvelteKit and Nuxt do not, so a load function or a server route that calls Ledger first fails with [`SD00100001`](https://docs.parrel.dev/errors/SD00100001) ("is not configured"). `npx parrel ledger init --framework sveltekit` and `--framework nuxt` write the files below for you; an existing file is never overwritten without `--force`.
|
|
155
|
+
|
|
156
|
+
**SvelteKit.** The config is `src/lib/ledger.ts`. `src/hooks.server.ts` imports it, so a load function finds it:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
// src/hooks.server.ts
|
|
160
|
+
import "#lib/ledger.js"; // registers defineParrelLedger(...)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Use `#lib/ledger.js` in SvelteKit 3, where `$lib` was removed (the app needs `"imports": { "#lib/*": "./src/lib/*" }` in `package.json`, which the current `sv create` template has; the extension is needed because that mapping is a plain path, and `svelte-check` rejects the form without it), and `$lib/ledger` in SvelteKit 2. `init` reads the version of `@sveltejs/kit` (the installed one, then the range in `package.json`; an unknown version counts as 3) and picks the right one, the same way `parrel sentinel init` does. If `hooks.server.ts` exists, `init` only adds the missing import and leaves the rest of the file alone.
|
|
164
|
+
|
|
165
|
+
**Nuxt.** The config is `lib/ledger.ts`. Nuxt does not import `lib/` on the server, and Nitro drops a bare `import` and an export that nothing uses, so `server/plugins/parrel-ledger.ts` really uses the config inside a plugin:
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
// server/plugins/parrel-ledger.ts
|
|
169
|
+
import { ParrelError } from "@parrel/ledger";
|
|
170
|
+
import { ledger } from "~~/lib/ledger";
|
|
171
|
+
|
|
172
|
+
export default defineNitroPlugin(() => {
|
|
173
|
+
if (!ledger) {
|
|
174
|
+
throw new ParrelError("SD00100001", "lib/ledger.ts must export the result of defineParrelLedger(...) as `ledger`, so the Ledger configuration is kept.");
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
`init` writes no request middleware and no Sentinel handle: sign-in, writes and uploads run in the browser, so a server forwards nothing about the visitor. Earlier versions of `init` wrote `createParrelSentinelHandle` into `src/hooks.server.ts` and `createParrelSentinelMiddleware` into `server/middleware/parrel-request.ts`. `@parrel/sentinel` no longer exports them, so **remove those lines and that file** from your project; `init` warns when it finds them. The dev media routes (`/api/dev-cms-media`) are unchanged, see [Framework media routes](#framework-media-routes).
|
|
180
|
+
|
|
181
|
+
## Browser configuration for pages that write
|
|
182
|
+
|
|
183
|
+
The `lib/ledger.ts` that `init` writes for Next.js, Nuxt and SvelteKit is the **server** configuration. A page that writes (an admin page that calls `setContent` or `setMedia`) runs in the browser, in a bundle that has no server configuration, so it needs its own call of `defineParrelLedger`. Give it:
|
|
184
|
+
|
|
185
|
+
- `apiOrigin` from the public variable of the framework (see [API origin override](#api-origin-override)), because browser code cannot read `PARREL_API_ORIGIN`;
|
|
186
|
+
- `mockData` outside production, because a browser cannot read `parrel/ledger/mock.json`. In production the browser talks to the Ledger service and `mockData` is not used.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
// lib/ledger.browser.ts (Next.js). Import it from browser code only.
|
|
190
|
+
import { defineParrelLedger } from "@parrel/ledger";
|
|
191
|
+
import mockData from "../parrel/ledger/mock.json";
|
|
192
|
+
|
|
193
|
+
export const ledgerInBrowser = defineParrelLedger({
|
|
194
|
+
slug: "your-service-slug",
|
|
195
|
+
apiOrigin: process.env.NEXT_PUBLIC_PARREL_API_ORIGIN,
|
|
196
|
+
mockData: process.env.NODE_ENV === "production" ? undefined : mockData,
|
|
197
|
+
});
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
In Nuxt and SvelteKit use `import.meta.env.VITE_PARREL_API_ORIGIN` and `import.meta.env.DEV ? mockData : undefined`. Without `mockData`, the first read or write in the browser in development throws [`SD06000007`](https://docs.parrel.dev/errors/SD06000007).
|
|
201
|
+
|
|
202
|
+
**Load it in the browser only.** `defineParrelLedger` keeps one configuration per process, and the last call wins. A module that a server-rendered page imports also runs on the server, so a browser configuration that is imported statically by such a page **replaces the server configuration on the server, without a warning**: reads on the server then use the browser settings (no `mediaProxyPath`, a mock that cannot read files). Load it where only the browser runs:
|
|
203
|
+
|
|
204
|
+
- **SvelteKit:** import it inside `onMount` (`await import("$lib/ledger.browser")`, `#lib/ledger.browser.js` in SvelteKit 3), or in a route or layout with `export const ssr = false`. Never put `import "$lib/ledger.browser"` at the top of a `+page.svelte` or `+layout.svelte` that is server-rendered.
|
|
205
|
+
- **Nuxt:** put it in a plugin that only runs in the browser, `plugins/parrel-ledger.client.ts` (the `.client` suffix), or import it inside `onMounted`.
|
|
206
|
+
- **Next.js:** import it inside `useEffect` (`await import("../lib/ledger.browser")`), or load the admin component with `next/dynamic` and `{ ssr: false }`. A `"use client"` file is still rendered once on the server.
|
|
207
|
+
|
|
208
|
+
## Handshake header
|
|
209
|
+
|
|
210
|
+
Every call of `@parrel/ledger` tells Ledger which package and version sent it: the header `X-Parrel-Package: @parrel/ledger@<version>`, so the service can count and log calls per package. Calls from a server, from the CLI and from a browser all send it; Ledger allows the header from browsers in its CORS answer. Set `sendHandshakeFromBrowser: false` in `defineParrelLedger` only when a proxy of your own between the browser and Ledger refuses the header; a server and the CLI always send it. The header carries only the package name and version.
|
|
211
|
+
|
|
212
|
+
## Project files
|
|
213
|
+
|
|
214
|
+
```
|
|
215
|
+
parrel/ledger/
|
|
216
|
+
├── maps/ one JSON map per resource, for example homepage.json
|
|
217
|
+
├── mock.json development content
|
|
218
|
+
└── mediamock/ development media files
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
A map describes the fields of one resource. The file name becomes the client property in camelCase (`home-page.json` → `ledgerClient.homePage`). A map has exactly these seven field types:
|
|
222
|
+
|
|
223
|
+
| Type | Value |
|
|
224
|
+
| --- | --- |
|
|
225
|
+
| `string` | text |
|
|
226
|
+
| `number` | a number |
|
|
227
|
+
| `boolean` | `true` or `false` |
|
|
228
|
+
| `media` | a media object `{ "file", "alt" }`; `getContent` returns the alt text and `getMedia` the URL |
|
|
229
|
+
| `media-reference` | handled like `media`: the same value, the same checks and the same generated type. It is not deprecated |
|
|
230
|
+
| `array` | a list; `items` describes one element |
|
|
231
|
+
| `object` | a group of fields; `fields` describes them |
|
|
232
|
+
|
|
233
|
+
Any other type (for example `date` or `decimal`) is refused with [`SD05000023`](https://docs.parrel.dev/errors/SD05000023) by `generate`, `sync` and `check-mock` before anything is sent, and `validateMapSet` reports it. An `array` and an `object` stay loose: Ledger checks only the required top-level fields of a write.
|
|
234
|
+
|
|
235
|
+
```json
|
|
236
|
+
{
|
|
237
|
+
"title": { "type": "string" },
|
|
238
|
+
"heroImage": { "type": "media", "mediaType": "image" }
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Three top-level keys of a map are settings of the map, not fields: `mediaDir` (the media folder of the map; Ledger uses the map name when it is missing), `version` and `name`. `generate` and `check-mock` skip them, so `mock.json` needs no value for them. A map can also keep its fields in a `fields` object next to the settings, and then any field name is allowed:
|
|
243
|
+
|
|
244
|
+
```json
|
|
245
|
+
{
|
|
246
|
+
"mediaDir": "homepage",
|
|
247
|
+
"fields": {
|
|
248
|
+
"name": { "type": "string" },
|
|
249
|
+
"heroImage": { "type": "media", "mediaType": "image" }
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
A map without a `fields` object cannot have a field named `mediaDir`, `version` or `name`: Ledger drops such a field at sync without a message, so the commands refuse the map with `SD05000007`. Rename the field or use the `fields` object.
|
|
255
|
+
|
|
256
|
+
`mock.json` holds the development content per resource. A media field is an object with the file name in `mediamock/` and its alt text:
|
|
257
|
+
|
|
258
|
+
```json
|
|
259
|
+
{
|
|
260
|
+
"homepage": {
|
|
261
|
+
"title": "Welcome",
|
|
262
|
+
"heroImage": { "file": "hero.svg", "alt": "Hero banner" }
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## API reference
|
|
268
|
+
|
|
269
|
+
### The typed client (recommended)
|
|
270
|
+
|
|
271
|
+
Run `npx parrel ledger generate` after you change a map (the `postinstall` script of the package runs it too). It writes one file, the declaration `node_modules/@parrel/ledger/dist/client/index.d.ts`, typed from your maps: one property per map. The runtime of `@parrel/ledger/client` is the same for every project, and the declaration matches it: `getContent` and `getMedia` resolve with the value, `setContent` and `setMedia` resolve with nothing (`Promise<void>`).
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { ledgerClient } from "@parrel/ledger/client";
|
|
275
|
+
|
|
276
|
+
const page = await ledgerClient.homepage.getContent();
|
|
277
|
+
page.title; // string
|
|
278
|
+
page.heroImage; // the alt text, not a URL
|
|
279
|
+
|
|
280
|
+
const heroUrl = await ledgerClient.homepage.heroImage.getMedia();
|
|
281
|
+
const firstItem = await ledgerClient.homepage.items[0].getContent();
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Every field is a node with `getContent(options?)` and `setContent(data)`: strings, numbers, booleans, media, objects and arrays, and the items of an array. Media fields also have `getMedia(options?)` and `setMedia(file)`.
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
await ledgerClient.homepage.setContent({ title: "New title" }); // changes the title, keeps every other field
|
|
288
|
+
await ledgerClient.homepage.title.setContent("New title"); // the same, one field
|
|
289
|
+
await ledgerClient.homepage.author.setContent({ name: "Ada" }); // changes author.name, keeps author.role
|
|
290
|
+
await ledgerClient.homepage.heroImage.setContent("New alt text"); // changes the alt text, keeps the file
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
**`setContent` never erases a field you did not pass.** On a resource or an object it takes a partial object (`Partial<Homepage>`) and writes each field you pass at its own path, one request per field; the other fields stay as they are. The value of a field replaces that field as a whole, so for an array or a nested object pass the whole new value, or use the node of the item or the nested field. To remove a field's content, write an empty value (`""`, `[]`) on its node: `setContent` cannot delete a field. The writes run one after the other; if one fails, its error is thrown and the fields after it are not written, so read the content again before you retry.
|
|
294
|
+
|
|
295
|
+
### `getContent(path, options?)`
|
|
296
|
+
|
|
297
|
+
Returns the content at `path` (`"homepage"`, `"homepage.title"`, `"homepage.items[0]"`). Media fields come back as their alt text, a string, in production and in development; use `getMedia` for the URL. The Ledger service does this on its side, and the development mock does the same with the `{ "file", "alt" }` objects of `mock.json`. The paths `homepage.heroImage.alt` and `homepage.heroImage.url` read the raw value of a media field.
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
import { getContent } from "@parrel/ledger";
|
|
301
|
+
|
|
302
|
+
const title = await getContent("homepage.title");
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### `uploadContent(path, value)` (`setContent` on the client)
|
|
306
|
+
|
|
307
|
+
Writes **the value at `path`**: `uploadContent("homepage", { title: "x" })` replaces the whole resource `homepage` with that object and erases every other field, while `uploadContent("homepage.title", "x")` changes one field. The typed client's `setContent` is the safe form: it writes the fields you pass one by one and never erases the others (see [the typed client](#the-typed-client-recommended)). Use `uploadContent` with a resource name only when you mean to replace the whole resource. Resolves with nothing on success and throws on failure. It does not return the new value: read it again with `{ cache: "force" }`. It runs in the browser only and sends the access token of the Sentinel browser session as `Authorization: Bearer`; on a server it throws [`SD02000008`](https://docs.parrel.dev/errors/SD02000008) before it sends anything. See [Writes need the browser session](#writes-need-the-browser-session).
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
await ledgerClient.homepage.setContent({ title: "New title" }); // the other fields stay
|
|
311
|
+
const updated = await ledgerClient.homepage.getContent({ cache: "force" });
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
### `getMedia(path, options?)`
|
|
315
|
+
|
|
316
|
+
Returns the URL of a media field (`"homepage-heroImage"` or `"homepage.heroImage"`): the Ledger service URL in production, a URL below `mediaProxyPath` when that is set, and `/api/dev-cms-media/<file name>` in development, where the file name is the `file` of the field in `mock.json` (for example `/api/dev-cms-media/hero.svg`). The development media route serves that file from `mediamock/`; see [Framework media routes](#framework-media-routes). A field in `mock.json` that has no `file` throws `SD02000006`.
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
const heroUrl = await ledgerClient.homepage.heroImage.getMedia();
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
### `uploadMedia(path, file)` (`setMedia` on the client)
|
|
323
|
+
|
|
324
|
+
Uploads a file for a media field. Resolves with nothing on success and throws on failure; read the URL again with `{ cache: "force" }`. Like `uploadContent` it runs in the browser only (`SD02000008` on a server), and it checks the file first: see [Media files](#media-files).
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
await ledgerClient.homepage.heroImage.setMedia(file);
|
|
328
|
+
const url = await ledgerClient.homepage.heroImage.getMedia({ cache: "force" });
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
### Writes need the browser session
|
|
332
|
+
|
|
333
|
+
`uploadContent`, `uploadMedia` and the `setContent` and `setMedia` of the typed client run in the browser, from the page of a signed-in user of the login that is linked to your Ledger service (rulebook LED-8). They send the access token of the Sentinel browser session (see `@parrel/sentinel`) as `Authorization: Bearer <access token>`. The package does not read a token from a cookie and does not store one itself.
|
|
334
|
+
|
|
335
|
+
- When Ledger answers `401`, the package calls `refreshCurrentAccessToken()` of `@parrel/sentinel` **once** and sends the write again with the new token. When Sentinel refuses the refresh token, the session is cleared and the `401` of Ledger is thrown.
|
|
336
|
+
- A write on a server (a Next.js server component or route, a SvelteKit `load` or `+server.ts`, a Nuxt server route) has no session and throws [`SD02000008`](https://docs.parrel.dev/errors/SD02000008): "Writes need a signed-in session in the browser. Sign in with Sentinel, then call this from client code." Call the write from client code. Reading on a server keeps working. The development mock throws the same code for a write on a server, so a mistake shows in development and not only in production.
|
|
337
|
+
- Ledger allows a write only from an allowed origin: add the origins of your site in the Parrel portal.
|
|
338
|
+
- A read (`getContent`, `getMedia`, the manifest) sends **no token at all**, from a browser or a server. Ledger has no read token (rulebook LED-16); a read needs only an allowed origin, and media needs only its URL. On a server the origin is the `siteOrigin` you set, see [Reading from a server](#reading-from-a-server).
|
|
339
|
+
|
|
340
|
+
```ts
|
|
341
|
+
"use client"; // client code: a write needs the browser session
|
|
342
|
+
|
|
343
|
+
import { ledgerClient } from "@parrel/ledger/client";
|
|
344
|
+
|
|
345
|
+
async function save(title: string) {
|
|
346
|
+
await ledgerClient.homepage.title.setContent(title);
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
### Media files
|
|
351
|
+
|
|
352
|
+
Media is public by its URL (rulebook LED-12): anyone who has the URL can read the file, and the media proxy sends neither `Origin` nor `Authorization`. Do not upload a file that must stay private.
|
|
353
|
+
|
|
354
|
+
A media file must:
|
|
355
|
+
|
|
356
|
+
- have one of these extensions: `jpg`, `jpeg`, `png`, `gif`, `webp`, `svg`, `mp4`, `webm`, `mov`, `pdf`, `doc`, `docx`, `txt`;
|
|
357
|
+
- not be empty;
|
|
358
|
+
- be at most **50 MB** (52428800 bytes).
|
|
359
|
+
|
|
360
|
+
`uploadMedia` checks these three things before it sends the file, so the person gets the answer at once. It uses the same codes as Ledger: `LE02500009` (empty), `LE02500007` (extension not allowed) and `LE02500010` (over 50 MB). The mock adapter gives the same codes and messages. The check does not replace the checks of Ledger: Ledger also checks the content type and the first bytes of the file, and if it accepts less than this list says, its own error is thrown after the check passes. You can call the same check yourself, for example when a file is chosen:
|
|
361
|
+
|
|
362
|
+
```ts
|
|
363
|
+
import { assertLedgerMediaFile } from "@parrel/ledger";
|
|
364
|
+
|
|
365
|
+
input.addEventListener("change", () => {
|
|
366
|
+
const file = input.files?.[0];
|
|
367
|
+
if (file) assertLedgerMediaFile(file); // throws a ParrelError with LE02500009, LE02500010 or LE02500007
|
|
368
|
+
});
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
### Cache modes
|
|
372
|
+
|
|
373
|
+
`getContent` and `getMedia` take an optional `cache` option:
|
|
374
|
+
|
|
375
|
+
| Mode | Behaviour | Use for |
|
|
376
|
+
| --- | --- | --- |
|
|
377
|
+
| `"default"` | Returns a fresh copy; after 300 seconds checks it against the manifest and downloads only what changed, and after 24 hours downloads it again (see [Caching](#caching)). | Public pages |
|
|
378
|
+
| `"force"` | `force` asks the service on every call and updates the copy. | Admin screens, previews, reading after a write |
|
|
379
|
+
| `"no-store"` | `no-store` skips the copy for this call: it asks the service and keeps nothing. | Previews, reading after a write, debugging |
|
|
380
|
+
|
|
381
|
+
Writes drop the copies of the resource they wrote; the manifest stays. `LedgerCache.clear()` drops every copy.
|
|
382
|
+
|
|
383
|
+
### Caching
|
|
384
|
+
|
|
385
|
+
Ledger expects a package to cache what it reads (rulebook LIM-11, LIM-13). The package keeps a **copy** of every resource, media URL and proxied media file it reads, and each copy has three times:
|
|
386
|
+
|
|
387
|
+
| Time | Option | Default | Meaning |
|
|
388
|
+
| --- | --- | --- | --- |
|
|
389
|
+
| Fresh | `cache.ttlSeconds` | `300` | Within this time after the copy was downloaded or last checked, it is returned without any request, not even the manifest. |
|
|
390
|
+
| Manifest | `cache.manifestTtlSeconds` | `300` | How long one read of the manifest serves every copy that is checked. |
|
|
391
|
+
| Age limit | `cache.maxAgeSeconds` | `86400` (24 hours) | After this time since the download, the copy is downloaded again, also when its hash did not change. |
|
|
392
|
+
|
|
393
|
+
```ts
|
|
394
|
+
defineParrelLedger({
|
|
395
|
+
slug: "your-service-slug",
|
|
396
|
+
cache: {
|
|
397
|
+
ttlSeconds: 300, // a copy is fresh for 5 minutes (default)
|
|
398
|
+
manifestTtlSeconds: 300, // one manifest read serves every check for 5 minutes (default)
|
|
399
|
+
maxAgeSeconds: 86_400, // a copy is downloaded again after 24 hours at the latest (default)
|
|
400
|
+
mediaCacheMaxBytes: 52_428_800, // keep up to 50 MB of proxied media in memory (default, 0 = off)
|
|
401
|
+
},
|
|
402
|
+
});
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
- **Fresh copy.** A read of a copy that is fresh sends no request at all.
|
|
406
|
+
- **Check.** When a copy is no longer fresh, the package reads the **manifest** of the service, which lists the hash of every resource and media file, and compares the hash of the copy with it. Unchanged: the copy is fresh for another `ttlSeconds`. Changed: only that resource or file is downloaded again; the others are not. One manifest read serves every copy that is checked within `manifestTtlSeconds`, and reads at the same time share one request.
|
|
407
|
+
- **24 hours.** A copy is downloaded again `maxAgeSeconds` after its download at the latest, also when its hash did not change.
|
|
408
|
+
- **The load on Ledger.** For each server process and each service, the package reads the manifest at most once per 300 seconds, and downloads a resource or a media file only when its hash changed or after 24 hours. The first read of a resource reads the manifest too (shared with every other read), so its copy has a hash to compare with.
|
|
409
|
+
- **Media URLs.** `getMedia` keeps the URL of a media field by the same rule. The manifest lists media files by file name, while `getMedia` is asked by field path, so a URL follows the hash of the resource that holds the field (`homepage-heroImage` belongs to `homepage`): a changed resource gives the URL again.
|
|
410
|
+
- **Media files.** The media proxy keeps the bytes of a file in memory by the same rule, checked against the hash of the file itself, up to `cache.mediaCacheMaxBytes`; the oldest files go first, and a file larger than the cap is passed on and not kept. The answer carries `ETag: "<hash>"`, a request with a matching `If-None-Match` gets `304`, and the `Cache-Control` header stays `public, max-age=300, stale-while-revalidate=60`. The request of a file sends no `Origin` and no `Authorization`: media is public by its URL. Only the manifest read of the proxy sends the site origin, when it is set.
|
|
411
|
+
- **Without a manifest.** A resource that the manifest does not list, a custom adapter without `getManifest` and a manifest that cannot be read use the plain fresh time: the copy is downloaded again when it is no longer fresh. A manifest that cannot be read never breaks a read of content that can still be downloaded.
|
|
412
|
+
- **Writes.** `uploadContent`, `uploadMedia` and the `setContent` and `setMedia` of the typed client drop the copies of the resource they wrote: its content and its media URLs. The manifest stays.
|
|
413
|
+
- **`"force"` and `"no-store"`.** `force` asks the service on every call and updates the copy. `no-store` skips the copy for this call and keeps nothing. Use them for admin screens, previews and a read after a write. `cache.enabled: false` makes every read behave like `no-store`.
|
|
414
|
+
- **Next.js.** The data cache of Next.js stays in use: a read sends `next: { revalidate }` with `cache.ttlSeconds` (the manifest with `cache.manifestTtlSeconds`), both 300 by default. When the manifest says a resource changed, or a copy is older than the age limit, the package skips the copy of Next.js for that read, so you never get the old content after a change. The copies live in the memory of the server process; on a serverless host each instance has its own, and they are not shared between processes.
|
|
415
|
+
- **Browser.** In a browser the copies live in the page. A reload starts again. `getContent` sends no custom headers, so it needs no extra CORS configuration.
|
|
416
|
+
- **Mock.** The mock adapter returns a real SHA-256 hash for every resource and a manifest `version` that goes up on each write, so the cache behaves in development as it does in production.
|
|
417
|
+
|
|
418
|
+
#### Read limit
|
|
419
|
+
|
|
420
|
+
A read of the manifest, a resource or a media file from your server counts on the **address of your server**, with its own counter for each service. A site that does not cache can use up its limit. Ledger limits these reads to 600 per minute for each service and address; above that it answers `429` with the code `LE04000027`. With the copies of the package a server reads the manifest at most once per 300 seconds and downloads only what changed, which keeps it far below the limit.
|
|
421
|
+
|
|
422
|
+
The full table of limits is in [Limits](#limits).
|
|
423
|
+
|
|
424
|
+
### Limits
|
|
425
|
+
|
|
426
|
+
Ledger limits requests per IP address, in a window of 60 seconds (rulebook LIM-3). A call from your server counts on the address of your server, never on a visitor address.
|
|
427
|
+
|
|
428
|
+
| Call | Limit per 60 seconds |
|
|
429
|
+
| --- | --- |
|
|
430
|
+
| Read the manifest, a resource or a media file | 600 for each service and IP address |
|
|
431
|
+
| Read a map | 600 for each service and IP address |
|
|
432
|
+
| Write from the site (`uploadContent`, `uploadMedia`) | 120 per IP address |
|
|
433
|
+
| Map sync (`parrel ledger sync`; the preview counts as a request) | 60 per IP address. See [Limits of a map sync](#limits-of-a-map-sync) for the size limits the command checks locally |
|
|
434
|
+
| Status check | 5 per IP address |
|
|
435
|
+
| Every other request | 300 per IP address |
|
|
436
|
+
|
|
437
|
+
Over a limit, Ledger answers `429` with the code `LE04000027` (rulebook LIM-6), and the package throws that error. Wait before you try again.
|
|
438
|
+
|
|
439
|
+
| Size limit | Value |
|
|
440
|
+
| --- | --- |
|
|
441
|
+
| A media file | 50 MB, from the site and in the portal alike (see [Media files](#media-files)) |
|
|
442
|
+
| A map sync | see [Limits of a map sync](#limits-of-a-map-sync) |
|
|
443
|
+
| A backup | 2 GB (rulebook LED-17) |
|
|
444
|
+
| A restore file | at most the size of the service, and 2 GB (rulebook LIM-7) |
|
|
445
|
+
|
|
446
|
+
A trial whose origin is `localhost` accepts at most 1000 requests and 100 MB of transfer (requests and answers together) per service per clock hour (UTC), reads and writes from the site together (rulebook MOD-10). Above that, Ledger answers `429` with `LE04000027` and a `Retry-After` header with the seconds until the next hour. A service in full mode has no such cap.
|
|
447
|
+
|
|
448
|
+
The limits that this package publishes are the limits that Ledger enforces (rulebook LIM-8).
|
|
449
|
+
|
|
450
|
+
### Framework media routes
|
|
451
|
+
|
|
452
|
+
Server frameworks serve production media same-origin through a small route that `init` scaffolds:
|
|
453
|
+
|
|
454
|
+
| Framework | Route file | Code |
|
|
455
|
+
| --- | --- | --- |
|
|
456
|
+
| Next.js | `app/api/cms-media/[...path]/route.ts` | `export const { GET } = createLedgerMediaRouteHandlers();` from `@parrel/ledger/next` |
|
|
457
|
+
| SvelteKit | `src/routes/api/cms-media/[...path]/+server.ts` | `export const { GET } = createLedgerMediaProxy();` from `@parrel/ledger/sveltekit` |
|
|
458
|
+
| Nuxt | `server/routes/api/cms-media/[...path].ts` | `export default createLedgerMediaProxy();` from `@parrel/ledger/nuxt` |
|
|
459
|
+
|
|
460
|
+
`init` also adds the development route that serves the URL which the mock `getMedia` returns. It serves the files of `mediamock/` by file name, answers `404` in production and for a file that does not exist, and `403` for a path outside the media folder:
|
|
461
|
+
|
|
462
|
+
| Framework | Development route file | Code |
|
|
463
|
+
| --- | --- | --- |
|
|
464
|
+
| Next.js | `app/api/dev-cms-media/[...path]/route.ts` | a small route that `init` writes out in full |
|
|
465
|
+
| SvelteKit | `src/routes/api/dev-cms-media/[...path]/+server.ts` | `export const { GET } = createLedgerDevMediaRoute();` from `@parrel/ledger/sveltekit` |
|
|
466
|
+
| Nuxt | `server/routes/api/dev-cms-media/[...path].ts` | `export default createLedgerDevMediaRoute();` from `@parrel/ledger/nuxt` |
|
|
467
|
+
|
|
468
|
+
React, Vue and Angular have no server, so they have no media route. See the next section.
|
|
469
|
+
|
|
470
|
+
### React, Vue and Angular (browser-only apps)
|
|
471
|
+
|
|
472
|
+
A browser cannot read `parrel/ledger/mock.json`, so these apps get their development content from the config instead. `npx parrel ledger init --framework react` (or `vue`, `angular`) writes this, and `npm run dev` then shows the sample content with no server and no network:
|
|
473
|
+
|
|
474
|
+
```ts
|
|
475
|
+
// src/ledger.ts (Vite: React, Vue)
|
|
476
|
+
import { defineParrelLedger } from "@parrel/ledger";
|
|
477
|
+
import mockData from "../parrel/ledger/mock.json";
|
|
478
|
+
|
|
479
|
+
export const ledger = defineParrelLedger({
|
|
480
|
+
slug: "your-service-slug",
|
|
481
|
+
apiOrigin: import.meta.env.VITE_PARREL_API_ORIGIN, // empty: the Parrel API
|
|
482
|
+
mockData,
|
|
483
|
+
mockMediaPath: "/parrel/ledger",
|
|
484
|
+
});
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
In Angular the file is `src/app/ledger.config.ts`, the origin is `environment.parrelApiOrigin` (add `parrelApiOrigin` to your environment files) and the config also sets `mode: environment.production ? "live" : "auto"`. The config imports JSON files. Angular 22 (`"module": "preserve"`) and any `tsconfig.json` with `"moduleResolution": "bundler"` build that as is; an older Angular needs `"resolveJsonModule": true` in `tsconfig.json`, which `init` adds when it is missing.
|
|
488
|
+
|
|
489
|
+
`init` writes these files:
|
|
490
|
+
|
|
491
|
+
| File | Purpose |
|
|
492
|
+
| --- | --- |
|
|
493
|
+
| `src/ledger.ts` (Angular: `src/app/ledger.config.ts`) | The config above |
|
|
494
|
+
| `parrel/ledger/maps/homepage.json` | The sample map, used by `generate` and `sync` |
|
|
495
|
+
| `parrel/ledger/mock.json` | The sample content, imported by the config |
|
|
496
|
+
| `public/parrel/ledger/hero.svg` | The sample media file (there is no `mediamock/` and no media route) |
|
|
497
|
+
|
|
498
|
+
How it works:
|
|
499
|
+
|
|
500
|
+
- **Import the config in the app entry**, before the first render: `import "./ledger";` in `src/main.tsx` (React) or `src/main.ts` (Vue), `import "./app/ledger.config";` in the `src/main.ts` of Angular. `init` prints this step.
|
|
501
|
+
- **Outside production** (and without `mode: "live"`) the mock answers from `mockData`, in memory, with the same shapes and error codes as the file mock on a server (`LE02000003`, `LE02000018`, `LE02500007` to `LE02500010` and so on). A change made with `uploadContent` or `uploadMedia` lasts until the page reloads.
|
|
502
|
+
- **Media:** `getMedia` returns `<mockMediaPath>/<file>`, for example `/parrel/ledger/hero.svg`. Put the files in `public/parrel/ledger/`; Vite (and Angular 18 or newer, from its `public/` folder) serves them from the root. A file that you upload in the page comes back as a data URL.
|
|
503
|
+
- **In production** the same config calls the Ledger service of your slug. The sample content is part of the bundle, so keep real secrets out of `mock.json`.
|
|
504
|
+
- **Without `mockData`** in a browser, `defineParrelLedger` still returns, and the first call throws [`SD06000007`](https://docs.parrel.dev/errors/SD06000007) with a message that tells you to pass `mockData` or to use `mode: "live"`.
|
|
505
|
+
- **A local backend:** set `VITE_PARREL_API_ORIGIN` (for example `http://localhost:18700`) in `.env` and add `mode: "live"`, as described in [API origin override](#api-origin-override).
|
|
506
|
+
|
|
507
|
+
### Exports
|
|
508
|
+
|
|
509
|
+
| Import path | Contents |
|
|
510
|
+
| --- | --- |
|
|
511
|
+
| `@parrel/ledger` | `defineParrelLedger`, `getContent`, `uploadContent`, `getMedia`, `uploadMedia`, `assertLedgerMediaFile`, `createParrelLedgerServerAdapter`, `resolveParrelApiOrigin`, `resolveParrelSiteOrigin`, `LedgerCache`, `ManifestCache` and the types (`LedgerFieldType` among them) |
|
|
512
|
+
| `@parrel/ledger/client` | The typed `ledgerClient` (generated by `npx parrel ledger generate`) |
|
|
513
|
+
| `@parrel/ledger/generated` | Same as `@parrel/ledger/client` |
|
|
514
|
+
| `@parrel/ledger/mock` | `mockAdapter`, `memoryMockAdapter` (the in-memory mock for a browser or a test), `mockAdapterByEnv`, `seedMockStoreFromFile`, `seedMockStoreFromData` |
|
|
515
|
+
| `@parrel/ledger/next` | `createLedgerMediaRouteHandlers` and the development rendering helpers |
|
|
516
|
+
| `@parrel/ledger/sveltekit` | `createLedgerMediaProxy` for a SvelteKit `+server.ts` route |
|
|
517
|
+
| `@parrel/ledger/nuxt` | `createLedgerMediaProxy` for a Nuxt server route |
|
|
518
|
+
| `@parrel/ledger/ui` | React components: `LedgerOverlay`, `ContentEditor`, `MediaUploader` |
|
|
519
|
+
| `@parrel/ledger/cli` | The programmatic CLI behind the `parrel` command |
|
|
520
|
+
|
|
521
|
+
## CLI
|
|
522
|
+
|
|
523
|
+
```bash
|
|
524
|
+
npx parrel ledger install # Install @parrel/ledger (no setup)
|
|
525
|
+
npx parrel ledger init # Config, sample map, content and media, framework media routes
|
|
526
|
+
npx parrel ledger generate # Generate the typed ledgerClient from parrel/ledger/maps/
|
|
527
|
+
npx parrel ledger sync # Preview, confirm and publish the maps (needs a deployment token). Options: --force|-f, --yes|-y
|
|
528
|
+
npx parrel ledger upload # Deprecated name of sync: prints a reminder, then runs sync
|
|
529
|
+
npx parrel ledger seed <file.parrel> # Fill parrel/ledger/ with the content of a .parrel backup. Option: --force|-f
|
|
530
|
+
npx parrel ledger check-mock # Validate mock.json and the mock media (mediamock/, or public/parrel/ledger/ in a browser-only app) against the maps
|
|
531
|
+
npx parrel ledger clean # Remove the client/ folder that earlier versions of generate wrote
|
|
532
|
+
npx parrel ledger help # Or: npx parrel ledger ?
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
`init` options: `--framework <next|nuxt|sveltekit|angular|vue|react>`, `--slug <slug>`, `-f` or `--force` (overwrite existing files) and `-y` or `--yes` (accept all defaults). `-h` or `--help` shows the help. `sync` reads the slug from the `defineParrelLedger({ slug })` call in your project and sends the maps with the map deployment token of the service (`POST /v1/map/sync/{slug}`). The token comes from the `PARREL_LEDGER_DEPLOYMENT_TOKEN` environment variable, or from a prompt when you run the command in a terminal (see [Deployment token in a job without a terminal](#deployment-token-in-a-job-without-a-terminal)). The sync publishes the whole set: it removes every map that has no file in `parrel/ledger/maps/`, together with its resources and media files. It sends the maps to `https://api.parrel.dev`, or to `PARREL_API_ORIGIN` when that variable is set. `sync` checks the [limits of a map sync](#limits-of-a-map-sync) before it sends anything, and shows [what it would delete or retype](#preview-and-confirmation-of-a-sync) before it changes anything.
|
|
536
|
+
|
|
537
|
+
## Use a backup as local content
|
|
538
|
+
|
|
539
|
+
A backup of a Ledger service is a `.parrel` file with every map, resource and media file of the service. Download it in the Parrel portal (the backup of the service), then turn it into the local content of your project with one command:
|
|
540
|
+
|
|
541
|
+
```bash
|
|
542
|
+
npx parrel ledger seed Ab3xYz9_kQ1w-20261007.parrel
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
The command checks the whole file before it writes anything, and then fills the folder that the mock adapter reads in development:
|
|
546
|
+
|
|
547
|
+
| From the backup | Goes to |
|
|
548
|
+
| --- | --- |
|
|
549
|
+
| `maps/<name>.json` | `parrel/ledger/maps/<name>.json`, byte for byte |
|
|
550
|
+
| `content/<name>.json` | one key `<name>` in `parrel/ledger/mock.json`, in name order. A media field (`{ "alt", "url" }`) becomes `{ "file": "<file name>", "alt": "<alt>" }`, where the file name is the last part of the URL. |
|
|
551
|
+
| `media/<name>` | `parrel/ledger/mediamock/<name>`, or `public/parrel/ledger/<name>` when that folder exists (a React, Vue or Angular app) |
|
|
552
|
+
| `extras/` (logs, activity, statistics and audit entries of a backup made with the Extras) | nothing: the seed skips them, as a restore does |
|
|
553
|
+
|
|
554
|
+
A project that still has only `parrel/cms/` is seeded in that folder. Then it runs the checks of `check-mock` and prints the result, and tells you to run `npx parrel ledger generate` to update the typed client. A media field whose file is not in the backup is kept as `{ "file", "alt" }` with a warning.
|
|
555
|
+
|
|
556
|
+
**What is replaced.** The seed replaces, it does not merge. When the folder already has map files, a `mock.json` that is not empty or mock media, it lists them, stops with [`SD05000029`](https://docs.parrel.dev/errors/SD05000029) and writes nothing. Run it again with `--force` (or `-f`) to delete `maps/*.json` and the files in the mock media folder, and write a new `mock.json`. Commit your local content first if you want to keep it.
|
|
557
|
+
|
|
558
|
+
**What is not in a backup.** A backup holds no token, no allowed origin, no slug of your project and no internal ids, so the seed never changes your config (`lib/ledger.ts`), your slug or your environment. The slug in the backup is not used.
|
|
559
|
+
|
|
560
|
+
The file is read with the limits of a restore in Ledger: at most 100000 entries, 16 MiB per map or resource and 2 GiB in total, counted while it is unpacked. A file that breaks a rule ends with its own code and writes nothing:
|
|
561
|
+
|
|
562
|
+
| Code | When |
|
|
563
|
+
| --- | --- |
|
|
564
|
+
| [`SD05000024`](https://docs.parrel.dev/errors/SD05000024) | No file was given, or it does not exist or is not a file |
|
|
565
|
+
| [`SD05000025`](https://docs.parrel.dev/errors/SD05000025) | Not a zip, a damaged zip, an entry that cannot be unpacked, or `counts` that do not match the entries |
|
|
566
|
+
| [`SD05000026`](https://docs.parrel.dev/errors/SD05000026) | `manifest.json` is missing or not valid, or the file is not a Ledger backup of format version 1 |
|
|
567
|
+
| [`SD05000027`](https://docs.parrel.dev/errors/SD05000027) | An unsafe or duplicate entry name, two names that differ only in case, or an entry outside `maps/`, `content/`, `media/` and `extras/` |
|
|
568
|
+
| [`SD05000028`](https://docs.parrel.dev/errors/SD05000028) | Over a limit: more than 100000 entries, a map or resource over 16 MiB, or more than 2 GiB unpacked |
|
|
569
|
+
| [`SD05000029`](https://docs.parrel.dev/errors/SD05000029) | The folder already has maps or content and `--force` is not given |
|
|
570
|
+
|
|
571
|
+
## Deployment token in a job without a terminal
|
|
572
|
+
|
|
573
|
+
`npx parrel ledger sync` needs a Ledger deployment token. Create one in the Parrel portal. A token is valid for 5 minutes, and only the newest token of the service works: when a new one is made, an older one gets `401` `DEPLOYMENT_TOKEN_SUPERSEDED` (`LE04000029`). The same token serves the preview and the sync after it. The command finds the token in this order:
|
|
574
|
+
|
|
575
|
+
1. The `PARREL_LEDGER_DEPLOYMENT_TOKEN` environment variable. Use it in a job without a terminal, where nobody can type: make a new token for each sync, pass it to that one run only and run `npx parrel ledger sync`. Never store the token as a secret of your CI system or in a file: it stops working after 5 minutes. An empty value counts as not set.
|
|
576
|
+
2. A prompt, only when the command runs in a terminal.
|
|
577
|
+
|
|
578
|
+
Without a token, and without a terminal (a CI job, or the input is closed, as with `< /dev/null`), the command sends nothing, prints `SD05000008` with the name of the variable and exits with code `1`. The token is never printed. There is no command-line option for the token, because an option stays in your shell history.
|
|
579
|
+
|
|
580
|
+
```bash
|
|
581
|
+
PARREL_LEDGER_DEPLOYMENT_TOKEN=<token from the portal> npx parrel ledger sync
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
## Preview and confirmation of a sync
|
|
585
|
+
|
|
586
|
+
`npx parrel ledger sync [--force|-f] [--yes|-y]` first asks Ledger what the sync would do (`POST /v1/map/sync/{slug}/preview`, with the same body and the same deployment token; the preview changes nothing, and the sync after it uses the same token). It prints the maps and fields that the sync would add, delete, remove or retype, with the number of resources and media files that go with them:
|
|
587
|
+
|
|
588
|
+
```text
|
|
589
|
+
Sync preview
|
|
590
|
+
add 1 · update 1 · delete 1 · unchanged 0
|
|
591
|
+
Maps that the sync deletes (with their resources and media files):
|
|
592
|
+
- faq: 1 resource(s), 3 media file(s)
|
|
593
|
+
Fields that the sync removes (their values are lost):
|
|
594
|
+
- footer.tagline: in 1 resource(s)
|
|
595
|
+
Fields that the sync gives another type:
|
|
596
|
+
- footer.year: string to number, in 1 resource(s)
|
|
597
|
+
```
|
|
598
|
+
|
|
599
|
+
When the sync deletes or retypes something, it needs a confirmation:
|
|
600
|
+
|
|
601
|
+
| Where it runs | What happens |
|
|
602
|
+
|---|---|
|
|
603
|
+
| In a terminal | It asks `This sync deletes 3 media files and removes or retypes 2 fields. Continue? (y/N)`. Only `y` or `yes` continues, and the sync is applied with the preview you saw (`previewId`). An empty answer or `n` sends nothing and exits with `SD05000015`. |
|
|
604
|
+
| Without a terminal (CI, or a closed input), without `--force` | It sends nothing and exits with code `1` and `SD05000015`. |
|
|
605
|
+
| With `--force` or `-f`, or `--yes` or `-y` (the same) | It prints the preview and applies the sync with `confirm: true`, without asking. Use it in CI: `PARREL_LEDGER_DEPLOYMENT_TOKEN=<token> npx parrel ledger sync --force`. |
|
|
606
|
+
|
|
607
|
+
A sync that deletes and retypes nothing needs no confirmation, also in CI. A `409` of the service is printed with its code: `MAP_SYNC_CONFIRMATION_REQUIRED`, `MAP_SYNC_PREVIEW_EXPIRED` (the preview is too old) or `MAP_SYNC_PREVIEW_STALE` (the maps changed after the preview). Run the sync again, with a new deployment token if the old one is older than 5 minutes. A token that is no longer the newest one of the service gets `401` `DEPLOYMENT_TOKEN_SUPERSEDED` (`LE04000029`): make a new token in the Parrel portal and run the sync again.
|
|
608
|
+
|
|
609
|
+
When the preview fails, for example with `404` or `405`, the command prints the error that Ledger sent, exits with code `1` and syncs nothing (rulebook LED-4). A sync never runs without the list of what it deletes.
|
|
610
|
+
|
|
611
|
+
From code, `validateMapSet(maps)`, `previewMapSync(slug, token, maps, options?)` and `applyMapSync(slug, token, maps, confirm, options?)` are exported from `@parrel/ledger/cli`. `previewMapSync` returns the preview or throws: the error that Ledger sent, or `SD01000012` for an answer that is not a preview. `applyMapSync` takes `{ confirm: true }` or `{ previewId }`.
|
|
612
|
+
|
|
613
|
+
## Limits of a map sync
|
|
614
|
+
|
|
615
|
+
The command checks these limits on your computer before it sends anything, so a sync that breaks one is never sent. Ledger checks the same limits.
|
|
616
|
+
|
|
617
|
+
| Limit | Value | Code |
|
|
618
|
+
|---|---|---|
|
|
619
|
+
| Size of the request body | 10 MB | `SD05000010` |
|
|
620
|
+
| Maps in one sync | 200 | `SD05000011` |
|
|
621
|
+
| Fields in one map, nested fields included (the fields of an `object`, the `items` of an `array`) | 500 | `SD05000012` |
|
|
622
|
+
| Nesting of fields (a field at the top of a map is level 1) | 8 levels | `SD05000013` |
|
|
623
|
+
|
|
624
|
+
The rate limit of the map sync is in the table under [Limits](#limits): 60 requests per minute per IP address, and the preview counts as a request. Over the limit, Ledger answers `429` with `LE04000027` and the command prints it.
|
|
625
|
+
|
|
626
|
+
## Error handling
|
|
627
|
+
|
|
628
|
+
### Error codes and handlers
|
|
629
|
+
|
|
630
|
+
`@parrel/ledger` has its own error codes and its own small error handlers. You do not need another package for them, and the handlers do not depend on the other Parrel packages. The other Parrel packages have the same handlers with their own codes.
|
|
631
|
+
|
|
632
|
+
| Export | What it does |
|
|
633
|
+
| --- | --- |
|
|
634
|
+
| `ParrelError` | The error class. It has the `code`, the HTTP `status` (only for an error that Ledger returned), the `traceId` of the request, the `fieldErrors` of a validation error, the `docs` link and the `cause`. Branch on the `code`, never on the message. |
|
|
635
|
+
| `isParrelError(value)` | `true` for any Parrel error, also for one that another Parrel package threw. It checks the shape of the error (a `code` such as `LE04000017`) and never uses `instanceof`, so it works when your app uses two packages and therefore has two `ParrelError` classes. |
|
|
636
|
+
| `parseApiError(response)` | Turns an error answer of Ledger into a `ParrelError` and keeps the code, the status and the trace id. Pass a `Response` to get a promise, or `{ status, body }` to get the error at once. An answer that is not a Parrel error becomes `SD01000012` with the HTTP status. It never throws. |
|
|
637
|
+
| `LedgerErrorCode` | The type of the codes of this package. It also accepts any other string, because a newer Ledger can return a code that your version does not know yet. |
|
|
638
|
+
| `getErrorInfo(code)` | In `@parrel/ledger/errors`. The name, HTTP status, message, what to do and the link to the documentation page of a code, or `undefined` for a code the package does not know. |
|
|
639
|
+
|
|
640
|
+
The package knows 114 `LE` codes (the errors of the Ledger endpoints that it calls) and 47 `SD` codes (the errors that the package raises itself). A code never belongs to two packages. Every code has a page at `https://docs.parrel.dev/errors/<code>`, for example <https://docs.parrel.dev/errors/LE04000017>. The rule that picks the codes is in the [root README](https://github.com/digistra-belgium/parrel-packages/blob/main/README.md#error-codes).
|
|
641
|
+
|
|
642
|
+
The codes that you will meet most:
|
|
643
|
+
|
|
644
|
+
| Code | Meaning | HTTP |
|
|
645
|
+
| --- | --- | --- |
|
|
646
|
+
| `LE00100002` to `LE00100004` | The slug is unknown. | 404 |
|
|
647
|
+
| `LE00100006` | The Ledger service is switched off. | 403 |
|
|
648
|
+
| `LE02000003`, `LE02000018`, `LE02000019` | The content does not exist. | 404 |
|
|
649
|
+
| `LE02500001` | The media file does not exist. | 404 |
|
|
650
|
+
| `LE04000015` to `LE04000017` | The request does not come from an allowed origin. From a server: no `siteOrigin` was sent (`LE04000015`), the service has no origins (`LE04000016`), or the `siteOrigin` is not on its list (`LE04000017`); see [Reading from a server](#reading-from-a-server). | 403 |
|
|
651
|
+
| `LE04000018`, `LE04000019` | The access token for a write is missing or not valid. | 401 |
|
|
652
|
+
| `LE09000023` | Sentinel gave no answer. Try again later. The session stays. | 503 |
|
|
653
|
+
| `LE04000021` to `LE04000024` | The deployment token of `parrel ledger sync` is missing, expired, not valid or for another service. | 401, 403 |
|
|
654
|
+
| `LE03000001` | The storage limit of the service is reached. | 409 |
|
|
655
|
+
| `LE02500011` | The upload is too large. | 413 |
|
|
656
|
+
| `LE04000026` | The IP address is blocked. | 403 |
|
|
657
|
+
| `LE04000027` | Too many requests. | 429 |
|
|
658
|
+
|
|
659
|
+
Show a message to a visitor with `getErrorInfo`:
|
|
660
|
+
|
|
661
|
+
```ts
|
|
662
|
+
import { isParrelError } from "@parrel/ledger";
|
|
663
|
+
import { getErrorInfo } from "@parrel/ledger/errors";
|
|
664
|
+
|
|
665
|
+
try {
|
|
666
|
+
await doSomething();
|
|
667
|
+
} catch (error) {
|
|
668
|
+
if (isParrelError(error)) {
|
|
669
|
+
const info = getErrorInfo(error.code);
|
|
670
|
+
showMessage(info?.message ?? "Something went wrong. Try again later.");
|
|
671
|
+
console.error(error.code, error.status, error.traceId, error.docs);
|
|
672
|
+
} else {
|
|
673
|
+
throw error;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
```
|
|
677
|
+
|
|
678
|
+
`info.message` is a full English sentence that is safe to show. `info.whatToDo` says what the visitor or the developer should do. Log `error.code` and `error.traceId`, and give them to Parrel support when you need help.
|
|
679
|
+
|
|
680
|
+
#### The separate `/errors` entry
|
|
681
|
+
|
|
682
|
+
`getErrorInfo` and the table of messages are in `@parrel/ledger/errors`, not in the main entry. Code that only throws and checks errors (`ParrelError`, `isParrelError`, `parseApiError`) does not bundle the messages, so a client component stays small. Import `@parrel/ledger/errors` only where you show a message.
|
|
683
|
+
|
|
684
|
+
#### Turn an answer into an error yourself
|
|
685
|
+
|
|
686
|
+
```ts
|
|
687
|
+
import { parseApiError } from "@parrel/ledger";
|
|
688
|
+
|
|
689
|
+
const response = await fetch(url);
|
|
690
|
+
if (!response.ok) {
|
|
691
|
+
const error = await parseApiError(response); // the response can still be read afterwards
|
|
692
|
+
console.error(error.code, error.status, error.traceId);
|
|
693
|
+
error.fieldErrors?.forEach((fieldError) => showFieldMessage(fieldError.field, fieldError.message));
|
|
694
|
+
}
|
|
695
|
+
```
|
|
696
|
+
|
|
697
|
+
Every function of the package that fails throws a `ParrelError`, never a plain `Error`. `error.toJSON()` returns `{ code, name, message, status, traceId, fieldErrors, docs }` for logs and API answers.
|
|
698
|
+
|
|
699
|
+
- An answer of Ledger that is not 2xx is passed on with its own code, status and trace id. A missing resource is `LE02000003` (404), a path that is not in the resource is `LE02000018` (404), a missing access token is `LE04000018` (401).
|
|
700
|
+
- A request that gets no answer (offline, DNS, connection refused, or in a browser a request from an origin that is not allowed) throws the `SD` code of the call, with the original error as `cause`. The message says that in a browser an origin that is not allowed looks the same, and to check the allowed origins of your Ledger service in the Parrel portal.
|
|
701
|
+
- An answer that is not a Parrel error body throws `SD01000012` with the HTTP status.
|
|
702
|
+
|
|
703
|
+
### Which function throws which code
|
|
704
|
+
|
|
705
|
+
| Function | Throws |
|
|
706
|
+
| --- | --- |
|
|
707
|
+
| `getContent()` | the code and status that Ledger returned; `SD01000001` (cannot be reached); `SD02000001` (a custom adapter cannot read content); `SD00100001` (not configured); on a server `SD00100019` (no site origin) and `SD00100018` (a wrong `PARREL_SITE_ORIGIN`) |
|
|
708
|
+
| `uploadContent()` | the code that Ledger returned (for example `LE04000018`, `LE02000012`, `LE04000027` over the rate limit); `SD02000008` (called on a server, no browser session); `SD01000002`; `SD02000002`; `SD00100001` |
|
|
709
|
+
| Media route (`proxyLedgerMedia`) | the status, body and content type that Ledger answered, unchanged (for example `LE02500001`, 404); `SD01000003` with status 502 when Ledger cannot be reached; `400` (plain text) for an unsafe path |
|
|
710
|
+
| `getMedia()` | the code that Ledger returned; `SD01000003`; `SD02000006` (Ledger answered without a usable URL); `SD02000003` and `SD02000005` (a custom adapter); `SD00100001`; on a server `SD00100019` and `SD00100018` |
|
|
711
|
+
| `uploadMedia()` and `assertLedgerMediaFile()` | `LE02500009` for an empty file, `LE02500007` for an extension that is not allowed and `LE02500010` for a file over 50 MB, all checked before anything is sent; `SD02000008` (called on a server, no browser session); the code that Ledger returned (for example `LE04000018`, `LE04000027`); `SD01000004`; `SD02000004`; `SD00100001` |
|
|
712
|
+
| manifest (`getManifest` of the adapter) | the code that Ledger returned; `SD01000005`; on a server `SD00100019` and `SD00100018` |
|
|
713
|
+
| `defineParrelLedger()` | `SD00100002` (no configuration), `SD00100003` (`slug`), `SD00100008` (`apiOrigin`), `SD00100018` (`siteOrigin`) |
|
|
714
|
+
| Mock adapter | the same codes and statuses as Ledger: `LE02000003`, `LE02000018`, `LE02000017` (empty path), `LE02500007` to `LE02500010` (files), `SD02000008` (`uploadContent` or `uploadMedia` on a server); `SD06000001` to `SD06000012` (the mock files and the seed helpers); `SD06000007` (browser without `mockData`); `SD06000009` (empty folder) |
|
|
715
|
+
| CLI | `SD05000002`, `SD05000003` (map files), `SD05000007` (a field with a reserved name), `SD05000023` (a field with a type outside the seven field types), `SD05000008` (no deployment token for `sync`), `SD05000010` to `SD05000013` (a limit of the map sync), `SD05000015` (the sync was not confirmed), `SD01000014` (sync cannot reach Ledger), the code that Ledger returned (also the `409` of the sync); `SD05000024` to `SD05000029` (`seed`, see [Use a backup as local content](#use-a-backup-as-local-content)) |
|
|
716
|
+
|
|
717
|
+
Writes throw instead of returning `false`, so wrap them in `try`/`catch` and branch on the code:
|
|
718
|
+
|
|
719
|
+
```ts
|
|
720
|
+
import { isParrelError } from "@parrel/ledger";
|
|
721
|
+
import { getErrorInfo } from "@parrel/ledger/errors";
|
|
722
|
+
|
|
723
|
+
try {
|
|
724
|
+
await ledgerClient.homepage.setContent({ title });
|
|
725
|
+
} catch (error) {
|
|
726
|
+
if (!isParrelError(error)) throw error;
|
|
727
|
+
if (error.code === "LE04000018") {
|
|
728
|
+
showError("Sign in to save changes.");
|
|
729
|
+
} else {
|
|
730
|
+
showError(getErrorInfo(error.code)?.message ?? error.message);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
The mock adapter throws the same codes as Ledger for the same mistake (an unknown resource, an empty file, a file that is not allowed, and a write on a server: `SD02000008`), so this code works in development and in production.
|
|
736
|
+
|
|
737
|
+
### Mistakes in the setup
|
|
738
|
+
|
|
739
|
+
A mistake in the setup throws a `ParrelError` whose message names the key or the file to fix:
|
|
740
|
+
|
|
741
|
+
| Code | When |
|
|
742
|
+
| --- | --- |
|
|
743
|
+
| `SD00100002` | `defineParrelLedger` gets no config |
|
|
744
|
+
| `SD00100003` | `slug` is missing, empty or not a string |
|
|
745
|
+
| `SD00100001` | Content is read or written before `defineParrelLedger` |
|
|
746
|
+
| `SD00100008` | `apiOrigin` or `PARREL_API_ORIGIN` is not allowed, see [API origin override](#api-origin-override) |
|
|
747
|
+
| `SD00100018` | `siteOrigin` or `PARREL_SITE_ORIGIN` is not an origin in the accepted form, see [Reading from a server](#reading-from-a-server) |
|
|
748
|
+
| `SD00100019` | A read on a server in production or live mode has no `siteOrigin` and no `PARREL_SITE_ORIGIN` |
|
|
749
|
+
|
|
750
|
+
The CLI prints an error as its code, its message and the link to its documentation page, for example `LE04000023 The deployment token is not valid.`, adds a hint for the deployment token codes, and exits with code `1`.
|
|
751
|
+
|
|
752
|
+
## Moving from @parrel/cms
|
|
753
|
+
|
|
754
|
+
Version 5 renames the package from `@parrel/cms` to `@parrel/ledger`. Every old name keeps working as a deprecated alias until version 6, so you can move step by step.
|
|
755
|
+
|
|
756
|
+
1. Swap the package:
|
|
757
|
+
|
|
758
|
+
```bash
|
|
759
|
+
npm uninstall @parrel/cms
|
|
760
|
+
npm install @parrel/ledger
|
|
761
|
+
```
|
|
762
|
+
|
|
763
|
+
Or install `@parrel/cms@5` first: that final version only re-exports `@parrel/ledger`, so nothing else has to change yet.
|
|
764
|
+
|
|
765
|
+
2. Replace the imports: `@parrel/cms` → `@parrel/ledger`, including the subpaths (`/client`, `/next`, `/sveltekit`, `/nuxt`, `/ui`, `/mock`, `/core/types`, `/core/transform-content`).
|
|
766
|
+
|
|
767
|
+
3. Rename what you use:
|
|
768
|
+
|
|
769
|
+
| `@parrel/cms` (deprecated) | `@parrel/ledger` |
|
|
770
|
+
| --- | --- |
|
|
771
|
+
| `defineParrelCms` | `defineParrelLedger` |
|
|
772
|
+
| `DefineParrelCmsConfig` | `DefineParrelLedgerConfig` |
|
|
773
|
+
| `cmsClient` | `ledgerClient` |
|
|
774
|
+
| `createCmsClient`, `CmsClient`, `CmsClientNode` | `createLedgerClient`, `LedgerClient`, `LedgerClientNode` |
|
|
775
|
+
| `createParrelCmsServerAdapter`, `ParrelCmsAdapter` | `createParrelLedgerServerAdapter`, `ParrelLedgerAdapter` |
|
|
776
|
+
| `CmsCache` | `LedgerCache` |
|
|
777
|
+
| `CmsContentPath`, `CmsMediaPath` | `LedgerContentPath`, `LedgerMediaPath` |
|
|
778
|
+
| `CmsMapSchema`, `CmsFieldDefinition` | `LedgerMapSchema`, `LedgerFieldDefinition` |
|
|
779
|
+
| `createCmsMediaRouteHandlers` (Next.js) | `createLedgerMediaRouteHandlers` |
|
|
780
|
+
| `createParrelCmsNextCacheAdapter` (Next.js) | `createParrelLedgerNextCacheAdapter` |
|
|
781
|
+
| `createCmsMediaProxy` (SvelteKit, Nuxt) | `createLedgerMediaProxy` |
|
|
782
|
+
| `CMSOverlay` | `LedgerOverlay` |
|
|
783
|
+
|
|
784
|
+
4. Use the new CLI scope: `npx parrel cms <command>` → `npx parrel ledger <command>`, and `upload` → `sync`. The old forms still run and print a reminder.
|
|
785
|
+
|
|
786
|
+
5. Move your content folder: `git mv parrel/cms parrel/ledger`. Until you do, the CLI and the mock adapter keep reading `parrel/cms/`; as soon as `parrel/ledger/` exists, it is used instead.
|
|
787
|
+
|
|
788
|
+
6. Run `npx parrel ledger generate`, so the typed client is written to `@parrel/ledger/client`.
|
|
789
|
+
|
|
790
|
+
Nothing changes on the Ledger service: the endpoints, your slug, your maps and your content stay the same. The media route paths (`/api/cms-media`, `/api/dev-cms-media`) also stay as they are, so the routes you scaffolded before keep working.
|
|
791
|
+
|
|
792
|
+
---
|
|
793
|
+
|
|
794
|
+
**Parrel** is a product of **Digistra**.
|