Skip to content

k.site.codes ​

Site code repository: create, read, update, delete, and query API endpoint scripts and reusable CodeBlocks

Execution ContextPrerequisitesTypical Use
KScript API / Server scriptsCurrent site context; Api creation requires url whereas CodeBlock has no routeProgrammatically manage site API scripts and reusable CodeBlock modules, update code bodies, and check change logs

Quick Start ​

Create and query a site API code resource (and resolve its registered route URL):

js
k.api.post(() => {
    const stamp = Date.now().toString()
    const name = "demo-api-" + stamp
    const url = "/api/demo-" + stamp

    k.site.codes.add({
        name,
        url,
        codeType: "Api",
        body: `k.api.get("ping", () => ({ stamp: "${stamp}" }))`
    })

    const api = k.site.codes.getByUrl(url)
    return {
        id: api ? api.id : null,
        route: api ? k.site.codes.getUrl(api.id) : null
    }
})

Quick Reference ​

Method / PropertyDescriptionReturns
all()Returns all Code items in the site (Api and CodeBlock)Code[]
get(nameOrId)Retrieves a single Code item by name or GUID idCode | null
getByUrl(url)Retrieves a routed Api code item by its route URLCode | null
add(code)Creates a CodeBlock or a routed Api itemvoid
update(code)Persists updates to a full Code objectvoid
updateBody(nameOrId, body)Replaces only the source body stringvoid
delete(nameOrId)Deletes a Code item by name or id (verify via get)void
getUrl(id) / getAbsUrl(id)Resolves relative or absolute URL for a routed Api by idstring | null
getLogs(nameOrId) / getByLog(logId)Lists version logs and restores a historical snapshotChangeLog[] | null / Code | null

codeType Categories and Boundaries ​

Within k.site.codes, the purpose is distinguished by codeType on the object — this is the core classification for server-side execution and routing:

codeType (when writing)Enumeration value (common when reading)MeaningTypical uses
"Api"4 or "Api"API scriptUse k.api to define HTTP endpoints; has routing URL, supports getByUrl / getUrl
"CodeBlock"10 or "CodeBlock"Code blockReusable KScript modules (export function, etc.); no standalone route, imported in pages/views
"PageScript"5Page scriptScript embedded in a page
"PaymentCallBack"7Payment callbackDedicated script type for payment callbacks

Representation of codeType

Pass string values "Api" / "CodeBlock" when calling add. On objects returned by get / all, codeType is often a numeric enumeration (such as 4, 10), or may be a string. Handle both forms when filtering.

add behaves differently between Api and CodeBlock

  • codeType: "CodeBlock": Only pass name and body; do not pass url (no site route is registered). scriptType is always set to Module (1), and any scriptType or cors passed in CodeInput is ignored.
  • codeType: "Api" (or other non-CodeBlock routable creation): requires name, body, and url (such as /api/demo), which registers a route similarly to k.site.pages / k.site.scripts; scriptType and cors apply only to non-CodeBlock creation.

Relationship with k.api

The API file written in the console corresponds to a Code item with codeType === "Api"; k.api.get/post inside the file defines sub-paths under that API. k.site.codes performs CRUD on these Code resources rather than replacing k.api syntax itself.

Detailed Methods ​

Filter by codeType ​

all() returns all Codes and should be filtered in script while handling both string and numeric enum forms of codeType.

None

Returns: Code[]

js
k.api.get(() => {
    const all = k.site.codes.all()
    const isApi = (c) => c.codeType === "Api" || c.codeType === 4
    const isCodeBlock = (c) => c.codeType === "CodeBlock" || c.codeType === 10
    return {
        apiCount: all.filter(isApi).length,
        codeBlockCount: all.filter(isCodeBlock).length
    }
})

add() — CodeBlock ​

Creates a reusable code block without registering a standalone route (do not pass url; scriptType is fixed to Module and scriptType / cors are ignored).

ParameterTypeRequiredDescription
code.namestringyesCodeBlock name
code.bodystringyesKScript source code
code.codeTypestringyesMust be "CodeBlock"

Returns: void

js
k.api.post(() => {
    const stamp = Date.now().toString()
    const name = "ai-cb-" + stamp

    k.site.codes.add({
        name,
        codeType: "CodeBlock",
        body: `export function aiCb_${stamp}() { return "${stamp}"; }`
    })

    const block = k.site.codes.get(name)
    return {
        verified: !!block && (block.codeType === "CodeBlock" || block.codeType === 10),
        id: block?.id,
        hasRoute: block ? !!k.site.codes.getUrl(block.id) : false
    }
})

hasRoute should be false: a CodeBlock does not register a standalone URL.

add() — Api ​

Creates an API script and registers its route URL.

ParameterTypeRequiredDescription
code.namestringyesAPI name (unique within site)
code.bodystringyesScript containing k.api.*
code.codeTypestringyesMust be "Api"
code.urlstringyesAPI root path, such as /api/demo
code.scriptTypeScriptTypenoScript engine type ("Classic" / 0 or "Module" / 1; applies only to non-CodeBlock creation)
code.corsbooleannoWhether to enable CORS (applies only to non-CodeBlock creation)

Returns: void

js
k.api.post(() => {
    const stamp = Date.now().toString()
    const name = "ai-api-" + stamp
    const url = "/api/ai-code-" + stamp

    k.site.codes.add({
        name,
        url,
        codeType: "Api",
        body: `k.api.get("ping", () => ({ stamp: "${stamp}" }))`
    })

    const api = k.site.codes.getByUrl(url)
    const route = api ? k.site.codes.getUrl(api.id) : null

    return {
        verified: !!api && (api.codeType === "Api" || api.codeType === 4) && route === url,
        id: api?.id,
        route
    }
})

