akanjs 3.1.1-rc.8 → 3.1.1

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 (126) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/base/baseEnv.ts +2 -1
  3. package/client/cookie.ts +10 -6
  4. package/client/csrLocation.ts +8 -0
  5. package/client/csrTypes.ts +2 -0
  6. package/client/index.ts +6 -1
  7. package/client/navigationGuards.ts +6 -6
  8. package/client/router.ts +13 -8
  9. package/common/IpBytes.ts +45 -0
  10. package/common/IpLiteral.ts +3 -44
  11. package/common/TrustedProxy.ts +13 -8
  12. package/common/clientAddress.ts +2 -1
  13. package/common/cookieJar.ts +18 -2
  14. package/common/index.ts +0 -1
  15. package/constant/constantRegistry.ts +3 -3
  16. package/constant/refNameClaims.ts +4 -4
  17. package/constant/serialize.ts +7 -1
  18. package/document/into.ts +8 -0
  19. package/fetch/agentTurn.ts +5 -3
  20. package/fetch/renderScope.ts +2 -2
  21. package/index.ts +11 -5
  22. package/package.json +1 -1
  23. package/server/akanOption.ts +28 -0
  24. package/server/akanServer.ts +5 -2
  25. package/server/contentEncoding.ts +12 -7
  26. package/server/di/diLifecycle.ts +15 -2
  27. package/server/di/utils.ts +5 -3
  28. package/server/hmr/clientReport.ts +70 -0
  29. package/server/hmr/clientScript.ts +39 -1
  30. package/server/hmr/wsHub.ts +7 -2
  31. package/server/logging/logControlSocket.ts +12 -0
  32. package/server/resolver/signal.resolver.ts +14 -7
  33. package/server/systemPageDocument.tsx +2 -1
  34. package/server/webRouter.ts +4 -4
  35. package/service/predefinedAdaptor/database.adaptor.ts +21 -16
  36. package/service/predefinedAdaptor/sql/AfterCommitHooks.ts +1 -2
  37. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +73 -11
  38. package/service/predefinedAdaptor/sql/TransactionScope.ts +22 -0
  39. package/service/predefinedAdaptor/sql/dialect/postgres.ts +5 -0
  40. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +8 -0
  41. package/service/predefinedAdaptor/sql/types.ts +9 -1
  42. package/service/serve.ts +2 -2
  43. package/store/action.ts +2 -1
  44. package/store/baseSt.ts +5 -1
  45. package/types/base/baseEnv.d.ts +1 -1
  46. package/types/client/csrLocation.d.ts +2 -0
  47. package/types/client/csrTypes.d.ts +2 -0
  48. package/types/client/index.d.ts +1 -1
  49. package/types/client/navigationGuards.d.ts +4 -4
  50. package/types/client/router.d.ts +2 -1
  51. package/types/common/IpBytes.d.ts +5 -0
  52. package/types/common/IpLiteral.d.ts +0 -2
  53. package/types/common/index.d.ts +0 -1
  54. package/types/constant/constantRegistry.d.ts +1 -1
  55. package/types/constant/refNameClaims.d.ts +1 -1
  56. package/types/document/into.d.ts +11 -0
  57. package/types/fetch/renderScope.d.ts +2 -2
  58. package/types/index.d.ts +11 -5
  59. package/types/server/akanOption.d.ts +6 -0
  60. package/types/server/di/utils.d.ts +2 -0
  61. package/types/server/hmr/clientReport.d.ts +16 -0
  62. package/types/server/webRouter.d.ts +1 -1
  63. package/types/service/predefinedAdaptor/sql/AfterCommitHooks.d.ts +1 -2
  64. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -1
  65. package/types/service/predefinedAdaptor/sql/TransactionScope.d.ts +6 -0
  66. package/types/service/predefinedAdaptor/sql/dialect/postgres.d.ts +1 -0
  67. package/types/service/predefinedAdaptor/sql/dialect/sqlite.d.ts +1 -0
  68. package/types/service/predefinedAdaptor/sql/types.d.ts +9 -1
  69. package/types/service/serve.d.ts +1 -1
  70. package/types/store/baseSt.d.ts +12 -12
  71. package/types/ui/Data/Item.d.ts +2 -1
  72. package/types/ui/Data/ListContainer.d.ts +11 -1
  73. package/types/ui/Data/UnlistedEditModal.d.ts +9 -0
  74. package/types/ui/Data/ViewActions.d.ts +12 -0
  75. package/types/ui/Data/useViewModal.d.ts +6 -0
  76. package/types/ui/Model/ViewModal.d.ts +3 -1
  77. package/types/ui/System/Common.d.ts +2 -2
  78. package/types/vendor/@akanjs/native/packages/cli/src/api.d.ts +10 -10
  79. package/types/vendor/@akanjs/native/packages/cli/src/config.d.ts +14 -4
  80. package/types/vendor/@akanjs/native/packages/cli/src/lib/publish.d.ts +13 -13
  81. package/types/vendor/@akanjs/native/packages/cli/src/lib/updates.d.ts +24 -12
  82. package/types/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.d.ts +5 -0
  83. package/types/vendor/@akanjs/native/packages/core/src/kernel.d.ts +11 -0
  84. package/types/vendor/@akanjs/native/packages/desktop/src/host.d.ts +3 -1
  85. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +8 -4
  86. package/types/vendor/@akanjs/native/plugins/updates/src/desktop.d.ts +16 -2
  87. package/types/vendor/@akanjs/native/plugins/updates/src/index.d.ts +18 -8
  88. package/types/webkit/index.d.ts +1 -0
  89. package/types/webkit/useNavigationGuard.d.ts +7 -0
  90. package/types/webkit/usePageLocation.d.ts +3 -4
  91. package/ui/Data/Item.tsx +41 -22
  92. package/ui/Data/ListContainer.tsx +40 -2
  93. package/ui/Data/UnlistedEditModal.tsx +31 -0
  94. package/ui/Data/ViewActions.tsx +57 -0
  95. package/ui/Data/useViewModal.ts +81 -0
  96. package/ui/Dialog/Provider.tsx +6 -0
  97. package/ui/Model/ViewModal.tsx +10 -9
  98. package/ui/System/CSR.tsx +1 -1
  99. package/ui/System/Client.tsx +4 -2
  100. package/ui/System/Common.tsx +2 -2
  101. package/ui/System/Messages.tsx +4 -2
  102. package/ui/System/Reconnect.tsx +3 -4
  103. package/ui/System/SSR.tsx +5 -3
  104. package/vendor/@akanjs/native/native/desktop/Cargo.toml +1 -1
  105. package/vendor/@akanjs/native/native/desktop/src/activity.rs +57 -0
  106. package/vendor/@akanjs/native/native/desktop/src/lib.rs +23 -4
  107. package/vendor/@akanjs/native/packages/cli/src/api.ts +12 -12
  108. package/vendor/@akanjs/native/packages/cli/src/commands/update.ts +4 -9
  109. package/vendor/@akanjs/native/packages/cli/src/config.ts +14 -4
  110. package/vendor/@akanjs/native/packages/cli/src/lib/configkeys.ts +11 -1
  111. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +3 -4
  112. package/vendor/@akanjs/native/packages/cli/src/lib/publish.ts +47 -49
  113. package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +58 -17
  114. package/vendor/@akanjs/native/packages/cli/src/platforms/android.ts +6 -5
  115. package/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.ts +20 -9
  116. package/vendor/@akanjs/native/packages/core/src/kernel.ts +59 -0
  117. package/vendor/@akanjs/native/packages/core/vectors/updates.json +24 -1
  118. package/vendor/@akanjs/native/packages/desktop/src/host.ts +6 -1
  119. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +19 -8
  120. package/vendor/@akanjs/native/packages/desktop/src/server.ts +2 -0
  121. package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +513 -217
  122. package/vendor/@akanjs/native/plugins/updates/src/index.ts +18 -8
  123. package/webkit/index.ts +1 -0
  124. package/webkit/nativeNavigation.ts +2 -10
  125. package/webkit/useNavigationGuard.ts +21 -0
  126. package/webkit/usePageLocation.ts +11 -5
