@agent-native/core 0.114.0 → 0.114.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.
- package/corpus/README.md +2 -2
- package/corpus/core/CHANGELOG.md +9 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/client/build-compatibility.ts +77 -0
- package/corpus/core/src/client/route-chunk-recovery/index.ts +1 -0
- package/corpus/core/src/client/use-action.ts +32 -1
- package/corpus/core/src/deploy/build.ts +4 -1
- package/corpus/core/src/org/context.ts +56 -30
- package/corpus/core/src/server/action-routes.ts +52 -2
- package/corpus/core/src/server/auth-plugin.ts +9 -4
- package/corpus/core/src/server/better-auth-instance.ts +5 -1
- package/corpus/core/src/shared/mcp-embed-headers.ts +1 -1
- package/corpus/core/src/vite/client.ts +17 -0
- package/corpus/templates/content/AGENTS.md +2 -0
- package/corpus/templates/content/actions/_content-database-personal-view.ts +49 -5
- package/corpus/templates/content/actions/_content-document-access.ts +21 -0
- package/corpus/templates/content/actions/_content-favorites.ts +91 -0
- package/corpus/templates/content/actions/_content-files.ts +79 -23
- package/corpus/templates/content/actions/_content-sidebar-state.ts +24 -0
- package/corpus/templates/content/actions/_content-space-access.ts +15 -17
- package/corpus/templates/content/actions/_content-space-catalog-guards.ts +20 -0
- package/corpus/templates/content/actions/_content-spaces.ts +364 -167
- package/corpus/templates/content/actions/_database-source-utils.ts +8 -0
- package/corpus/templates/content/actions/_database-utils.ts +249 -15
- package/corpus/templates/content/actions/_delete-content-space.ts +84 -0
- package/corpus/templates/content/actions/_files-system-properties.ts +499 -0
- package/corpus/templates/content/actions/_local-file-documents.ts +0 -1
- package/corpus/templates/content/actions/_property-utils.ts +18 -9
- package/corpus/templates/content/actions/bind-content-database-source-field.ts +3 -0
- package/corpus/templates/content/actions/configure-document-property.ts +3 -0
- package/corpus/templates/content/actions/create-content-database.ts +2 -2
- package/corpus/templates/content/actions/create-content-space.ts +34 -0
- package/corpus/templates/content/actions/create-document.ts +4 -1
- package/corpus/templates/content/actions/delete-content-space.ts +19 -0
- package/corpus/templates/content/actions/delete-database-items.ts +28 -1
- package/corpus/templates/content/actions/delete-document-property.ts +3 -0
- package/corpus/templates/content/actions/delete-document.ts +39 -2
- package/corpus/templates/content/actions/duplicate-database-item.ts +6 -0
- package/corpus/templates/content/actions/duplicate-database-items.ts +6 -0
- package/corpus/templates/content/actions/duplicate-document-property.ts +3 -0
- package/corpus/templates/content/actions/get-content-database.ts +11 -2
- package/corpus/templates/content/actions/get-content-sidebar-state.ts +23 -0
- package/corpus/templates/content/actions/get-document.ts +32 -7
- package/corpus/templates/content/actions/import-content-source.ts +33 -1
- package/corpus/templates/content/actions/list-content-spaces.ts +34 -2
- package/corpus/templates/content/actions/list-documents.ts +39 -7
- package/corpus/templates/content/actions/reorder-document-property.ts +9 -0
- package/corpus/templates/content/actions/set-document-property.ts +41 -23
- package/corpus/templates/content/actions/share-local-file-document.ts +15 -0
- package/corpus/templates/content/actions/submit-content-database-form.ts +7 -0
- package/corpus/templates/content/actions/sync-local-folder-source.ts +14 -0
- package/corpus/templates/content/actions/update-content-database-view.ts +1 -0
- package/corpus/templates/content/actions/update-content-sidebar-state.ts +27 -0
- package/corpus/templates/content/actions/update-document.ts +158 -66
- package/corpus/templates/content/app/components/EmptyState.tsx +4 -57
- package/corpus/templates/content/app/components/editor/CommentsSidebar.tsx +8 -1
- package/corpus/templates/content/app/components/editor/DocumentEditor.tsx +519 -178
- package/corpus/templates/content/app/components/editor/DocumentInfoPanel.tsx +39 -0
- package/corpus/templates/content/app/components/editor/DocumentProperties.tsx +1 -1
- package/corpus/templates/content/app/components/editor/DocumentToolbar.tsx +266 -7
- package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +430 -152
- package/corpus/templates/content/app/components/editor/database/sidebar.tsx +467 -66
- package/corpus/templates/content/app/components/editor/database/view-config.ts +9 -3
- package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +720 -196
- package/corpus/templates/content/app/components/sidebar/DocumentTreeItem.tsx +173 -1
- package/corpus/templates/content/app/components/sidebar/document-sidebar-sections.ts +1 -1
- package/corpus/templates/content/app/components/sidebar/select-content-space.ts +91 -16
- package/corpus/templates/content/app/entry.client.tsx +5 -1
- package/corpus/templates/content/app/hooks/use-content-database.ts +84 -3
- package/corpus/templates/content/app/hooks/use-content-spaces.ts +60 -2
- package/corpus/templates/content/app/hooks/use-create-page.ts +30 -0
- package/corpus/templates/content/app/hooks/use-documents.ts +270 -19
- package/corpus/templates/content/app/i18n-data.ts +243 -20
- package/corpus/templates/content/app/lib/local-folder-picker-safety.ts +54 -0
- package/corpus/templates/content/app/lib/local-folder-picker-support.ts +18 -0
- package/corpus/templates/content/app/routes/_app.favorites.tsx +30 -0
- package/corpus/templates/content/app/routes/_app.local-files.tsx +18 -6
- package/corpus/templates/content/changelog/2026-07-17-workspace-files-now-stay-in-a-loading-state-until-automatic-.md +6 -0
- package/corpus/templates/content/changelog/2026-07-17-workspace-switching-now-opens-the-selected-files-database-pr.md +6 -0
- package/corpus/templates/content/changelog/2026-07-17-workspaces-now-expand-above-their-own-files-list-without-dup.md +6 -0
- package/corpus/templates/content/changelog/2026-07-18-create-named-workspaces-each-with-its-own-private-files-data.md +6 -0
- package/corpus/templates/content/changelog/2026-07-18-favorites-align-with-workspace-and-file-rows-in-the-sidebar.md +6 -0
- package/corpus/templates/content/changelog/2026-07-18-local-folder-selection-no-longer-invokes-the-unsafe-native-p.md +6 -0
- package/corpus/templates/content/changelog/2026-07-18-made-content-workspaces-independently-expandable-restored-or.md +6 -0
- package/corpus/templates/content/changelog/2026-07-18-page-details-now-live-in-a-shared-info-and-comments-rail-dat.md +6 -0
- package/corpus/templates/content/changelog/2026-07-18-workspace-database-views-now-control-sidebar-workspace-navig.md +6 -0
- package/corpus/templates/content/changelog/2026-07-18-workspace-navigation-now-aligns-favorites-with-workspace-pag.md +6 -0
- package/corpus/templates/content/changelog/2026-07-19-favorites-now-open-as-a-table-and-compact-breadcrumbs-make-w.md +6 -0
- package/corpus/templates/content/changelog/2026-07-19-files-databases-now-start-unfiltered-sidebar-rows-exactly-fo.md +6 -0
- package/corpus/templates/content/changelog/2026-07-19-sidebar-page-trees-now-open-only-when-expanded-remember-thei.md +6 -0
- package/corpus/templates/content/changelog/2026-07-19-workspace-file-databases-now-use-the-workspace-name-open-as-.md +6 -0
- package/corpus/templates/content/changelog/2026-07-19-workspace-navigation-now-stays-stable-on-hover-uses-folder-i.md +6 -0
- package/corpus/templates/content/changelog/2026-07-19-workspace-rows-now-use-folder-icons-and-deleting-a-user-crea.md +6 -0
- package/corpus/templates/content/changelog/2026-07-19-workspaces-can-be-created-without-leaving-the-workspaces-dat.md +6 -0
- package/corpus/templates/content/e2e/global-setup.ts +3 -2
- package/corpus/templates/content/parity/matrix.md +28 -28
- package/corpus/templates/content/parity/matrix.ts +8 -2
- package/corpus/templates/content/server/db/index.ts +1 -0
- package/corpus/templates/content/server/db/schema.ts +10 -0
- package/corpus/templates/content/server/lib/documents.ts +12 -7
- package/corpus/templates/content/server/plugins/db.ts +17 -0
- package/corpus/templates/content/shared/api.ts +9 -0
- package/corpus/templates/content/shared/database-form.ts +11 -2
- package/corpus/templates/content/vite.config.ts +1 -0
- package/dist/client/build-compatibility.d.ts +11 -0
- package/dist/client/build-compatibility.d.ts.map +1 -0
- package/dist/client/build-compatibility.js +56 -0
- package/dist/client/build-compatibility.js.map +1 -0
- package/dist/client/route-chunk-recovery/index.d.ts +1 -0
- package/dist/client/route-chunk-recovery/index.d.ts.map +1 -1
- package/dist/client/route-chunk-recovery/index.js +1 -0
- package/dist/client/route-chunk-recovery/index.js.map +1 -1
- package/dist/client/use-action.d.ts.map +1 -1
- package/dist/client/use-action.js +19 -1
- package/dist/client/use-action.js.map +1 -1
- package/dist/collab/routes.d.ts +1 -1
- package/dist/collab/struct-routes.d.ts +1 -1
- package/dist/deploy/build.js +2 -1
- package/dist/deploy/build.js.map +1 -1
- package/dist/file-upload/actions/upload-image.d.ts +1 -1
- package/dist/notifications/routes.d.ts +1 -1
- package/dist/observability/routes.d.ts +5 -5
- package/dist/org/context.d.ts +4 -2
- package/dist/org/context.d.ts.map +1 -1
- package/dist/org/context.js +44 -22
- package/dist/org/context.js.map +1 -1
- package/dist/progress/routes.d.ts +1 -1
- package/dist/provider-api/actions/custom-provider-registration.d.ts +10 -10
- package/dist/provider-api/actions/provider-api.d.ts +12 -12
- package/dist/provider-api/corpus-jobs.d.ts +2 -2
- package/dist/resources/handlers.d.ts +1 -1
- package/dist/secrets/routes.d.ts +9 -9
- package/dist/server/action-routes.d.ts.map +1 -1
- package/dist/server/action-routes.js +32 -2
- package/dist/server/action-routes.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/auth-plugin.d.ts.map +1 -1
- package/dist/server/auth-plugin.js +9 -5
- package/dist/server/auth-plugin.js.map +1 -1
- package/dist/server/better-auth-instance.d.ts.map +1 -1
- package/dist/server/better-auth-instance.js +4 -1
- package/dist/server/better-auth-instance.js.map +1 -1
- package/dist/server/transcribe-voice.d.ts +1 -1
- package/dist/shared/mcp-embed-headers.d.ts +1 -1
- package/dist/shared/mcp-embed-headers.d.ts.map +1 -1
- package/dist/shared/mcp-embed-headers.js +1 -1
- package/dist/shared/mcp-embed-headers.js.map +1 -1
- package/dist/vite/client.d.ts +6 -0
- package/dist/vite/client.d.ts.map +1 -1
- package/dist/vite/client.js +8 -0
- package/dist/vite/client.js.map +1 -1
- package/package.json +1 -1
- package/src/client/build-compatibility.ts +77 -0
- package/src/client/route-chunk-recovery/index.ts +1 -0
- package/src/client/use-action.ts +32 -1
- package/src/deploy/build.ts +4 -1
- package/src/org/context.ts +56 -30
- package/src/server/action-routes.ts +52 -2
- package/src/server/auth-plugin.ts +9 -4
- package/src/server/better-auth-instance.ts +5 -1
- package/src/shared/mcp-embed-headers.ts +1 -1
- package/src/vite/client.ts +17 -0
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
runMigrations,
|
|
5
5
|
} from "@agent-native/core/db";
|
|
6
6
|
|
|
7
|
+
import { repairFilesSystemPropertyDefinitions } from "../../actions/_files-system-properties.js";
|
|
7
8
|
import { repairUnseededBlocksFields } from "../../actions/_property-utils.js";
|
|
8
9
|
import * as schema from "../db/schema.js";
|
|
9
10
|
|
|
@@ -847,6 +848,14 @@ const runContentMigrations = runMigrations(
|
|
|
847
848
|
CREATE UNIQUE INDEX IF NOT EXISTS content_database_items_database_document_unique
|
|
848
849
|
ON content_database_items (database_id, document_id)`,
|
|
849
850
|
},
|
|
851
|
+
{
|
|
852
|
+
version: 75,
|
|
853
|
+
name: "content-files-system-properties",
|
|
854
|
+
sql: `ALTER TABLE document_property_definitions ADD COLUMN IF NOT EXISTS system_role TEXT;
|
|
855
|
+
ALTER TABLE content_databases ADD COLUMN IF NOT EXISTS files_system_properties_seeded INTEGER NOT NULL DEFAULT 0;
|
|
856
|
+
CREATE UNIQUE INDEX IF NOT EXISTS document_property_definitions_database_system_role_unique
|
|
857
|
+
ON document_property_definitions (database_id, system_role)`,
|
|
858
|
+
},
|
|
850
859
|
],
|
|
851
860
|
{ table: "content_migrations" },
|
|
852
861
|
);
|
|
@@ -922,4 +931,12 @@ export default async function contentDatabasePlugin(
|
|
|
922
931
|
// legacy databases without their primary Blocks field until a full reboot.
|
|
923
932
|
scheduleBlocksRepairRetry();
|
|
924
933
|
}
|
|
934
|
+
try {
|
|
935
|
+
await repairFilesSystemPropertyDefinitions();
|
|
936
|
+
} catch (err) {
|
|
937
|
+
console.warn(
|
|
938
|
+
"[db] Files system-property repair failed (non-fatal):",
|
|
939
|
+
err instanceof Error ? err.message : err,
|
|
940
|
+
);
|
|
941
|
+
}
|
|
925
942
|
}
|
|
@@ -168,6 +168,7 @@ export type {
|
|
|
168
168
|
export interface DocumentPropertyDefinition {
|
|
169
169
|
id: string;
|
|
170
170
|
databaseId: string | null;
|
|
171
|
+
systemRole?: DocumentPropertySystemRole | null;
|
|
171
172
|
name: string;
|
|
172
173
|
type: DocumentPropertyType;
|
|
173
174
|
description?: string;
|
|
@@ -178,6 +179,11 @@ export interface DocumentPropertyDefinition {
|
|
|
178
179
|
updatedAt: string;
|
|
179
180
|
}
|
|
180
181
|
|
|
182
|
+
export type DocumentPropertySystemRole =
|
|
183
|
+
| "files_kind"
|
|
184
|
+
| "files_parent"
|
|
185
|
+
| "files_source";
|
|
186
|
+
|
|
181
187
|
export interface DocumentProperty {
|
|
182
188
|
definition: DocumentPropertyDefinition;
|
|
183
189
|
value: DocumentPropertyValue;
|
|
@@ -227,6 +233,7 @@ export interface ContentDatabase {
|
|
|
227
233
|
id: string;
|
|
228
234
|
documentId: string;
|
|
229
235
|
title: string;
|
|
236
|
+
systemRole?: string | null;
|
|
230
237
|
description?: string;
|
|
231
238
|
viewConfig: ContentDatabaseViewConfig;
|
|
232
239
|
createdAt: string;
|
|
@@ -334,6 +341,8 @@ export interface ContentDatabaseViewConfig {
|
|
|
334
341
|
columnWidths: Record<string, number>;
|
|
335
342
|
}
|
|
336
343
|
|
|
344
|
+
export const CONTENT_DATABASE_PERSONAL_VIEW_OVERRIDES_VERSION = 2;
|
|
345
|
+
|
|
337
346
|
export interface ContentDatabasePersonalViewOverrides {
|
|
338
347
|
version: number;
|
|
339
348
|
activeViewId?: string;
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
ContentDatabaseFormQuestion,
|
|
3
|
+
ContentDatabaseView,
|
|
4
|
+
DocumentPropertySystemRole,
|
|
5
|
+
} from "./api";
|
|
2
6
|
import {
|
|
3
7
|
isComputedPropertyType,
|
|
4
8
|
type DocumentPropertyType,
|
|
@@ -8,6 +12,7 @@ export interface ContentDatabaseFormPropertyLike {
|
|
|
8
12
|
definition: {
|
|
9
13
|
id: string;
|
|
10
14
|
type: DocumentPropertyType;
|
|
15
|
+
systemRole?: DocumentPropertySystemRole | null;
|
|
11
16
|
};
|
|
12
17
|
}
|
|
13
18
|
|
|
@@ -18,7 +23,11 @@ export function contentDatabaseFormQuestions(
|
|
|
18
23
|
const availableKeys = [
|
|
19
24
|
"name",
|
|
20
25
|
...properties
|
|
21
|
-
.filter(
|
|
26
|
+
.filter(
|
|
27
|
+
(property) =>
|
|
28
|
+
!property.definition.systemRole &&
|
|
29
|
+
!isComputedPropertyType(property.definition.type),
|
|
30
|
+
)
|
|
22
31
|
.map((property) => property.definition.id),
|
|
23
32
|
];
|
|
24
33
|
const available = new Set(availableKeys);
|
|
@@ -429,6 +429,7 @@ export default defineConfig({
|
|
|
429
429
|
contentLocalComponentsPlugin(),
|
|
430
430
|
...reactRouterPlugins(),
|
|
431
431
|
...agentNativePlugins({
|
|
432
|
+
clientCompatibilityVersion: "content-spaces-v1",
|
|
432
433
|
fsAllow: [
|
|
433
434
|
...(localWorkspaceRoot ? [localWorkspaceRoot] : []),
|
|
434
435
|
...dynamicLocalComponentDirs,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const BUILD_CACHE_BUSTER_PARAM = "__an_build";
|
|
2
|
+
type CompatibilityWindow = Pick<Window, "location" | "history"> & {
|
|
3
|
+
sessionStorage?: Storage;
|
|
4
|
+
__agentNativeClientCompatibilityReload?: string;
|
|
5
|
+
};
|
|
6
|
+
export declare function clientBuildId(): string;
|
|
7
|
+
export declare function clientCompatibilityVersion(): string;
|
|
8
|
+
export declare function reloadForClientCompatibilityMismatch(serverBuildId: string, requiredCompatibility: string, win?: CompatibilityWindow | undefined): boolean;
|
|
9
|
+
export declare function stripBuildCompatibilityCacheBuster(win?: CompatibilityWindow | undefined): void;
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=build-compatibility.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-compatibility.d.ts","sourceRoot":"","sources":["../../src/client/build-compatibility.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB,eAAe,CAAC;AAErD,KAAK,mBAAmB,GAAG,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,SAAS,CAAC,GAAG;IAChE,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,sCAAsC,CAAC,EAAE,MAAM,CAAC;CACjD,CAAC;AAEF,wBAAgB,aAAa,IAAI,MAAM,CAQtC;AAED,wBAAgB,0BAA0B,IAAI,MAAM,CAWnD;AAiBD,wBAAgB,oCAAoC,CAClD,aAAa,EAAE,MAAM,EACrB,qBAAqB,EAAE,MAAM,EAC7B,GAAG,GAAE,mBAAmB,GAAG,SAEjB,GACT,OAAO,CAST;AAED,wBAAgB,kCAAkC,CAChD,GAAG,GAAE,mBAAmB,GAAG,SAEjB,GACT,IAAI,CAMN"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const RELOAD_MARKER_KEY = "__agentNativeClientCompatibilityReload";
|
|
2
|
+
export const BUILD_CACHE_BUSTER_PARAM = "__an_build";
|
|
3
|
+
export function clientBuildId() {
|
|
4
|
+
if (typeof __AGENT_NATIVE_BUILD_ID__ === "string") {
|
|
5
|
+
return __AGENT_NATIVE_BUILD_ID__;
|
|
6
|
+
}
|
|
7
|
+
return (globalThis
|
|
8
|
+
.__AGENT_NATIVE_BUILD_ID__ ?? "");
|
|
9
|
+
}
|
|
10
|
+
export function clientCompatibilityVersion() {
|
|
11
|
+
if (typeof __AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__ === "string") {
|
|
12
|
+
return __AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__;
|
|
13
|
+
}
|
|
14
|
+
return (globalThis.__AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__ ?? "");
|
|
15
|
+
}
|
|
16
|
+
function readReloadMarker(win) {
|
|
17
|
+
try {
|
|
18
|
+
return win.sessionStorage?.getItem(RELOAD_MARKER_KEY) ?? "";
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return win.__agentNativeClientCompatibilityReload ?? "";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function writeReloadMarker(win, marker) {
|
|
25
|
+
win.__agentNativeClientCompatibilityReload = marker;
|
|
26
|
+
try {
|
|
27
|
+
win.sessionStorage?.setItem(RELOAD_MARKER_KEY, marker);
|
|
28
|
+
}
|
|
29
|
+
catch { }
|
|
30
|
+
}
|
|
31
|
+
export function reloadForClientCompatibilityMismatch(serverBuildId, requiredCompatibility, win = typeof window === "undefined"
|
|
32
|
+
? undefined
|
|
33
|
+
: window) {
|
|
34
|
+
if (!win?.location)
|
|
35
|
+
return false;
|
|
36
|
+
const marker = `${requiredCompatibility}:${serverBuildId}`;
|
|
37
|
+
if (readReloadMarker(win) === marker)
|
|
38
|
+
return false;
|
|
39
|
+
writeReloadMarker(win, marker);
|
|
40
|
+
const target = new URL(win.location.href);
|
|
41
|
+
target.searchParams.set(BUILD_CACHE_BUSTER_PARAM, serverBuildId || "latest");
|
|
42
|
+
win.location.replace(target.href);
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
export function stripBuildCompatibilityCacheBuster(win = typeof window === "undefined"
|
|
46
|
+
? undefined
|
|
47
|
+
: window) {
|
|
48
|
+
if (!win?.location || !win.history)
|
|
49
|
+
return;
|
|
50
|
+
const target = new URL(win.location.href);
|
|
51
|
+
if (!target.searchParams.has(BUILD_CACHE_BUSTER_PARAM))
|
|
52
|
+
return;
|
|
53
|
+
target.searchParams.delete(BUILD_CACHE_BUSTER_PARAM);
|
|
54
|
+
win.history.replaceState(win.history.state, "", target.href);
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=build-compatibility.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-compatibility.js","sourceRoot":"","sources":["../../src/client/build-compatibility.ts"],"names":[],"mappings":"AAGA,MAAM,iBAAiB,GAAG,wCAAwC,CAAC;AACnE,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC;AAOrD,MAAM,UAAU,aAAa;IAC3B,IAAI,OAAO,yBAAyB,KAAK,QAAQ,EAAE,CAAC;QAClD,OAAO,yBA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AAC;IAC1C,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,wBAAwB,EAAE,aAAa,IAAI,QAAQ,CAAC,CAAC;IAC7E,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAClC,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,kCAAkC,CAChD,GAAG,GAAoC,OAAO,MAAM,KAAK,WAAW;IAClE,CAAC,CAAC,SAAS;IACX,CAAC,CAAC,MAAM;IAEV,IAAI,CAAC,GAAG,EAAE,QAAQ,IAAI,CAAC,GAAG,CAAC,OAAO;QAAE,OAAO;IAC3C,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC1C,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,wBAAwB,CAAC;QAAE,OAAO;IAC/D,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,wBAAwB,CAAC,CAAC;IACrD,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["declare const __AGENT_NATIVE_BUILD_ID__: string | undefined;\ndeclare const __AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__: string | undefined;\n\nconst RELOAD_MARKER_KEY = \"__agentNativeClientCompatibilityReload\";\nexport const BUILD_CACHE_BUSTER_PARAM = \"__an_build\";\n\ntype CompatibilityWindow = Pick<Window, \"location\" | \"history\"> & {\n sessionStorage?: Storage;\n __agentNativeClientCompatibilityReload?: string;\n};\n\nexport function clientBuildId(): string {\n if (typeof __AGENT_NATIVE_BUILD_ID__ === \"string\") {\n return __AGENT_NATIVE_BUILD_ID__;\n }\n return (\n (globalThis as typeof globalThis & { __AGENT_NATIVE_BUILD_ID__?: string })\n .__AGENT_NATIVE_BUILD_ID__ ?? \"\"\n );\n}\n\nexport function clientCompatibilityVersion(): string {\n if (typeof __AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__ === \"string\") {\n return __AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__;\n }\n return (\n (\n globalThis as typeof globalThis & {\n __AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__?: string;\n }\n ).__AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__ ?? \"\"\n );\n}\n\nfunction readReloadMarker(win: CompatibilityWindow): string {\n try {\n return win.sessionStorage?.getItem(RELOAD_MARKER_KEY) ?? \"\";\n } catch {\n return win.__agentNativeClientCompatibilityReload ?? \"\";\n }\n}\n\nfunction writeReloadMarker(win: CompatibilityWindow, marker: string): void {\n win.__agentNativeClientCompatibilityReload = marker;\n try {\n win.sessionStorage?.setItem(RELOAD_MARKER_KEY, marker);\n } catch {}\n}\n\nexport function reloadForClientCompatibilityMismatch(\n serverBuildId: string,\n requiredCompatibility: string,\n win: CompatibilityWindow | undefined = typeof window === \"undefined\"\n ? undefined\n : window,\n): boolean {\n if (!win?.location) return false;\n const marker = `${requiredCompatibility}:${serverBuildId}`;\n if (readReloadMarker(win) === marker) return false;\n writeReloadMarker(win, marker);\n const target = new URL(win.location.href);\n target.searchParams.set(BUILD_CACHE_BUSTER_PARAM, serverBuildId || \"latest\");\n win.location.replace(target.href);\n return true;\n}\n\nexport function stripBuildCompatibilityCacheBuster(\n win: CompatibilityWindow | undefined = typeof window === \"undefined\"\n ? undefined\n : window,\n): void {\n if (!win?.location || !win.history) return;\n const target = new URL(win.location.href);\n if (!target.searchParams.has(BUILD_CACHE_BUSTER_PARAM)) return;\n target.searchParams.delete(BUILD_CACHE_BUSTER_PARAM);\n win.history.replaceState(win.history.state, \"\", target.href);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/route-chunk-recovery/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/route-chunk-recovery/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/route-chunk-recovery/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC","sourcesContent":["export * from \"../route-chunk-recovery.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/route-chunk-recovery/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC","sourcesContent":["export * from \"../route-chunk-recovery.js\";\nexport * from \"../build-compatibility.js\";\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-action.d.ts","sourceRoot":"","sources":["../../src/client/use-action.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EACnB,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"use-action.d.ts","sourceRoot":"","sources":["../../src/client/use-action.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EACnB,MAAM,uBAAuB,CAAC;AAyC/B,mCAAmC;AACnC,wBAAgB,uBAAuB,CACrC,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,OAAO,GACb,OAAO,CAaT;AAED,+CAA+C;AAC/C,eAAO,MAAM,8BAA8B,gCAA0B,CAAC;AAwBtE;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAEzE;AAMD;;;;;GAKG;AACH,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,yBAAyB;KAAG;CACvC;AAED,MAAM,WAAW,cAAe,SAAQ,yBAAyB;CAAG;AAEpE,2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YAAY,CAAC,KAAK,CAAC,EAC5B,OAAO,CAAC,EAAE,IAAI,CACZ,eAAe,CAAC,OAAO,SAAS,SAAS,GAAG,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,EAC1E,UAAU,GAAG,SAAS,CACvB,6HAcF;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,GAAG,SAAS,EACjB,UAAU,GAAG,SAAS,EACtB,KAAK,SAAS,UAAU,GAAG,UAAU,EAErC,UAAU,EAAE,KAAK,EACjB,OAAO,CAAC,EAAE,IAAI,CACZ,kBAAkB,CAChB,KAAK,SAAS,SAAS,GAAG,YAAY,CAAC,KAAK,CAAC,GAAG,KAAK,EACrD,KAAK,EACL,UAAU,SAAS,SAAS,GAAG,YAAY,CAAC,KAAK,CAAC,GAAG,UAAU,CAChE,EACD,YAAY,CACb,GAAG;IACF,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;IACnC,2BAA2B,CAAC,EAAE,OAAO,CAAC;CACvC,6LA2BF"}
|
|
@@ -25,6 +25,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
|
25
25
|
import { trackEvent } from "./analytics.js";
|
|
26
26
|
import { agentNativePath } from "./api-path.js";
|
|
27
27
|
import { getBrowserTabId } from "./browser-tab-id.js";
|
|
28
|
+
import { clientBuildId, clientCompatibilityVersion, reloadForClientCompatibilityMismatch, } from "./build-compatibility.js";
|
|
28
29
|
import { ensureEmbedAuthFetchInterceptor } from "./embed-auth.js";
|
|
29
30
|
const ACTION_PREFIX = agentNativePath("/_agent-native/actions");
|
|
30
31
|
/**
|
|
@@ -177,6 +178,13 @@ async function performActionFetch(name, method, params, options) {
|
|
|
177
178
|
}
|
|
178
179
|
: {}),
|
|
179
180
|
};
|
|
181
|
+
const compatibilityVersion = clientCompatibilityVersion();
|
|
182
|
+
if (compatibilityVersion) {
|
|
183
|
+
headers["X-Agent-Native-Client-Compatibility"] = compatibilityVersion;
|
|
184
|
+
}
|
|
185
|
+
const buildId = clientBuildId();
|
|
186
|
+
if (buildId)
|
|
187
|
+
headers["X-Agent-Native-Build-Id"] = buildId;
|
|
180
188
|
const tz = resolveUserTimezone();
|
|
181
189
|
if (tz)
|
|
182
190
|
headers["x-user-timezone"] = tz;
|
|
@@ -246,6 +254,16 @@ async function performActionFetch(name, method, params, options) {
|
|
|
246
254
|
const cause = err instanceof Error ? err.message : String(err);
|
|
247
255
|
throw new Error(`Action ${name} failed: ${cause}`);
|
|
248
256
|
}
|
|
257
|
+
if (res.status === 409 &&
|
|
258
|
+
res.headers.get("X-Agent-Native-Client-Mismatch") === "1") {
|
|
259
|
+
const serverBuildId = res.headers.get("X-Agent-Native-Build-Id") ?? "latest";
|
|
260
|
+
const requiredCompatibility = res.headers.get("X-Agent-Native-Client-Compatibility") ?? "unknown";
|
|
261
|
+
reloadForClientCompatibilityMismatch(serverBuildId, requiredCompatibility);
|
|
262
|
+
const error = new Error(`Action ${name} requires a refreshed browser client`);
|
|
263
|
+
error.status = 409;
|
|
264
|
+
error.code = "client_build_mismatch";
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
249
267
|
// 204 No Content — nothing to parse.
|
|
250
268
|
if (res.status === 204)
|
|
251
269
|
return null;
|
|
@@ -541,7 +559,7 @@ export function useActionMutation(actionName, options) {
|
|
|
541
559
|
if (!skipActionQueryInvalidation) {
|
|
542
560
|
queryClient.invalidateQueries({ queryKey: ["action"] });
|
|
543
561
|
}
|
|
544
|
-
onSuccess?.(...args);
|
|
562
|
+
return onSuccess?.(...args);
|
|
545
563
|
},
|
|
546
564
|
});
|
|
547
565
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-action.js","sourceRoot":"","sources":["../../src/client/use-action.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,uBA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AK,EAAE,uBAAuB;QAC9B,UAAU,EAAE,4BAA4B;QACxC,GAAG,OAAO;KACX,CAAC,CAAC;AACL,CAAC;AAED,8EAA8E;AAC9E,gBAAgB;AAChB,8EAA8E;AAE9E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,iBAAiB,CAK/B,UAAiB,EACjB,OAUC;IAED,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;IACrC,MAAM,EACJ,MAAM,EAAE,SAAS,EACjB,SAAS,EACT,2BAA2B,GAAG,KAAK,EACnC,GAAG,WAAW,EACf,GAAG,OAAO,IAAK,EAAU,CAAC;IAC3B,MAAM,MAAM,GAAG,SAAS,IAAI,MAAM,CAAC;IAKnC,OAAO,WAAW,CAAc;QAC9B,GAAG,WAAW;QACd,UAAU,EAAE,CAAC,MAAM,EAAE,EAAE,CACrB,WAAW,CAAI,UAAU,EAAE,MAAM,EAAE,MAA6B,CAAC;QACnE,SAAS,EAAE,CAAC,GAAG,IAAqB,EAAE,EAAE;YACtC,iEAAiE;YACjE,wEAAwE;YACxE,IAAI,CAAC,2BAA2B,EAAE,CAAC;gBACjC,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;YAC1D,CAAC;YACA,SAAsB,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QACrC,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Client helpers for calling actions through the framework transport.\n *\n * Components should prefer `useActionQuery` / `useActionMutation`; use\n * `callAction` for imperative cases such as debounced search, prefetching, or\n * event handlers that do not fit a hook.\n *\n * ## End-to-end type safety\n *\n * When the action type registry is generated (via the Vite plugin or CLI),\n * `useActionQuery` and `useActionMutation` automatically infer the correct\n * return type and parameter types from the action definitions — no manual\n * type annotations needed.\n *\n * ```ts\n * // Fully typed — return type and params inferred from the action's defineAction()\n * const { data } = useActionQuery(\"list-forms\", { status: \"published\" });\n * // ^? Form[] (inferred from the action's run() return type)\n * ```\n *\n * Without the registry, the hooks fall back to `any` types for backward\n * compatibility.\n */\nimport { useQuery, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport type {\n UseQueryOptions,\n UseMutationOptions,\n} from \"@tanstack/react-query\";\n\nimport { trackEvent } from \"./analytics.js\";\nimport { agentNativePath } from \"./api-path.js\";\nimport { getBrowserTabId } from \"./browser-tab-id.js\";\nimport { ensureEmbedAuthFetchInterceptor } from \"./embed-auth.js\";\n\nconst ACTION_PREFIX = agentNativePath(\"/_agent-native/actions\");\n\n/**\n * Upper bound on how long a single action fetch may stay in flight (headers\n * AND body). Converts a hung server/proxy/connection into a visible, typed\n * failure instead of a UI that spins forever. Generous on purpose: it sits\n * above every server-side budget (serverless function limits, hosted run\n * wall-clock), so it only fires when something is genuinely stuck.\n */\nconst DEFAULT_ACTION_TIMEOUT_MS = 60_000;\n\nfunction isAuthFailure(error: unknown): boolean {\n return (\n !!error &&\n typeof error === \"object\" &&\n \"status\" in error &&\n ((error as { status?: unknown }).status === 401 ||\n (error as { status?: unknown }).status === 403)\n );\n}\n\nfunction isActionTimeout(error: unknown): boolean {\n return (\n !!error &&\n typeof error === \"object\" &&\n (error as { timedOut?: unknown }).timedOut === true\n );\n}\n\n/** @internal exported for tests */\nexport function defaultActionQueryRetry(\n failureCount: number,\n error: unknown,\n): boolean {\n if (isAuthFailure(error)) return false;\n // A timeout already made the user wait the full timeout window once;\n // silently retrying would multiply that wait. Surface it instead.\n if (isActionTimeout(error)) return false;\n if (isBrowserResourceExhaustion(error)) return false;\n // Network-level failures never carry an HTTP `status` (actionFetch only\n // sets it after a response arrives). Chrome reports connection-pool\n // exhaustion (net::ERR_INSUFFICIENT_RESOURCES) as a generic \"Failed to\n // fetch\", indistinguishable from a transient blip — allow one retry, not\n // three, so an exhausted tab cannot sustain its own fetch storm.\n if (isNetworkLevelFailure(error)) return failureCount < 1;\n return failureCount < 3;\n}\n\n/** @internal alias kept for existing specs. */\nexport const shouldRetryActionQueryForError = defaultActionQueryRetry;\n\nfunction isBrowserResourceExhaustion(error: unknown): boolean {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\";\n return /ERR_INSUFFICIENT_RESOURCES|insufficient resources/i.test(message);\n}\n\nfunction isNetworkLevelFailure(error: unknown): boolean {\n // Match the exact shape actionFetch produces for fetch-level failures (its\n // catch wraps the cause as \"Action <name> failed: <cause>\" and never sets a\n // status). Other status-less errors (test doubles, transport internals)\n // keep the standard three-retry policy.\n return (\n error instanceof Error &&\n (error as { status?: unknown }).status === undefined &&\n /^Action .+ failed: /.test(error.message)\n );\n}\n\n/**\n * Default retry backoff for action queries. React Query's stock retryDelay\n * (1s → 2s → 4s) makes a failing query sit on a spinner for ~7s before the\n * error surfaces; interactive data fetches want failures visible fast.\n *\n * @internal exported for tests\n */\nexport function defaultActionQueryRetryDelay(failureCount: number): number {\n return Math.min(500 * 2 ** failureCount, 2_000);\n}\n\n// ---------------------------------------------------------------------------\n// Action type registry — augmented by generated code\n// ---------------------------------------------------------------------------\n\n/**\n * Action type registry. This interface is empty by default and gets augmented\n * by the auto-generated `.generated/action-types.d.ts` file. When augmented,\n * it maps action names to their parameter and return types, enabling\n * end-to-end type safety for `useActionQuery` and `useActionMutation`.\n */\ndeclare global {\n interface AgentNativeActionRegistry {}\n}\n\nexport interface ActionRegistry extends AgentNativeActionRegistry {}\n\n/** Resolves to the union of registered action names, or `string` if no registry exists. */\ntype ActionName = keyof ActionRegistry extends never\n ? string\n : (keyof ActionRegistry & string) | (string & {});\n\n/** Resolves the return type of an action, or `any` if not in the registry. */\ntype ActionResult<T extends string> = T extends keyof ActionRegistry\n ? ActionRegistry[T] extends { result: infer R }\n ? R\n : any\n : any;\n\n/** Resolves the parameter type of an action, or `Record<string, any>` if not in the registry. */\ntype ActionParams<T extends string> = T extends keyof ActionRegistry\n ? ActionRegistry[T] extends { params: infer P }\n ? P\n : Record<string, any>\n : Record<string, any>;\n\nexport type ClientActionMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n\nexport interface ClientActionCallOptions {\n method?: ClientActionMethod;\n /** Abort signal for the underlying fetch. */\n signal?: AbortSignal;\n /** Override the default 60s fetch timeout for long-running actions. */\n timeoutMs?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Fetch helper\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the browser's IANA timezone (e.g. \"America/Los_Angeles\"). This is\n * sent on every action request as `x-user-timezone` so server-side defaults\n * like \"today\" honor the user's local day rather than the server's UTC clock.\n */\nfunction resolveUserTimezone(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function serializeActionQueryParams(\n params: Record<string, any>,\n): string {\n const qs = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n appendActionQueryParam(qs, key, value);\n }\n return qs.toString();\n}\n\nfunction appendActionQueryParam(\n qs: URLSearchParams,\n key: string,\n value: unknown,\n) {\n if (value === null || value === undefined) return;\n if (Array.isArray(value)) {\n // Use bracket keys so a one-item array still arrives as an array after the\n // server parses URLSearchParams. Repeated bare keys lose that distinction.\n for (const item of value) {\n appendActionQueryParam(qs, `${key}[]`, item);\n }\n return;\n }\n qs.append(key, String(value));\n}\n\nexport interface ActionFetchOptions {\n /**\n * Abort signal from the caller (React Query passes one per queryFn\n * invocation so superseded requests — key change, unmount, refetch — cancel\n * the underlying network request instead of hogging a connection slot).\n */\n signal?: AbortSignal;\n /** Per-call override for the fetch timeout. */\n timeoutMs?: number;\n /** Keep the request alive while the document is being unloaded. */\n keepalive?: boolean;\n /** Pre-serialized mutation body used by the keepalive budget coordinator. */\n serializedBody?: string;\n /** Omit the tab echo-suppression tag for imperative callers. */\n includeRequestSource?: boolean;\n}\n\ntype InternalActionFetchOptions = ActionFetchOptions & {\n onResponse?: (response: Response) => void;\n};\n\n/**\n * Conservative per-document keepalive body budget. Browsers commonly enforce\n * an approximately 64 KiB aggregate limit across every in-flight keepalive\n * request; leaving headroom for other framework traffic prevents a request\n * that passed our guard from being rejected by the browser at send time.\n */\nexport const ACTION_KEEPALIVE_BODY_BUDGET_BYTES = 48_000;\n\nlet reservedKeepaliveBodyBytes = 0;\n\nfunction utf8ByteLength(value: string): number {\n if (typeof TextEncoder !== \"undefined\") {\n return new TextEncoder().encode(value).byteLength;\n }\n\n let bytes = 0;\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n bytes +=\n codePoint <= 0x7f\n ? 1\n : codePoint <= 0x7ff\n ? 2\n : codePoint <= 0xffff\n ? 3\n : 4;\n }\n return bytes;\n}\n\nasync function performActionFetch<T>(\n name: string,\n method: string,\n params?: Record<string, any>,\n options?: InternalActionFetchOptions,\n): Promise<T> {\n ensureEmbedAuthFetchInterceptor();\n let url = `${ACTION_PREFIX}/${name}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n // Tag browser-originated action calls so the server can set\n // `ctx.caller = \"frontend\"` (vs a bare programmatic `\"http\"` POST).\n // Mirrors the X-Agent-Native-Tool-Bridge: 1 convention. The header is\n // safe to expose: CORS allows it (see action-routes.ts) and it carries\n // no auth weight — it only narrows the caller tag.\n \"X-Agent-Native-Frontend\": \"1\",\n ...(options?.includeRequestSource !== false\n ? {\n // The server copies this onto the emitted action sync event.\n // useDbSync can then ignore the echo in this tab while other tabs\n // still refresh.\n \"X-Request-Source\": getBrowserTabId(),\n }\n : {}),\n };\n const tz = resolveUserTimezone();\n if (tz) headers[\"x-user-timezone\"] = tz;\n const init: RequestInit = {\n method,\n headers,\n cache: \"no-store\",\n keepalive: options?.keepalive,\n };\n\n if (method === \"GET\" && params && Object.keys(params).length > 0) {\n // Skip null/undefined so optional filters don't turn into literal \"null\"\n // strings in the query string (e.g. `?folderId=null`).\n const qs = serializeActionQueryParams(params);\n if (qs) url += `?${qs}`;\n } else if (method !== \"GET\" && params) {\n init.body = options?.serializedBody ?? JSON.stringify(params);\n }\n\n // One controller drives both cancellation sources: the caller's signal\n // (superseded query, unmount) and the timeout. The timer stays armed until\n // the BODY is fully read — headers arriving quickly while the body stalls\n // is exactly the hang this bounds.\n const outerSignal = options?.signal;\n const timeoutMs = options?.timeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS;\n const controller =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n const onOuterAbort = () => controller?.abort();\n if (outerSignal && controller) {\n if (outerSignal.aborted) controller.abort();\n else outerSignal.addEventListener(\"abort\", onOuterAbort, { once: true });\n }\n let timedOut = false;\n const timer = controller\n ? setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs)\n : null;\n if (controller) init.signal = controller.signal;\n\n const throwTimeout = (): never => {\n const error = new Error(\n `Action ${name} timed out after ${Math.round(timeoutMs / 1000)}s`,\n );\n (error as any).timedOut = true;\n (error as any).status = 408;\n throw error;\n };\n\n let res: Response;\n let raw = \"\";\n let readFailed = false;\n let readError: unknown;\n try {\n try {\n res = await fetch(url, init);\n options?.onResponse?.(res);\n } catch (err) {\n if (timedOut) throwTimeout();\n // Caller-initiated cancellation — rethrow untouched so React Query\n // recognizes it as a cancellation rather than a query failure.\n if (outerSignal?.aborted) throw err;\n // Network failures, CORS, server unreachable, etc. — give the caller a\n // useful message instead of the opaque \"Failed to fetch\".\n const cause = err instanceof Error ? err.message : String(err);\n throw new Error(`Action ${name} failed: ${cause}`);\n }\n\n // 204 No Content — nothing to parse.\n if (res.status === 204) return null as T;\n\n // Read the body as text first so we can:\n // - tolerate empty bodies (avoids \"Unexpected end of JSON input\")\n // - surface non-JSON error responses (HTML 401/404 pages, plain text, etc.)\n // - preserve the original HTTP status in the thrown error\n // Track read failures separately from \"no body\" — a stream interruption /\n // decode failure on a 2xx response should error rather than silently\n // succeed with `null`.\n try {\n raw = await res.text();\n } catch (err) {\n if (timedOut) throwTimeout();\n if (outerSignal?.aborted) throw err;\n readFailed = true;\n readError = err;\n }\n } finally {\n if (timer) clearTimeout(timer);\n if (outerSignal) outerSignal.removeEventListener(\"abort\", onOuterAbort);\n }\n\n let data: any = undefined;\n let parseFailed = false;\n if (raw.length > 0) {\n try {\n data = JSON.parse(raw);\n } catch {\n // Body wasn't JSON — keep `data` undefined and use the raw text below.\n parseFailed = true;\n }\n }\n\n if (!res.ok) {\n const message =\n (data && (data.error || data.message)) ||\n // Truncate non-JSON bodies so we don't dump entire HTML pages into the\n // console, but still give the developer a hint as to what came back.\n (raw && raw.slice(0, 200)) ||\n res.statusText ||\n `HTTP ${res.status}`;\n const error = new Error(`Action ${name} failed: ${message}`);\n (error as any).status = res.status;\n throw error;\n }\n\n // 2xx but the body couldn't even be read (mid-stream abort, decode failure,\n // etc.). Don't silently treat that as a `null` success.\n if (readFailed) {\n const cause =\n readError instanceof Error ? readError.message : String(readError);\n const error = new Error(\n `Action ${name} returned ${res.status} but the body could not be read: ${cause}`,\n );\n (error as any).status = res.status;\n throw error;\n }\n\n // 2xx with a non-empty, non-JSON body. Action callers expect typed data, so\n // returning `null` here would silently mask a real server bug (e.g. a proxy\n // returning HTML 200 instead of JSON). Throw instead — empty bodies (handled\n // above by the `raw.length > 0` guard and the 204 short-circuit) still\n // correctly resolve to `null`.\n if (parseFailed) {\n const error = new Error(\n `Action ${name} returned a non-JSON ${res.status} response: ${raw.slice(0, 200)}`,\n );\n (error as any).status = res.status;\n throw error;\n }\n\n return (data ?? (null as unknown)) as T;\n}\n\nfunction actionTelemetryNow(): number {\n return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nfunction parseServerTiming(\n response: Response | undefined,\n): Map<string, number> {\n const timings = new Map<string, number>();\n const value = response?.headers.get(\"server-timing\");\n if (!value) return timings;\n\n for (const entry of value.split(\",\")) {\n const [rawName, ...params] = entry.trim().split(\";\");\n const name = rawName?.trim();\n if (!name) continue;\n const duration = params\n .map((param) => /^dur=(.+)$/i.exec(param.trim())?.[1])\n .find(Boolean);\n const parsed = duration === undefined ? NaN : Number(duration);\n if (Number.isFinite(parsed)) timings.set(name, parsed);\n }\n return timings;\n}\n\nfunction shouldTrackActionResponse(\n error: unknown,\n durationMs: number,\n response: Response | undefined,\n): boolean {\n if (error || durationMs >= 1_000) return true;\n if (response && response.status >= 400 && response.status < 500) return true;\n if (\n /\\bstartup(?:-db)?\\s*;/i.test(response?.headers.get(\"server-timing\") ?? \"\")\n ) {\n return true;\n }\n const raw = (import.meta.env as Record<string, string | undefined>)\n ?.VITE_AGENT_NATIVE_ACTION_TELEMETRY_SAMPLE_RATE;\n const parsed = raw === undefined ? 0.1 : Number(raw);\n const rate = Number.isFinite(parsed) ? Math.max(0, Math.min(1, parsed)) : 0.1;\n return Math.random() < rate;\n}\n\nasync function actionFetch<T>(\n name: string,\n method: string,\n params?: Record<string, any>,\n options?: ActionFetchOptions,\n): Promise<T> {\n const startedAt = actionTelemetryNow();\n let response: Response | undefined;\n let responseAt: number | undefined;\n let error: unknown;\n\n try {\n return await performActionFetch<T>(name, method, params, {\n ...options,\n onResponse: (nextResponse) => {\n response = nextResponse;\n responseAt = actionTelemetryNow();\n },\n });\n } catch (caught) {\n error = caught;\n throw caught;\n } finally {\n try {\n const completedAt = actionTelemetryNow();\n const durationMs = Math.max(0, completedAt - startedAt);\n if (shouldTrackActionResponse(error, durationMs, response)) {\n const ttfbMs =\n responseAt === undefined\n ? undefined\n : Math.max(0, responseAt - startedAt);\n const serverTiming = parseServerTiming(response);\n const serverDurationMs = serverTiming.get(\"app\");\n const errorStatus = Number(\n (error as { status?: unknown } | undefined)?.status,\n );\n const statusCode =\n response?.status ??\n (Number.isFinite(errorStatus) ? errorStatus : undefined);\n const timedOut =\n (error as { timedOut?: unknown } | undefined)?.timedOut === true;\n const cancelled = options?.signal?.aborted === true && !timedOut;\n const contentLength = Number(response?.headers.get(\"content-length\"));\n\n trackEvent(\"action.response\", {\n request_id:\n response?.headers.get(\"x-agent-native-request-id\") ?? undefined,\n action: name,\n method,\n status_code: statusCode,\n status_class:\n statusCode === undefined\n ? \"network\"\n : `${Math.floor(statusCode / 100)}xx`,\n success: !error,\n outcome: !error\n ? \"success\"\n : timedOut\n ? \"timeout\"\n : cancelled\n ? \"cancelled\"\n : response\n ? \"http-error\"\n : \"network-error\",\n duration_ms: Math.round(durationMs),\n ttfb_ms: ttfbMs === undefined ? undefined : Math.round(ttfbMs),\n body_ms:\n ttfbMs === undefined ? undefined : Math.round(durationMs - ttfbMs),\n server_duration_ms:\n serverDurationMs === undefined\n ? undefined\n : Math.round(serverDurationMs),\n network_overhead_ms:\n ttfbMs === undefined || serverDurationMs === undefined\n ? undefined\n : Math.max(0, Math.round(ttfbMs - serverDurationMs)),\n framework_ready_wait_ms: serverTiming.get(\"startup\"),\n db_operation_wall_ms: serverTiming.get(\"db\"),\n db_connect_total_ms: serverTiming.get(\"db-connect\"),\n db_slowest_operation_ms: serverTiming.get(\"db-slowest\"),\n startup_db_operation_wall_ms: serverTiming.get(\"startup-db\"),\n startup_db_connect_total_ms: serverTiming.get(\"startup-db-connect\"),\n response_bytes:\n Number.isFinite(contentLength) && contentLength >= 0\n ? contentLength\n : undefined,\n });\n }\n } catch {\n // Performance telemetry must never change the action result.\n }\n }\n}\n\n/**\n * Imperatively call an action from browser/client code.\n *\n * Prefer `useActionQuery` / `useActionMutation` in React render flows. Use this\n * helper when a hook is not ergonomic; do not hand-write fetch calls to\n * `/_agent-native/actions/*` in components.\n */\nexport function callAction<\n TResult = undefined,\n TName extends ActionName = ActionName,\n>(\n actionName: TName,\n params?: ActionParams<TName>,\n options: ClientActionCallOptions = {},\n): Promise<TResult extends undefined ? ActionResult<TName> : TResult> {\n type R = TResult extends undefined ? ActionResult<TName> : TResult;\n return actionFetch<R>(actionName, options.method ?? \"POST\", params, {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n includeRequestSource: false,\n });\n}\n\nexport type KeepaliveActionCallRejectionReason =\n | \"body-too-large\"\n | \"budget-exhausted\";\n\nexport type KeepaliveActionCallResult<TResult> =\n | {\n accepted: true;\n bodyBytes: number;\n completion: Promise<TResult>;\n }\n | {\n accepted: false;\n bodyBytes: number;\n reason: KeepaliveActionCallRejectionReason;\n completion: null;\n };\n\n/**\n * Attempts an unload-safe action call without exceeding the browser's shared\n * keepalive request budget. The reservation remains held until the response\n * body has completed, because browsers count every in-flight keepalive body\n * against the same per-document quota.\n *\n * A rejected attempt is deliberately synchronous so callers can fall back to\n * a durable outbox before returning from `pagehide`.\n */\nexport function tryCallActionKeepalive<\n TResult = undefined,\n TName extends ActionName = ActionName,\n>(\n actionName: TName,\n params?: ActionParams<TName>,\n options: Omit<ClientActionCallOptions, \"method\"> = {},\n): KeepaliveActionCallResult<\n TResult extends undefined ? ActionResult<TName> : TResult\n> {\n type R = TResult extends undefined ? ActionResult<TName> : TResult;\n const serializedBody = JSON.stringify(params ?? {});\n const bodyBytes = utf8ByteLength(serializedBody);\n\n if (bodyBytes > ACTION_KEEPALIVE_BODY_BUDGET_BYTES) {\n return {\n accepted: false,\n bodyBytes,\n reason: \"body-too-large\",\n completion: null,\n };\n }\n\n if (\n reservedKeepaliveBodyBytes + bodyBytes >\n ACTION_KEEPALIVE_BODY_BUDGET_BYTES\n ) {\n return {\n accepted: false,\n bodyBytes,\n reason: \"budget-exhausted\",\n completion: null,\n };\n }\n\n reservedKeepaliveBodyBytes += bodyBytes;\n const completion = actionFetch<R>(actionName, \"POST\", params, {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n keepalive: true,\n serializedBody,\n }).finally(() => {\n reservedKeepaliveBodyBytes = Math.max(\n 0,\n reservedKeepaliveBodyBytes - bodyBytes,\n );\n });\n\n return { accepted: true, bodyBytes, completion };\n}\n\n// ---------------------------------------------------------------------------\n// Query hook\n// ---------------------------------------------------------------------------\n\n/**\n * Query an action exposed as GET.\n *\n * When the action type registry is generated, the return type and parameter\n * types are inferred automatically from the action's `defineAction()` call.\n *\n * ```ts\n * // Type-safe — no manual generic needed\n * const { data } = useActionQuery(\"list-meals\", { date: \"2025-01-01\" });\n *\n * // Manual override still works when needed\n * const { data } = useActionQuery<CustomType>(\"list-meals\");\n * ```\n */\nexport function useActionQuery<\n TResult = undefined,\n TName extends ActionName = ActionName,\n>(\n actionName: TName,\n params?: ActionParams<TName>,\n options?: Omit<\n UseQueryOptions<TResult extends undefined ? ActionResult<TName> : TResult>,\n \"queryKey\" | \"queryFn\"\n >,\n) {\n type R = TResult extends undefined ? ActionResult<TName> : TResult;\n return useQuery<R>({\n queryKey: [\"action\", actionName, params],\n // Thread React Query's per-fetch AbortSignal into the network request so\n // superseded fetches (key change, unmount, rapid refetch) actually cancel\n // instead of holding a per-origin connection slot until they finish.\n queryFn: ({ signal }) =>\n actionFetch<R>(actionName, \"GET\", params, { signal }),\n retry: defaultActionQueryRetry,\n retryDelay: defaultActionQueryRetryDelay,\n ...options,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Mutation hook\n// ---------------------------------------------------------------------------\n\n/**\n * Mutate via an action exposed as POST (default), PUT, or DELETE.\n *\n * When the action type registry is generated, the return type and parameter\n * types are inferred automatically.\n *\n * ```ts\n * // Type-safe\n * const { mutate } = useActionMutation(\"log-meal\");\n * mutate({ name: \"Salad\", calories: 350 });\n * ```\n */\nexport function useActionMutation<\n TData = undefined,\n TVariables = undefined,\n TName extends ActionName = ActionName,\n>(\n actionName: TName,\n options?: Omit<\n UseMutationOptions<\n TData extends undefined ? ActionResult<TName> : TData,\n Error,\n TVariables extends undefined ? ActionParams<TName> : TVariables\n >,\n \"mutationFn\"\n > & {\n method?: \"POST\" | \"PUT\" | \"DELETE\";\n skipActionQueryInvalidation?: boolean;\n },\n) {\n const queryClient = useQueryClient();\n const {\n method: methodOpt,\n onSuccess,\n skipActionQueryInvalidation = false,\n ...restOptions\n } = options ?? ({} as any);\n const method = methodOpt ?? \"POST\";\n\n type D = TData extends undefined ? ActionResult<TName> : TData;\n type V = TVariables extends undefined ? ActionParams<TName> : TVariables;\n\n return useMutation<D, Error, V>({\n ...restOptions,\n mutationFn: (params) =>\n actionFetch<D>(actionName, method, params as Record<string, any>),\n onSuccess: (...args: [any, any, any]) => {\n // Most mutations change app data broadly. High-volume background\n // mutations can opt out and perform narrower invalidation in onSuccess.\n if (!skipActionQueryInvalidation) {\n queryClient.invalidateQueries({ queryKey: [\"action\"] });\n }\n (onSuccess as Function)?.(...args);\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-action.js","sourceRoot":"","sources":["../../src/client/use-action.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAM9E,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EACL,aAAa,EACb,0BAA0B,EAC1B,oCAAoC,GACrC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,+BAA+B,EAAE,MAAM,iBAAiB,CAAC;AAElE,MAAM,aAAa,GAAG,eAAe,CAAC,wBAAwB,CAAC,CAAC;AAEhE;;;;;;GAMG;AACH,MAAM,yBAAyB,GAAG,MAAM,CAAC;AAEzC,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,CACL,CAAC,CAAC,KAAK;QACP,OAAO,KAAK,KAAK,QAAQ;QACzB,QAAQ,IAAI,KAAK;QACjB,CAAE,KAA8B,CAAC,MAAM,KAAK,GAAG;YAC5C,KAA8B,CAAC,MAAM,KAAK,GAAG,CAAC,CAClD,CAAC;AACJ,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACrC,OAAO,CACL,CAAC,CAAC,KAAK;QACP,OAAO,KAAK,KAAK,QAAQ;QACxB,KAAgC,CAAC,QAAQ,KAAK,IAAI,CACpD,CAAC;AACJ,CAAC;AAED,mCAAmC;AACnC,MAAM,UAAU,uBAAuB,CACrC,YAAoB,EACpB,KAAc;IAEd,IAAI,aAAa,CAAC,KAAK,CAAC;QAAE,O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uB;QAC9B,UAAU,EAAE,4BAA4B;QACxC,GAAG,OAAO;KACX,CAAC,CAAC;AACL,CAAC;AAED,8EAA8E;AAC9E,gBAAgB;AAChB,8EAA8E;AAE9E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,iBAAiB,CAK/B,UAAiB,EACjB,OAUC;IAED,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;IACrC,MAAM,EACJ,MAAM,EAAE,SAAS,EACjB,SAAS,EACT,2BAA2B,GAAG,KAAK,EACnC,GAAG,WAAW,EACf,GAAG,OAAO,IAAK,EAAU,CAAC;IAC3B,MAAM,MAAM,GAAG,SAAS,IAAI,MAAM,CAAC;IAKnC,OAAO,WAAW,CAAc;QAC9B,GAAG,WAAW;QACd,UAAU,EAAE,CAAC,MAAM,EAAE,EAAE,CACrB,WAAW,CAAI,UAAU,EAAE,MAAM,EAAE,MAA6B,CAAC;QACnE,SAAS,EAAE,CAAC,GAAG,IAAqB,EAAE,EAAE;YACtC,iEAAiE;YACjE,wEAAwE;YACxE,IAAI,CAAC,2BAA2B,EAAE,CAAC;gBACjC,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;YAC1D,CAAC;YACD,OAAQ,SAAsB,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QAC5C,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Client helpers for calling actions through the framework transport.\n *\n * Components should prefer `useActionQuery` / `useActionMutation`; use\n * `callAction` for imperative cases such as debounced search, prefetching, or\n * event handlers that do not fit a hook.\n *\n * ## End-to-end type safety\n *\n * When the action type registry is generated (via the Vite plugin or CLI),\n * `useActionQuery` and `useActionMutation` automatically infer the correct\n * return type and parameter types from the action definitions — no manual\n * type annotations needed.\n *\n * ```ts\n * // Fully typed — return type and params inferred from the action's defineAction()\n * const { data } = useActionQuery(\"list-forms\", { status: \"published\" });\n * // ^? Form[] (inferred from the action's run() return type)\n * ```\n *\n * Without the registry, the hooks fall back to `any` types for backward\n * compatibility.\n */\nimport { useQuery, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport type {\n UseQueryOptions,\n UseMutationOptions,\n} from \"@tanstack/react-query\";\n\nimport { trackEvent } from \"./analytics.js\";\nimport { agentNativePath } from \"./api-path.js\";\nimport { getBrowserTabId } from \"./browser-tab-id.js\";\nimport {\n clientBuildId,\n clientCompatibilityVersion,\n reloadForClientCompatibilityMismatch,\n} from \"./build-compatibility.js\";\nimport { ensureEmbedAuthFetchInterceptor } from \"./embed-auth.js\";\n\nconst ACTION_PREFIX = agentNativePath(\"/_agent-native/actions\");\n\n/**\n * Upper bound on how long a single action fetch may stay in flight (headers\n * AND body). Converts a hung server/proxy/connection into a visible, typed\n * failure instead of a UI that spins forever. Generous on purpose: it sits\n * above every server-side budget (serverless function limits, hosted run\n * wall-clock), so it only fires when something is genuinely stuck.\n */\nconst DEFAULT_ACTION_TIMEOUT_MS = 60_000;\n\nfunction isAuthFailure(error: unknown): boolean {\n return (\n !!error &&\n typeof error === \"object\" &&\n \"status\" in error &&\n ((error as { status?: unknown }).status === 401 ||\n (error as { status?: unknown }).status === 403)\n );\n}\n\nfunction isActionTimeout(error: unknown): boolean {\n return (\n !!error &&\n typeof error === \"object\" &&\n (error as { timedOut?: unknown }).timedOut === true\n );\n}\n\n/** @internal exported for tests */\nexport function defaultActionQueryRetry(\n failureCount: number,\n error: unknown,\n): boolean {\n if (isAuthFailure(error)) return false;\n // A timeout already made the user wait the full timeout window once;\n // silently retrying would multiply that wait. Surface it instead.\n if (isActionTimeout(error)) return false;\n if (isBrowserResourceExhaustion(error)) return false;\n // Network-level failures never carry an HTTP `status` (actionFetch only\n // sets it after a response arrives). Chrome reports connection-pool\n // exhaustion (net::ERR_INSUFFICIENT_RESOURCES) as a generic \"Failed to\n // fetch\", indistinguishable from a transient blip — allow one retry, not\n // three, so an exhausted tab cannot sustain its own fetch storm.\n if (isNetworkLevelFailure(error)) return failureCount < 1;\n return failureCount < 3;\n}\n\n/** @internal alias kept for existing specs. */\nexport const shouldRetryActionQueryForError = defaultActionQueryRetry;\n\nfunction isBrowserResourceExhaustion(error: unknown): boolean {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\";\n return /ERR_INSUFFICIENT_RESOURCES|insufficient resources/i.test(message);\n}\n\nfunction isNetworkLevelFailure(error: unknown): boolean {\n // Match the exact shape actionFetch produces for fetch-level failures (its\n // catch wraps the cause as \"Action <name> failed: <cause>\" and never sets a\n // status). Other status-less errors (test doubles, transport internals)\n // keep the standard three-retry policy.\n return (\n error instanceof Error &&\n (error as { status?: unknown }).status === undefined &&\n /^Action .+ failed: /.test(error.message)\n );\n}\n\n/**\n * Default retry backoff for action queries. React Query's stock retryDelay\n * (1s → 2s → 4s) makes a failing query sit on a spinner for ~7s before the\n * error surfaces; interactive data fetches want failures visible fast.\n *\n * @internal exported for tests\n */\nexport function defaultActionQueryRetryDelay(failureCount: number): number {\n return Math.min(500 * 2 ** failureCount, 2_000);\n}\n\n// ---------------------------------------------------------------------------\n// Action type registry — augmented by generated code\n// ---------------------------------------------------------------------------\n\n/**\n * Action type registry. This interface is empty by default and gets augmented\n * by the auto-generated `.generated/action-types.d.ts` file. When augmented,\n * it maps action names to their parameter and return types, enabling\n * end-to-end type safety for `useActionQuery` and `useActionMutation`.\n */\ndeclare global {\n interface AgentNativeActionRegistry {}\n}\n\nexport interface ActionRegistry extends AgentNativeActionRegistry {}\n\n/** Resolves to the union of registered action names, or `string` if no registry exists. */\ntype ActionName = keyof ActionRegistry extends never\n ? string\n : (keyof ActionRegistry & string) | (string & {});\n\n/** Resolves the return type of an action, or `any` if not in the registry. */\ntype ActionResult<T extends string> = T extends keyof ActionRegistry\n ? ActionRegistry[T] extends { result: infer R }\n ? R\n : any\n : any;\n\n/** Resolves the parameter type of an action, or `Record<string, any>` if not in the registry. */\ntype ActionParams<T extends string> = T extends keyof ActionRegistry\n ? ActionRegistry[T] extends { params: infer P }\n ? P\n : Record<string, any>\n : Record<string, any>;\n\nexport type ClientActionMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n\nexport interface ClientActionCallOptions {\n method?: ClientActionMethod;\n /** Abort signal for the underlying fetch. */\n signal?: AbortSignal;\n /** Override the default 60s fetch timeout for long-running actions. */\n timeoutMs?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Fetch helper\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the browser's IANA timezone (e.g. \"America/Los_Angeles\"). This is\n * sent on every action request as `x-user-timezone` so server-side defaults\n * like \"today\" honor the user's local day rather than the server's UTC clock.\n */\nfunction resolveUserTimezone(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function serializeActionQueryParams(\n params: Record<string, any>,\n): string {\n const qs = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n appendActionQueryParam(qs, key, value);\n }\n return qs.toString();\n}\n\nfunction appendActionQueryParam(\n qs: URLSearchParams,\n key: string,\n value: unknown,\n) {\n if (value === null || value === undefined) return;\n if (Array.isArray(value)) {\n // Use bracket keys so a one-item array still arrives as an array after the\n // server parses URLSearchParams. Repeated bare keys lose that distinction.\n for (const item of value) {\n appendActionQueryParam(qs, `${key}[]`, item);\n }\n return;\n }\n qs.append(key, String(value));\n}\n\nexport interface ActionFetchOptions {\n /**\n * Abort signal from the caller (React Query passes one per queryFn\n * invocation so superseded requests — key change, unmount, refetch — cancel\n * the underlying network request instead of hogging a connection slot).\n */\n signal?: AbortSignal;\n /** Per-call override for the fetch timeout. */\n timeoutMs?: number;\n /** Keep the request alive while the document is being unloaded. */\n keepalive?: boolean;\n /** Pre-serialized mutation body used by the keepalive budget coordinator. */\n serializedBody?: string;\n /** Omit the tab echo-suppression tag for imperative callers. */\n includeRequestSource?: boolean;\n}\n\ntype InternalActionFetchOptions = ActionFetchOptions & {\n onResponse?: (response: Response) => void;\n};\n\n/**\n * Conservative per-document keepalive body budget. Browsers commonly enforce\n * an approximately 64 KiB aggregate limit across every in-flight keepalive\n * request; leaving headroom for other framework traffic prevents a request\n * that passed our guard from being rejected by the browser at send time.\n */\nexport const ACTION_KEEPALIVE_BODY_BUDGET_BYTES = 48_000;\n\nlet reservedKeepaliveBodyBytes = 0;\n\nfunction utf8ByteLength(value: string): number {\n if (typeof TextEncoder !== \"undefined\") {\n return new TextEncoder().encode(value).byteLength;\n }\n\n let bytes = 0;\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n bytes +=\n codePoint <= 0x7f\n ? 1\n : codePoint <= 0x7ff\n ? 2\n : codePoint <= 0xffff\n ? 3\n : 4;\n }\n return bytes;\n}\n\nasync function performActionFetch<T>(\n name: string,\n method: string,\n params?: Record<string, any>,\n options?: InternalActionFetchOptions,\n): Promise<T> {\n ensureEmbedAuthFetchInterceptor();\n let url = `${ACTION_PREFIX}/${name}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n // Tag browser-originated action calls so the server can set\n // `ctx.caller = \"frontend\"` (vs a bare programmatic `\"http\"` POST).\n // Mirrors the X-Agent-Native-Tool-Bridge: 1 convention. The header is\n // safe to expose: CORS allows it (see action-routes.ts) and it carries\n // no auth weight — it only narrows the caller tag.\n \"X-Agent-Native-Frontend\": \"1\",\n ...(options?.includeRequestSource !== false\n ? {\n // The server copies this onto the emitted action sync event.\n // useDbSync can then ignore the echo in this tab while other tabs\n // still refresh.\n \"X-Request-Source\": getBrowserTabId(),\n }\n : {}),\n };\n const compatibilityVersion = clientCompatibilityVersion();\n if (compatibilityVersion) {\n headers[\"X-Agent-Native-Client-Compatibility\"] = compatibilityVersion;\n }\n const buildId = clientBuildId();\n if (buildId) headers[\"X-Agent-Native-Build-Id\"] = buildId;\n const tz = resolveUserTimezone();\n if (tz) headers[\"x-user-timezone\"] = tz;\n const init: RequestInit = {\n method,\n headers,\n cache: \"no-store\",\n keepalive: options?.keepalive,\n };\n\n if (method === \"GET\" && params && Object.keys(params).length > 0) {\n // Skip null/undefined so optional filters don't turn into literal \"null\"\n // strings in the query string (e.g. `?folderId=null`).\n const qs = serializeActionQueryParams(params);\n if (qs) url += `?${qs}`;\n } else if (method !== \"GET\" && params) {\n init.body = options?.serializedBody ?? JSON.stringify(params);\n }\n\n // One controller drives both cancellation sources: the caller's signal\n // (superseded query, unmount) and the timeout. The timer stays armed until\n // the BODY is fully read — headers arriving quickly while the body stalls\n // is exactly the hang this bounds.\n const outerSignal = options?.signal;\n const timeoutMs = options?.timeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS;\n const controller =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n const onOuterAbort = () => controller?.abort();\n if (outerSignal && controller) {\n if (outerSignal.aborted) controller.abort();\n else outerSignal.addEventListener(\"abort\", onOuterAbort, { once: true });\n }\n let timedOut = false;\n const timer = controller\n ? setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs)\n : null;\n if (controller) init.signal = controller.signal;\n\n const throwTimeout = (): never => {\n const error = new Error(\n `Action ${name} timed out after ${Math.round(timeoutMs / 1000)}s`,\n );\n (error as any).timedOut = true;\n (error as any).status = 408;\n throw error;\n };\n\n let res: Response;\n let raw = \"\";\n let readFailed = false;\n let readError: unknown;\n try {\n try {\n res = await fetch(url, init);\n options?.onResponse?.(res);\n } catch (err) {\n if (timedOut) throwTimeout();\n // Caller-initiated cancellation — rethrow untouched so React Query\n // recognizes it as a cancellation rather than a query failure.\n if (outerSignal?.aborted) throw err;\n // Network failures, CORS, server unreachable, etc. — give the caller a\n // useful message instead of the opaque \"Failed to fetch\".\n const cause = err instanceof Error ? err.message : String(err);\n throw new Error(`Action ${name} failed: ${cause}`);\n }\n\n if (\n res.status === 409 &&\n res.headers.get(\"X-Agent-Native-Client-Mismatch\") === \"1\"\n ) {\n const serverBuildId =\n res.headers.get(\"X-Agent-Native-Build-Id\") ?? \"latest\";\n const requiredCompatibility =\n res.headers.get(\"X-Agent-Native-Client-Compatibility\") ?? \"unknown\";\n reloadForClientCompatibilityMismatch(\n serverBuildId,\n requiredCompatibility,\n );\n const error = new Error(\n `Action ${name} requires a refreshed browser client`,\n );\n (error as any).status = 409;\n (error as any).code = \"client_build_mismatch\";\n throw error;\n }\n\n // 204 No Content — nothing to parse.\n if (res.status === 204) return null as T;\n\n // Read the body as text first so we can:\n // - tolerate empty bodies (avoids \"Unexpected end of JSON input\")\n // - surface non-JSON error responses (HTML 401/404 pages, plain text, etc.)\n // - preserve the original HTTP status in the thrown error\n // Track read failures separately from \"no body\" — a stream interruption /\n // decode failure on a 2xx response should error rather than silently\n // succeed with `null`.\n try {\n raw = await res.text();\n } catch (err) {\n if (timedOut) throwTimeout();\n if (outerSignal?.aborted) throw err;\n readFailed = true;\n readError = err;\n }\n } finally {\n if (timer) clearTimeout(timer);\n if (outerSignal) outerSignal.removeEventListener(\"abort\", onOuterAbort);\n }\n\n let data: any = undefined;\n let parseFailed = false;\n if (raw.length > 0) {\n try {\n data = JSON.parse(raw);\n } catch {\n // Body wasn't JSON — keep `data` undefined and use the raw text below.\n parseFailed = true;\n }\n }\n\n if (!res.ok) {\n const message =\n (data && (data.error || data.message)) ||\n // Truncate non-JSON bodies so we don't dump entire HTML pages into the\n // console, but still give the developer a hint as to what came back.\n (raw && raw.slice(0, 200)) ||\n res.statusText ||\n `HTTP ${res.status}`;\n const error = new Error(`Action ${name} failed: ${message}`);\n (error as any).status = res.status;\n throw error;\n }\n\n // 2xx but the body couldn't even be read (mid-stream abort, decode failure,\n // etc.). Don't silently treat that as a `null` success.\n if (readFailed) {\n const cause =\n readError instanceof Error ? readError.message : String(readError);\n const error = new Error(\n `Action ${name} returned ${res.status} but the body could not be read: ${cause}`,\n );\n (error as any).status = res.status;\n throw error;\n }\n\n // 2xx with a non-empty, non-JSON body. Action callers expect typed data, so\n // returning `null` here would silently mask a real server bug (e.g. a proxy\n // returning HTML 200 instead of JSON). Throw instead — empty bodies (handled\n // above by the `raw.length > 0` guard and the 204 short-circuit) still\n // correctly resolve to `null`.\n if (parseFailed) {\n const error = new Error(\n `Action ${name} returned a non-JSON ${res.status} response: ${raw.slice(0, 200)}`,\n );\n (error as any).status = res.status;\n throw error;\n }\n\n return (data ?? (null as unknown)) as T;\n}\n\nfunction actionTelemetryNow(): number {\n return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nfunction parseServerTiming(\n response: Response | undefined,\n): Map<string, number> {\n const timings = new Map<string, number>();\n const value = response?.headers.get(\"server-timing\");\n if (!value) return timings;\n\n for (const entry of value.split(\",\")) {\n const [rawName, ...params] = entry.trim().split(\";\");\n const name = rawName?.trim();\n if (!name) continue;\n const duration = params\n .map((param) => /^dur=(.+)$/i.exec(param.trim())?.[1])\n .find(Boolean);\n const parsed = duration === undefined ? NaN : Number(duration);\n if (Number.isFinite(parsed)) timings.set(name, parsed);\n }\n return timings;\n}\n\nfunction shouldTrackActionResponse(\n error: unknown,\n durationMs: number,\n response: Response | undefined,\n): boolean {\n if (error || durationMs >= 1_000) return true;\n if (response && response.status >= 400 && response.status < 500) return true;\n if (\n /\\bstartup(?:-db)?\\s*;/i.test(response?.headers.get(\"server-timing\") ?? \"\")\n ) {\n return true;\n }\n const raw = (import.meta.env as Record<string, string | undefined>)\n ?.VITE_AGENT_NATIVE_ACTION_TELEMETRY_SAMPLE_RATE;\n const parsed = raw === undefined ? 0.1 : Number(raw);\n const rate = Number.isFinite(parsed) ? Math.max(0, Math.min(1, parsed)) : 0.1;\n return Math.random() < rate;\n}\n\nasync function actionFetch<T>(\n name: string,\n method: string,\n params?: Record<string, any>,\n options?: ActionFetchOptions,\n): Promise<T> {\n const startedAt = actionTelemetryNow();\n let response: Response | undefined;\n let responseAt: number | undefined;\n let error: unknown;\n\n try {\n return await performActionFetch<T>(name, method, params, {\n ...options,\n onResponse: (nextResponse) => {\n response = nextResponse;\n responseAt = actionTelemetryNow();\n },\n });\n } catch (caught) {\n error = caught;\n throw caught;\n } finally {\n try {\n const completedAt = actionTelemetryNow();\n const durationMs = Math.max(0, completedAt - startedAt);\n if (shouldTrackActionResponse(error, durationMs, response)) {\n const ttfbMs =\n responseAt === undefined\n ? undefined\n : Math.max(0, responseAt - startedAt);\n const serverTiming = parseServerTiming(response);\n const serverDurationMs = serverTiming.get(\"app\");\n const errorStatus = Number(\n (error as { status?: unknown } | undefined)?.status,\n );\n const statusCode =\n response?.status ??\n (Number.isFinite(errorStatus) ? errorStatus : undefined);\n const timedOut =\n (error as { timedOut?: unknown } | undefined)?.timedOut === true;\n const cancelled = options?.signal?.aborted === true && !timedOut;\n const contentLength = Number(response?.headers.get(\"content-length\"));\n\n trackEvent(\"action.response\", {\n request_id:\n response?.headers.get(\"x-agent-native-request-id\") ?? undefined,\n action: name,\n method,\n status_code: statusCode,\n status_class:\n statusCode === undefined\n ? \"network\"\n : `${Math.floor(statusCode / 100)}xx`,\n success: !error,\n outcome: !error\n ? \"success\"\n : timedOut\n ? \"timeout\"\n : cancelled\n ? \"cancelled\"\n : response\n ? \"http-error\"\n : \"network-error\",\n duration_ms: Math.round(durationMs),\n ttfb_ms: ttfbMs === undefined ? undefined : Math.round(ttfbMs),\n body_ms:\n ttfbMs === undefined ? undefined : Math.round(durationMs - ttfbMs),\n server_duration_ms:\n serverDurationMs === undefined\n ? undefined\n : Math.round(serverDurationMs),\n network_overhead_ms:\n ttfbMs === undefined || serverDurationMs === undefined\n ? undefined\n : Math.max(0, Math.round(ttfbMs - serverDurationMs)),\n framework_ready_wait_ms: serverTiming.get(\"startup\"),\n db_operation_wall_ms: serverTiming.get(\"db\"),\n db_connect_total_ms: serverTiming.get(\"db-connect\"),\n db_slowest_operation_ms: serverTiming.get(\"db-slowest\"),\n startup_db_operation_wall_ms: serverTiming.get(\"startup-db\"),\n startup_db_connect_total_ms: serverTiming.get(\"startup-db-connect\"),\n response_bytes:\n Number.isFinite(contentLength) && contentLength >= 0\n ? contentLength\n : undefined,\n });\n }\n } catch {\n // Performance telemetry must never change the action result.\n }\n }\n}\n\n/**\n * Imperatively call an action from browser/client code.\n *\n * Prefer `useActionQuery` / `useActionMutation` in React render flows. Use this\n * helper when a hook is not ergonomic; do not hand-write fetch calls to\n * `/_agent-native/actions/*` in components.\n */\nexport function callAction<\n TResult = undefined,\n TName extends ActionName = ActionName,\n>(\n actionName: TName,\n params?: ActionParams<TName>,\n options: ClientActionCallOptions = {},\n): Promise<TResult extends undefined ? ActionResult<TName> : TResult> {\n type R = TResult extends undefined ? ActionResult<TName> : TResult;\n return actionFetch<R>(actionName, options.method ?? \"POST\", params, {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n includeRequestSource: false,\n });\n}\n\nexport type KeepaliveActionCallRejectionReason =\n | \"body-too-large\"\n | \"budget-exhausted\";\n\nexport type KeepaliveActionCallResult<TResult> =\n | {\n accepted: true;\n bodyBytes: number;\n completion: Promise<TResult>;\n }\n | {\n accepted: false;\n bodyBytes: number;\n reason: KeepaliveActionCallRejectionReason;\n completion: null;\n };\n\n/**\n * Attempts an unload-safe action call without exceeding the browser's shared\n * keepalive request budget. The reservation remains held until the response\n * body has completed, because browsers count every in-flight keepalive body\n * against the same per-document quota.\n *\n * A rejected attempt is deliberately synchronous so callers can fall back to\n * a durable outbox before returning from `pagehide`.\n */\nexport function tryCallActionKeepalive<\n TResult = undefined,\n TName extends ActionName = ActionName,\n>(\n actionName: TName,\n params?: ActionParams<TName>,\n options: Omit<ClientActionCallOptions, \"method\"> = {},\n): KeepaliveActionCallResult<\n TResult extends undefined ? ActionResult<TName> : TResult\n> {\n type R = TResult extends undefined ? ActionResult<TName> : TResult;\n const serializedBody = JSON.stringify(params ?? {});\n const bodyBytes = utf8ByteLength(serializedBody);\n\n if (bodyBytes > ACTION_KEEPALIVE_BODY_BUDGET_BYTES) {\n return {\n accepted: false,\n bodyBytes,\n reason: \"body-too-large\",\n completion: null,\n };\n }\n\n if (\n reservedKeepaliveBodyBytes + bodyBytes >\n ACTION_KEEPALIVE_BODY_BUDGET_BYTES\n ) {\n return {\n accepted: false,\n bodyBytes,\n reason: \"budget-exhausted\",\n completion: null,\n };\n }\n\n reservedKeepaliveBodyBytes += bodyBytes;\n const completion = actionFetch<R>(actionName, \"POST\", params, {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n keepalive: true,\n serializedBody,\n }).finally(() => {\n reservedKeepaliveBodyBytes = Math.max(\n 0,\n reservedKeepaliveBodyBytes - bodyBytes,\n );\n });\n\n return { accepted: true, bodyBytes, completion };\n}\n\n// ---------------------------------------------------------------------------\n// Query hook\n// ---------------------------------------------------------------------------\n\n/**\n * Query an action exposed as GET.\n *\n * When the action type registry is generated, the return type and parameter\n * types are inferred automatically from the action's `defineAction()` call.\n *\n * ```ts\n * // Type-safe — no manual generic needed\n * const { data } = useActionQuery(\"list-meals\", { date: \"2025-01-01\" });\n *\n * // Manual override still works when needed\n * const { data } = useActionQuery<CustomType>(\"list-meals\");\n * ```\n */\nexport function useActionQuery<\n TResult = undefined,\n TName extends ActionName = ActionName,\n>(\n actionName: TName,\n params?: ActionParams<TName>,\n options?: Omit<\n UseQueryOptions<TResult extends undefined ? ActionResult<TName> : TResult>,\n \"queryKey\" | \"queryFn\"\n >,\n) {\n type R = TResult extends undefined ? ActionResult<TName> : TResult;\n return useQuery<R>({\n queryKey: [\"action\", actionName, params],\n // Thread React Query's per-fetch AbortSignal into the network request so\n // superseded fetches (key change, unmount, rapid refetch) actually cancel\n // instead of holding a per-origin connection slot until they finish.\n queryFn: ({ signal }) =>\n actionFetch<R>(actionName, \"GET\", params, { signal }),\n retry: defaultActionQueryRetry,\n retryDelay: defaultActionQueryRetryDelay,\n ...options,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Mutation hook\n// ---------------------------------------------------------------------------\n\n/**\n * Mutate via an action exposed as POST (default), PUT, or DELETE.\n *\n * When the action type registry is generated, the return type and parameter\n * types are inferred automatically.\n *\n * ```ts\n * // Type-safe\n * const { mutate } = useActionMutation(\"log-meal\");\n * mutate({ name: \"Salad\", calories: 350 });\n * ```\n */\nexport function useActionMutation<\n TData = undefined,\n TVariables = undefined,\n TName extends ActionName = ActionName,\n>(\n actionName: TName,\n options?: Omit<\n UseMutationOptions<\n TData extends undefined ? ActionResult<TName> : TData,\n Error,\n TVariables extends undefined ? ActionParams<TName> : TVariables\n >,\n \"mutationFn\"\n > & {\n method?: \"POST\" | \"PUT\" | \"DELETE\";\n skipActionQueryInvalidation?: boolean;\n },\n) {\n const queryClient = useQueryClient();\n const {\n method: methodOpt,\n onSuccess,\n skipActionQueryInvalidation = false,\n ...restOptions\n } = options ?? ({} as any);\n const method = methodOpt ?? \"POST\";\n\n type D = TData extends undefined ? ActionResult<TName> : TData;\n type V = TVariables extends undefined ? ActionParams<TName> : TVariables;\n\n return useMutation<D, Error, V>({\n ...restOptions,\n mutationFn: (params) =>\n actionFetch<D>(actionName, method, params as Record<string, any>),\n onSuccess: (...args: [any, any, any]) => {\n // Most mutations change app data broadly. High-volume background\n // mutations can opt out and perform narrower invalidation in onSuccess.\n if (!skipActionQueryInvalidation) {\n queryClient.invalidateQueries({ queryKey: [\"action\"] });\n }\n return (onSuccess as Function)?.(...args);\n },\n });\n}\n"]}
|
package/dist/collab/routes.d.ts
CHANGED
|
@@ -26,8 +26,8 @@ export declare const getCollabState: import("h3").EventHandlerWithFetch<import("
|
|
|
26
26
|
* Body: { update: string (base64), requestSource?: string }
|
|
27
27
|
*/
|
|
28
28
|
export declare const postCollabUpdate: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
|
|
29
|
-
ok?: undefined;
|
|
30
29
|
error: string;
|
|
30
|
+
ok?: undefined;
|
|
31
31
|
} | {
|
|
32
32
|
error?: undefined;
|
|
33
33
|
ok: boolean;
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
* Body: { json: any, fieldName?: string, type?: "map"|"array", requestSource?: string }
|
|
14
14
|
*/
|
|
15
15
|
export declare const postCollabJson: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
|
|
16
|
-
ok?: undefined;
|
|
17
16
|
error: string;
|
|
17
|
+
ok?: undefined;
|
|
18
18
|
} | {
|
|
19
19
|
error?: undefined;
|
|
20
20
|
ok: boolean;
|
package/dist/deploy/build.js
CHANGED
|
@@ -1045,7 +1045,7 @@ async function getHandler() {
|
|
|
1045
1045
|
headers: {
|
|
1046
1046
|
"Access-Control-Allow-Origin": "*",
|
|
1047
1047
|
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
1048
|
-
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Embed-Target",
|
|
1048
|
+
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Client-Compatibility,X-Agent-Native-Build-Id,X-Agent-Native-Embed-Target",
|
|
1049
1049
|
},
|
|
1050
1050
|
});
|
|
1051
1051
|
}
|
|
@@ -2831,6 +2831,7 @@ export default bundle;
|
|
|
2831
2831
|
},
|
|
2832
2832
|
replace: {
|
|
2833
2833
|
"process.env.AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID": JSON.stringify(process.env.GA_MEASUREMENT_ID?.trim() || ""),
|
|
2834
|
+
"process.env.AGENT_NATIVE_BUILD_DEPLOY_CONTEXT": JSON.stringify(process.env.CONTEXT?.trim() || ""),
|
|
2834
2835
|
},
|
|
2835
2836
|
// Replace browser-only renderers (Excalidraw/Mermaid) with an inert proxy in
|
|
2836
2837
|
// the server bundle. Without this, Nitro's Rolldown build pulls the real
|