@plitzi/sdk-kernel 0.0.0-stage → 0.39.3

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 (142) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +80 -2
  3. package/dist/build/esbuild.d.ts +16 -0
  4. package/dist/build/index.d.ts +1 -0
  5. package/dist/build/index.mjs +35 -0
  6. package/dist/cache/CompressedFileCache.d.ts +18 -0
  7. package/dist/cache/TtlCache.d.ts +65 -0
  8. package/dist/cache/index.d.ts +3 -0
  9. package/dist/cache/index.mjs +1 -0
  10. package/dist/chunks/TtlCache-J_jG9oL9.mjs +200 -0
  11. package/dist/chunks/channel-DnVf7PJB.mjs +190 -0
  12. package/dist/chunks/csrf-BLWcaYOV.mjs +295 -0
  13. package/dist/chunks/link-C9wyDS9H.mjs +124 -0
  14. package/dist/chunks/query-DGbrN3mN.mjs +20 -0
  15. package/dist/chunks/scopes-Co6ZjhAm.mjs +46 -0
  16. package/dist/chunks/serverLog-BKaKjjc4.mjs +137 -0
  17. package/dist/chunks/session-B-dTEjeG.mjs +253 -0
  18. package/dist/chunks/sessionActivity-Ch7xuQ_o.mjs +43 -0
  19. package/dist/chunks/spaceDeployment-J2IMLfij.mjs +76 -0
  20. package/dist/chunks/stage-y6deE9LJ.mjs +345 -0
  21. package/dist/chunks/supervisor-Dh34v1vq.mjs +117 -0
  22. package/dist/chunks/tail-D-USrZIR.mjs +55 -0
  23. package/dist/chunks/tokens-BAV5YeT9.mjs +273 -0
  24. package/dist/data/index.d.ts +2 -0
  25. package/dist/data/index.mjs +68 -0
  26. package/dist/data/projectData.d.ts +21 -0
  27. package/dist/deployment/hostDeployment.d.ts +8 -0
  28. package/dist/deployment/index.d.ts +3 -0
  29. package/dist/deployment/index.mjs +19 -0
  30. package/dist/deployment/spaceDeployment.d.ts +11 -0
  31. package/dist/engine/index.d.ts +2 -0
  32. package/dist/engine/index.mjs +1 -0
  33. package/dist/engine/page.d.ts +49 -0
  34. package/dist/engine/rsc.d.ts +32 -0
  35. package/dist/files/atomicFile.d.ts +10 -0
  36. package/dist/files/index.d.ts +1 -0
  37. package/dist/files/index.mjs +32 -0
  38. package/dist/http/bearer.d.ts +5 -0
  39. package/dist/http/buildResponseHelpers.d.ts +23 -0
  40. package/dist/http/closeOnSignals.d.ts +28 -0
  41. package/dist/http/compress.d.ts +20 -0
  42. package/dist/http/dispatcher.d.ts +15 -0
  43. package/dist/http/drain.d.ts +18 -0
  44. package/dist/http/fleet/channel.d.ts +103 -0
  45. package/dist/http/fleet/link.d.ts +28 -0
  46. package/dist/http/fleet/role.d.ts +46 -0
  47. package/dist/http/fleet/supervisor.d.ts +29 -0
  48. package/dist/http/freePort.d.ts +24 -0
  49. package/dist/http/health.d.ts +21 -0
  50. package/dist/http/index.d.ts +48 -0
  51. package/dist/http/index.mjs +1313 -0
  52. package/dist/http/middlewares/auth.d.ts +2 -0
  53. package/dist/http/middlewares/basicAuth.d.ts +6 -0
  54. package/dist/http/mimeTypes.d.ts +13 -0
  55. package/dist/http/navigation.d.ts +14 -0
  56. package/dist/http/onAbort.d.ts +12 -0
  57. package/dist/http/probes.d.ts +4 -0
  58. package/dist/http/requestParser.d.ts +22 -0
  59. package/dist/http/runMiddlewares.d.ts +6 -0
  60. package/dist/http/securityHeaders.d.ts +18 -0
  61. package/dist/http/server.d.ts +39 -0
  62. package/dist/http/socketResponse.d.ts +18 -0
  63. package/dist/http/sse.d.ts +26 -0
  64. package/dist/http/stages/crossSiteWrites.d.ts +24 -0
  65. package/dist/http/stages/health.d.ts +11 -0
  66. package/dist/http/stages/middlewares.d.ts +3 -0
  67. package/dist/http/stages/static.d.ts +4 -0
  68. package/dist/http/staticFiles.d.ts +3 -0
  69. package/dist/http/stopping.d.ts +11 -0
  70. package/dist/http/transports.d.ts +31 -0
  71. package/dist/http/types.d.ts +29 -0
  72. package/dist/http/unusedPort.d.ts +10 -0
  73. package/dist/http/webExchange.d.ts +18 -0
  74. package/dist/http/wsFrame.d.ts +3 -0
  75. package/dist/identity/accounts.d.ts +278 -0
  76. package/dist/identity/authorize.d.ts +96 -0
  77. package/dist/identity/credentials.d.ts +40 -0
  78. package/dist/identity/csrf.d.ts +139 -0
  79. package/dist/identity/debugAuthorization.d.ts +24 -0
  80. package/dist/identity/domains.d.ts +41 -0
  81. package/dist/identity/identity.d.ts +119 -0
  82. package/dist/identity/index.d.ts +21 -0
  83. package/dist/identity/index.mjs +731 -0
  84. package/dist/identity/passwords.d.ts +15 -0
  85. package/dist/identity/previewToken.d.ts +21 -0
  86. package/dist/identity/requestIdentity.d.ts +14 -0
  87. package/dist/identity/scopes.d.ts +56 -0
  88. package/dist/identity/session.d.ts +185 -0
  89. package/dist/identity/sessionActivity.d.ts +11 -0
  90. package/dist/identity/spaceTokens.d.ts +174 -0
  91. package/dist/index.d.ts +17 -0
  92. package/dist/index.mjs +1 -0
  93. package/dist/log/index.d.ts +3 -0
  94. package/dist/log/index.mjs +3 -0
  95. package/dist/log/serverLog.d.ts +49 -0
  96. package/dist/log/tail.d.ts +43 -0
  97. package/dist/mysql/accounts.d.ts +4 -0
  98. package/dist/mysql/admin.d.ts +58 -0
  99. package/dist/mysql/config.d.ts +82 -0
  100. package/dist/mysql/identities.d.ts +35 -0
  101. package/dist/mysql/index.d.ts +7 -0
  102. package/dist/mysql/index.mjs +1203 -0
  103. package/dist/mysql/pool.d.ts +3 -0
  104. package/dist/mysql/query.d.ts +12 -0
  105. package/dist/mysql/schema.d.ts +43 -0
  106. package/dist/mysql/sessions.d.ts +23 -0
  107. package/dist/mysql/spaceTokens.d.ts +11 -0
  108. package/dist/mysql/store.d.ts +66 -0
  109. package/dist/outbound/index.d.ts +4 -0
  110. package/dist/outbound/index.mjs +314 -0
  111. package/dist/outbound/inside.d.ts +36 -0
  112. package/dist/outbound/outboundGuard.d.ts +69 -0
  113. package/dist/pubsub/index.d.ts +3 -0
  114. package/dist/pubsub/index.mjs +76 -0
  115. package/dist/pubsub/memoryPubSub.d.ts +10 -0
  116. package/dist/pubsub/redisPubSub.d.ts +24 -0
  117. package/dist/stats/index.d.ts +9 -0
  118. package/dist/stats/index.mjs +228 -0
  119. package/dist/stats/load.d.ts +31 -0
  120. package/dist/stats/memory.d.ts +20 -0
  121. package/dist/stats/pools.d.ts +15 -0
  122. package/dist/stats/recorder.d.ts +34 -0
  123. package/dist/stats/stage.d.ts +15 -0
  124. package/dist/stats/types.d.ts +309 -0
  125. package/dist/testing/certificates.d.ts +21 -0
  126. package/dist/testing/fleet.d.ts +28 -0
  127. package/dist/testing/goneRuns.d.ts +5 -0
  128. package/dist/testing/index.d.ts +5 -0
  129. package/dist/testing/index.mjs +270 -0
  130. package/dist/testing/keys.d.ts +2 -0
  131. package/dist/testing/runNames.d.ts +10 -0
  132. package/dist/tokens/index.d.ts +2 -0
  133. package/dist/tokens/index.mjs +1 -0
  134. package/dist/tokens/tokens.d.ts +195 -0
  135. package/dist/types/adapters.d.ts +388 -0
  136. package/dist/types/config.d.ts +240 -0
  137. package/dist/types/index.d.ts +5 -0
  138. package/dist/types/index.mjs +1 -0
  139. package/dist/types/log.d.ts +119 -0
  140. package/dist/types/oauth.d.ts +246 -0
  141. package/dist/types/pipeline.d.ts +239 -0
  142. package/package.json +67 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # @plitzi/sdk-kernel
