NormalScript:一种完全正常的脚本语言
NormalScript: A perfectly normal scripting language

原始链接: https://psychoscript.com/

NormalScript® 是一个面向 Node ≥24 或 Bun ≥1.4 的小型、快速嵌入式 JavaScript 虚拟机。它在现有进程内以脚本或代理代码模式运行 JavaScript 的严格子集,不使用 WASM、原生插件或 worker。开发者使用 `Runtime.make` 创建运行时,通过 `Host.fn` 和命名空间暴露普通宿主函数,然后调用 `runtime.execute` 或 `program.run`。脚本可以链式调用宿主函数,并使用 async 函数、生成器、类以及顶层 await/return。运行可被挂起,使用 `toBytes()` 序列化,并在之后使用 `fromBytes()` 和 `runtime.resume()` 恢复,在全局变量和构建匹配时保留状态。虚拟机支持 JSON 类似的结果传递、限制、取消、持久调用和流式处理。它在范围内通过了 19,408 个中的 22,253 个 test262 文件。它采用 MIT 许可证,省略了定时器、I/O、磁盘模块加载、动态代码、非严格模式以及许多高级元编程功能。

Hacker News new | past | comments | ask | show | jobs | submit login NormalScript:一门完全正常的脚本语言 ( psychoscript.com ) 21 分 由 hn-aarvin 3 小时前 | hide | past | favorite | 3 评论 help lioeters 13 分钟前 | next [–] 令人印象深刻且令人头脑炸裂。最终让我的浏览器崩溃了,但值得。 网站是开源的。 https://github.com/anomalyco/psychoscript/tree/dev/website#r... reply hn-aarvin 3 小时前 | prev | next [–] 通过点击笑脸揭示的可视化效果,必须是我在网上见过的最酷的东西之一。 reply hmry 13 分钟前 | prev [–] 仅支持 WebGPU。如果你不理解,启用 WebGPU 后再试。 Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact Search:
相关文章

原文
Contact sales

Enterprise scripting solutions

NormalScript® is a small, fast virtual machine for a subset of JavaScript. It embeds in your Node or Bun application: give it a few host functions and it runs little scripts and agent code mode, pausing to bytes and resuming later. Nothing unusual happens here.

Review capabilities View compliance matrix View on GitHub

Trusted by more than 400 normal organizations · Node ≥ 24 or Bun ≥ 1.4 · MIT licensed

0

WASM modules, native addons, or workers to wire up

1

Call to run a script: runtime.execute(code)

19,408

test262 files passing; 2,845 skipped as known gaps, 0 failing

Bytes

What a paused run is saved as, and resumed from

Core capabilities

Embedded scripting for your existing application.

For teams that run little scripts, plugins, lightweight workflows, or agent code mode inside a Node or Bun application, without operating a second runtime.

Embeds as a library

A pure JavaScript package for Node ≥ 24 or Bun ≥ 1.4, with no WASM module, native addon, or isolate to wire up. Call Runtime.make, pass plain host functions, and run.

Small and fast

Scripts compile to bytecode and run on a compact virtual machine inside your process. There is no worker to spawn and nothing to boot, so a run starts when you call it and stops on timeoutMs or an AbortSignal.

Code mode and little scripts

An agent, user, or plugin writes one script that chains many host calls, with loops, branches, and Promise.all in between. Errors return a kind, a message, and optional suggestions.

A plain host API

Host.fn turns an ordinary function into a global. Host.namespace resolves large catalogs lazily. Host.durableFn keeps long work running across a suspend. StreamingResponse streams a response body.

Suspend, save, and resume

Suspend a waiting run with program.suspend(), save its state with toBytes(), and continue it with fromBytes() and runtime.resume(). Same build, same globals, same result.

A JavaScript subset, a simple API

Scripts are written in a modern, strict-mode subset of JavaScript: async functions, generators, classes, and top-level await and return. The host API is Promise-based, with the same names over Effect at /effect.

Reference integration

Integration follows a documented procedure.

