fakelab 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,12 +27,15 @@ create `fakelab.config.ts` file in the project root. and reference your typescri
27
27
  import { defineConfig } from "fakelab";
28
28
 
29
29
  export default defineConfig({
30
- sourcePath: "./types", // can set one/multiple directory(s) or typescript file(s).
30
+ sourcePath: ["./types", "./fixtures/**/*.ts"], // supports glob pattern
31
31
  faker: { locale: "en" }, // optional
32
32
  server: { pathPrefix: "api/v1", port: 8080 }, // optional
33
+ browser: { expose: { mode: "module" } }, // optional
33
34
  });
34
35
  ```
35
36
 
37
+ ## Faker Annotations
38
+
36
39
  Fakelab allows you to control generated mock data using JSDoc tags.
37
40
  You simply annotate your TypeScript interfaces with the @faker tag, and Fakelab uses the corresponding [faker](https://fakerjs.dev/)
38
41
  method when generating mock values.
@@ -85,18 +88,14 @@ export interface User {
85
88
 
86
89
  ## Fakelab Runtime
87
90
 
88
- `fakelab/runtime` enables a **global Fakelab object** at runtime, allowing your frontend or Node environment to communicate with the running Fakelab mock server.
89
-
90
- ## Enabling the runtime (important)
91
-
92
- To enable the global `fakelab` object, you **must import the runtime once** in your application.
91
+ `fakelab/runtime` enables `fakelab` module at runtime, allowing your frontend or Node environment to communicate with the running Fakelab mock server.
93
92
 
94
- ## `fakelab.URL`
93
+ ## `fakelab.url()`
95
94
 
96
95
  The base URL of the running Fakelab server.
97
96
 
98
97
  ```ts
99
- fakelab.URL;
98
+ fakelab.url();
100
99
  // e.g. "http://localhost:50000/api"
101
100
  ```
102
101
 
@@ -107,7 +106,7 @@ Fetch mock data from the Fakelab server by **typescript interface/type name**.
107
106
  ### Signature
108
107
 
109
108
  ```ts
110
- fakelab.fetch(name: string, count?: number): Promise<T[]>
109
+ fakelab.fetch(name: string, count?: number): Promise<T>
111
110
  ```
112
111
 
113
112
  ### Parameters
@@ -120,6 +119,15 @@ fakelab.fetch(name: string, count?: number): Promise<T[]>
120
119
  ### Basic example
121
120
 
122
121
  ```ts
122
+ import { fakelab } from "fakelab/runtime";
123
+
124
+ const users = await fakelab.fetch("User", 10);
125
+
126
+ console.log(users);
127
+
128
+ // or
129
+
130
+ // can be enabled as a global object
123
131
  import "fakelab/runtime";
124
132
 
125
133
  const users = await fakelab.fetch("User", 10);
@@ -127,6 +135,69 @@ const users = await fakelab.fetch("User", 10);
127
135
  console.log(users);
