@zhama/tego-plugin-sdk 1.36.1 → 1.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +50 -3
  2. package/agent/RULES.md +123 -0
  3. package/agent/guides/access.md +39 -0
  4. package/agent/guides/backend.md +76 -0
  5. package/agent/guides/claw.md +18 -0
  6. package/agent/guides/desktop-web.md +48 -0
  7. package/agent/guides/frontend.md +83 -0
  8. package/agent/guides/host-api-versions.md +34 -0
  9. package/agent/guides/i18n.md +17 -0
  10. package/agent/guides/manifest.md +26 -0
  11. package/agent/guides/migrations.md +17 -0
  12. package/agent/guides/storage.md +18 -0
  13. package/agent/guides/testing.md +17 -0
  14. package/agent/guides/ui.md +22 -0
  15. package/agent/reference/plugin-sdk-api.md +561 -0
  16. package/bin/tego-plugin-pack.mjs +1 -1
  17. package/bin/tego-plugin.mjs +4 -2
  18. package/dist/chunk-2NTAWYCG.js +1 -0
  19. package/dist/chunk-2P6UEAPV.cjs +1 -0
  20. package/dist/chunk-45Y4CR4R.cjs +1 -0
  21. package/dist/{chunk-THMWRUAT.cjs → chunk-4LKRXDYY.cjs} +13 -12
  22. package/dist/{chunk-7XHF3YSK.js → chunk-56QOZQTY.js} +1 -1
  23. package/dist/{chunk-C2OCOPZQ.cjs → chunk-6HNG5OZI.cjs} +1 -1
  24. package/dist/chunk-DEGQDJF6.js +1 -0
  25. package/dist/chunk-EIVA5BR6.js +1 -0
  26. package/dist/chunk-FCYAAOHC.js +20 -0
  27. package/dist/chunk-HZ4YWRYX.cjs +5 -0
  28. package/dist/chunk-I5Z3ECC4.js +5 -0
  29. package/dist/chunk-INCA3GFW.js +1 -0
  30. package/dist/chunk-IVJECPGG.js +1 -0
  31. package/dist/chunk-MWMGJJ74.cjs +1 -0
  32. package/dist/chunk-N4SXZZPY.cjs +1 -0
  33. package/dist/chunk-SKNPNPJP.cjs +1 -0
  34. package/dist/dev.cjs +358 -0
  35. package/dist/dev.d.cts +144 -0
  36. package/dist/dev.d.ts +144 -0
  37. package/dist/dev.js +358 -0
  38. package/dist/doctor.cjs +8 -0
  39. package/dist/doctor.d.cts +62 -0
  40. package/dist/doctor.d.ts +62 -0
  41. package/dist/doctor.js +8 -0
  42. package/dist/frontend.d.cts +33 -1
  43. package/dist/frontend.d.ts +33 -1
  44. package/dist/hono.cjs +1 -0
  45. package/dist/hono.d.cts +84 -0
  46. package/dist/hono.d.ts +84 -0
  47. package/dist/hono.js +1 -0
  48. package/dist/index.cjs +1 -1
  49. package/dist/index.d.cts +8 -3
  50. package/dist/index.d.ts +8 -3
  51. package/dist/index.js +1 -1
  52. package/dist/{manifest-types-DQARCQJt.d.cts → manifest-types-CUTNfJTa.d.cts} +1 -1
  53. package/dist/{manifest-types-DQARCQJt.d.ts → manifest-types-CUTNfJTa.d.ts} +1 -1
  54. package/dist/manifest.cjs +1 -1
  55. package/dist/manifest.d.cts +55 -2
  56. package/dist/manifest.d.ts +55 -2
  57. package/dist/manifest.js +1 -1
  58. package/dist/migrations-sync.cjs +1 -0
  59. package/dist/migrations-sync.d.cts +20 -0
  60. package/dist/migrations-sync.d.ts +20 -0
  61. package/dist/migrations-sync.js +1 -0
  62. package/dist/pack.cjs +1 -1
  63. package/dist/pack.d.cts +8 -2
  64. package/dist/pack.d.ts +8 -2
  65. package/dist/pack.js +1 -1
  66. package/dist/publish.cjs +1 -1
  67. package/dist/publish.d.cts +1 -1
  68. package/dist/publish.d.ts +1 -1
  69. package/dist/publish.js +1 -1
  70. package/dist/react.cjs +1 -0
  71. package/dist/react.d.cts +101 -0
  72. package/dist/react.d.ts +101 -0
  73. package/dist/react.js +1 -0
  74. package/dist/scaffold.cjs +672 -17
  75. package/dist/scaffold.d.cts +42 -18
  76. package/dist/scaffold.d.ts +42 -18
  77. package/dist/scaffold.js +674 -19
  78. package/dist/server-runtime.cjs +1 -1
  79. package/dist/server-runtime.d.cts +27 -2
  80. package/dist/server-runtime.d.ts +27 -2
  81. package/dist/server-runtime.js +1 -1
  82. package/dist/testing.cjs +6 -2
  83. package/dist/testing.d.cts +19 -1
  84. package/dist/testing.d.ts +19 -1
  85. package/dist/testing.js +6 -2
  86. package/dist/verify-FF2RD2MV.cjs +1 -0
  87. package/dist/verify-W7ZTUCO4.js +1 -0
  88. package/dist/vite.cjs +1 -1
  89. package/dist/vite.d.cts +27 -1
  90. package/dist/vite.d.ts +27 -1
  91. package/dist/vite.js +1 -1
  92. package/package.json +37 -3
  93. package/dist/chunk-3KUOBGJN.js +0 -19
  94. package/dist/chunk-3WA3M347.cjs +0 -1
  95. package/dist/chunk-5CU33JVY.js +0 -1
  96. package/dist/chunk-7K37PVGV.js +0 -5
  97. package/dist/chunk-BTHXQWHT.js +0 -1
  98. package/dist/chunk-ROFUQLOZ.cjs +0 -1
  99. package/dist/chunk-W7C357A6.cjs +0 -5