Runtime.make takes a globals function and optional limits. Plain objects of host functions act as namespaces. Arguments reach the host as copies, and results are copied back. There is no further setup.

Exhibit A · A code-mode script chaining host calls

import { Host, Runtime } from "normalscript"

const ledger = [
  { id: "INV-1", total: 1200, paid: true },
  { id: "INV-2", total: 450, paid: false },
  { id: "INV-3", total: 80, paid: false },
]
const outbox = []

const runtime = Runtime.make({
  limits: { timeoutMs: 1_000 },
  globals: () => ({
    invoices: {
      list: Host.fn(() => ledger),
      remind: Host.fn(([id]) => outbox.push(id), {
        type: "async",
      }),
    },
  }),
})

// Code mode: one script, several host calls.
const result = await runtime.execute(`
  const due = invoices.list().filter((i) => !i.paid)
  await Promise.all(due.map((i) => invoices.remind(i.id)))
  const owed = due.reduce((sum, i) => sum + i.total, 0)
  return { reminded: due.length, owed }
`)
console.log(result.value)
// { reminded: 2, owed: 530 }

Exhibit B · Suspend, save, and resume

import {
  Host,
  Runtime,
  fromBytes,
  toBytes,
} from "normalscript"

const slow = ([n]) =>
  new Promise((done) => setTimeout(() => done(n * 10), 50))

const runtime = Runtime.make({
  globals: () => ({
    fetchMetric: Host.fn(slow, {
      type: "async",
      idempotent: true,
    }),
  }),
})

const program = runtime.program(`
  let total = 0
  for (const n of [1, 2, 3]) total += await fetchMetric(n)
  return total
`)
const running = program.run()

// Pause the run mid-call and save its state as bytes.
const outcome = await program.suspend()
await running
const bytes = toBytes(outcome.state)

// Later, in any process with the same build and globals.
const result = await runtime.resume(fromBytes(bytes)).run()
console.log(result.value)
// 60

Operational specifications

Runtime characteristics, documented in full.

How a run starts, stops, pauses, and resumes. All behavior below is standard.

Embedding

Runtime.make({ globals, limits }) returns a runtime. globals is called for each run, and again on resume, with the run's id and metadata. Globals shadow built-ins of the same name.

Host calls

A sync host function returns its value to the script directly. An async one gives the script a promise at once. Host calls may run concurrently. Host.fail gives the script a catchable error with your own kind.

Results

{ ok: true, value } or { ok: false, error: { kind, message, suggestions? } }, plus console logs, warnings, and the run's metadata. The value crosses as JSON.stringify would serialize it.

Limits

Two options, neither set by default. timeoutMs is active time, summed across resumes and checked between VM steps; a single regular-expression match runs on the host engine and is not interrupted. maxOutputBytes is the UTF-8 bytes kept from the result and logs, with an equal budget for warnings; the rest is cut. There is no separate memory or step-count limit.

Fixed caps

Strings: 2^24 characters. Arrays: 10,000,000 elements. Pending promises: 10,000. Nesting across the host boundary: 32 levels. Exceeding a cap throws a RangeError in the script.

Cancellation

Aborting the signal passed to execute() or program.run() aborts every host call's call.signal and rejects the run with an AbortError. A host call that ignores its signal is not waited for.

Snapshots

suspend() returns the run's state; toBytes() and fromBytes() turn it into bytes and back. A snapshot resumes on the build that wrote it. Another build, or malformed bytes, rejects with a SnapshotError. suspend({ maxBytes }) caps the size. Store snapshots as you would store code.

Host calls during suspend

An async call marked idempotent runs again on resume with the same call.key. Otherwise suspend() rejects with a SuspendError while the call is in progress, and the run goes on.

Durable calls

Host.durableFn work keeps running across a suspend. start() returns JSON kept in the snapshot, wait() gets the result, again after a resume, and cancel() runs if the run ends without it.

Determinism