128
136
  ```
129
137
 
138
+ **NOTE:** Set count to a negative number to get an empty array.
139
+
140
+ ## Database Mode
141
+
142
+ Fakelab can persist generated mock data to a local database.
143
+
144
+ Under the hood, Fakelab uses the lightweight [lowdb](https://github.com/typicode/lowdb)
145
+ library for persistence, ensuring fast reads, simple JSON storage, and zero external dependencies.
146
+
147
+ ### Database Options
148
+
149
+ ```ts
150
+ export type DatabaseOptions = {
151
+ enabled: boolean;
152
+ dest?: string;
153
+ };
154
+ ```
155
+
156
+ ### Basic example
157
+
158
+ ```ts
159
+ export default defineConfig({
160
+ database: { enabled: true, dest: "db" },
161
+ });
162
+ ```
163
+
164
+ ## Network Simulation
165
+
166
+ Fakelab can simulate real-world network conditions such as latency, random failures, timeouts, and offline mode.
167
+ This is useful for testing loading states, retry logic, and poor network UX without changing frontend code.
168
+
169
+ ### Network Options
170
+
171
+ ```ts
172
+ type NetworkBehaviourOptions = {
173
+ delay?: number | [number, number];
174
+ errorRate?: number;
175
+ timeoutRate?: number;
176
+ offline?: boolean;
177
+ };
178
+
179
+ export type NetworkOptions = NetworkBehaviourOptions & {
180
+ preset?: string;
181
+ presets?: Record<string, NetworkBehaviourOptions>;
182
+ };
183
+ ```
184
+
185
+ ### Basic example
186
+
187
+ ```ts
188
+ export default defineConfig({
189
+ network: {
190
+ delay: [300, 1200],
191
+ errorRate: 0.1,
192
+ timeoutRate: 0.05,
193
+ presets: { wifi: { errorRate: 1 } },
194
+ preset: "wifi",
195
+ },
196
+ });
197
+ ```
198
+
199
+ **NOTE:** When both inline network options and a `preset` are defined, inline options always take precedence and override the preset values.
200
+
130
201
  ## Server Command
131
202
 
132
203
  Run:
package/lib/cli.js CHANGED
@@ -1,5 +1,7 @@
1
- import y from'path';import {fileURLToPath}from'url';import E from'fs-extra';import {Command}from'commander';import v from'express';import G from'cors';import z from'express-ejs-layouts';import K from'http';import'ejs';import M from'qs';import {Project}from'ts-morph';import l from'picocolors';import Q from'figlet';import {bundleRequire}from'bundle-require';import Y from'joycon';var p=class r{static prefix(e){let t=new Date().toLocaleTimeString();return {info:l.blue,warn:l.yellow,error:l.red,success:l.green,debug:l.magenta}[e](`[${t}] FAKELAB_${e.toUpperCase()}`)}static log(e,t,...n){let o=l.white,s=r.prefix(e);(e==="error"?console.error:e==="warn"?console.warn:console.log)(s,o(t),...n);}static info(e,...t){this.log("info",e,...t);}static warn(e,...t){this.log("warn",e,...t);}static error(e,...t){this.log("error",e,...t);}static success(e,...t){this.log("success",e,...t);}};var h=class{constructor(e){this.faker=e;}JSDOC_FAKER_FIELD="faker";FAKER_TAG_REGEX=/^([a-zA-Z0-9._]+)(?:\((.*)\))?$/;boolMapping={true:true,false:false};string(e){return this.execute(e,this.faker.word.noun)}int(e){return this.execute(e,this.faker.number.int)}bool(e){return this.execute(e,this.faker.datatype.boolean)}bigInt(e){return this.execute(e,this.faker.number.bigInt)}litbool(e){return this.boolMapping[e]}async object(e,t){let n={};return await Promise.all(e.map(async o=>{let s=o.getTypeAtLocation(o.getValueDeclarationOrThrow());n[o.getName()]=await t(s,this,this.readJSDocTags(o));})),n}async union(e){let t=await Promise.all(e);return t[Math.floor(Math.random()*t.length)]}async intersection(e){let t=await Promise.all(e);return t[Math.floor(Math.random()*t.length)]}evalArgs(e){if(!(!e||!e.trim()))return Function(`"use strict"; return (${e});`)()}readJSDocTags(e){let t=e.getJsDocTags().filter(n=>n.getName()===this.JSDOC_FAKER_FIELD);return t.length===0?[]:t.map(n=>{let[o]=n.getText();if(!o)return;let s=o.text.trim().match(this.FAKER_TAG_REGEX);if(!s)return;let[,i,a]=s,c=this.evalArgs(a);return {path:i,args:c}})}execute(e,t){if(!e)return t();let n=e.path.split("."),o=this.faker;for(let s of n)o=o[s],o||(p.error("Invalid faker module path:",e.path),process.exit(1));typeof o!="function"&&(p.error("Unresolvable faker function.",e.path),process.exit(1));try{return e.args?o(e.args):o()}catch{return p.error("Passed invalid arguments to faker function."),o()}}};var D=fileURLToPath(import.meta.url),O=y.dirname(D),d=class{constructor(e){this.files=e;let n=new Project({tsConfigFilePath:"tsconfig.json"}).addSourceFilesAtPaths(e);this.__targets=n.flatMap(o=>{let s=o.getInterfaces(),i=o.getTypeAliases(),a=o.getExportDeclarations().flatMap(c=>c.getNamedExports().flatMap(f=>f.getLocalTargetDeclarations()));return [...s,...i,...a]}),this.generateInFileEntitiyMap(this.__targets);}__targets;async run(e){return await e()}normalizePath(e){return e.split(y.sep).join(y.posix.sep)}generateInFileEntitiyMap(e){let n=`declare global {
2
- interface FakeRuntime {${[...new Set(e.map(o=>{let s=o.getName(),i=o.getSourceFile().getFilePath();return `${s}: import("${i}").${s}`}))].join(`
1
+ import g from'path';import O from'fs-extra';import {Command}from'commander';import R from'express';import H from'cors';import K from'express-ejs-layouts';import X from'http';import'ejs';import {Project}from'ts-morph';import d from'winston';import b from'picocolors';import {JSONFilePreset}from'lowdb/node';import {fileURLToPath}from'url';import U from'qs';import V from'figlet';import {bundleRequire}from'bundle-require';import se from'joycon';function S(s){switch(s){case "info":return b.blueBright(s.toUpperCase());case "error":return b.redBright(s.toUpperCase());case "warn":return b.yellowBright(s.toUpperCase());default:return s.toUpperCase()}}var j=d.format.printf(({level:s,message:e,timestamp:t})=>`${b.dim(`[${t}]`)} ${S(s)} ${e}`),m=d.createLogger({format:d.format.combine(d.format.timestamp(),d.format.splat(),j),transports:[new d.transports.Console]}),I=new Intl.ListFormat("en",{style:"long",type:"unit"}),c=class{static info(e,...t){return m.info(e,...t)}static warn(e,...t){return m.warn(e,...t)}static error(e,...t){return m.error(e,...t)}static debug(e,...t){if(!(typeof process>"u"||!process.env.DEBUG))return m.info(e,...t)}static list(e){return I.format(e)}static close(){m.removeAllListeners(),m.close();}};var w=class{constructor(e){this.faker=e;}JSDOC_FAKER_FIELD="faker";FAKER_TAG_REGEX=/^([a-zA-Z0-9._]+)(?:\((.*)\))?$/;boolMapping={true:true,false:false};string(e){return this.execute(e,this.faker.word.noun)}int(e){return this.execute(e,this.faker.number.int)}bool(e){return this.execute(e,this.faker.datatype.boolean)}bigInt(e){return this.execute(e,this.faker.number.bigInt)}litbool(e){return this.boolMapping[e]}async object(e,t){let r={};return await Promise.all(e.map(async o=>{let i=o.getTypeAtLocation(o.getValueDeclarationOrThrow());r[o.getName()]=await t(i,this,this.readJSDocTags(o));})),r}async union(e){let t=await Promise.all(e);return t[Math.floor(Math.random()*t.length)]}async intersection(e){let t=await Promise.all(e);return t[Math.floor(Math.random()*t.length)]}evalArgs(e){if(!(!e||!e.trim()))return Function(`"use strict"; return (${e});`)()}readJSDocTags(e){let t=e.getJsDocTags().filter(r=>r.getName()===this.JSDOC_FAKER_FIELD);return t.length===0?[]:t.map(r=>{let[o]=r.getText();if(!o)return;let i=o.text.trim().match(this.FAKER_TAG_REGEX);if(!i)return;let[,n,a]=i,p=this.evalArgs(a);return {path:n,args:p}})}execute(e,t){if(!e)return t();let r=e.path.split("."),o=this.faker;for(let i of r)o=o[i],o||(c.error("Invalid faker module path:",e.path),process.exit(1));typeof o!="function"&&(c.error("Unresolvable faker function.",e.path),process.exit(1));try{return e.args?o(e.args):o()}catch{return c.error("Passed invalid arguments to faker function."),o()}}};var u=g.dirname(fileURLToPath(import.meta.url)),F=process.cwd();var k=class{constructor(e,t){this.files=e;this.config=t;let o=new Project({tsConfigFilePath:"tsconfig.json"}).addSourceFilesAtPaths(e);this.__targets=o.flatMap(i=>{let n=i.getInterfaces(),a=i.getTypeAliases(),p=i.getExportDeclarations().flatMap(l=>l.getNamedExports().flatMap(f=>f.getLocalTargetDeclarations()));return [...n,...a,...p]}),this.generateInFileEntitiyMap(this.__targets);}__targets;async run(e){return await e()}normalizePath(e){return e.split(g.sep).join(g.posix.sep)}generateInFileEntitiyMap(e){let t=[...new Set(e.map(i=>{let n=i.getName(),a=i.getSourceFile().getFilePath();return `${n}: import("${a}").${n}`}))],{expose:r}=this.config.browserOpts(),o=`
2
+ interface Runtime$ {
3
+ ${t.join(`
3
4
  `)}
4
- }
5
- }`;E.appendFile(y.resolve(O,"runtime.d.ts"),n);}entities(){let e=this.__targets.map(t=>{let n=t.getName().toLowerCase(),o=t.getType(),s=this.normalizePath(process.cwd()),a=this.normalizePath(t.getSourceFile().getDirectoryPath()).replace(s,""),c=t.getSourceFile().getBaseName(),f=`${a}/${c}`;return [n,{type:o,filepath:f}]});return new Map(e)}async loadFaker(e){let{faker:t}=await import(`@faker-js/faker/locale/${e.locale}`);return t}};async function m(r,e,t=[],n=0){if(r.isString())return e.string(t[n]);if(r.isNumber())return e.int(t[n]);if(r.isBoolean())return e.bool(t[n]);if(r.isBigInt())return e.bigInt(t[n]);if(r.isBooleanLiteral())return e.litbool(r.getText());if(r.isLiteral())return r.getLiteralValue();if(!r.isUndefined()){if(r.isUnion()){let o=r.getUnionTypes();return await e.union(o.map((s,i)=>m(s,e,t,i)))}if(r.isIntersection()){let o=r.getIntersectionTypes();return await e.intersection(o.map((s,i)=>m(s,e,t,i)))}if(r.isArray()){let o=r.getArrayElementTypeOrThrow();return [await m(o,e,t,n)]}if(r.isObject()){let o=r.getProperties();return await e.object(o,(s,i,a)=>m(s,i,a,n))}return null}}function R({each:r}){return {resolve:async t=>await Promise.all(Array.from({length:t},r))}}async function F(r,e){let t=await r.files(e.source),n=new d(t),o=await n.loadFaker(r.fakerOpts(e.locale)),s=new h(o),i=n.entities();async function a(c,f){let u=R({each:()=>m(c,s)}),g=await(f.count?u.resolve(parseInt(f.count)):m(c,s)),k=JSON.stringify(g,null,2);return {data:g,json:k}}return {entities:i,forge:a}}var U=fileURLToPath(import.meta.url),B=y.dirname(U),b=E.readJSONSync(y.join(B,"../package.json")),w=class{constructor(e,t,n){this.router=e;this.config=t;this.opts=n;let{pathPrefix:o}=this.config.serverOpts(this.opts.pathPrefix,this.opts.port);this.prefix=o;}prefix;async handleQueries(e){let t=e.query.count;return t?{count:t.toString()}:{}}async register(){let{entities:e,forge:t}=await F(this.config,this.opts);this.router.get("/",(n,o)=>{let s=n.path;o.render("index",{currentPath:s,entities:e,version:b.version});}),this.router.get("/:name",async(n,o)=>{let s=`${n.protocol}://${n.host}/`,i=n.path,a=n.params.name,c=await this.handleQueries(n),f=M.stringify(c,{addQueryPrefix:true}),u=e.get(a.toLowerCase());if(u){let{json:g}=await t(u.type,c),k=u.filepath;o.render("preview",{name:a,filepath:k,currentPath:i,address:s,search:f,json:g,entities:e,version:b.version,prefix:this.prefix});}else o.redirect("/");}),this.router.get(`/${this.prefix}/:name`,async(n,o)=>{try{let s=n.params.name,i=await this.handleQueries(n),a=e.get(s.toLowerCase());if(a){let{data:c}=await t(a.type,i);o.status(200).json(c);}else o.status(400).json({message:"The requested interface is not found"});}catch(s){o.status(500).send(s);}});}};var q=fileURLToPath(import.meta.url),x=y.dirname(q);function V(r,e,t){let{port:n}=e.serverOpts(t.pathPrefix,t.port);r.listen(n,"localhost",async()=>{p.info(`Server: http://localhost:${n}`),console.log(await Q.text("FAKELAB"));});}function X(r,e,t){e.setHeader("x-powered-by","fakelab"),t();}function H(r){r.disable("x-powered-by"),r.use(v.json()),r.use(G({methods:"GET"})),r.use(v.static(x+"/public")),r.use(X);}function Z(r){r.set("views",y.join(x,"views")),r.set("view engine","ejs"),r.use(z),r.set("layout","layouts/main");}async function _(r,e){let t=v(),n=v.Router(),o=K.createServer(t);H(t),Z(t),await r.generateInFileRuntimeConfig(x,e),await new w(n,r,e).register(),t.use(n),V(o,r,e);}async function C(){try{let e=await new Y().resolve({files:["fakelab.config.ts"]});return e||(p.error("No fakelab config file is detected."),process.exit(1)),(await bundleRequire({filepath:e})).mod.default}catch{p.error("Could not load the config file."),process.exit(1);}}var P=new Command,oe=fileURLToPath(import.meta.url),ne=y.dirname(oe),T=E.readJSONSync(y.join(ne,"../package.json"));P.name(T.name).description(T.description).version(T.version);P.command("serve").description("start server").option("-s, --source <char>","config source path").option("-x, --pathPrefix <char>","server url path prefix").option("-p, --port <number>","server port number",parseInt).option("-l, --locale <char>","faker custom locale").action(async r=>{let e=await C();_(e,r);});P.parse();
5
+ }`;r.mode==="global"&&(o=`
6
+ declare global {${o}
7
+ }`),O.appendFile(g.resolve(u,this.config.RUNTIME_DECL_FILENAME),o);}address(e,t){let r=this.normalizePath(F);return `${e.replace(r,"")}/${t}`}async entities(){let e=await Promise.all(this.__targets.map(async t=>{let r=t.getName().toLowerCase(),o=t.getType(),i=this.normalizePath(t.getSourceFile().getDirectoryPath()),n=t.getSourceFile().getBaseName(),a=this.address(i,n),p=this.config.getDatabaseDirectoryPath(),l=g.resolve(p,`${r}.json`),f=this.address(this.normalizePath(p),g.basename(l)),y=await JSONFilePreset(l,[]);return [r,{type:o,filepath:a,table:y,tablepath:f}]}));return new Map(e)}async initFakerLibrary(e){let{faker:t}=await import(`@faker-js/faker/locale/${e.locale}`);return t}};async function h(s,e,t=[],r=0){if(s.isString())return e.string(t[r]);if(s.isNumber())return e.int(t[r]);if(s.isBoolean())return e.bool(t[r]);if(s.isBigInt())return e.bigInt(t[r]);if(s.isBooleanLiteral())return e.litbool(s.getText());if(s.isLiteral())return s.getLiteralValue();if(!s.isUndefined()){if(s.isUnion()){let o=s.getUnionTypes();return await e.union(o.map((i,n)=>h(i,e,t,n)))}if(s.isIntersection()){let o=s.getIntersectionTypes();return await e.intersection(o.map((i,n)=>h(i,e,t,n)))}if(s.isArray()){let o=s.getArrayElementTypeOrThrow();return [await h(o,e,t,r)]}if(s.isObject()){let o=s.getProperties();return await e.object(o,(i,n,a)=>h(i,n,a,r))}return null}}function J({each:s}){return {resolve:async t=>await Promise.all(Array.from({length:t},s))}}async function A(s,e){let t=await s.files(e.source),r=new k(t,s),o=await r.entities(),i=await r.initFakerLibrary(s.fakerOpts(e.locale)),n=new w(i);async function a(p,l){let f=J({each:()=>h(p,n)}),y=await(l.count?f.resolve(parseInt(l.count)):h(p,n)),D=JSON.stringify(y,null,2);return {data:y,json:D}}return {entities:o,build:a}}var v=class{constructor(e,t,r){this.builder=e;this.config=t;this.pkg=r;}async handleQueries(e){let t=e.query.count;return t?{count:t.toString()}:{}}index(){return (e,t)=>{t.render("index",{name:null,entities:this.builder.entities,version:this.pkg.version,enabled:this.config.databaseEnabled()});}}preview(e){return async(t,r)=>{let o=`${t.protocol}://${t.host}/`,i=t.params.name,n=await this.handleQueries(t),a=U.stringify(n,{addQueryPrefix:true}),p=this.builder.entities.get(i.toLowerCase());if(p){let{json:l}=await this.builder.build(p.type,n),f=p.filepath;r.render("preview",{name:i,filepath:f,address:o,search:a,json:l,prefix:e,entities:this.builder.entities,version:this.pkg.version,enabled:this.config.databaseEnabled()});}else r.redirect("/");}}database(){return (e,t)=>{this.config.databaseEnabled()?t.render("database",{name:null,entities:this.builder.entities,version:this.pkg.version}):t.redirect("/");}}table(e){return async(t,r)=>{let o=`${t.protocol}://${t.host}/`,i=t.params.name,n=this.builder.entities.get(i.toLowerCase());if(!this.config.databaseEnabled())r.redirect("/");else if(n){await n.table.read();let p=n.table.data.length>0,l=JSON.stringify(n.table.data,null,2),f=n.filepath;r.render("table",{name:i,filepath:f,address:o,prefix:e,json:l,hasData:p,entities:this.builder.entities,version:this.pkg.version});}else r.redirect("/database");}}};var x=class{constructor(e,t){this.builder=e;this.network=t;}async handleQueries(e){let t=e.query.count;return t?{count:t.toString()}:{}}async applyNetworkHandlers(e){if(this.network.offline()){let{status:t,message:r}=this.network.state("offline");return e.status(t).json({message:r}),true}if(await this.network.wait(),this.network.timeout())return true;if(this.network.error()){let{status:t,message:r}=this.network.state("error");return e.status(t).json({message:r}),true}return false}entity(){return async(e,t)=>{try{if(await this.applyNetworkHandlers(t))return;let r=e.params.name,o=await this.handleQueries(e),i=this.builder.entities.get(r.toLowerCase());if(i){let{data:n}=await this.builder.build(i.type,o);t.status(200).json(n);}else t.status(400).json({message:"The entity is not exists"});}catch(r){t.status(500).send(r);}}}getTable(){return async(e,t)=>{try{if(await this.applyNetworkHandlers(t))return;let r=e.params.name,o=this.builder.entities.get(r.toLowerCase());o?(await o.table.read(),t.status(200).json(o.table.data)):t.status(400).json({message:"The table is not exists"});}catch(r){t.status(500).send(r);}}}updateTable(){return async(e,t)=>{try{if(await this.applyNetworkHandlers(t))return;let r=e.params.name,o=await this.handleQueries(e),i=this.builder.entities.get(r.toLowerCase());if(i){let{data:n}=await this.builder.build(i.type,o);await i.table.update(a=>a.push(n)),t.status(200).json({success:!0});}else t.status(400).json({success:!1,message:"The table is not exists"});}catch(r){t.status(500).send(r);}}}_update(){return async(e,t)=>{try{let r=e.params.name,o=await this.handleQueries(e),i=this.builder.entities.get(r.toLowerCase());if(i){let{data:n}=await this.builder.build(i.type,o);await i.table.update(a=>a.push(n)),t.status(301).redirect(`/database/${r.toLowerCase()}`);}else t.status(400).redirect("/database");}catch{t.status(500).redirect("/database");}}}_clear(){return async(e,t)=>{try{let r=e.params.name,o=this.builder.entities.get(r.toLowerCase());o?(await o.table.read(),o.table.data.length>0&&await o.table.update(i=>i.length=0),t.status(301).redirect(`/database/${r.toLowerCase()}`)):t.status(400).redirect("/database");}catch{t.status(500).redirect("/database");}}}};var G=O.readJSONSync(g.join(u,"../package.json")),C=class{constructor(e,t,r,o){this.router=e;this.config=t;this.opts=r;this.network=o;let{pathPrefix:i}=this.config.serverOpts(this.opts.pathPrefix,this.opts.port);this.prefix=i;}prefix;async register(){let e=await A(this.config,this.opts),t=new v(e,this.config,G),r=new x(e,this.network);this.router.get("/",t.index()),this.router.get("/entities/:name",t.preview(this.prefix)),this.router.get("/database",t.database()),this.router.get("/database/:name",t.table(this.prefix)),this.router.get(`/${this.prefix}/:name`,r.entity()),this.router.get(`/${this.prefix}/database/:name`,r.getTable()),this.router.post(`/${this.prefix}/database/:name`,r.updateTable()),this.router.post("/__update/:name",r._update()),this.router.post("/__delete/:name",r._clear());}};var T=class s{constructor(e){this.config=e;this.options=this.config.networkOpts(),this.timeout=this.timeout.bind(this),this.error=this.error.bind(this),this.state=this.state.bind(this),this.middleware=this.middleware.bind(this),this.wait=this.wait.bind(this),this.offline=this.offline.bind(this);}options;static initHandlers(e){return new s(e)}timeout(){let e=this.chance(this.options?.timeoutRate);return e&&c.debug("Network timeout..."),e}error(){let e=this.chance(this.options?.errorRate);return e&&c.debug("Network error..."),e}state(e){switch(e){case "error":return {status:500,message:"Network error"};case "offline":return {status:503,message:"Network offline"};default:return {status:500,message:"Unknown error"}}}async wait(){let e=this.resolveDelay();e>0&&(c.debug("Network waiting (%d ms)...",e),await this.sleep(e));}offline(){return this.options?.offline??false}middleware(e,t,r){let o=this.options?.errorRate||0,i=this.options?.timeoutRate||0,n=this.options?.offline??false,a=`delay=${this.resolveDelay()},error=${o},timeout=${i},offline=${n}`;t.setHeader("X-Fakelab-Network",a),r();}resolveDelay(){let e=this.options?.delay;return typeof e=="number"?Math.round(e):Array.isArray(e)?this.random(e):0}chance(e=0){return Math.random()<e}random([e,t]){return Math.round(Math.random()*(t-e)+e)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function W(s,e){try{process.loadEnvFile("./.env.local");}catch{}s.databaseEnabled()&&c.info(`database: ${s.getDatabaseDirectoryPath()}`),c.info(`server: http://localhost:${e}`),console.log(V.textSync("FAKELAB"));}function Z(s,e,t){let{port:r}=e.serverOpts(t.pathPrefix,t.port);s.listen(r,"localhost",()=>W(e,r)),s.on("close",()=>{c.close();});}function Y(s,e,t){e.setHeader("x-powered-by","fakelab"),t();}function ee(s,e){s.disable("x-powered-by"),s.use(R.json()),s.use(H({methods:"GET"})),s.use(R.static(u+"/public")),s.use(Y),s.use(e.middleware);}function te(s){s.set("views",g.join(u,"views")),s.set("view engine","ejs"),s.use(K),s.set("layout","layouts/main");}async function L(s,e){let t=R(),r=R.Router(),o=X.createServer(t),i=T.initHandlers(s);ee(t,i),te(t),await s.generateInFileRuntimeConfig(u,e),await new C(r,s,e,i).register(),t.use(r),Z(o,s,e);}async function N(){try{let e=await new se().resolve({files:["fakelab.config.ts"]});return e||(c.error("No fakelab config file is detected."),process.exit(1)),(await bundleRequire({filepath:e})).mod.default}catch{c.error("Could not load the config file."),process.exit(1);}}var P=new Command,E=O.readJSONSync(g.join(u,"../package.json"));P.name(E.name).description(E.description).version(E.version);P.command("serve").description("start server").option("-s, --source <char>","config source path").option("-x, --pathPrefix <char>","server url path prefix").option("-p, --port <number>","server port number",parseInt).option("-l, --locale <char>","faker custom locale").action(async s=>{let e=await N();L(e,s);});P.parse();
package/lib/main.d.ts CHANGED
@@ -14,10 +14,35 @@ type ServerOptions = {
14
14
  type FakerEngineOptions = {
15
15
  locale?: FakerLocale;
16
16
  };
17
+ type DatabaseOptions = {
18
+ enabled: boolean;
19
+ dest?: string;
20
+ };
21
+ type BrowserExposeOptions = {
22
+ name: string;
23
+ mode: "module" | "global";
24
+ };
25
+ type BrowserOptions = {
26
+ expose?: Partial<BrowserExposeOptions>;
27
+ };
28
+ type NetworkBehaviourOptions = {
29
+ delay?: number | [number, number];
30
+ errorRate?: number;
31
+ timeoutRate?: number;
32
+ offline?: boolean;
33
+ };
34
+ type NetworkOptions = NetworkBehaviourOptions & {
35
+ preset?: string;
36
+ presets?: Record<string, NetworkBehaviourOptions>;
37
+ };
17
38
  type ConfigOptions = {
18
39
  sourcePath: string | string[];
19
40
  server?: ServerOptions;
20
41
  faker?: FakerEngineOptions;
42
+ database?: DatabaseOptions;
43
+ browser?: BrowserOptions;
44
+ network?: NetworkOptions;
45
+ transform?: Record<string, (data: any) => any | Promise<any>>;
21
46
  };
22
47
  type ServerCLIOptions = {
23
48
  source?: string;
@@ -28,11 +53,21 @@ type ServerCLIOptions = {
28
53
 
29
54
  declare class Config {
30
55
  private readonly opts;
56
+ readonly RUNTIME_SOURCE_FILENAME = "runtime.js";
57
+ readonly RUNTIME_DECL_FILENAME = "runtime.d.ts";
58
+ readonly FAKELAB_PERSIST_DIR = ".fakelab";
59
+ NETWORK_DEFAULT_OPTIONS: Readonly<NetworkOptions>;
31
60
  constructor(opts: ConfigOptions);
32
61
  files(_sourcePath?: string): Promise<string[]>;
33
62
  serverOpts(prefix?: string, port?: number): Required<ServerOptions>;
63
+ browserOpts(name?: string, mode?: "module" | "global"): Required<BrowserOptions>;
64
+ networkOpts(): NetworkOptions;
34
65
  fakerOpts(locale?: FakerLocale): Required<FakerEngineOptions>;
35
- generateInFileRuntimeConfig(dir: string, options: ServerCLIOptions): Promise<void>;
66
+ generateInFileRuntimeConfig(dirname: string, options: ServerCLIOptions): Promise<void>;
67
+ getDatabaseDirectoryPath(): string;
68
+ databaseEnabled(): boolean;
69
+ private initializeDatabase;
70
+ private modifyGitignoreFile;
36
71
  private tryStat;
37
72
  private isReadable;
38
73
  private resolveSourcePath;
package/lib/main.js CHANGED
@@ -1,9 +1,10 @@
1
- import k from'fast-glob';import l from'path';import m from'fs-extra';import {stat,access,constants}from'fs/promises';import a from'picocolors';var s=class o{static prefix(e){let t=new Date().toLocaleTimeString();return {info:a.blue,warn:a.yellow,error:a.red,success:a.green,debug:a.magenta}[e](`[${t}] FAKELAB_${e.toUpperCase()}`)}static log(e,t,...r){let n=a.white,c=o.prefix(e);(e==="error"?console.error:e==="warn"?console.warn:console.log)(c,n(t),...r);}static info(e,...t){this.log("info",e,...t);}static warn(e,...t){this.log("warn",e,...t);}static error(e,...t){this.log("error",e,...t);}static success(e,...t){this.log("success",e,...t);}};var f=["af","ar","az","bn","cs","cy","da","de","dv","el","en","eo","es","fa","fi","fr","he","hr","hu","hy","id","it","ja","ka","ko","ku","lv","mk","nb","ne","nl","pl","pt","ro"];function h(){let o=Intl.DateTimeFormat().resolvedOptions().locale;if(!o)return "en";let[e]=o.split("-"),t=e.toLowerCase();return f.includes(t)?t:"en"}var i=class{static source(e,t){return `global.fakelab = {};
2
- global.fakelab.URL = "http://localhost:${e}/${t}/";
3
- global.fakelab.fetch = async function (name, count) {
1
+ import N from'fast-glob';import i from'path';import d from'fs-extra';import {stat,access,constants}from'fs/promises';import F from'is-glob';import p from'winston';import u from'picocolors';import {transform}from'esbuild';function M(a){switch(a){case "info":return u.blueBright(a.toUpperCase());case "error":return u.redBright(a.toUpperCase());case "warn":return u.yellowBright(a.toUpperCase());default:return a.toUpperCase()}}var D=p.format.printf(({level:a,message:e,timestamp:t})=>`${u.dim(`[${t}]`)} ${M(a)} ${e}`),l=p.createLogger({format:p.format.combine(p.format.timestamp(),p.format.splat(),D),transports:[new p.transports.Console]}),_=new Intl.ListFormat("en",{style:"long",type:"unit"}),s=class{static info(e,...t){return l.info(e,...t)}static warn(e,...t){return l.warn(e,...t)}static error(e,...t){return l.error(e,...t)}static debug(e,...t){if(!(typeof process>"u"||!process.env.DEBUG))return l.info(e,...t)}static list(e){return _.format(e)}static close(){l.removeAllListeners(),l.close();}};var g="fakelab",y="module",h=["af","ar","az","bn","cs","cy","da","de","dv","el","en","eo","es","fa","fi","fr","he","hr","hu","hy","id","it","ja","ka","ko","ku","lv","mk","nb","ne","nl","pl","pt","ro"];function O(){let a=Intl.DateTimeFormat().resolvedOptions().locale;if(!a)return "en";let[e]=a.split("-"),t=e.toLowerCase();return h.includes(t)?t:"en"}var T=`let fl = {};
2
+ let db = {};
3
+ fl.url = () => "http://localhost:PORT/PREFIX/";
4
+ fl.fetch = async function (name, count) {
4
5
  const search = count ? "?count=" + count : "";
5
6
 
6
- const response = await fetch(global.fakelab.URL + name + search);
7
+ const response = await fetch(fl.url() + name + search);
7
8
 
8
9
  if (!response.ok) throw new Error("[fakelab] Failed to retreived mock data.");
9
10
 
@@ -11,25 +12,108 @@ global.fakelab.fetch = async function (name, count) {
11
12
 
12
13
  return result;
13
14
  };
14
- `}static decl(){return `export {};
15
+
16
+ db.enabled = () => ENABLED_COND;
17
+ db.get = async function (name) {
18
+ if (!db.enabled()) throw new Error("[fakelab] Database is not enabled.");
19
+
20
+ const response = await fetch(NAME.url() + "database/" + name);
21
+
22
+ if (!response.ok) throw new Error("[fakelab] Failed to retreived data from database.");
23
+
24
+ const result = await response.json();
25
+
26
+ return result;
27
+ };
28
+ db.post = async function (name) {
29
+ if (!db.enabled()) throw new Error("[fakelab] Database is not enabled.");
30
+
31
+ const response = await fetch(NAME.url() + "database/" + name, { method: "POST" });
32
+
33
+ if (!response.ok) throw new Error("[fakelab] Failed to post data to database.");
34
+ };
35
+
36
+ const NAME = Object.freeze(fl);
37
+ const database = Object.freeze(db);
38
+
39
+ export { NAME, database };`,A=`declare function fetch<T extends keyof Runtime$, CT extends number | undefined = undefined>(name: T, count?: CT): Promise<Result$<Runtime$[T], CT>>;
40
+ declare function get<T extends keyof Runtime$>(name: T): Promise<Runtime$[T]>;
41
+ declare function post<T extends keyof Runtime$>(name: T): Promise<void>;
42
+ declare function enabled(): boolean;
43
+ declare function url(): string;
44
+ declare const NAME: {
45
+ fetch: typeof fetch;
46
+ url: typeof url;
47
+ };
48
+ declare const database: {
49
+ get: typeof get;
50
+ post: typeof post;
51
+ enabled: typeof enabled;
52
+ };
53
+ type Result$<T, CT> = CT extends number ? (CT extends 0 ? T : T[]) : T;
54
+ interface Runtime$ {}
55
+
56
+ export { NAME, database };`,L=`global.NAME = {};
57
+ global.NAME.database = {};
58
+ global.NAME.url = () => "http://localhost:PORT/PREFIX/";
59
+ global.NAME.fetch = async function (name, count) {
60
+ const search = count ? "?count=" + count : "";
61
+
62
+ const response = await fetch(global.NAME.url() + name + search);
63
+
64
+ if (!response.ok) throw new Error("[fakelab] Failed to retreived mock data.");
65
+
66
+ const result = await response.json();
67
+
68
+ return result;
69
+ };
70
+ global.NAME.database.enabled = () => ENABLED_COND;
71
+ global.NAME.database.get = async function (name) {
72
+ if (!global.NAME.database.enabled()) throw new Error("[fakelab] Database is not enabled.");
73
+
74
+ const response = await fetch(global.NAME.url() + "database/" + name);
75
+
76
+ if (!response.ok) throw new Error("[fakelab] Failed to retreived data from database.");
77
+
78
+ const result = await response.json();
79
+
80
+ return result;
81
+ };
82
+ global.NAME.database.post = async function (name) {
83
+ if (!global.NAME.database.enabled()) throw new Error("[fakelab] Database is not enabled.");
84
+
85
+ const response = await fetch(global.NAME.url() + "database/" + name, { method: "POST" });
86
+
87
+ if (!response.ok) throw new Error("[fakelab] Failed to post data to database.");
88
+ };
89
+
90
+ const NAME = Object.freeze(fl);
91
+ const database = Object.freeze(db);
92
+
93
+ export { NAME, database };`,R=`export {};
15
94
 
16
95
  declare global {
17
- const fakelab: {
18
- fetch<T extends keyof FakeRuntime, Count extends number | undefined = undefined>(name: T, count?: Count): Promise<FakeResult<FakeRuntime[T], Count>>;
19
- readonly URL: string;
96
+ const database: {
97
+ enabled(): boolean;
98
+ get<T extends keyof Runtime$>(name: T): Promise<Runtime$[T]>;
99
+ post(name: keyof Runtime$): Promise<void>;
100
+ };
101
+ const NAME: {
102
+ fetch<T extends keyof Runtime$, CT extends number | undefined = undefined>(name: T, count?: CT): Promise<Result$<Runtime$[T], CT>>;
103
+ url(): string;
104
+ database: typeof database;
20
105
  };
21
- type FakeResult<T, Count> = Count extends number ? (Count extends 0 ? T : T[]) : T;
22
- interface FakeRuntime {}
106
+ type Result$<T, CT> = CT extends number ? (CT extends 0 ? T : T[]) : T;
107
+ interface Runtime$ {}
23
108
  interface Window {
24
- readonly fakelab: typeof fakelab;
109
+ readonly NAME: typeof NAME;
25
110
  }
26
111
 
27
112
  namespace NodeJS {
28
113
  interface Global {
29
- fakelab: typeof fakelab;
114
+ NAME: typeof NAME;
30
115
  }
31
116
  }
32
- }
33
- `}};var p=class{constructor(e){this.opts=e;this.files=this.files.bind(this),this.serverOpts=this.serverOpts.bind(this),this.fakerOpts=this.fakerOpts.bind(this);}async files(e){let t=this.resolveSourcePath(e||this.opts.sourcePath),r=Array.from(new Set((await Promise.all(t.map(n=>this.resolveTSFiles(n)))).flat()));return r.length===0&&(s.error(`No Typescript files found in:
34
- %s`,t.join(`
35
- `)),process.exit(1)),r}serverOpts(e,t){return {pathPrefix:e||this.opts.server?.pathPrefix||"api",port:t||this.opts.server?.port||5200}}fakerOpts(e){let t=(e||this.opts.faker?.locale)?.toLowerCase();return t&&f.includes(t)?{locale:t}:{locale:h()}}async generateInFileRuntimeConfig(e,t){let{port:r,pathPrefix:n}=this.serverOpts(t.pathPrefix,t.port),c=l.resolve(e,"runtime.js"),u=l.resolve(e,"runtime.d.ts");await Promise.all([m.writeFile(c,i.source(r,n)),m.writeFile(u,i.decl())]);}async tryStat(e){try{return await stat(e)}catch{return null}}async isReadable(e){try{return await access(e,constants.R_OK),!0}catch{return false}}resolveSourcePath(e){return (Array.isArray(e)?e:[e]).map(r=>l.resolve(r))}async resolveTSFiles(e){let t=l.resolve(e),r=t.endsWith(".ts")?t:t+".ts";if((await this.tryStat(r))?.isFile()){if(!await this.isReadable(r))throw new Error(`Cannot read file: ${r}`);return s.info("Source:",r),[r]}if((await this.tryStat(t))?.isDirectory())return s.info("Source:",t),k("**/*.ts",{cwd:t,absolute:true,ignore:["**/*.d.ts"]});s.error(`Invalid source path: ${e}`),process.exit(1);}};function b(o){return new p(o)}export{b as defineConfig};
117
+ }`;var w=class{constructor(e,t,r,o){this.port=e;this.prefix=t;this.browserOptions=r;this.dbOptions=o;this.name=this.browserOptions?.expose?.name||"fakelab",this.databaseEnabled=this.dbOptions?.enabled??true?"true":"false";}name;databaseEnabled;transformOptions={minify:true,platform:"browser",target:"es2022"};replacer(e,t){let r=e;for(let o in t)r=r.replace(new RegExp(o,"g"),t[o].toString().trim());return r}async prepareGlobalSource(){let e=this.replacer(L,{NAME:this.name,PORT:this.port,PREFIX:this.prefix,ENABLED_COND:this.databaseEnabled});try{let{code:t}=await transform(e,this.transformOptions);return t}catch(t){return t instanceof Error&&s.warn(t.message),e}}globalDeclaration(){return this.replacer(R,{NAME:this.name})}},b=class a extends w{constructor(t,r,o,c){super(t,r,o,c);this.port=t;this.prefix=r;this.browserOptions=o;this.dbOptions=c;}static init(t,r,o,c){let E=new a(t,r,o,c);return new Proxy(E,{get(n,f){return f==="prepareSource"?o?.expose?.mode==="global"?n.prepareGlobalSource:n.prepareSource:f==="declaration"?o?.expose?.mode==="global"?n.globalDeclaration:n.declaration:n[f]}})}async prepareSource(){let t=this.replacer(T,{NAME:this.name,PORT:this.port,PREFIX:this.prefix,ENABLED_COND:this.databaseEnabled});try{let{code:r}=await transform(t,this.transformOptions);return r}catch(r){return r instanceof Error&&s.warn(r.message),t}}declaration(){return this.replacer(A,{NAME:this.name})}};var m=class{constructor(e){this.opts=e;this.files=this.files.bind(this),this.serverOpts=this.serverOpts.bind(this),this.fakerOpts=this.fakerOpts.bind(this),this.browserOpts=this.browserOpts.bind(this),this.NETWORK_DEFAULT_OPTIONS=Object.freeze({delay:this.opts.network?.delay||0,errorRate:this.opts.network?.errorRate||0,timeoutRate:this.opts.network?.timeoutRate||0,offline:this.opts.network?.offline??false});}RUNTIME_SOURCE_FILENAME="runtime.js";RUNTIME_DECL_FILENAME="runtime.d.ts";FAKELAB_PERSIST_DIR=".fakelab";NETWORK_DEFAULT_OPTIONS;async files(e){let t=this.resolveSourcePath(e||this.opts.sourcePath),r=Array.from(new Set((await Promise.all(t.map(o=>this.resolveTSFiles(o)))).flat()));return r.length===0&&(s.error("No Typescript files found in: %s",s.list(t.map(o=>i.basename(o)))),process.exit(1)),r}serverOpts(e,t){return {pathPrefix:e||this.opts.server?.pathPrefix||"api",port:t||this.opts.server?.port||5200}}browserOpts(e,t){return {expose:{mode:t||this.opts.browser?.expose?.mode||y,name:e||this.opts.browser?.expose?.name||g}}}networkOpts(){let e=this.opts.network?.preset,t=this.opts.network?.presets??{};return !e||!t[e]?this.NETWORK_DEFAULT_OPTIONS:{...t[e],...this.opts.network??{}}}fakerOpts(e){let t=(e||this.opts.faker?.locale)?.toLowerCase();return t&&h.includes(t)?{locale:t}:{locale:O()}}async generateInFileRuntimeConfig(e,t){let{port:r,pathPrefix:o}=this.serverOpts(t.pathPrefix,t.port);await this.initializeDatabase();let c=i.resolve(e,this.RUNTIME_SOURCE_FILENAME),E=i.resolve(e,this.RUNTIME_DECL_FILENAME),n=b.init(r,o,this.opts.browser,this.opts.database),f=await n.prepareSource();await Promise.all([d.writeFile(c,f),d.writeFile(E,n.declaration())]);}getDatabaseDirectoryPath(){let e=this.opts.database?.dest||"db";return i.resolve(process.cwd(),e)}databaseEnabled(){return this.opts.database?.enabled??false}async initializeDatabase(){if(this.databaseEnabled())try{let e=this.opts.database?.dest||"db";await d.ensureDir(this.getDatabaseDirectoryPath()),await this.modifyGitignoreFile(e);}catch{s.error("Could not create database.");}else (!this.opts.database||!this.databaseEnabled())&&await d.rm(this.getDatabaseDirectoryPath(),{force:true,recursive:true});}async modifyGitignoreFile(e){try{let t=i.resolve(process.cwd(),".gitignore");if((await d.readFile(t,{encoding:"utf8"})).split(`
118
+ `).some(o=>o.trim()===e.trim()))return;await d.appendFile(t,`
119
+ ${e}`);}catch{s.error("Could not modify .gitignore file.");}}async tryStat(e){try{return await stat(e)}catch{return null}}async isReadable(e){try{return await access(e,constants.R_OK),!0}catch{return false}}resolveSourcePath(e){return (Array.isArray(e)?e:[e]).map(r=>F(r,{strict:true})?r:i.resolve(r))}async resolveTSFiles(e){if(F(e,{strict:true}))return s.info("source: %s",e),N(e,{absolute:true,ignore:["**/*.d.ts"]});let t=i.resolve(e),r=t.endsWith(".ts")?t:t+".ts";return (await this.tryStat(r))?.isFile()?(await this.isReadable(r)||(s.error("Cannot read file: %s",r),process.exit(1)),s.info("source: %s",r),[r]):(await this.tryStat(t))?.isDirectory()?(s.info("source: %s",t),N("**/*.ts",{cwd:t,absolute:true,ignore:["**/*.d.ts"]})):(s.warn("invalid source: [REDACTED]/%s",i.basename(r)),[])}};function v(a){return new m(a)}export{v as defineConfig};
@@ -88,6 +88,31 @@ pre {
88
88
  padding-block: 16px;
89
89
  }
90
90
 
91
+ .sidebar_content .database_section {
92
+ display: flex;
93
+ flex: 1;
94
+ max-height: fit-content;
95
+ padding-inline: 16px;
96
+ padding-bottom: 16px;
97
+ }
98
+ .database_section .database_btn {
99
+ display: flex;
100
+ gap: 8px;
101
+ align-items: center;
102
+ flex: 1;
103
+ padding: 12px;
104
+ background: linear-gradient(to right bottom, oklch(60% 0.118 184.704), oklch(60.9% 0.126 221.723));
105
+ color: #ffffff;
106
+ text-decoration: none;
107
+ font-size: 14px;
108
+ font-weight: 500;
109
+ font-family: inter;
110
+ border-radius: 999px;
111
+ &:hover {
112
+ background: linear-gradient(to right bottom, oklch(70.4% 0.14 182.503), oklch(71.5% 0.143 215.221));
113
+ }
114
+ }
115
+
91
116
  .sidebar_content .sidebar_content_leading {
92
117
  display: flex;
93
118
  gap: 8px;
@@ -311,6 +336,60 @@ pre {
311
336
  }
312
337
  }
313
338
 
339
+ .toolbar_setting .toolbar_db_action {
340
+ display: flex;
341
+ align-items: center;
342
+ justify-content: center;
343
+ border-radius: 4px;
344
+ border: none;
345
+ gap: 6px;
346
+ min-width: fit-content;
347
+ white-space: nowrap;
348
+ outline: none;
349
+ background: oklch(27.8% 0.033 256.848);
350
+ box-shadow: 0px 0px 2px hsl(220, 43%, 10%);
351
+ height: 32px;
352
+ padding-inline: 12px;
353
+ color: #fff;
354
+ font-size: 12px;
355
+ cursor: pointer;
356
+ transition: background 250ms ease-in-out;
357
+ &:hover {
358
+ background: hsl(216, 31%, 19%);
359
+ }
360
+ }
361
+
362
+ .toolbar_setting .toolbar_clear_action {
363
+ display: flex;
364
+ align-items: center;
365
+ justify-content: center;
366
+ border-radius: 4px;
367
+ gap: 6px;
368
+ border: none;
369
+ min-width: fit-content;
370
+ white-space: nowrap;
371
+ outline: none;
372
+ background: oklch(27.8% 0.033 256.848);
373
+ box-shadow: 0px 0px 2px hsl(220, 43%, 10%);
374
+ height: 32px;
375
+ padding-inline: 12px;
376
+ color: #fff;
377
+ font-size: 12px;
378
+ cursor: pointer;
379
+ transition: background 250ms ease-in-out;
380
+ &:hover {
381
+ background: hsl(216, 31%, 19%);
382
+ }
383
+ }
384
+
385
+ .toolbar_clear_action.disabled {
386
+ cursor: default;
387
+ opacity: 0.5;
388
+ &:hover {
389
+ background: oklch(27.8% 0.033 256.848);
390
+ }
391
+ }
392
+
314
393
  .toolbar_setting .toolbar_setting_overlay {
315
394
  display: none;
316
395
  position: absolute;
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-left-icon lucide-arrow-left"><path d="m12 19-7-7 7-7"/><path d="M19 12H5"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-database-icon lucide-database"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-eraser-icon lucide-eraser"><path d="M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21"/><path d="m5.082 11.09 8.828 8.828"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-between-horizontal-start-icon lucide-between-horizontal-start"><rect width="13" height="7" x="8" y="3" rx="1"/><path d="m2 9 3 3-3 3"/><rect width="13" height="7" x="8" y="14" rx="1"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-icon lucide-trash"><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
@@ -27,10 +27,11 @@ function downloadJsonCode(e) {
27
27
  });
28
28
  }
29
29
  function openSettings() {
30
- document.getElementById("setting_overlay").setAttribute("data-visible", "true");
30
+ document.getElementById("setting_overlay")?.setAttribute("data-visible", "true");
31
31
  }
32
32
  function handleCloseSetting(e) {
33
33
  var t = document.getElementById("setting_overlay");
34
+ if (!t) return;
34
35
  e.target && !t.contains(e.target) && "overlay_trigger" !== e.target.id && t.setAttribute("data-visible", "false");
35
36
  }
36
37
  function submitForm(e) {
@@ -0,0 +1,30 @@
1
+ <aside class="sidebar">
2
+ <a class="logo" href="/"><img src="/icons/logo.svg" width="20px" height="20px" /><span>Fakelab</span></a>
3
+ <div class="sidebar_content">
4
+ <div class="database_section">
5
+ <a href="/" class="database_btn">
6
+ <img src="/icons/arrow-left.svg" width="18px" height="18px" />
7
+ <span>Dashboard</span>
8
+ </a>
9
+ </div>
10
+ <div class="sidebar_content_leading">
11
+ <div class="sidebar_content_indicator_icon"></div>
12
+ <span class="sidebar_content_title">Registered tables</span>
13
+ </div>
14
+ <div class="sidebar_content_list">
15
+ <% entities.forEach((entity,entityName) => { %>
16
+ <a class="sidebar_content_list_item <%= entityName === name ? 'active' : '' %>" href="/database/<%= entityName %>">
17
+ <span class="item_name"><%= entityName %></span>
18
+ <span class="item_filepath"><%= entity.tablepath %></span>
19
+ </a>
20
+ <% }) %>
21
+ </div>
22
+ </div>
23
+ <a class="sidebar_docs" href="https://fakerjs.dev/" target="_blank" rel="noopener noreferrer">
24
+ <span>Fakerjs documents</span>
25
+ <img class="icon" src="/icons/link.svg" width="18px" height="18px" />
26
+ </a>
27
+ <div class="sidebar_footer">
28
+ <span>app version: <%= version %></span>
29
+ </div>
30
+ </aside>
@@ -0,0 +1,40 @@
1
+ <div class="preview_toolbar loading">
2
+ <div class="toolbar_setting">
3
+ <div class="data_fetch_address">
4
+ <div class="address">
5
+ <span class="address_method">GET</span>
6
+ <span id="request_address_url" class="address_url"><%= address %><%= prefix %>/database/<%= name %></span>
7
+ </div>
8
+ <img id="copy_btn" onclick="copyAddressUrl()" class="icon pointer_auto" src="/icons/copy.svg" width="16px" height="16px" />
9
+ </div>
10
+ <form action="/__update/<%= name %>" method="POST">
11
+ <button class="toolbar_db_action" type="submit">
12
+ <img src="/icons/insert.svg" width="16px" height="16px" />
13
+ Add a record
14
+ </button>
15
+ </form>
16
+ <% if (hasData) { %>
17
+ <form action="/__delete/<%= name %>" method="POST">
18
+ <button class="toolbar_clear_action" type="submit">
19
+ <img src="/icons/eraser.svg" width="16px" height="16px" />
20
+ Clear
21
+ </button>
22
+ </form>
23
+ <% } else { %>
24
+ <button class="toolbar_clear_action disabled" type="submit">
25
+ <img src="/icons/eraser.svg" width="16px" height="16px" />
26
+ Clear
27
+ </button>
28
+ <% } %>
29
+ </div>
30
+
31
+ <div class="toolbar_actions">
32
+ <div class="toolbar_action_item" onclick="copyJsonCode()">
33
+ <img class="icon" src="/icons/copy.svg" width="18px" height="18px" />
34
+ </div>
35
+ <div class="divider"></div>
36
+ <a class="toolbar_action_item" data-source-name="<%= name %>" onclick="downloadJsonCode(this)">
37
+ <img class="icon" src="/icons/download.svg" width="18px" height="18px" />
38
+ </a>
39
+ </div>
40
+ </div>
@@ -1,14 +1,22 @@
1
1
  <aside class="sidebar">
2
2
  <a class="logo" href="/"><img src="/icons/logo.svg" width="20px" height="20px" /><span>Fakelab</span></a>
3
3
  <div class="sidebar_content">
4
+ <% if (enabled) { %>
5
+ <div class="database_section">
6
+ <a href="/database" class="database_btn">
7
+ <img src="/icons/database.svg" width="18px" height="18px" />
8
+ <span>Database</span>
9
+ </a>
10
+ </div>
11
+ <% } %>
4
12
  <div class="sidebar_content_leading">
5
13
  <div class="sidebar_content_indicator_icon"></div>
6
14
  <span class="sidebar_content_title">Found interfaces</span>
7
15
  </div>
8
16
  <div class="sidebar_content_list">
9
- <% entities.forEach((entity,name) => { %>
10
- <a class="sidebar_content_list_item <%= currentPath === `/${name}` ? 'active' : '' %>" href="/<%= name %>">
11
- <span class="item_name"><%= name %></span>
17
+ <% entities.forEach((entity,entityName) => { %>
18
+ <a class="sidebar_content_list_item <%= entityName === name ? 'active' : '' %>" href="/entities/<%= entityName %>">
19
+ <span class="item_name"><%= entityName %></span>
12
20
  <span class="item_filepath"><%= entity.filepath %></span>
13
21
  </a>
14
22
  <% }) %>
@@ -0,0 +1,9 @@
1
+ <%- include("components/database/sidebar", { entities, version, name }) %> <% title = "Fakelab | Database" %>
2
+ <main class="main">
3
+ <header class="header"></header>
4
+ <div class="preview">
5
+ <div class="nodata">
6
+ <span>Select a table to load the data.</span>
7
+ </div>
8
+ </div>
9
+ </main>
@@ -1,9 +1,9 @@
1
- <%- include("components/sidebar", {currentPath, entities, version }) %> <% title = "Fakelab" %>
1
+ <%- include("components/sidebar", { entities, version, enabled, name }) %> <% title = "Fakelab" %>
2
2
  <main class="main">
3
3
  <header class="header"></header>
4
4
  <div class="preview">
5
5
  <div class="nodata">
6
- <span>Select a interface to load data.</span>
6
+ <span>Select a interface to load the data.</span>
7
7
  </div>
8
8
  </div>
9
9
  </main>
@@ -1,4 +1,4 @@
1
- <%- include("components/sidebar", {currentPath, entities, version }) %> <% title = name %>
1
+ <%- include("components/sidebar", {entities, name, version, enabled }) %> <% title = name %>
2
2
  <main class="main">
3
3
  <header class="header">
4
4
  <span class="interface_name"><%= name %></span>
@@ -0,0 +1,8 @@
1
+ <%- include("components/database/sidebar", { entities, name, version }) %> <% title = name %>
2
+ <main class="main">
3
+ <header class="header">
4
+ <span class="interface_name"><%= name %></span>
5
+ </header>
6
+ <div class="preview"><%- include("components/database/toolbar", { address, prefix, name, hasData }) %><%- include("components/code", { lang: "json", code: json }) %></div>
7
+ </main>
8
+ <script src="/js/fakelab.min.js"></script>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fakelab",
3
- "version": "0.0.16",
3
+ "version": "0.0.18",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "A easy-config mock server for frontend developers.",
@@ -12,7 +12,7 @@
12
12
  "types": "./lib/main.d.ts",
13
13
  "default": "./lib/main.js"
14
14
  },
15
- "./runtime": {
15
+ "./browser": {
16
16
  "types": "./lib/runtime.d.ts",
17
17
  "node": "./lib/runtime.js",
18
18
  "default": "./lib/runtime.js"
@@ -33,7 +33,7 @@
33
33
  "url": "https://github.com/alirezahematidev/fakelab/issues"
34
34
  },
35
35
  "scripts": {
36
- "build": "tsup",
36
+ "build": "tsc && tsup",
37
37
  "release": "release-it --ci",
38
38
  "dev": "node --import=tsx src/cli.ts serve",
39
39
  "serve": "yarn build && node lib/cli.js serve"
@@ -60,6 +60,7 @@
60
60
  "@types/express": "^5.0.6",
61
61
  "@types/express-ejs-layouts": "^2.5.4",
62
62
  "@types/fs-extra": "^11.0.4",
63
+ "@types/is-glob": "^4.0.4",
63
64
  "@types/node": "^24.10.1",
64
65
  "release-it": "^19.0.6",
65
66
  "tsup": "^8.5.1",
@@ -73,15 +74,19 @@
73
74
  "commander": "^14.0.2",
74
75
  "cors": "^2.8.5",
75
76
  "ejs": "^3.1.10",
77
+ "esbuild": "^0.27.2",
76
78
  "express": "^5.2.1",
77
79
  "express-ejs-layouts": "^2.5.1",
78
80
  "fast-glob": "^3.3.3",
79
81
  "figlet": "^1.9.4",
80
82
  "fs-extra": "^11.3.2",
83
+ "is-glob": "^4.0.3",
81
84
  "joycon": "^3.1.1",
85
+ "lowdb": "^7.0.1",
82
86
  "picocolors": "^1.1.1",
83
87
  "qs": "^6.14.0",
84
- "ts-morph": "^27.0.2"
88
+ "ts-morph": "^27.0.2",
89
+ "winston": "^3.19.0"
85
90
  },
86
91
  "bin": {
87
92
  "fakelab": "bin/run.js"