fleetbo-svro 1.0.46 → 1.0.48

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/dist/cli.cjs CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- var Q=(e,o)=>()=>{try{return o||e((o={exports:{}}).exports,o),o.exports}catch(s){throw o=0,s}};var J=Q((Ne,$)=>{var a=require("fs"),b=require("path"),Z=require("https"),{execSync:ee}=require("child_process"),te="\x1B[38;2;231;233;237m",oe="\x1B[31m",j="\x1B[0m";function g(e){console.log(` ${te}${e}${j}`)}function h(e){console.error(` ${oe}${e}${j}`)}function ne(e){let o={};return e.forEach(s=>{if(s.startsWith("--")){let[n,r]=s.slice(2).split("=");n&&r&&(o[n]=r)}}),o}function A(e,o){try{let s=JSON.parse(a.readFileSync(e,"utf8"));return!!(s.dependencies&&s.dependencies[o]||s.devDependencies&&s.devDependencies[o])}catch{return!1}}function se(e,o){try{return a.existsSync(b.join(e,"node_modules",o,"package.json"))}catch{return!1}}function re(e,o){if(a.existsSync(b.join(e,"pnpm-lock.yaml")))return"pnpm";if(a.existsSync(b.join(e,"yarn.lock")))return"yarn";if(a.existsSync(b.join(e,"bun.lockb")))return"bun";try{let s=JSON.parse(a.readFileSync(o,"utf8"));if(typeof s.packageManager=="string"){if(s.packageManager.startsWith("pnpm"))return"pnpm";if(s.packageManager.startsWith("yarn"))return"yarn";if(s.packageManager.startsWith("bun"))return"bun"}}catch{}return"npm"}function ie(e,o){if(!A(o,"fleetbo-svro")||!se(e,"fleetbo-svro")){let s=re(e,o),n={pnpm:"pnpm add fleetbo-svro",yarn:"yarn add fleetbo-svro",bun:"bun add fleetbo-svro",npm:"npm install fleetbo-svro"}[s];g(`\u2192 Installing fleetbo-svro into the project (detected: ${s})...`);try{ee(n,{cwd:e,stdio:"inherit"}),g("fleetbo-svro installed successfully!")}catch(r){h(`\u26A0\uFE0F Automatic installation failed: ${r.message}`),h(`\u{1F449} Please run '${n}' manually.`)}}}function le(e){let o=b.join(e,"svro.schema.json");if(a.existsSync(o))return;let s=new Date().toISOString(),n={createdAt:s,patchedAt:s,schemaVersion:1,collections:{}};a.writeFileSync(o,JSON.stringify(n,null,2)+`
3
- `),g("\u2192 Created svro.schema.json at project root.")}function ae(e){let o=b.join(e,".env"),s=`
2
+ var Q=(e,o)=>()=>{try{return o||e((o={exports:{}}).exports,o),o.exports}catch(r){throw o=0,r}};var J=Q((ke,$)=>{var a=require("fs"),f=require("path"),Z=require("https"),{execSync:ee}=require("child_process"),te="\x1B[38;2;231;233;237m",oe="\x1B[31m",j="\x1B[0m";function g(e){console.log(` ${te}${e}${j}`)}function E(e){console.error(` ${oe}${e}${j}`)}function ne(e){let o={};return e.forEach(r=>{if(r.startsWith("--")){let[n,s]=r.slice(2).split("=");n&&s&&(o[n]=s)}}),o}function w(e,o){try{let r=JSON.parse(a.readFileSync(e,"utf8"));return!!(r.dependencies&&r.dependencies[o]||r.devDependencies&&r.devDependencies[o])}catch{return!1}}function re(e,o){try{return a.existsSync(f.join(e,"node_modules",o,"package.json"))}catch{return!1}}function se(e,o){if(a.existsSync(f.join(e,"pnpm-lock.yaml")))return"pnpm";if(a.existsSync(f.join(e,"yarn.lock")))return"yarn";if(a.existsSync(f.join(e,"bun.lockb")))return"bun";try{let r=JSON.parse(a.readFileSync(o,"utf8"));if(typeof r.packageManager=="string"){if(r.packageManager.startsWith("pnpm"))return"pnpm";if(r.packageManager.startsWith("yarn"))return"yarn";if(r.packageManager.startsWith("bun"))return"bun"}}catch{}return"npm"}function ie(e,o){if(!w(o,"fleetbo-svro")||!re(e,"fleetbo-svro")){let r=se(e,o),n={pnpm:"pnpm add fleetbo-svro",yarn:"yarn add fleetbo-svro",bun:"bun add fleetbo-svro",npm:"npm install fleetbo-svro"}[r];g(`\u2192 Installing fleetbo-svro into the project (detected: ${r})...`);try{ee(n,{cwd:e,stdio:"inherit"}),g("fleetbo-svro installed successfully!")}catch(s){E(`\u26A0\uFE0F Automatic installation failed: ${s.message}`),E(`\u{1F449} Please run '${n}' manually.`)}}}function le(e){let o=f.join(e,"svro.schema.json");if(a.existsSync(o))return;let r=new Date().toISOString(),n={createdAt:r,patchedAt:r,schemaVersion:1,collections:{}};a.writeFileSync(o,JSON.stringify(n,null,2)+`
3
+ `),g("\u2192 Created svro.schema.json at project root.")}function ae(e){let o=f.join(e,".env"),r=`
4
4
  # Fleetbo UI Sandbox Mode
5
5
  # true = Sandbox mode: simulates writes locally for fluid UI testing; no DB access and IDE alert.
6
6
  # false = Strict production mode: enforces schema contracts and persists to DB
7
7
  VITE_FLEETBO_PROTOTYPE=true
8
- `;if(!a.existsSync(o))a.writeFileSync(o,s.trimStart()),g("\u2192 Created .env with VITE_FLEETBO_PROTOTYPE=true");else{let n=a.readFileSync(o,"utf8");!n.includes("VITE_FLEETBO_PROTOTYPE")&&!n.includes("FLEETBO_PROTOTYPE")&&(a.appendFileSync(o,s),g("\u2192 Injected VITE_FLEETBO_PROTOTYPE=true into existing .env"))}}function ce(e){let o=b.join(e,"src");if(!a.existsSync(o))return;let s=b.join(o,"fleetbo.d.ts");if(a.existsSync(s))return;let n=`/* eslint-disable */
8
+ `;if(!a.existsSync(o))a.writeFileSync(o,r.trimStart()),g("\u2192 Created .env with VITE_FLEETBO_PROTOTYPE=true");else{let n=a.readFileSync(o,"utf8");!n.includes("VITE_FLEETBO_PROTOTYPE")&&!n.includes("FLEETBO_PROTOTYPE")&&(a.appendFileSync(o,r),g("\u2192 Injected VITE_FLEETBO_PROTOTYPE=true into existing .env"))}}function ce(e){let o=f.join(e,"src");if(!a.existsSync(o))return;let r=f.join(o,"fleetbo.d.ts");if(a.existsSync(r))return;let n=`/* eslint-disable */
9
9
  /* prettier-ignore */
10
10
  // @ts-nocheck
11
11
  export {}
@@ -70,16 +70,16 @@ declare global {
70
70
  'fleetbo-reference': FleetboProp;
71
71
  }
72
72
  }
73
- `;try{a.writeFileSync(s,n),g("\u2192 Created src/fleetbo.d.ts stub for instant IDE auto-completion.")}catch(r){h(`\u26A0\uFE0F Unable to create src/fleetbo.d.ts: ${r.message}`)}}function pe(e){let o=b.join(e,"index.d.ts");a.existsSync(o)||g("\u2192 Verified index.d.ts presence.")}function de(e){let o=["tsconfig.json","jsconfig.json"];for(let s of o){let n=b.join(e,s);if(a.existsSync(n)){let r=new Date;a.utimesSync(n,r,r);break}}}function ue(e){return new Promise((o,s)=>{let n=JSON.stringify({token:e}),r={hostname:"bootstrapproject-jqycakhlxa-uc.a.run.app",path:"/",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n)}},p=Z.request(r,t=>{let i="";t.on("data",l=>{i+=l}),t.on("end",()=>{if(t.statusCode>=200&&t.statusCode<300)try{o(JSON.parse(i))}catch{s(new Error("Invalid response received from Fleetbo server."))}else try{let l=JSON.parse(i);s(new Error(l.error||`Server error ${t.statusCode}`))}catch{s(new Error(`Server error ${t.statusCode}`))}})});p.on("error",t=>s(t)),p.write(n),p.end()})}async function be(e,o=[]){let s=b.join(e,".env");if(a.existsSync(s)&&a.readFileSync(s,"utf8").includes("VITE_FLEETBO_DB_KEY")){g("\u2192 Fleetbo environment variables already present in .env \u2014 skipping step.");return}let n=ne(o),r=n.keyApp,p=n.token||n.bootstrapToken,t=n.email||"";(!r||!p)&&(h("\u26A0\uFE0F Missing required parameters."),h("\u{1F449} Usage: npx fleetbo-svro init --keyApp=YOUR_KEY --token=YOUR_TOKEN"),process.exit(1)),g("\u2192 Exchanging bootstrap token for project keys...");let i;try{i=await ue(p)}catch(u){h(`\u26A0\uFE0F Token exchange failed: ${u.message}`),h("\u{1F449} The token may have expired (15 min limit) or was already used. Please regenerate one from the Fleetbo dashboard."),process.exit(1)}(!i.enterpriseId||!i.fleetboDBKey)&&(h("\u26A0\uFE0F Incomplete response from Fleetbo server."),process.exit(1));let l=i.facebookAppId||n.fbAppId||n.facebookAppId||"11967268204758",c=`
73
+ `;try{a.writeFileSync(r,n),g("\u2192 Created src/fleetbo.d.ts stub for instant IDE auto-completion.")}catch(s){E(`\u26A0\uFE0F Unable to create src/fleetbo.d.ts: ${s.message}`)}}function de(e){let o=f.join(e,"index.d.ts");a.existsSync(o)||g("\u2192 Verified index.d.ts presence.")}function pe(e){let o=["tsconfig.json","jsconfig.json"];for(let r of o){let n=f.join(e,r);if(a.existsSync(n)){let s=new Date;a.utimesSync(n,s,s);break}}}function ue(e){return new Promise((o,r)=>{let n=JSON.stringify({token:e}),s={hostname:"bootstrapproject-jqycakhlxa-uc.a.run.app",path:"/",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n)}},c=Z.request(s,t=>{let i="";t.on("data",l=>{i+=l}),t.on("end",()=>{if(t.statusCode>=200&&t.statusCode<300)try{o(JSON.parse(i))}catch{r(new Error("Invalid response received from Fleetbo server."))}else try{let l=JSON.parse(i);r(new Error(l.error||`Server error ${t.statusCode}`))}catch{r(new Error(`Server error ${t.statusCode}`))}})});c.on("error",t=>r(t)),c.write(n),c.end()})}async function be(e,o=[]){let r=f.join(e,".env");if(a.existsSync(r)&&a.readFileSync(r,"utf8").includes("VITE_FLEETBO_DB_KEY")){g("\u2192 Fleetbo environment variables already present in .env \u2014 skipping step.");return}let n=ne(o),s=n.keyApp,c=n.token||n.bootstrapToken,t=n.email||"";(!s||!c)&&(E("\u26A0\uFE0F Missing required parameters."),E("\u{1F449} Usage: npx fleetbo-svro init --keyApp=YOUR_KEY --token=YOUR_TOKEN"),process.exit(1)),g("\u2192 Exchanging bootstrap token for project keys...");let i;try{i=await ue(c)}catch(b){E(`\u26A0\uFE0F Token exchange failed: ${b.message}`),E("\u{1F449} The token may have expired (15 min limit) or was already used. Please regenerate one from the Fleetbo dashboard."),process.exit(1)}(!i.enterpriseId||!i.fleetboDBKey)&&(E("\u26A0\uFE0F Incomplete response from Fleetbo server."),process.exit(1));let l=i.facebookAppId||n.fbAppId||n.facebookAppId||"11967268204758",d=`
74
74
  VITE_FLEETBO_DB_KEY=${i.fleetboDBKey}
75
75
  VITE_FLEETBO_ENTERPRISE_ID=${i.enterpriseId}
76
- VITE_FLEETBO_KEY_APP=${r}
76
+ VITE_FLEETBO_KEY_APP=${s}
77
77
  ${t?`VITE_FLEETBO_TESTER_EMAIL=${t}
78
78
  `:""}VITE_FLEETBO_FACEBOOK_APP_ID=${l}
79
- `;a.appendFileSync(s,c),g(".env file updated successfully with Fleetbo keys!")}function L(e){let o=b.join(e,"svro.d.ts");if(a.existsSync(o))try{a.unlinkSync(o),g("\u2192 Removed legacy svro.d.ts from project root.")}catch{}}function _(e,o){if(process.env.FLEETBO_SKIP_TYPECHECK_SETUP)return;let s=b.join(e,"tsconfig.json"),n=b.join(e,"jsconfig.json"),r=a.existsSync(s)?s:n,p=!a.existsSync(r),t={};if(!p)try{t=JSON.parse(a.readFileSync(r,"utf8"))}catch{h(`\u26A0\uFE0F Unable to read ${b.basename(r)} (Invalid JSON).`);return}t.compilerOptions=t.compilerOptions||{};let i=!1,l=A(o,"react");p?(t.compilerOptions.checkJs=!0,t.compilerOptions.allowJs=!0,t.compilerOptions.target=t.compilerOptions.target||"ES2020",t.compilerOptions.module=t.compilerOptions.module||"ESNext",t.compilerOptions.moduleResolution=t.compilerOptions.moduleResolution||"bundler",t.include=["src/**/*"],i=!0):(t.compilerOptions.checkJs===void 0&&(t.compilerOptions.checkJs=!0,i=!0),t.compilerOptions.allowJs===void 0&&(t.compilerOptions.allowJs=!0,i=!0)),l&&t.compilerOptions.jsx===void 0&&(t.compilerOptions.jsx="react-jsx",i=!0),Array.isArray(t.compilerOptions.types)&&t.compilerOptions.types.includes("vite/client")&&(t.compilerOptions.types=t.compilerOptions.types.filter(c=>c!=="vite/client"),t.compilerOptions.types.length===0&&delete t.compilerOptions.types,i=!0,g(`\u2192 Removed legacy "vite/client" entry from ${b.basename(r)}.`)),i&&(a.writeFileSync(r,JSON.stringify(t,null,2)+`
80
- `),g(`\u2192 Updated ${b.basename(r)}.`))}function U(e){let o=["src/app/layout.tsx","src/app/layout.jsx","app/layout.tsx","app/layout.jsx","src/pages/_app.tsx","src/pages/_app.jsx","pages/_app.tsx","pages/_app.jsx","src/main.tsx","src/main.jsx","src/main.ts","src/main.js","src/index.tsx","src/index.jsx","src/index.ts","src/index.js","src/App.tsx","src/App.jsx","src/App.vue","app.vue","src/routes/+layout.svelte","src/routes/+layout.ts","src/main.singletons.ts"];for(let s of o){let n=b.join(e,s);if(a.existsSync(n)){let r=a.readFileSync(n,"utf8");r.includes("fleetbo-svro")||(r.startsWith('"use client"')||r.startsWith("'use client'")?r=r.replace(/(['"]use client['"];?\r?\n)/,`$1import 'fleetbo-svro';
81
- `):r=`import 'fleetbo-svro';
82
- `+r,a.writeFileSync(n,r));return}}}function B(e,o){if(process.env.FLEETBO_SKIP_AUTOIMPORT_SETUP)return;let n=["vite.config.ts","vite.config.js","vite.config.mjs"].map(l=>b.join(e,l)).find(l=>a.existsSync(l));if(!n)return;let r;try{r=a.readFileSync(n,"utf8")}catch{return}let p="fleetbo-svro",t=r,i=`{
79
+ `;a.appendFileSync(r,d),g(".env file updated successfully with Fleetbo keys!")}function L(e){let o=f.join(e,"svro.d.ts");if(a.existsSync(o))try{a.unlinkSync(o),g("\u2192 Removed legacy svro.d.ts from project root.")}catch{}}function _(e,o){if(process.env.FLEETBO_SKIP_TYPECHECK_SETUP)return;let r=f.join(e,"tsconfig.json"),n=f.join(e,"jsconfig.json"),s=a.existsSync(r)?r:n,c=!a.existsSync(s),t={};if(!c)try{t=JSON.parse(a.readFileSync(s,"utf8"))}catch{E(`\u26A0\uFE0F Unable to read ${f.basename(s)} (Invalid JSON).`);return}t.compilerOptions=t.compilerOptions||{};let i=!1,l=w(o,"react");c?(t.compilerOptions.checkJs=!0,t.compilerOptions.allowJs=!0,t.compilerOptions.target=t.compilerOptions.target||"ES2020",t.compilerOptions.module=t.compilerOptions.module||"ESNext",t.compilerOptions.moduleResolution=t.compilerOptions.moduleResolution||"bundler",t.include=["src/**/*"],i=!0):(t.compilerOptions.checkJs===void 0&&(t.compilerOptions.checkJs=!0,i=!0),t.compilerOptions.allowJs===void 0&&(t.compilerOptions.allowJs=!0,i=!0)),l&&t.compilerOptions.jsx===void 0&&(t.compilerOptions.jsx="react-jsx",i=!0),Array.isArray(t.compilerOptions.types)&&t.compilerOptions.types.includes("vite/client")&&(t.compilerOptions.types=t.compilerOptions.types.filter(d=>d!=="vite/client"),t.compilerOptions.types.length===0&&delete t.compilerOptions.types,i=!0,g(`\u2192 Removed legacy "vite/client" entry from ${f.basename(s)}.`)),i&&(a.writeFileSync(s,JSON.stringify(t,null,2)+`
80
+ `),g(`\u2192 Updated ${f.basename(s)}.`))}function U(e){let o=["src/app/layout.tsx","src/app/layout.jsx","app/layout.tsx","app/layout.jsx","src/pages/_app.tsx","src/pages/_app.jsx","pages/_app.tsx","pages/_app.jsx","src/main.tsx","src/main.jsx","src/main.ts","src/main.js","src/index.tsx","src/index.jsx","src/index.ts","src/index.js","src/App.tsx","src/App.jsx","src/App.vue","app.vue","src/routes/+layout.svelte","src/routes/+layout.ts","src/main.singletons.ts"];for(let r of o){let n=f.join(e,r);if(a.existsSync(n)){let s=a.readFileSync(n,"utf8");s.includes("fleetbo-svro")||(s.startsWith('"use client"')||s.startsWith("'use client'")?s=s.replace(/(['"]use client['"];?\r?\n)/,`$1import 'fleetbo-svro';
81
+ `):s=`import 'fleetbo-svro';
82
+ `+s,a.writeFileSync(n,s));return}}}function B(e,o){if(process.env.FLEETBO_SKIP_AUTOIMPORT_SETUP)return;let n=["vite.config.ts","vite.config.js","vite.config.mjs"].map(l=>f.join(e,l)).find(l=>a.existsSync(l));if(!n)return;let s;try{s=a.readFileSync(n,"utf8")}catch{return}let c="fleetbo-svro",t=s,i=`{
83
83
  name: 'fleetbo-auto-runtime',
84
84
  transform(code, id) {
85
85
  if (!id.includes('node_modules') && !code.includes('fleetbo-svro') && /(src[\\\\/](main|index|App|root))\\.(jsx?|tsx?|vue|svelte)/i.test(id)) {
@@ -131,25 +131,33 @@ ${t?`VITE_FLEETBO_TESTER_EMAIL=${t}
131
131
  watch: {
132
132
  ignored: ['**/svro.schema.json', '**/src/auto-imports.d.ts']
133
133
  }
134
- },`))),!t.includes("unplugin-auto-import")){let l=t.match(/plugins\s*:\s*\[/);if(l){let c=l.index+l[0].length,u=`
134
+ },`))),!t.includes("unplugin-auto-import")){let l=t.match(/plugins\s*:\s*\[/);if(l){let d=l.index+l[0].length,b=`
135
135
  AutoImport({
136
- imports: [{ '${p}': ['Fleetbo', 'FleetboUI'] }],
136
+ imports: [{ '${c}': ['Fleetbo', 'FleetboUI'] }],
137
137
  dts: 'src/auto-imports.d.ts'
138
- }),`;if(t=t.slice(0,c)+u+t.slice(c),!t.includes("import AutoImport")){let y=[...t.matchAll(/^import .+;?$/gm)].pop(),T=`import AutoImport from 'unplugin-auto-import/vite';
138
+ }),`;if(t=t.slice(0,d)+b+t.slice(d),!t.includes("import AutoImport")){let y=[...t.matchAll(/^import .+;?$/gm)].pop(),h=`import AutoImport from 'unplugin-auto-import/vite';
139
139
  `;if(y){let F=y.index+y[0].length;t=t.slice(0,F)+`
140
- `+T+t.slice(F)}else t=T+t}}}if(!t.includes("fleetbo-auto-runtime")){let l=t.match(/plugins\s*:\s*\[/);if(l){let c=l.index+l[0].length;t=t.slice(0,c)+`
141
- `+i+t.slice(c)}}t!==r&&a.writeFileSync(n,t)}function fe(e){let o=b.join(e,".vscode"),s=b.join(o,"settings.json");try{a.existsSync(o)||a.mkdirSync(o,{recursive:!0});let n={};if(a.existsSync(s))try{n=JSON.parse(a.readFileSync(s,"utf8"))}catch{n={}}n["workbench.colorCustomizations"]=n["workbench.colorCustomizations"]||{},n["workbench.colorCustomizations"]["editorInfo.foreground"]="#00feae",n["workbench.colorCustomizations"]["editorHint.foreground"]="#00feae",a.writeFileSync(s,JSON.stringify(n,null,2)+`
142
- `),g("\u2192 Configured Fleetbo Cyan visual hints in .vscode/settings.json.")}catch{}}function me(e,o,s={}){let{skipSelfInstall:n=!1}=s,r=b.join(__dirname,"..");n||ie(e,o),le(e),ae(e),pe(r),ce(e),fe(e),L(e),_(e,o),B(e,o),U(e)}$.exports={touchTsConfig:de,log:g,logError:h,handleAuthAndEnv:be,detectDependency:A,cleanupLegacyRootDts:L,patchJsOrTsConfig:_,attemptViteAutoImportPatch:B,injectUniversalRuntime:U,runFullSetup:me}});var d=require("fs"),m=require("path"),H=require("https"),ge=require("http"),N=require("os"),{exec:Fe}=require("child_process"),{runFullSetup:ye,handleAuthAndEnv:Te,touchTsConfig:he,attemptViteAutoImportPatch:Ee,injectUniversalRuntime:Se}=J(),Pe="\x1B[34m",Oe="\x1B[31m",q="\x1B[0m";function f(e){console.log(`${Pe}${e}${q}`)}function S(e){console.error(`${Oe}${e}${q}`)}function ve(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Fe(`${o} "${e}"`)}function xe(e){return new Promise((o,s)=>{let n=ge.createServer((r,p)=>{if(p.setHeader("Access-Control-Allow-Origin","*"),p.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),p.setHeader("Access-Control-Allow-Headers","Content-Type"),r.method==="OPTIONS"){p.writeHead(204),p.end();return}let t=new URL(r.url,"http://localhost");if(t.pathname==="/callback"){let i=t.searchParams.get("token");if(!i){p.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),p.end("<h3>Error: Missing token.</h3>");return}let l=m.join(N.homedir(),".fleetbo");d.existsSync(l)||d.mkdirSync(l,{recursive:!0}),d.writeFileSync(m.join(l,"credentials.json"),JSON.stringify({devToken:i,updatedAt:new Date().toISOString()},null,2));let c=m.join(e,".env");if(d.existsSync(c)){let u=d.readFileSync(c,"utf8");u.includes("FLEETBO_DEV_TOKEN=")?u=u.replace(/FLEETBO_DEV_TOKEN=.*/g,`FLEETBO_DEV_TOKEN=${i}`):u+=`
140
+ `+h+t.slice(F)}else t=h+t}}}if(!t.includes("fleetbo-auto-runtime")){let l=t.match(/plugins\s*:\s*\[/);if(l){let d=l.index+l[0].length;t=t.slice(0,d)+`
141
+ `+i+t.slice(d)}}t!==s&&a.writeFileSync(n,t)}function fe(e){let o=f.join(e,".vscode"),r=f.join(o,"settings.json");try{a.existsSync(o)||a.mkdirSync(o,{recursive:!0});let n={};if(a.existsSync(r))try{n=JSON.parse(a.readFileSync(r,"utf8"))}catch{n={}}n["workbench.colorCustomizations"]=n["workbench.colorCustomizations"]||{},n["workbench.colorCustomizations"]["editorInfo.foreground"]="#00feae",n["workbench.colorCustomizations"]["editorHint.foreground"]="#00feae",a.writeFileSync(r,JSON.stringify(n,null,2)+`
142
+ `),g("\u2192 Configured Fleetbo Cyan visual hints in .vscode/settings.json.")}catch{}}function me(e,o,r={}){let{skipSelfInstall:n=!1}=r,s=f.join(__dirname,"..");n||ie(e,o),le(e),ae(e),de(s),ce(e),fe(e),L(e),_(e,o),B(e,o),U(e)}$.exports={touchTsConfig:pe,log:g,logError:E,handleAuthAndEnv:be,detectDependency:w,cleanupLegacyRootDts:L,patchJsOrTsConfig:_,attemptViteAutoImportPatch:B,injectUniversalRuntime:U,runFullSetup:me}});var p=require("fs"),m=require("path"),H=require("https"),ge=require("http"),k=require("os"),{exec:Fe}=require("child_process"),{runFullSetup:ye,handleAuthAndEnv:he,touchTsConfig:Ee,attemptViteAutoImportPatch:Te,injectUniversalRuntime:Se}=J(),Pe="\x1B[34m",Oe="\x1B[31m",q="\x1B[0m";function u(e){console.log(`${Pe}${e}${q}`)}function S(e){console.error(`${Oe}${e}${q}`)}function ve(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Fe(`${o} "${e}"`)}function xe(e){return new Promise((o,r)=>{let n=ge.createServer((s,c)=>{if(c.setHeader("Access-Control-Allow-Origin","*"),c.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),c.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),c.setHeader("Access-Control-Allow-Private-Network","true"),s.method==="OPTIONS"){c.writeHead(204),c.end();return}let t=new URL(s.url,"http://127.0.0.1");if(t.pathname==="/callback"){let i=t.searchParams.get("token");if(!i){c.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),c.end("<h3>Error: Missing token.</h3>");return}let l=m.join(k.homedir(),".fleetbo");p.existsSync(l)||p.mkdirSync(l,{recursive:!0}),p.writeFileSync(m.join(l,"credentials.json"),JSON.stringify({devToken:i,updatedAt:new Date().toISOString()},null,2));let d=m.join(e,".env");if(p.existsSync(d)){let b=p.readFileSync(d,"utf8");b.includes("FLEETBO_DEV_TOKEN=")?b=b.replace(/FLEETBO_DEV_TOKEN=.*/g,`FLEETBO_DEV_TOKEN=${i}`):b+=`
143
143
  FLEETBO_DEV_TOKEN=${i}
144
- `,d.writeFileSync(c,u,"utf8")}p.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),p.end(`
145
- <div style="font-family: sans-serif; text-align: center; margin-top: 50px;">
146
- <h2 style="color: #0F9C8C;">Authentication Successful!</h2>
147
- <p>Your terminal is now connected to Fleetbo. You can close this window.</p>
148
- </div>
149
- `),f(`
150
- [Fleetbo] Developer token received and stored successfully!`),n.close(()=>o())}});n.listen(0,()=>{let p=`https://fleetbo.io/cli-auth?port=${n.address().port}`;f(`
151
- [Fleetbo] Waiting for authentication...`),f(`If your browser does not open automatically, visit: ${p}`),ve(p)}),n.on("error",r=>s(r))})}function Ie(e,o){return new Promise((s,n)=>{let r=JSON.stringify({enterpriseID:e,schema:o}),p={hostname:"fleetbo-gatekeeper.fleetbo.workers.dev",path:"/sync-schema",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}},t=H.request(p,i=>{let l="";i.on("data",c=>{l+=c}),i.on("end",()=>{i.statusCode>=200&&i.statusCode<300?s(JSON.parse(l)):n(new Error(`Edge sync failed with HTTP ${i.statusCode}`))})});t.on("error",i=>n(i)),t.write(r),t.end()})}function M(e){let o=m.join(e,".env");if(!d.existsSync(o))return{};let s=d.readFileSync(o,"utf8"),n={};return s.split(`
152
- `).forEach(r=>{let[p,...t]=r.split("=");p&&t.length>0&&(n[p.trim()]=t.join("=").trim())}),n}function V(e,o){return new Promise((s,n)=>{let r=JSON.stringify({projectId:e,moduleName:o}),p={hostname:"getmodulecache-jqycakhlxa-uc.a.run.app",path:"/",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}},t=H.request(p,i=>{let l="";i.on("data",c=>{l+=c}),i.on("end",()=>{if(i.statusCode>=200&&i.statusCode<300)try{let c=JSON.parse(l);if(c.success&&c.found&&c.module){let u=c.module.code||c.module.mockCode;s(typeof u=="string"?JSON.parse(u):u)}else s(null)}catch{n(new Error(`Invalid JSON response for ${o}.`))}else n(new Error(`Server error ${i.statusCode} while fetching ${o}`))})});t.on("error",i=>n(i)),t.write(r),t.end()})}var C=process.argv.slice(2),I=C[0];function Ce(e,o){return`# LE CONTRAT DE DONN\xC9ES FLEETBO (FLEETBO DATA CONTRACT)
144
+ `,p.writeFileSync(d,b,"utf8")}c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(`
145
+ <!DOCTYPE html>
146
+ <html>
147
+ <head><meta charset="utf-8"><title>Fleetbo CLI</title></head>
148
+ <body style="font-family: sans-serif; background: #0A0C10; color: #E7E9ED; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0;">
149
+ <div style="text-align: center; padding: 40px; border: 1px solid #232830; border-radius: 16px; background: #12151B;">
150
+ <h2 style="color: #45D4C4; margin-bottom: 12px;">Authentication Successful!</h2>
151
+ <p style="color: #8A93A3; font-size: 14px;">You can now close this tab and return to your terminal.</p>
152
+ </div>
153
+ </body>
154
+ </html>
155
+ `),u(`
156
+ [Fleetbo] Developer token received and stored successfully!`),u(`
157
+ Next step to connect your AI agents:`),u(` npx fleetbo-svro mcp (Configure Cursor, Windsurf, Claude Code, etc.)
158
+ `),n.close(()=>o())}});n.listen(0,"127.0.0.1",()=>{let c=`https://fleetbo.io/cli-auth?port=${n.address().port}`;u(`
159
+ [Fleetbo] Waiting for authentication...`),u(`If your browser does not open automatically, visit: ${c}`),ve(c)}),n.on("error",s=>r(s))})}function Ie(e,o){return new Promise((r,n)=>{let s=JSON.stringify({enterpriseID:e,schema:o}),c={hostname:"fleetbo-gatekeeper.fleetbo.workers.dev",path:"/sync-schema",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(s)}},t=H.request(c,i=>{let l="";i.on("data",d=>{l+=d}),i.on("end",()=>{i.statusCode>=200&&i.statusCode<300?r(JSON.parse(l)):n(new Error(`Edge sync failed with HTTP ${i.statusCode}`))})});t.on("error",i=>n(i)),t.write(s),t.end()})}function M(e){let o=m.join(e,".env");if(!p.existsSync(o))return{};let r=p.readFileSync(o,"utf8"),n={};return r.split(`
160
+ `).forEach(s=>{let[c,...t]=s.split("=");c&&t.length>0&&(n[c.trim()]=t.join("=").trim())}),n}function V(e,o){return new Promise((r,n)=>{let s=JSON.stringify({projectId:e,moduleName:o}),c={hostname:"getmodulecache-jqycakhlxa-uc.a.run.app",path:"/",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(s)}},t=H.request(c,i=>{let l="";i.on("data",d=>{l+=d}),i.on("end",()=>{if(i.statusCode>=200&&i.statusCode<300)try{let d=JSON.parse(l);if(d.success&&d.found&&d.module){let b=d.module.code||d.module.mockCode;r(typeof b=="string"?JSON.parse(b):b)}else r(null)}catch{n(new Error(`Invalid JSON response for ${o}.`))}else n(new Error(`Server error ${i.statusCode} while fetching ${o}`))})});t.on("error",i=>n(i)),t.write(s),t.end()})}var C=process.argv.slice(2),I=C[0];function Ce(e,o){return`# LE CONTRAT DE DONN\xC9ES FLEETBO (FLEETBO DATA CONTRACT)
153
161
 
154
162
  Ce document constitue le **Cahier des charges officiel et le Contrat bilat\xE9ral d'int\xE9grit\xE9** liant le code client (d\xE9veloppeur ou agent IA) et le moteur Data OS Fleetbo SVRO.
155
163
 
@@ -230,21 +238,21 @@ ${JSON.stringify(e||{},null,2)}
230
238
  \`\`\`json
231
239
  ${JSON.stringify(o||{},null,2)}
232
240
  \`\`\`
233
- `}async function we(){let e=process.cwd(),o=m.join(e,"package.json");if(I==="init"||I==="doctor")f(`
234
- [Fleetbo] Initializing and configuring Fleetbo...`),await Te(e,C),ye(e,o),f(`
241
+ `}async function Ae(){let e=process.cwd(),o=m.join(e,"package.json");if(I==="init"||I==="doctor")u(`
242
+ [Fleetbo] Initializing and configuring Fleetbo...`),await he(e,C),ye(e,o),u(`
235
243
  [Fleetbo] Configuration completed successfully!
236
- `),f(`
237
- Next step:`),f(` npx fleetbo-svro sync (Sync cloud schema & generate IDE types)
238
- `);else if(I==="sync"){let s=C.includes("--dry-run");f(`[Fleetbo] Syncing schema...${s?" (dry-run)":""}`);let n=m.join(e,"svro.schema.json"),r=m.join(e,"svro.workflow.json"),p=m.join(e,"Fleetbo_contract.md"),t=m.join(__dirname,".."),i=m.join(t,"index.d.ts"),l=m.join(e,"src","fleetbo.d.ts"),u=M(e).VITE_FLEETBO_ENTERPRISE_ID,y=null,T=null;if(u)try{f("\u2192 Fetching latest contracts from Fleetbo Cloud..."),y=await V(u,"svro.schema.json"),y&&(d.writeFileSync(n,JSON.stringify(y,null,2)+`
239
- `),f("\u2192 Local svro.schema.json updated.")),T=await V(u,"svro.workflow.json"),T&&(d.writeFileSync(r,JSON.stringify(T,null,2)+`
240
- `),f("\u2192 Local svro.workflow.json updated."))}catch(P){S(`\u26A0\uFE0F Cloud fetch bypassed: ${P.message}. Using local file fallback.`)}else S("\u26A0\uFE0F VITE_FLEETBO_ENTERPRISE_ID missing in .env. Skipping cloud fetch.");d.existsSync(n)||(S("Error: svro.schema.json not found."),process.exit(1));let F=y||JSON.parse(d.readFileSync(n,"utf8")),E=T;if(!E&&d.existsSync(r))try{E=JSON.parse(d.readFileSync(r,"utf8"))}catch{}let K=Ce(F,E);d.writeFileSync(p,K,"utf8"),f("\u2192 Fleetbo_contract.md successfully generated at project root.");try{let P=Object.keys(F.collections||{});if(u)try{await Ie(u,F),f("\u2192 Schema successfully sealed at Fleetbo Global Edge (O(1)).")}catch(O){S(`\u26A0\uFE0F Fleetbo Edge Shield sync warning: ${O.message}`)}let W=F.collections||{},k=Object.entries(W).map(([O,R])=>{let G=R.fields||R.schema||{},X=Object.entries(G).map(([z,w])=>{let x="any",v=String(typeof w=="string"?w:w.type||"").toLowerCase();return v==="string"||v==="text"||v==="media"?x="string":v==="number"?x="number":v==="boolean"||v==="toggle"?x="boolean":v==="array"&&(x="any[]"),` ${z}?:${x};`}).join(`
244
+ `),u(`
245
+ Next step:`),u(` npx fleetbo-svro sync (Sync cloud schema & generate IDE types)
246
+ `);else if(I==="sync"){let r=C.includes("--dry-run");u(`[Fleetbo] Syncing schema...${r?" (dry-run)":""}`);let n=m.join(e,"svro.schema.json"),s=m.join(e,"svro.workflow.json"),c=m.join(e,"Fleetbo_contract.md"),t=m.join(__dirname,".."),i=m.join(t,"index.d.ts"),l=m.join(e,"src","fleetbo.d.ts"),b=M(e).VITE_FLEETBO_ENTERPRISE_ID,y=null,h=null;if(b)try{u("\u2192 Fetching latest contracts from Fleetbo Cloud..."),y=await V(b,"svro.schema.json"),y&&(p.writeFileSync(n,JSON.stringify(y,null,2)+`
247
+ `),u("\u2192 Local svro.schema.json updated.")),h=await V(b,"svro.workflow.json"),h&&(p.writeFileSync(s,JSON.stringify(h,null,2)+`
248
+ `),u("\u2192 Local svro.workflow.json updated."))}catch(P){S(`\u26A0\uFE0F Cloud fetch bypassed: ${P.message}. Using local file fallback.`)}else S("\u26A0\uFE0F VITE_FLEETBO_ENTERPRISE_ID missing in .env. Skipping cloud fetch.");p.existsSync(n)||(S("Error: svro.schema.json not found."),process.exit(1));let F=y||JSON.parse(p.readFileSync(n,"utf8")),T=h;if(!T&&p.existsSync(s))try{T=JSON.parse(p.readFileSync(s,"utf8"))}catch{}let K=Ce(F,T);p.writeFileSync(c,K,"utf8"),u("\u2192 Fleetbo_contract.md successfully generated at project root.");try{let P=Object.keys(F.collections||{});if(b)try{await Ie(b,F),u("\u2192 Schema successfully sealed at Fleetbo Global Edge (O(1)).")}catch(O){S(`\u26A0\uFE0F Fleetbo Edge Shield sync warning: ${O.message}`)}let W=F.collections||{},N=Object.entries(W).map(([O,R])=>{let G=R.fields||R.schema||{},X=Object.entries(G).map(([z,A])=>{let x="any",v=String(typeof A=="string"?A:A.type||"").toLowerCase();return v==="string"||v==="text"||v==="media"?x="string":v==="number"?x="number":v==="boolean"||v==="toggle"?x="boolean":v==="array"&&(x="any[]"),` ${z}?:${x};`}).join(`
241
249
  `);return` ${O}: {
242
250
  ${X}
243
251
  };`}).join(`
244
252
  `),D=P.length>0?P.map(O=>`'${O}'`).join(" | "):"string",Y=`// Generated by fleetbo-svro \u2014 Updated via fleetbo sync
245
253
 
246
254
  export interface FleetboSchemaMap {
247
- ${k}
255
+ ${N}
248
256
  }
249
257
 
250
258
  export type KnownFleetboTables = ${D};
@@ -504,7 +512,7 @@ declare module 'svelte/elements' {
504
512
  'fleetbo-reference': FleetboProp;
505
513
  }
506
514
  }
507
- `;if(d.writeFileSync(i,Y),d.existsSync(m.dirname(l))){let O=`/* eslint-disable */
515
+ `;if(p.writeFileSync(i,Y),p.existsSync(m.dirname(l))){let O=`/* eslint-disable */
508
516
  /* prettier-ignore */
509
517
  // @ts-nocheck
510
518
  // Generated by fleetbo-svro \u2014 Updated via fleetbo sync
@@ -533,7 +541,7 @@ type FleetboProp = {
533
541
  };
534
542
 
535
543
  interface FleetboSchemaMap {
536
- ${k}
544
+ ${N}
537
545
  }
538
546
 
539
547
  declare global {
@@ -638,9 +646,9 @@ declare module 'svelte/elements' {
638
646
  'fleetbo-reference': FleetboProp;
639
647
  }
640
648
  }
641
- `;d.writeFileSync(l,O)}he(e),Ee(e,o),Se(e),f(`[Fleetbo] Schema synced successfully (${P.length} collection(s)).`),s&&f("\u2192 [Dry-run] Schema is valid.")}catch(P){S(`Error during synchronization: ${P.message}`),process.exit(1)}}else if(I==="mcp"){if(!process.stdin.isTTY||C.includes("--run")){try{await import(`file://${m.join(__dirname,"fleetbo-mcp.js")}`)}catch(c){S(`Failed to start MCP server: ${c.message}`),process.exit(1)}return}f(`
642
- [Fleetbo] Configuring MCP server for your environment...`);let n=M(e).FLEETBO_DEV_TOKEN||process.env.FLEETBO_DEV_TOKEN||"";if(!n){let c=m.join(N.homedir(),".fleetbo","credentials.json");if(d.existsSync(c))try{n=JSON.parse(d.readFileSync(c,"utf8")).devToken||""}catch{}}let r={command:"npx",args:["-y","fleetbo-svro","mcp","--run"],env:{FLEETBO_DEV_TOKEN:n}},p=(c,u,y)=>{let T=m.dirname(c);d.existsSync(T)||d.mkdirSync(T,{recursive:!0});let F={mcpServers:{}};if(d.existsSync(c))try{let E=JSON.parse(d.readFileSync(c,"utf8"));E&&typeof E=="object"&&!Array.isArray(E)&&(F=E)}catch{}F.mcpServers=F.mcpServers||{},F.mcpServers[u]=y,d.writeFileSync(c,JSON.stringify(F,null,2)+`
643
- `)},t=m.join(e,".cursor"),i=m.join(t,"mcp.json");p(i,"fleetbo-svro",r),f("\u2192 Configured for Cursor (.cursor/mcp.json)");let l=m.join(N.homedir(),".codeium","windsurf","mcp_config.json");d.existsSync(m.dirname(l))&&(p(l,"fleetbo-svro",r),f("\u2192 Configured for Windsurf (~/.codeium/windsurf/mcp_config.json)")),f(`
644
- Universal connection command for Claude Code and standalone agents:`),f(` claude mcp add fleetbo-svro -- npx -y fleetbo-svro mcp --run
645
- `),n?f(`[Fleetbo] Agent ready! Your development environment now has access to Fleetbo MCP tools.
646
- `):S('\u26A0\uFE0F No developer token found. Run "npx fleetbo-svro login" or set FLEETBO_DEV_TOKEN in your .env file.'),process.exit(0)}else I==="login"?(await xe(e),process.exit(0)):(S('Unknown command. Usage: "npx fleetbo-svro init", "npx fleetbo-svro sync", "npx fleetbo-svro mcp" or "npx fleetbo-svro login"'),process.exit(1))}we().catch(e=>{S(`Fleetbo CLI Error: ${e.message}`),process.exit(1)});
649
+ `;p.writeFileSync(l,O)}Ee(e),Te(e,o),Se(e),u(`[Fleetbo] Schema synced successfully (${P.length} collection(s)).`),r&&u("\u2192 [Dry-run] Schema is valid.")}catch(P){S(`Error during synchronization: ${P.message}`),process.exit(1)}}else if(I==="mcp"){if(!process.stdin.isTTY||C.includes("--run")){try{await import(`file://${m.join(__dirname,"fleetbo-mcp.js")}`)}catch(d){S(`Failed to start MCP server: ${d.message}`),process.exit(1)}return}u(`
650
+ [Fleetbo] Configuring MCP server for your environment...`);let n=M(e).FLEETBO_DEV_TOKEN||process.env.FLEETBO_DEV_TOKEN||"";if(!n){let d=m.join(k.homedir(),".fleetbo","credentials.json");if(p.existsSync(d))try{n=JSON.parse(p.readFileSync(d,"utf8")).devToken||""}catch{}}let s={command:"npx",args:["-y","fleetbo-svro","mcp","--run"],env:{FLEETBO_DEV_TOKEN:n}},c=(d,b,y)=>{let h=m.dirname(d);p.existsSync(h)||p.mkdirSync(h,{recursive:!0});let F={mcpServers:{}};if(p.existsSync(d))try{let T=JSON.parse(p.readFileSync(d,"utf8"));T&&typeof T=="object"&&!Array.isArray(T)&&(F=T)}catch{}F.mcpServers=F.mcpServers||{},F.mcpServers[b]=y,p.writeFileSync(d,JSON.stringify(F,null,2)+`
651
+ `)},t=m.join(e,".cursor"),i=m.join(t,"mcp.json");c(i,"fleetbo-svro",s),u("\u2192 Configured for Cursor (.cursor/mcp.json)");let l=m.join(k.homedir(),".codeium","windsurf","mcp_config.json");p.existsSync(m.dirname(l))&&(c(l,"fleetbo-svro",s),u("\u2192 Configured for Windsurf (~/.codeium/windsurf/mcp_config.json)")),u(`
652
+ Universal connection command for Claude Code and standalone agents:`),u(` claude mcp add fleetbo-svro -- npx -y fleetbo-svro mcp --run
653
+ `),n?u(`[Fleetbo] Agent ready! Your development environment now has access to Fleetbo MCP tools.
654
+ `):S('\u26A0\uFE0F No developer token found. Run "npx fleetbo-svro login" or set FLEETBO_DEV_TOKEN in your .env file.'),process.exit(0)}else I==="login"?(await xe(e),process.exit(0)):(S('Unknown command. Usage: "npx fleetbo-svro init", "npx fleetbo-svro sync", "npx fleetbo-svro mcp" or "npx fleetbo-svro login"'),process.exit(1))}Ae().catch(e=>{S(`Fleetbo CLI Error: ${e.message}`),process.exit(1)});
@@ -0,0 +1,489 @@
1
+ #!/usr/bin/env node
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import {
5
+ CallToolRequestSchema,
6
+ ListToolsRequestSchema,
7
+ ListPromptsRequestSchema,
8
+ GetPromptRequestSchema,
9
+ } from "@modelcontextprotocol/sdk/types.js";
10
+ import { z } from "zod";
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import os from "node:os";
14
+
15
+ function getDevToken() {
16
+ if (process.env.FLEETBO_DEV_TOKEN) return process.env.FLEETBO_DEV_TOKEN;
17
+ try {
18
+ const credPath = path.join(os.homedir(), ".fleetbo", "credentials.json");
19
+ if (fs.existsSync(credPath)) {
20
+ return JSON.parse(fs.readFileSync(credPath, "utf8")).devToken || null;
21
+ }
22
+ } catch (_) {}
23
+ return null;
24
+ }
25
+
26
+ const DEV_AUTH_TOKEN = getDevToken();
27
+ const CLOUD_RUN_REGION = "jqycakhlxa-uc.a.run.app";
28
+
29
+ // ============================================================================
30
+ // CONTRAT DE DONNÉES & DIRECTIVES STRICTES D'ARCHITECTURE FLEETBO SVRO
31
+ // ============================================================================
32
+ const FLEETBO_SYSTEM_GUIDELINES = `
33
+ # LE CONTRAT DE DONNÉES FLEETBO (FLEETBO DATA CONTRACT)
34
+ Ce document constitue le Cahier des charges officiel et le Contrat bilatéral d'intégrité liant le code client et le moteur Data OS Fleetbo SVRO.
35
+
36
+ 🚨 DIRECTIVE D'EXÉCUTION OBLIGATOIRE POUR L'AGENT IA :
37
+ 1. Interdiction d'extrapolation : Ne crée aucun champ, type ou endpoint non déclaré explicitement dans svro.schema.json.
38
+ 2. Zéro backend intermédiaire : N'écris AUCUN serveur Express, NestJS ou route d'API REST fictive.
39
+ 3. Objet global unique : Utilise exclusivement l'objet global Fleetbo.* (add, getDocsG, getDoc, update, delete, call, join).
40
+ 4. Zero Import : L'objet Fleetbo et les balises <fleetbo-*> sont des composants globaux au runtime. Ne fais aucun import manuel de SDK.
41
+ 5. Typage strict avant écriture : Caste systématiquement les types reçus des formulaires (Number, String, Boolean).
42
+
43
+ CYCLE DE MODÉLISATION DU DATA OS :
44
+ - Étape 1 (Création) : Alloue le projet via 'fleetbo_create_project'.
45
+ - Étape 2 (Amorçage) : Lance 'npx fleetbo-svro init ...' puis 'npx fleetbo-svro sync'.
46
+ - Étape 3 (Modélisation Jour 1) : Écris tes premières vues UI (JSX, TSX, Vue) et modélise la base via 'fleetbo_update_project'.
47
+ - Étape 4 (Scellage) : Exécute 'npx fleetbo-svro sync' pour générer svro.schema.json, svro.workflow.json, Fleetbo_contract.md et le typage TypeScript.
48
+ - Étape 5 (Évolutions Jour 2) : Chaque nouvelle vue ou règle passe par 'fleetbo_update_project' suivi d'un 'npx fleetbo-svro sync'.
49
+
50
+ SYNTAXE CRUD CANONIQUE DU SDK FLEETBO :
51
+ - CREATE : await Fleetbo.add('collection', { name: String(n).trim(), price: Number(p) });
52
+ - READ ALL : const docs = await Fleetbo.getDocsG('collection');
53
+ - READ ONE : const doc = await Fleetbo.getDoc('collection', docId);
54
+ - READ USER : const docs = await Fleetbo.getDocsU('collection');
55
+ - UPDATE : await Fleetbo.update('collection', docId, { status: 'PAID' });
56
+ - DELETE : await Fleetbo.delete('collection', docId);
57
+ - JOIN : await Fleetbo.join('orders', { innerJoin: { collection: 'users', on: ['userId', '==', 'id'], as: 'user' } });
58
+ - CLOUD FUNCTION : const res = await Fleetbo.call('$functionName', payload);
59
+
60
+ GESTION DE L'ENVIRONNEMENT (.env) :
61
+ - VITE_FLEETBO_PROTOTYPE=true : Mode bac à sable UI. L'Edge acquitte immédiatement sans toucher à la base physique.
62
+ - VITE_FLEETBO_PROTOTYPE=false : Mode strict live. L'Edge valide le contrat DDL et persiste sur MongoDB Atlas.
63
+ `;
64
+
65
+ const server = new Server(
66
+ {
67
+ name: "fleetbo-svro-mcp",
68
+ version: "1.0.0",
69
+ },
70
+ {
71
+ capabilities: {
72
+ tools: {},
73
+ prompts: {},
74
+ },
75
+ }
76
+ );
77
+
78
+ // ============================================================================
79
+ // 1. PROMPTS MCP
80
+ // ============================================================================
81
+ server.setRequestHandler(ListPromptsRequestSchema, async () => {
82
+ return {
83
+ prompts: [
84
+ {
85
+ name: "fleetbo_contract_rules",
86
+ description:
87
+ "Loads strict architectural rules, invariants, and integrity directives for Fleetbo SVRO.",
88
+ },
89
+ ],
90
+ };
91
+ });
92
+
93
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
94
+ if (request.params.name === "fleetbo_contract_rules") {
95
+ return {
96
+ description: "Official Fleetbo SVRO architecture directives",
97
+ messages: [
98
+ {
99
+ role: "user",
100
+ content: {
101
+ type: "text",
102
+ text: FLEETBO_SYSTEM_GUIDELINES,
103
+ },
104
+ },
105
+ ],
106
+ };
107
+ }
108
+ throw new Error(`Unknown prompt: ${request.params.name}`);
109
+ });
110
+
111
+ // ============================================================================
112
+ // 2. OUTILS MCP (Tools)
113
+ // ============================================================================
114
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
115
+ return {
116
+ tools: [
117
+ {
118
+ name: "fleetbo_create_project",
119
+ description:
120
+ "Étape 1 : Crée une nouvelle application Fleetbo Data OS dans le Cloud avec son nom et sa clé unique (contrats initiaux vierges prêts pour la modélisation).",
121
+ inputSchema: {
122
+ type: "object",
123
+ properties: {
124
+ name: {
125
+ type: "string",
126
+ description: "Nom d'affichage de l'application (ex: CoWorking Manager)",
127
+ },
128
+ keyApp: {
129
+ type: "string",
130
+ description: "Clé unique d'application sans espace ni caractères spéciaux (ex: coworking_prod)",
131
+ },
132
+ },
133
+ required: ["name", "keyApp"],
134
+ },
135
+ },
136
+ {
137
+ name: "fleetbo_update_project",
138
+ description:
139
+ "Step 3 & 5: Analyzes UI component files (JSX, TSX, Vue) and business rules to forge or enrich DDL schema and workflow additively.",
140
+ inputSchema: {
141
+ type: "object",
142
+ properties: {
143
+ keyApp: {
144
+ type: "string",
145
+ description: "Unique application key (e.g. coworking_prod)",
146
+ },
147
+ name: {
148
+ type: "string",
149
+ description: "Application name",
150
+ },
151
+ rules: {
152
+ type: "string",
153
+ description: "New business rules, calculations, or state transitions.",
154
+ },
155
+ filePaths: {
156
+ type: "array",
157
+ items: { type: "string" },
158
+ description: "Relative paths of view files to analyze (e.g. ['src/views/Bookings.jsx']).",
159
+ },
160
+ viewFiles: {
161
+ type: "array",
162
+ items: {
163
+ type: "object",
164
+ properties: {
165
+ name: { type: "string" },
166
+ content: { type: "string" },
167
+ },
168
+ required: ["name", "content"],
169
+ },
170
+ description: "View files already loaded in memory [{ name, content }].",
171
+ },
172
+ },
173
+ required: ["keyApp", "name"],
174
+ },
175
+ },
176
+ {
177
+ name: "fleetbo_publish_function",
178
+ description:
179
+ "Deploys a private or public cloud utility function executed in a secure Fleetbo serverless environment.",
180
+ inputSchema: {
181
+ type: "object",
182
+ properties: {
183
+ enterpriseID: {
184
+ type: "string",
185
+ description: "Project enterpriseID infrastructure identifier",
186
+ },
187
+ functionName: {
188
+ type: "string",
189
+ description: "Function name (alphanumeric 3-40 chars, e.g. calculateTotal)",
190
+ },
191
+ code: {
192
+ type: "string",
193
+ description: "JS source code (e.g. async function calculateTotal(payload, Fleetbo) { ... })",
194
+ },
195
+ description: {
196
+ type: "string",
197
+ description: "Action documentation for the catalog and Alex AI",
198
+ },
199
+ isPublic: {
200
+ type: "boolean",
201
+ description: "true to publish to the global Marketplace, false for private function",
202
+ },
203
+ },
204
+ required: ["enterpriseID", "functionName", "code"],
205
+ },
206
+ },
207
+ {
208
+ name: "fleetbo_get_contract",
209
+ description:
210
+ "Provides the official data contract, SDK directives, production lifecycle and canonical blueprint.",
211
+ inputSchema: {
212
+ type: "object",
213
+ properties: {},
214
+ },
215
+ },
216
+ ],
217
+ };
218
+ });
219
+
220
+ // ============================================================================
221
+ // 3. EXÉCUTION DES OUTILS
222
+ // ============================================================================
223
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
224
+ const { name, arguments: args } = request.params;
225
+
226
+ if (name === "fleetbo_get_contract") {
227
+ return {
228
+ content: [
229
+ {
230
+ type: "text",
231
+ text: FLEETBO_SYSTEM_GUIDELINES,
232
+ },
233
+ ],
234
+ };
235
+ }
236
+
237
+ if (!DEV_AUTH_TOKEN) {
238
+ return {
239
+ isError: true,
240
+ content: [
241
+ {
242
+ type: "text",
243
+ text: "Error: FLEETBO_DEV_TOKEN is missing from your environment. Run 'npx fleetbo-svro login' or configure it in your MCP client.",
244
+ },
245
+ ],
246
+ };
247
+ }
248
+
249
+ try {
250
+ // --- ACTION 1 : CREATE PROJECT ---
251
+ if (name === "fleetbo_create_project") {
252
+ const schema = z.object({
253
+ name: z.string().min(2),
254
+ keyApp: z.string().min(2),
255
+ });
256
+ const params = schema.parse(args);
257
+
258
+ const res = await fetch(`https://createprojectlight-${CLOUD_RUN_REGION}`, {
259
+ method: "POST",
260
+ headers: {
261
+ "Content-Type": "application/json",
262
+ Authorization: `Bearer ${DEV_AUTH_TOKEN}`,
263
+ },
264
+ body: JSON.stringify({
265
+ data: {
266
+ name: params.name,
267
+ keyApp: params.keyApp,
268
+ },
269
+ }),
270
+ });
271
+
272
+ const json = await res.json();
273
+ if (!res.ok || json.error) {
274
+ throw new Error(json.error?.message || "Failed to create project on Fleetbo OS.");
275
+ }
276
+
277
+ const proj = json.result?.data || json.data || {};
278
+ const resolvedId = proj.enterpriseId || proj.referenceId || proj.id;
279
+
280
+ return {
281
+ content: [
282
+ {
283
+ type: "text",
284
+ text: JSON.stringify(
285
+ {
286
+ status: "SUCCESS",
287
+ message: `Project "${params.name}" successfully created. Ready for modeling.`,
288
+ enterpriseID: resolvedId,
289
+ keyApp: params.keyApp,
290
+ bootstrapToken: proj.bootstrapToken,
291
+ commandInit: `npx fleetbo-svro init --keyApp=${params.keyApp} --token=${proj.bootstrapToken}`,
292
+ nextSteps: [
293
+ "1. Run commandInit in your terminal to configure local .env.",
294
+ "2. Write your initial UI component (e.g. src/views/App.jsx).",
295
+ "3. Call 'fleetbo_update_project' with this file to forge data contract.",
296
+ "4. Run 'npx fleetbo-svro sync' to seal Edge and generate Fleetbo_contract.md.",
297
+ ],
298
+ },
299
+ null,
300
+ 2
301
+ ),
302
+ },
303
+ ],
304
+ };
305
+ }
306
+
307
+ // --- ACTION 2 : UPDATE PROJECT (MODÉLISATION ADDITIVE) ---
308
+ if (name === "fleetbo_update_project") {
309
+ const schema = z.object({
310
+ keyApp: z.string().min(2),
311
+ name: z.string().min(2),
312
+ rules: z.string().optional(),
313
+ filePaths: z.array(z.string()).optional(),
314
+ viewFiles: z
315
+ .array(
316
+ z.object({
317
+ name: z.string(),
318
+ content: z.string(),
319
+ })
320
+ )
321
+ .optional(),
322
+ });
323
+ const params = schema.parse(args);
324
+
325
+ const filesPayload = [...(params.viewFiles || [])];
326
+
327
+ const ALLOWED_EXTENSIONS = new Set([".jsx", ".tsx", ".vue", ".svelte", ".js", ".ts", ".html"]);
328
+ const FORBIDDEN_PATTERNS = [/\.env/i, /id_rsa/i, /node_modules/i, /\.git/i, /package-lock/i, /\.pem$/i];
329
+ const MAX_FILE_SIZE_BYTES = 500 * 1024;
330
+
331
+ if (params.filePaths && params.filePaths.length > 0) {
332
+ const resolvedProjectRoot = path.resolve(process.cwd());
333
+
334
+ for (const relPath of params.filePaths) {
335
+ const fullPath = path.resolve(resolvedProjectRoot, relPath);
336
+ const relative = path.relative(resolvedProjectRoot, fullPath);
337
+
338
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
339
+ console.warn(`[MCP Security] Access denied outside project directory: ${relPath}`);
340
+ continue;
341
+ }
342
+
343
+ const baseName = path.basename(fullPath);
344
+ if (FORBIDDEN_PATTERNS.some((pat) => pat.test(baseName))) {
345
+ console.warn(`[MCP Security] Sensitive file skipped: ${baseName}`);
346
+ continue;
347
+ }
348
+
349
+ const ext = path.extname(fullPath).toLowerCase();
350
+ if (!ALLOWED_EXTENSIONS.has(ext)) {
351
+ console.warn(`[MCP Security] Unsupported file extension: ${ext}`);
352
+ continue;
353
+ }
354
+
355
+ if (fs.existsSync(fullPath)) {
356
+ const stat = fs.statSync(fullPath);
357
+ if (!stat.isFile()) {
358
+ console.warn(`[MCP Security] Path skipped (not a regular file): ${relPath}`);
359
+ continue;
360
+ }
361
+ if (stat.size > MAX_FILE_SIZE_BYTES) {
362
+ console.warn(`[MCP Security] File too large (> 500 KB) skipped: ${relPath}`);
363
+ continue;
364
+ }
365
+
366
+ filesPayload.push({
367
+ name: baseName,
368
+ content: fs.readFileSync(fullPath, "utf8"),
369
+ });
370
+ } else {
371
+ console.warn(`[MCP Security] File not found on disk: ${relPath}`);
372
+ }
373
+ }
374
+ }
375
+
376
+ if (filesPayload.length === 0 && (!params.rules || !params.rules.trim())) {
377
+ throw new Error(
378
+ "Modeling failed: You must provide at least one valid UI view file (filePaths/viewFiles) or a business rule (rules)."
379
+ );
380
+ }
381
+
382
+ const res = await fetch(`https://updateprojectlight-${CLOUD_RUN_REGION}`, {
383
+ method: "POST",
384
+ headers: {
385
+ "Content-Type": "application/json",
386
+ Authorization: `Bearer ${DEV_AUTH_TOKEN}`,
387
+ },
388
+ body: JSON.stringify({
389
+ data: {
390
+ keyApp: params.keyApp,
391
+ name: params.name,
392
+ newViewFiles: filesPayload,
393
+ fleetbo_rules: params.rules || "",
394
+ },
395
+ }),
396
+ });
397
+
398
+ const json = await res.json();
399
+ if (!res.ok || json.error) {
400
+ throw new Error(json.error?.message || "Failed to model project on Fleetbo Cloud.");
401
+ }
402
+
403
+ return {
404
+ content: [
405
+ {
406
+ type: "text",
407
+ text: JSON.stringify(
408
+ {
409
+ status: "SUCCESS",
410
+ message: `Alex AI modeled ${filesPayload.length} component(s) and registered business rules successfully.`,
411
+ actionRequired: "npx fleetbo-svro sync",
412
+ directive:
413
+ "RUN 'npx fleetbo-svro sync' in terminal now to fetch contracts, seal Edge KV, update TypeScript types and generate Fleetbo_contract.md.",
414
+ },
415
+ null,
416
+ 2
417
+ ),
418
+ },
419
+ ],
420
+ };
421
+ }
422
+
423
+ // --- ACTION 3 : PUBLISH FUNCTION ---
424
+ if (name === "fleetbo_publish_function") {
425
+ const schema = z.object({
426
+ enterpriseID: z.string(),
427
+ functionName: z.string().min(3).max(40),
428
+ code: z.string().min(10),
429
+ description: z.string().optional(),
430
+ isPublic: z.boolean().optional(),
431
+ });
432
+ const params = schema.parse(args);
433
+
434
+ const res = await fetch(`https://publishfunction-${CLOUD_RUN_REGION}`, {
435
+ method: "POST",
436
+ headers: {
437
+ "Content-Type": "application/json",
438
+ Authorization: `Bearer ${DEV_AUTH_TOKEN}`,
439
+ },
440
+ body: JSON.stringify({
441
+ data: {
442
+ enterpriseID: params.enterpriseID,
443
+ functionName: params.functionName,
444
+ targetType: "inline",
445
+ code: params.code,
446
+ description: params.description || "",
447
+ isPublic: params.isPublic ?? false,
448
+ },
449
+ }),
450
+ });
451
+
452
+ const json = await res.json();
453
+ if (!res.ok || json.error) {
454
+ throw new Error(json.error?.message || "Failed to deploy function.");
455
+ }
456
+
457
+ return {
458
+ content: [
459
+ {
460
+ type: "text",
461
+ text: JSON.stringify(
462
+ {
463
+ status: "SUCCESS",
464
+ functionName: `$${params.functionName}`,
465
+ isPublic: params.isPublic ?? false,
466
+ usageHint: `Direct client usage: const res = await Fleetbo.call.$${params.functionName}(payload);`,
467
+ },
468
+ null,
469
+ 2
470
+ ),
471
+ },
472
+ ],
473
+ };
474
+ }
475
+
476
+ throw new Error(`Unknown tool: ${name}`);
477
+ } catch (err) {
478
+ return {
479
+ isError: true,
480
+ content: [{ type: "text", text: `Fleetbo MCP Error: ${err.message}` }],
481
+ };
482
+ }
483
+ });
484
+
485
+ // ============================================================================
486
+ // 4. CONNEXION STDIO
487
+ // ============================================================================
488
+ const transport = new StdioServerTransport();
489
+ await server.connect(transport);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fleetbo-svro",
3
- "version": "1.0.46",
3
+ "version": "1.0.48",
4
4
  "main": "dist/index.js",
5
5
  "type": "module",
6
6
  "exports": {
@@ -21,8 +21,10 @@
21
21
  "index.d.ts"
22
22
  ],
23
23
  "dependencies": {
24
+ "@modelcontextprotocol/sdk": "^1.30.0",
24
25
  "firebase": "^12.16.0",
25
- "unplugin-auto-import": "^0.18.0"
26
+ "unplugin-auto-import": "^0.18.0",
27
+ "zod": "^4.6.5"
26
28
  },
27
29
  "devDependencies": {
28
30
  "esbuild": "^0.28.1"