modelence 0.2.1 → 0.4.2
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 +12 -2
- package/dist/bin/modelence.js +5 -0
- package/dist/bin/modelence.js.map +1 -0
- package/dist/chunk-D5LNOX64.js +2 -0
- package/dist/chunk-D5LNOX64.js.map +1 -0
- package/dist/index-5e-76duG.d.ts +15 -0
- package/dist/index.d.ts +12 -1
- package/dist/index.js +1 -1
- package/dist/mongo.d.ts +5 -0
- package/dist/mongo.js +2 -0
- package/dist/mongo.js.map +1 -0
- package/dist/server.d.ts +237 -15
- package/dist/server.js +3 -3
- package/dist/server.js.map +1 -1
- package/package.json +13 -9
- package/dist/cli/setup.js +0 -5
- package/dist/cli/setup.js.map +0 -1
- package/dist/cli.d.ts +0 -1
package/README.md
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
|
+
<a href="https://modelence.com">
|
|
3
|
+
<picture>
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="assets/modelence.png">
|
|
5
|
+
<img alt="Modelence logo" src="assets/modelence.png" height="128">
|
|
6
|
+
</picture>
|
|
7
|
+
</a>
|
|
8
|
+
<h1>Modelence</h1>
|
|
2
9
|
|
|
3
10
|

