k.site.codes
Site code repository: create, read, update, delete, and query API endpoint scripts and reusable CodeBlocks
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
| KScript API / Server scripts | Current site context; Api creation requires url whereas CodeBlock has no route | Programmatically 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):
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 / Property | Description | Returns |
|---|---|---|
all() | Returns all Code items in the site (Api and CodeBlock) | Code[] |
get(nameOrId) | Retrieves a single Code item by name or GUID id | Code | null |
getByUrl(url) | Retrieves a routed Api code item by its route URL | Code | null |
add(code) | Creates a CodeBlock or a routed Api item | void |
update(code) | Persists updates to a full Code object | void |
updateBody(nameOrId, body) | Replaces only the source body string | void |
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 id | string | null |
getLogs(nameOrId) / getByLog(logId) | Lists version logs and restores a historical snapshot | ChangeLog[] | 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) | Meaning | Typical uses |
|---|---|---|---|
"Api" | 4 or "Api" | API script | Use k.api to define HTTP endpoints; has routing URL, supports getByUrl / getUrl |
"CodeBlock" | 10 or "CodeBlock" | Code block | Reusable KScript modules (export function, etc.); no standalone route, imported in pages/views |
"PageScript" | 5 | Page script | Script embedded in a page |
"PaymentCallBack" | 7 | Payment callback | Dedicated 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 passnameandbody; do not passurl(no site route is registered).scriptTypeis always set toModule(1), and anyscriptTypeorcorspassed inCodeInputis ignored.codeType: "Api"(or other non-CodeBlockroutable creation): requiresname,body, andurl(such as/api/demo), which registers a route similarly to k.site.pages / k.site.scripts;scriptTypeandcorsapply only to non-CodeBlockcreation.
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[]
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).
| Parameter | Type | Required | Description |
|---|---|---|---|
code.name | string | yes | CodeBlock name |
code.body | string | yes | KScript source code |
code.codeType | string | yes | Must be "CodeBlock" |
Returns: void
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
code.name | string | yes | API name (unique within site) |
code.body | string | yes | Script containing k.api.* |
code.codeType | string | yes | Must be "Api" |
code.url | string | yes | API root path, such as /api/demo |
code.scriptType | ScriptType | no | Script engine type ("Classic" / 0 or "Module" / 1; applies only to non-CodeBlock creation) |
code.cors | boolean | no | Whether to enable CORS (applies only to non-CodeBlock creation) |
Returns: void
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.
| Method | Parameters | Returns | Description |
|---|---|---|---|
all() | None | Code[] | Returns all Code / CodeBlock resources |
get(nameOrId) | nameOrId: string | Code | null | Gets a resource by name or ID |
getByUrl(url) | url: string | Code | null | Only valid for routed Api code items (codeType is "Api" or 4) |
Returns: Code[] or Code | null
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.
| Method | Parameters | Returns | Description |
|---|---|---|---|
update(code) | code: Code | void | Updates the full Code object |
updateBody(nameOrId, body) | nameOrId: string, body: string | void | Replaces only the source body |
Returns: void
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).
| Parameter | Type | Required | Description |
|---|---|---|---|
nameOrId | string | yes | Code name or ID |
Returns: void
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.
| Method | Parameters | Returns | Description |
|---|---|---|---|
getUrl(id) | id: string | string | null | Gets the relative URL; only APIs with routes return a value |
getAbsUrl(id) | id: string | string | null | Gets the absolute URL |
Returns: string | null
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.
| Method | Parameters | Returns | Description |
|---|---|---|---|
getLogs(nameOrId) | nameOrId: string | ChangeLog[] | null | Gets version logs |
getByLog(logId) | logId: number | Code | null | Gets a historical version by log ID |
Returns: ChangeLog[] | null or Code | null
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
| Field | Type | Description |
|---|---|---|
id | string | Code ID |
name | string | Code name |
body | string | Source code |
codeType | CodeType | Api, CodeBlock, etc. |
scriptType | ScriptType | Script engine type (ScriptType enum: "Classic" = 0, "Module" = 1); appears as a numeric enum value (0 or 1) when read in KScript |
extension | string | Usually .js |
cors | boolean | Whether CORS is enabled for the API |
parameters | string[] | Declared API request parameters |
online | boolean | Whether it is online |
version | number | Version number |
TypeScript Definitions
Show full TypeScript definitions
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;
}Related Docs
- k.api — API route writing method
- k.site
- k.site.scripts — External link JS resources (non-Code repository)
- k.module — module context