@plitzi/sdk-server 0.37.8 → 0.37.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +236 -0
  2. package/README.md +7 -2
  3. package/dist/actions.d.ts +1 -1
  4. package/dist/adapters/cloudAdapters.js +4 -30
  5. package/dist/core/services/functionRoutes.d.ts +2 -2
  6. package/dist/core/services/functionRoutes.js +2 -2
  7. package/dist/functions-api.d.ts +23 -2
  8. package/dist/functions.d.ts +1 -1
  9. package/dist/functions.js +2 -2
  10. package/dist/modules/actions/index.d.ts +1 -1
  11. package/dist/modules/actions/index.js +3 -2
  12. package/dist/modules/actions/runtime/renderResolver.js +30 -4
  13. package/dist/modules/actions/taskCatalog.d.ts +3 -1
  14. package/dist/modules/actions/taskCatalog.js +1 -0
  15. package/dist/modules/actions/tasks/registry.js +4 -2
  16. package/dist/modules/actions/types.d.ts +6 -0
  17. package/dist/modules/functions/config.d.ts +19 -3
  18. package/dist/modules/functions/config.js +30 -14
  19. package/dist/modules/functions/contract.d.ts +10 -3
  20. package/dist/modules/functions/driver.js +4 -2
  21. package/dist/modules/functions/manifest.d.ts +5 -3
  22. package/dist/modules/functions/manifest.js +36 -5
  23. package/dist/modules/functions/routes.d.ts +1 -1
  24. package/dist/modules/functions/routes.js +3 -3
  25. package/dist/modules/functions/space.d.ts +7 -5
  26. package/dist/modules/functions/space.js +17 -10
  27. package/dist/modules/runtime/contract.d.ts +1 -1
  28. package/dist/modules/runtime/stages.d.ts +1 -1
  29. package/dist/modules/runtime/stages.js +1 -1
  30. package/dist/modules/ssr/prepareRender.js +2 -2
  31. package/dist/modules/ssr/registerExternalPlugins.d.ts +5 -1
  32. package/dist/modules/ssr/registerExternalPlugins.js +6 -2
  33. package/package.json +3 -3
  34. package/skills/plitzi-authoring/SKILL.md +11 -8
  35. package/skills/plitzi-authoring/reference/components.md +75 -0
  36. package/skills/plitzi-authoring/reference/flows.md +1 -1
  37. package/skills/plitzi-authoring/reference/plugins.md +12 -0
  38. package/skills/plitzi-authoring/reference/templates-and-export.md +6 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,241 @@
1
1
  # @plitzi/sdk-server
2
2
 