Runs are deterministic except for Math.random(), Date.now(), new Date() with no arguments, crypto.randomUUID(), and crypto.getRandomValues(). There is no option to seed them. A host may shadow them with globals; the replacement is the whole object.

Effect API

Optional. The /effect entry point exports the same names with an Effect API. Host functions may return Effects, and interrupting a run interrupts its host calls. The Promise API has no dependency on Effect.

Scope and compliance matrix

A clear accounting of what is and is not supported.

NormalScript® is a small embeddable virtual machine for a subset of JavaScript, not a full runtime such as Node, Bun, or a browser. Whatever a script needs from outside, the host passes in. The omissions below keep it small.

Supported

  • Host runtimes: Node ≥ 24 or Bun ≥ 1.4.
  • Syntax: let and const, destructuring, spread, arrow, async, and generator functions, async generators and for await, classes (fields, static members, getters and setters, extends, super), object literal getters and setters, labels, try/finally, and top-level await and return. Unsupported syntax fails before the script runs, with a hint.
  • Built-ins: Object, Array, String, Number, BigInt, Math, JSON, Date, RegExp, Map, Set, WeakMap, WeakSet, Promise, Iterator helpers, and errors.
  • Pure-data helpers: URL, URLSearchParams, Headers, TextEncoder/TextDecoder, atob/btoa, structuredClone, crypto.randomUUID/getRandomValues, Uint8Array, Node's Buffer, and console.
  • Imports: import and require bind host globals by module name before the script runs.
  • Host function options: type is sync (the default), async, or sync-thenable. idempotent permits a suspend mid-call. constructible allows new. takesFunctions accepts functions the host returned earlier. snapshot keeps functions in results across a resume.
  • Argument translation: A script function or promise inside a host argument fails the call by default. The translate option can drop functions and await promises instead.
  • Conformance: test262 at pinned revision 250f204f, excluding features out of scope by design. Of 22,253 files kept, 19,408 pass and 2,845 are skipped as known gaps. None fail. Not yet run in CI.

Not supported

  • Timers and event loop: No setTimeout, setInterval, setImmediate, or queueMicrotask, and no background event loop. A script runs its top-level body to completion and exits. Un-awaited promises and in-flight host calls still pending are interrupted.
  • Runtime and I/O APIs: No fetch, fs, process, AbortController, EventTarget, Request/Response/Blob, WebSocket, Worker, crypto.subtle, Intl, or DOM. The host passes in whatever a script needs.
  • Module loader and export: import and require only bind host globals and configured module aliases. Scripts do not load files or packages from disk. export is a syntax error.
  • Script functions as host arguments: Not yet. Arguments are copied across the boundary, so callbacks cannot be passed to host functions today. Support is planned for a future release. Host objects are not classes.
  • Dynamic code and sloppy mode: eval, new Function(...), with, and non-strict mode.
  • Metaprogramming: Object.setPrototypeOf, __proto__ assignment, __defineGetter__/__defineSetter__, Proxy, and Reflect.
  • Class features: Private members (#x), static blocks, and new on plain functions. Only classes and host functions marked constructible can be constructed.
  • Symbols: Symbol(). Only Symbol.iterator, Symbol.asyncIterator, Symbol.toPrimitive, and Symbol.toStringTag exist.
  • Binary and weak references: Typed arrays other than Uint8Array, ArrayBuffer, DataView, WeakRef, and FinalizationRegistry.
  • TypeScript syntax: Scripts must be plain JavaScript.

Evaluation and procurement

Initiate a standard internal review.

NormalScript® is distributed under the MIT License. To begin an evaluation, request a demo or download the white paper. Both are standard next steps.

Form NS-7 · Declaration of Normal Viewing

I, the undersigned, declare that I viewed the NormalScript® website and that nothing unusual happened.

I did not take the tab. I did not see a sun, a face, a valley, a terminal, a planet, a snake, or my manager. Any colours I recall were within brand guidelines.

I understand that this declaration may be audited.

SignatureDate

Retain for your records. Do not fold.

联系我们 contact @ memedata.com