all() / get() / getByUrl() ​

List all Code resources, look up by name/ID, or look up a routed Api by URL.

MethodParametersReturnsDescription
all()NoneCode[]Returns all Code / CodeBlock resources
get(nameOrId)nameOrId: stringCode | nullGets a resource by name or ID
getByUrl(url)url: stringCode | nullOnly valid for routed Api code items (codeType is "Api" or 4)

Returns: Code[] or Code | null

js
k.api.get(() => {
    const code = k.site.codes.get("my-api")
    const byUrl = k.site.codes.getByUrl("/api/hello")
    return {
        byName: code ? { name: code.name, codeType: code.codeType } : null,
        byUrl: byUrl ? { name: byUrl.name, codeType: byUrl.codeType } : null
    }
})

update() / updateBody() ​

Update a full Code object or replace only its body source text.

MethodParametersReturnsDescription
update(code)code: CodevoidUpdates the full Code object
updateBody(nameOrId, body)nameOrId: string, body: stringvoidReplaces only the source body

Returns: void

js
k.api.post(() => {
    const stamp = Date.now().toString()
    const name = "ai-api-upd-" + stamp
    const url = "/api/ai-code-upd-" + stamp

    k.site.codes.add({
        name,
        url,
        codeType: "Api",
        body: 'k.api.get(() => "v1")'
    })

    const api = k.site.codes.getByUrl(url)
    api.body = 'k.api.get(() => "v2")'
    k.site.codes.update(api)

    const after = k.site.codes.getByUrl(url)
    return { verified: after?.body?.indexOf("v2") >= 0 }
})

updateBody(nameOrId, body) only replaces body and works identically to styles/scripts.

delete() ​

Use get(name) to verify after deletion; do not call getByUrl after deleting an API (stale route cleanup behaves like k.site.pages).

ParameterTypeRequiredDescription
nameOrIdstringyesCode name or ID

Returns: void

js
k.api.post(() => {
    const stamp = Date.now().toString()
    const name = "ai-api-del-" + stamp
    const url = "/api/ai-code-del-" + stamp

    k.site.codes.add({
        name,
        url,
        codeType: "Api",
        body: 'k.api.get(() => "del")'
    })
    const before = k.site.codes.getByUrl(url)

    k.site.codes.delete(name)
    const after = k.site.codes.get(name)

    return { verified: !!before && !after }
})

getUrl() / getAbsUrl() ​

Resolve relative or absolute URLs for routed API Code items by id.

MethodParametersReturnsDescription
getUrl(id)id: stringstring | nullGets the relative URL; only APIs with routes return a value
getAbsUrl(id)id: stringstring | nullGets the absolute URL

Returns: string | null

js
k.api.get(() => {
    const apis = k.site.codes.all().filter((c) => c.codeType === "Api" || c.codeType === 4)
    for (const api of apis) {
        const rel = k.site.codes.getUrl(api.id)
        if (!rel) continue
        const abs = k.site.codes.getAbsUrl(api.id)
        return { relative: rel, absolute: abs, name: api.name }
    }
    return null
})

getLogs() / getByLog() ​

Consistent with other k.site.* text repositories: query change history and restore historical snapshots by log ID.

MethodParametersReturnsDescription
getLogs(nameOrId)nameOrId: stringChangeLog[] | nullGets version logs
getByLog(logId)logId: numberCode | nullGets a historical version by log ID

Returns: ChangeLog[] | null or Code | null

js
k.api.get(() => {
    const codes = k.site.codes.all()
    if (!codes.length) return { error: "no codes" }

    const logs = k.site.codes.getLogs(codes[0].id)
    return { logCount: logs ? logs.length : 0 }
})

Common Code Fields ​

FieldTypeDescription
idstringCode ID
namestringCode name
bodystringSource code
codeTypeCodeTypeApi, CodeBlock, etc.
scriptTypeScriptTypeScript engine type (ScriptType enum: "Classic" = 0, "Module" = 1); appears as a numeric enum value (0 or 1) when read in KScript
extensionstringUsually .js
corsbooleanWhether CORS is enabled for the API
parametersstring[]Declared API request parameters
onlinebooleanWhether it is online
versionnumberVersion number

TypeScript Definitions ​

Show full TypeScript definitions
ts
type CodeType =
  | 'Api'
  | 'CodeBlock'
  | 'PageScript'
  | 'PaymentCallBack';

type ScriptType = 'Classic' | 'Module' | number;

interface CodeRepository {
  add(code: CodeInput): void;
  all(): Code[];
  get(nameOrId: string): Code | null;
  getByUrl(url: string): Code | null;
  update(code: Code): void;
  updateBody(nameOrId: string, body: string): void;
  delete(nameOrId: string): void;
  getUrl(id: string): string | null;
  getAbsUrl(id: string): string | null;
  getLogs(nameOrId: string): ChangeLog[] | null;
  getByLog(logId: number): Code | null;
}

interface CodeInput {
  name: string;
  body: string;
  codeType: CodeType;
  url?: string;
  /** Applies only to non-CodeBlock creation; CodeBlock always uses Module (1) */
  scriptType?: ScriptType;
  /** Applies only to non-CodeBlock creation */
  cors?: boolean;
}