2
+
3
+ ## 0.39.3
4
+
5
+ ### Patch Changes
6
+
7
+ - @plitzi/sdk-shared@0.39.3
8
+
9
+ ## 0.39.2
10
+
11
+ ### Patch Changes
12
+
13
+ - fad1264: Released with every `@plitzi` package at this version. What changed in each, and what to do when you upgrade, is in
14
+ `@plitzi/cli`'s `CHANGELOG.md`: one copy of the notes, not one per package.
15
+ - Updated dependencies [fad1264]
16
+ - @plitzi/sdk-shared@0.39.2
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # @plitzi/sdk-kernel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ What every Plitzi server process is built on, and nothing else: the HTTP server and its request pipeline, health and
4
+ shutdown, the workers of one machine, the host → deployment resolution, and checking who a request is.
5
+
6
+ The page server ([`@plitzi/sdk-server`](../../apps/server/README.md)), the MCP server
7
+ ([`@plitzi/sdk-mcp`](../../apps/mcp/README.md)), the actions worker ([`@plitzi/sdk-actions`](../sdk-actions/README.md))
8
+ and the functions runner ([`@plitzi/sdk-runtime`](../sdk-runtime/README.md)) run on it: a process
9
+ that renders no page installs this and never loads React.
10
+
11
+ ## Entries
12
+
13
+ Each folder is an entry of its own, so a process loads what it imports and nothing beside it.
14
+
15
+ | Entry | What it holds |
16
+ |---|---|
17
+ | `@plitzi/sdk-kernel/http` | `createHttpServer`, `makeHandler` and the stage types; health (`healthStage`, `registerHealthCheck`); `closeOnSignals` and the drain; the fleet of workers; security headers, cross-site writes, static files; `parseRequest` and the other request readers; SSE and WebSocket framing; `unusedPort` for tests |
18
+ | `@plitzi/sdk-kernel/identity` | Who a request is: the session cookies, CSRF, origins and domains, `createIdentity`, the RBAC checks, the scopes a token may carry, the preview token's carrier, the one `RequestIdentity` a page server and a worker take, and the account store's contract (`AccountAdapters`) and password hashing |
19
+ | `@plitzi/sdk-kernel/tokens` | Minting and verifying the tokens themselves (`createTokens`, `generateTokenKeys`). An entry of its own because it loads `jsonwebtoken`: a page server that only reads a session cookie does not |
20
+ | `@plitzi/sdk-kernel/mysql` | The account store over MySQL (`createMysqlStore`): accounts, sessions, linked identities, space tokens, with its schema. Reads sessions for a worker and writes accounts for sign-in, one schema with one owner. `mysql2` is an optional peer |
21
+ | `@plitzi/sdk-kernel/engine` | Types alone: what a page server is handed of the actions engine (`PageEngine`) and the resolver of a page's server element (`RscElementResolver`) |
22
+ | `@plitzi/sdk-kernel/data` | A space's data folder as a lookup (`dataDirLookup`): what a `/data/<file>` provider and a function's `ctx.data` read alike |
23
+ | `@plitzi/sdk-kernel/pubsub` | The pub/sub a cache's invalidations and the realtime channels travel on (`createMemoryPubSub`, `createRedisPubSub`) |
24
+ | `@plitzi/sdk-kernel/files` | Writing a file whole or not at all (`writeFileAtomic`) |
25
+ | `@plitzi/sdk-kernel/deployment` | Which deployment a request's host is: the stage and the middleware, and the adapter they ask |
26
+ | `@plitzi/sdk-kernel/cache` | The bounded caches a server keeps (`TtlCache`, `CompressedFileCache`) |
27
+ | `@plitzi/sdk-kernel/log` | `serverLog`, `consoleLogger` and the log levels |
28
+ | `@plitzi/sdk-kernel/outbound` | Where a request somebody else wrote may go (`assertOutboundAllowed`, `fetchOutbound`), and a process's requests to its own public address sent to where it listens (`reachOwnServer`, `reachSpaceInside`) |
29
+ | `@plitzi/sdk-kernel/build` | `esbuildBuild`: the one way a process builds, so esbuild's child is stopped once nothing builds |
30
+ | `@plitzi/sdk-kernel/stats` | A process's stats and its pools: the recorder (`createStatsRecorder`), `GET /_stats` behind a secret (`statsStage`), `readPools` and `createLocalPoolSource`, and the `PoolScaler` contract |
31
+ | `@plitzi/sdk-kernel/types` | Types alone: the request pipeline (`SSRRequest`, `SSRMiddleware`, `SSRContext`), the adapters a deployment answers (`SSRAdapters`, `SSRPageAdapters`) and what they are asked with, the configuration every server shares (`ServerBaseConfig`), the log's events and OAuth's |
32
+ | `@plitzi/sdk-kernel/testing` | What the packages built on this test with: `TEST_KEYS`, `TEST_CERTIFICATES`, a fleet simulated in one process, the names of an integration run's tables (`runName`, `dropTablesOfThisRun`) |
33
+
34
+ The root carries the types a server is written against (`BaseContext`, `Stage`, `HttpServer`…) and no code.
35
+
36
+ ## A server on the kernel
37
+
38
+ ```ts
39
+ import { createHttpServer, healthStage, makeHandler } from '@plitzi/sdk-kernel/http';
40
+
41
+ import type { BaseContext, BuildContext, Stage } from '@plitzi/sdk-kernel/http';
42
+
43
+ const hello: Stage = ({ res }) => {
44
+ res.send('hello');
45
+
46
+ return true;
47
+ };
48
+
49
+ const config = { httpVersion: 1, adapters: {} } as const;
50
+ const handlerFor = (port: number) => {
51
+ const context: BuildContext<BaseContext> = (raw, rawRes, req, res) => ({ raw, rawRes, req, res, config, port });
52
+
53
+ return makeHandler('HELLO', context, [healthStage, hello]);
54
+ };
55
+
56
+ await createHttpServer(config, handlerFor, { label: 'HELLO' }).listen(8080);
57
+ ```
58
+
59
+ A stage answers the request and returns `true`, or returns `false` to let the next one try. `createHttpServer` is the
60
+ transport and its lifecycle: `listen`, `close`, and a fleet of workers when `workers` asks for one. What a server offers
61
+ beyond that it builds itself.
62
+
63
+ ## Credentials
64
+
65
+ Tokens are signed with ES256. `generateTokenKeys()` makes a key pair once, for the deployment to keep:
66
+
67
+ ```ts
68
+ import { createTokens, generateTokenKeys } from '@plitzi/sdk-kernel/tokens';
69
+
70
+ const keys = generateTokenKeys(); // { signing: { kid, privateKey }, verifying: [{ kid, publicKey }] }
71
+ const tokens = createTokens({ keys, issuer: 'https://acme.com' });
72
+ ```
73
+
74
+ A process that only checks credentials is given `verifying` alone: it cannot mint one, and asked to, it refuses and
75
+ names the missing key. Signing people in — the `/auth` flows, passwords, second factors — is `@plitzi/sdk-server/auth`.
76
+
77
+ ## What it may import
78
+
79
+ From another Plitzi package, types only: a value would load that package into every process built on this one. ESLint
80
+ refuses a value import of `@plitzi/*` here. Its own dependencies are `jsonwebtoken`, `ws` and `undici` (loaded only by `reachOwnServer` and `reachSpaceInside`); `esbuild` is an optional
81
+ peer, needed only by a process that imports `./build`.
@@ -0,0 +1,16 @@
1
+ import { BuildOptions, BuildResult } from 'esbuild';
2
+ /** esbuild's own guard against an option it does not know, which `build` takes its options through. */
3
+ type SameShape<Out, In extends Out> = In & {
4
+ [Key in Exclude<keyof In, keyof Out>]: never;
5
+ };
6
+ /** How long esbuild's process is kept once nothing is building: a burst of builds shares one, a rest frees it. */
7
+ export declare const ESBUILD_REST_MS = 60000;
8
+ /**
9
+ * esbuild's `build`, and the one way this process builds with it. esbuild runs as a child process it starts on the
10
+ * first build and keeps for the life of the parent — 16–26 MiB resident in a page server's pod for builds that happen
11
+ * at boot (its plugins) and seldom after. Every build here counts itself, and the child is stopped once none has run for
12
+ * `ESBUILD_REST_MS`; the next build starts it again (a few milliseconds). Stopping kills whatever the child is doing, so
13
+ * a build that went to esbuild directly would fail with it: the server's builds and `@plitzi/sdk-mcp`'s all come here.
14
+ */
15
+ export declare const esbuildBuild: <T extends BuildOptions>(options: SameShape<BuildOptions, T>) => Promise<BuildResult<T>>;
16
+ export {};
@@ -0,0 +1 @@
1
+ export { ESBUILD_REST_MS, esbuildBuild } from './esbuild';
@@ -0,0 +1,35 @@
1
+ import { c as serverLog } from "../chunks/serverLog-BKaKjjc4.mjs";
2
+ import esbuild from "esbuild";
3
+ // src/build/esbuild.ts
4
+ /** How long esbuild's process is kept once nothing is building: a burst of builds shares one, a rest frees it. */
5
+ var ESBUILD_REST_MS = 6e4;
6
+ var building = 0;
7
+ var rest;
8
+ var stopResting = () => {
9
+ rest = void 0;
10
+ esbuild.stop().catch((error) => {
11
+ serverLog.warn("esbuild", `its process could not be stopped, and stays: ${String(error)}`);
12
+ });
13
+ };
14
+ /**
15
+ * esbuild's `build`, and the one way this process builds with it. esbuild runs as a child process it starts on the
16
+ * first build and keeps for the life of the parent — 16–26 MiB resident in a page server's pod for builds that happen
17
+ * at boot (its plugins) and seldom after. Every build here counts itself, and the child is stopped once none has run for
18
+ * `ESBUILD_REST_MS`; the next build starts it again (a few milliseconds). Stopping kills whatever the child is doing, so
19
+ * a build that went to esbuild directly would fail with it: the server's builds and `@plitzi/sdk-mcp`'s all come here.
20
+ */
21
+ var esbuildBuild = async (options) => {
22
+ building++;
23
+ clearTimeout(rest);
24
+ rest = void 0;
25
+ try {
26
+ return await esbuild.build(options);
27
+ } finally {
28
+ building--;
29
+ if (building === 0) {
30
+ rest = setTimeout(stopResting, ESBUILD_REST_MS);
31
+ rest.unref();
32
+ }
33
+ }
34
+ };
35
+ export { ESBUILD_REST_MS, esbuildBuild };
@@ -0,0 +1,18 @@
1
+ import { CompressedBodies } from '../types';
2
+ /**
3
+ * The compressed forms of static files, one entry per file, within a byte budget.
4
+ *
5
+ * A file is compressed once per version and encoding instead of on every request — the SDK bundle alone is megabytes
6
+ * of JavaScript. Keyed by path with the version beside it, so a file that changed replaces its old forms rather than
7
+ * sitting next to them. Past the budget the least recently served files go first.
8
+ */
9
+ export declare class CompressedFileCache {
10
+ private readonly maxBytes;
11
+ private readonly entries;
12
+ constructor(maxBytes: number);
13
+ /** Where the compressed forms of this version of the file are kept; `send` fills it as encodings are asked for. */
14
+ storeFor(filePath: string, version: string): CompressedBodies;
15
+ /** Drops the least recently served files until the rest fit the budget. Called after a send may have grown one. */
16
+ trim(): void;
17
+ get bytes(): number;
18
+ }
@@ -0,0 +1,65 @@
1
+ export type TtlCacheOptions<T> = {
2
+ /**
3
+ * What the cache holds at most, in bytes as `sizeOf` measures them. Without one, only the entry count bounds it —
4
+ * which is no bound at all on entries of a megabyte each.
5
+ */
6
+ maxBytes?: number;
7
+ sizeOf?: (value: T) => number;
8
+ /** How long past its TTL an entry is still handed out by {@link TtlCache.read}, marked stale. */
9
+ staleMs?: number;
10
+ sweepIntervalMs?: number;
11
+ };
12
+ /** An entry, and whether its TTL has passed — a stale one is still within the window `staleMs` keeps it for. */
13
+ export type CacheRead<T> = {
14
+ value: T;
15
+ stale: boolean;
16
+ storedAt: number;
17
+ };
18
+ /**
19
+ * A map whose entries expire, bounded by count and by bytes — a segmented LRU.
20
+ *
21
+ * An entry starts on probation and is protected once it is used again. When the cache is full, probation gives way
22
+ * first, its least recently used entry first, and only then the protected entry used longest ago; protected entries
23
+ * past their share go back to probation. So what was asked for once — a page of a space barely visited, every URL a
24
+ * crawler made up — never pushes out what is asked for all the time, whichever space it is of: a space that just got
25
+ * busy earns its room from the ones that went quiet, and a burst of one-off pages only displaces itself.
26
+ *
27
+ * Least recently USED, not least recently stored: the first version dropped the oldest entry whatever it was, so the
28
+ * site's home page — stored first and served on every visit — was the one evicted when the cache filled.
29
+ */
30
+ export declare class TtlCache<T> {
31
+ private readonly ttlMs;
32
+ private readonly maxSize;
33
+ private readonly store;
34
+ private readonly lanes;
35
+ private readonly maxBytes;
36
+ private readonly sizeOf;
37
+ private readonly staleMs;
38
+ private sweepTimer;
39
+ constructor(ttlMs: number, maxSize?: number, { maxBytes, sizeOf, staleMs, sweepIntervalMs }?: TtlCacheOptions<T>);
40
+ /** The entry while its TTL lasts. */
41
+ get(key: string): T | undefined;
42
+ /** The entry while its TTL lasts, and after it for `staleMs`, saying which. A read is a use: see the class. */
43
+ read(key: string): CacheRead<T> | undefined;
44
+ /**
45
+ * `storedAt` for an entry that was made before it reached this cache — read from a store several processes share.
46
+ * An entry stored again (rendered again once it expired) keeps the standing it had.
47
+ */
48
+ set(key: string, value: T, storedAt?: number): void;
49
+ delete(key: string): void;
50
+ invalidateWhere(predicate: (key: string) => boolean): number;
51
+ clear(): void;
52
+ destroy(): void;
53
+ get size(): number;
54
+ get bytes(): number;
55
+ /** Whether an entry has been used since it was stored — what keeps it when the cache needs room. */
56
+ isProtected(key: string): boolean;
57
+ /** Moves an entry to the most recently used end of a segment. */
58
+ private place;
59
+ /** Protected entries past their share go back to probation, the one used longest ago first — never `kept`. */
60
+ private keepProtectedToShare;
61
+ /** Drops one entry to make room — probation's least recently used, else the protected one used longest ago. */
62
+ private evictOne;
63
+ private remove;
64
+ private sweep;
65
+ }
@@ -0,0 +1,3 @@
1
+ export { CompressedFileCache } from './CompressedFileCache';
2
+ export { TtlCache } from './TtlCache';
3
+ export type { TtlCacheOptions, CacheRead } from './TtlCache';
@@ -0,0 +1 @@
1
+ export { n as CompressedFileCache, t as TtlCache } from "../chunks/TtlCache-J_jG9oL9.mjs";
@@ -0,0 +1,200 @@
1
+ // src/cache/CompressedFileCache.ts
2
+ var sizeOf = (bodies) => (bodies.br?.length ?? 0) + (bodies.gzip?.length ?? 0);
3
+ /**
4
+ * The compressed forms of static files, one entry per file, within a byte budget.
5
+ *
6
+ * A file is compressed once per version and encoding instead of on every request — the SDK bundle alone is megabytes
7
+ * of JavaScript. Keyed by path with the version beside it, so a file that changed replaces its old forms rather than
8
+ * sitting next to them. Past the budget the least recently served files go first.
9
+ */
10
+ var CompressedFileCache = class {
11
+ maxBytes;
12
+ entries = /* @__PURE__ */ new Map();
13
+ constructor(maxBytes) {
14
+ this.maxBytes = maxBytes;
15
+ }
16
+ /** Where the compressed forms of this version of the file are kept; `send` fills it as encodings are asked for. */
17
+ storeFor(filePath, version) {
18
+ const existing = this.entries.get(filePath);
19
+ this.entries.delete(filePath);
20
+ const entry = existing?.version === version ? existing : {
21
+ version,
22
+ bodies: {}
23
+ };
24
+ this.entries.set(filePath, entry);
25
+ return entry.bodies;
26
+ }
27
+ /** Drops the least recently served files until the rest fit the budget. Called after a send may have grown one. */
28
+ trim() {
29
+ let total = 0;
30
+ for (const entry of this.entries.values()) total += sizeOf(entry.bodies);
31
+ for (const [filePath, entry] of this.entries) {
32
+ if (total <= this.maxBytes) return;
33
+ total -= sizeOf(entry.bodies);
34
+ this.entries.delete(filePath);
35
+ }
36
+ }
37
+ get bytes() {
38
+ let total = 0;
39
+ for (const entry of this.entries.values()) total += sizeOf(entry.bodies);
40
+ return total;
41
+ }
42
+ };
43
+ // src/cache/TtlCache.ts
44
+ /** What of the cache the entries used more than once may hold: the rest is where new ones prove themselves. */
45
+ var PROTECTED_SHARE = .8;
46
+ /**
47
+ * A map whose entries expire, bounded by count and by bytes — a segmented LRU.
48
+ *
49
+ * An entry starts on probation and is protected once it is used again. When the cache is full, probation gives way
50
+ * first, its least recently used entry first, and only then the protected entry used longest ago; protected entries
51
+ * past their share go back to probation. So what was asked for once — a page of a space barely visited, every URL a
52
+ * crawler made up — never pushes out what is asked for all the time, whichever space it is of: a space that just got
53
+ * busy earns its room from the ones that went quiet, and a burst of one-off pages only displaces itself.
54
+ *
55
+ * Least recently USED, not least recently stored: the first version dropped the oldest entry whatever it was, so the
56
+ * site's home page — stored first and served on every visit — was the one evicted when the cache filled.
57
+ */
58
+ var TtlCache = class {
59
+ ttlMs;
60
+ maxSize;
61
+ store = /* @__PURE__ */ new Map();
62
+ lanes = {
63
+ probation: {
64
+ keys: /* @__PURE__ */ new Map(),
65
+ bytes: 0
66
+ },
67
+ protected: {
68
+ keys: /* @__PURE__ */ new Map(),
69
+ bytes: 0
70
+ }
71
+ };
72
+ maxBytes;
73
+ sizeOf;
74
+ staleMs;
75
+ sweepTimer;
76
+ constructor(ttlMs, maxSize = 500, { maxBytes = Infinity, sizeOf, staleMs = 0, sweepIntervalMs = ttlMs } = {}) {
77
+ this.ttlMs = ttlMs;
78
+ this.maxSize = maxSize;
79
+ this.maxBytes = maxBytes;
80
+ this.sizeOf = sizeOf;
81
+ this.staleMs = staleMs;
82
+ this.sweepTimer = setInterval(() => this.sweep(), sweepIntervalMs);
83
+ this.sweepTimer.unref?.();
84
+ }
85
+ /** The entry while its TTL lasts. */
86
+ get(key) {
87
+ const read = this.read(key);
88
+ return read && !read.stale ? read.value : void 0;
89
+ }
90
+ /** The entry while its TTL lasts, and after it for `staleMs`, saying which. A read is a use: see the class. */
91
+ read(key) {
92
+ const entry = this.store.get(key);
93
+ if (!entry) return;
94
+ const age = Date.now() - entry.storedAt;
95
+ if (age > this.ttlMs + this.staleMs) {
96
+ this.remove(key, entry);
97
+ return;
98
+ }
99
+ this.place(key, entry, "protected");
100
+ this.keepProtectedToShare(key);
101
+ return {
102
+ value: entry.value,
103
+ stale: age > this.ttlMs,
104
+ storedAt: entry.storedAt
105
+ };
106
+ }
107
+ /**
108
+ * `storedAt` for an entry that was made before it reached this cache — read from a store several processes share.
109
+ * An entry stored again (rendered again once it expired) keeps the standing it had.
110
+ */
111
+ set(key, value, storedAt = Date.now()) {
112
+ const previous = this.store.get(key);
113
+ if (previous) this.remove(key, previous);
114
+ const bytes = this.sizeOf?.(value) ?? 0;
115
+ if (bytes > this.maxBytes) return;
116
+ const entry = {
117
+ value,
118
+ storedAt,
119
+ bytes,
120
+ segment: previous?.segment ?? "probation"
121
+ };
122
+ this.store.set(key, entry);
123
+ this.place(key, entry, entry.segment);
124
+ this.keepProtectedToShare(key);
125
+ while (this.store.size > this.maxSize || this.bytes > this.maxBytes) if (!this.evictOne(key)) break;
126
+ }
127
+ delete(key) {
128
+ const entry = this.store.get(key);
129
+ if (entry) this.remove(key, entry);
130
+ }
131
+ invalidateWhere(predicate) {
132
+ let count = 0;
133
+ for (const [key, entry] of this.store) if (predicate(key)) {
134
+ this.remove(key, entry);
135
+ count++;
136
+ }
137
+ return count;
138
+ }
139
+ clear() {
140
+ this.store.clear();
141
+ for (const lane of Object.values(this.lanes)) {
142
+ lane.keys.clear();
143
+ lane.bytes = 0;
144
+ }
145
+ }
146
+ destroy() {
147
+ clearInterval(this.sweepTimer);
148
+ this.clear();
149
+ }
150
+ get size() {
151
+ return this.store.size;
152
+ }
153
+ get bytes() {
154
+ return this.lanes.probation.bytes + this.lanes.protected.bytes;
155
+ }
156
+ /** Whether an entry has been used since it was stored — what keeps it when the cache needs room. */
157
+ isProtected(key) {
158
+ return this.store.get(key)?.segment === "protected";
159
+ }
160
+ /** Moves an entry to the most recently used end of a segment. */
161
+ place(key, entry, segment) {
162
+ const from = this.lanes[entry.segment];
163
+ if (from.keys.delete(key)) from.bytes -= entry.bytes;
164
+ entry.segment = segment;
165
+ const to = this.lanes[segment];
166
+ to.keys.set(key, true);
167
+ to.bytes += entry.bytes;
168
+ }
169
+ /** Protected entries past their share go back to probation, the one used longest ago first — never `kept`. */
170
+ keepProtectedToShare(kept) {
171
+ const lane = this.lanes.protected;
172
+ while (lane.keys.size > 1 && (lane.bytes > this.maxBytes * PROTECTED_SHARE || lane.keys.size > this.maxSize * PROTECTED_SHARE)) {
173
+ const [oldest] = lane.keys.keys();
174
+ const entry = this.store.get(oldest);
175
+ if (oldest === kept || !entry) break;
176
+ this.place(oldest, entry, "probation");
177
+ }
178
+ }
179
+ /** Drops one entry to make room — probation's least recently used, else the protected one used longest ago. */
180
+ evictOne(kept) {
181
+ for (const lane of [this.lanes.probation, this.lanes.protected]) for (const key of lane.keys.keys()) {
182
+ const entry = this.store.get(key);
183
+ if (key !== kept && entry) {
184
+ this.remove(key, entry);
185
+ return true;
186
+ }
187
+ }
188
+ return false;
189
+ }
190
+ remove(key, entry) {
191
+ this.store.delete(key);
192
+ const lane = this.lanes[entry.segment];
193
+ if (lane.keys.delete(key)) lane.bytes -= entry.bytes;
194
+ }
195
+ sweep() {
196
+ const oldest = Date.now() - this.ttlMs - this.staleMs;
197
+ for (const [key, entry] of this.store) if (entry.storedAt < oldest) this.remove(key, entry);
198
+ }
199
+ };
200
+ export { CompressedFileCache as n, TtlCache as t };
@@ -0,0 +1,190 @@
1
+ // src/http/fleet/channel.ts
2
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ /** The channel is shared with `node:cluster` and anything else the deployment sends: only these are ours. */
4
+ var isFleetMessage = (value) => {
5
+ if (!isRecord(value)) return false;
6
+ if (value.sdkFleet === "call") return typeof value.id === "number" && typeof value.store === "string" && typeof value.method === "string" && Array.isArray(value.args);
7
+ if (value.sdkFleet === "reply") return typeof value.id === "number" && typeof value.ok === "boolean";
8
+ if (value.sdkFleet === "broadcast") return typeof value.channel === "string";
9
+ return false;
10
+ };
11
+ var hostable = (create, methods) => ({
12
+ create,
13
+ methods: new Set(Object.keys(methods))
14
+ });
15
+ /**
16
+ * The primary's side: the stores it keeps for its workers, answering their calls.
17
+ *
18
+ * A worker names a store `<kind>#<n>` — the n-th of that kind its code built, the same in every worker since they
19
+ * all run the same code — and the primary makes it from the catalogue the first time it is asked. Nothing is made
20
+ * that no worker uses. A call names a method the kind was registered with and nothing else: the channel is not a way
21
+ * to reach whatever the object happens to carry.
22
+ */
23
+ var createStoreHost = (catalogue) => {
24
+ const instances = /* @__PURE__ */ new Map();
25
+ const storeFor = (key) => {
26
+ const existing = instances.get(key);
27
+ if (existing) return existing;
28
+ const kind = key.slice(0, key.lastIndexOf("#"));
29
+ if (!Object.hasOwn(catalogue, kind)) return;
30
+ const { create, methods } = catalogue[kind];
31
+ const made = {
32
+ instance: create(),
33
+ methods
34
+ };
35
+ instances.set(key, made);
36
+ return made;
37
+ };
38
+ const answer = async (call) => {
39
+ const store = storeFor(call.store);
40
+ const method = store?.methods.has(call.method) ? Reflect.get(store.instance, call.method) : void 0;
41
+ if (!store || typeof method !== "function") return {
42
+ sdkFleet: "reply",
43
+ id: call.id,
44
+ ok: false,
45
+ error: `the primary holds no store "${call.store}" with a method "${call.method}"`
46
+ };
47
+ try {
48
+ const value = await Reflect.apply(method, store.instance, call.args);
49
+ return {
50
+ sdkFleet: "reply",
51
+ id: call.id,
52
+ ok: true,
53
+ value
54
+ };
55
+ } catch (error) {
56
+ return {
57
+ sdkFleet: "reply",
58
+ id: call.id,
59
+ ok: false,
60
+ error: error instanceof Error ? error.message : String(error)
61
+ };
62
+ }
63
+ };
64
+ return { answer };
65
+ };
66
+ /** Who in this process hears a broadcast, by channel. A listener that throws is the caller's to report. */
67
+ var createListeners = (onError) => {
68
+ const listeners = /* @__PURE__ */ new Map();
69
+ const listen = (channel, listener) => {
70
+ const set = listeners.get(channel) ?? /* @__PURE__ */ new Set();
71
+ set.add(listener);
72
+ listeners.set(channel, set);
73
+ return () => set.delete(listener);
74
+ };
75
+ const deliver = (channel, payload) => {
76
+ listeners.get(channel)?.forEach((listener) => {
77
+ try {
78
+ listener(payload);
79
+ } catch (error) {
80
+ onError(channel, error);
81
+ }
82
+ });
83
+ };
84
+ return {
85
+ listen,
86
+ deliver
87
+ };
88
+ };
89
+ /**
90
+ * A worker's side: calls to the primary's stores, and broadcasts both ways.
91
+ *
92
+ * `send` may throw — a value that cannot cross the channel, a primary already gone — and the call then fails
93
+ * rather than waiting for an answer that will not come. The same when the channel closes with calls in flight.
94
+ */
95
+ var createFleetClient = (send, deliver) => {
96
+ const pending = /* @__PURE__ */ new Map();
97
+ let nextId = 0;
98
+ let closed = false;
99
+ const call = (store, method, args) => {
100
+ if (closed) return Promise.reject(/* @__PURE__ */ new Error(`[fleet] ${store}.${method}: the primary is gone`));
101
+ nextId += 1;
102
+ const id = nextId;
103
+ return new Promise((resolve, reject) => {
104
+ pending.set(id, {
105
+ resolve,
106
+ reject
107
+ });
108
+ try {
109
+ send({
110
+ sdkFleet: "call",
111
+ id,
112
+ store,
113
+ method,
114
+ args
115
+ });
116
+ } catch (error) {
117
+ pending.delete(id);
118
+ reject(new Error(`[fleet] ${store}.${method} could not be sent to the primary`, { cause: error }));
119
+ }
120
+ });
121
+ };
122
+ /** Every method of the store, each a call to the copy the primary keeps. */
123
+ const remote = (store, methods) => Object.fromEntries(Object.keys(methods).map((method) => [method, (...args) => call(store, method, args)]));
124
+ const broadcast = (channel, payload) => {
125
+ if (!closed) send({
126
+ sdkFleet: "broadcast",
127
+ channel,
128
+ payload
129
+ });
130
+ };
131
+ const receive = (message) => {
132
+ if (message.sdkFleet === "reply") {
133
+ const waiting = pending.get(message.id);
134
+ pending.delete(message.id);
135
+ if (message.ok) waiting?.resolve(message.value);
136
+ else waiting?.reject(/* @__PURE__ */ new Error(`[fleet] ${message.error}`));
137
+ return;
138
+ }
139
+ if (message.sdkFleet === "broadcast") deliver(message.channel, message.payload);
140
+ };
141
+ const close = () => {
142
+ closed = true;
143
+ const waiting = [...pending.values()];
144
+ pending.clear();
145
+ waiting.forEach((entry) => entry.reject(/* @__PURE__ */ new Error("[fleet] the primary is gone")));
146
+ };
147
+ return {
148
+ call,
149
+ remote,
150
+ broadcast,
151
+ receive,
152
+ close
153
+ };
154
+ };
155
+ /**
156
+ * The primary's side of the channel: it answers its workers' calls from the stores it holds, and passes each
157
+ * broadcast on to every process that did not send it — itself included, so a server in the primary hears it too.
158
+ *
159
+ * A peer that went away between a call and its answer is simply not answered: it is not waiting any more.
160
+ */
161
+ var createFleetHub = ({ host, deliver, peers }) => {
162
+ const sendTo = (peer, message) => {
163
+ try {
164
+ peer?.send(message);
165
+ } catch {}
166
+ };
167
+ const broadcast = (channel, payload, except) => {
168
+ peers().filter((peer) => peer.id !== except).forEach((peer) => sendTo(peer, {
169
+ sdkFleet: "broadcast",
170
+ channel,
171
+ payload
172
+ }));
173
+ };
174
+ const receive = async (from, message) => {
175
+ if (message.sdkFleet === "call") {
176
+ const reply = await host.answer(message);
177
+ sendTo(peers().find((peer) => peer.id === from), reply);
178
+ return;
179
+ }
180
+ if (message.sdkFleet === "broadcast") {
181
+ deliver(message.channel, message.payload);
182
+ broadcast(message.channel, message.payload, from);
183
+ }
184
+ };
185
+ return {
186
+ receive,
187
+ broadcast
188
+ };
189
+ };
190
+ export { hostable as a, createStoreHost as i, createFleetHub as n, isFleetMessage as o, createListeners as r, createFleetClient as t };