Skip to content

k.module ​

KScript runtime API for script modules (Develop → Modules)

Execution ContextPrerequisitesTypical Use
Module scripts (context members) or Site Code / API (management methods)Context members require a Module execution context; management needs site authIsolated module files/DBs, scheduled tasks, ZIP & repository sync

A module is a self-contained extension package with its own directories and routes (view/, api/, code/, module.config, etc.), mounted inside a site under /_moduleName/{part}. k.module exposes the active module context, settings, scheduled tasks, module-local files and databases, and site-level module package management (create, import, export, and repository install).

Quick Start ​

js
// Read module.config settings and write a module-local file inside a module script
const prefix = k.module.baseUrl
const title = k.module.config?.text || k.module.name

const files = k.module.openFileStream("file")
files.writeText("notes.txt", "hello from " + prefix)
const text = files.readText("notes.txt")

Quick Reference ​

Method / PropertyDescriptionReturns
baseUrl / name / configCurrent module root URL, name, and saved settings (module context)string / any
taskFluent scheduler API for module background tasks (module context)KTask
localFile / openFileStream(fileType)Read and write files in module resource folders (module context)LocalFile / KModuleFiles
localIndexedDb / localSqliteModule-local isolated databases (module context)IDatabase / SqliteDatabase
list() / isNameExists(name)List site modules or check module name availabilityScriptModule[] / boolean
createModule(name) / remove(...)Create empty module metadata or delete a module by ID/nameScriptModule / void
importZip(name, binary) / exportAsZip(nameOrId)Import or export a module archive as zip bytesstring / number[]
importFromUrl(...)Fetch and install a module from another Kooboo sitestring
searchRepository(keyword) / installFromRepository(packageId, name)Search and install modules from the Kooboo repositoryModuleSearchResult[] / string

Execution context

Context-scoped members (baseUrl, config, name, localFile, localIndexedDb, localSqlite, task, and openFileStream) are available only when executing inside a module script (module view/api/code, or an entry imported via Module: / ModuleApi:). Accessing them from ordinary site Code or API scripts throws part of k.module only available under Module execution context.

Site-level management methods (list, createModule, remove, isNameExists, importZip, exportAsZip, importFromUrl, searchRepository, installFromRepository) can be called from authorized site scripts. Create or import modules and configure module.config settings under Modules (CMS).

Difference from k.site and Module Imports

APIScope
k.site.*Site-wide pages, layouts, views, and Code resources
k.module.*Current module package files, configuration, local stores, and routing
js
import { helper } from "Module:myModule/utils.js"
// Module API entry
import api from "ModuleApi:myModule/hello.js"

Module: automatically resolves inside the module's code/ directory and ModuleApi: resolves inside api/. Provide the exact relative filename including extension (no .js extension is appended automatically, and do not duplicate code/ or api/ in the specifier).

Module-Context Members ​

baseUrl / config / name ​

Read the active module's root URL (including its route prefix, without a trailing slash /, e.g. https://example.com/_myModule), saved admin settings (from settingDefines in module.config plus site settings JSON), and active module name.

Note: On the first read when module settings have not yet been initialized in the database, k.module.config persists default values from module.config and returns null (subsequent reads return the parsed settings object). Always guard property reads with optional chaining such as k.module.config?.text.

Returns: baseUrl and name return string; config returns Record<string, any> | null.

js
// Inside module view or api scripts
const home = k.module.baseUrl + "/index"
const title = k.module.config?.text
const moduleName = k.module.name

task ​

Fluent scheduler API for module background tasks (typically placed in event.js or a task script).

MethodParametersReturnsDescription
day(day)day: numberKTaskSet day interval
hour(hour)hour: numberKTaskSet hour interval
minute(minutes)minutes: numberKTaskSet minute interval
run(js)js: anyvoidRegister the callback function to run on schedule

Returns: day, hour, and minute return KTask for chaining; run returns void.

js
k.module.task
  .day(1)
  .hour(0)
  .run(function () {
    // scheduled logic
  })

localFile / openFileStream() ​

Access files inside the module's directory on disk, grouped by resource directory, or call k.module.openFileStream(fileType) where fileType is one of css, js, view, api, img, or file.