package/dist/dev.cjs ADDED
@@ -0,0 +1,358 @@
1
+ "use strict";var W=Object.defineProperty;var o=(e,t)=>W(e,"name",{value:t,configurable:!0});var chunkIMAVYQ4U_cjs=require("./chunk-IMAVYQ4U.cjs"),chunk4LKRXDYY_cjs=require("./chunk-4LKRXDYY.cjs");require("./chunk-HZ4YWRYX.cjs");var chunkMWMGJJ74_cjs=require("./chunk-MWMGJJ74.cjs");require("./chunk-SKNPNPJP.cjs"),require("./chunk-45Y4CR4R.cjs");var chunk2P6UEAPV_cjs=require("./chunk-2P6UEAPV.cjs");require("./chunk-N4SXZZPY.cjs"),require("./chunk-6HNG5OZI.cjs");var chunkBN6TGHSB_cjs=require("./chunk-BN6TGHSB.cjs");require("./chunk-AJY7ZHXK.cjs"),require("./chunk-OP64Y4IN.cjs");var crypto=require("crypto"),fs=require("fs"),promises=require("fs/promises"),http=require("http"),module$1=require("module"),path=require("path"),child_process=require("child_process"),net=require("net"),DEV_USER_HEADER="x-tego-dev-user-id",DEV_ROLES_HEADER="x-tego-dev-roles",DEV_TENANT_ID="dev-tenant",DEFAULT_DEV_USER_ID="00000000-0000-4000-8000-000000000001";function devCallerOf(e){const t=o(n=>(Array.isArray(n)?n[0]:n)?.trim()??"","single"),r=t(e[DEV_USER_HEADER])||DEFAULT_DEV_USER_ID;let a=[];try{const n=JSON.parse(t(e[DEV_ROLES_HEADER])||"[]");Array.isArray(n)&&(a=n.filter(i=>typeof i=="string"))}catch{}return{userId:r,roles:a}}o(devCallerOf,"devCallerOf");function gatewayHeaders(e,t,r,a=Date.now()){const n={};for(const[s,l]of Object.entries(e)){const d=s.toLowerCase();l===void 0||d.startsWith("x-tego-")||d==="cookie"||d==="authorization"||d==="host"||d==="connection"||(n[d]=Array.isArray(l)?l.join(", "):l)}const i=JSON.stringify(t.roles),u=String(a);return n[chunkBN6TGHSB_cjs.PLUGIN_CONTEXT_HEADERS.userId]=t.userId,n[chunkBN6TGHSB_cjs.PLUGIN_CONTEXT_HEADERS.tenantId]=DEV_TENANT_ID,n[chunkBN6TGHSB_cjs.PLUGIN_CONTEXT_HEADERS.roles]=i,n[chunkBN6TGHSB_cjs.PLUGIN_CONTEXT_HEADERS.issuedAt]=u,n[chunkBN6TGHSB_cjs.PLUGIN_CONTEXT_HEADERS.signature]=chunkIMAVYQ4U_cjs.signPluginContext({userId:t.userId,tenantId:DEV_TENANT_ID,rolesHeader:i,avatarId:"",issuedAt:u},r),n}o(gatewayHeaders,"gatewayHeaders");var DEV_MIGRATIONS_TABLE="tego_dev_migrations";function devSchemaName(e){return`tego_dev_${e.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`.slice(0,63)}o(devSchemaName,"devSchemaName");function devDatabaseUrl(e,t){const r=new URL(e);r.searchParams.delete("options");const a=r.search.replace(/^\?/,"");return r.search=`?${a?`${a}&`:""}options=${encodeURIComponent(`-c search_path=${t}`)}`,r.toString()}o(devDatabaseUrl,"devDatabaseUrl");async function connect(e){let t;try{t=await import("pg")}catch(n){throw new Error(`The local backend needs the "pg" driver; add it to the plugin's dependencies.`,{cause:n})}const r=t.default?.Client??t.Client;if(!r)throw new Error('The "pg" module has no Client constructor.');const a=new r({connectionString:e});try{await a.connect()}catch(n){throw new Error(`Cannot connect to DATABASE_URL (${redactUrl(e)}): ${n instanceof Error?n.message:String(n)}`,{cause:n})}return a}o(connect,"connect");function redactUrl(e){try{const t=new URL(e);return t.password&&(t.password="***"),t.toString()}catch{return"<unparseable DATABASE_URL>"}}o(redactUrl,"redactUrl");var quote=o(e=>`"${e.replace(/"/g,'""')}"`,"quote");async function applyDevMigrations(e){const t=await promises.readdir(e.migrationsDir).then(i=>i.filter(u=>u.endsWith(".sql")).sort(),i=>{if(i.code==="ENOENT")return[];throw i}),r=await connect(e.databaseUrl),a=quote(e.schema),n=`${a}.${quote(DEV_MIGRATIONS_TABLE)}`;try{await r.query(`CREATE SCHEMA IF NOT EXISTS ${a}`),await r.query(`CREATE TABLE IF NOT EXISTS ${n} (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())`);const i=new Set((await r.query(`SELECT name FROM ${n}`)).rows.map(s=>String(s.name))),u=[];for(const s of t){if(i.has(s))continue;const l=await promises.readFile(path.join(e.migrationsDir,s),"utf8");await r.query("BEGIN");try{await r.query(`SET LOCAL search_path TO ${a}`),await r.query("SELECT set_config('app.tenant_id', $1, true)",[e.tenantId]),await r.query(l),await r.query(`INSERT INTO ${n} (name) VALUES ($1)`,[s]),await r.query("COMMIT")}catch(d){throw await r.query("ROLLBACK").catch(()=>{}),new Error(`Migration ${s} failed: ${d instanceof Error?d.message:String(d)}`,{cause:d})}u.push(s)}return u}finally{await r.end().catch(()=>{})}}o(applyDevMigrations,"applyDevMigrations");var REBUILD_DEBOUNCE_MS=250,STOP_TIMEOUT_MS=5e3;function freePort(){return new Promise((e,t)=>{const r=net.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{const a=r.address(),n=typeof a=="object"&&a?a.port:0;r.close(()=>e(n))})})}o(freePort,"freePort");function stopChild(e){return!e||e.exitCode!==null||e.signalCode!==null?Promise.resolve():new Promise(t=>{const r=setTimeout(()=>{e.kill("SIGKILL"),t()},STOP_TIMEOUT_MS);e.once("exit",()=>{clearTimeout(r),t()}),e.kill("SIGTERM")})}o(stopChild,"stopChild");async function startDevBackend(e){const{part:t,log:r}=e;if(t.runtime==="python")throw new Error("The local preview runs TypeScript backends only; a python backend runs through the platform.");const a=await freePort(),n=devSchemaName(e.pluginId),i=path.resolve(e.root,t.migrationsDirPath),u=path.join(e.outDir,t.entryPath),s={...process.env,NODE_ENV:"development",TEGO_PLUGIN_ID:e.pluginId,TEGO_PLUGIN_VERSION:e.version,TEGO_PLUGIN_INSTALL_ID:"dev-install",TEGO_TENANT_ID:DEV_TENANT_ID,TEGO_PLUGIN_PORT:String(a),TEGO_PLUGIN_HEALTH_PATH:t.healthPath,TEGO_PLUGIN_HOST_API_URL:e.hostApiUrl,TEGO_PLUGIN_HOST_API_TOKEN:e.hostApiToken,TEGO_PLUGIN_GATEWAY_KEY:e.gatewayKey,DATABASE_URL:devDatabaseUrl(e.databaseUrl,n)};let l=null,d=!1;async function f(){await promises.rm(e.outDir,{recursive:!0,force:!0}),await chunk4LKRXDYY_cjs.buildPluginBackend(t,{root:e.root,outDir:e.outDir});const g=await applyDevMigrations({databaseUrl:e.databaseUrl,schema:n,migrationsDir:i,tenantId:DEV_TENANT_ID});for(const E of g)r(`[backend] applied migration ${E}`)}o(f,"build");function v(){const g=child_process.spawn(process.execPath,[u],{env:s,stdio:["ignore","pipe","pipe"]});l=g,g.stdout?.on("data",E=>process.stdout.write(E)),g.stderr?.on("data",E=>process.stderr.write(E)),g.on("exit",E=>{l===g&&!d&&(l=null,r(`[backend] exited (code ${E??"null"}); it starts again on the next save`))})}o(v,"start"),await f(),v(),r(`[backend] ${e.pluginId} on 127.0.0.1:${a}, schema ${n} in ${redactUrl(e.databaseUrl)}`);let y=null,m=null,D=!1;const A=o(async()=>{if(m){D=!0;return}m=(async()=>{try{await f();const g=l;l=null,await stopChild(g),d||(v(),r("[backend] rebuilt and restarted"))}catch(g){r(`[backend] rebuild failed, the previous build keeps running: ${g instanceof Error?g.message:String(g)}`)}})(),await m,m=null,D&&!d&&(D=!1,await A())},"rebuild"),N=[];for(const g of[t.dir,"shared"]){const E=path.resolve(e.root,g);fs.existsSync(E)&&N.push(fs.watch(E,{recursive:!0},(_,k)=>{k&&/(^|[\\/])(node_modules|dist)([\\/]|$)/.test(String(k))||(y&&clearTimeout(y),y=setTimeout(()=>void A(),REBUILD_DEBOUNCE_MS))}))}return{port:a,schema:n,async close(){d=!0,y&&clearTimeout(y);for(const g of N)g.close();await m,await stopChild(l)}}}o(startDevBackend,"startDevBackend");var FAKE_HOST_PREFIX="/__tego/host",FAKE_FILES_PREFIX="/__tego/files",MAX_JSON_BYTES=1024*1024;async function readBody(e,t=1/0){const r=[];let a=0;for await(const n of e){if(a+=n.length,a>t)throw Object.assign(new Error("body too large"),{status:413});r.push(n)}return Buffer.concat(r)}o(readBody,"readBody");function send(e,t,r){if(r===void 0){e.writeHead(t),e.end();return}e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(r))}o(send,"send");function storagePath(e,t){const r=path.resolve(e),a=path.resolve(r,t);if(!t||path.isAbsolute(t)||!a.startsWith(r+path.sep))throw Object.assign(new Error(`invalid storage key ${JSON.stringify(t)}`),{status:400});return a}o(storagePath,"storagePath");var metaOf=o(e=>`${e}.tego-meta.json`,"metaOf");async function head(e){const t=await promises.stat(e).catch(()=>null);if(!t?.isFile())return null;const r=await promises.readFile(metaOf(e),"utf8").then(a=>JSON.parse(a),()=>({}));return{size:t.size,contentType:r.contentType??null,versionTag:crypto.createHash("sha1").update(`${t.size}:${t.mtimeMs}`).digest("hex")}}o(head,"head");async function put(e,t,r){await promises.mkdir(path.dirname(e),{recursive:!0}),await promises.writeFile(e,t),await promises.writeFile(metaOf(e),JSON.stringify({contentType:r??null}))}o(put,"put");async function handleFakeHost(e,t,r){const a=new URL(e.url??"/","http://preview.local");try{if(a.pathname.startsWith(FAKE_FILES_PREFIX)){const s=storagePath(r.storageDir,a.searchParams.get("key")??""),l=await head(s);if(!l)return send(t,404);t.writeHead(200,{"content-type":l.contentType??"application/octet-stream"}),t.end(await promises.readFile(s));return}if(e.headers.authorization!==`Bearer ${r.token}`)return send(t,401,{error:"bad host API token"});const n=a.pathname.slice(FAKE_HOST_PREFIX.length)||"/",i=o(async()=>JSON.parse((await readBody(e,MAX_JSON_BYTES)).toString("utf8")||"{}"),"json"),u=o(s=>storagePath(r.storageDir,String(s??"")),"keyFile");switch(n){case"/config":return send(t,200,{data:{values:r.config()}});case"/log":{const{level:s,message:l,fields:d}=await i();return r.log(`[backend ${String(s??"info")}] ${String(l??"")}${d?` ${JSON.stringify(d)}`:""}`),send(t,200,{data:{}})}case"/events":{const{name:s,payload:l}=await i();return r.log(`[event] ${String(s)} ${JSON.stringify(l??null)}`),send(t,200,{data:{}})}case"/notifications":return r.log(`[notification] ${JSON.stringify(await i())}`),send(t,200,{data:{id:crypto.randomUUID()}});case"/directory/identity":{const{userId:s}=await i(),l=r.users().get(String(s));return send(t,200,{data:{active:!!l,roleNames:l??[],memberships:[],checkedAt:new Date().toISOString()}})}case"/directory/list":{const{kind:s,search:l,ids:d}=await i(),f=typeof l=="string"?l.toLowerCase():"",v=Array.isArray(d)?new Set(d.map(String)):void 0,y=s==="users"?[...r.users().keys()].filter(m=>(!v||v.has(m))&&m.toLowerCase().includes(f)).map(m=>({id:m,displayName:m,active:!0})):[];return send(t,200,{data:{items:y,hasMore:!1}})}case"/directory/match":{const{userId:s,principals:l}=await i(),d=Array.isArray(l)?l:[];return send(t,200,{data:{active:r.users().has(String(s)),matched:d.flatMap((f,v)=>f.kind==="user"&&f.id===s?[v]:[]),checkedAt:new Date().toISOString()}})}case"/directory/validate":{const{principals:s}=await i(),l=Array.isArray(s)?s:[],d=r.users();return send(t,200,{data:{invalid:l.flatMap((f,v)=>f.kind==="user"&&d.has(String(f.id))?[]:[v])}})}case"/storage/get":case"/storage/stream":{const s=u(a.searchParams.get("key"));if(e.method==="POST"&&n==="/storage/stream")return await put(s,await readBody(e),e.headers["content-type"]),send(t,200,{data:{}});const l=await head(s);if(!l)return send(t,404);let d=await promises.readFile(s);const f=Number(a.searchParams.get("bytes"));Number.isFinite(f)&&f>0&&(d=d.subarray(0,f)),t.writeHead(200,{"content-type":l.contentType??"application/octet-stream"}),t.end(d);return}case"/storage/put":return await put(u(a.searchParams.get("key")),await readBody(e),e.headers["content-type"]),send(t,200,{data:{}});case"/storage/head":{const s=await head(u((await i()).key));return s?send(t,200,{data:s}):send(t,404)}case"/storage/delete":{const s=u((await i()).key);return await promises.rm(s,{force:!0}),await promises.rm(metaOf(s),{force:!0}),send(t,200,{data:{}})}case"/storage/copy":{const{sourceKey:s,destinationKey:l}=await i(),d=u(s),f=u(l);return await head(d)?(await promises.mkdir(path.dirname(f),{recursive:!0}),await promises.copyFile(d,f),await promises.copyFile(metaOf(d),metaOf(f)).catch(()=>{}),send(t,200,{data:await head(f)})):send(t,404)}case"/storage/signed-url":{const{key:s}=await i();u(s);const l=`${FAKE_FILES_PREFIX}?key=${encodeURIComponent(String(s))}`;return send(t,200,{data:{url:`${r.origin()}${l}`,path:l}})}default:return r.log(`[host] ${n} is not available in local preview`),send(t,501,{error:{code:"not_available_in_preview",message:`${n} is not available in local preview`}})}}catch(n){const i=n.status??500;send(t,i,{error:{message:n instanceof Error?n.message:String(n)}})}}o(handleFakeHost,"handleFakeHost");var SDK_PACKAGE="@tego/plugin-sdk",SDK_IMPORT=JSON.stringify(SDK_PACKAGE),SDK_FRONTEND_IMPORT=JSON.stringify(`${SDK_PACKAGE}/frontend`);function shellFiles(e){return[{path:"index.html",contents:indexHtml(e)},{path:"main.tsx",contents:mainTsx(e)},{path:"shell.css",contents:SHELL_CSS},{path:"plugin-surface.tsx",contents:PLUGIN_SURFACE_STUB}]}o(shellFiles,"shellFiles");var escapeHtml=o(e=>e.replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),"escapeHtml");function indexHtml({displayName:e}){return`<!doctype html>
2
+ <html lang="en" class="h-full">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>${escapeHtml(e)} \xB7 local preview</title>
7
+ </head>
8
+ <body class="h-full">
9
+ <div id="tego-dev-bar"></div>
10
+ <div id="tego-dev-plugin"></div>
11
+ <script type="module" src="/main.tsx"><\/script>
12
+ </body>
13
+ </html>
14
+ `}o(indexHtml,"indexHtml");var SHELL_CSS=`@tailwind base;
15
+ @tailwind components;
16
+ @tailwind utilities;
17
+
18
+ html,
19
+ body {
20
+ height: 100%;
21
+ }
22
+
23
+ body {
24
+ display: flex;
25
+ flex-direction: column;
26
+ @apply bg-background text-foreground antialiased;
27
+ }
28
+
29
+ #tego-dev-plugin {
30
+ flex: 1;
31
+ min-height: 0;
32
+ overflow: auto;
33
+ }
34
+ `,PLUGIN_SURFACE_STUB=`import type { ReactNode } from 'react';
35
+
36
+ function Unavailable(): ReactNode {
37
+ return (
38
+ <div className='flex h-full items-center justify-center p-6 text-sm text-muted-foreground'>
39
+ Chat is not available in local preview.
40
+ </div>
41
+ );
42
+ }
43
+
44
+ export const ChatSurface = Unavailable;
45
+ export const ChatPanel = Unavailable;
46
+ export function useTopic() {
47
+ return { topic: undefined, topics: [], loading: false };
48
+ }
49
+ `;function mainTsx(e){const t=JSON.stringify({pluginId:e.pluginId,displayName:e.displayName,nav:e.nav.map(a=>({key:a.key,labelKey:a.labelKey,path:a.path??"/"})),config:e.config,locales:e.locales,defaultTarget:e.defaultTarget??"web",userHeader:DEV_USER_HEADER,rolesHeader:DEV_ROLES_HEADER,defaultUser:DEFAULT_DEV_USER_ID},null,2),r=e.entry?`import plugin from ${JSON.stringify(e.entry)};`:"const plugin = undefined;";return`// Generated by \`tego-plugin dev\` on every start; edits here are overwritten.
50
+ import '@tego/ui/styles/tokens.css';
51
+ import './shell.css';
52
+
53
+ import { pluginI18nNamespace } from ${SDK_IMPORT};
54
+ import type { PluginFrontendModule, PluginHostContext, PluginRoute } from ${SDK_FRONTEND_IMPORT};
55
+ import {
56
+ Button,
57
+ Input,
58
+ Select,
59
+ SelectContent,
60
+ SelectItem,
61
+ SelectTrigger,
62
+ SelectValue,
63
+ Toaster,
64
+ TooltipProvider,
65
+ } from '@tego/ui';
66
+ import i18next from 'i18next';
67
+ import { useState, useSyncExternalStore } from 'react';
68
+ import { createRoot } from 'react-dom/client';
69
+ import { initReactI18next } from 'react-i18next';
70
+
71
+ ${r}
72
+
73
+ const DEV = ${t};
74
+ const TARGET: 'web' | 'desktop' = /(?:^|;\\s*)tego-dev-target=desktop(?:;|$)/.test(document.cookie)
75
+ ? 'desktop'
76
+ : /(?:^|;\\s*)tego-dev-target=web(?:;|$)/.test(document.cookie)
77
+ ? 'web'
78
+ : DEV.defaultTarget;
79
+ const BASE = '/p/' + DEV.pluginId;
80
+ const NAMESPACE = pluginI18nNamespace(DEV.pluginId);
81
+
82
+ function stored(key: string, fallback: string): string {
83
+ try {
84
+ return localStorage.getItem('tegoDev.' + key) ?? fallback;
85
+ } catch {
86
+ return fallback;
87
+ }
88
+ }
89
+ function store(key: string, value: string): void {
90
+ try {
91
+ localStorage.setItem('tegoDev.' + key, value);
92
+ } catch {
93
+ // storage blocked: the choice lasts until the next reload
94
+ }
95
+ }
96
+
97
+ const user = {
98
+ userId: stored('userId', DEV.defaultUser),
99
+ roles: stored('roles', '').split(',').map(role => role.trim()).filter(Boolean),
100
+ };
101
+ const language = DEV.locales.includes(stored('lang', 'zh-CN')) ? stored('lang', 'zh-CN') : (DEV.locales[0] ?? 'en');
102
+ if (stored('theme', 'light') === 'dark') document.documentElement.classList.add('dark');
103
+
104
+ async function loadLocale(tag: string): Promise<void> {
105
+ if (i18next.hasResourceBundle(tag, NAMESPACE)) return;
106
+ const response = await fetch('/i18n/' + tag + '.json');
107
+ if (response.ok) i18next.addResourceBundle(tag, NAMESPACE, await response.json(), true, true);
108
+ }
109
+ await i18next.use(initReactI18next).init({
110
+ lng: language,
111
+ fallbackLng: false,
112
+ ns: [NAMESPACE],
113
+ defaultNS: NAMESPACE,
114
+ resources: {},
115
+ interpolation: { escapeValue: false },
116
+ });
117
+ await loadLocale(language);
118
+
119
+ const listeners = new Set<() => void>();
120
+ function readRoute(): PluginRoute {
121
+ const path = location.pathname.slice(BASE.length) || '/';
122
+ return { path: path.startsWith('/') ? path : '/' + path, search: location.search };
123
+ }
124
+ let route = readRoute();
125
+ function routeChanged(): void {
126
+ const next = readRoute();
127
+ if (next.path === route.path && next.search === route.search) return;
128
+ route = next;
129
+ for (const listener of listeners) listener();
130
+ }
131
+ addEventListener('popstate', routeChanged);
132
+ if (!location.pathname.startsWith(BASE)) history.replaceState(null, '', BASE + '/');
133
+
134
+ function navigate(to: string): void {
135
+ history.pushState(null, '', to.startsWith('/p/') ? to : BASE + (to.startsWith('/') ? to : '/' + to));
136
+ routeChanged();
137
+ }
138
+
139
+ const api: PluginHostContext['api'] = {
140
+ request: (path, init = {}) =>
141
+ fetch('/api/v1/tego-os/plugin-api/' + DEV.pluginId + (path.startsWith('/') ? path : '/' + path), {
142
+ ...init,
143
+ headers: {
144
+ ...(init.headers as Record<string, string> | undefined),
145
+ [DEV.userHeader]: user.userId,
146
+ [DEV.rolesHeader]: JSON.stringify(user.roles),
147
+ },
148
+ }),
149
+ async json<T>(path: string, init?: RequestInit): Promise<T> {
150
+ const response = await api.request(path, init);
151
+ if (!response.ok) throw new Error((init?.method ?? 'GET') + ' ' + path + ': ' + response.status);
152
+ return (await response.json()) as T;
153
+ },
154
+ };
155
+
156
+ const navKeys = DEV.nav.map(entry => entry.key);
157
+ const context: PluginHostContext = {
158
+ pluginId: DEV.pluginId,
159
+ layout: { collapseSidebar: () => () => {} },
160
+ basePath: BASE,
161
+ publicPagesUrl: location.origin + '/public/' + DEV.pluginId + '/',
162
+ hostUrl: path => new URL(path, location.origin).toString(),
163
+ user: { userId: user.userId, tenantId: 'dev-tenant', roles: user.roles, displayName: user.userId },
164
+ api,
165
+ route: {
166
+ current: () => route,
167
+ subscribe: listener => {
168
+ listeners.add(listener);
169
+ return () => listeners.delete(listener);
170
+ },
171
+ },
172
+ events: { subscribe: () => () => {}, connected: () => false, subscribeStatus: () => () => {} },
173
+ config: DEV.config,
174
+ navigate,
175
+ can: navKey => navKeys.includes(navKey),
176
+ // Host API 1.37, as the shells provide it: the preview prints what a plugin
177
+ // asked for, then does the browser equivalent.
178
+ platform: TARGET,
179
+ openExternal: async url => {
180
+ if (!/^https?:\\/\\//i.test(url)) throw new Error('openExternal takes an http(s) URL');
181
+ console.info('[preview] openExternal', url);
182
+ window.open(url, '_blank', 'noopener');
183
+ },
184
+ download: async request => {
185
+ const anchor = document.createElement('a');
186
+ let revoke: string | undefined;
187
+ if ('blob' in request) {
188
+ revoke = URL.createObjectURL(request.blob);
189
+ anchor.href = revoke;
190
+ anchor.download = request.fileName;
191
+ } else {
192
+ if (!request.path.startsWith('/')) throw new Error('download takes a root-relative host path');
193
+ anchor.href = context.hostUrl(request.path);
194
+ if (request.fileName) anchor.download = request.fileName;
195
+ }
196
+ console.info('[preview] download', 'blob' in request ? request.fileName : request.path);
197
+ document.body.append(anchor);
198
+ anchor.click();
199
+ anchor.remove();
200
+ if (revoke) setTimeout(() => URL.revokeObjectURL(revoke), 30_000);
201
+ },
202
+ copyText: async text => {
203
+ try {
204
+ await navigator.clipboard.writeText(text);
205
+ return true;
206
+ } catch {
207
+ return false;
208
+ }
209
+ },
210
+ };
211
+
212
+ // What the imitated shell's CSP refused on this page (the server prints them too).
213
+ const violations: string[] = [];
214
+ const violationListeners = new Set<() => void>();
215
+ document.addEventListener('securitypolicyviolation', event => {
216
+ violations.push(event.effectiveDirective + ': ' + (event.blockedURI || 'inline'));
217
+ for (const listener of violationListeners) listener();
218
+ });
219
+ function useViolations(): number {
220
+ return useSyncExternalStore(
221
+ listener => {
222
+ violationListeners.add(listener);
223
+ return () => violationListeners.delete(listener);
224
+ },
225
+ () => violations.length
226
+ );
227
+ }
228
+
229
+ function useRoute(): PluginRoute {
230
+ return useSyncExternalStore(context.route.subscribe, context.route.current);
231
+ }
232
+
233
+ function DevBar() {
234
+ const current = useRoute();
235
+ const [lang, setLang] = useState(language);
236
+ const [dark, setDark] = useState(document.documentElement.classList.contains('dark'));
237
+ const [userId, setUserId] = useState(user.userId);
238
+ const [roles, setRoles] = useState(user.roles.join(', '));
239
+ const blocked = useViolations();
240
+ const switchTarget = (next: 'web' | 'desktop') => {
241
+ const url = new URL(location.href);
242
+ url.searchParams.set('target', next);
243
+ location.assign(url.toString());
244
+ };
245
+ const switchUser = () => {
246
+ store('userId', userId.trim() || DEV.defaultUser);
247
+ store('roles', roles);
248
+ location.reload();
249
+ };
250
+ return (
251
+ <div className='flex shrink-0 items-center gap-2 border-b border-border bg-card px-3 py-2 text-sm'>
252
+ <span className='shrink-0 font-medium'>{DEV.displayName}</span>
253
+ <span className='shrink-0 rounded-control bg-sunken px-1.5 py-0.5 font-mono text-xs text-muted-foreground'>preview</span>
254
+ <nav className='flex min-w-0 flex-1 items-center gap-1 overflow-x-auto'>
255
+ {DEV.nav.map(entry => (
256
+ <Button
257
+ key={entry.key}
258
+ size='sm'
259
+ variant={current.path === entry.path ? 'secondary' : 'ghost'}
260
+ onClick={() => navigate(entry.path)}
261
+ >
262
+ {i18next.t(entry.labelKey, { ns: NAMESPACE, lng: lang })}
263
+ </Button>
264
+ ))}
265
+ </nav>
266
+ <Select
267
+ value={lang}
268
+ onValueChange={async next => {
269
+ await loadLocale(next);
270
+ await i18next.changeLanguage(next);
271
+ store('lang', next);
272
+ setLang(next);
273
+ }}
274
+ >
275
+ <SelectTrigger className='h-8 w-28' aria-label='Language'>
276
+ <SelectValue />
277
+ </SelectTrigger>
278
+ <SelectContent>
279
+ {DEV.locales.map(tag => (
280
+ <SelectItem key={tag} value={tag}>
281
+ {tag}
282
+ </SelectItem>
283
+ ))}
284
+ </SelectContent>
285
+ </Select>
286
+ <div className='flex shrink-0 items-center rounded-control border border-border p-0.5' role='group' aria-label='Shell'>
287
+ {(['web', 'desktop'] as const).map(target => (
288
+ <Button
289
+ key={target}
290
+ size='sm'
291
+ variant={TARGET === target ? 'secondary' : 'ghost'}
292
+ aria-pressed={TARGET === target}
293
+ onClick={() => TARGET !== target && switchTarget(target)}
294
+ >
295
+ {target === 'web' ? 'Web' : 'Desktop'}
296
+ </Button>
297
+ ))}
298
+ </div>
299
+ {blocked > 0 && (
300
+ <span
301
+ className='shrink-0 rounded-control bg-destructive-soft px-1.5 py-0.5 text-xs text-destructive'
302
+ title={violations.join('\\n')}
303
+ >
304
+ CSP blocked {blocked}
305
+ </span>
306
+ )}
307
+ <Button
308
+ size='sm'
309
+ variant='ghost'
310
+ onClick={() => {
311
+ document.documentElement.classList.toggle('dark', !dark);
312
+ store('theme', dark ? 'light' : 'dark');
313
+ setDark(!dark);
314
+ }}
315
+ >
316
+ {dark ? 'Light' : 'Dark'}
317
+ </Button>
318
+ <form
319
+ className='flex shrink-0 items-center gap-1'
320
+ onSubmit={event => {
321
+ event.preventDefault();
322
+ switchUser();
323
+ }}
324
+ >
325
+ <Input className='h-8 w-32' aria-label='User id' value={userId} onChange={event => setUserId(event.target.value)} />
326
+ <Input
327
+ className='h-8 w-36'
328
+ aria-label='Roles, comma-separated'
329
+ placeholder='roles'
330
+ value={roles}
331
+ onChange={event => setRoles(event.target.value)}
332
+ />
333
+ <Button size='sm' variant='outline' type='submit'>
334
+ Sign in as
335
+ </Button>
336
+ </form>
337
+ </div>
338
+ );
339
+ }
340
+
341
+ createRoot(document.getElementById('tego-dev-bar')!).render(
342
+ <TooltipProvider>
343
+ <DevBar />
344
+ <Toaster />
345
+ </TooltipProvider>
346
+ );
347
+
348
+ const mountPoint = document.getElementById('tego-dev-plugin')!;
349
+ const frontend = plugin as PluginFrontendModule | undefined;
350
+ if (frontend) {
351
+ frontend.mount(mountPoint, context);
352
+ } else {
353
+ mountPoint.innerHTML =
354
+ '<p style="padding:24px">This plugin has no frontend part; its API is served at /api/v1/tego-os/plugin-api/' +
355
+ DEV.pluginId +
356
+ '/</p>';
357
+ }
358
+ `}o(mainTsx,"mainTsx");var CSP_REPORT_PATH="/__tego/csp-report",CSP_REPORT_PREFIX="TEGO_DEV_CSP ",TARGET_COOKIE="tego-dev-target",DESKTOP_MAX_RESPONSE_BYTES=100*1024*1024,SHARED=["default-src 'self'","object-src 'none'","base-uri 'self'"],PREVIEW_CSP={web:[...SHARED,"script-src 'self' 'wasm-unsafe-eval'","style-src 'self' 'unsafe-inline'","img-src 'self' data: blob: https:","font-src 'self' data:","connect-src 'self' wss: ws:","frame-src 'self'","worker-src 'self' blob:"].join("; "),desktop:[...SHARED,"script-src 'self' 'wasm-unsafe-eval'","style-src 'self' 'unsafe-inline' https:","img-src 'self' data: blob: http: https:","font-src 'self' data: blob: https:","media-src 'self' data: blob:","worker-src 'self' blob:","connect-src 'self' http: https: ws: wss:","frame-src 'self'"].join("; ")};function isPreviewTarget(e){return e==="web"||e==="desktop"}o(isPreviewTarget,"isPreviewTarget");function targetOf(e,t){const r=new URL(e.url??"/","http://preview.local").searchParams.get("target");if(isPreviewTarget(r))return r;const a=/(?:^|;\s*)tego-dev-target=(web|desktop)(?:;|$)/.exec(String(e.headers.cookie??""))?.[1];return isPreviewTarget(a)?a:t}o(targetOf,"targetOf");function parseCspReport(e){try{const t=JSON.parse(e)["csp-report"];if(!t)return;const r=String(t["effective-directive"]??t["violated-directive"]??""),a=String(t["blocked-uri"]??"");if(!r)return;const n=typeof t["source-file"]=="string"?t["source-file"]:void 0,i=typeof t["line-number"]=="number"?t["line-number"]:void 0;return{directive:r,blocked:a,...n?{source:n}:{},...i?{line:i}:{}}}catch{return}}o(parseCspReport,"parseCspReport");var DEFAULT_DEV_PORT=5280,PORT_ATTEMPTS=20,DEV_READY_PREFIX="TEGO_DEV_READY ",DEV_DIR=".tego-dev",PLUGIN_API_PREFIX="/api/v1/tego-os/plugin-api/";function displayNameOf(e){const{displayName:t}=e;return typeof t=="string"?t:t.en??t["zh-CN"]??Object.values(t)[0]??e.id}o(displayNameOf,"displayNameOf");function packageDir(e,t){for(let r=path.resolve(e);;r=path.dirname(r)){const a=path.join(r,"node_modules",...t.split("/"));if(fs.existsSync(path.join(a,"package.json")))return fs.realpathSync(a);if(path.dirname(r)===r)return}}o(packageDir,"packageDir");function sendJson(e,t,r){e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(r))}o(sendJson,"sendJson");function listen(e,t,r){return new Promise((a,n)=>{const i=o(s=>{e.off("listening",u),n(s)},"onError"),u=o(()=>{e.off("error",i);const s=e.address();a(typeof s=="object"&&s?s.port:t)},"onListening");e.once("error",i),e.once("listening",u),e.listen(t,r)})}o(listen,"listen");async function shellTailwind(e,t){const r=module$1.createRequire(path.join(e,"vite.config.ts"));let a,n;try{a=r("@tego/ui/tailwind-preset"),n=path.dirname(r.resolve("@tego/ui"))}catch(u){throw new Error(`The preview cannot load @tego/ui's Tailwind preset from ${e}: ${u instanceof Error?u.message:String(u)}. Install the plugin's dependencies.`,{cause:u})}const i=(await import("tailwindcss")).default;return i({presets:[a],content:[path.join(n,"**/*.{js,cjs}"),path.join(t,"*.tsx")]})}o(shellTailwind,"shellTailwind");function perStylesheet(e,t,r){return{postcssPlugin:"tego-dev-stylesheets",async Once(a,n){const i=a.source?.input.file,u=i&&path.resolve(i)===e?[t]:r;if(u.length===0)return;const s=await n.postcss(u).process(a,{from:i});n.result.messages.push(...s.messages)}}}o(perStylesheet,"perStylesheet");function servePlugins(e){return Array.isArray(e)?e.flat(1/0).map(t=>{if(!t||typeof t!="object")return t;const{buildStart:r}=t;return typeof r!="function"?t:{...t,buildStart(...a){const n=new Proxy(this,{get(i,u){if(u==="emitFile")return()=>"";const s=Reflect.get(i,u);return typeof s=="function"?s.bind(i):s}});return r.apply(n,a)}}}):e}o(servePlugins,"servePlugins");async function startDevServer(e){const t=path.resolve(e.root),r=e.log??(c=>console.log(c)),a=await chunk4LKRXDYY_cjs.readManifest(t),n=chunk2P6UEAPV_cjs.resolvePluginParts(a),i=path.join(t,DEV_DIR),u=path.join(i,"shell"),s=crypto.randomBytes(32).toString("hex"),l=crypto.randomBytes(24).toString("hex");let d="";const f=new Map;let v,y={};const m=n.frontend?path.resolve(t,n.frontend.dir):t,{loadConfigFromFile:D,createServer:A,mergeConfig:N}=await import("vite");if(n.frontend){const c=path.join(m,"vite.config.ts");fs.existsSync(c)&&(y=(await D({command:"serve",mode:"development"},c,t))?.config??{});const p=y.build?.rollupOptions?.input,w=path.resolve(t,typeof p=="string"?p:`${n.frontend.dir}/src/index.tsx`);if(!fs.existsSync(w))throw new Error(`The frontend entry ${path.relative(t,w)} does not exist.`);v=path.relative(u,w).split(path.sep).join("/"),v.startsWith(".")||(v=`./${v}`)}const g=o(()=>n.frontend?chunk4LKRXDYY_cjs.readPluginLocales(t,a,n.frontend.i18nDirPath):Promise.resolve(new Map),"localeFiles"),E=[...(await g()).keys()].map(c=>c.replace(/\.json$/,""));await promises.mkdir(u,{recursive:!0});for(const c of shellFiles({pluginId:a.id,displayName:displayNameOf(a),nav:n.frontend?.nav??[],config:n.frontend?.config?chunkMWMGJJ74_cjs.applyConfigDefaults(n.frontend.config.schema,{}):{},entry:v,locales:E,defaultTarget:e.target??"web"}))await promises.writeFile(path.join(u,c.path),c.contents);let _,k;const F=o(()=>n.backend?.config?chunkMWMGJJ74_cjs.applyConfigDefaults(n.backend.config.schema,{}):{},"backendConfig"),R=http.createServer((c,p)=>void M(c,p));async function M(c,p){const w=(c.url??"/").split("?")[0],T=targetOf(c,e.target??"web");try{if(w==="/favicon.ico"){p.writeHead(204),p.end();return}if(w===CSP_REPORT_PATH){const h=await new Promise(L=>{let P="";c.setEncoding("utf8"),c.on("data",x=>P+=x),c.on("end",()=>L(P))}),b=parseCspReport(h);b&&(r(`[csp:${T}] blocked ${b.blocked||"(inline)"} by ${b.directive}${b.source?` in ${b.source}${b.line?`:${b.line}`:""}`:""}`),r(`${CSP_REPORT_PREFIX}${JSON.stringify({target:T,...b})}`)),p.writeHead(204),p.end();return}if(w.startsWith(FAKE_HOST_PREFIX)||w.startsWith(FAKE_FILES_PREFIX)){await handleFakeHost(c,p,{token:l,storageDir:path.join(i,"storage"),config:F,origin:o(()=>d,"origin"),users:o(()=>f,"users"),log:r});return}const S=/^\/i18n\/([A-Za-z-]+)\.json$/.exec(w);if(S){const h=(await g()).get(`${S[1]}.json`);if(h===void 0)return sendJson(p,404,{error:`no ${S[1]}.json`});p.writeHead(200,{"content-type":"application/json"}),p.end(h);return}const I=`${PLUGIN_API_PREFIX}${a.id}`;if(w===I||w.startsWith(`${I}/`)){q(c,p,(c.url??"/").slice(I.length)||"/",T);return}if(String(c.headers.accept??"").includes("text/html")){p.setHeader("Content-Security-Policy",`${PREVIEW_CSP[T]}; report-uri ${CSP_REPORT_PATH}`);const h=new URL(c.url??"/","http://preview.local").searchParams.get("target");isPreviewTarget(h)&&p.setHeader("Set-Cookie",`${TARGET_COOKIE}=${h}; Path=/; SameSite=Lax`)}C.middlewares(c,p,()=>sendJson(p,404,{error:`${w} not found`}))}catch(S){sendJson(p,500,{error:S instanceof Error?S.message:String(S)})}}o(M,"route");function q(c,p,w,T){if(!_){sendJson(p,503,{error:k??"The plugin has no backend part."});return}const S=devCallerOf(c.headers);f.set(S.userId,S.roles);const I=http.request({host:"127.0.0.1",port:_.port,method:c.method,path:w,headers:{...gatewayHeaders(c.headers,S,s),...T==="desktop"?{"accept-encoding":"identity"}:{}}},h=>{if(T!=="desktop"){p.writeHead(h.statusCode??502,h.headers),h.pipe(p);return}const b=[];let L=0,P=!1;h.on("data",x=>{if(!P){if(L+=x.length,L>DESKTOP_MAX_RESPONSE_BYTES){P=!0,h.destroy(),r(`[desktop] ${c.method} ${w}: response over 100 MB refused (413)`),sendJson(p,413,{error:"Response over 100 MB: the desktop app refuses it. Serve large files through storage paths."});return}b.push(x)}}),h.on("end",()=>{if(P)return;const x=Buffer.concat(b),G={...h.headers};delete G["transfer-encoding"],G["content-length"]=String(x.length),p.writeHead(h.statusCode??502,G),p.end(x)})});I.on("error",h=>{p.headersSent?p.destroy():sendJson(p,502,{error:`The backend is not answering (${h.message}); see the terminal.`})}),c.pipe(I)}o(q,"proxy");const K=path.join(u,"shell.css"),J=(()=>{const c=y.css?.postcss;return c&&typeof c=="object"?c.plugins??[]:[]})(),$=(()=>{const c=packageDir(m,"react-i18next");return(c&&packageDir(c,"i18next"))??packageDir(m,"i18next")})(),{css:X,mode:Y,build:z,...U}=y;U.plugins=servePlugins(U.plugins);const C=await A(N(U,{configFile:!1,root:u,mode:"development",appType:"spa",clearScreen:!1,logLevel:"info",esbuild:{jsx:"automatic",jsxDev:!1},css:{postcss:{plugins:[perStylesheet(K,await shellTailwind(m,u),J)]}},resolve:{alias:[{find:"@tego/chat/plugin-surface",replacement:path.join(u,"plugin-surface.tsx")},...$?[{find:/^i18next$/,replacement:$}]:[]]},server:{middlewareMode:!0,hmr:{server:R},fs:{allow:[t,u,...$?[$]:[]]}},optimizeDeps:{entries:[path.join(u,"index.html")]}})),O=e.host??"127.0.0.1";let j;const H=e.port??DEFAULT_DEV_PORT;for(let c=0;j===void 0;c++)try{j=await listen(R,H===0?0:H+c,O)}catch(p){if(p.code!=="EADDRINUSE"||H===0||c>=PORT_ATTEMPTS)throw await C.close(),p}const V=O==="0.0.0.0"||O==="::"?"127.0.0.1":O;if(d=`http://${V.includes(":")?`[${V}]`:V}:${j}`,!n.backend)k="The plugin has no backend part.";else if(e.backend===!1)k="The backend is off (--no-backend).";else if(!e.databaseUrl)k="The backend needs a PostgreSQL: start the preview with DATABASE_URL=postgres://\u2026 (each plugin gets its own schema).";else try{_=await startDevBackend({root:t,pluginId:a.id,version:a.version,part:n.backend,databaseUrl:e.databaseUrl,outDir:path.join(i,"backend"),hostApiUrl:`${d}${FAKE_HOST_PREFIX}`,hostApiToken:l,gatewayKey:s,log:r})}catch(c){k=`The backend did not start: ${c instanceof Error?c.message:String(c)}`}k&&n.backend&&r(`[backend] ${k}`);const B=`${d}/p/${a.id}/`;return r(`${a.id} ${a.version}: local preview at ${B}`),e.databaseUrl&&_&&r(` database ${redactUrl(e.databaseUrl)}, schema ${_.schema}`),r(`${DEV_READY_PREFIX}${JSON.stringify({url:B})}`),{url:B,async close(){await _?.close(),await C.close(),R.closeAllConnections(),await new Promise(c=>R.close(()=>c()))}}}o(startDevServer,"startDevServer"),exports.CSP_REPORT_PREFIX=CSP_REPORT_PREFIX,exports.DEFAULT_DEV_PORT=DEFAULT_DEV_PORT,exports.DEV_DIR=DEV_DIR,exports.DEV_READY_PREFIX=DEV_READY_PREFIX,exports.DEV_ROLES_HEADER=DEV_ROLES_HEADER,exports.DEV_TENANT_ID=DEV_TENANT_ID,exports.DEV_USER_HEADER=DEV_USER_HEADER,exports.PREVIEW_CSP=PREVIEW_CSP,exports.applyDevMigrations=applyDevMigrations,exports.devCallerOf=devCallerOf,exports.devDatabaseUrl=devDatabaseUrl,exports.devSchemaName=devSchemaName,exports.gatewayHeaders=gatewayHeaders,exports.handleFakeHost=handleFakeHost,exports.parseCspReport=parseCspReport,exports.shellFiles=shellFiles,exports.startDevServer=startDevServer,exports.storagePath=storagePath,exports.targetOf=targetOf;
package/dist/dev.d.cts ADDED
@@ -0,0 +1,144 @@
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { P as PluginNavEntry } from './manifest-types-CUTNfJTa.cjs';
3
+
4
+ /**
5
+ * The two shells a plugin page runs in, as the local preview imitates them.
6
+ *
7
+ * - `web`: the platform's nginx CSP (`docker/ai-studio/nginx.conf`) — the page
8
+ * may connect to the platform only. Its per-request nonce is left out: Vite's
9
+ * dev scripts cannot carry one, and what the nonce guards (injected inline
10
+ * scripts, `eval`) is refused here the same way.
11
+ * - `desktop`: the Tauri app's CSP (`apps/ai-studio/src-tauri/tauri.conf.json`)
12
+ * — no `eval`/`new Function`, no `blob:` scripts — and its protocol proxy,
13
+ * which buffers every `ctx.api` response whole, refuses one over 100 MB, and
14
+ * strips `accept-encoding`.
15
+ *
16
+ * Both report violations to the preview, which prints them, so a dependency
17
+ * that compiles strings or a call to a third-party URL shows up while
18
+ * developing instead of after release.
19
+ */
20
+
21
+ type PreviewTarget = 'web' | 'desktop';
22
+ /** The machine-readable line tools watch for (`TEGO_DEV_CSP {"target",…}`). */
23
+ declare const CSP_REPORT_PREFIX = "TEGO_DEV_CSP ";
24
+ declare const PREVIEW_CSP: Record<PreviewTarget, string>;
25
+ /** `?target=` wins, then the cookie the shell's switch sets, then the default. */
26
+ declare function targetOf(req: Pick<IncomingMessage, 'url' | 'headers'>, fallback: PreviewTarget): PreviewTarget;
27
+ interface CspViolation {
28
+ directive: string;
29
+ blocked: string;
30
+ source?: string;
31
+ line?: number;
32
+ }
33
+ /** A browser's `application/csp-report` body; `undefined` when it is not one. */
34
+ declare function parseCspReport(body: string): CspViolation | undefined;
35
+
36
+ /** `tego_dev_<id>` with every character Postgres would need quoted folded to `_`. */
37
+ declare function devSchemaName(pluginId: string): string;
38
+ /**
39
+ * The database URL the backend gets: the developer's, with the schema pinned
40
+ * as the only `search_path` entry (percent-encoded by hand, as the host does:
41
+ * libpq reads a `+` literally).
42
+ */
43
+ declare function devDatabaseUrl(databaseUrl: string, schema: string): string;
44
+ /** Applies the files not yet in the ledger, in name order; returns their names. */
45
+ declare function applyDevMigrations(options: {
46
+ databaseUrl: string;
47
+ schema: string;
48
+ migrationsDir: string;
49
+ tenantId: string;
50
+ }): Promise<string[]>;
51
+
52
+ /** Who the preview shell says is calling; sent by the shell on every API request. */
53
+ declare const DEV_USER_HEADER = "x-tego-dev-user-id";
54
+ declare const DEV_ROLES_HEADER = "x-tego-dev-roles";
55
+ declare const DEV_TENANT_ID = "dev-tenant";
56
+ interface DevCaller {
57
+ userId: string;
58
+ roles: string[];
59
+ }
60
+ /** The caller the shell named, falling back to the default dev user; never throws. */
61
+ declare function devCallerOf(headers: Record<string, string | string[] | undefined>): DevCaller;
62
+ /**
63
+ * Request headers for the backend: the browser's, minus anything that could
64
+ * pass for identity (cookies, authorization, every `x-tego-*`), plus the
65
+ * signed context `serveBackend` verifies.
66
+ */
67
+ declare function gatewayHeaders(incoming: Record<string, string | string[] | undefined>, caller: DevCaller, key: string, nowMs?: number): Record<string, string>;
68
+
69
+ interface FakeHostOptions {
70
+ token: string;
71
+ storageDir: string;
72
+ /** Backend config values, defaults applied. */
73
+ config: () => Record<string, unknown>;
74
+ /** The preview's origin, for signed URLs. */
75
+ origin: () => string;
76
+ /** Users the preview has made calls as, with the roles they had. */
77
+ users: () => ReadonlyMap<string, string[]>;
78
+ log(line: string): void;
79
+ }
80
+ /** A storage key as a file below the storage dir; refuses `..` and absolute keys. */
81
+ declare function storagePath(storageDir: string, key: string): string;
82
+ /** Handles a request below {@link FAKE_HOST_PREFIX} or {@link FAKE_FILES_PREFIX}. */
83
+ declare function handleFakeHost(req: IncomingMessage, res: ServerResponse, options: FakeHostOptions): Promise<void>;
84
+
85
+ /**
86
+ * The page the local preview serves: a small stand-in for the shell's plugin
87
+ * page, written into the plugin's `.tego-dev/shell/` on every start.
88
+ *
89
+ * Written into the plugin rather than served from this package so that its
90
+ * imports (`react`, `@tego/ui`, `react-i18next`) resolve to the plugin's own
91
+ * installed copies — the same single instances the plugin's code imports, as
92
+ * in the shell, where they are shared rather than bundled twice.
93
+ *
94
+ * It mounts the plugin's source entry with a `PluginHostContext` built the
95
+ * way the shell builds one: `basePath` `/p/<id>`, history-backed routing,
96
+ * `ctx.api` at `/api/v1/tego-os/plugin-api/<id>/*`, the frontend config's
97
+ * defaults. What only the platform has (`ai`, `office`, live events) is
98
+ * absent or inert. The top bar switches page, language, theme and the user
99
+ * the API calls are made as.
100
+ */
101
+
102
+ interface ShellOptions {
103
+ pluginId: string;
104
+ displayName: string;
105
+ nav: PluginNavEntry[];
106
+ config: Record<string, unknown>;
107
+ /** Import specifier of the plugin's source entry, relative to the shell dir; none without a frontend. */
108
+ entry?: string | undefined;
109
+ /** Locales the plugin ships (`en.json` → `en`). */
110
+ locales: string[];
111
+ /** The shell imitated when the page has not chosen one. */
112
+ defaultTarget?: 'web' | 'desktop';
113
+ }
114
+ interface ShellFile {
115
+ path: string;
116
+ contents: string;
117
+ }
118
+ declare function shellFiles(options: ShellOptions): ShellFile[];
119
+
120
+ /** First port tried; the next free one is taken when it is busy. */
121
+ declare const DEFAULT_DEV_PORT = 5280;
122
+ /** The line tools (Tego Studio) wait for; the JSON after it is `{ "url" }`. */
123
+ declare const DEV_READY_PREFIX = "TEGO_DEV_READY ";
124
+ declare const DEV_DIR = ".tego-dev";
125
+ interface DevServerOptions {
126
+ /** The plugin folder (holding tego.plugin.json). */
127
+ root: string;
128
+ /** 0 for any free port; defaults to {@link DEFAULT_DEV_PORT} or the next free one. */
129
+ port?: number;
130
+ host?: string;
131
+ /** Run the backend part (needs `databaseUrl`); default true. */
132
+ backend?: boolean;
133
+ /** Which shell to imitate by default (CSP, network proxy); the page can switch. Default `web`. */
134
+ target?: PreviewTarget;
135
+ databaseUrl?: string;
136
+ log?(line: string): void;
137
+ }
138
+ interface DevServer {
139
+ url: string;
140
+ close(): Promise<void>;
141
+ }
142
+ declare function startDevServer(options: DevServerOptions): Promise<DevServer>;
143
+
144
+ export { CSP_REPORT_PREFIX, type CspViolation, DEFAULT_DEV_PORT, DEV_DIR, DEV_READY_PREFIX, DEV_ROLES_HEADER, DEV_TENANT_ID, DEV_USER_HEADER, type DevServer, type DevServerOptions, PREVIEW_CSP, type PreviewTarget, applyDevMigrations, devCallerOf, devDatabaseUrl, devSchemaName, gatewayHeaders, handleFakeHost, parseCspReport, shellFiles, startDevServer, storagePath, targetOf };