3
+ ## 0.37.9
4
+
5
+ ### Patch Changes
6
+
7
+ - 3ae61a4: ## Components replace segments
8
+
9
+ - **What a component is:** a reusable block written once and placed anywhere as an instance. An edit to the component
10
+ is an edit to every instance.
11
+ - **Where it lives:** in the space document, as `schema.components`, one tree per component and never in
12
+ `schema.flat`. It is published, rolled back, copied by templates and exported with the space.
13
+ - **Props and slots:**
14
+ - A component declares props (`type`, `description`, `required`, `default`, `options`). An instance hands them in
15
+ as its own attributes, so templates and bindings reach them. Inside, they are read as `{{ props.<name> }}`.
16
+ - Slots are elements an instance fills; each child names its slot in `attributes.slot`.
17
+ - **A prop an instance leaves out prints nothing.** It is its `default`, or `null`. `props` is a settled source:
18
+ - `processTwig` takes `{ settled }` in place of `keepEmptyTokens: true`.
19
+ - Every other empty token is still kept for a later pass.
20
+ - `COMPONENT_PROPS_SOURCE` names the source.
21
+ - **Fixed: a flow in a list row or a component instance acts on its own copy.** A step's target resolves in the
22
+ replica the flow fired in first, then outwards. It used to reach whichever copy registered last.
23
+ - **Fixed: an instance's own `visible` hides it in preview.** The same goes for an element reference.
24
+ - **Fixed: a list row keeps its state with its record.** Rows are keyed by each record's unique `id`, so filtering no
25
+ longer moves one row's state onto another.
26
+ - **Closed scope:** inside, a component reads only its props and the globals. The validator, `lintSpace` and
27
+ `authorSpace` each refuse a read of the page around an instance. Components nest, and a cycle is refused.
28
+ - **Where to use them:**
29
+ - In code (`@plitzi/sdk-authoring`): `SpaceSpec.components` and `component(id, { props, children })`.
30
+ `specFromSpace` and `specToSource` read and write both.
31
+ - In the builder:
32
+ - a Components panel lists them, and an open component becomes the canvas;
33
+ - an element becomes a component with **Save as component**;
34
+ - in an instance's settings, an instance gets its props and slots, or is **detached** back into a copy.
35
+ - In the MCP: `upsertComponent` and `deleteComponent`. Element ops work inside a component through `pageRef`.
36
+ - **Schema helpers:** `@plitzi/sdk-schema` gains `addComponent`, `updateComponent`, `removeComponent`,
37
+ `detachInstance`, `renameElement`, `treeOf`, `flatMapOf` and `documentIds`.
38
+ - **GraphQL and live events:** `SpaceAddComponent`, `SpaceUpdateComponent`, `SpaceRemoveComponent` and
39
+ `SpaceDetachInstance`, each with a live event. History records a declaration change as a `component` entry.
40
+ - **Breaking: segments are removed.** This covers:
41
+ - `@plitzi/sdk-shared`'s segment types, queries, mutations, context and `SEGMENT_*` events;
42
+ - `referenceType: 'segment'`;
43
+ - the `Segments` builder module;
44
+ - `Space.segments` and the `Segment`/`Segments` queries;
45
+ - `CommonState.prevSchema`.
46
+ - **Breaking: `ElementLayout` and `LayoutBody` change shape.**
47
+ - `ElementLayout` is `{ slots, rootId, type }`; it was `{ containerId }`.
48
+ - `LayoutBody` takes `bodies` keyed by slot.
49
+ - `reference`'s `referenceContainer` attribute is removed.
50
+ - Guide: `docs/en/components.md`.
51
+
52
+ ## Functions ask for the time they need
53
+ - **What changes:** a task can ask for more CPU or wall time than the default with `limits`, in milliseconds. Example:
54
+ `limits: { cpuMs: 1000, wallMs: 20_000 }`. `defineFunctions({ limits })` asks it for every task and route at once,
55
+ and a task's own limits win over those.
56
+ - **What a run is given:** what it asked for, or the default (100 ms of CPU, 10 s) when it asked for nothing. Never
57
+ above the space's plan or the deployment's ceiling.
58
+ - **Deployment ceilings:** `functions.limits` sets them. `DEFAULT_FUNCTION_CEILINGS` covers each unset one, at 2 s of
59
+ CPU and 30 s.
60
+ - **Asking for more than the ceiling** is a problem when the functions are saved; it is never quietly cut down.
61
+ - **Manifest:** carries what each task asked for, and the builder shows it beside the task.
62
+
63
+ ## Functions answer under `/fn`, not `/api`
64
+
65
+ A space's routes are served at `/fn/<path>` (`FUNCTION_ROUTES_PREFIX`). `/api` is a slug a site wants for a page of its
66
+ own. A page under `/fn` is refused instead (`page-route-reserved`).
67
+
68
+ ## The builder's Functions panel
69
+
70
+ Rebuilt around the code. The panel reads `defineFunctions` as it is typed and writes into it, so the code stays the one
71
+ place a function is declared.
72
+
73
+ - **Layout:** the tasks, routes and files on the left, the code in the middle, the selected task on the right.
74
+ - **Live list:** tasks and routes are listed as the code declares them, including tasks imported from another file.
75
+ A task you have written but not saved says so. Tasks built by calling something are counted, and listed once saved.
76
+ - **Code and panel follow each other:** clicking a task or a route opens its file at its line. Putting the cursor inside
77
+ a task's code selects that task.
78
+ - **New task:** + in Tasks asks for its namespace, action and title. The task is written into `defineFunctions` with a
79
+ `run` to start from, in the file's own quotes, and the editor opens on it.
80
+ - **Time limit:** each task gets a slider from 100 ms to 1 s of CPU per run, with presets. The value is written into
81
+ the task as `limits: { cpuMs }`. "Use default" takes it out. `DEFAULT_FUNCTION_TIME_LIMITS` in
82
+ `@plitzi/sdk-shared/actions` is the default both the panel and the server use.
83
+ - **Test:** fills a task's params the way its step does, from their defaults: a select, a switch or text. JSON stays a
84
+ toggle away. With unsaved changes, the button reads "Save & run": it saves, then runs. If the save fails, it says why.
85
+ - **Header:** shows Saved, Unsaved (and in how many files) or the number of problems the last save found. ⌘S saves.
86
+ **Discard** asks first, then puts every file back to what was last saved, or back to nothing for functions never
87
+ saved. Removing the functions is a quiet button beside Save.
88
+ - **Problems:** clicking one opens its file at its line.
89
+ - **Editor:** each file has its own editor and undo history. Opening another file no longer marks the one you left as
90
+ changed. Before this, it could also write the newly opened file's text into the one you left. The cause was in
91
+ `@plitzi/plitzi-ui`'s CodeMirror, fixed in 1.6.25, which every package now depends on. That release also sets code
92
+ editors (several lines) in a monospaced face again. Long lines scroll inside the editor, and the line numbers stay
93
+ in place.
94
+
95
+ ## A space's own functions are their own category of steps
96
+
97
+ In the action editor's step picker, the space's own functions are listed under **Functions**, apart from the
98
+ platform's **Tasks**. The other headings now read Callbacks, Global callbacks and Utilities. The saved step is still a
99
+ `task` node.
100
+
101
+ - `@plitzi/sdk-server`: every registered task has an `origin`, `'deployment'` (shipped with the server or a native
102
+ function) or `'space'` (from the space's functions). `describeCatalog`, `/_action/catalog` and the builder's
103
+ `SpaceActionTasks` carry it (`ActionTaskDescriptor.origin`).
104
+ - `@plitzi/sdk-shared`: an `InteractionCallback` may name the `group` the picker lists it under.
105
+
106
+ ## Fixed: preview no longer breaks a builder that is embedded in a page
107
+
108
+ When the builder is mounted inside a Plitzi page (the platform's `/spaces/:id/update`), going to preview with a page
109
+ that has SEO turned on left the builder unstyled. The previewed page wrote its title and description through a head
110
+ manager of the builder's own, and that manager rewrote the host page's head, removing the builder's own stylesheet.
111
+
112
+ - `@plitzi/sdk-shared`: a new render setting, `ownsHead`, says whether the page may write the document head. It is on
113
+ by default (`DEFAULT_RENDER_SETTINGS`).
114
+ - `@plitzi/sdk-elements`: `Page` writes its SEO only where `ownsHead` is on.
115
+ - Builder: sets `ownsHead: false` for its canvas. A page drawn there is in a frame, and the document head is the
116
+ editor's. The canvas's own `HelmetProvider` is gone.
117
+
118
+ ## Fixed: the builder's plan usage panel shows the space being edited
119
+ - **The 404 is gone.** Opening Plan usage said "The account breakdown could not be read (The server answered 404.)".
120
+ The panel asked `/account/usage`, which went away when accounts became workspaces.
121
+ - **Only this space.** The panel listed every space of the workspace. It now reads `/spaces/:spaceId/usage`, which
122
+ now also answers the space's own `pages` (the heaviest ten), `pagesTotal` and `periodEndsAt`. The plan's ceilings
123
+ stay on top. Anyone who can edit the space can read it, including a guest of another workspace.
124
+ - **It scrolls.** A long breakdown scrolls inside the modal, where it used to overflow.
125
+ - **`getKeyDecoded(webKey, true)` reads the token's subject.** The function, in `@plitzi/sdk-shared`, looked for
126
+ `data.spaceId`, which space tokens no longer carry, so every space decoded as 0. The builder asked about space 0, and
127
+ the builder and the SDK kept every space's persisted state under the same key on a host. Pages served without a
128
+ `webKey` (SSR) still decode as 0, which is what their painted-state cookie is named after.
129
+
130
+ ## Fixed: a remote plugin in the builder reads the canvas it sits in
131
+
132
+ The builder carries its own copy of the Plitzi runtime. A remote plugin imports `@plitzi/plitzi-sdk`, which the page's
133
+ import map resolves to the SDK's copy. Each copy made its own React contexts, so on the builder's canvas a plugin read
134
+ none of the canvas's providers. In the builder embedded in Plitzi's site, it read the site around the builder instead:
135
+ the site's element as its own, the site's live mode (so it stayed interactive while being edited), and the site's store
136
+ and interactions.
137
+
138
+ - `@plitzi/sdk-shared` gains `sharedContext(name, default)`: a context made once per page and handed to every copy of
139
+ the runtime that asks for it.
140
+ - The runtime's contexts now go through it, so a provider from any copy reaches a consumer from any copy:
141
+ - `@plitzi/sdk-shared`: service, component, schema, network, theme scope, dev tools, builder.
142
+ - `@plitzi/sdk-elements`: element, element parent, layout body.
143
+ - interactions, plugins, event bridge, auth, variables and style.
144
+ - The store's contexts need `@plitzi/nexus` 1.4.0, which does the same. Every `@plitzi/*` package now asks for
145
+ `^1.4.0`, which is published.
146
+
147
+ ## The source of plugins and runtimes is kept on the space
148
+
149
+ What a plugin or a runtime is built from now goes up with it, so a space can be taken back out as a project
150
+ (`plitzi create --from`, below).
151
+
152
+ - `@plitzi/cli`:
153
+ - `plitzi pack plugin` writes the plugin's source beside its zip: every file of the project its elements import,
154
+ `import type` included, and the packages they need. `--source-root` names the project those paths are relative to.
155
+ - `plitzi upload plugin` and `plitzi runtime push` keep that source on the space, in its private bucket.
156
+ - `plitzi pack source` writes it to a file.
157
+ - A source that cannot be kept (a file outside the project, an undeclared package, a credential in the code) never
158
+ stops the upload or the push: they say why, and the artifact is kept built only.
159
+ - `@plitzi/sdk-shared/source`: the snapshot's format, the paths it may hold and the credential check, shared by the CLI
160
+ and the platform.
161
+
162
+ ## `plitzi create --from` and `plitzi pull`: a space on Plitzi as a project of your own
163
+
164
+ The way back from everything the CLI puts on Plitzi. `plitzi create my-board --from pizarra` writes a server project
165
+ holding what the space is made of, and runs it with nothing of Plitzi's: neither its servers nor its CDN. `plitzi pull`
166
+ keeps it in step with the space. See `docs/en/projects-from-spaces.md`.
167
+
168
+ - **What lands in the project:**
169
+ - its pages as authoring code;
170
+ - its server actions as `defineAction` code — JSON, with the reason said, for one that would not read back exactly;
171
+ - its plugins and runtime as the source they were uploaded from, and its functions;
172
+ - its files, downloaded into `public/`, with every CDN address rewritten to the project's.
173
+ - **`src/main.ts`** serves all of it, the runtime in the same process.
174
+ - **`.env`** gets a key made for the project's actions to sign with, and the names of the variables and credentials
175
+ the space had. Their values stay on Plitzi.
176
+ - **Who may run it:** the person must be signed in and able to change the space (owner, administrator or writer).
177
+ - **Plugins** are rebuilt against the project's SDK. One uploaded before sources were kept runs as it was built, from
178
+ `vendor/plugins/`, and the report says to upload it again.
179
+ - **The end of `create`** says what came across differently, including a space whose visitors sign in with Plitzi.
180
+ - `--source cloud` keeps the pages on Plitzi and runs the rest locally.
181
+ - **Any version:** `--environment` and `--revision` take out a published snapshot — its latest, or one revision pinned
182
+ — instead of the draft, with the source its plugins and runtime were built from then. A cloud project serves that
183
+ revision pinned.
184
+ - **`plitzi pull`** writes what changed on the space, keeps what changed in the project, and writes nothing when a
185
+ file changed on both — naming them, with `--force` to take the space's copy. It never touches `.env`, only adds to
186
+ `package.json`, and keeps `plitzi functions push` working from the project. It follows the version the project was
187
+ made from, and `--environment`/`--revision` move it.
188
+ - `@plitzi/sdk-authoring`:
189
+ - `actionSpecFromEntry` reads an action document back into its `defineAction` declaration, only when the round trip
190
+ is exact, and `actionToSource` writes it as a module.
191
+ - `defineAction` takes `limits`.
192
+ - `specToSource` takes `importExtension: '.ts'`, for split files that Node imports as they are.
193
+
194
+ ## The builder shows what a snapshot holds
195
+
196
+ **Make Snapshot** lists what it will freeze — pages, layouts and elements, server actions, connectors, functions, the
197
+ runtime and the plugins, each with whether its source is kept — and what no snapshot freezes: the space's files, its
198
+ variables and credentials. A space's components are part of its document, so they are frozen with its pages. **Publish Snapshot** lists what the chosen environment's snapshot holds.
199
+
200
+ ## Fixed: a space read from Plitzi kept its server elements
201
+ - **What happened:** a page server reading its space from Plitzi (`createCloudAdapters`) never ran an element's
202
+ `render` action, and a browser-rendered space ignored `loadStrategy`. The space's GraphQL answered neither
203
+ `runtime` nor `loadStrategy` of an element, nor the space's `rsc` settings.
204
+ - **Now:** the platform answers them, and the SDK, the builder and the cloud adapters ask for them.
205
+
206
+ ## A plugin the deployment registers is not looked for elsewhere
207
+
208
+ `@plitzi/sdk-server` used to fetch the manifest of every plugin the space lists on its CDN, even one the deployment
209
+ registers itself, and logged a warning when the CDN was out of reach. It now asks only for the ones it does not have.
210
+
211
+ ## Fixed: inline code in Markdown carries nothing of the syntax tree
212
+
213
+ A `markdown` element wrote every inline `` `code` `` as `<code node="[object Object]">`: `react-markdown` hands its
214
+ renderers the syntax-tree node as a prop, and the inline branch spread it onto the tag. Fixed in
215
+ `@plitzi/plitzi-ui` 1.6.26 (with a test), which every package now asks for.
216
+
217
+ ## Dev tools hear about the render run the page stopped waiting for
218
+
219
+ When a server element's action ran past the section's budget, the page was answered without it. The run ended a moment
220
+ later, after the page's runs had been sent, so the dev tools never showed the one run that needed debugging. It is now
221
+ told the moment the page stops waiting, as `aborted`, with the reason.
222
+
223
+ ## Fixed: a tab you come back to no longer loses its session
224
+ - **What happened:** a page left in another tab past its access token's life signed its visitor out on return. A
225
+ reload put them right back in.
226
+ - **Why:** the browser drops the cookie carrying the access token the moment the token expires, and the background
227
+ tab's renewal timer had not run. The first check on return was told `missing`, which the client took as no
228
+ session at all.
229
+ - **Now:** a `missing` refusal is renewed instead whenever the browser can still renew, meaning it holds a refresh
230
+ token or a session hint whose renewal window is open. The session ends only if that renewal fails.
231
+ - **Requests made in that moment:** `reportAuthFailure` now answers whether it renewed the session. A read refused
232
+ as the tab came back is asked again, once, once the session is renewed. This covers an api container's read and a
233
+ server section's refresh, so they no longer show a 401 that only a reload cleared.
234
+
235
+ - Updated dependencies [3ae61a4]
236
+ - @plitzi/sdk-shared@0.37.9
237
+ - @plitzi/plitzi-sdk@0.37.9
238
+
3
239
  ## 0.37.8
4
240
 
5
241
  ### Patch Changes
package/README.md CHANGED
@@ -155,6 +155,11 @@ adapters: createJsonAdapters({ offlineData: './space.json' })
155
155
  `validateSpace({ schema, style })` from `@plitzi/sdk-authoring` answers whether one is servable before you
156
156
  serve it — worth running over anything that arrives as a file.
157
157
 
158
+ A space on Plitzi comes out whole, as a project wired to this server: `npx @plitzi/cli create my-site --from <space>`
159
+ writes its pages as authoring code, its actions as `defineAction` code, its functions, the source of its plugins and
160
+ runtime, and its files into `public/` — a draft, or any published snapshot (`--environment`, `--revision`) — and
161
+ `plitzi pull` keeps it in step. See `docs/en/projects-from-spaces.md` in the workspace.
162
+
158
163
  ## Configuration
159
164
 
160
165
  | Option | Type | Default | Description |
@@ -171,7 +176,7 @@ serve it — worth running over anything that arrives as a file.
171
176
  | `plugins` | `Record<string, PluginSource>` | — | Named plugin definitions. Compiled or copied on first use and cached for `pluginsTtlMs`. |
172
177
  | `pluginsCacheDir` | `string` | `.sdk-plugins` | Directory where compiled plugin files are stored. |
173
178
  | `pluginsTtlMs` | `number` | `604800000` | TTL in milliseconds for compiled plugins (default: 1 week). |
174
- | `autoLoadSchemaPlugins` | `boolean` | `true` | Auto-download and cache plugins declared in the schema's `offlineData.plugins` list. Set to `false` to manage plugin loading manually. |
179
+ | `autoLoadSchemaPlugins` | `boolean` | `true` | Auto-download and cache plugins declared in the schema's `offlineData.plugins` list. A type the deployment registers itself (`plugins`, named in `pluginNames`) is never looked for there: its own build is the one rendered. Set to `false` to manage plugin loading manually. |
175
180
  | `allowPrivatePluginHosts` | `boolean` | `false` | Read a schema plugin from a private address (`localhost`, this server's own network). A plugin's address is typed by whoever edits a space, so leave it off anywhere but a development machine whose bucket is local. |
176
181
  | `publicDir` | `string` | — | Absolute path to a directory served at the root URL level (e.g. `robots.txt`, `favicon.png`). Files are checked before `static` prefix routes. |
177
182
  | `static` | `Record<string, string>` | — | URL prefix → filesystem path mappings for static file serving. |
@@ -213,7 +218,7 @@ type SSRAdapters = {
213
218
  };
214
219
  ```
215
220
 
216
- - **`getOfflineData`** — returns the space snapshot (schema, plugins, styles, segments, collections) for SSR.
221
+ - **`getOfflineData`** — returns the space snapshot (schema, plugins, styles, collections) for SSR.
217
222
  - **`getSpaceDeployment`** — resolves which space and environment to render for a given inbound request. Return `{ error: { code, message } }` to abort with an HTTP error. Optionally include `templateProps` to override template variables, or `pluginNames` to activate plugins for the space (see [Plugins](#plugins) and [Template props](#template-props)).
218
223
  - **`getUser`** *(optional)* — resolves the authenticated user from the inbound request (e.g. via a session cookie or `Authorization` header). Called in parallel with `getOfflineData` on every cache miss. Return `undefined` for unauthenticated requests. What it returns is inlined into the page — `authenticated`, `user.details`, the access token and its expiry — and that does two things: it decides page-level access for guest vs. registered users during the render, and it **saves the browser its first auth request**. The SDK adopts the inlined session on boot, stores it and schedules the renewal, rather than asking the same authority the same question a few milliseconds later. Implement this one adapter and every server-rendered page starts signed in with no round trip; `createAuth` answers it for you.
219
224
  - **`authenticate`** *(optional)* — called when `POST {loginPath}` is received, with the credentials already parsed from the body (a posted form or JSON), whatever fields they are. Return a session to grant one, `undefined` to refuse — and never throw for a wrong password. **Identity only**: the cookies, their lifetimes and the readable hint are the server's, which is what keeps a session established here visible to the API side and the other way round. For a navigation (full-page form submit, `Sec-Fetch-Mode: navigate`) the server answers a `303` so the view re-renders via a GET; for a fetch it answers `200` with `{ success, access_token, expire_at }` or `401` with `{ error, reason }` — never a bodyless status, which leaves a caller holding nothing. This route knows a session and not the account behind it; `createServer({ auth })` serves the same path from the auth kernel instead, which answers the full grant.
package/dist/actions.d.ts CHANGED
@@ -68,7 +68,7 @@ export type { KvListEntry, KvListPut, KvListPutOptions, KvListRange } from './mo
68
68
  */
69
69
  export { createRunLogger, createRejectLogger } from './modules/actions/runtime/runLogger';
70
70
  export type { TaskRegistryOptions } from './modules/actions/tasks/registry';
71
- export type { ActionCredential, ActionDbDriver, ActionEmailConfig, ActionEmailDelivery, ActionEmailMessage, ActionEmailTransport, ActionJobsConfig, ActionKvAdapter, ActionKvStore, ActionLookups, ActionRejectRecord, ActionRunRecord, ActionRunRequest, ActionRunResult, ActionsConfig, ActionTask, ActionTaskContext, ActionTaskRegistry, RegisteredTask, ResolvedConnector } from './modules/actions/types';
71
+ export type { ActionCredential, ActionDbDriver, ActionEmailConfig, ActionEmailDelivery, ActionEmailMessage, ActionEmailTransport, ActionJobsConfig, ActionKvAdapter, ActionKvStore, ActionLookups, ActionRejectRecord, ActionRunRecord, ActionRunRequest, ActionRunResult, ActionsConfig, ActionTask, ActionTaskContext, ActionTaskOrigin, ActionTaskRegistry, RegisteredTask, ResolvedConnector } from './modules/actions/types';
72
72
  export type { ActionsModule } from './modules/actions';
73
73
  export type { ActionJobs, JobWorker, JobWorkerOptions, MemoryJobQueueOptions, Scheduler, SchedulerOptions, SweepResult } from './modules/actions/jobs';
74
74
  export type { ActiveRun, RunGuards } from './modules/actions/runtime/guards';
@@ -27,22 +27,13 @@ var SPACE_QUERY = `query InitQuery($environment: String!, $revision: Int) {
27
27
  Space(environment: $environment, revision: $revision) {
28
28
  schema {
29
29
  settings
30
- flat { id definition { label type initialState styleSelectors bindings interactions parentId rootId items } attributes }
30
+ rsc
31
+ flat { id definition { label type initialState styleSelectors bindings interactions parentId rootId items runtime loadStrategy } attributes }
31
32
  pages
33
+ components
32
34
  pageFolders { id name slug parentId }
33
35
  variables { name type value subValues { when value } }
34
36
  }
35
- segments {
36
- id
37
- identifier
38
- definition
39
- schema {
40
- settings
41
- variables { name type value subValues { value when } }
42
- flat { id definition { label type initialState styleSelectors bindings interactions parentId rootId items } attributes }
43
- }
44
- style { cache }
45
- }
46
37
  plugins { type resource settings }
47
38
  style { variables cache }
48
39
  }
@@ -80,22 +71,6 @@ var toSchema = (schema) => ({
80
71
  flat: byElementId(schema.flat)
81
72
  });
82
73
  /**
83
- * Segments arrive as a list and are read by identifier, which is how every other reader of a space holds them. Each
84
- * one carries a schema of its own, so its `flat` needs the same keying the space's does.
85
- */
86
- var byIdentifier = (segments) => (segments ?? []).reduce((acum, segment) => {
87
- const entry = segment;
88
- const identifier = entry.identifier;
89
- if (!identifier || identifier in acum) return acum;
90
- return {
91
- ...acum,
92
- [identifier]: {
93
- ...entry,
94
- ...entry.schema && { schema: toSchema(entry.schema) }
95
- }
96
- };
97
- }, {});
98
- /**
99
74
  * The `scope` claim, read without verifying anything.
100
75
  *
101
76
  * Verification is the server's and this cannot do it — there is no signing key here, and a key this deployment does
@@ -174,8 +149,7 @@ var createCloudAdapters = (config) => {
174
149
  return {
175
150
  schema: toSchema(space.schema),
176
151
  style: space.style,
177
- plugins: space.plugins,
178
- segments: byIdentifier(space.segments)
152
+ plugins: space.plugins
179
153
  };
180
154
  };
181
155
  const fetchLatestRevision = async (env) => {
@@ -1,8 +1,8 @@
1
1
  import { SSRContext, Stage } from '../http/types';
2
2
  /**
3
- * The space's functions answering HTTP under `/api/`: a request there that a declared route answers is run
3
+ * The space's functions answering HTTP under `/fn/`: a request there that a declared route answers is run
4
4
  * by it — the deployment's own routes first, then the space's, in the sandbox — and anything else goes on to the page
5
- * server, which answers as it would have. `/api` is never a page: its slug is refused, so the path is the functions'.
5
+ * server, which answers as it would have. `/fn` is never a page: its slug is refused, so the path is the functions'.
6
6
  *
7
7
  * After the auth chain, so `ctx.user` is who the session says; the session itself never reaches the code.
8
8
  */
@@ -2,9 +2,9 @@ import { clientIp, readRawBytes, requestOrigin } from "../requestParser.js";
2
2
  import { FUNCTION_ROUTES_PREFIX } from "@plitzi/sdk-shared/actions";
3
3
  //#region src/core/services/functionRoutes.ts
4
4
  /**
5
- * The space's functions answering HTTP under `/api/`: a request there that a declared route answers is run
5
+ * The space's functions answering HTTP under `/fn/`: a request there that a declared route answers is run
6
6
  * by it — the deployment's own routes first, then the space's, in the sandbox — and anything else goes on to the page
7
- * server, which answers as it would have. `/api` is never a page: its slug is refused, so the path is the functions'.
7
+ * server, which answers as it would have. `/fn` is never a page: its slug is refused, so the path is the functions'.
8
8
  *
9
9
  * After the auth chain, so `ctx.user` is who the session says; the session itself never reaches the code.
10
10
  */
@@ -118,7 +118,7 @@ export declare type FunctionFetchInit = {
118
118
  };
119
119
 
120
120
  /**
121
- * An HTTP endpoint of the space, under `/api/`: a web-standard handler, the shape every edge runtime runs. The request
121
+ * An HTTP endpoint of the space, under `/fn/`: a web-standard handler, the shape every edge runtime runs. The request
122
122
  * carries no credentials — `ctx.user` says who is asking — and the response sets no cookies: the host's are the
123
123
  * platform's.
124
124
  */
@@ -136,8 +136,10 @@ export declare type FunctionsDefinition = {
136
136
  hosts?: string[];
137
137
  };
138
138
  tasks?: FunctionTask<never>[];
139
- /** `'GET /board-assets/:board/:asset'` → a handler, served at `/api/board-assets/…`. */
139
+ /** `'GET /board-assets/:board/:asset'` → a handler, served at `/fn/board-assets/…`. */
140
140
  routes?: Record<string, FunctionRoute>;
141
+ /** More CPU or time than an invocation gets by default, for every task and route — a task may ask for its own. */
142
+ limits?: FunctionTimeLimits;
141
143
  };
142
144
 
143
145
  /**
@@ -151,9 +153,28 @@ export declare type FunctionTask<T extends Record<string, unknown> = Record<stri
151
153
  title: string;
152
154
  description?: string;
153
155
  params: Record<keyof T, InteractionCallbackParam<T>>;
156
+ /**
157
+ * More CPU or time than an invocation gets by default — `{ cpuMs: 1000 }` for a task that reshapes a big feed — up to
158
+ * what the server allows. Over the functions' own `limits`, for this task.
159
+ */
160
+ limits?: FunctionTimeLimits;
154
161
  run: (params: T, ctx: FunctionContext) => unknown;
155
162
  };
156
163
 
164
+ /**
165
+ * A space's own functions, as everything outside the runner sees them: the builder, the CLI, the MCP and the
166
+ * platform that stores them. The contract the code itself is written against is `@plitzi/sdk-server/functions`.
167
+ */
168
+ /**
169
+ * What a task — or every task and route, declared once for all of them — asks to be given beyond an invocation's
170
+ * default: CPU time, awaits not counted, and wall time, from the moment it starts. Never more than the server allows;
171
+ * asking for more is a problem when the functions are saved.
172
+ */
173
+ declare type FunctionTimeLimits = {
174
+ cpuMs?: number;
175
+ wallMs?: number;
176
+ };
177
+
157
178
  /**
158
179
  * Who started the run, as a space's own code may know them: everything a function decides by — who, their roles and
159
180
  * permissions — and never their session. A token inside the sandbox is a token a function could send anywhere.
@@ -6,7 +6,7 @@
6
6
  export { ActionRefusal, defineFunctions } from './modules/functions/contract';
7
7
  export type { FunctionContext, FunctionFetch, FunctionFetchInit, FunctionRoute, FunctionRouteContext, FunctionsDefinition, FunctionTask, FunctionUser } from './modules/functions/contract';
8
8
  export type { FunctionsConfig, FunctionUsageRecord } from './modules/functions/config';
9
- export { DEFAULT_FUNCTION_LIMITS } from './modules/functions/config';
9
+ export { DEFAULT_FUNCTION_CEILINGS, DEFAULT_FUNCTION_LIMITS } from './modules/functions/config';
10
10
  /**
11
11
  * What the platform keeps of a space's functions, and what it hands a runner: the built bundle and what it declared
12
12
  * when it was saved (`prepareFunctions` on the actions module is the one way to make one).
package/dist/functions.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ActionRefusal } from "./modules/actions/runtime/errors.js";
2
- import { DEFAULT_FUNCTION_LIMITS } from "./modules/functions/config.js";
2
+ import { DEFAULT_FUNCTION_CEILINGS, DEFAULT_FUNCTION_LIMITS } from "./modules/functions/config.js";
3
3
  import { defineFunctions } from "./modules/functions/contract.js";
4
4
  import { TRY_STEP, functionTryEntry } from "./modules/functions/tryEntry.js";
5
- export { ActionRefusal, DEFAULT_FUNCTION_LIMITS, TRY_STEP, defineFunctions, functionTryEntry };
5
+ export { ActionRefusal, DEFAULT_FUNCTION_CEILINGS, DEFAULT_FUNCTION_LIMITS, TRY_STEP, defineFunctions, functionTryEntry };
@@ -66,4 +66,4 @@ export type { ActionJobs, JobWorker, JobWorkerOptions, Scheduler, SchedulerOptio
66
66
  export type { ActiveRun, RunGuards } from './runtime/guards';
67
67
  export type { ActionTaskDescriptor } from './taskCatalog';
68
68
  export type { TaskRegistryOptions } from './tasks/registry';
69
- export type { ActionCredential, ActionDbDriver, ActionEmailConfig, ActionEmailDelivery, ActionEmailMessage, ActionEmailTransport, ActionJobsConfig, ActionKvStore, ActionLookups, ActionRejectRecord, ActionRunRecord, ActionRunRequest, ActionRunResult, ActionsConfig, ActionTask, ActionTaskContext, ActionTaskRegistry, RegisteredTask, ResolvedConnector } from './types';
69
+ export type { ActionCredential, ActionDbDriver, ActionEmailConfig, ActionEmailDelivery, ActionEmailMessage, ActionEmailTransport, ActionJobsConfig, ActionKvStore, ActionLookups, ActionRejectRecord, ActionRunRecord, ActionRunRequest, ActionRunResult, ActionsConfig, ActionTask, ActionTaskContext, ActionTaskOrigin, ActionTaskRegistry, RegisteredTask, ResolvedConnector } from './types';
@@ -12,6 +12,7 @@ import { namespaceKv, spaceKvPatterns } from "./runtime/namespaceKv.js";
12
12
  import "./runtime/precheck.js";
13
13
  import { createActionRunner } from "./runtime/runAction.js";
14
14
  import { createTaskRegistry } from "./tasks/registry.js";
15
+ import { functionCeilings } from "../functions/config.js";
15
16
  import { readManifest } from "../functions/manifest.js";
16
17
  import { createRoutes } from "../functions/routes.js";
17
18
  import { createSpaceRegistries, prepareFunctions } from "../functions/space.js";
@@ -72,12 +73,12 @@ var createActionsModule = (given) => {
72
73
  routeFor: routes.routeFor,
73
74
  prepareFunctions: (source) => {
74
75
  const runner = config.functions?.runner;
75
- return runner ? prepareFunctions(source, runner, reserved) : Promise.resolve({
76
+ return runner ? prepareFunctions(source, runner, reserved, functionCeilings(config.functions?.limits)) : Promise.resolve({
76
77
  ok: false,
77
78
  problems: [{ message: "This server runs no space functions" }]
78
79
  });
79
80
  },
80
- readManifest: (declared) => readManifest(declared, reserved),
81
+ readManifest: (declared) => readManifest(declared, reserved, functionCeilings(config.functions?.limits)),
81
82
  guards,
82
83
  kv: (spaceId) => namespaceKv(kv, spaceId),
83
84
  limitsFor
@@ -72,6 +72,7 @@ var createActionResolver = (lookups, module) => {
72
72
  values
73
73
  ]);
74
74
  const callerId = user ? `user:${user.id}` : "render";
75
+ let ownRunId;
75
76
  const startRun = async () => {
76
77
  /**
77
78
  * A key of its own per render, so two visitors are never each other's duplicate.
@@ -90,6 +91,7 @@ var createActionResolver = (lookups, module) => {
90
91
  kind: "render",
91
92
  ttlMs: module.limitsFor(entry.document).timeoutMs
92
93
  });
94
+ ownRunId = run.runId;
93
95
  /**
94
96
  * The render giving up ends the run, not just the wait for it.
95
97
  *
@@ -157,13 +159,35 @@ var createActionResolver = (lookups, module) => {
157
159
  await module.guards.end(run);
158
160
  }
159
161
  };
162
+ let told = false;
160
163
  const record = (summary) => {
161
- (req.ctx.actionRuns ??= []).push({
162
- ...summary,
163
- elementId: element.id
164
- });
164
+ if (!told) {
165
+ told = true;
166
+ (req.ctx.actionRuns ??= []).push({
167
+ ...summary,
168
+ elementId: element.id
169
+ });
170
+ }
165
171
  };
166
172
  /**
173
+ * The page stopped waiting — the section's budget ran out — and is answered without it: said NOW, while the page
174
+ * still has the request's runs to send. The run itself ends a moment later, aborted, when the page has gone; told
175
+ * then, a debugger would never hear of the one run it needed to — the slow one.
176
+ */
177
+ const askedAt = Date.now();
178
+ const stopWaiting = onAbort(signal, () => {
179
+ record({
180
+ actionId: entry.id,
181
+ runId: ownRunId ?? `render:${randomUUID()}`,
182
+ trigger: "render",
183
+ status: "aborted",
184
+ startedAt: askedAt,
185
+ endedAt: Date.now(),
186
+ steps: [],
187
+ error: "Still running when the page stopped waiting for it: it took longer than a section is given"
188
+ });
189
+ });
190
+ /**
167
191
  * Everyone asking the same question at once gets one run, and its answer.
168
192
  *
169
193
  * Not an optimisation — it is what makes a page survive being read. Without it, a thousand visitors of one URL
@@ -177,6 +201,8 @@ var createActionResolver = (lookups, module) => {
177
201
  } catch (error) {
178
202
  if (error instanceof RenderRunFailure) record(error.summary);
179
203
  throw error;
204
+ } finally {
205
+ stopWaiting();
180
206
  }
181
207
  };
182
208
  };
@@ -1,4 +1,4 @@
1
- import { ActionTaskRegistry, RegisteredTask } from './types';
1
+ import { ActionTaskOrigin, ActionTaskRegistry, RegisteredTask } from './types';
2
2
  /**
3
3
  * A task as an editor renders it.
4
4
  *
@@ -18,6 +18,8 @@ export type ActionTaskDescriptor = {
18
18
  action: string;
19
19
  title: string;
20
20
  description?: string;
21
+ /** The deployment's step, or one of the space's own functions. */
22
+ origin: ActionTaskOrigin;
21
23
  /** Serializable params only — see above. */
22
24
  params: Record<string, unknown>;
23
25
  };
@@ -16,6 +16,7 @@ var describeTask = (task) => ({
16
16
  action: task.action,
17
17
  title: task.title,
18
18
  description: task.description,
19
+ origin: task.origin,
19
20
  params: jsonSafe(task.params)
20
21
  });
21
22
  /** The whole catalog, in the order the registry holds it. */
@@ -26,7 +26,8 @@ var createTaskRegistry = (functions = [], { db = false } = {}) => {
26
26
  const tasks = /* @__PURE__ */ new Map();
27
27
  (db ? [...builtinTasks, ...dbTasks] : builtinTasks).forEach((task) => tasks.set(taskName(task), {
28
28
  ...task,
29
- name: taskName(task)
29
+ name: taskName(task),
30
+ origin: "deployment"
30
31
  }));
31
32
  nativeTasks(functions).forEach((task) => {
32
33
  const problem = taskNameProblem(task);
@@ -35,7 +36,8 @@ var createTaskRegistry = (functions = [], { db = false } = {}) => {
35
36
  if (tasks.has(name)) throw new Error(`[Actions] Task "${name}" is registered twice`);
36
37
  tasks.set(name, {
37
38
  ...task,
38
- name
39
+ name,
40
+ origin: "deployment"
39
41
  });
40
42
  });
41
43
  return {
@@ -219,8 +219,14 @@ export type ActionTask<T extends Record<string, unknown> = Record<string, unknow
219
219
  run: (params: T, ctx: ActionTaskContext) => unknown;
220
220
  };
221
221
  /** A task with its addressable name resolved, as the registry stores and lists it. */
222
+ /**
223
+ * Whose task it is: the deployment's — shipped with the server, or its own native functions — or the space's, from the
224
+ * functions it saved. The run treats both alike; an editor lists them apart, as the platform's steps and the space's own.
225
+ */
226
+ export type ActionTaskOrigin = 'deployment' | 'space';
222
227
  export type RegisteredTask = ActionTask<Record<string, unknown>> & {
223
228
  name: string;
229
+ origin: ActionTaskOrigin;
224
230
  };
225
231
  export type ActionTaskRegistry = {
226
232
  get: (name: string) => RegisteredTask | undefined;
@@ -1,5 +1,6 @@
1
1
  import { FunctionsDefinition } from './contract';
2
2
  import { FunctionLimits, FunctionRunner, FunctionUsage } from './protocol';
3
+ import { FunctionTimeLimits } from '@plitzi/sdk-shared';
3
4
  /** One invocation of a space's task, as metering sees it. */
4
5
  export type FunctionUsageRecord = {
5
6
  spaceId: number;
@@ -19,7 +20,11 @@ export type FunctionsConfig = {
19
20
  * functions here — their tasks are not offered and none of their code runs.
20
21
  */
21
22
  runner?: FunctionRunner;
22
- /** The most one invocation may spend on this deployment. A space's plan may ask for less, never more. */
23
+ /**
24
+ * The most one invocation may spend on this deployment ({@link DEFAULT_FUNCTION_CEILINGS} for each unset): what a
25
+ * task may ask for in CPU and time, and what every invocation gets of the rest. A space's plan may allow less, never
26
+ * more.
27
+ */
23
28
  limits?: Partial<FunctionLimits>;
24
29
  /**
25
30
  * Asked before each invocation: why this space may not run code right now — its account spent its CPU for the minute,
@@ -29,6 +34,17 @@ export type FunctionsConfig = {
29
34
  /** Told what each invocation spent, however it ended: what `admit` budgets by, and what a deployment meters. */
30
35
  onUsage?: (record: FunctionUsageRecord) => void;
31
36
  };
37
+ /** What an invocation gets unless its task asks for more CPU or time. */
32
38
  export declare const DEFAULT_FUNCTION_LIMITS: FunctionLimits;
33
- /** What one invocation of a space may spend: its own limits, never above the deployment's. */
34
- export declare const functionLimitsFor: (ceilings?: Partial<FunctionLimits>, space?: Partial<FunctionLimits>) => FunctionLimits;
39
+ /**
40
+ * The most a deployment lets one invocation have, unless it says otherwise: two seconds of CPU and half a minute of
41
+ * time for a task that asks; the rest as every invocation gets it.
42
+ */
43
+ export declare const DEFAULT_FUNCTION_CEILINGS: FunctionLimits;
44
+ /** A deployment's ceilings, each unset one the default's. */
45
+ export declare const functionCeilings: (ceilings?: Partial<FunctionLimits>) => FunctionLimits;
46
+ /**
47
+ * What one invocation of a space may spend: the CPU and time its task asked for — the default's when it asked for none
48
+ * — and the rest as the deployment gives it; never above the space's plan, nor above the deployment's ceilings.
49
+ */
50
+ export declare const functionLimitsFor: (ceilings?: Partial<FunctionLimits>, space?: Partial<FunctionLimits>, asked?: FunctionTimeLimits) => FunctionLimits;