MemberDirectory
k.module.localFile.viewview/
k.module.localFile.apiapi/
k.module.localFile.jsjs/
k.module.localFile.csscss/
k.module.localFile.imgimg/
k.module.localFile.filefile/

KModuleFiles methods:

MethodParametersReturnsDescription
readText(fileName)fileName: stringstringRead a text file
writeText(fileName, content)fileName: string, content: stringvoidWrite a text file
readBytes(fileName)fileName: stringnumber[]Read binary bytes
writeBytes(fileName, binaryBytes)fileName: string, binaryBytes: number[]voidWrite binary bytes
delete(fileName)fileName: stringvoidDelete a file
files()NoneModuleFileInfo[]List files in that resource directory

Returns: openFileStream() returns KModuleFiles.

js
// Inside a module script, read and write in file/
const files = k.module.openFileStream("file")
files.writeText("notes.txt", "hello module")
const text = files.readText("notes.txt")
const entries = files.files()

localIndexedDb / localSqlite ​

MemberDescription
k.module.localIndexedDbModule-local IndexedDB-style database (IDatabase)
k.module.localSqliteModule-local SQLite database (_sqlite.db at module root)

Ideal for module-private storage, isolated from the site's k.DB.

Site-Level Management APIs ​

These methods run in authorized site Code / API scripts to automate module installation and lifecycle operations.

list() ​

Return all ScriptModule records registered in the site.

Parameters: None.

Returns: ScriptModule[].

js
k.api.get(() => {
  return k.module.list().map((m) => ({ id: m.id, name: m.name, online: m.online }))
})

createModule() ​

Create a new ScriptModule metadata entry and register its module route. Note that createModule() only saves the module metadata without creating its folder on disk until files are created inside it (calling exportAsZip() immediately on an empty newly created module throws a missing-directory error).

ParameterTypeRequiredDescription
namestringYesNew module name

Returns: ScriptModule.

js
k.api.post(() => {
  const mod = k.module.createModule(k.request.form.name)
  return { id: mod.id, name: mod.name }
})

remove() ​

Delete a module by GUID Id, name/ID string, or on a remote destination site domain.

OverloadDescription
remove(Id)Delete module in the current site by GUID
remove(IdOrName)Delete module in the current site by ID or name
remove(IdOrName, DestinationSiteUrl)Delete matching module on the specified destination site URL
ParameterTypeRequiredDescription
Id / IdOrNameany | stringYesModule ID or name
DestinationSiteUrlstringNoTarget site domain (omit to target current site)

Returns: void.

js
k.api.post(() => {
  k.module.remove(k.request.form.name)
  return { ok: true }
})

isNameExists() ​

Check whether a module name already exists in the current site.

ParameterTypeRequiredDescription
namestringYesModule name to check

Returns: boolean.

js
k.api.get(() => {
  return { exists: k.module.isNameExists(k.request.queryString.name) }
})

importZip() ​

Create a module and extract a zip archive into its directory, returning the new module ID.

ParameterTypeRequiredDescription
namestringYesImported module name
binarynumber[]YesZip file byte array

Returns: string. New module ID.

js
k.api.post(() => {
  const file = k.request.files[0]
  const id = k.module.importZip(k.request.form.name, file.bytes)
  return { id }
})

exportAsZip() ​

Export an existing module directory as a zip byte array, or null if the module does not exist.

ParameterTypeRequiredDescription
nameOrIdstringYesModule name or ID

Returns: number[] | null.

js
k.api.get(() => {
  const bytes = k.module.exportAsZip(k.request.queryString.name)
  return { size: bytes ? bytes.length : 0 }
})

importFromUrl() ​

Fetch a shared module zip from another Kooboo site and install it.

OverloadDescription
importFromUrl(SiteUrl, ModuleId, newModuleName)Install into current site (ModuleId accepts string or GUID)
importFromUrl(SiteUrl, ModuleId, newModuleName, DestinationSiteUrl)Install into a target site
ParameterTypeRequiredDescription
SiteUrlstringYesSource site URL
ModuleIdstring | anyYesSource module GUID
newModuleNamestringYesInstalled module name
DestinationSiteUrlstringNoTarget site URL (omit for current site)

Returns: string. Installed module ID.