|
|
11
|
+
<a href="https://www.npmjs.com/package/modelence"><img alt="NPM version" src="https://img.shields.io/npm/v/modelence.svg"></a>
|
|
12
|
+
|
|
13
|
+
</div>
|
|
4
14
|
|
|
5
15
|
Full-stack JavaScript framework for interactive web applications
|
|
6
16
|
|
|
@@ -44,7 +54,7 @@ npm install --save-dev tailwindcss postcss autoprefixer
|
|
|
44
54
|
```json
|
|
45
55
|
{
|
|
46
56
|
"compilerOptions": {
|
|
47
|
-
"outDir": "./.modelence/",
|
|
57
|
+
"outDir": "./.modelence/build/",
|
|
48
58
|
"baseUrl": ".",
|
|
49
59
|
"paths": {
|
|
50
60
|
"@/*": ["./src/*"]
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import G,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import T from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import re from'archiver';import Q from'open';var h=".modelence.env";async function I(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function L(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${h} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function F(e){return String(e).replace(/"/g,'\\"')}async function _(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function N(e){try{let o=join(process.cwd(),h),t={};try{let c=await promises.readFile(o,"utf8");t=parse(c),await _(o),await L()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await I(e.token,e.host),i={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_DEPLOYMENT_ID:r.deploymentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},s=Object.entries(i).map(([c,n])=>`${c}="${F(n)}"`).join(`
|
|
3
|
+
`);await promises.writeFile(o,s.trim()+`
|
|
4
|
+
`),console.log(`Successfully configured ${h} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var y=null,v=null;function z(){if(!y)throw new Error("Environment variables not loaded");return y}function k(){if(!v)throw new Error("Configuration not loaded");return v}function d(e){let o=z().MODELENCE_SERVICE_ENDPOINT;if(!o)throw new Error("MODELENCE_SERVICE_ENDPOINT not found in environment variables");return `${o}${e}`}function g(){let{serverDir:e,serverEntry:o}=k();return join(e,o)}function x(){return k().postBuildCommand}function D(e){let o=C("build");return o}function u(e){return join(process.cwd(),e)}function C(e){let o=u(".modelence");return e?join(o,e):o}async function S(){try{let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");v=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await T.readFile(join(process.cwd(),".modelence.env"),"utf-8");y=parse(e);}catch(e){if(e.code!=="ENOENT")throw e}}async function K(){let e=x();if(e){console.log("Running post-build command..."),execSync(e);return}await X();}async function X(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:G.resolve(process.cwd(),".modelence/build/client"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function H(){return console.log("Building server with tsup..."),new Promise((e,o)=>{build({entry:[g()],format:"esm",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,skipNodeModulesBundle:false,outExtension:({format:t})=>({js:".mjs"}),onSuccess:async()=>{e(undefined);}});})}async function w(){console.log("Building Modelence project...");try{let e=D();await T.rm(e,{recursive:!0,force:!0}),await H(),await K(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await T.access(C());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function O(){let e=await fetch(d("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:t}=await e.json();console.log(`Please visit ${t} to authenticate`),console.log(`Code: ${o}`),await Q(t);let r=await oe(o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:r})),{token:r}}async function oe(e){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await te(e);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function te(e){let o=await fetch(d(`/api/cli/token?code=${e}`),{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:t}=await o.json();return t}async function B(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip");await w(),await ie(r);let{token:i}=await O(),{bundleName:s}=await se(e.env,r,i);await promises.unlink(r),await ce(e.env,s,join(".modelence","build","app.mjs"),i);}async function ie(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=re("zip",{zlib:{level:9}});t.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),t.on("error",n=>{throw n});let r=new Promise((n,b)=>{o.on("close",n),o.on("error",b),t.on("error",b);});t.pipe(o);let i=["package.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server",join(".modelence","build"),".next"];for(let n of i)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.file(u(n),{name:n});for(let n of s)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.directory(u(n),n);await t.finalize(),await r;let c=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(c.size/1024/1024).toFixed(2)} MB)`);}async function se(e,o,t){let r=await fetch(d(`/api/deployments/${e}/upload`),{method:"POST",headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw console.error(await r.text()),new Error(`Failed to create upload URL: ${r.statusText}`);let{uploadUrl:i,bundleName:s}=await r.json(),c=await promises.readFile(o),n=await fetch(i,{method:"PUT",body:c,headers:{"Content-Type":"application/zip"}});if(!n.ok)throw new Error(`Failed to upload bundle: ${n.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${s}`),{bundleName:s}}async function ce(e,o,t,r){let i=await fetch(d(`/api/deployments/${e}/deploy`),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({bundleName:o,entryPoint:t})});if(!i.ok)throw new Error(`Failed to trigger deployment: ${i.statusText}`);let{deploymentUrl:s}=await i.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${s}`);}function j(){build({entry:[g()],format:"esm",outDir:".modelence/dev",clean:true,watch:true,bundle:true,minify:false,sourcemap:true,treeshake:false,skipNodeModulesBundle:true,outExtension:({format:e})=>({js:".mjs"}),onSuccess:async()=>{try{execSync("node .modelence/dev/app.mjs",{stdio:"inherit",env:{...process.env,NODE_ENV:"development"}});}catch(e){console.error("Server crashed:",e);}}});}var m=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");m.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await N(e);});m.command("build").description("Build the application").action(async()=>{await w();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-e, --env <env>","Environment (deployment alias)").action(async e=>{await B(e);});m.command("dev").description("Start development server").action(async()=>{j();});S().then(()=>{m.parse(process.argv);});//# sourceMappingURL=modelence.js.map
|
|
5
|
+
//# sourceMappingURL=modelence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../bin/setup.ts","../../bin/config.ts","../../bin/build.ts","../../bin/auth.ts","../../bin/deploy.ts","../../bin/dev.ts","../../bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","studioBaseUrl","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","reject","tsupBuild","format","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","bundleFiles","bundleDirs","file","dir","stats","deploymentAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","program","Command"],"mappings":";wbAKA,IAAMA,CAAqB,CAAA,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAoBC,CAAAA,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAGD,EAAAA,CAAI,CAAc,UAAA,CAAA,CAAA,CAChD,MAAQ,CAAA,KAAA,CACR,OAAS,CAAA,CACP,yBAA2BD,CAAAA,CAC7B,CACF,CAAC,CAED,CAAA,GAAI,CAACE,CAAAA,CAAS,EAAI,CAAA,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAK,EAAA,CACtC,MAAM,IAAI,KAAMC,CAAAA,CAAAA,EAAa,CAA8BD,2BAAAA,EAAAA,CAAAA,CAAS,MAAM,CAAE,CAAA,CAC9E,CAEA,OAAOA,CAAS,CAAA,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAKC,CAAAA,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAQ,CAAA,KAAA,CACf,MAAQ,CAAA,OAAA,CAAQ,MAClB,CAAC,CAED,CAAA,OAAO,IAAI,OAAA,CAASC,CAAY,EAAA,CAC9BF,CAAG,CAAA,QAAA,CAAS,CAAYP,SAAAA,EAAAA,CAAkB,uDAAyDU,CAAW,EAAA,CAC5G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AAQ,CAAA,GAAA,CACX,QAAU,CAAA,aACZ,CACF,CAAC,EACH,CAASlC,MAAAA,CAAAA,CAAO,CAEd,OAAQ,CAAA,KAAA,CAAM,kBAAmBA,CAAK,EACxC,CACF,CACF,CAAC,EACH,CC1BA,IAAMgF,CAAU,CAAA,IAAIC,OAAQ,EAAA,CACzB,KAAK,WAAW,CAAA,CAChB,WAAY,CAAA,oBAAoB,EAChC,OAAQ,CAAA,OAAO,EAElBD,CACG,CAAA,OAAA,CAAQ,OAAO,CACf,CAAA,WAAA,CAAY,uCAAuC,CAAA,CACnD,eAAe,qBAAuB,CAAA,uBAAuB,CAC7D,CAAA,MAAA,CAAO,oBAAqB,gBAAkB,CAAA,6BAA6B,CAC3E,CAAA,MAAA,CAAO,MAAO9E,CAAY,EAAA,CACzB,MAAMD,CAAAA,CAAMC,CAAO,EACrB,CAAC,CAEH8E,CAAAA,CAAAA,CACG,QAAQ,OAAO,CAAA,CACf,WAAY,CAAA,uBAAuB,EACnC,MAAO,CAAA,SAAY,CAClB,MAAMnC,IACR,CAAC,EAEHmC,CACG,CAAA,OAAA,CAAQ,QAAQ,CAChB,CAAA,WAAA,CAAY,2BAA2B,CAAA,CACvC,eAAe,iBAAmB,CAAA,gCAAgC,CAClE,CAAA,MAAA,CAAO,MAAO9E,CAAY,EAAA,CACzB,MAAMqD,CAAAA,CAAOrD,CAAO,EACtB,CAAC,EAEH8E,CACG,CAAA,OAAA,CAAQ,KAAK,CACb,CAAA,WAAA,CAAY,0BAA0B,CAAA,CACtC,OAAO,SAAY,CAClBD,CAAI,GACN,CAAC,CAEHrD,CAAAA,CAAAA,EAAU,CAAA,IAAA,CAAK,IAAM,CACnBsD,CAAAA,CAAQ,MAAM,OAAQ,CAAA,IAAI,EAC5B,CAAC,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n deploymentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise((resolve) => {\n rl.question(`Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n });\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string, host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch (error) {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_DEPLOYMENT_ID: config.deploymentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport { ModelenceConfig } from '../packages/types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT;\n if (!studioBaseUrl) {\n throw new Error('MODELENCE_SERVICE_ENDPOINT not found in environment variables');\n }\n\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n return join(serverDir, serverEntry);\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n return subPath ? join(buildDir, subPath) : buildDir;\n}\n\nexport function getProjectPath(subPath: string) {\n return join(process.cwd(), subPath);\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n return subPath ? join(modelenceDir, subPath) : modelenceDir;\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n \n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { env: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli();\n\n const { bundleName } = await uploadBundle(options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.env, bundleName, join('.modelence', 'build', 'app.mjs'), token);\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 } // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = [\n 'public',\n 'server',\n join('.modelence', 'build'),\n '.next',\n ];\n\n for (const file of bundleFiles) {\n if (await fs.access(getProjectPath(file)).then(() => true).catch(() => false)) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (await fs.access(getProjectPath(dir)).then(() => true).catch(() => false)) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(`Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);\n}\n\nasync function uploadBundle(deploymentAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/deployments/${deploymentAlias}/upload`), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`\n }\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: fileBuffer,\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(deploymentAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/deployments/${deploymentAlias}/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { execSync } from 'child_process';\nimport { getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\n\nexport function dev() {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n outDir: '.modelence/dev',\n clean: true,\n watch: true,\n bundle: true,\n minify: false,\n sourcemap: true,\n treeshake: false,\n skipNodeModulesBundle: true,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => {\n // Restart the server on successful builds\n try {\n execSync('node .modelence/dev/app.mjs', {\n stdio: 'inherit',\n env: {\n ...process.env,\n NODE_ENV: 'development' \n }\n });\n } catch (error) {\n // Server crashed, waiting for next rebuild\n console.error('Server crashed:', error);\n }\n }\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { loadEnv } from './config';\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version('0.2.1');\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-e, --env <env>', 'Environment (deployment alias)')\n .action(async (options) => {\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n dev();\n });\n\nloadEnv().then(() => {\n program.parse(process.argv);\n});\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var t=class extends Error{constructor(s){super(s),this.name="AuthError",this.status=401;}},r=class extends Error{constructor(s){super(s),this.name="ValidationError",this.status=400;}};export{t as a,r as b};//# sourceMappingURL=chunk-D5LNOX64.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-D5LNOX64.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../error.ts"],"names":["AuthError","message","ValidationError"],"mappings":"AAAO,IAAMA,CAAN,CAAA,cAAwB,KAAM,CAGnC,YAAYC,CAAiB,CAAA,CAC3B,KAAMA,CAAAA,CAAO,EACb,IAAK,CAAA,IAAA,CAAO,WACZ,CAAA,IAAA,CAAK,OAAS,IAChB,CACF,CAEaC,CAAAA,CAAAA,CAAN,cAA8B,KAAM,CAGzC,WAAA,CAAYD,EAAiB,CAC3B,KAAA,CAAMA,CAAO,CAAA,CACb,KAAK,IAAO,CAAA,iBAAA,CACZ,IAAK,CAAA,MAAA,CAAS,IAChB,CACF","file":"chunk-D5LNOX64.js","sourcesContent":["export class AuthError extends Error {\n status: number;\n\n constructor(message: string) {\n super(message);\n this.name = 'AuthError';\n this.status = 401;\n }\n}\n\nexport class ValidationError extends Error {\n status: number;\n\n constructor(message: string) {\n super(message);\n this.name = 'ValidationError';\n this.status = 400;\n }\n}\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Request, Response, NextFunction } from 'express';
|
|
2
|
+
|
|
3
|
+
type ExpressMiddleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
|
|
4
|
+
interface ModelenceConfig {
|
|
5
|
+
serverDir: string;
|
|
6
|
+
serverEntry: string;
|
|
7
|
+
postBuildCommand?: string;
|
|
8
|
+
}
|
|
9
|
+
interface AppServer {
|
|
10
|
+
init: () => Promise<void>;
|
|
11
|
+
handler: (req: Request, res: Response) => void;
|
|
12
|
+
middlewares?: () => ExpressMiddleware[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type { AppServer as A, ModelenceConfig as M };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { C as ConfigSchema } from './types-RXrmChkk.js';
|
|
2
|
+
export { M as ModelenceConfig } from './index-5e-76duG.js';
|
|
3
|
+
import 'express';
|
|
2
4
|
|
|
3
5
|
declare const time: {
|
|
4
6
|
seconds: (x: number) => number;
|
|
@@ -8,4 +10,13 @@ declare const time: {
|
|
|
8
10
|
weeks: (x: number) => number;
|
|
9
11
|
};
|
|
10
12
|
|
|
11
|
-
|
|
13
|
+
declare class AuthError extends Error {
|
|
14
|
+
status: number;
|
|
15
|
+
constructor(message: string);
|
|
16
|
+
}
|
|
17
|
+
declare class ValidationError extends Error {
|
|
18
|
+
status: number;
|
|
19
|
+
constructor(message: string);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export { AuthError, ValidationError, time };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as time}from'./chunk-GDI7FXAT.js';//# sourceMappingURL=index.js.map
|
|
1
|
+
export{a as AuthError,b as ValidationError}from'./chunk-D5LNOX64.js';export{a as time}from'./chunk-GDI7FXAT.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/mongo.d.ts
ADDED
package/dist/mongo.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../mongo.ts"],"names":["mongo_default"],"mappings":"4CAEA,IAAOA,EAAQ","file":"mongo.js","sourcesContent":["export { ClientSession, ObjectId } from 'mongodb';\n\nexport default {};\n"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { C as ConfigSchema, a as ConfigKey } from './types-RXrmChkk.js';
|
|
2
|
-
import { ObjectId, WithId, IndexDescription, MongoClient, Collection, Filter, FindOptions, Document, OptionalUnlessRequiredId, InsertOneResult, InsertManyResult, UpdateFilter, UpdateResult, DeleteResult, AggregateOptions, AggregationCursor, AnyBulkWriteOperation, BulkWriteResult } from 'mongodb';
|
|
2
|
+
import { ObjectId as ObjectId$1, WithId, IndexDescription, MongoClient, Collection, Filter, FindOptions, Document, OptionalUnlessRequiredId, InsertOneResult, InsertManyResult, UpdateFilter, UpdateResult, ClientSession, DeleteResult, AggregateOptions, AggregationCursor, AnyBulkWriteOperation, BulkWriteResult, Db } from 'mongodb';
|
|
3
3
|
export { ObjectId } from 'mongodb';
|
|
4
4
|
import * as zod from 'zod';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
+
import { Request } from 'express';
|
|
7
|
+
import { A as AppServer } from './index-5e-76duG.js';
|
|
6
8
|
|
|
7
9
|
type CronJobHandler = () => Promise<void>;
|
|
8
10
|
type CronJobInputParams = {
|
|
@@ -44,9 +46,9 @@ declare const schema: {
|
|
|
44
46
|
<U extends string, T extends Readonly<[U, ...U[]]>>(values: T, params?: z.RawCreateParams): z.ZodEnum<z.Writeable<T>>;
|
|
45
47
|
<U extends string, T extends [U, ...U[]]>(values: T, params?: z.RawCreateParams): z.ZodEnum<T>;
|
|
46
48
|
};
|
|
47
|
-
readonly objectId: () => z.ZodType<ObjectId>;
|
|
48
|
-
readonly userId: () => z.ZodType<ObjectId>;
|
|
49
|
-
readonly ref: (collection: string | Store<any, any>) => z.ZodType<ObjectId>;
|
|
49
|
+
readonly objectId: () => z.ZodType<ObjectId$1>;
|
|
50
|
+
readonly userId: () => z.ZodType<ObjectId$1>;
|
|
51
|
+
readonly ref: (collection: string | Store<any, any>) => z.ZodType<ObjectId$1>;
|
|
50
52
|
readonly union: <T extends readonly [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]>(types: T, params?: z.RawCreateParams) => z.ZodUnion<T>;
|
|
51
53
|
readonly infer: <T extends SchemaTypeDefinition>(schema: T) => InferDocumentType<T>;
|
|
52
54
|
};
|
|
@@ -78,19 +80,20 @@ declare namespace schema {
|
|
|
78
80
|
* });
|
|
79
81
|
* ```
|
|
80
82
|
*/
|
|
81
|
-
declare class Store<TSchema extends ModelSchema, TMethods extends Record<string, (this: InferDocumentType<TSchema
|
|
83
|
+
declare class Store<TSchema extends ModelSchema, TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>> {
|
|
82
84
|
/** @internal */
|
|
83
85
|
readonly _type: InferDocumentType<TSchema>;
|
|
84
86
|
/** @internal */
|
|
85
87
|
readonly _rawDoc: WithId<this['_type']>;
|
|
86
88
|
/** @internal */
|
|
87
|
-
readonly _doc:
|
|
89
|
+
readonly _doc: this['_rawDoc'] & TMethods;
|
|
88
90
|
readonly Doc: this['_doc'];
|
|
89
|
-
private
|
|
91
|
+
private name;
|
|
90
92
|
private readonly schema;
|
|
91
93
|
private readonly methods?;
|
|
92
94
|
private readonly indexes;
|
|
93
95
|
private collection?;
|
|
96
|
+
private client?;
|
|
94
97
|
/**
|
|
95
98
|
* Creates a new Store instance
|
|
96
99
|
*
|
|
@@ -109,10 +112,14 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
|
|
|
109
112
|
/** @internal */
|
|
110
113
|
getSchema(): TSchema;
|
|
111
114
|
/** @internal */
|
|
112
|
-
|
|
115
|
+
init(client: MongoClient): void;
|
|
116
|
+
/** @internal */
|
|
117
|
+
createIndexes(): Promise<void>;
|
|
113
118
|
private wrapDocument;
|
|
114
119
|
/** @internal */
|
|
115
120
|
requireCollection(): Collection<this["_type"]>;
|
|
121
|
+
/** @internal */
|
|
122
|
+
requireClient(): MongoClient;
|
|
116
123
|
findOne(query: Filter<this['_type']>, options?: FindOptions): Promise<this["_doc"] | null>;
|
|
117
124
|
requireOne(query: Filter<this['_type']>, options?: FindOptions, errorHandler?: () => Error): Promise<this['_doc']>;
|
|
118
125
|
private find;
|
|
@@ -122,7 +129,7 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
|
|
|
122
129
|
* @param id - The ID of the document to find
|
|
123
130
|
* @returns The document, or null if not found
|
|
124
131
|
*/
|
|
125
|
-
findById(id: string | ObjectId): Promise<this['_doc'] | null>;
|
|
132
|
+
findById(id: string | ObjectId$1): Promise<this['_doc'] | null>;
|
|
126
133
|
/**
|
|
127
134
|
* Fetches a single document by its ID, or throws an error if not found
|
|
128
135
|
*
|
|
@@ -130,7 +137,7 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
|
|
|
130
137
|
* @param errorHandler - Optional error handler to return a custom error if the document is not found
|
|
131
138
|
* @returns The document
|
|
132
139
|
*/
|
|
133
|
-
requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']>;
|
|
140
|
+
requireById(id: string | ObjectId$1, errorHandler?: () => Error): Promise<this['_doc']>;
|
|
134
141
|
/**
|
|
135
142
|
* Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.
|
|
136
143
|
*
|
|
@@ -140,6 +147,8 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
|
|
|
140
147
|
*/
|
|
141
148
|
fetch(query: Filter<this['_type']>, options?: {
|
|
142
149
|
sort?: Document;
|
|
150
|
+
limit?: number;
|
|
151
|
+
skip?: number;
|
|
143
152
|
}): Promise<this['_doc'][]>;
|
|
144
153
|
/**
|
|
145
154
|
* Inserts a single document
|
|
@@ -178,7 +187,9 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
|
|
|
178
187
|
* @param update - The MongoDB modifier to apply to the documents
|
|
179
188
|
* @returns The result of the update operation
|
|
180
189
|
*/
|
|
181
|
-
updateMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']
|
|
190
|
+
updateMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>, options?: {
|
|
191
|
+
session?: ClientSession;
|
|
192
|
+
}): Promise<UpdateResult>;
|
|
182
193
|
/**
|
|
183
194
|
* Updates multiple documents, or inserts them if they don't exist
|
|
184
195
|
*
|
|
@@ -216,6 +227,26 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
|
|
|
216
227
|
* @returns The result of the bulk write operation
|
|
217
228
|
*/
|
|
218
229
|
bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult>;
|
|
230
|
+
/**
|
|
231
|
+
* Returns the raw MongoDB database instance for advanced operations
|
|
232
|
+
* @returns The MongoDB database instance
|
|
233
|
+
* @throws Error if the store is not provisioned
|
|
234
|
+
*/
|
|
235
|
+
getDatabase(): Db;
|
|
236
|
+
/**
|
|
237
|
+
* Returns the raw MongoDB collection instance for advanced operations
|
|
238
|
+
* @returns The MongoDB collection instance
|
|
239
|
+
* @throws Error if the store is not provisioned
|
|
240
|
+
*/
|
|
241
|
+
rawCollection(): Collection<this["_type"]>;
|
|
242
|
+
/**
|
|
243
|
+
* Renames an existing collection to this store's name, used for migrations
|
|
244
|
+
* @param oldName - The previous name of the collection
|
|
245
|
+
* @throws Error if the old collection doesn't exist or if this store's collection already exists
|
|
246
|
+
*/
|
|
247
|
+
renameFrom(oldName: string, options?: {
|
|
248
|
+
session?: ClientSession;
|
|
249
|
+
}): Promise<void>;
|
|
219
250
|
}
|
|
220
251
|
|
|
221
252
|
type UserInfo = {
|
|
@@ -225,7 +256,7 @@ type UserInfo = {
|
|
|
225
256
|
type Session = {
|
|
226
257
|
authToken: string;
|
|
227
258
|
expiresAt: Date;
|
|
228
|
-
userId: ObjectId | null;
|
|
259
|
+
userId: ObjectId$1 | null;
|
|
229
260
|
};
|
|
230
261
|
type Permission = string;
|
|
231
262
|
type RoleDefinition = {
|
|
@@ -268,6 +299,7 @@ type RouteParams = {
|
|
|
268
299
|
params: Record<string, string>;
|
|
269
300
|
headers: Record<string, string>;
|
|
270
301
|
cookies: Record<string, string>;
|
|
302
|
+
req: Request;
|
|
271
303
|
};
|
|
272
304
|
type RouteResponse<T = any> = {
|
|
273
305
|
data: T;
|
|
@@ -305,14 +337,159 @@ declare class Module {
|
|
|
305
337
|
});
|
|
306
338
|
}
|
|
307
339
|
|
|
308
|
-
|
|
340
|
+
type MigrationScript = {
|
|
341
|
+
version: number;
|
|
342
|
+
description: string;
|
|
343
|
+
handler: () => Promise<void>;
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
type AppOptions = {
|
|
309
347
|
modules?: Module[];
|
|
348
|
+
server?: AppServer;
|
|
310
349
|
roles?: Record<string, RoleDefinition>;
|
|
311
350
|
defaultRoles?: Record<string, string>;
|
|
312
|
-
|
|
351
|
+
migrations?: Array<MigrationScript>;
|
|
352
|
+
};
|
|
353
|
+
declare function startApp({ modules, roles, defaultRoles, server, migrations }: AppOptions): Promise<void>;
|
|
313
354
|
|
|
314
355
|
declare function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>): void;
|
|
315
356
|
|
|
357
|
+
/** @public */
|
|
358
|
+
declare abstract class BSONValue {
|
|
359
|
+
/** @public */
|
|
360
|
+
abstract get _bsontype(): string;
|
|
361
|
+
/* Excluded from this release type: [BSON_VERSION_SYMBOL] */
|
|
362
|
+
/**
|
|
363
|
+
* @public
|
|
364
|
+
* Prints a human-readable string of BSON value information
|
|
365
|
+
* If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
|
|
366
|
+
*/
|
|
367
|
+
abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
|
|
368
|
+
/* Excluded from this release type: toExtendedJSON */
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
declare type InspectFn = (x: unknown, options?: unknown) => string;
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* A class representation of the BSON ObjectId type.
|
|
375
|
+
* @public
|
|
376
|
+
* @category BSONType
|
|
377
|
+
*/
|
|
378
|
+
declare class ObjectId extends BSONValue {
|
|
379
|
+
get _bsontype(): 'ObjectId';
|
|
380
|
+
/* Excluded from this release type: index */
|
|
381
|
+
static cacheHexString: boolean;
|
|
382
|
+
/* Excluded from this release type: buffer */
|
|
383
|
+
/**
|
|
384
|
+
* Create ObjectId from a number.
|
|
385
|
+
*
|
|
386
|
+
* @param inputId - A number.
|
|
387
|
+
* @deprecated Instead, use `static createFromTime()` to set a numeric value for the new ObjectId.
|
|
388
|
+
*/
|
|
389
|
+
constructor(inputId: number);
|
|
390
|
+
/**
|
|
391
|
+
* Create ObjectId from a 24 character hex string.
|
|
392
|
+
*
|
|
393
|
+
* @param inputId - A 24 character hex string.
|
|
394
|
+
*/
|
|
395
|
+
constructor(inputId: string);
|
|
396
|
+
/**
|
|
397
|
+
* Create ObjectId from the BSON ObjectId type.
|
|
398
|
+
*
|
|
399
|
+
* @param inputId - The BSON ObjectId type.
|
|
400
|
+
*/
|
|
401
|
+
constructor(inputId: ObjectId);
|
|
402
|
+
/**
|
|
403
|
+
* Create ObjectId from the object type that has the toHexString method.
|
|
404
|
+
*
|
|
405
|
+
* @param inputId - The ObjectIdLike type.
|
|
406
|
+
*/
|
|
407
|
+
constructor(inputId: ObjectIdLike);
|
|
408
|
+
/**
|
|
409
|
+
* Create ObjectId from a 12 byte binary Buffer.
|
|
410
|
+
*
|
|
411
|
+
* @param inputId - A 12 byte binary Buffer.
|
|
412
|
+
*/
|
|
413
|
+
constructor(inputId: Uint8Array);
|
|
414
|
+
/** To generate a new ObjectId, use ObjectId() with no argument. */
|
|
415
|
+
constructor();
|
|
416
|
+
/**
|
|
417
|
+
* Implementation overload.
|
|
418
|
+
*
|
|
419
|
+
* @param inputId - All input types that are used in the constructor implementation.
|
|
420
|
+
*/
|
|
421
|
+
constructor(inputId?: string | number | ObjectId | ObjectIdLike | Uint8Array);
|
|
422
|
+
/**
|
|
423
|
+
* The ObjectId bytes
|
|
424
|
+
* @readonly
|
|
425
|
+
*/
|
|
426
|
+
get id(): Uint8Array;
|
|
427
|
+
set id(value: Uint8Array);
|
|
428
|
+
/* Excluded from this release type: validateHexString */
|
|
429
|
+
/** Returns the ObjectId id as a 24 lowercase character hex string representation */
|
|
430
|
+
toHexString(): string;
|
|
431
|
+
/* Excluded from this release type: getInc */
|
|
432
|
+
/**
|
|
433
|
+
* Generate a 12 byte id buffer used in ObjectId's
|
|
434
|
+
*
|
|
435
|
+
* @param time - pass in a second based timestamp.
|
|
436
|
+
*/
|
|
437
|
+
static generate(time?: number): Uint8Array;
|
|
438
|
+
/**
|
|
439
|
+
* Converts the id into a 24 character hex string for printing, unless encoding is provided.
|
|
440
|
+
* @param encoding - hex or base64
|
|
441
|
+
*/
|
|
442
|
+
toString(encoding?: 'hex' | 'base64'): string;
|
|
443
|
+
/** Converts to its JSON the 24 character hex string representation. */
|
|
444
|
+
toJSON(): string;
|
|
445
|
+
/* Excluded from this release type: is */
|
|
446
|
+
/**
|
|
447
|
+
* Compares the equality of this ObjectId with `otherID`.
|
|
448
|
+
*
|
|
449
|
+
* @param otherId - ObjectId instance to compare against.
|
|
450
|
+
*/
|
|
451
|
+
equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean;
|
|
452
|
+
/** Returns the generation date (accurate up to the second) that this ID was generated. */
|
|
453
|
+
getTimestamp(): Date;
|
|
454
|
+
/* Excluded from this release type: createPk */
|
|
455
|
+
/* Excluded from this release type: serializeInto */
|
|
456
|
+
/**
|
|
457
|
+
* Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
|
|
458
|
+
*
|
|
459
|
+
* @param time - an integer number representing a number of seconds.
|
|
460
|
+
*/
|
|
461
|
+
static createFromTime(time: number): ObjectId;
|
|
462
|
+
/**
|
|
463
|
+
* Creates an ObjectId from a hex string representation of an ObjectId.
|
|
464
|
+
*
|
|
465
|
+
* @param hexString - create a ObjectId from a passed in 24 character hexstring.
|
|
466
|
+
*/
|
|
467
|
+
static createFromHexString(hexString: string): ObjectId;
|
|
468
|
+
/** Creates an ObjectId instance from a base64 string */
|
|
469
|
+
static createFromBase64(base64: string): ObjectId;
|
|
470
|
+
/**
|
|
471
|
+
* Checks if a value can be used to create a valid bson ObjectId
|
|
472
|
+
* @param id - any JS value
|
|
473
|
+
*/
|
|
474
|
+
static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean;
|
|
475
|
+
/* Excluded from this release type: toExtendedJSON */
|
|
476
|
+
/* Excluded from this release type: fromExtendedJSON */
|
|
477
|
+
/* Excluded from this release type: isCached */
|
|
478
|
+
/**
|
|
479
|
+
* Converts to a string representation of this Id.
|
|
480
|
+
*
|
|
481
|
+
* @returns return the 24 character hex string representation.
|
|
482
|
+
*/
|
|
483
|
+
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** @public */
|
|
487
|
+
declare interface ObjectIdLike {
|
|
488
|
+
id: string | Uint8Array;
|
|
489
|
+
__id?: string;
|
|
490
|
+
toHexString(): string;
|
|
491
|
+
}
|
|
492
|
+
|
|
316
493
|
declare const usersCollection: Store<{
|
|
317
494
|
handle: zod.ZodString;
|
|
318
495
|
emails: zod.ZodOptional<zod.ZodArray<zod.ZodObject<{
|
|
@@ -356,7 +533,52 @@ declare const usersCollection: Store<{
|
|
|
356
533
|
id: string;
|
|
357
534
|
} | undefined;
|
|
358
535
|
}>;
|
|
359
|
-
}, {
|
|
536
|
+
}, Record<string, (this: Pick<InferDocumentType<{
|
|
537
|
+
handle: zod.ZodString;
|
|
538
|
+
emails: zod.ZodOptional<zod.ZodArray<zod.ZodObject<{
|
|
539
|
+
address: zod.ZodString;
|
|
540
|
+
verified: zod.ZodBoolean;
|
|
541
|
+
}, "strip", zod.ZodTypeAny, {
|
|
542
|
+
address: string;
|
|
543
|
+
verified: boolean;
|
|
544
|
+
}, {
|
|
545
|
+
address: string;
|
|
546
|
+
verified: boolean;
|
|
547
|
+
}>, "many">>;
|
|
548
|
+
createdAt: zod.ZodDate;
|
|
549
|
+
authMethods: zod.ZodObject<{
|
|
550
|
+
password: zod.ZodOptional<zod.ZodObject<{
|
|
551
|
+
hash: zod.ZodString;
|
|
552
|
+
}, "strip", zod.ZodTypeAny, {
|
|
553
|
+
hash: string;
|
|
554
|
+
}, {
|
|
555
|
+
hash: string;
|
|
556
|
+
}>>;
|
|
557
|
+
google: zod.ZodOptional<zod.ZodObject<{
|
|
558
|
+
id: zod.ZodString;
|
|
559
|
+
}, "strip", zod.ZodTypeAny, {
|
|
560
|
+
id: string;
|
|
561
|
+
}, {
|
|
562
|
+
id: string;
|
|
563
|
+
}>>;
|
|
564
|
+
}, "strip", zod.ZodTypeAny, {
|
|
565
|
+
password?: {
|
|
566
|
+
hash: string;
|
|
567
|
+
} | undefined;
|
|
568
|
+
google?: {
|
|
569
|
+
id: string;
|
|
570
|
+
} | undefined;
|
|
571
|
+
}, {
|
|
572
|
+
password?: {
|
|
573
|
+
hash: string;
|
|
574
|
+
} | undefined;
|
|
575
|
+
google?: {
|
|
576
|
+
id: string;
|
|
577
|
+
} | undefined;
|
|
578
|
+
}>;
|
|
579
|
+
}>, "handle" | "createdAt" | "emails" | "authMethods"> & {
|
|
580
|
+
_id: ObjectId;
|
|
581
|
+
}, ...args: Parameters<any>) => any>>;
|
|
360
582
|
|
|
361
583
|
declare function getConfig(key: ConfigKey): string | number | boolean;
|
|
362
584
|
|