@@ -24,14 +24,30 @@ export class CookieJar {
24
24
  static parse(header: string | null | undefined): CookieJar {
25
25
  const segments: CookieSegment[] = [];
26
26
  for (const part of header?.split(";") ?? []) {
27
- const raw = part.trim();
27
+ const raw = CookieJar.#trim(part);
28
28
  const eq = raw.indexOf("=");
29
29
  if (eq === -1) continue;
30
- segments.push({ name: raw.slice(0, eq).trim(), value: CookieJar.#decode(raw.slice(eq + 1).trim()), raw });
30
+ segments.push({
31
+ name: CookieJar.#trim(raw.slice(0, eq)),
32
+ value: CookieJar.#decode(CookieJar.#trim(raw.slice(eq + 1))),
33
+ raw,
34
+ });
31
35
  }
32
36
  return new CookieJar(segments);
33
37
  }
34
38
 
39
+ static #trim(text: string) {
40
+ let start = 0;
41
+ let end = text.length;
42
+ while (start < end && CookieJar.#isBlank(text[start])) start++;
43
+ while (end > start && CookieJar.#isBlank(text[end - 1])) end--;
44
+ return text.slice(start, end);
45
+ }
46
+
47
+ static #isBlank(char: string | undefined) {
48
+ return char === " " || char === "\t";
49
+ }
50
+
35
51
  static #decode(text: string): string {
36
52
  const unquoted = text.length >= 2 && text.startsWith('"') && text.endsWith('"') ? text.slice(1, -1) : text;
37
53
  try {
package/common/index.ts CHANGED
@@ -73,7 +73,6 @@ export {
73
73
  isCodeAgentReply,
74
74
  } from "./codeAgentWire";
75
75
  export { type CookieEntry, CookieJar, type CookieRead } from "./cookieJar";
76
- export { CookieSweep, type CookieSweepTarget } from "./cookieSweep";
77
76
  export { EventStream, type EventStreamOptions } from "./eventStream";
78
77
  export {
79
78
  type FileUploadCapability,
@@ -50,8 +50,8 @@ export class ConstantRegistry {
50
50
  ? { key: caller.file, label: `${caller.file}:${caller.row}` }
51
51
  : { key: "", label: "a registrant naming no origin" };
52
52
  }
53
- static assertConsistentRefNames() {
54
- ConstantRegistry.#claims.assertConsistent();
53
+ static assertConsistentRefNames(skippedOrigins: readonly string[] = []) {
54
+ ConstantRegistry.#claims.assertConsistent(new Set(skippedOrigins));
55
55
  }
56
56
  static has(modelRef: Cls): boolean {
57
57
  return ConstantRegistry.modelRefNameMap.has(modelRef);
@@ -246,7 +246,7 @@ export class ConstantRegistry {
246
246
 
247
247
  if (ConstantRegistry.enum.get(enumKey) !== value) ConstantRegistry.#addOrigin("enum", enumKey, origin);
248
248
  ConstantRegistry.enum.set(enumKey, value as EnumInstance);
249
- ConstantRegistry.#claims.claim("enum", enumKey, [value as Cls], owner);
249
+ ConstantRegistry.#claims.claim("enum", (value as EnumInstance).refName, [value as Cls], owner);
250
250
  } else ConstantRegistry.value.set(key, value);
251
251
  }
252
252
  }
@@ -34,8 +34,8 @@ export class RefNameClaims {
34
34
  this.#entries.set(id, entry);
35
35
  }
36
36
 
37
- assertConsistent() {
38
- const clashes = [...this.#entries.values()].flatMap((entry) => this.#clashesOf(entry));
37
+ assertConsistent(skippedOwners: ReadonlySet<string> = new Set()) {
38
+ const clashes = [...this.#entries.values()].flatMap((entry) => this.#clashesOf(entry, skippedOwners));
39
39
  if (!clashes.length) return;
40
40
  throw new Error(
41
41
  `[ConstantRegistry] ${clashes.length} refName(s) declared with different shapes:\n${clashes.join("\n")}\n` +
@@ -44,8 +44,8 @@ export class RefNameClaims {
44
44
  );
45
45
  }
46
46
 
47
- #clashesOf({ kind, key, claims }: RefNameEntry): string[] {
48
- const ordered = [...claims.values()];
47
+ #clashesOf({ kind, key, claims }: RefNameEntry, skippedOwners: ReadonlySet<string>): string[] {
48
+ const ordered = [...claims.values()].filter(({ owner }) => !skippedOwners.has(owner.key));
49
49
  const latest = ordered.at(-1);
50
50
  if (!latest) return [];
51
51
  return ordered.slice(0, -1).flatMap((earlier) => {
@@ -28,6 +28,9 @@ const getSerializeFn = (inputRef: Cls, { optional = false }: { optional?: boolea
28
28
  PrimitiveRegistry.has(inputRef)
29
29
  ? (value: unknown) => (inputRef as typeof PrimitiveScalar)._serialize(value as never, { optional })
30
30
  : (value: unknown) => value as object;
31
+
32
+ const keepsBlank = (primitive: unknown, value: unknown, serializeType: "input" | "object") =>
33
+ serializeType === "object" && value === "" && primitive === String;
31
34
  const optionalSerialize = { optional: true } as const;
32
35
  const requiredSerialize = { optional: false } as const;
33
36
  const serializeInput = <Input = unknown>(
@@ -49,6 +52,7 @@ const serializeInput = <Input = unknown>(
49
52
  ]),
50
53
  ) as unknown as Input;
51
54
  } else if (PrimitiveRegistry.has(inputRef as Cls)) {
55
+ if (keepsBlank(inputRef, value, serializeType)) return value;
52
56
  return (inputRef as typeof PrimitiveScalar)._serialize(
53
57
  value as never,
54
58
  optional ? optionalSerialize : requiredSerialize,
@@ -60,7 +64,7 @@ const serializeInput = <Input = unknown>(
60
64
  const fieldValue = (value as Record<string, unknown> | null | undefined)?.[key];
61
65
  serialized[key] =
62
66
  primitive && !field.arrDepth
63
- ? serializePrimitive(primitive, fieldValue, serializeOption)
67
+ ? serializePrimitive(primitive, fieldValue, serializeOption, serializeType)
64
68
  : serializeType === "input" && isRelationRef
65
69
  ? serialize(ID, field.arrDepth, getRelationId(fieldValue), serializeType, serializeOption)
66
70
  : serialize(field.modelRef, field.arrDepth, fieldValue, serializeType, serializeOption);
@@ -92,11 +96,13 @@ const serializePrimitive = (
92
96
  primitive: typeof PrimitiveScalar,
93
97
  value: unknown,
94
98
  { nullable, key }: { nullable: boolean; key: string },
99
+ serializeType: "input" | "object",
95
100
  ) => {
96
101
  if (value === null || value === undefined) {
97
102
  if (nullable) return null;
98
103
  if ((primitive as unknown) !== Any) throw missingValueError(primitive, value, key);
99
104
  }
105
+ if (keepsBlank(primitive, value, serializeType)) return value;
100
106
  return primitive._serialize(value as never, nullable ? optionalSerialize : requiredSerialize);
101
107
  };
102
108
  const missingValueError = (argRef: unknown, value: unknown, key?: string) =>
package/document/into.ts CHANGED
@@ -93,6 +93,14 @@ export type Mdl<
93
93
  purgeMany(query: _RawQuery): Promise<number>;
94
94
  updateById(id: string, update: DocumentUpdateInput<_RawDoc>, options?: DocumentUpdateOptions): Promise<UpdateResult>;
95
95
  removeById(id: string): Promise<UpdateResult>;
96
+ /**
97
+ * The same write, over a stored row only when the row matches `where`, a removed row only with `withRemoved`; a free
98
+ * id is inserted. `modifiedCount` is 0 when the stored row did not match, and `upsertedId` is set on an insert.
99
+ */
100
+ upsertById(
101
+ data: Partial<_RawDoc> & { id: string },
102
+ options: { where: _RawQuery; withRemoved?: boolean; preserveTimestamps?: boolean },
103
+ ): Promise<UpdateResult>;
96
104
  /**
97
105
  * Writes the record as the row under its own id, a new one or in place of the stored one, with no hook: a sync's or a
98
106
  * backfill's write, which may run twice. `preserveTimestamps` keeps its `createdAt` and `updatedAt`.
@@ -13,7 +13,9 @@ export class AgentTurn extends via((field) => ({
13
13
  }
14
14
  }
15
15
 
16
- export const agentTurnConstant = ConstantRegistry.buildScalar("agentTurn" as const, AgentTurn, {
16
+ export const agentTurnConstant = ConstantRegistry.buildScalar(
17
+ "agentTurn" as const,
17
18
  AgentTurn,
18
- AgentStop,
19
- });
19
+ { AgentTurn, AgentStop },
20
+ "akanjs",
21
+ );
@@ -8,8 +8,8 @@ declare global {
8
8
  }
9
9
 
10
10
  /**
11
- * Marks the render of a route — its guards, head, layouts and page body — where a write runs only when its call passes
12
- * `{ duringRender: true }`. Security: a server render sends the visitor's credential and no `Origin`, which
11
+ * @internal Marks the render of a route — its guards, head, layouts and page body — where a write runs only when its
12
+ * call passes `{ duringRender: true }`. Security: a server render sends the visitor's credential and no `Origin`, which
13
13
  * `CrossSiteGuard` reads as a non-browser caller, so a write there would run for whoever opened a link.
14
14
  */
15
15
  export class RenderScope {
package/index.ts CHANGED
@@ -127,20 +127,20 @@ export interface AkanNativeDeepLinks {
127
127
  */
128
128
  export interface AkanNativeUpdatesConfig {
129
129
  /**
130
- * A static base URL, https in a release build, with no query: `<url>/<os>-<arch>/<channel>.json` (desktop) or
130
+ * A static base URL, https in a release build, with no query: `<url>/<os>-<arch>/<channel>/app.json` (desktop) or
131
131
  * `<url>/<platform>/<channel>/<nativeApi>.json` (a phone's web bundle, one envelope per binary generation).
132
132
  */
133
133
  url: string;
134
134
  /**
135
- * The keys a phone binary trusts, raw 32-byte Ed25519 public keys in base64 (`akan update-keygen` prints one), 1 to
136
- * 3: the online signing key first, offline spares after it, since a key may revoke only keys listed before it. A
137
- * desktop app trusts the first.
135
+ * The keys a binary trusts, raw 32-byte Ed25519 public keys in base64 (`akan update-keygen` prints one), 1 to 3:
136
+ * the online signing key first, offline spares after it, since a key may revoke only keys listed before it. A desktop
137
+ * app built before protocol v2 trusts the first.
138
138
  */
139
139
  publicKeys?: string[];
140
140
  /** The one-key form of `publicKeys`, never beside it: a target overriding native.updates' keys keeps its form. */
141
141
  publicKey?: string;
142
142
  /**
143
- * keyIds every phone release revokes (`akan update-keygen` prints a key's), kept here so a release published from a
143
+ * keyIds every release revokes (`akan update-keygen` prints a key's), kept here so a release published from a
144
144
  * fresh checkout still revokes them; `akan publish-update --revoke` starts a revocation. A key may revoke only keys
145
145
  * listed before it in publicKeys, so a release is signed with one listed after them.
146
146
  */
@@ -157,6 +157,12 @@ export interface AkanNativeUpdatesConfig {
157
157
  * launch or return to the foreground, so rollback rates are visible. Left out, nothing is sent.
158
158
  */
159
159
  report?: { url: string };
160
+ /**
161
+ * Desktop: the app looks for a release in the background (soon after it starts, then hourly), downloads it, and
162
+ * installs it as it quits, so the next launch runs it. false leaves all three to the app's own `updates` calls. A
163
+ * phone always takes a new web bundle by itself. Default true.
164
+ */
165
+ automatic?: boolean;
160
166
  }
161
167
 
162
168
  export interface AkanNativeIosConfig {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.1.1-rc.8",
3
+ "version": "3.1.1",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -24,6 +24,7 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
24
24
  readonly #adaptorOverrides: AdaptorOverride[] = [];
25
25
  readonly #webProxies: WebProxyRegistration[] = [];
26
26
  readonly #getLlms: ((env: Env) => LlmOption)[] = [];
27
+ readonly #envTransforms: ((env: Env) => Env)[] = [];
27
28
  #getMcp: ((env: Env) => boolean | McpServerOption) | undefined;
28
29
  #agentAccess: GuardCls | GuardCls[] | null | undefined;
29
30
  #agentRequestPolicy: AgentRequestPolicy | null | undefined;
@@ -97,6 +98,25 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
97
98
  else this.#getLlms.push(() => llmOrFn);
98
99
  return this;
99
100
  }
101
+ /**
102
+ * Rewrites the server env once, when the server is built and before any option, injection or lib reads it; libs in
103
+ * mount order, the app's last. Gets a copy, so the imported env module is left as it was.
104
+ */
105
+ transformEnv(fn: (env: Env) => Env) {
106
+ this.#envTransforms.push(fn);
107
+ return this;
108
+ }
109
+ resolveEnv(env: Env): Env {
110
+ if (!this.#envTransforms.length) return env;
111
+ return this.#envTransforms.reduce((current, fn) => {
112
+ const next = fn(current);
113
+ if (!next || typeof next !== "object")
114
+ throw new Error(
115
+ `transformEnv must return the env object, and one returned ${next === null ? "null" : typeof next}`,
116
+ );
117
+ return next;
118
+ }, AkanOption.#copyPlain(env));
119
+ }
100
120
  /** Every entry in declaration order, duplicates kept: the boot stage rejects a key claimed twice. */
101
121
  getUses(env: Env): [string, PromiseOrObject<unknown>][] {
102
122
  return this.#getUses.flatMap((fn) => Object.entries(fn(env)));
@@ -134,6 +154,14 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
134
154
  getLlm(env: Env): LlmOption {
135
155
  return Object.assign({}, ...this.#getLlms.map((fn) => fn(env)));
136
156
  }
157
+
158
+ static #copyPlain<T>(value: T): T {
159
+ if (Array.isArray(value)) return value.map((item) => AkanOption.#copyPlain(item)) as T;
160
+ if (!value || typeof value !== "object") return value;
161
+ const proto = Object.getPrototypeOf(value);
162
+ if (proto !== Object.prototype && proto !== null) return value;
163
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, AkanOption.#copyPlain(item)])) as T;
164
+ }
137
165
  }
138
166
 
139
167
  export function createDefaultAkanOption() {
@@ -216,7 +216,7 @@ export class AkanServer {
216
216
  this.name = name;
217
217
  this.logger = new Logger(name);
218
218
  this.libs = libs;
219
- this.env = { ...env };
219
+ this.env = libs.reduce((current, lib) => lib.option.resolveEnv(current), { ...env });
220
220
 
221
221
  if (AkanServer.#isEdge(this.env) && !AkanServer.#isEnvEnabled("AKAN_MCP", "AKAN_PUBLIC_MCP")) this.mcp = false;
222
222
  this.openapi = options?.openapi ?? this.openapi;
@@ -398,7 +398,10 @@ export class AkanServer {
398
398
  const { WebRouter } = await import("./webRouter");
399
399
  const webRouter = await WebRouter.create({
400
400
  web: requestedWeb,
401
- upgradeHmrWs: (req, data) => this.#server?.upgrade(req, { data }) ?? false,
401
+
402
+ upgradeHmrWs: (req, data) =>
403
+ (this.#wsServer?.requestIP(req as Bun.BunRequest) ? this.#wsServer : this.#server)?.upgrade(req, { data }) ??
404
+ false,
402
405
  });
403
406
 
404
407
  if (!webRouter) {
@@ -49,6 +49,8 @@ export const isCompressibleContentType = (contentType: string): boolean => {
49
49
  };
50
50
 
51
51
  const BROTLI_QUALITY = 4;
52
+
53
+ const STORED_BROTLI_QUALITY = 9;
52
54
  const GZIP_LEVEL = 6;
53
55
  /** Under a KB the framing bytes and the call cost more than the repetition they remove. */
54
56
  const MIN_COMPRESS_BYTES = 1024;
@@ -58,11 +60,11 @@ const MAX_COMPRESS_BYTES = 4 * 1024 * 1024;
58
60
  const brotliCompressAsync = promisify(brotliCompress);
59
61
  const gzipAsync = promisify(gzip);
60
62
 
61
- const compressBody = (bytes: Uint8Array, encoding: ContentEncoding) =>
63
+ const compressBody = (bytes: Uint8Array, encoding: ContentEncoding, brotliQuality = BROTLI_QUALITY) =>
62
64
  encoding === "br"
63
65
  ? brotliCompressAsync(bytes, {
64
66
  params: {
65
- [constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY,
67
+ [constants.BROTLI_PARAM_QUALITY]: brotliQuality,
66
68
  [constants.BROTLI_PARAM_SIZE_HINT]: bytes.byteLength,
67
69
  },
68
70
  })
@@ -83,6 +85,7 @@ const negotiateEncoding = (req: Request, response: Pick<Response, "status" | "he
83
85
  if (Number(response.headers.get("content-length")) > MAX_COMPRESS_BYTES) return null;
84
86
  if (!isCompressibleContentType(response.headers.get("content-type") ?? "")) return null;
85
87
  if (isCompressionOff()) return null;
88
+ varyOnEncoding(response.headers);
86
89
  return acceptedEncodings(req.headers.get("accept-encoding") ?? "")[0] ?? null;
87
90
  };
88
91
 
@@ -139,7 +142,6 @@ export const compressResponse = async (req: Request, response: Response): Promis
139
142
  const headers = new Headers(response.headers);
140
143
  headers.set("Content-Encoding", encoding);
141
144
  headers.set("Content-Length", String(compressed.byteLength));
142
- varyOnEncoding(headers);
143
145
  return new Response(compressed, { status: response.status, statusText: response.statusText, headers });
144
146
  };
145
147
 
@@ -202,7 +204,6 @@ export const compressStreamResponse = (req: Request, response: Response): Respon
202
204
  const headers = new Headers(response.headers);
203
205
  headers.set("Content-Encoding", encoding);
204
206
  headers.delete("Content-Length");
205
- varyOnEncoding(headers);
206
207
  const etag = headers.get("etag");
207
208
 
208
209
  if (etag && !etag.startsWith("W/")) headers.set("ETag", `W/${etag}`);
@@ -228,7 +229,7 @@ export const encodeBody = async (body: string | Uint8Array<ArrayBuffer>): Promis
228
229
  return { bytes, encodings, byteLength };
229
230
  await Promise.all(
230
231
  CONTENT_ENCODINGS.map(async ({ encoding }) => {
231
- const encoded = await compressBody(bytes, encoding);
232
+ const encoded = await compressBody(bytes, encoding, STORED_BROTLI_QUALITY);
232
233
  encodings[encoding] = encoded;
233
234
  byteLength += encoded.byteLength;
234
235
  }),
@@ -248,7 +249,6 @@ export const encodedBodyResponse = (
248
249
  const headers = new Headers(init.headers);
249
250
  headers.set("Content-Encoding", encoding);
250
251
  headers.set("Content-Length", String(encoded.byteLength));
251
- varyOnEncoding(headers);
252
252
  return new Response(encoded, { status, headers });
253
253
  };
254
254
 
@@ -283,7 +283,12 @@ export const encodedFileResponse = async (
283
283
  ): Promise<Response> => {
284
284
  if (isCompressibleContentType(contentType)) varyOnEncoding(headers);
285
285
  const sidecar = await resolveEncodedSidecar(req, filePath, contentType);
286
- if (!sidecar) return new Response(Bun.file(filePath).stream(), { headers });
286
+ if (!sidecar) {
287
+ const file = Bun.file(filePath);
288
+
289
+ headers.set("Content-Length", String(file.size));
290
+ return new Response(file, { headers });
291
+ }
287
292
  headers.set("Content-Encoding", sidecar.encoding);
288
293
  headers.set("Content-Length", String(sidecar.bytes.byteLength));
289
294
  return new Response(sidecar.bytes, { headers });
@@ -122,7 +122,8 @@ export class DiLifecycle {
122
122
  }
123
123
 
124
124
  constructor({ env, modules = [], disableModules = [], disableLibs = [] }: DiLifecycleProps, ...libs: AkanLib[]) {
125
- ConstantRegistry.assertConsistentRefNames();
125
+
126
+ ConstantRegistry.assertConsistentRefNames(disableLibs);
126
127
  this.#env = env;
127
128
  const databaseMode = DiLifecycle.#databaseMode();
128
129
  this.logger.debug(`Database mode: ${DatabaseModes.describe(databaseMode)}`);
@@ -464,11 +465,23 @@ export class DiLifecycle {
464
465
  this.logger.verbose(`${doneLabel} in ${Date.now() - now}ms`);
465
466
  }
466
467
 
468
+ static readonly #jobScopes: { [type: string]: string } = {
469
+ init: "init",
470
+ destroy: "destroy",
471
+ process: "process",
472
+ cron: "schedule",
473
+ interval: "schedule",
474
+ timeout: "schedule",
475
+ };
467
476
  #assertUniqueInternalJobs() {
468
477
  const jobs = this.#allModules().flatMap(({ signal: { internal } }) =>
469
478
  Object.entries(internal[INTERNAL_META])
470
479
  .filter(([, { type }]) => type !== "resolveField")
471
- .map(([key, { type }]) => ({ key, owner: `the ${type} of "${internal.refName}"` })),
480
+ .map(([key, { type }]) => ({
481
+ key,
482
+ owner: `the ${type} of "${internal.refName}"`,
483
+ scope: DiLifecycle.#jobScopes[type] ?? type,
484
+ })),
472
485
  );
473
486
  assertUniqueRegistrations("internal", jobs);
474
487
  }
@@ -105,15 +105,17 @@ export interface Registration {
105
105
  key: string;
106
106
  /** What claimed the key, phrased for a boot error: `predefined adaptor "storage"`, `lib "shared"`. */
107
107
  owner: string;
108
+ /** Keys clash only within one scope. */
109
+ scope?: string;
108
110
  }
109
111
 
110
112
  export const assertUniqueRegistrations = (kind: string, registrations: Registration[]) => {
111
113
  const claimed = new Map<string, string>();
112
114
  const clashes: string[] = [];
113
- for (const { key, owner } of registrations) {
114
- const previous = claimed.get(key);
115
+ for (const { key, owner, scope = "" } of registrations) {
116
+ const previous = claimed.get(`${scope}\0${key}`);
115
117
  if (previous) clashes.push(` • "${key}" is registered by ${previous} and by ${owner}`);
116
- else claimed.set(key, owner);
118
+ else claimed.set(`${scope}\0${key}`, owner);
117
119
  }
118
120
  if (!clashes.length) return;
119
121
  throw new Error(`[DI:${kind}] ${clashes.length} duplicate registration(s):\n${clashes.join("\n")}`);
@@ -0,0 +1,70 @@
1
+ import { Logger } from "akanjs/common";
2
+
3
+ export interface HmrClientReport {
4
+ type: "client-report";
5
+ kind: "error" | "rejection";
6
+ message: string;
7
+ stack?: string;
8
+ href: string;
9
+ client: "ssr" | "csr";
10
+ platform?: string;
11
+ target?: string;
12
+ }
13
+
14
+ export class ClientReport {
15
+ static readonly #fieldLimit = 4_000;
16
+ static readonly #stackLines = 6;
17
+
18
+ static readonly #controlChars = /[\u0000-\u0008\u000b-\u001f\u007f]/g;
19
+
20
+ static parse(value: unknown): HmrClientReport | null {
21
+ if (!value || typeof value !== "object") return null;
22
+ const report = value as Partial<HmrClientReport>;
23
+ if (report.type !== "client-report") return null;
24
+ if (report.kind !== "error" && report.kind !== "rejection") return null;
25
+ if (report.client !== "ssr" && report.client !== "csr") return null;
26
+ if (typeof report.message !== "string" || typeof report.href !== "string") return null;
27
+ return {
28
+ type: "client-report",
29
+ kind: report.kind,
30
+ message: ClientReport.#clean(report.message),
31
+ href: ClientReport.#clean(report.href),
32
+ client: report.client,
33
+ ...(typeof report.stack === "string" && report.stack ? { stack: ClientReport.#clean(report.stack) } : {}),
34
+ ...(typeof report.platform === "string" ? { platform: ClientReport.#clean(report.platform) } : {}),
35
+ ...(typeof report.target === "string" ? { target: ClientReport.#clean(report.target) } : {}),
36
+ };
37
+ }
38
+
39
+ static describe(report: HmrClientReport) {
40
+ const where = [report.client, report.platform && report.platform !== "web" ? report.platform : null, report.target]
41
+ .filter(Boolean)
42
+ .join(" ");
43
+ const what = report.kind === "rejection" ? "Unhandled rejection" : "Uncaught error";
44
+ const head = `${what} on ${report.href} (${where}): ${report.message}`;
45
+ const frames = (report.stack ?? "")
46
+ .split("\n")
47
+ .filter((line) => line.trim().length > 1 && !report.message.includes(line.trim()))
48
+ .slice(0, ClientReport.#stackLines);
49
+ return [head, ...frames.map((line) => ` ${line.trim()}`)].join("\n");
50
+ }
51
+
52
+ static log(report: HmrClientReport) {
53
+ Logger.emit({
54
+ level: "error",
55
+ name: "ClientReport",
56
+ message: ClientReport.describe(report),
57
+ attrs: {
58
+ kind: report.kind,
59
+ href: report.href,
60
+ client: report.client,
61
+ platform: report.platform ?? null,
62
+ target: report.target ?? null,
63
+ },
64
+ });
65
+ }
66
+
67
+ static #clean(text: string) {
68
+ return Logger.stripAnsi(text).replace(ClientReport.#controlChars, "").slice(0, ClientReport.#fieldLimit);
69
+ }
70
+ }
@@ -40,6 +40,42 @@ export const HMR_CLIENT_SCRIPT = `(function(){
40
40
  }
41
41
  };
42
42
 
43
+ var reportsHeard = false;
44
+ var reportQueue = [];
45
+ var reportedKeys = {};
46
+ var reportCount = 0;
47
+ var reportTarget = new URLSearchParams(location.search).get("akanMobileTarget");
48
+ function sendReports(){
49
+ while (reportsHeard && reportQueue.length && socket && socket.readyState === WebSocket.OPEN) {
50
+ try { socket.send(JSON.stringify(reportQueue.shift())); } catch(e) { return; }
51
+ }
52
+ }
53
+ function report(kind, error, fallback){
54
+ var message = error && typeof error.message === "string" ? error.message : String(fallback === undefined ? error : fallback);
55
+ var stack = error && typeof error.stack === "string" ? error.stack : "";
56
+ var key = kind + "|" + message + "|" + stack.slice(0, 300);
57
+ if (reportedKeys[key] || reportCount >= 50) return;
58
+ reportedKeys[key] = true;
59
+ reportCount++;
60
+ var native = self.__AKAN_NATIVE__;
61
+ reportQueue.push({
62
+ type: "client-report",
63
+ kind: kind,
64
+ message: (error && error.name && message.indexOf(error.name) !== 0 ? error.name + ": " : "") + message,
65
+ stack: stack,
66
+ href: location.pathname + location.search,
67
+ client: clientKind,
68
+ platform: native && typeof native.platform === "string" ? native.platform : "web",
69
+ target: reportTarget || undefined
70
+ });
71
+ if (reportQueue.length > 20) reportQueue.shift();
72
+ sendReports();
73
+ }
74
+ if (!systemPage) {
75
+ self.addEventListener("error", function(ev){ report("error", ev.error, ev.message); });
76
+ self.addEventListener("unhandledrejection", function(ev){ report("rejection", ev.reason); });
77
+ }
78
+
43
79
  self.$RefreshReg$ = self.$RefreshReg$ || function(type, id){
44
80
  if (refreshRuntime) refreshRuntime.register(type, id);
45
81
  else pendingRefreshRegistrations.push([type, id]);
@@ -58,6 +94,8 @@ export const HMR_CLIENT_SCRIPT = `(function(){
58
94
  if (!msg || typeof msg.type !== "string") return;
59
95
  if (msg.type === "hello") {
60
96
  attempts = 0;
97
+ reportsHeard = true;
98
+ sendReports();
61
99
  var dropped = Array.isArray(msg.failingPhases) && dropBuildErrorsExcept(msg.failingPhases);
62
100
  if (dropped && systemPage) {
63
101
  reloadForUpdate("the build that failed to render this page recovered");
@@ -144,7 +182,7 @@ export const HMR_CLIENT_SCRIPT = `(function(){
144
182
  return;
145
183
  }
146
184
  });
147
- socket.addEventListener("close", function(){ socket = null; schedule(); });
185
+ socket.addEventListener("close", function(){ socket = null; reportsHeard = false; schedule(); });
148
186
  socket.addEventListener("error", function(){ try { socket && socket.close(); } catch(e){} });
149
187
  }
150
188
 
@@ -1,5 +1,6 @@
1
1
  import { Logger } from "akanjs/common";
2
2
  import type { BuildPhase, HmrTrace } from "../artifact";
3
+ import { ClientReport } from "./clientReport";
3
4
 
4
5
  export type ChangeKind = "code" | "css" | "config" | "ignore";
5
6
 
@@ -109,14 +110,18 @@ export class HmrWsHub {
109
110
  }
110
111
 
111
112
  handleMessage(message: string): void {
112
- if (!isSyncNavigationEnabled()) return;
113
113
  let parsed: unknown;
114
114
  try {
115
115
  parsed = JSON.parse(message);
116
116
  } catch {
117
117
  return;
118
118
  }
119
- if (!isSyncNavigationMessage(parsed)) return;
119
+ const report = ClientReport.parse(parsed);
120
+ if (report) {
121
+ ClientReport.log(report);
122
+ return;
123
+ }
124
+ if (!isSyncNavigationEnabled() || !isSyncNavigationMessage(parsed)) return;
120
125
  this.broadcast(parsed);
121
126
  }
122
127
  }
@@ -60,6 +60,8 @@ export class LogControlSocket {
60
60
 
61
61
  async start() {
62
62
  await mkdir(path.dirname(this.path), { recursive: true });
63
+
64
+ if (await LogControlSocket.#answers(this.path)) throw new Error("another server is listening on it");
63
65
  await rm(this.path, { force: true });
64
66
  this.#server = Bun.listen<ClientState>({
65
67
  unix: this.path,
@@ -85,6 +87,16 @@ export class LogControlSocket {
85
87
  await rm(this.path, { force: true });
86
88
  }
87
89
 
90
+ static async #answers(socketPath: string) {
91
+ try {
92
+ const socket = await Bun.connect<undefined>({ unix: socketPath, socket: { data: () => undefined } });
93
+ socket.end();
94
+ return true;
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
99
+
88
100
  #onData(socket: Bun.Socket<ClientState>, chunk: Buffer) {
89
101
  const state = socket.data;
90
102
  state.inbox += chunk.toString("utf8");
@@ -78,7 +78,7 @@ export class SignalResolver {
78
78
  };
79
79
  static readonly #coalescingRooms = new Set<string>();
80
80
  static readonly #liveRoutes = new Map<string, { store: DocumentStore; route: LiveRoute }>();
81
- static readonly #everyRowAsked = new Set<string>();
81
+ static readonly #cappedListKeys = new Set<string>();
82
82
  static readonly #websockets = new WeakMap<InjectRegistry, { key: AdaptorCls; websocket: WebsocketAdaptor }>();
83
83
 
84
84
  static coalescesRoom(roomId: string): boolean {
@@ -358,12 +358,15 @@ export class SignalResolver {
358
358
  else SignalResolver.logger.warn(message);
359
359
  }
360
360
 
361
- static #clientPageLimit(listKey: string, asked: unknown) {
362
- if (asked !== 0) return resolvePageLimit(asked);
363
- if (!SignalResolver.#everyRowAsked.has(listKey)) {
364
- SignalResolver.#everyRowAsked.add(listKey);
361
+ static #clientPageLimit(listKey: string, storeKey: string, asked: unknown) {
362
+ const isCapped = asked === 0 || Number(asked) > MAX_PAGE_SIZE;
363
+ if (!isCapped) return resolvePageLimit(asked);
364
+ if (!SignalResolver.#cappedListKeys.has(listKey)) {
365
+ SignalResolver.#cappedListKeys.add(listKey);
365
366
  SignalResolver.logger.warn(
366
- `${listKey} was asked for limit: 0 and served ${MAX_PAGE_SIZE} rows, the most a client may take; paginate, or name a page size`,
367
+ `${listKey} was asked for limit: ${String(asked)} and served at most ${MAX_PAGE_SIZE} rows, the most a client may take; ` +
368
+ `any row past them is dropped and the client is not told. Page with skip/limit at ${MAX_PAGE_SIZE} or fewer per request ` +
369
+ `(st.do.loadMoreOf${storeKey}() while hasMoreOf${storeKey}), or aggregate on the server in an insight or a dedicated endpoint`,
367
370
  );
368
371
  }
369
372
  return MAX_PAGE_SIZE;
@@ -415,7 +418,11 @@ export class SignalResolver {
415
418
  .exec(async function (this: any, ...requestArgs: any) {
416
419
  const args = requestArgs.slice(0, argLength);
417
420
  const skip = resolvePageSkip(requestArgs[argLength]);
418
- const limit = SignalResolver.#clientPageLimit(listKey, requestArgs[argLength + 1]);
421
+ const limit = SignalResolver.#clientPageLimit(
422
+ listKey,
423
+ `${capitalizedRefName}${capitalizedKey}`,
424
+ requestArgs[argLength + 1],
425
+ );
419
426
  const sort = requestArgs[argLength + 2] ?? "latest";
420
427
  const internalArgs = requestArgs.slice(argLength + 3);
421
428
  const query = assertSliceQuery(