js
k.api.post(() => {
  const id = k.module.importFromUrl(
    k.request.form.siteUrl,
    k.request.form.moduleId,
    k.request.form.name
  )
  return { id }
})

searchRepository() / installFromRepository() ​

Search the Kooboo module repository and install a package by packageId.

MethodParametersReturnsDescription
searchRepository(keyword)keyword: stringModuleSearchResult[]Search packages by keyword
installFromRepository(packageId, name)packageId: string, name: stringstringInstall package and return module ID

Returns: searchRepository() returns ModuleSearchResult[]; installFromRepository() returns the new module ID string.

js
k.api.post(() => {
  const results = k.module.searchRepository(k.request.form.keyword)
  if (!results.length) return { installed: false }
  const id = k.module.installFromRepository(results[0].packageId, k.request.form.name)
  return { installed: true, id }
})

module.config Conventions ​

Common fields in a module's root module.config JSON file:

FieldDescription
name / version / descriptionPackage metadata (name serves as the menu module identifier)
settingDefinesForm definitions for admin Settings (name, type, defaultValue, display, etc.)
menuAdmin sidebar entry configuration (applies only to online modules)

When a site loads, Kooboo reads menu entries from online modules' module.config files and merges them into the admin left navigation (see Modules (CMS)).

FieldDescription
nameMenu title
nameTranslationOptional localized titles keyed by admin user language
parentOptional parent top-level menu key (such as commerce or content)
urlOptional relative path under module view/ (defaults to module start view when empty)
iconOptional image file name under img/
childrenOptional submenu items containing name, url, etc.

Resolved URLs follow /_moduleName/{viewPath}?SiteId={siteGuid}. Saved settingDefines values are exposed to module scripts via k.module.config. Module documentation can live in Readme.md.

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface KModule {
  task: KTask;
  baseUrl: string;
  config: any;
  name: string;
  localIndexedDb: IDatabase;
  localSqlite: SqliteDatabase;
  localFile: LocalFile;

  list(): ScriptModule[];
  createModule(name: string): ScriptModule;
  remove(Id: any): void;
  remove(IdOrName: string): void;
  remove(IdOrName: string, DestinationSiteUrl: string): void;
  isNameExists(name: string): boolean;
  importZip(name: string, Binary: number[]): string;
  exportAsZip(NameOrId: string): number[];
  importFromUrl(SiteUrl: string, ModuleId: string, newModuleName: string): string;
  importFromUrl(SiteUrl: string, ModuleId: any, newModuleName: string): string;
  importFromUrl(SiteUrl: string, ModuleId: string, newModuleName: string, DestinationSiteUrl: string): string;
  searchRepository(keyword: string): ModuleSearchResult[];
  installFromRepository(PackageId: string, Name: string): string;
  openFileStream(fileType: string): KModuleFiles;
}

interface LocalFile {
  css: KModuleFiles;
  js: KModuleFiles;
  api: KModuleFiles;
  img: KModuleFiles;
  file: KModuleFiles;
  view: KModuleFiles;
}

interface KModuleFiles {
  context: any;
  type: any;
  readText(FileName: string): string;
  writeText(fileName: string, content: string): void;
  readBytes(FileName: string): number[];
  writeBytes(fileName: string, BinaryBytes: number[]): void;
  delete(fileName: string): void;
  files(): ModuleFileInfo[];
}

interface ModuleFileInfo {
  name: string;
  fullName: string;
  folderName: string;
  extension: string;
  size: number;
  stringSize: string;
  lastModified: Date;
}

interface KTask {
  hour(hour: number): KTask;
  minute(minutes: number): KTask;
  day(day: number): KTask;
  run(js: any): void;
}

interface ScriptModule {
  id: any;
  name: string;
  packageName: string;
  moduleVersion: string;
  relativeFolder: string;
  startView: string;
  settings: string;
  taskJs: string;
  online: boolean;
  creationDate: Date;
  lastModified: Date;
}

interface ModuleSearchResult {
  packageId: string;
  title: string;
  description: string;
}
  • Modules (CMS) — List, import, development mode, online status, and sharing
  • k.site — Site resources
  • k.DB — Site databases
  • k.file — Site files outside module directories
  • Scheduled Jobs — Site-level scheduled jobs