@nuraly/lumenjs 0.1.2 → 0.1.4
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/README.md +76 -235
- package/dist/auth/config.d.ts +23 -0
- package/dist/auth/config.js +115 -0
- package/dist/auth/guard.d.ts +12 -0
- package/dist/auth/guard.js +28 -0
- package/dist/auth/index.d.ts +3 -0
- package/dist/auth/index.js +1 -0
- package/dist/auth/middleware.d.ts +23 -0
- package/dist/auth/middleware.js +89 -0
- package/dist/auth/native-auth.d.ts +73 -0
- package/dist/auth/native-auth.js +293 -0
- package/dist/auth/oidc-client.d.ts +17 -0
- package/dist/auth/oidc-client.js +123 -0
- package/dist/auth/providers/google.d.ts +23 -0
- package/dist/auth/providers/google.js +25 -0
- package/dist/auth/providers/index.d.ts +2 -0
- package/dist/auth/providers/index.js +1 -0
- package/dist/auth/routes/login.d.ts +8 -0
- package/dist/auth/routes/login.js +98 -0
- package/dist/auth/routes/logout.d.ts +4 -0
- package/dist/auth/routes/logout.js +79 -0
- package/dist/auth/routes/oidc-callback.d.ts +3 -0
- package/dist/auth/routes/oidc-callback.js +70 -0
- package/dist/auth/routes/password.d.ts +5 -0
- package/dist/auth/routes/password.js +149 -0
- package/dist/auth/routes/signup.d.ts +3 -0
- package/dist/auth/routes/signup.js +81 -0
- package/dist/auth/routes/token.d.ts +4 -0
- package/dist/auth/routes/token.js +70 -0
- package/dist/auth/routes/utils.d.ts +7 -0
- package/dist/auth/routes/utils.js +35 -0
- package/dist/auth/routes/verify.d.ts +3 -0
- package/dist/auth/routes/verify.js +26 -0
- package/dist/auth/routes.d.ts +8 -0
- package/dist/auth/routes.js +110 -0
- package/dist/auth/session.d.ts +8 -0
- package/dist/auth/session.js +54 -0
- package/dist/auth/token.d.ts +33 -0
- package/dist/auth/token.js +90 -0
- package/dist/auth/types.d.ts +156 -0
- package/dist/auth/types.js +2 -0
- package/dist/build/build-client.d.ts +15 -0
- package/dist/build/build-client.js +45 -0
- package/dist/build/build-prerender.d.ts +11 -0
- package/dist/build/build-prerender.js +159 -0
- package/dist/build/build-server.d.ts +17 -0
- package/dist/build/build-server.js +98 -0
- package/dist/build/build.js +52 -120
- package/dist/build/scan.d.ts +19 -0
- package/dist/build/scan.js +77 -6
- package/dist/build/serve-api.js +8 -2
- package/dist/build/serve-loaders.d.ts +4 -2
- package/dist/build/serve-loaders.js +128 -10
- package/dist/build/serve-ssr.js +38 -11
- package/dist/build/serve-static.js +3 -3
- package/dist/build/serve.js +229 -14
- package/dist/cli.js +37 -6
- package/dist/communication/encryption.d.ts +35 -0
- package/dist/communication/encryption.js +90 -0
- package/dist/communication/handlers/context.d.ts +27 -0
- package/dist/communication/handlers/context.js +1 -0
- package/dist/communication/handlers/conversation.d.ts +24 -0
- package/dist/communication/handlers/conversation.js +113 -0
- package/dist/communication/handlers/file-upload.d.ts +17 -0
- package/dist/communication/handlers/file-upload.js +62 -0
- package/dist/communication/handlers/messaging.d.ts +30 -0
- package/dist/communication/handlers/messaging.js +237 -0
- package/dist/communication/handlers/presence.d.ts +15 -0
- package/dist/communication/handlers/presence.js +76 -0
- package/dist/communication/handlers.d.ts +5 -0
- package/dist/communication/handlers.js +5 -0
- package/dist/communication/index.d.ts +9 -0
- package/dist/communication/index.js +7 -0
- package/dist/communication/link-preview.d.ts +18 -0
- package/dist/communication/link-preview.js +115 -0
- package/dist/communication/schema.d.ts +10 -0
- package/dist/communication/schema.js +101 -0
- package/dist/communication/server.d.ts +86 -0
- package/dist/communication/server.js +212 -0
- package/dist/communication/signaling.d.ts +43 -0
- package/dist/communication/signaling.js +271 -0
- package/dist/communication/store.d.ts +71 -0
- package/dist/communication/store.js +289 -0
- package/dist/communication/types.d.ts +454 -0
- package/dist/communication/types.js +1 -0
- package/dist/create.d.ts +1 -0
- package/dist/create.js +55 -0
- package/dist/db/auto-migrate.d.ts +3 -0
- package/dist/db/auto-migrate.js +100 -0
- package/dist/db/client.d.ts +3 -0
- package/dist/db/client.js +18 -0
- package/dist/db/context.d.ts +2 -0
- package/dist/db/context.js +9 -0
- package/dist/db/index.d.ts +23 -0
- package/dist/db/index.js +258 -0
- package/dist/db/seed.d.ts +12 -0
- package/dist/db/seed.js +88 -0
- package/dist/db/table.d.ts +10 -0
- package/dist/db/table.js +12 -0
- package/dist/dev-server/config.d.ts +14 -0
- package/dist/dev-server/config.js +26 -9
- package/dist/dev-server/index-html.d.ts +3 -0
- package/dist/dev-server/index-html.js +18 -6
- package/dist/dev-server/nuralyui-aliases.d.ts +0 -4
- package/dist/dev-server/nuralyui-aliases.js +115 -94
- package/dist/dev-server/plugins/vite-plugin-api-routes.js +29 -5
- package/dist/dev-server/plugins/vite-plugin-auth.d.ts +6 -0
- package/dist/dev-server/plugins/vite-plugin-auth.js +223 -0
- package/dist/dev-server/plugins/vite-plugin-auto-define.d.ts +16 -0
- package/dist/dev-server/plugins/vite-plugin-auto-define.js +111 -0
- package/dist/dev-server/plugins/vite-plugin-communication.d.ts +6 -0
- package/dist/dev-server/plugins/vite-plugin-communication.js +205 -0
- package/dist/dev-server/plugins/vite-plugin-editor-api.d.ts +6 -0
- package/dist/dev-server/plugins/vite-plugin-editor-api.js +318 -0
- package/dist/dev-server/plugins/vite-plugin-i18n.js +69 -2
- package/dist/dev-server/plugins/vite-plugin-lit-dedup.d.ts +6 -0
- package/dist/dev-server/plugins/vite-plugin-lit-dedup.js +78 -34
- package/dist/dev-server/plugins/vite-plugin-lit-hmr.js +44 -2
- package/dist/dev-server/plugins/vite-plugin-llms.d.ts +2 -0
- package/dist/dev-server/plugins/vite-plugin-llms.js +92 -0
- package/dist/dev-server/plugins/vite-plugin-loaders.d.ts +0 -1
- package/dist/dev-server/plugins/vite-plugin-loaders.js +311 -42
- package/dist/dev-server/plugins/vite-plugin-routes.js +18 -6
- package/dist/dev-server/plugins/vite-plugin-socketio.d.ts +2 -0
- package/dist/dev-server/plugins/vite-plugin-socketio.js +51 -0
- package/dist/dev-server/plugins/vite-plugin-source-annotator.d.ts +2 -0
- package/dist/dev-server/plugins/vite-plugin-source-annotator.js +26 -3
- package/dist/dev-server/plugins/vite-plugin-storage.d.ts +10 -0
- package/dist/dev-server/plugins/vite-plugin-storage.js +126 -0
- package/dist/dev-server/plugins/vite-plugin-virtual-modules.js +111 -2
- package/dist/dev-server/server.js +128 -12
- package/dist/dev-server/ssr-render.d.ts +2 -1
- package/dist/dev-server/ssr-render.js +107 -48
- package/dist/editor/ai/backend.d.ts +20 -0
- package/dist/editor/ai/backend.js +104 -0
- package/dist/editor/ai/claude-code-client.d.ts +20 -0
- package/dist/editor/ai/claude-code-client.js +145 -0
- package/dist/editor/ai/opencode-client.d.ts +14 -0
- package/dist/editor/ai/opencode-client.js +125 -0
- package/dist/editor/ai/snapshot-store.d.ts +22 -0
- package/dist/editor/ai/snapshot-store.js +35 -0
- package/dist/editor/ai/types.d.ts +30 -0
- package/dist/editor/ai/types.js +136 -0
- package/dist/editor/ai-chat-panel.d.ts +13 -0
- package/dist/editor/ai-chat-panel.js +587 -0
- package/dist/editor/ai-markdown.d.ts +10 -0
- package/dist/editor/ai-markdown.js +70 -0
- package/dist/editor/ai-project-panel.d.ts +11 -0
- package/dist/editor/ai-project-panel.js +332 -0
- package/dist/editor/ast-modification.d.ts +11 -0
- package/dist/editor/ast-modification.js +1 -0
- package/dist/editor/ast-service.d.ts +30 -0
- package/dist/editor/ast-service.js +180 -0
- package/dist/editor/css-rules.d.ts +54 -0
- package/dist/editor/css-rules.js +423 -0
- package/dist/editor/editor-api-client.d.ts +51 -0
- package/dist/editor/editor-api-client.js +162 -0
- package/dist/editor/editor-bridge.d.ts +1 -0
- package/dist/editor/editor-bridge.js +17 -8
- package/dist/editor/editor-toolbar.d.ts +14 -0
- package/dist/editor/editor-toolbar.js +115 -0
- package/dist/editor/file-editor.d.ts +9 -0
- package/dist/editor/file-editor.js +236 -0
- package/dist/editor/file-service.d.ts +16 -0
- package/dist/editor/file-service.js +52 -0
- package/dist/editor/i18n-key-gen.d.ts +1 -0
- package/dist/editor/i18n-key-gen.js +7 -0
- package/dist/editor/inline-text-edit.d.ts +5 -0
- package/dist/editor/inline-text-edit.js +173 -92
- package/dist/editor/overlay-events.d.ts +5 -0
- package/dist/editor/overlay-events.js +364 -0
- package/dist/editor/overlay-hmr.d.ts +2 -0
- package/dist/editor/overlay-hmr.js +75 -0
- package/dist/editor/overlay-selection.d.ts +29 -0
- package/dist/editor/overlay-selection.js +148 -0
- package/dist/editor/overlay-utils.d.ts +12 -0
- package/dist/editor/overlay-utils.js +59 -0
- package/dist/editor/properties-panel-persist.d.ts +14 -0
- package/dist/editor/properties-panel-persist.js +70 -0
- package/dist/editor/properties-panel-rows.d.ts +10 -0
- package/dist/editor/properties-panel-rows.js +349 -0
- package/dist/editor/properties-panel-styles.d.ts +4 -0
- package/dist/editor/properties-panel-styles.js +174 -0
- package/dist/editor/properties-panel.d.ts +4 -0
- package/dist/editor/properties-panel.js +148 -0
- package/dist/editor/property-registry.d.ts +16 -0
- package/dist/editor/property-registry.js +303 -0
- package/dist/editor/standalone-file-panel.d.ts +0 -0
- package/dist/editor/standalone-file-panel.js +1 -0
- package/dist/editor/standalone-overlay-dom.d.ts +0 -0
- package/dist/editor/standalone-overlay-dom.js +1 -0
- package/dist/editor/standalone-overlay-styles.d.ts +0 -0
- package/dist/editor/standalone-overlay-styles.js +1 -0
- package/dist/editor/standalone-overlay.d.ts +1 -0
- package/dist/editor/standalone-overlay.js +76 -0
- package/dist/editor/syntax-highlighter.d.ts +4 -0
- package/dist/editor/syntax-highlighter.js +81 -0
- package/dist/editor/text-toolbar.d.ts +11 -0
- package/dist/editor/text-toolbar.js +327 -0
- package/dist/editor/toolbar-styles.d.ts +4 -0
- package/dist/editor/toolbar-styles.js +198 -0
- package/dist/email/index.d.ts +32 -0
- package/dist/email/index.js +154 -0
- package/dist/email/providers/resend.d.ts +2 -0
- package/dist/email/providers/resend.js +24 -0
- package/dist/email/providers/sendgrid.d.ts +2 -0
- package/dist/email/providers/sendgrid.js +31 -0
- package/dist/email/providers/smtp.d.ts +13 -0
- package/dist/email/providers/smtp.js +125 -0
- package/dist/email/template-engine.d.ts +18 -0
- package/dist/email/template-engine.js +116 -0
- package/dist/email/templates/base.d.ts +9 -0
- package/dist/email/templates/base.js +65 -0
- package/dist/email/templates/password-reset.d.ts +5 -0
- package/dist/email/templates/password-reset.js +15 -0
- package/dist/email/templates/verify-email.d.ts +5 -0
- package/dist/email/templates/verify-email.js +15 -0
- package/dist/email/templates/welcome.d.ts +5 -0
- package/dist/email/templates/welcome.js +13 -0
- package/dist/email/types.d.ts +49 -0
- package/dist/email/types.js +1 -0
- package/dist/llms/generate.d.ts +46 -0
- package/dist/llms/generate.js +185 -0
- package/dist/permissions/guard.d.ts +28 -0
- package/dist/permissions/guard.js +30 -0
- package/dist/permissions/index.d.ts +6 -0
- package/dist/permissions/index.js +3 -0
- package/dist/permissions/service.d.ts +80 -0
- package/dist/permissions/service.js +210 -0
- package/dist/permissions/tables.d.ts +5 -0
- package/dist/permissions/tables.js +68 -0
- package/dist/permissions/types.d.ts +33 -0
- package/dist/permissions/types.js +1 -0
- package/dist/runtime/app-shell.js +163 -0
- package/dist/runtime/auth.d.ts +10 -0
- package/dist/runtime/auth.js +30 -0
- package/dist/runtime/communication.d.ts +137 -0
- package/dist/runtime/communication.js +228 -0
- package/dist/runtime/error-boundary.d.ts +23 -0
- package/dist/runtime/error-boundary.js +120 -0
- package/dist/runtime/i18n.d.ts +6 -1
- package/dist/runtime/i18n.js +42 -21
- package/dist/runtime/router-data.d.ts +5 -0
- package/dist/runtime/router-data.js +121 -16
- package/dist/runtime/router-hydration.js +25 -0
- package/dist/runtime/router.d.ts +21 -1
- package/dist/runtime/router.js +221 -39
- package/dist/runtime/socket-client.d.ts +2 -0
- package/dist/runtime/socket-client.js +30 -0
- package/dist/runtime/webrtc.d.ts +47 -0
- package/dist/runtime/webrtc.js +178 -0
- package/dist/shared/graceful-shutdown.d.ts +8 -0
- package/dist/shared/graceful-shutdown.js +36 -0
- package/dist/shared/health.d.ts +8 -0
- package/dist/shared/health.js +25 -0
- package/dist/shared/llms-txt.d.ts +31 -0
- package/dist/shared/llms-txt.js +85 -0
- package/dist/shared/logger.d.ts +32 -0
- package/dist/shared/logger.js +93 -0
- package/dist/shared/meta.d.ts +27 -0
- package/dist/shared/meta.js +71 -0
- package/dist/shared/middleware-runner.d.ts +9 -0
- package/dist/shared/middleware-runner.js +29 -0
- package/dist/shared/rate-limit.d.ts +18 -0
- package/dist/shared/rate-limit.js +71 -0
- package/dist/shared/request-id.d.ts +5 -0
- package/dist/shared/request-id.js +18 -0
- package/dist/shared/route-matching.js +16 -1
- package/dist/shared/security-headers.d.ts +18 -0
- package/dist/shared/security-headers.js +38 -0
- package/dist/shared/socket-io-setup.d.ts +11 -0
- package/dist/shared/socket-io-setup.js +51 -0
- package/dist/shared/types.d.ts +16 -0
- package/dist/shared/utils.d.ts +37 -7
- package/dist/shared/utils.js +175 -26
- package/dist/storage/adapters/local.d.ts +44 -0
- package/dist/storage/adapters/local.js +85 -0
- package/dist/storage/adapters/s3.d.ts +32 -0
- package/dist/storage/adapters/s3.js +116 -0
- package/dist/storage/adapters/types.d.ts +53 -0
- package/dist/storage/adapters/types.js +1 -0
- package/dist/storage/index.d.ts +76 -0
- package/dist/storage/index.js +83 -0
- package/package.json +20 -1
- package/templates/blog/api/posts.ts +6 -0
- package/templates/blog/data/migrations/001_init.sql +13 -0
- package/templates/blog/lumenjs.config.ts +3 -0
- package/templates/blog/package.json +14 -0
- package/templates/blog/pages/_layout.ts +25 -0
- package/templates/blog/pages/index.ts +65 -0
- package/templates/blog/pages/posts/[slug].ts +60 -0
- package/templates/blog/pages/tag/[tag].ts +44 -0
- package/templates/dashboard/api/stats.ts +10 -0
- package/templates/dashboard/data/migrations/001_init.sql +13 -0
- package/templates/dashboard/lumenjs.config.ts +3 -0
- package/templates/dashboard/package.json +14 -0
- package/templates/dashboard/pages/_layout.ts +25 -0
- package/templates/dashboard/pages/index.ts +72 -0
- package/templates/dashboard/pages/settings/index.ts +29 -0
- package/templates/default/lumenjs.config.ts +3 -0
- package/templates/default/package.json +14 -0
- package/templates/default/pages/index.ts +24 -0
- package/templates/social/api/posts/[id].ts +14 -0
- package/templates/social/api/posts.ts +11 -0
- package/templates/social/api/profile/[username].ts +10 -0
- package/templates/social/api/upload.ts +19 -0
- package/templates/social/data/migrations/001_init.sql +78 -0
- package/templates/social/data/migrations/002_add_image_url.sql +1 -0
- package/templates/social/data/migrations/003_auth.sql +7 -0
- package/templates/social/docs/architecture.md +76 -0
- package/templates/social/docs/components.md +100 -0
- package/templates/social/docs/data.md +89 -0
- package/templates/social/docs/pages.md +96 -0
- package/templates/social/docs/theming.md +52 -0
- package/templates/social/lib/media.ts +130 -0
- package/templates/social/lumenjs.auth.ts +21 -0
- package/templates/social/lumenjs.config.ts +3 -0
- package/templates/social/package.json +5 -0
- package/templates/social/pages/_layout.ts +239 -0
- package/templates/social/pages/apps/[id].ts +173 -0
- package/templates/social/pages/apps/index.ts +116 -0
- package/templates/social/pages/auth/login.ts +92 -0
- package/templates/social/pages/bookmarks.ts +57 -0
- package/templates/social/pages/explore.ts +73 -0
- package/templates/social/pages/index.ts +351 -0
- package/templates/social/pages/messages.ts +298 -0
- package/templates/social/pages/new.ts +77 -0
- package/templates/social/pages/notifications.ts +73 -0
- package/templates/social/pages/post/[id].ts +124 -0
- package/templates/social/pages/profile/[username].ts +100 -0
- package/templates/social/pages/settings/accessibility.ts +153 -0
- package/templates/social/pages/settings/account.ts +260 -0
- package/templates/social/pages/settings/help.ts +141 -0
- package/templates/social/pages/settings/language.ts +103 -0
- package/templates/social/pages/settings/privacy.ts +183 -0
- package/templates/social/pages/settings/security.ts +133 -0
- package/templates/social/pages/settings.ts +185 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import path from 'path';
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import { resolvePageFile, extractRouteParams } from './plugins/vite-plugin-loaders.js';
|
|
4
|
-
import { stripOuterLitMarkers, dirToLayoutTagName, filePathToTagName } from '../shared/utils.js';
|
|
4
|
+
import { stripOuterLitMarkers, dirToLayoutTagName, filePathToTagName, patchLoaderDataSpread } from '../shared/utils.js';
|
|
5
5
|
import { installDomShims } from '../shared/dom-shims.js';
|
|
6
6
|
import { loadTranslationsFromDisk } from './plugins/vite-plugin-i18n.js';
|
|
7
7
|
/**
|
|
@@ -10,7 +10,7 @@ import { loadTranslationsFromDisk } from './plugins/vite-plugin-i18n.js';
|
|
|
10
10
|
*
|
|
11
11
|
* Returns pre-rendered HTML and loader data, or null on failure (falls back to CSR).
|
|
12
12
|
*/
|
|
13
|
-
export async function ssrRenderPage(server, pagesDir, pathname, headers, locale) {
|
|
13
|
+
export async function ssrRenderPage(server, pagesDir, pathname, headers, locale, user) {
|
|
14
14
|
try {
|
|
15
15
|
const filePath = resolvePageFile(pagesDir, pathname);
|
|
16
16
|
if (!filePath)
|
|
@@ -20,32 +20,27 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
|
|
|
20
20
|
await server.ssrLoadModule('@lit-labs/ssr/lib/install-global-dom-shim.js');
|
|
21
21
|
// Patch missing DOM APIs that NuralyUI components may use during SSR
|
|
22
22
|
installDomShims();
|
|
23
|
-
// Initialize i18n in the SSR context so t() works during render
|
|
24
|
-
if (locale) {
|
|
25
|
-
const projectDir = path.resolve(pagesDir, '..');
|
|
26
|
-
const translations = loadTranslationsFromDisk(projectDir, locale);
|
|
27
|
-
try {
|
|
28
|
-
// Load the same i18n module the page will import (via resolve.alias)
|
|
29
|
-
const i18nMod = await server.ssrLoadModule('@lumenjs/i18n');
|
|
30
|
-
if (i18nMod?.initI18n) {
|
|
31
|
-
i18nMod.initI18n({ locales: [], defaultLocale: locale, prefixDefault: false }, locale, translations);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
catch {
|
|
35
|
-
// i18n module not available — translations will show keys
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
23
|
// Invalidate SSR module cache so we always get fresh content after file edits.
|
|
39
24
|
// Also clear the custom element from the SSR registry so the new class is used.
|
|
25
|
+
// IMPORTANT: This must happen BEFORE i18n/auth init, because invalidation
|
|
26
|
+
// recursively clears all SSR-imported modules (including @lumenjs/i18n).
|
|
27
|
+
// If we init i18n first, then invalidate, the page reload gets a fresh i18n
|
|
28
|
+
// module instance with empty translations.
|
|
40
29
|
const g = globalThis;
|
|
41
30
|
invalidateSsrModule(server, filePath);
|
|
42
31
|
clearSsrCustomElement(g);
|
|
43
32
|
// Load the page module via Vite (registers the custom element, applies transforms)
|
|
33
|
+
// Bypass get() so auto-define re-registers fresh classes
|
|
34
|
+
const registry = g.customElements;
|
|
35
|
+
if (registry)
|
|
36
|
+
registry.__nk_bypass_get = true;
|
|
44
37
|
const mod = await server.ssrLoadModule(filePath);
|
|
38
|
+
if (registry)
|
|
39
|
+
registry.__nk_bypass_get = false;
|
|
45
40
|
// Run loader if present
|
|
46
41
|
let loaderData = undefined;
|
|
47
42
|
if (mod.loader && typeof mod.loader === 'function') {
|
|
48
|
-
loaderData = await mod.loader({ params, query: {}, url: pathname, headers: headers || {}, locale });
|
|
43
|
+
loaderData = await mod.loader({ params, query: {}, url: pathname, headers: headers || {}, locale, user: user ?? null });
|
|
49
44
|
if (loaderData && typeof loaderData === 'object' && loaderData.__nk_redirect) {
|
|
50
45
|
return { html: '', loaderData: null, redirect: { location: loaderData.location, status: loaderData.status || 302 } };
|
|
51
46
|
}
|
|
@@ -53,8 +48,8 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
|
|
|
53
48
|
// Determine the custom element tag name from file path (matches client router)
|
|
54
49
|
const relPath = path.relative(pagesDir, filePath).replace(/\\/g, '/');
|
|
55
50
|
const tagName = filePathToTagName(relPath);
|
|
56
|
-
//
|
|
57
|
-
const layoutChain = discoverLayoutChain(pagesDir, filePath);
|
|
51
|
+
// Standalone pages skip all layouts
|
|
52
|
+
const layoutChain = mod.standalone ? [] : discoverLayoutChain(pagesDir, filePath);
|
|
58
53
|
const layoutsData = [];
|
|
59
54
|
// Load layout modules and run their loaders
|
|
60
55
|
const layoutModules = [];
|
|
@@ -62,10 +57,14 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
|
|
|
62
57
|
// Invalidate layout module cache and clear SSR element registry
|
|
63
58
|
invalidateSsrModule(server, layout.filePath);
|
|
64
59
|
clearSsrCustomElement(g);
|
|
60
|
+
if (registry)
|
|
61
|
+
registry.__nk_bypass_get = true;
|
|
65
62
|
const layoutMod = await server.ssrLoadModule(layout.filePath);
|
|
63
|
+
if (registry)
|
|
64
|
+
registry.__nk_bypass_get = false;
|
|
66
65
|
let layoutLoaderData = undefined;
|
|
67
66
|
if (layoutMod.loader && typeof layoutMod.loader === 'function') {
|
|
68
|
-
layoutLoaderData = await layoutMod.loader({ params: {}, query: {}, url: pathname, headers: headers || {}, locale });
|
|
67
|
+
layoutLoaderData = await layoutMod.loader({ params: {}, query: {}, url: pathname, headers: headers || {}, locale, user: user ?? null });
|
|
69
68
|
if (layoutLoaderData && typeof layoutLoaderData === 'object' && layoutLoaderData.__nk_redirect) {
|
|
70
69
|
return { html: '', loaderData: null, redirect: { location: layoutLoaderData.location, status: layoutLoaderData.status || 302 } };
|
|
71
70
|
}
|
|
@@ -74,6 +73,38 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
|
|
|
74
73
|
layoutModules.push({ tagName: layoutTagName, loaderData: layoutLoaderData });
|
|
75
74
|
layoutsData.push({ loaderPath: layout.dir, data: layoutLoaderData });
|
|
76
75
|
}
|
|
76
|
+
// Patch element classes to spread loaderData into individual properties
|
|
77
|
+
for (const lm of layoutModules) {
|
|
78
|
+
patchLoaderDataSpread(lm.tagName);
|
|
79
|
+
}
|
|
80
|
+
patchLoaderDataSpread(tagName);
|
|
81
|
+
// Initialize i18n in the SSR context AFTER all page/layout modules are loaded.
|
|
82
|
+
// This ensures t() uses the same module instance the components imported.
|
|
83
|
+
// Must happen after invalidation + module loading, because invalidateSsrModule
|
|
84
|
+
// recursively clears cached modules — if i18n was initialized before, the
|
|
85
|
+
// reloaded page/layout would get a fresh i18n instance with empty translations.
|
|
86
|
+
if (locale) {
|
|
87
|
+
const projectDir = path.resolve(pagesDir, '..');
|
|
88
|
+
const translations = loadTranslationsFromDisk(projectDir, locale);
|
|
89
|
+
try {
|
|
90
|
+
const i18nMod = await server.ssrLoadModule('@lumenjs/i18n');
|
|
91
|
+
if (i18nMod?.initI18n) {
|
|
92
|
+
i18nMod.initI18n({ locales: [], defaultLocale: locale, prefixDefault: false }, locale, translations);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
// i18n module not available — translations will show keys
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
// Initialize auth in the SSR context (same reason — after module loading)
|
|
100
|
+
if (user) {
|
|
101
|
+
try {
|
|
102
|
+
const authMod = await server.ssrLoadModule('@nuraly/lumenjs-auth');
|
|
103
|
+
if (authMod?.initAuth)
|
|
104
|
+
authMod.initAuth(user);
|
|
105
|
+
}
|
|
106
|
+
catch { }
|
|
107
|
+
}
|
|
77
108
|
// Load SSR render + lit/static-html.js through Vite (same module registry as page)
|
|
78
109
|
const { render } = await server.ssrLoadModule('@lit-labs/ssr');
|
|
79
110
|
const { html, unsafeStatic } = await server.ssrLoadModule('lit/static-html.js');
|
|
@@ -106,7 +137,7 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
|
|
|
106
137
|
htmlStr = layoutHtml + htmlStr;
|
|
107
138
|
}
|
|
108
139
|
}
|
|
109
|
-
return { html: htmlStr, loaderData, layoutsData: layoutsData.length > 0 ? layoutsData : undefined };
|
|
140
|
+
return { html: htmlStr, loaderData, layoutsData: layoutsData.length > 0 ? layoutsData : undefined, authUser: user ?? undefined };
|
|
110
141
|
}
|
|
111
142
|
catch (err) {
|
|
112
143
|
console.error('[LumenJS] SSR render failed, falling back to CSR:', err);
|
|
@@ -145,41 +176,69 @@ function findLayoutFile(dir) {
|
|
|
145
176
|
return null;
|
|
146
177
|
}
|
|
147
178
|
/**
|
|
148
|
-
* Aggressively invalidate a module
|
|
179
|
+
* Aggressively invalidate a module and all its SSR-imported dependencies.
|
|
180
|
+
* Without this, editing a component imported by a page/layout serves stale SSR.
|
|
149
181
|
*/
|
|
150
182
|
function invalidateSsrModule(server, filePath) {
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
183
|
+
const visited = new Set();
|
|
184
|
+
function invalidateRecursive(id) {
|
|
185
|
+
if (visited.has(id))
|
|
186
|
+
return;
|
|
187
|
+
visited.add(id);
|
|
188
|
+
const mods = server.moduleGraph.getModulesByFile(id);
|
|
189
|
+
if (mods) {
|
|
190
|
+
for (const m of mods) {
|
|
191
|
+
server.moduleGraph.invalidateModule(m);
|
|
192
|
+
m.ssrModule = null;
|
|
193
|
+
m.ssrTransformResult = null;
|
|
194
|
+
// Recurse into SSR-imported modules
|
|
195
|
+
if (m.ssrImportedModules) {
|
|
196
|
+
for (const dep of m.ssrImportedModules) {
|
|
197
|
+
if (dep.file)
|
|
198
|
+
invalidateRecursive(dep.file);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const urlMod = server.moduleGraph.getModuleById(id);
|
|
204
|
+
if (urlMod) {
|
|
205
|
+
server.moduleGraph.invalidateModule(urlMod);
|
|
206
|
+
urlMod.ssrModule = null;
|
|
207
|
+
urlMod.ssrTransformResult = null;
|
|
157
208
|
}
|
|
158
209
|
}
|
|
159
|
-
|
|
160
|
-
if (urlMod) {
|
|
161
|
-
server.moduleGraph.invalidateModule(urlMod);
|
|
162
|
-
urlMod.ssrModule = null;
|
|
163
|
-
urlMod.ssrTransformResult = null;
|
|
164
|
-
}
|
|
210
|
+
invalidateRecursive(filePath);
|
|
165
211
|
}
|
|
166
212
|
/**
|
|
167
|
-
* Patch the SSR customElements registry to allow re-registration
|
|
213
|
+
* Patch the SSR customElements registry to allow re-registration,
|
|
214
|
+
* and proactively clear all definitions so auto-define guards pass.
|
|
168
215
|
*/
|
|
169
216
|
function clearSsrCustomElement(g) {
|
|
170
217
|
const registry = g.customElements;
|
|
171
|
-
if (!registry
|
|
218
|
+
if (!registry)
|
|
172
219
|
return;
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
registry.
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
if (
|
|
180
|
-
registry.
|
|
220
|
+
// Patch define() to allow re-registration and get() to bypass
|
|
221
|
+
// auto-define guards (one-time)
|
|
222
|
+
if (!registry.__nk_patched) {
|
|
223
|
+
registry.__nk_patched = true;
|
|
224
|
+
const origDefine = registry.define.bind(registry);
|
|
225
|
+
registry.define = (name, ctor) => {
|
|
226
|
+
if (registry.__definitions && registry.__definitions.has(name)) {
|
|
227
|
+
const oldCtor = registry.__definitions.get(name)?.ctor;
|
|
228
|
+
registry.__definitions.delete(name);
|
|
229
|
+
if (oldCtor && registry.__reverseDefinitions) {
|
|
230
|
+
registry.__reverseDefinitions.delete(oldCtor);
|
|
231
|
+
}
|
|
181
232
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
233
|
+
return origDefine(name, ctor);
|
|
234
|
+
};
|
|
235
|
+
// Patch get() so auto-define's `if (!customElements.get('tag'))` guard
|
|
236
|
+
// always passes, allowing define() to re-register the fresh class.
|
|
237
|
+
const origGet = registry.get.bind(registry);
|
|
238
|
+
registry.get = (name) => {
|
|
239
|
+
if (registry.__nk_bypass_get)
|
|
240
|
+
return undefined;
|
|
241
|
+
return origGet(name);
|
|
242
|
+
};
|
|
243
|
+
}
|
|
185
244
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI backend router — selects between Claude Code and OpenCode based on:
|
|
3
|
+
* 1. AI_BACKEND env var ('claude-code' | 'opencode')
|
|
4
|
+
* 2. Auto-detection: Claude Code CLI first, then OpenCode server
|
|
5
|
+
*/
|
|
6
|
+
import type { AiChatOptions, AiChatResult, AiStatusResult } from './types.js';
|
|
7
|
+
export type { AiChatOptions, AiChatResult, AiStatusResult } from './types.js';
|
|
8
|
+
/**
|
|
9
|
+
* Stream an AI chat message using the configured backend.
|
|
10
|
+
*/
|
|
11
|
+
export declare function streamAiChat(projectDir: string, options: AiChatOptions): AiChatResult;
|
|
12
|
+
/**
|
|
13
|
+
* Warm up the AI backend session in the background.
|
|
14
|
+
* Call on editor startup so the first user request is fast.
|
|
15
|
+
*/
|
|
16
|
+
export declare function warmUpAiSession(projectDir: string): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Check if any AI backend is available.
|
|
19
|
+
*/
|
|
20
|
+
export declare function checkAiStatus(): Promise<AiStatusResult>;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI backend router — selects between Claude Code and OpenCode based on:
|
|
3
|
+
* 1. AI_BACKEND env var ('claude-code' | 'opencode')
|
|
4
|
+
* 2. Auto-detection: Claude Code CLI first, then OpenCode server
|
|
5
|
+
*/
|
|
6
|
+
let resolvedBackend = null;
|
|
7
|
+
async function detectBackend() {
|
|
8
|
+
if (resolvedBackend)
|
|
9
|
+
return resolvedBackend;
|
|
10
|
+
const explicit = process.env.AI_BACKEND;
|
|
11
|
+
if (explicit === 'claude-code' || explicit === 'opencode') {
|
|
12
|
+
resolvedBackend = explicit;
|
|
13
|
+
console.log(`[LumenJS] AI backend: ${explicit} (from AI_BACKEND env)`);
|
|
14
|
+
return resolvedBackend;
|
|
15
|
+
}
|
|
16
|
+
// Auto-detect: try Claude Code first (subscription-based, no server needed)
|
|
17
|
+
try {
|
|
18
|
+
const cc = await import('./claude-code-client.js');
|
|
19
|
+
const status = await cc.checkAiStatus();
|
|
20
|
+
if (status.configured) {
|
|
21
|
+
resolvedBackend = 'claude-code';
|
|
22
|
+
console.log('[LumenJS] AI backend: claude-code (auto-detected)');
|
|
23
|
+
return resolvedBackend;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// SDK not installed or CLI not found
|
|
28
|
+
}
|
|
29
|
+
// Fall back to OpenCode
|
|
30
|
+
resolvedBackend = 'opencode';
|
|
31
|
+
console.log('[LumenJS] AI backend: opencode (fallback)');
|
|
32
|
+
return resolvedBackend;
|
|
33
|
+
}
|
|
34
|
+
async function getClient() {
|
|
35
|
+
const backend = await detectBackend();
|
|
36
|
+
if (backend === 'claude-code') {
|
|
37
|
+
return import('./claude-code-client.js');
|
|
38
|
+
}
|
|
39
|
+
return import('./opencode-client.js');
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Stream an AI chat message using the configured backend.
|
|
43
|
+
*/
|
|
44
|
+
export function streamAiChat(projectDir, options) {
|
|
45
|
+
const tokenCallbacks = [];
|
|
46
|
+
const doneCallbacks = [];
|
|
47
|
+
const errorCallbacks = [];
|
|
48
|
+
let innerResult = null;
|
|
49
|
+
const run = async () => {
|
|
50
|
+
try {
|
|
51
|
+
const client = await getClient();
|
|
52
|
+
innerResult = client.streamAiChat(projectDir, options);
|
|
53
|
+
// Forward callbacks registered before the client loaded
|
|
54
|
+
for (const cb of tokenCallbacks)
|
|
55
|
+
innerResult.onToken(cb);
|
|
56
|
+
for (const cb of doneCallbacks)
|
|
57
|
+
innerResult.onDone(cb);
|
|
58
|
+
for (const cb of errorCallbacks)
|
|
59
|
+
innerResult.onError(cb);
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
63
|
+
for (const cb of errorCallbacks)
|
|
64
|
+
cb(error);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
run();
|
|
68
|
+
return {
|
|
69
|
+
get sessionId() { return innerResult?.sessionId || options.sessionId || ''; },
|
|
70
|
+
onToken: (cb) => { tokenCallbacks.push(cb); innerResult?.onToken(cb); },
|
|
71
|
+
onDone: (cb) => { doneCallbacks.push(cb); innerResult?.onDone(cb); },
|
|
72
|
+
onError: (cb) => { errorCallbacks.push(cb); innerResult?.onError(cb); },
|
|
73
|
+
abort: () => innerResult?.abort(),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Warm up the AI backend session in the background.
|
|
78
|
+
* Call on editor startup so the first user request is fast.
|
|
79
|
+
*/
|
|
80
|
+
export async function warmUpAiSession(projectDir) {
|
|
81
|
+
const backend = await detectBackend();
|
|
82
|
+
if (backend === 'claude-code') {
|
|
83
|
+
try {
|
|
84
|
+
const cc = await import('./claude-code-client.js');
|
|
85
|
+
await cc.warmUpSession(projectDir);
|
|
86
|
+
console.log('[LumenJS] AI session warmed up');
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
// Non-fatal
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Check if any AI backend is available.
|
|
95
|
+
*/
|
|
96
|
+
export async function checkAiStatus() {
|
|
97
|
+
try {
|
|
98
|
+
const client = await getClient();
|
|
99
|
+
return client.checkAiStatus();
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return { configured: false, backend: 'opencode' };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code AI client — uses the Claude Agent SDK (@anthropic-ai/claude-agent-sdk).
|
|
3
|
+
* Spawns the `claude` CLI as a subprocess. Requires Claude Code CLI installed and logged in.
|
|
4
|
+
* Works with Pro/Max subscription — no API key needed.
|
|
5
|
+
*/
|
|
6
|
+
import type { AiChatOptions, AiChatResult, AiStatusResult } from './types.js';
|
|
7
|
+
/**
|
|
8
|
+
* Warm up by pre-spawning a Claude Code session. The first real request
|
|
9
|
+
* will resume this session, skipping CLI cold-start entirely.
|
|
10
|
+
*/
|
|
11
|
+
export declare function warmUpSession(projectDir: string): Promise<void>;
|
|
12
|
+
/**
|
|
13
|
+
* Stream an AI chat message via Claude Code Agent SDK.
|
|
14
|
+
*/
|
|
15
|
+
export declare function streamAiChat(projectDir: string, options: AiChatOptions): AiChatResult;
|
|
16
|
+
/**
|
|
17
|
+
* Check if Claude Code CLI is installed and the Agent SDK is importable.
|
|
18
|
+
* Both are required — the CLI alone isn't enough.
|
|
19
|
+
*/
|
|
20
|
+
export declare function checkAiStatus(): Promise<AiStatusResult>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code AI client — uses the Claude Agent SDK (@anthropic-ai/claude-agent-sdk).
|
|
3
|
+
* Spawns the `claude` CLI as a subprocess. Requires Claude Code CLI installed and logged in.
|
|
4
|
+
* Works with Pro/Max subscription — no API key needed.
|
|
5
|
+
*/
|
|
6
|
+
import { SYSTEM_PROMPT, buildPrompt } from './types.js';
|
|
7
|
+
import { execSync } from 'child_process';
|
|
8
|
+
// ── SDK Cache & Session Warm-up ──────────────────────────────────
|
|
9
|
+
let _sdkCache = null;
|
|
10
|
+
let _warmSessionId = null;
|
|
11
|
+
async function getSdk() {
|
|
12
|
+
if (_sdkCache)
|
|
13
|
+
return _sdkCache;
|
|
14
|
+
const sdk = await import('@anthropic-ai/claude-agent-sdk');
|
|
15
|
+
const query = sdk.query || sdk.default?.query;
|
|
16
|
+
if (!query)
|
|
17
|
+
throw new Error('Claude Agent SDK loaded but query() not found');
|
|
18
|
+
_sdkCache = { query };
|
|
19
|
+
return _sdkCache;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Warm up by pre-spawning a Claude Code session. The first real request
|
|
23
|
+
* will resume this session, skipping CLI cold-start entirely.
|
|
24
|
+
*/
|
|
25
|
+
export async function warmUpSession(projectDir) {
|
|
26
|
+
try {
|
|
27
|
+
const { query } = await getSdk();
|
|
28
|
+
const stream = query({
|
|
29
|
+
prompt: 'Ready.',
|
|
30
|
+
options: {
|
|
31
|
+
cwd: projectDir,
|
|
32
|
+
systemPrompt: SYSTEM_PROMPT,
|
|
33
|
+
allowedTools: ['Read', 'Edit', 'Write', 'Glob', 'Grep', 'Bash'],
|
|
34
|
+
maxTurns: 1,
|
|
35
|
+
model: 'sonnet',
|
|
36
|
+
effort: 'low',
|
|
37
|
+
persistSession: true,
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
for await (const msg of stream) {
|
|
41
|
+
if (msg.session_id) {
|
|
42
|
+
_warmSessionId = msg.session_id;
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// Non-fatal — first request will just be slower
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Stream an AI chat message via Claude Code Agent SDK.
|
|
53
|
+
*/
|
|
54
|
+
export function streamAiChat(projectDir, options) {
|
|
55
|
+
const tokenCallbacks = [];
|
|
56
|
+
const doneCallbacks = [];
|
|
57
|
+
const errorCallbacks = [];
|
|
58
|
+
let aborted = false;
|
|
59
|
+
let sessionId = options.sessionId || '';
|
|
60
|
+
const enrichedPrompt = buildPrompt(options);
|
|
61
|
+
const run = async () => {
|
|
62
|
+
try {
|
|
63
|
+
const { query } = await getSdk();
|
|
64
|
+
let fullText = '';
|
|
65
|
+
const queryOptions = {
|
|
66
|
+
cwd: projectDir,
|
|
67
|
+
systemPrompt: SYSTEM_PROMPT,
|
|
68
|
+
allowedTools: ['Read', 'Edit', 'Write', 'Glob', 'Grep', 'Bash'],
|
|
69
|
+
maxTurns: 10,
|
|
70
|
+
persistSession: true,
|
|
71
|
+
model: 'sonnet',
|
|
72
|
+
};
|
|
73
|
+
// Use Sonnet + low effort for fast mode (quick actions like text improvement, spacing)
|
|
74
|
+
if (options.model === 'fast') {
|
|
75
|
+
queryOptions.model = 'sonnet';
|
|
76
|
+
queryOptions.effort = 'low';
|
|
77
|
+
queryOptions.maxTurns = 5;
|
|
78
|
+
}
|
|
79
|
+
// Resume existing session, or use pre-warmed session for instant first request
|
|
80
|
+
if (sessionId) {
|
|
81
|
+
queryOptions.resume = sessionId;
|
|
82
|
+
}
|
|
83
|
+
else if (_warmSessionId) {
|
|
84
|
+
queryOptions.resume = _warmSessionId;
|
|
85
|
+
sessionId = _warmSessionId;
|
|
86
|
+
_warmSessionId = null;
|
|
87
|
+
}
|
|
88
|
+
const stream = query({
|
|
89
|
+
prompt: enrichedPrompt,
|
|
90
|
+
options: queryOptions,
|
|
91
|
+
});
|
|
92
|
+
for await (const msg of stream) {
|
|
93
|
+
if (aborted)
|
|
94
|
+
break;
|
|
95
|
+
// Capture session ID from any message
|
|
96
|
+
if (msg.session_id && !sessionId) {
|
|
97
|
+
sessionId = msg.session_id;
|
|
98
|
+
}
|
|
99
|
+
if (msg.type === 'assistant' && msg.message?.content) {
|
|
100
|
+
for (const block of msg.message.content) {
|
|
101
|
+
if (block.type === 'text' && block.text) {
|
|
102
|
+
fullText += block.text;
|
|
103
|
+
for (const cb of tokenCallbacks)
|
|
104
|
+
cb(block.text);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (!aborted) {
|
|
110
|
+
for (const cb of doneCallbacks)
|
|
111
|
+
cb(fullText);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
if (aborted)
|
|
116
|
+
return;
|
|
117
|
+
for (const cb of errorCallbacks)
|
|
118
|
+
cb(err instanceof Error ? err : new Error(String(err)));
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
// Start the async flow
|
|
122
|
+
run();
|
|
123
|
+
return {
|
|
124
|
+
get sessionId() { return sessionId; },
|
|
125
|
+
onToken: (cb) => { tokenCallbacks.push(cb); },
|
|
126
|
+
onDone: (cb) => { doneCallbacks.push(cb); },
|
|
127
|
+
onError: (cb) => { errorCallbacks.push(cb); },
|
|
128
|
+
abort: () => { aborted = true; },
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Check if Claude Code CLI is installed and the Agent SDK is importable.
|
|
133
|
+
* Both are required — the CLI alone isn't enough.
|
|
134
|
+
*/
|
|
135
|
+
export async function checkAiStatus() {
|
|
136
|
+
try {
|
|
137
|
+
execSync('claude --version', { timeout: 5000, stdio: 'pipe' });
|
|
138
|
+
// Verify the SDK is actually importable (it's an optional dependency)
|
|
139
|
+
await import('@anthropic-ai/claude-agent-sdk');
|
|
140
|
+
return { configured: true, backend: 'claude-code' };
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
return { configured: false, backend: 'claude-code' };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode AI client — wraps the OpenCode REST API for AI coding agent integration.
|
|
3
|
+
* Connects to an OpenCode server (`opencode serve`) that handles LLM calls and file editing.
|
|
4
|
+
*/
|
|
5
|
+
import type { AiChatOptions, AiChatResult, AiStatusResult } from './types.js';
|
|
6
|
+
/**
|
|
7
|
+
* Stream an AI chat message via OpenCode's REST API.
|
|
8
|
+
* Uses the /api/session and /api/message endpoints.
|
|
9
|
+
*/
|
|
10
|
+
export declare function streamAiChat(projectDir: string, options: AiChatOptions): AiChatResult;
|
|
11
|
+
/**
|
|
12
|
+
* Check if OpenCode server is reachable.
|
|
13
|
+
*/
|
|
14
|
+
export declare function checkAiStatus(): Promise<AiStatusResult>;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode AI client — wraps the OpenCode REST API for AI coding agent integration.
|
|
3
|
+
* Connects to an OpenCode server (`opencode serve`) that handles LLM calls and file editing.
|
|
4
|
+
*/
|
|
5
|
+
import { SYSTEM_PROMPT, buildPrompt } from './types.js';
|
|
6
|
+
const OPENCODE_URL = process.env.OPENCODE_URL || 'http://localhost:3500';
|
|
7
|
+
const OPENCODE_PASSWORD = process.env.OPENCODE_SERVER_PASSWORD || '';
|
|
8
|
+
function buildHeaders() {
|
|
9
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
10
|
+
if (OPENCODE_PASSWORD) {
|
|
11
|
+
headers['Authorization'] = `Bearer ${OPENCODE_PASSWORD}`;
|
|
12
|
+
}
|
|
13
|
+
return headers;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Stream an AI chat message via OpenCode's REST API.
|
|
17
|
+
* Uses the /api/session and /api/message endpoints.
|
|
18
|
+
*/
|
|
19
|
+
export function streamAiChat(projectDir, options) {
|
|
20
|
+
const tokenCallbacks = [];
|
|
21
|
+
const doneCallbacks = [];
|
|
22
|
+
const errorCallbacks = [];
|
|
23
|
+
const controller = new AbortController();
|
|
24
|
+
let sessionId = options.sessionId || '';
|
|
25
|
+
const enrichedPrompt = buildPrompt(options);
|
|
26
|
+
const run = async () => {
|
|
27
|
+
try {
|
|
28
|
+
// Create a new session if we don't have one
|
|
29
|
+
if (!sessionId) {
|
|
30
|
+
const createRes = await fetch(`${OPENCODE_URL}/api/session`, {
|
|
31
|
+
method: 'POST',
|
|
32
|
+
headers: buildHeaders(),
|
|
33
|
+
body: JSON.stringify({ path: projectDir, system: SYSTEM_PROMPT }),
|
|
34
|
+
signal: controller.signal,
|
|
35
|
+
});
|
|
36
|
+
if (!createRes.ok) {
|
|
37
|
+
throw new Error(`Failed to create OpenCode session: ${createRes.status}`);
|
|
38
|
+
}
|
|
39
|
+
const sessionData = await createRes.json();
|
|
40
|
+
sessionId = sessionData.id || sessionData.sessionId || '';
|
|
41
|
+
}
|
|
42
|
+
// Send message and stream response
|
|
43
|
+
const msgRes = await fetch(`${OPENCODE_URL}/api/session/${sessionId}/message`, {
|
|
44
|
+
method: 'POST',
|
|
45
|
+
headers: { ...buildHeaders(), 'Accept': 'text/event-stream' },
|
|
46
|
+
body: JSON.stringify({ content: enrichedPrompt }),
|
|
47
|
+
signal: controller.signal,
|
|
48
|
+
});
|
|
49
|
+
if (!msgRes.ok) {
|
|
50
|
+
throw new Error(`OpenCode message failed: ${msgRes.status}`);
|
|
51
|
+
}
|
|
52
|
+
const reader = msgRes.body?.getReader();
|
|
53
|
+
if (!reader)
|
|
54
|
+
throw new Error('No response body from OpenCode');
|
|
55
|
+
const decoder = new TextDecoder();
|
|
56
|
+
let fullText = '';
|
|
57
|
+
let buffer = '';
|
|
58
|
+
while (true) {
|
|
59
|
+
const { done, value } = await reader.read();
|
|
60
|
+
if (done)
|
|
61
|
+
break;
|
|
62
|
+
buffer += decoder.decode(value, { stream: true });
|
|
63
|
+
const lines = buffer.split('\n');
|
|
64
|
+
buffer = lines.pop() || '';
|
|
65
|
+
for (const line of lines) {
|
|
66
|
+
if (line.startsWith('data: ')) {
|
|
67
|
+
const data = line.slice(6).trim();
|
|
68
|
+
if (data === '[DONE]')
|
|
69
|
+
continue;
|
|
70
|
+
try {
|
|
71
|
+
const parsed = JSON.parse(data);
|
|
72
|
+
// Handle different event formats from OpenCode
|
|
73
|
+
const text = parsed.content || parsed.text || parsed.delta || '';
|
|
74
|
+
if (text) {
|
|
75
|
+
fullText += text;
|
|
76
|
+
for (const cb of tokenCallbacks)
|
|
77
|
+
cb(text);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Non-JSON data line, treat as raw text
|
|
82
|
+
if (data) {
|
|
83
|
+
fullText += data;
|
|
84
|
+
for (const cb of tokenCallbacks)
|
|
85
|
+
cb(data);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
for (const cb of doneCallbacks)
|
|
92
|
+
cb(fullText);
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
if (err?.name === 'AbortError')
|
|
96
|
+
return;
|
|
97
|
+
for (const cb of errorCallbacks)
|
|
98
|
+
cb(err instanceof Error ? err : new Error(String(err)));
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
// Start the async flow
|
|
102
|
+
run();
|
|
103
|
+
return {
|
|
104
|
+
get sessionId() { return sessionId; },
|
|
105
|
+
onToken: (cb) => { tokenCallbacks.push(cb); },
|
|
106
|
+
onDone: (cb) => { doneCallbacks.push(cb); },
|
|
107
|
+
onError: (cb) => { errorCallbacks.push(cb); },
|
|
108
|
+
abort: () => controller.abort(),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Check if OpenCode server is reachable.
|
|
113
|
+
*/
|
|
114
|
+
export async function checkAiStatus() {
|
|
115
|
+
try {
|
|
116
|
+
const res = await fetch(`${OPENCODE_URL}/api/status`, {
|
|
117
|
+
headers: buildHeaders(),
|
|
118
|
+
signal: AbortSignal.timeout(3000),
|
|
119
|
+
});
|
|
120
|
+
return { configured: res.ok, backend: 'opencode' };
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return { configured: false, backend: 'opencode' };
|
|
124
|
+
}
|
|
125
|
+
}
|