file_path
stringlengths 3
280
| file_language
stringclasses 66
values | content
stringlengths 1
1.04M
| repo_name
stringlengths 5
92
| repo_stars
int64 0
154k
| repo_description
stringlengths 0
402
| repo_primary_language
stringclasses 108
values | developer_username
stringlengths 1
25
| developer_name
stringlengths 0
30
| developer_company
stringlengths 0
82
|
|---|---|---|---|---|---|---|---|---|---|
src/canvas-shapes-bg.ts
|
TypeScript
|
interface Obj {
[key: string]: any
}
interface Options {
shapesPool?: string[],
colorPool?: string[],
shapeCount?: number,
interval?: number,
step?: number,
minSize?: number,
maxSize?: number
}
class CanvasShapesBg {
observer: ResizeObserver | null = null
dom: HTMLCanvasElement
ctx: CanvasRenderingContext2D
timerHandle: any
intervalHandle: any
shapesPool: string[] = ['star']
shapes: any[] = []
actionCount: number = 0
width: number = 20
height: number = 20
shapeCount: number = 20
interval: number = 100
step: number = 3
minSize: number = 50
maxSize: number = 150
colorRed = 'rgba(207,13,31,.25)'
colorPool: string[] = [
'rgba(156,183,52,.25)',
'rgba(227,163,26,.25)',
'rgba(217,84,56,.25)',
'rgba(4,80,150,.25)',
'rgba(122,24,105,.25)',
]
constructor (_element: HTMLCanvasElement | undefined | Options, _options: Options | undefined) {
const element = _element instanceof HTMLCanvasElement
? _element
: this.createElement()
const options = ((_element instanceof Option ? _element : _options) || {}) as Options
Object.assign(this, options)
this.dom = element
element.setAttribute('width', element.offsetWidth.toString())
element.setAttribute('height', element.offsetHeight.toString())
this.ctx = element.getContext('2d') as CanvasRenderingContext2D
this.width = element.width
this.height = element.height
this.watch()
}
createElement () {
const canvas = document.createElement('canvas')
// Set canvas size to match the window inner size
canvas.setAttribute('width', window.innerWidth.toString())
canvas.setAttribute('height', window.innerHeight.toString())
// Set canvas position to absolute
canvas.style.position = 'absolute'
canvas.style.left = '0'
canvas.style.top = '0'
// Append the canvas to the body
document.body.appendChild(canvas)
return canvas
}
debounce<T extends (...args: any[]) => any>(
func: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: NodeJS.Timeout
return function debouncedFunction(...args: Parameters<T>) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
func(...args);
}, delay)
};
}
handleCanvasDimensionChange (entries: Obj[]) {
const { dom } = this
for (const entry of entries) {
if (entry.target === dom) {
// Get the new offsetWidth and offsetHeight when the canvas size changes
const newWidth = entry.contentRect.width
const newHeight = entry.contentRect.height
this.width = newWidth
this.height = newHeight
dom.setAttribute('width', newWidth.toString())
dom.setAttribute('height', newHeight.toString())
this.stop()
this.start(this.shapeCount)
}
}
}
watch () {
if (this.dom) {
const observer = new ResizeObserver(
this.debounce(this.handleCanvasDimensionChange.bind(this), 1000)
)
observer.observe(this.dom)
this.observer = observer
}
}
destroy () {
this.observer?.unobserve(this.dom)
this.observer?.disconnect()
}
start (count: number = this.shapeCount) {
this.buildShapes(count)
this.animate()
}
animate () {
this.loop()
}
stop () {
clearTimeout(this.intervalHandle)
this.clearShapes()
this.shapes = []
}
clearShapes () {
this.ctx.clearRect(0, 0, this.width, this.height)
}
loop () {
this.renderShapes()
this.move()
this.intervalHandle = setTimeout(this.loop.bind(this), this.interval)
}
renderShapes () {
const { shapes } = this
this.clearShapes()
for(let i = 0, len = shapes.length;i < len;i ++) {
const obj = shapes[i]
const type = obj.type
;(this as any)['draw' + this.capitalizeString(type)](obj)
}
}
buildPosArrayFromText(_text: string, _options?: Obj): Obj[] {
const th = this
const ctx = th.ctx
const w = th.width
const h = th.height
const text = _text
const options = _options || {}
const shapeSize = options.shapeSize || 20
const scanDistance = options.scanDistance || 5
const fontSize = options.fontSize || 200
const fontFamily = options.fontFamily || 'sans-serif'
const top = options.top || 20
// Supports any of the following values:
// start end left right center
ctx.textAlign = options.textAlign || 'start'
// Supports any of the following values:
// top hanging middle alphabetic ideographic bottom
ctx.textBaseline = options.textBaseline || 'top'
th.clearShapes()
ctx.font = fontSize + 'px ' + fontFamily
ctx.fillStyle = 'red'
ctx.fillText(text, 20, top)
const data = ctx.getImageData(0, 0, w, h)
const dataObj = data.data
const arr: Obj[] = []
for (let i = 0; i < w; i += scanDistance) {
for (let j = 0; j < h; j += scanDistance) {
const point = j * w + i
const dataPoint = dataObj[point * 4];
if (dataPoint) {
arr.push({ x: i, y: j })
}
}
}
th.clearShapes()
return arr
}
moveTo(_targetArr: Obj [], _options?: Obj): void {
const th = this
const shapes = th.shapes
const tarr = _targetArr
const res: Obj[] = []
const options = _options || {}
let speed = options.speed
speed = !speed || speed > 1 || speed <= 0 ? 0.5 : speed
for (let i = 0, len = shapes.length; i < len; i++) {
const pos = shapes[i]
const tpos = tarr[i]
const tx = (pos.x + tpos.x) * speed
const ty = (pos.y + tpos.y) * speed
res.push({ ...pos, x: tx, y: ty })
}
th.shapes = res
}
move () {
const {
shapes,
step
} = this
const res = []
for(let i = 0, len = shapes.length;i < len;i ++) {
const pos = shapes[i]
const ratio = pos.directionY / pos.directionX
const { r } = pos
let tx = pos.x + pos.directionX * step
let ty = pos.y + pos.directionY * step
const ex = tx > pos.r? tx - (this.width - pos.r) : pos.r - tx
const ey = ty > pos.r? ty - (this.height - pos.r) : pos.r - ty
let disx = 0
let disy = 0
if(ex > 0 && ey > 0) {
if(ex > ey) {
ty = ty > pos.r? this.height - pos.r: r
disy = ty - pos.y
disx = disy / pos.directionY * pos.directionX
tx = pos.x + disx
pos.directionY = - pos.directionY
}
else {
tx = tx > pos.r? this.width - pos.r: r
disx = tx - pos.x
disy = disx / pos.directionX * pos.directionY
ty = pos.y + disy
pos.directionX = - pos.directionX
}
} else if(ex > 0) {
tx = tx > pos.r? this.width - pos.r: r
disx = tx - pos.x
disy = disx / pos.directionX * pos.directionY
ty = pos.y + disy
pos.directionX = - pos.directionX
} else if(ey > 0) {
ty = ty > pos.r? this.height - pos.r: r
disy = ty - pos.y
disx = disy / pos.directionY * pos.directionX
tx = pos.x + disx
pos.directionY = - pos.directionY
}
pos.x = tx
pos.y = ty
res.push(pos)
}
this.shapes = res
}
capitalizeString (str: string) {
if (typeof str !== 'string' || str.length === 0) {
return str
}
return str.charAt(0).toUpperCase() + str.slice(1)
}
getRandomColor () {
const { colorPool } = this
const clen = colorPool.length
const cr = Math.floor(Math.random() * clen)
return colorPool[cr]
}
buildShapes (_count: number, typesPool?: string[]) {
const count = _count || this.shapeCount
const shapesPool = typesPool || this.shapesPool
const len = shapesPool.length
let r: any
for(let i = 0;i < count;i ++) {
r = Math.floor(Math.random() * len)
this.shapes.push(this.buildShape(shapesPool[r]))
}
}
buildShape (type: string) {
return (this as any)['buildShape' + this.capitalizeString(type)]()
}
popShape (count: number) {
const len = this.shapes.length
let _count = len < count ? len : count
_count = len - _count
this.shapes = this.shapes.slice(0, _count)
this.shapeCount = this.shapeCount - count
}
pushShape (obj: Obj, typesPool?: string[]) {
const shapesPool = typesPool || this.shapesPool
const len = shapesPool.length
const r = Math.floor(Math.random() * len)
this.shapes.push({
...this.buildShape(shapesPool[r]),
...obj
})
this.shapeCount++
}
drawBubble (pos: Obj) {
const { ctx } = this
ctx.beginPath()
ctx.fillStyle = pos.fillStyle
ctx.arc(pos.x, pos.y, pos.r, 0, Math.PI * 2, true)
ctx.fill()
ctx.closePath()
}
drawBalloon (pos: Obj) {
const { ctx } = this
ctx.beginPath()
ctx.fillStyle = pos.fillStyle
ctx.arc(pos.x, pos.y, pos.r, 0, Math.PI * 2, true)
ctx.fill()
ctx.closePath()
ctx.beginPath()
ctx.moveTo(this.width / 2, this.height - 20)
ctx.lineTo(pos.x, pos.y)
ctx.strokeStyle = pos.strokeStyle
ctx.stroke()
ctx.closePath()
}
drawLight (pos: Obj) {
const { ctx } = this
ctx.beginPath()
ctx.moveTo(20, 20)
ctx.lineTo(pos.x, pos.y)
ctx.strokeStyle = pos.strokeStyle
ctx.stroke()
ctx.closePath()
}
drawHeart(pos: Obj): void {
const { ctx } = this
const ratio = pos.r / 75
const { x, y } = pos
const bx = x - pos.r
const by = y - pos.r
ctx.beginPath()
ctx.fillStyle = pos.fillStyle
ctx.moveTo(bx + 75 * ratio, by + 40 * ratio)
ctx.bezierCurveTo(bx + 75 * ratio, by + 37 * ratio, bx + 70 * ratio, by + 25 * ratio, bx + 50 * ratio, by + 25 * ratio)
ctx.bezierCurveTo(bx + 20 * ratio, by + 25 * ratio, bx + 20 * ratio, by + 62.5 * ratio, bx + 20 * ratio, by + 62.5 * ratio)
ctx.bezierCurveTo(bx + 20 * ratio, by + 80 * ratio, bx + 40 * ratio, by + 102 * ratio, bx + 75 * ratio, by + 120 * ratio)
ctx.bezierCurveTo(bx + 110 * ratio, by + 102 * ratio, bx + 130 * ratio, by + 80 * ratio, bx + 130 * ratio, by + 62.5 * ratio)
ctx.bezierCurveTo(bx + 130 * ratio, by + 62.5 * ratio, bx + 130 * ratio, by + 25 * ratio, bx + 100 * ratio, by + 25 * ratio)
ctx.bezierCurveTo(bx + 85 * ratio, by + 25 * ratio, bx + 75 * ratio, by + 37 * ratio, bx + 75 * ratio, by + 40 * ratio)
ctx.fill()
ctx.closePath()
}
drawStar(pos: Obj): void {
let rot = Math.PI / 2 * 3
const cx = pos.x
const cy = pos.y
const spike = pos.spike
const step = Math.PI / spike
const { ctx } = this
const outerRadius = pos.outerR
const innerRadius = pos.innerR
let x, y
if (pos.strokeStyle) {
ctx.strokeStyle = pos.strokeStyle
} else {
ctx.fillStyle = pos.fillStyle
}
ctx.beginPath()
ctx.moveTo(cx, cy - outerRadius)
for (let i = 0; i < spike; i++) {
x = cx + Math.cos(rot) * outerRadius
y = cy + Math.sin(rot) * outerRadius
ctx.lineTo(x, y)
rot += step
x = cx + Math.cos(rot) * innerRadius
y = cy + Math.sin(rot) * innerRadius
ctx.lineTo(x, y)
rot += step
}
ctx.lineTo(cx, cy - outerRadius)
if (pos.strokeStyle) {
ctx.stroke()
} else {
ctx.fill()
}
ctx.closePath()
}
buildShapeBubble(color = this.getRandomColor()): Obj {
const size = Math.floor(Math.random() * (this.maxSize - this.minSize)) + this.minSize
const s2 = size * 2
const xx = this.width > s2 ? this.width : s2 + 1
const yy = this.height > s2 ? this.height : s2 + 1
const x = size + Math.floor(Math.random() * (xx - s2))
const y = size + Math.floor(Math.random() * (yy - s2))
const directionX = (Math.floor(Math.random() * 7) - 3) / 3
const directionY = (Math.floor(Math.random() * 7) - 3) / 3
const obj: Obj = {
x,
y,
r: size,
directionX,
directionY,
type: 'bubble',
fillStyle: color
}
return obj
}
buildShapeBalloon(color = this.getRandomColor()): Obj {
const size = Math.floor(Math.random() * (this.maxSize - this.minSize)) + this.minSize
const s2 = size * 2
const xx = this.width > s2 ? this.width : s2 + 1
const yy = this.height > s2 ? this.height : s2 + 1
const x = size + Math.floor(Math.random() * (xx - s2))
const y = size + Math.floor(Math.random() * (yy - s2))
const directionX = (Math.floor(Math.random() * 7) - 3) / 3
const directionY = (Math.floor(Math.random() * 7) - 3) / 3
const obj: Obj = {
x,
y,
r: size,
directionX,
directionY,
type: 'balloon',
strokeStyle: color,
fillStyle: color
}
return obj
}
buildShapeLight(color = this.getRandomColor()): Obj {
const size = Math.floor(Math.random() * (this.maxSize - this.minSize)) + this.minSize
const s2 = size * 2
const xx = this.width > s2 ? this.width : s2 + 1
const yy = this.height > s2 ? this.height : s2 + 1
const x = size + Math.floor(Math.random() * (xx - s2))
const y = size + Math.floor(Math.random() * (yy - s2))
const directionX = (Math.floor(Math.random() * 7) - 3) / 3
const directionY = (Math.floor(Math.random() * 7) - 3) / 3
const obj: Obj = {
x,
y,
r: size,
directionX,
directionY,
type: 'light',
strokeStyle: color
}
return obj
}
//heart from https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes
buildShapeHeart (color = this.getRandomColor()): Obj {
const size = Math.floor(Math.random() * (this.maxSize - this.minSize)) + this.minSize
const s2 = size * 2
const xx = this.width > s2 ? this.width : s2 + 1
const yy = this.height > s2 ? this.height : s2 + 1
const x = size + Math.floor(Math.random() * (xx - s2))
const y = size + Math.floor(Math.random() * (yy - s2))
const directionX = Math.random() * 2 - 1
const directionY = Math.random() * 2 - 1
const obj: Obj = {
x,
y,
r: size,
directionX,
directionY,
type: 'heart',
fillStyle: color
}
return obj
}
buildShapeStar (color = this.getRandomColor()): Obj {
const size = Math.floor(Math.random() * (this.maxSize - this.minSize)) + this.minSize
const s2 = size * 2
const xx = this.width > s2 ? this.width : s2 + 1
const yy = this.height > s2 ? this.height : s2 + 1
const x = size + Math.floor(Math.random() * (xx - s2))
const y = size + Math.floor(Math.random() * (yy - s2))
const directionX = Math.random() * 2 - 1
const directionY = Math.random() * 2 - 1
const spike = 5 + Math.floor(Math.random() * 5)
const obj: Obj = {
x,
y,
r: size,
outerR: size,
innerR: size / 2,
spike,
directionX,
directionY,
type: 'star'
}
if (spike === 5) {
obj.fillStyle = this.colorRed
} else {
obj.strokeStyle = color
}
return obj
}
}
export default CanvasShapesBg
|
zxdong262/canvas-shapes-bg
| 1
|
Draw simple shape moving animation in canvas as webpage background
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
babel.config.js
|
JavaScript
|
module.exports = {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "10.10"
}
}
],
"@babel/preset-typescript"
]
}
|
zxdong262/pipedrive-api-client
| 2
|
PipeDrive API wrapper.
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
examples/server.js
|
JavaScript
|
require('dotenv').config()
const express = require('express')
const PipeDrive = require('../dist/pipedrive')
const app = express()
const pd = new PipeDrive({
logger: console,
redirectUri: process.env.REDIRECT_URL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET
})
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.get('/pipedrive-oauth', async function (req, res) {
const { code } = req.query
await pd.authorize(code)
await pd.refresh()
const r = await pd.get('/v1/users/me')
.then(d => d.data)
.catch(console.log)
console.log('user info', r.data)
console.log('user token', pd.token)
// await pd.revoke()
// .catch(console.log)
// console.log('user token after revoke', pd.token)
res.send(
`<div id='result-r'>
${JSON.stringify(r || 'err')}
</div>
<div id='token-r'>
${JSON.stringify(pd.token)}
</div>
`
)
})
app.listen(6066, '127.0.0.1', () => {
console.log('-> server running at 127.0.0.1:6066')
console.log('login url', pd.authorizeUri())
})
|
zxdong262/pipedrive-api-client
| 2
|
PipeDrive API wrapper.
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/pipedrive.ts
|
TypeScript
|
// based on tyler's work: https://github.com/tylerlong/ringcentral-js-concise
import axios, { AxiosInstance } from 'axios'
import { Config, Data, Options, Token, Logger } from './types'
const version = process.env.version
class PipeDriveClient {
token: Token
oauthServer: string
appName: string
version: string | undefined
appVersion: string
_axios: AxiosInstance
userAgentHeader: string
logger?: Logger
host?: string
apiToken?: string
redirectUri?: string
refreshRequest?: any
clientId?: string
clientSecret?: string
static oauthServer = 'https://oauth.pipedrive.com'
constructor (options: Options) {
this.logger = options.logger
this.host = options.host
this.apiToken = options.apiToken
this.redirectUri = options.redirectUri
this.token = options.token || {}
this.clientId = options.clientId
this.clientSecret = options.clientSecret
this.oauthServer = options.oauthServer || PipeDriveClient.oauthServer
this.appName = options.appName || 'Unknown'
this.appVersion = options.appVersion || 'v0.0.1'
this.version = version
this.userAgentHeader = `${this.appName}/${this.appVersion} pipedrive-api-client/${version}`
this._axios = axios.create()
}
request (config: Config) {
let url = config.url.startsWith('http')
? config.url
: (
this.apiToken
? this.host + '/api' + config.url
: this.token.api_domain + config.url
)
if (this.apiToken) {
const sep = url.includes('?')
? '&'
: '?'
const q = sep + 'api_token=' + this.apiToken
url = url + q
}
this.log('request url', url)
const headers = this._patchHeaders(config.headers)
this.log('request headers', headers)
return this._axios.request({
...config,
url,
headers
})
}
log (...logs: any[]) {
if (this.logger) {
this.logger.log(...logs)
}
}
authorizeUri (state: string = '') {
return this.oauthServer +
`/oauth/authorize?client_id=${this.clientId}&state=${state}` +
`&redirect_uri=${encodeURIComponent(this.redirectUri || '')}`
}
oauthUrl () {
return `${this.oauthServer}/oauth/token`
}
async authorize (code: string) {
const data = `grant_type=authorization_code&code=${code}&redirect_uri=${encodeURIComponent(this.redirectUri || '')}`
const url = this.oauthUrl()
this.log('oauth url', url)
const r = await this._axios.request({
method: 'post',
url,
data,
headers: this._basicAuthorizationHeader()
}).then(r => r.data)
Object.assign(
this.token,
r
)
}
async refresh () {
if (!this.token?.refresh_token) {
return
}
if (!this.refreshRequest) {
const data = `grant_type=refresh_token&refresh_token=${this.token.refresh_token}`
this.refreshRequest = this._axios.request({
method: 'post',
url: this.oauthUrl(),
data,
headers: this._basicAuthorizationHeader()
}).then(r => r.data)
}
const r = await this.refreshRequest
Object.assign(
this.token,
r
)
this.refreshRequest = undefined
}
async revoke () {
if (!this.token.access_token) {
return
}
await this._axios.request({
method: 'post',
url: `${this.oauthServer}/oauth/revoke`,
data: `token=${this.token.refresh_token}&token_type_hint=refresh_token`,
headers: this._basicAuthorizationHeader()
})
this.token = {}
return true
}
get (url: string, config = {}) {
return this.request({ ...config, method: 'get', url })
}
delete (url: string, config = {}) {
return this.request({ ...config, method: 'delete', url })
}
post (url: string, data = undefined, config = {}) {
return this.request({ ...config, method: 'post', url, data })
}
put (url: string, data = undefined, config = {}) {
return this.request({ ...config, method: 'put', url, data })
}
/* istanbul ignore next */
patch (url: string, data = undefined, config = {}) {
return this.request({ ...config, method: 'patch', url, data })
}
_patchHeaders (headers: Data = {}) {
return {
'Content-Type': 'application/json',
...this._authHeader(),
'X-User-Agent': this.userAgentHeader,
...headers,
...this._authHeader()
}
}
_authHeader () {
return this.token.access_token
? {
Authorization: `Bearer ${this.token.access_token}`
}
: {
Authorization: ''
}
}
_basicAuthorizationHeader () {
return {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64')}`
}
}
}
module.exports = PipeDriveClient
export default PipeDriveClient
|
zxdong262/pipedrive-api-client
| 2
|
PipeDrive API wrapper.
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/types.ts
|
TypeScript
|
interface TokenBase {
refresh_token?: string,
access_token?: string,
apiToken?: string,
token_type?: string,
scope?: string,
expires_in?: number,
api_domain?: string
}
export interface Token {
[key : string]: any | TokenBase
}
export interface Logger {
log: Function
}
export interface Options {
host?: string,
apiToken?: string,
clientId?: string,
clientSecret?: string,
oauthServer?: string,
redirectUri?: string,
appName?: string,
appVersion?: string,
token?: Token,
logger?: Logger
}
export interface ConfigBase {
url?: string,
headers?: Object
}
export interface Config {
[key : string]: any | ConfigBase
}
export interface Data {
[key : string]: any
}
|
zxdong262/pipedrive-api-client
| 2
|
PipeDrive API wrapper.
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
tests/api-token.spec.js
|
JavaScript
|
/* eslint-env jest */
import PipeDrive from '../src/pipedrive'
const pack = require('../package.json')
jest.setTimeout(64000)
const pd = new PipeDrive({
apiToken: process.env.API_TOKEN,
host: process.env.HOST
})
describe(pack.name, () => {
test('basic', async () => {
const r = await pd.get('/v1/users/me')
.then(d => d.data)
.catch(console.log)
expect(r.success).toBe(true)
const name = 'test contact'
const contact = await pd.post('/v1/persons', {
name
}).then(d => d.data)
expect(contact.data.name).toBe(name)
const newName = 'new name'
const u = await pd.put('/v1/persons/' + contact.data.id, {
name: newName
}).then(d => d.data)
expect(u.data.name).toBe(newName)
const d = await pd.delete(pd.host + '/v1/persons/' + contact.data.id + '?xx=xx').then(d => d.data)
expect(d.data.id).toBe(contact.data.id)
const xx = await pd.get('/v1/users/mexxx?xx=ff')
.catch(err => {
console.log(err)
return 'error'
})
expect(xx).toBe('error')
const ud = await pd.refresh()
expect(ud).toBe(undefined)
const ud1 = await pd.revoke()
expect(ud1).toBe(undefined)
})
})
|
zxdong262/pipedrive-api-client
| 2
|
PipeDrive API wrapper.
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
tests/oauth.spec.js
|
JavaScript
|
/* eslint-env jest */
import PipeDrive from '../src/pipedrive'
import puppeteer from 'puppeteer'
const {
USER,
PASS
} = process.env
const pack = require('../package.json')
jest.setTimeout(64000)
const pd = new PipeDrive({
logger: console,
redirectUri: process.env.REDIRECT_URL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET
})
describe(pack.name, () => {
test('basic', async () => {
const launchOptions = {
headless: false,
args: ['--start-maximized']
}
const browser = await puppeteer.launch(launchOptions)
const page = await browser.newPage()
await page.setViewport({ width: 1366, height: 768 })
await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36')
const url = pd.authorizeUri()
console.log('url', url)
await page.goto(url, {
waitUntil: 'load', timeout: 0
})
const loginSel = '#login'
const passSel = '#password'
await page.waitForSelector('#login')
await page.type(loginSel, USER)
await page.type(passSel, PASS)
await page.click('button.pb-button')
await page.waitForSelector('button.cui5-button--variant-primary')
await page.click('button.cui5-button--variant-primary')
await page.waitForSelector('#result-r')
const text = await page.$eval('#result-r', (e) => e.textContent)
console.log(text)
expect(text.length > 1).toBe(true)
await pd.authorize(text.trim())
await pd.refresh()
const r = await pd.get('/v1/users/me')
.then(d => d.data)
.catch(err => {
console.log(err.stack)
})
expect(r.success).toBe(true)
const rx = await pd.revoke()
expect(rx).toBe(true)
expect(!pd.token.access_token).toBe(true)
await browser.close()
})
})
|
zxdong262/pipedrive-api-client
| 2
|
PipeDrive API wrapper.
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
tests/server.js
|
JavaScript
|
require('dotenv').config()
const express = require('express')
const PipeDrive = require('../dist/pipedrive')
const app = express()
const pd = new PipeDrive({
logger: console,
redirectUri: process.env.REDIRECT_URL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET
})
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.get('/pipedrive-oauth', async function (req, res) {
const { code } = req.query
res.send(
`<div id='result-r'>
${code}
</div>
`
)
})
app.listen(6066, '127.0.0.1', () => {
console.log('-> server running at 127.0.0.1:6066')
console.log('login url', pd.authorizeUri())
})
|
zxdong262/pipedrive-api-client
| 2
|
PipeDrive API wrapper.
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/index.js
|
JavaScript
|
import express from 'express'
import dotenv from 'dotenv'
import auth from './middleware/auth.js'
import { runScript, stopScript, listScripts, getStatus } from './services/taskManager.js'
// 加载环境变量
dotenv.config()
const app = express()
const PORT = process.env.PORT || 3000
const HOST = process.env.HOST || '0.0.0.0'
// 中间件
app.use(express.json())
app.use(auth) // 应用基本认证
// API端点
// 运行脚本
app.post('/api/scripts/run', async (req, res) => {
try {
const { script, args = [], oneTime = false } = req.body
if (!script) {
return res.status(400).json({ error: 'Script path is required' })
}
const result = await runScript(script, args, { oneTime })
res.status(200).json(result)
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// 停止脚本
app.post('/api/scripts/stop/:id', async (req, res) => {
try {
const { id } = req.params
const result = await stopScript(id)
res.status(200).json(result)
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// 列出所有运行中的脚本
app.get('/api/scripts', async (req, res) => {
try {
const scripts = await listScripts()
res.status(200).json(scripts)
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// 获取服务器状态
app.get('/api/status', async (req, res) => {
try {
const status = await getStatus()
res.status(200).json(status)
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// 健康检查
app.get('/health', (req, res) => {
res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() })
})
// 启动服务器
app.listen(PORT, HOST, () => {
console.log(`Task Runner API running on http://${HOST}:${PORT}`)
console.log(`Health check: http://${HOST}:${PORT}/health`)
console.log('API Documentation:')
console.log(' POST /api/scripts/run - Run a new script')
console.log(' Body: { script, args?, oneTime? }')
console.log(' - oneTime: run synchronously and return result (not tracked)')
console.log(' - default: run asynchronously (tracked)')
console.log(' POST /api/scripts/stop/:id - Stop a running script')
console.log(' GET /api/scripts - List all running scripts')
console.log(' GET /api/status - Get server status')
})
// 优雅关闭
process.on('SIGINT', () => {
console.log('Server shutting down...')
process.exit(0)
})
process.on('SIGTERM', () => {
console.log('Server shutting down...')
process.exit(0)
})
|
zxdong262/task-runner
| 1
|
A simple web server that can run/stop tasks
|
JavaScript
|
zxdong262
|
ZHAO Xudong
| |
src/middleware/auth.js
|
JavaScript
|
import basicAuth from 'basic-auth'
/**
* 基本认证中间件
* 验证请求的用户凭据是否与环境变量中配置的匹配
*/
const auth = (req, res, next) => {
const credentials = basicAuth(req)
// 获取环境变量中的认证信息
const expectedUser = process.env.AUTH_USER || 'admin'
const expectedPassword = process.env.AUTH_PASSWORD || 'password'
// 检查凭据是否提供且匹配
if (!credentials ||
credentials.name !== expectedUser ||
credentials.pass !== expectedPassword) {
// 设置WWW-Authenticate头,要求基本认证
res.set('WWW-Authenticate', 'Basic realm="Task Runner API"')
// 返回401未授权状态
return res.status(401).json({
error: 'Authentication required',
message: 'Please provide valid username and password'
})
}
// 认证成功,继续处理请求
next()
}
export default auth
|
zxdong262/task-runner
| 1
|
A simple web server that can run/stop tasks
|
JavaScript
|
zxdong262
|
ZHAO Xudong
| |
src/services/taskManager.js
|
JavaScript
|
import { spawn } from 'child_process'
import { randomUUID } from 'crypto'
import { cwd } from 'process'
// import { resolve } from 'path'
// 存储运行中的脚本进程
const runningScripts = new Map()
/**
* 运行本地脚本
* @param {string} scriptPath - 脚本路径
* @param {string[]} args - 脚本参数
* @param {Object} options - 运行选项
* @param {boolean} options.oneTime - 是否启动后立即返回,让子进程独立运行(一次性运行,不追踪)
* @returns {Promise<Object>} 运行结果信息
*/
export const runScript = async (scriptPath, args = [], options = {}) => {
console.log(`Running script: ${scriptPath} with args: ${args.join(' ')} (oneTime: ${options.oneTime || false})`)
const { oneTime = false } = options
console.log('Starting runScript execution')
return new Promise((resolve) => {
try {
// 生成唯一ID
const id = randomUUID()
// 获取当前工作目录
const workingDir = cwd()
// 解析脚本路径为绝对路径
// const absoluteScriptPath = resolve(workingDir, scriptPath)
console.log('Working dir:', workingDir)
console.log('Script path:', scriptPath)
// console.log('Absolute script path:', absoluteScriptPath)
// 记录开始时间
const startTime = new Date()
// 根据文件扩展名决定如何运行脚本
let command, commandArgs
if (scriptPath.endsWith('.js')) {
// Node.js 脚本
command = 'node'
commandArgs = [scriptPath, ...args]
} else if (scriptPath.endsWith('.bat')) {
// Windows 批处理文件
command = 'cmd'
commandArgs = ['/c', scriptPath, ...args]
} else {
// 其他脚本类型,尝试直接执行
command = scriptPath
commandArgs = args
}
console.log('Command:', command)
console.log('Command args:', commandArgs)
console.log('About to spawn process')
const childProcess = spawn(command, commandArgs, {
cwd: workingDir,
stdio: ['pipe', 'pipe', 'pipe'],
detached: oneTime, // 一次性运行时分离
env: process.env
})
console.log('Spawn successful, child PID:', childProcess.pid)
// 存储输出日志
const stdout = []
const stderr = []
// 同步运行模式:启动进程后立即返回,让子进程独立运行
if (oneTime) {
// 收集标准输出(可选,用于调试)
childProcess.stdout.on('data', (data) => {
console.log(`[oneTime:${id}] STDOUT: ${data.toString().trim()}`)
})
// 收集错误输出(可选,用于调试)
childProcess.stderr.on('data', (data) => {
console.error(`[oneTime:${id}] STDERR: ${data.toString().trim()}`)
})
// 可选:监听进程退出(仅用于日志,不阻塞)
childProcess.on('close', (code) => {
console.log(`[oneTime:${id}] Script completed with exit code ${code}`)
})
// 立即返回,让子进程独立运行
resolve({
success: true,
id,
mode: 'oneTime',
message: 'Script started and will run independently',
details: {
pid: childProcess.pid,
scriptPath,
args,
startTime: startTime.toISOString(),
note: 'Process detached and running independently'
}
})
return
}
// 异步跟踪模式:启动后立即返回,可被追踪和停止
// 收集标准输出
childProcess.stdout.on('data', (data) => {
const output = data.toString()
stdout.push(output)
console.log(`[${id}] STDOUT: ${output.trim()}`)
})
// 收集错误输出
childProcess.stderr.on('data', (data) => {
const output = data.toString()
stderr.push(output)
console.error(`[${id}] STDERR: ${output.trim()}`)
})
// 处理进程退出
childProcess.on('close', (code) => {
console.log(`[${id}] Script exited with code ${code}`)
// 更新脚本状态
if (runningScripts.has(id)) {
const scriptInfo = runningScripts.get(id)
scriptInfo.status = 'completed'
scriptInfo.exitCode = code
scriptInfo.endTime = new Date()
scriptInfo.duration = scriptInfo.endTime - scriptInfo.startTime
// 移除已完成的脚本
setTimeout(() => {
if (runningScripts.has(id) && runningScripts.get(id).status === 'completed') {
runningScripts.delete(id)
}
}, 60000) // 1分钟后清理已完成的脚本记录
}
})
// 存储脚本信息
const scriptInfo = {
id,
scriptPath,
args,
pid: childProcess.pid,
startTime,
status: 'running',
workingDir,
stdout,
stderr,
mode: 'tracked'
}
runningScripts.set(id, scriptInfo)
resolve({
success: true,
id,
mode: 'tracked',
message: 'Script started successfully',
details: {
pid: childProcess.pid,
scriptPath,
args,
startTime: startTime.toISOString(),
note: 'This process will be tracked'
}
})
} catch (error) {
console.error('Error running script:', error)
console.error('Error message:', error.message)
console.error('Error stack:', error.stack)
resolve({
success: false,
error: error.message || 'Unknown error',
message: 'Failed to start script'
})
}
})
}
/**
* 停止正在运行的脚本
* @param {string} id - 脚本ID
* @returns {Promise<Object>} 停止结果
*/
export const stopScript = async (id) => {
try {
if (!runningScripts.has(id)) {
return {
success: false,
error: 'Script not found',
message: 'No running script with the specified ID'
}
}
const scriptInfo = runningScripts.get(id)
if (scriptInfo.status !== 'running') {
return {
success: false,
error: 'Script not running',
message: `Script is in ${scriptInfo.status} state`
}
}
// 尝试终止进程
try {
if (process.platform === 'win32') {
// On Windows, use taskkill with /t to kill process tree
const { spawn } = await import('child_process')
const taskkill = spawn('taskkill', ['/pid', scriptInfo.pid.toString(), '/t', '/f'], {
stdio: 'inherit'
})
await new Promise((resolve, reject) => {
taskkill.on('close', (code) => {
// taskkill returns 0 for success, 128 for process not found (already dead)
if (code === 0 || code === 128) {
resolve()
} else {
reject(new Error(`taskkill failed with code ${code}`))
}
})
taskkill.on('error', (error) => {
// If process doesn't exist, that's fine
if (error.code === 'ENOENT' || error.message.includes('not found')) {
resolve()
} else {
reject(error)
}
})
})
} else {
// On Unix-like systems, use SIGTERM
process.kill(scriptInfo.pid, 'SIGTERM')
}
} catch (killError) {
console.error('Error killing process:', killError)
// Continue with status update even if kill failed
}
// 更新脚本状态
scriptInfo.status = 'stopped'
scriptInfo.endTime = new Date()
scriptInfo.duration = scriptInfo.endTime - scriptInfo.startTime
// 从运行列表中移除
setTimeout(() => {
runningScripts.delete(id)
}, 5000)
return {
success: true,
message: 'Script stopped successfully',
id,
details: {
pid: scriptInfo.pid,
stopTime: scriptInfo.endTime.toISOString(),
duration: scriptInfo.duration
}
}
} catch (error) {
console.error('Error stopping script:', error)
return {
success: false,
error: error.message,
message: 'Failed to stop script'
}
}
}
/**
* 列出所有正在运行的脚本
* @returns {Promise<Array>} 运行中脚本列表
*/
export const listScripts = async () => {
const scripts = []
runningScripts.forEach((scriptInfo) => {
scripts.push({
id: scriptInfo.id,
scriptPath: scriptInfo.scriptPath,
args: scriptInfo.args,
pid: scriptInfo.pid,
status: scriptInfo.status,
startTime: scriptInfo.startTime.toISOString(),
endTime: scriptInfo.endTime ? scriptInfo.endTime.toISOString() : null,
duration: scriptInfo.duration || null,
workingDir: scriptInfo.workingDir
})
})
return {
success: true,
count: scripts.length,
scripts
}
}
/**
* 获取服务器状态信息
* @returns {Promise<Object>} 服务器状态
*/
export const getStatus = async () => {
// 获取系统内存使用情况(简化版本)
const memoryUsage = process.memoryUsage()
// 统计不同状态的脚本数量
const statusCount = {
running: 0,
completed: 0,
stopped: 0
}
runningScripts.forEach((scriptInfo) => {
if (Object.prototype.hasOwnProperty.call(statusCount, scriptInfo.status)) {
statusCount[scriptInfo.status]++
}
})
return {
success: true,
server: {
uptime: process.uptime(),
timestamp: new Date().toISOString(),
nodeVersion: process.version,
platform: process.platform,
arch: process.arch
},
memory: {
rss: memoryUsage.rss,
heapTotal: memoryUsage.heapTotal,
heapUsed: memoryUsage.heapUsed,
external: memoryUsage.external
},
tasks: {
total: runningScripts.size,
...statusCount
}
}
}
|
zxdong262/task-runner
| 1
|
A simple web server that can run/stop tasks
|
JavaScript
|
zxdong262
|
ZHAO Xudong
| |
tests/services/taskManager.test.js
|
JavaScript
|
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { runScript, stopScript, listScripts, getStatus } from '../../src/services/taskManager.js'
import { spawn } from 'child_process'
// 模拟child_process
vi.mock('child_process', () => {
const mockProcess = {
pid: 1234,
stdout: {
on: vi.fn((event, callback) => {
if (event === 'data') {
setTimeout(() => callback(Buffer.from('Test output')), 10)
}
})
},
stderr: {
on: vi.fn()
},
on: vi.fn((event, callback) => {
if (event === 'close') {
// For oneTime mode, trigger close immediately
const exitCode = 0
setTimeout(() => {
callback(exitCode)
}, 10)
}
}),
kill: vi.fn().mockReturnValue(true),
unref: vi.fn()
}
return {
spawn: vi.fn().mockReturnValue(mockProcess)
}
})
vi.mock('crypto', () => ({
randomUUID: vi.fn().mockReturnValue('test-uuid-123')
}))
describe('Task Manager', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
vi.resetAllMocks()
})
describe('runScript', () => {
it('should run a script successfully', async () => {
const result = await runScript('./tests/test-script.js', ['arg1'])
expect(result.success).toBe(true)
expect(result.id).toBe('test-uuid-123')
expect(spawn).toHaveBeenCalledWith('node', ['./tests/test-script.js', 'arg1'], expect.any(Object))
})
it('should run a script in oneTime mode', async () => {
// Mock a simple process that exits immediately for oneTime testing
const mockProcess = {
pid: 1234,
stdout: {
on: vi.fn((event, callback) => {
if (event === 'data') {
setTimeout(() => callback(Buffer.from('OneTime test output')), 10)
}
})
},
stderr: {
on: vi.fn((event, callback) => {
if (event === 'data') {
setTimeout(() => callback(Buffer.from('OneTime test error')), 10)
}
})
},
on: vi.fn((event, callback) => {
if (event === 'close') {
const exitCode = 42
setTimeout(() => {
callback(exitCode)
}, 10)
}
}),
kill: vi.fn().mockReturnValue(true),
unref: vi.fn()
}
spawn.mockReturnValueOnce(mockProcess)
const result = await runScript('./tests/test-one-time.js', ['arg1'], { oneTime: true })
expect(result.success).toBe(true)
expect(result.mode).toBe('oneTime')
expect(result.exitCode).toBe(42)
expect(result.output).toContain('OneTime test output')
expect(result.error).toContain('OneTime test error')
expect(spawn).toHaveBeenCalledWith('node', ['./tests/test-one-time.js', 'arg1'], expect.objectContaining({ detached: true }))
})
it('should handle script errors gracefully', async () => {
spawn.mockImplementationOnce(() => {
throw new Error('Spawn error')
})
const result = await runScript('./invalid.js')
expect(result.success).toBe(false)
expect(result.error).toBe('Spawn error')
})
})
describe('listScripts', () => {
it('should list running scripts', async () => {
// 先运行一个脚本
await runScript('./tests/test-script.js')
const result = await listScripts()
expect(result.success).toBe(true)
expect(result.count).toBeGreaterThan(0)
expect(result.scripts).toBeInstanceOf(Array)
})
it('should return empty list when no scripts are running', async () => {
// 注意:这会测试当前状态,可能受之前测试影响
const result = await listScripts()
expect(result.success).toBe(true)
expect(Array.isArray(result.scripts)).toBe(true)
})
})
describe('getStatus', () => {
it('should return server status information', async () => {
const result = await getStatus()
expect(result.success).toBe(true)
expect(result.server).toHaveProperty('uptime')
expect(result.server).toHaveProperty('timestamp')
expect(result.memory).toHaveProperty('rss')
expect(result.tasks).toHaveProperty('total')
})
})
describe('stopScript', () => {
it('should attempt to stop a running script', async () => {
// 先运行一个脚本获取ID
const runResult = await runScript('./tests/test-script.js')
const stopResult = await stopScript(runResult.id)
// 在测试环境中,我们只验证调用了正确的方法,不关心实际结果
expect(stopResult).toBeTruthy()
expect(stopResult.id).toBe(runResult.id)
})
it('should return error for non-existent script', async () => {
const result = await stopScript('non-existent-id')
expect(result.success).toBe(false)
expect(result.error).toBe('Script not found')
})
})
})
|
zxdong262/task-runner
| 1
|
A simple web server that can run/stop tasks
|
JavaScript
|
zxdong262
|
ZHAO Xudong
| |
tests/setup.js
|
JavaScript
|
// 测试环境设置
import { beforeAll, afterAll } from 'vitest'
// 模拟环境变量
process.env.AUTH_USER = 'test_user'
process.env.AUTH_PASSWORD = 'test_password'
process.env.PORT = '3001'
// 在所有测试之前执行
beforeAll(() => {
console.log('Test environment setup')
})
// 在所有测试之后执行
afterAll(() => {
console.log('Test environment teardown')
})
|
zxdong262/task-runner
| 1
|
A simple web server that can run/stop tasks
|
JavaScript
|
zxdong262
|
ZHAO Xudong
| |
tests/test-one-time.js
|
JavaScript
|
#!/usr/bin/env node
// Test script for oneTime execution mode
// This script runs synchronously and returns results
console.log('OneTime test script started!')
console.log('Arguments:', process.argv.slice(2))
// Output some test data
console.log('Test output line 1')
console.error('Test error line 1')
// Simulate some processing
setTimeout(() => {
console.log('Processing complete')
console.log('Exit code: 42')
// Exit with a specific code for testing
process.exit(42)
}, 100)
|
zxdong262/task-runner
| 1
|
A simple web server that can run/stop tasks
|
JavaScript
|
zxdong262
|
ZHAO Xudong
| |
tests/test-script.js
|
JavaScript
|
#!/usr/bin/env node
// 简单的测试脚本,用于演示任务运行器功能
console.log('Test script started!')
console.log('Arguments:', process.argv.slice(2))
// 输出当前环境信息
console.log('Current directory:', process.cwd())
console.log('Node version:', process.version)
console.log('Platform:', process.platform)
// 模拟一些工作
let counter = 0
const interval = setInterval(() => {
counter++
console.log(`Working... iteration ${counter}`)
// 每5秒输出一些信息
if (counter % 5 === 0) {
console.log(`Progress update: ${counter} seconds completed`)
}
// 模拟30秒后完成
if (counter >= 30) {
clearInterval(interval)
console.log('Test script completed successfully!')
console.log('Total iterations:', counter)
process.exit(0)
}
}, 1000)
// 处理信号
process.on('SIGTERM', () => {
console.log('Received SIGTERM, shutting down gracefully...')
clearInterval(interval)
console.log(`Script stopped after ${counter} iterations`)
process.exit(0)
})
process.on('SIGINT', () => {
console.log('Received SIGINT, shutting down gracefully...')
clearInterval(interval)
console.log(`Script stopped after ${counter} iterations`)
process.exit(0)
})
// 设置超时保护
setTimeout(() => {
console.error('Script timed out after 60 seconds!')
process.exit(1)
}, 60000)
console.log('Test script is running. Press Ctrl+C to stop.')
|
zxdong262/task-runner
| 1
|
A simple web server that can run/stop tasks
|
JavaScript
|
zxdong262
|
ZHAO Xudong
| |
vite.config.js
|
JavaScript
|
import { defineConfig } from 'vite'
import { fileURLToPath, URL } from 'node:url'
export default defineConfig({
test: {
environment: 'node',
globals: true,
setupFiles: ['./tests/setup.js'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html']
}
},
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
|
zxdong262/task-runner
| 1
|
A simple web server that can run/stop tasks
|
JavaScript
|
zxdong262
|
ZHAO Xudong
| |
bin/vite.config.js
|
JavaScript
|
import { defineConfig } from 'vite'
export default defineConfig({
build: {
emptyOutDir: true, // This will clean dist/ before building
lib: {
entry: 'src/zmodem.ts',
formats: ['es', 'cjs'],
fileName: (format) => `zmodem.${format === 'es' ? 'js' : 'cjs'}`
},
outDir: 'dist',
rollupOptions: {
output: [
{
format: 'es',
entryFileNames: 'zmodem.js'
},
{
format: 'cjs',
entryFileNames: 'zmodem.cjs',
exports: 'default'
}
]
}
}
})
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
examples/addon-zmodem.jsx
|
JavaScript (JSX)
|
import Sentry from 'zmodem-ts/dist/zsentry'
// or
// import Sentry from 'zmodem-ts/esm/zsentry.mjs'
// a xtermjs addon example
export class AddonZmodem {
_disposables = []
activate (terminal) {
terminal.zmodemAttach = this.zmodemAttach
}
sendWebSocket = (octets) => {
const { socket } = this
if (socket && socket.readyState === WebSocket.OPEN) {
return socket.send(new Uint8Array(octets))
} else {
console.error('WebSocket is not open')
}
}
zmodemAttach = (ctx) => {
this.socket = ctx.socket
this.term = ctx.term
this.ctx = ctx
this.zsentry = new Sentry({
to_terminal: (octets) => {
if (ctx.onZmodem) {
this.term.write(String.fromCharCode.apply(String, octets))
}
},
sender: this.sendWebSocket,
on_retract: ctx.onzmodemRetract,
on_detect: ctx.onZmodemDetect
})
this.socket.binaryType = 'arraybuffer'
this.socket.addEventListener('message', this.handleWSMessage)
}
handleWSMessage = (evt) => {
if (typeof evt.data === 'string') {
if (this.ctx.onZmodem) {
this.term.write(evt.data)
}
} else {
this.zsentry.consume(evt.data)
}
}
dispose = () => {
this.socket && this.socket.removeEventListener('message', this.handleWSMessage)
this._disposables.forEach(d => d.dispose())
this._disposables.length = 0
this.term = null
this.zsentry = null
this.socket = null
}
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
examples/terminal.jsx
|
JavaScript (JSX)
|
import AttachAddon from './addon-zmodem'
export class Term extends Component {
componentDidMount () {
this.zmodemAddon = new AddonZmodem()
term.loadAddon(this.zmodemAddon)
}
onzmodemRetract = () => {
log.debug('zmodemRetract')
}
writeBanner = (type) => {
this.term.write(`\x1b[32mZMODEM::${type}::START\x1b[0m\r\n\r\n`)
}
onReceiveZmodemSession = async () => {
const savePath = await this.openSaveFolderSelect()
this.zsession.on('offer', this.onOfferReceive)
this.zsession.start()
this.term.write('\r\n\x1b[2A\r\n')
if (!savePath) {
return this.onZmodemEnd()
}
this.writeBanner('RECEIVE')
this.zmodemSavePath = savePath
return new Promise((resolve) => {
this.zsession.on('session_end', resolve)
})
.then(this.onZmodemEnd)
.catch(this.onZmodemCatch)
}
initZmodemDownload = async (name, size) => {
if (!this.zmodemSavePath) {
return
}
let pth = window.pre.resolve(
this.zmodemSavePath, name
)
const exist = await fs.exists(pth).catch(() => false)
if (exist) {
pth = pth + '.' + generate()
}
const fd = await fs.open(pth, 'w').catch(this.onZmodemEnd)
this.downloadFd = fd
this.downloadPath = pth
this.downloadCount = 0
this.zmodemStartTime = Date.now()
this.downloadSize = size
this.updateZmodemProgress(
0, pth, size, transferTypeMap.download
)
return fd
}
onOfferReceive = async (xfer) => {
const {
name,
size
} = xfer.get_details()
if (!this.downloadFd) {
await this.initZmodemDownload(name, size)
}
xfer.on('input', this.onZmodemDownload)
this.xfer = xfer
await xfer.accept()
.then(this.finishZmodemTransfer)
.catch(this.onZmodemEnd)
}
onZmodemDownload = async payload => {
console.log('onZmodemDownload', payload)
if (this.onCanceling || !this.downloadFd) {
return
}
this.downloadCount += payload.length
await fs.write(this.downloadFd, new Uint8Array(payload))
this.updateZmodemProgress(
this.downloadCount,
this.downloadPath,
this.downloadSize,
transferTypeMap.download
)
}
updateZmodemProgress = throttle((start, name, size, type) => {
this.zmodemTransfer = {
type,
start,
name,
size
}
this.writeZmodemProgress()
}, 500)
finishZmodemTransfer = () => {
this.zmodemTransfer = {
...this.zmodemTransfer,
start: this.zmodemTransfer.size
}
this.writeZmodemProgress()
}
writeZmodemProgress = () => {
if (this.onCanceling) {
return
}
const {
size, start, name
} = this.zmodemTransfer
const speed = size > 0 ? formatBytes(start * 1000 / 1024 / (Date.now() - this.zmodemStartTime)) : 0
const percent = size > 0 ? Math.floor(start * 100 / size) : 100
const str = `\x1b[32m${name}\x1b[0m::${percent}%,${start}/${size},${speed}/s`
this.term.write('\r\n\x1b[2A' + str + '\n')
}
zmodemTransferFile = async (file, filesRemaining, sizeRemaining) => {
const offer = {
obj: file,
name: file.name,
size: file.size,
files_remaining: filesRemaining,
bytes_remaining: sizeRemaining
}
const xfer = await this.zsession.send_offer(offer)
if (!xfer) {
this.onZmodemEnd()
return window.store.onError(new Error('Transfer cancelled, maybe file already exists'))
}
this.zmodemStartTime = Date.now()
const fd = await fs.open(file.filePath, 'r')
let start = 0
const { size } = file
let inited = false
while (start < size || !inited) {
const rest = size - start
const len = rest > zmodemTransferPackSize ? zmodemTransferPackSize : rest
const buffer = new Uint8Array(len)
const newArr = await fs.read(fd, buffer, 0, len, null)
const n = newArr.length
await xfer.send(newArr)
start = start + n
inited = true
this.updateZmodemProgress(start, file.name, size, transferTypeMap.upload)
if (n < zmodemTransferPackSize || start >= file.size || this.onCanceling) {
break
}
}
await fs.close(fd)
this.finishZmodemTransfer()
await xfer.end()
}
openFileSelect = async () => {
const properties = [
'openFile',
'multiSelections',
'showHiddenFiles',
'noResolveAliases',
'treatPackageAsDirectory',
'dontAddToRecent'
]
const files = await window.api.openDialog({
title: 'Choose some files to send',
message: 'Choose some files to send',
properties
}).catch(() => false)
if (!files || !files.length) {
return this.onZmodemEnd()
}
const r = []
for (const filePath of files) {
const stat = await getLocalFileInfo(filePath)
r.push({ ...stat, filePath })
}
return r
}
openSaveFolderSelect = async () => {
const savePaths = await window.api.openDialog({
title: 'Choose a folder to save file(s)',
message: 'Choose a folder to save file(s)',
properties: [
'openDirectory',
'showHiddenFiles',
'createDirectory',
'noResolveAliases',
'treatPackageAsDirectory',
'dontAddToRecent'
]
}).catch(() => false)
if (!savePaths || !savePaths.length) {
return false
}
return savePaths[0]
}
beforeZmodemUpload = async (files) => {
if (!files || !files.length) {
return false
}
this.writeBanner('SEND')
let filesRemaining = files.length
let sizeRemaining = files.reduce((a, b) => a + b.size, 0)
for (const f of files) {
await this.zmodemTransferFile(f, filesRemaining, sizeRemaining)
filesRemaining = filesRemaining - 1
sizeRemaining = sizeRemaining - f.size
}
this.onZmodemEnd()
}
onSendZmodemSession = async () => {
this.term.write('\r\n\x1b[2A\n')
const files = await this.openFileSelect()
this.beforeZmodemUpload(files)
}
onZmodemEnd = async () => {
delete this.zmodemSavePath
this.onCanceling = true
if (this.downloadFd) {
await fs.close(this.downloadFd)
}
if (this.xfer && this.xfer.end) {
await this.xfer.end().catch(
console.error
)
}
delete this.xfer
if (this.zsession && this.zsession.close) {
await this.zsession.close().catch(
console.error
)
}
delete this.zsession
this.term.focus()
this.term.write('\r\n')
this.onZmodem = false
delete this.downloadFd
delete this.downloadPath
delete this.downloadCount
delete this.downloadSize
delete this.DownloadCache
}
onZmodemCatch = (e) => {
this.onZmodemEnd()
}
onZmodemDetect = detection => {
this.onCanceling = false
this.term.blur()
this.onZmodem = true
const zsession = detection.confirm()
this.zsession = zsession
if (zsession.type === 'receive') {
this.onReceiveZmodemSession()
} else {
this.onSendZmodemSession()
}
}
render () {
return null
}
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
jest.config.cjs
|
JavaScript
|
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: [
'./tests'
],
silent: false
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/encode.ts
|
TypeScript
|
import { N } from './types'
const HEX_DIGITS: number[] = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102]
const HEX_OCTET_VALUE: N = {}
for (let hd = 0; hd < HEX_DIGITS.length; hd++) {
HEX_OCTET_VALUE[HEX_DIGITS[hd]] = hd
}
export const ZmodemEncodeLib = {
/**
* Pack a 16-bit number to big-endian format.
*
* @param {number} number - The number to pack.
*
* @returns {number[]} The packed values.
*/
pack_u16_be (number: number): number[] {
if (number > 0xffff) throw new Error(`Number cannot exceed 16 bits: ${number}`)
return [number >> 8, number & 0xff]
},
/**
* Pack a 32-bit number to little-endian format.
*
* @param {number} number - The number to pack.
*
* @returns {number[]} The packed values.
*/
pack_u32_le (number: number): number[] {
const highBytes = number / 65536
return [
number & 0xff,
(number & 65535) >> (8),
highBytes & 0xff,
highBytes >> (8)
]
},
/**
* Unpack a big-endian 16-bit number.
*
* @param {number[]} bytesArr - An array with two 8-bit numbers.
*
* @returns {number} The unpacked value.
*/
unpack_u16_be (bytesArr: number[]): number {
return (bytesArr[0] << (8)) + bytesArr[1]
},
/**
* Unpack a little-endian 32-bit number.
*
* @param {number[]} octets - An array with four 8-bit numbers.
*
* @returns {number} The unpacked value.
*/
unpack_u32_le (octets: number[]): number {
return octets[0] + (octets[1] << 8) + (octets[2] << 16) + (octets[3] * 16777216)
},
/**
* Convert a series of octets to their hex
* representation.
*
* @param {number[]} octets - The octet values.
*
* @returns {number[]} The hex values of the octets.
*/
octets_to_hex (octets: number[]): number[] {
const hex: number[] = []
for (let o = 0; o < octets.length; o++) {
hex.push(
(HEX_DIGITS[octets[o] >> 4]) as never,
HEX_DIGITS[octets[o] & 0x0f] as never
)
}
return hex
},
/**
* The inverse of octets_to_hex(): takes an array
* of hex octet pairs and returns their octet values.
*
* @param {number[]} hex_octets - The hex octet values.
*
* @returns {number[]} The parsed octet values.
*/
parse_hex_octets (hexOctets: number[]): number[] {
const octets = new Array(hexOctets.length / 2)
for (let i = 0; i < octets.length; i++) {
octets[i] = (HEX_OCTET_VALUE[hexOctets[2 * i]] << 4) + HEX_OCTET_VALUE[hexOctets[1 + 2 * i]]
}
return octets
}
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/eventer.ts
|
TypeScript
|
import { Obj } from './types'
class _Eventer {
_on_evt: Obj = {}
_evt_once_index: Obj = {}
// Private method to initialize event queue and once index
_Add_event (evtName: string): void {
this._on_evt[evtName] = []
this._evt_once_index[evtName] = []
}
// Private method to get the event queue, throwing if it doesn't exist
_get_evt_queue (evtName: string): any[] {
if (typeof this._on_evt[evtName] === 'undefined') {
throw new Error(`Bad event: ${evtName}`)
}
return this._on_evt[evtName]
}
/**
* Register a callback for a given event.
*
* @param evtName The name of the event.
* @param todo The function to execute when the event happens.
*/
on (evtName: string, todo: Function): _Eventer {
const queue = this._get_evt_queue(evtName)
queue.push(todo)
return this
}
/**
* Unregister a callback for a given event.
*
* @param evtName The name of the event.
* @param todo The function to unregister, if provided.
*/
off (evtName: string, todo?: Function): _Eventer {
const queue = this._get_evt_queue(evtName)
if (todo !== undefined) {
const at = queue.indexOf(todo)
if (at === -1) {
throw new Error(`"${todo.name}" is not in the "${evtName}" queue.`)
}
queue.splice(at, 1)
} else {
queue.pop()
}
return this
}
// Private method to trigger the event and call all registered callbacks
_Happen (evtName: string, ...args: any[]): number {
const queue = this._get_evt_queue(evtName) // Validate here if needed
queue.forEach((cb: Function) => {
cb.apply(this, args)
})
return queue.length
}
}
export default _Eventer
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/offer.ts
|
TypeScript
|
import _Eventer from './eventer'
import { Opts, Obj } from './types'
import ZmodemError from './zerror'
import { transferOfferDecorator } from './transfer-offer-mixin'
const DEFAULT_RECEIVE_INPUT_MODE = 'spool_uint8array'
/**
* A class to represent a receiver’s interaction with a single file
* transfer offer within a batch. There is functionality here to
* skip or accept offered files and either to spool the packet
* payloads or to handle them yourself.
*/
class Offer extends transferOfferDecorator(_Eventer) {
_zfile_opts: any
_file_info: any
_accept_func: Function
_skip_func: Function
_skipped: boolean = false
_accepted: boolean = false
_file_offset: number = 0
_spool: any
_input_handler_mode: string | Function = ''
/**
* Not called directly.
*/
constructor (
zfileOpts: Obj,
fileInfo: Obj,
acceptFunc: Function,
skipFunc: Function
) {
super()
this._zfile_opts = zfileOpts
this._file_info = fileInfo
this._accept_func = acceptFunc
this._skip_func = skipFunc
this._Add_event('input')
this._Add_event('complete')
// Register this first so that application handlers receive
// the updated offset.
this.on('input', this._input_handler)
}
_verify_not_skipped (): void {
if (this._skipped) {
throw new ZmodemError('Already skipped!') // ??
}
}
/**
* Tell the sender that you don’t want the offered file.
*
* You can send this in lieu of `accept()` or after it, e.g.,
* if you find that the transfer is taking too long. Note that,
* if you `skip()` after you `accept()`, you’ll likely have to
* wait for buffers to clear out.
*
*/
skip (...args: any[]): any {
this._verify_not_skipped()
this._skipped = true
return this._skip_func.apply(this, args)
}
/**
* Tell the sender to send the offered file.
*
* @param {Object} [opts] - Can be:
* @param {string} [opts.oninput=spool_uint8array] - Can be:
*
* - `spool_uint8array`: Stores the ZMODEM
* packet payloads as Uint8Array instances.
* This makes for an easy transition to a Blob,
* which JavaScript can use to save the file to disk.
*
* - `spool_array`: Stores the ZMODEM packet payloads
* as Array instances. Each value is an octet value.
*
* - (function): A handler that receives each payload
* as it arrives. The Offer object does not store
* the payloads internally when thus configured.
*
* @return { Promise } Resolves when the file is fully received.
* If the Offer has been spooling
* the packet payloads, the promise resolves with an Array
* that contains those payloads.
*/
async accept (opts: Opts = {}): Promise<any> {
this._verify_not_skipped()
if (this._accepted) {
throw new ZmodemError('Already accepted!')
}
this._accepted = true
this._file_offset = opts.offset ?? 0
switch (opts.on_input) {
case null:
case undefined:
case 'spool_array':
case DEFAULT_RECEIVE_INPUT_MODE: // default
this._spool = []
break
default:
if (typeof opts.on_input !== 'function') {
throw new Error('Invalid “on_input”: ' + opts.on_input)
}
}
this._input_handler_mode = opts.on_input ?? DEFAULT_RECEIVE_INPUT_MODE
return this._accept_func(this._file_offset).then(this._get_spool.bind(this))
}
_input_handler (payload: any): void {
this._file_offset += payload.length as number
if (typeof this._input_handler_mode === 'function') {
this._input_handler_mode(payload)
} else {
if (this._input_handler_mode === DEFAULT_RECEIVE_INPUT_MODE) {
payload = new Uint8Array(payload)
} else if (this._input_handler_mode !== 'spool_array') {
throw new ZmodemError(`WTF?? _input_handler_mode = ${this._input_handler_mode}`)
}
this._spool.push(payload)
}
}
_get_spool (): any {
return this._spool
}
}
export default Offer
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/transfer-offer-mixin.ts
|
TypeScript
|
import { Obj } from './types'
export function transferOfferDecorator<T extends new (...args: any[]) => any> (target: T): T {
return class extends target {
get_details (): Obj {
return Object.assign({}, this._file_info)
}
get_options (): Obj {
return Object.assign({}, this._zfile_opts)
}
get_offset (): number {
return this._file_offset
}
}
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/transfer.ts
|
TypeScript
|
import { Obj } from './types'
import { transferOfferDecorator } from './transfer-offer-mixin'
/**
* A class to represent a receiver’s interaction with a single file
* transfer offer within a batch. There is functionality here to
* skip or accept offered files and either to spool the packet
* payloads or to handle them yourself.
*/
class Transfer extends transferOfferDecorator(Object) {
_file_info: Obj
_file_offset: number
_send: Function
_end: Function
/**
* Not called directly.
*/
constructor (
fileInfo: Obj,
offset: number,
sendFunc: Function,
endFunc: Function
) {
super()
this._file_info = fileInfo
this._file_offset = offset ?? 0
this._send = sendFunc
this._end = endFunc
}
/**
* Send a (non-terminal) piece of the file.
*
* @param { number[] | Uint8Array } arrayLike - The bytes to send.
*/
send (arrayLike: number[] | Uint8Array): void {
this._send(arrayLike)
this._file_offset += arrayLike.length
}
/**
* Complete the file transfer.
*
* @param { number[] | Uint8Array } [arrayLike] - The last bytes to send.
*
* @return { Promise } Resolves when the receiver has indicated
* acceptance of the end of the file transfer.
*/
async end (arrayLike: number[] | Uint8Array | undefined): Promise<any> {
const ret = this._end(arrayLike ?? [])
if (arrayLike !== undefined) {
this._file_offset += arrayLike.length
}
return ret
}
}
export default Transfer
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/types.ts
|
TypeScript
|
export interface Obj {
[key: string]: any
}
export interface FlagType {
[key: string]: number
}
export interface N {
[key: number]: number
}
export interface Opts {
offset?: number
on_input?: string
}
export interface ZDLEConfig {
escape_ctrl_chars: boolean
turbo_escape: boolean
}
export interface SentryOpts {
to_terminal: Function
on_detect: Function
on_retract: Function
sender: Function
}
export interface ValidateParams {
name: string
serial?: any
size?: number
mode?: number
files_remaining?: number
bytes_remaining?: number
mtime?: number | Date
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zcrc.ts
|
TypeScript
|
import { buf } from 'crc-32'
import { ZmodemEncodeLib } from './encode'
import ZmodemError from './zerror'
type OctetNumbers = number[]
const crcWidth = 16
const crcPolynomial = 0x1021
const crcCastMask = 0xffff
const crcMsbmask = 1 << (crcWidth - 1)
function computeCrcTab (): number[] {
const crcTab = new Array(256)
const divideShift = crcWidth - 8
for (let divide = 0; divide < 256; divide++) {
let currByte = (divide << divideShift) & crcCastMask
for (let bit = 0; bit < 8; bit++) {
if ((currByte & crcMsbmask) !== 0) {
currByte <<= 1
currByte ^= crcPolynomial
} else {
currByte <<= 1
}
}
crcTab[divide] = currByte & crcCastMask
}
return crcTab
}
function updateCrc (cp: number, crc: number): number {
const crcTab = computeCrcTab()
return crcTab[((crc >> 8) & 255)] ^ ((255 & crc) << 8) ^ cp
}
function verify (expect: OctetNumbers, got: OctetNumbers): void {
if (expect.join() !== got.join()) {
throw new ZmodemError('crc', got, expect)
}
}
const CRC = {
crc16 (octetNums: OctetNumbers) {
let crc = octetNums[0]
for (let b = 1; b < octetNums.length; b++) {
crc = updateCrc(octetNums[b], crc)
}
crc = updateCrc(0, updateCrc(0, crc))
return ZmodemEncodeLib.pack_u16_be(crc)
},
crc32 (octetNums: OctetNumbers) {
return ZmodemEncodeLib.pack_u32_le(
buf(octetNums) >>> 0
)
},
verify16 (bytesArr: OctetNumbers, got: OctetNumbers) {
return verify(CRC.crc16(bytesArr), got)
},
verify32 (bytesArr: OctetNumbers, crc: OctetNumbers) {
verify(CRC.crc32(bytesArr), crc)
}
}
export default CRC
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zdle.ts
|
TypeScript
|
import ZMLIB from './zmlib'
import { ZDLEConfig } from './types'
/**
* Class that handles ZDLE encoding and decoding.
* Encoding is subject to a given configuration--specifically, whether
* we want to escape all control characters. Decoding is static; however
* a given string is encoded we can always decode it.
*/
class ZmodemZDLE {
_config: ZDLEConfig = { escape_ctrl_chars: false, turbo_escape: false }
_zdle_table?: number[]
_lastcode?: number
/**
* Create a ZDLE encoder.
*
* @param {object} [config] - The initial configuration.
* @param {object} config.escape_ctrl_chars - Whether the ZDLE encoder
* should escape control characters.
*/
constructor (config?: ZDLEConfig) {
if (config !== undefined) {
this.set_escape_ctrl_chars(config.escape_ctrl_chars)
}
}
set_escape_ctrl_chars (value: boolean): void {
if (value !== this._config.escape_ctrl_chars) {
this._config.escape_ctrl_chars = value
this._setup_zdle_table()
}
}
/**
* Whether or not control-character escaping is enabled.
*
* @return {boolean} Whether the escaping is on (true) or off (false).
*/
escapes_ctrl_chars (): boolean {
return this._config.escape_ctrl_chars
}
/**
* Encode an array of octet values and return it.
* This will mutate the given array.
*
* @param {number[]} octets - The octet values to transform.
* Each array member should be an 8-bit unsigned integer (0-255).
* This object is mutated in the function.
*
* @returns {number[]} The passed-in array, transformed. This is the
* same object that is passed in.
*/
encode (octets: number[]): number[] {
// NB: Performance matters here!
if (this._zdle_table === undefined) {
throw new Error('No ZDLE encode table configured!')
}
const zdleTable = this._zdle_table
let lastCode = this._lastcode
const arrbuf = new ArrayBuffer(2 * octets.length)
const arrbufUint8 = new Uint8Array(arrbuf)
const escctlYn = this._config.escape_ctrl_chars
let arrbufI = 0
for (let encodeCur = 0; encodeCur < octets.length; encodeCur++) {
const encodeTodo = zdleTable[octets[encodeCur]]
if (encodeTodo === undefined) {
console.error('bad encode() call:', JSON.stringify(octets))
this._lastcode = lastCode
throw new Error(`Invalid octet: ${octets[encodeCur]}`)
}
lastCode = octets[encodeCur]
if (encodeTodo === 1) {
// Do nothing; we append last_code below.
} else if (escctlYn || encodeTodo === 2 || (lastCode & 0x7f) === 0x40) {
arrbufUint8[arrbufI] = ZMLIB.ZDLE
arrbufI++
lastCode ^= 0x40 // 0100
}
arrbufUint8[arrbufI] = lastCode
arrbufI++
}
this._lastcode = lastCode
octets.splice(0)
octets.push(...new Uint8Array(arrbuf, 0, arrbufI))
return octets
}
/**
* Decode an array of octet values and return it.
* This will mutate the given array.
*
* @param {number[]} octets - The octet values to transform.
* Each array member should be an 8-bit unsigned integer (0-255).
* This object is mutated in the function.
*
* @returns {number[]} The passed-in array.
* This is the same object that is passed in.
*/
static decode (octets: number[]): number[] {
for (let o = octets.length - 1; o >= 0; o--) {
if (octets[o] === ZMLIB.ZDLE) {
octets.splice(o, 2, octets[o + 1] - 64)
}
}
return octets
}
/**
* Remove, ZDLE-decode, and return bytes from the passed-in array.
* If the requested number of ZDLE-encoded bytes isn’t available,
* then the passed-in array is unmodified (and the return is undefined).
*
* @param {number[]} octets - The octet values to transform.
* Each array member should be an 8-bit unsigned integer (0-255).
* This object is mutated in the function.
*
* @param {number} offset - The number of (undecoded) bytes to skip
* at the beginning of the “octets” array.
*
* @param {number} count - The number of bytes (octet values) to return.
*
* @returns {number[]|undefined} An array with the requested number of
* decoded octet values, or undefined if that number of decoded
* octets isn’t available (given the passed-in offset).
*/
static splice (octets: number[], offset: number = 0, count: number): number[] | undefined {
let soFar = 0
let i = offset
for (; i < octets.length && soFar < count; i++) {
soFar++
if (octets[i] === ZMLIB.ZDLE) i++
}
if (soFar === count) {
// Don’t accept trailing ZDLE. This check works
// because of the i++ logic above.
if (octets.length === i - 1) return undefined
octets.splice(0, offset)
return ZmodemZDLE.decode(octets.splice(0, i - offset))
}
return undefined
}
_setup_zdle_table (): void {
const zsendlineTab = new Array(256)
for (let i = 0; i < zsendlineTab.length; i++) {
// 1 = never escape
// 2 = always escape
// 3 = escape only if the previous byte was '@'
// Never escape characters from 0x20 (32) to 0x7f (127).
// This is the range of printable characters, plus DEL.
// I guess ZMODEM doesn’t consider DEL to be a control character?
if ((i & 0x60) !== 0) {
zsendlineTab[i] = 1
} else {
switch (i) {
case ZMLIB.ZDLE: // NB: no (ZDLE | 0x80)
case ZMLIB.XOFF:
case ZMLIB.XON:
case ZMLIB.XOFF | 0x80:
case ZMLIB.XON | 0x80:
zsendlineTab[i] = 2
break
case 0x10:
case 0x90:
zsendlineTab[i] = this._config.turbo_escape ? 1 : 2
break
case 0x0d:
case 0x8d:
zsendlineTab[i] =
this._config.escape_ctrl_chars
? 2
: !this._config.turbo_escape
? 3
: 1
break
default:
zsendlineTab[i] = this._config.escape_ctrl_chars ? 2 : 1
}
}
}
this._zdle_table = zsendlineTab
}
}
export default ZmodemZDLE
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zerror.ts
|
TypeScript
|
function crcMessage (got: number[], expected: number[]): string {
return (
'CRC check failed! (got: ' +
got.join() +
'; expected: ' +
expected.join() +
')'
)
}
function pass<T> (value: T): T {
return value
}
const typeMessage: Record<string, unknown> = {
aborted: 'Session aborted',
peerAborted: 'Peer aborted session',
alreadyAborted: 'Session already aborted',
crc: crcMessage,
validation: pass
}
function generateMessage (type: string, ...args: any[]): any {
const message = typeMessage[type]
switch (typeof message) {
case 'string':
return message
case 'function':
return message(...args)
}
return null
}
class ZmodemError extends Error {
type?: string
constructor (messageOrType: string, ...args: any[]) {
super()
const generated = generateMessage(messageOrType, ...args)
if (generated !== null) {
this.type = messageOrType
this.message = generated
} else {
this.message = messageOrType
}
}
}
export default ZmodemError
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zheader-base.ts
|
TypeScript
|
import { ZmodemEncodeLib } from './encode'
import CRC from './zcrc'
import {
HEX_HEADER_PREFIX,
BINARY16_HEADER_PREFIX,
BINARY32_HEADER_PREFIX,
HEX_HEADER_CRLF_XON
} from './zheader-constants'
import { Obj } from './types'
/** Class that represents a ZMODEM header. */
class ZmodemHeaderBase {
_hex_header_ending: number[] = HEX_HEADER_CRLF_XON
TYPENUM: number = 0
NAME: string = ''
_bytes4: number[] = [0, 0, 0, 0]
/**
* Return the octet values array that represents the object
* in ZMODEM hex encoding.
*
* @returns {number[]} An array of octet values suitable for sending
* as binary data.
*/
to_hex (): number[] {
const toCrc = this._crc_bytes()
return HEX_HEADER_PREFIX.concat(
ZmodemEncodeLib.octets_to_hex(toCrc.concat(CRC.crc16(toCrc))),
this._hex_header_ending
)
}
/**
* Return the octet values array that represents the object
* in ZMODEM binary encoding with a 16-bit CRC.
*
* @param {ZDLE} zencoder - A ZDLE instance to use for
* ZDLE encoding.
*
* @returns {number[]} An array of octet values suitable for sending
* as binary data.
*/
to_binary16 (zencoder: any): number[] {
return this._to_binary(zencoder, BINARY16_HEADER_PREFIX, CRC.crc16)
}
get_options (): Obj { return {} }
get_offset (): number { return 0 }
get_buffer_size (): any { return 0 }
can_full_duplex (): boolean { return false }
can_overlap_io (): boolean { return false }
escape_8th_bit (): boolean { return false }
escape_ctrl_chars (): boolean { return false }
/**
* Return the octet values array that represents the object
* in ZMODEM binary encoding with a 32-bit CRC.
*
* @param {ZDLE} zencoder - A ZDLE instance to use for
* ZDLE encoding.
*
* @returns {number[]} An array of octet values suitable for sending
* as binary data.
*/
to_binary32 (zencoder: any): number[] {
return this._to_binary(zencoder, BINARY32_HEADER_PREFIX, CRC.crc32)
}
_to_binary (zencoder: any, prefix: number[], crcFunc: (data: number[]) => number[]): number[] {
const toCrc = this._crc_bytes()
// Both the 4-byte payload and the CRC bytes are ZDLE-encoded.
const octets = prefix.concat(
zencoder.encode(toCrc.concat(crcFunc(toCrc)))
)
return octets
}
_crc_bytes (): number[] {
return [this.TYPENUM].concat(this._bytes4)
}
}
export default ZmodemHeaderBase
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zheader-class.ts
|
TypeScript
|
import { ZmodemEncodeLib } from './encode'
import { Obj } from './types'
import {
FlagType,
HEX_HEADER_CRLF,
ZRINIT_FLAG,
ZSINIT_FLAG,
ZFILE_VALUES,
ZFILE_ORDER,
ZMSKNOLOC,
MANAGEMENT_MASK,
ZXSPARS
} from './zheader-constants'
import {
getZRINITFlagNum,
getZSINITFlagNum
} from './zheader-functions'
import ZmodemHeaderBase from './zheader-base'
// every {name}_HEADER class add a NAME = '{name}' prototype
export class ZRQINIT_HEADER extends ZmodemHeaderBase {
NAME = 'ZRQINIT'
TYPENUM = 0
}
export class ZRINIT_HEADER extends ZmodemHeaderBase {
constructor (flagsArr: any[], bufsize: number = 0) {
super()
let flagsNum = 0
flagsArr.forEach(function (fl) {
flagsNum |= getZRINITFlagNum(fl)
})
this._bytes4 = [
bufsize & 0xff,
bufsize >> 8,
0,
flagsNum
]
}
NAME = 'ZRINIT'
TYPENUM = 1
// undefined if nonstop I/O is allowed
get_buffer_size (): number | undefined {
const r = ZmodemEncodeLib.unpack_u16_be(this._bytes4.slice(0, 2))
if (r === 0) {
return undefined
}
return r
}
can_full_duplex (): boolean {
return Boolean(this._bytes4[3] & ZRINIT_FLAG.CANFDX)
}
can_overlap_io (): boolean {
return Boolean(this._bytes4[3] & ZRINIT_FLAG.CANOVIO)
}
can_break (): boolean {
return Boolean(this._bytes4[3] & ZRINIT_FLAG.CANBRK)
}
can_fcs_32 (): boolean {
return Boolean(this._bytes4[3] & ZRINIT_FLAG.CANFC32)
}
escape_ctrl_chars (): boolean {
return Boolean(this._bytes4[3] & ZRINIT_FLAG.ESCCTL)
}
// Is this used? I don’t see it used in lrzsz or syncterm
// Looks like it was a “foreseen” feature that Forsberg
// never implemented. (The need for it went away, maybe?)
escape_8th_bit (): boolean {
return Boolean(this._bytes4[3] & ZRINIT_FLAG.ESC8)
}
}
export class ZSINIT_HEADER extends ZmodemHeaderBase {
NAME = 'ZSINIT'
TYPENUM = 2
_data: any[] = []
constructor (flagsArr: any[], attnSeqArr?: any[]) {
super()
let flagsNum = 0
flagsArr.forEach(function (fl) {
flagsNum |= getZSINITFlagNum(fl)
})
this._bytes4 = [0, 0, 0, flagsNum]
if (attnSeqArr != null) {
if (attnSeqArr.length > 31) {
throw new Error('Attn sequence must be <= 31 bytes')
}
if (attnSeqArr.some(function (num) { return num > 255 })) {
throw new Error(`Attn sequence ( ${attnSeqArr.join(',')} ) must be <256`)
}
this._data = attnSeqArr.concat([0])
}
}
escape_ctrl_chars (): boolean {
return Boolean(this._bytes4[3] & ZSINIT_FLAG.ESCCTL)
}
// Is this used? I don’t see it used in lrzsz or syncterm
escape_8th_bit (): boolean {
return Boolean(this._bytes4[3] & ZSINIT_FLAG.ESC8)
}
}
export class ZACK_HEADER extends ZmodemHeaderBase {
_hex_header_ending = HEX_HEADER_CRLF
constructor (payload4?: any[]) {
super()
if (payload4 != null) {
this._bytes4 = payload4.slice()
}
}
NAME = 'ZACK'
TYPENUM = 3
}
export class ZFILE_HEADER extends ZmodemHeaderBase {
// TODO: allow options on instantiation
NAME = 'ZFILE'
TYPENUM = 4
get_options (): Obj {
const opts: Obj = {
sparse: Boolean(this._bytes4[0] & ZXSPARS)
}
const bytesCopy = this._bytes4.slice(0)
ZFILE_ORDER.forEach((key, i) => {
if (Array.isArray(ZFILE_VALUES[key])) {
if (key === 'management') {
opts.skip_if_absent = Boolean(bytesCopy[i] & ZMSKNOLOC)
bytesCopy[i] &= MANAGEMENT_MASK
}
const arr: any[] = ZFILE_VALUES[key] as any[]
opts[key] = arr[bytesCopy[i]]
} else {
for (const extkey in ZFILE_VALUES[key]) {
const v = Boolean(bytesCopy[i] & (ZFILE_VALUES[key] as FlagType)[extkey])
opts[extkey] = v
if (v) {
bytesCopy[i] ^= (ZFILE_VALUES[key] as FlagType)[extkey]
}
}
}
if (opts[key] === undefined && bytesCopy[i] !== undefined) {
opts[key] = `unknown:${bytesCopy[i]}`
}
})
return opts
}
}
// ----------------------------------------------------------------------
// Empty headers - in addition to ZRQINIT
export class ZSKIP_HEADER extends ZmodemHeaderBase {
NAME = 'ZSKIP'
TYPENUM = 5
}
// No need for ZNAK
export class ZABORT_HEADER extends ZmodemHeaderBase {
NAME = 'ZABORT'
TYPENUM = 7
}
export class ZFIN_HEADER extends ZmodemHeaderBase {
NAME = 'ZFIN'
TYPENUM = 8
}
export class ZFERR_HEADER extends ZmodemHeaderBase {
_hex_header_ending = HEX_HEADER_CRLF
NAME = 'ZFERR'
TYPENUM = 11
}
export class ZOffsetHeader extends ZmodemHeaderBase {
constructor (offset: number) {
super()
this._bytes4 = ZmodemEncodeLib.pack_u32_le(offset)
}
get_offset (): number {
return ZmodemEncodeLib.unpack_u32_le(this._bytes4)
}
}
export class ZRPOS_HEADER extends ZOffsetHeader {
NAME = 'ZRPOS'
TYPENUM = 9
}
export class ZDATA_HEADER extends ZOffsetHeader {
NAME = 'ZDATA'
TYPENUM = 10
}
export class ZEOF_HEADER extends ZOffsetHeader {
NAME = 'ZEOF'
TYPENUM = 11
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zheader-constants.ts
|
TypeScript
|
import ZMLIB from './zmlib'
export const ZPAD = '*'.charCodeAt(0)
export const ZBIN = 'A'.charCodeAt(0)
export const ZHEX = 'B'.charCodeAt(0)
export const ZBIN32 = 'C'.charCodeAt(0)
export const HEX_HEADER_CRLF = [0x0d, 0x0a]
export const HEX_HEADER_CRLF_XON = [...HEX_HEADER_CRLF, ZMLIB.XON]
export const HEX_HEADER_PREFIX = [ZPAD, ZPAD, ZMLIB.ZDLE, ZHEX]
export const BINARY16_HEADER_PREFIX = [ZPAD, ZMLIB.ZDLE, ZBIN]
export const BINARY32_HEADER_PREFIX = [ZPAD, ZMLIB.ZDLE, ZBIN32]
// Define the type for ZRINIT_FLAG and ZSINIT_FLAG
export interface FlagType {
[key: string]: number
}
export const ZRINIT_FLAG: FlagType = {
CANFDX: 0x01,
CANOVIO: 0x02,
CANBRK: 0x04,
CANCRY: 0x08,
CANLZW: 0x10,
CANFC32: 0x20,
ESCCTL: 0x40,
ESC8: 0x80
}
export const ZSINIT_FLAG: FlagType = {
ESCCTL: 0x40,
ESC8: 0x80
}
// Define the type for ZRINIT_FLAG and ZSINIT_FLAG
interface JSONType {
[key: string]: FlagType | any[]
}
export const ZFILE_VALUES: JSONType = {
extended: {
sparse: 0x40
},
transport: [
undefined,
'compress',
'encrypt',
'rle'
],
management: [
undefined,
'newer_or_longer',
'crc',
'append',
'clobber',
'newer',
'mtime_or_length',
'protect',
'rename'
],
conversion: [
undefined,
'binary',
'text',
'resume'
]
}
export const ZFILE_ORDER = ['extended', 'transport', 'management', 'conversion']
export const ZMSKNOLOC = 0x80
export const MANAGEMENT_MASK = 0x1f
export const ZXSPARS = 0x40
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zheader-functions.ts
|
TypeScript
|
import {
ZRINIT_FLAG,
ZSINIT_FLAG
} from './zheader-constants'
import ZmodemError from './zerror'
export function getZRINITFlagNum (fl: string): number {
const flag = ZRINIT_FLAG[fl]
if (flag === undefined) {
throw new ZmodemError('Invalid ZRINIT flag: ' + fl)
}
return flag
}
export function getZSINITFlagNum (fl: string): number {
const flag = ZSINIT_FLAG[fl]
if (flag === undefined) {
throw new ZmodemError('Invalid ZSINIT flag: ' + fl)
}
return flag
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zheader-functions2.ts
|
TypeScript
|
import { ZmodemEncodeLib } from './encode'
import CRC from './zcrc'
import ZmodemZDLE from './zdle'
import {
BINARY16_HEADER_PREFIX,
BINARY32_HEADER_PREFIX
} from './zheader-constants'
import {
ZRQINIT_HEADER,
ZRINIT_HEADER,
ZSINIT_HEADER,
ZACK_HEADER,
ZFILE_HEADER,
ZSKIP_HEADER,
ZABORT_HEADER,
ZFIN_HEADER,
ZFERR_HEADER,
ZOffsetHeader,
ZRPOS_HEADER,
ZDATA_HEADER,
ZEOF_HEADER
} from './zheader-class'
export type AnyClass = typeof ZRQINIT_HEADER | typeof ZRINIT_HEADER | typeof ZSINIT_HEADER | typeof ZACK_HEADER | typeof ZFILE_HEADER | typeof ZSKIP_HEADER | typeof ZABORT_HEADER | typeof ZFIN_HEADER | typeof ZFERR_HEADER | typeof ZRPOS_HEADER | typeof ZDATA_HEADER | typeof ZEOF_HEADER
interface FrameClassType {
header: AnyClass
name: string
}
const FRAME_CLASS_TYPES: Array<FrameClassType | undefined> = [
{ header: ZRQINIT_HEADER, name: 'ZRQINIT' },
{ header: ZRINIT_HEADER, name: 'ZRINIT' },
{ header: ZSINIT_HEADER, name: 'ZSINIT' },
{ header: ZACK_HEADER, name: 'ZACK' },
{ header: ZFILE_HEADER, name: 'ZFILE' },
{ header: ZSKIP_HEADER, name: 'ZSKIP' },
undefined, // [ ZNAK_HEADER, "ZNAK" ],
{ header: ZABORT_HEADER, name: 'ZABORT' },
{ header: ZFIN_HEADER, name: 'ZFIN' },
{ header: ZRPOS_HEADER, name: 'ZRPOS' },
{ header: ZDATA_HEADER, name: 'ZDATA' },
{ header: ZEOF_HEADER, name: 'ZEOF' },
{ header: ZFERR_HEADER, name: 'ZFERR' }, // see note
undefined, // [ ZCRC_HEADER, "ZCRC" ],
undefined, // [ ZCHALLENGE_HEADER, "ZCHALLENGE" ],
undefined, // [ ZCOMPL_HEADER, "ZCOMPL" ],
undefined, // [ ZCAN_HEADER, "ZCAN" ],
undefined, // [ ZFREECNT_HEADER, "ZFREECNT" ],
undefined, // [ ZCOMMAND_HEADER, "ZCOMMAND" ],
undefined // [ ZSTDERR_HEADER, "ZSTDERR" ],
]
/*
ZFERR is described as “error in reading or writing file”. It’s really
not a good idea from a security angle for the endpoint to expose this
information. We should parse this and handle it as ZABORT but never send it.
Likewise with ZFREECNT: the sender shouldn’t ask how much space is left
on the other box rather, the receiver should decide what to do with the
file size as the sender reports it.
*/
interface Creator {
[key: string]: AnyClass
}
const FRAME_NAME_CREATOR0: Creator = {}
const len = FRAME_CLASS_TYPES.length
for (let fc = 0; fc < len; fc++) {
if (FRAME_CLASS_TYPES[fc] == null) {
continue
}
const v = FRAME_CLASS_TYPES[fc] as FrameClassType
const Cls = v.header
FRAME_NAME_CREATOR0[v.name] = Cls
}
export const FRAME_NAME_CREATOR: Creator = FRAME_NAME_CREATOR0
// ----------------------------------------------------------------------
const CREATORS = [
ZRQINIT_HEADER,
ZRINIT_HEADER,
ZSINIT_HEADER,
ZACK_HEADER,
ZFILE_HEADER,
ZSKIP_HEADER,
'ZNAK',
ZABORT_HEADER,
ZFIN_HEADER,
ZRPOS_HEADER,
ZDATA_HEADER,
ZEOF_HEADER,
ZFERR_HEADER,
'ZCRC', // ZCRC_HEADER, -- leaving unimplemented?
'ZCHALLENGE',
'ZCOMPL',
'ZCAN',
'ZFREECNT', // ZFREECNT_HEADER,
'ZCOMMAND',
'ZSTDERR'
]
export function getBlankHeader (typenum: number): AnyClass {
const creator = CREATORS[typenum]
if (typeof (creator) === 'string') {
throw new Error('Received unsupported header: ' + creator)
}
/*
if (creator === ZCRC_HEADER) {
return new creator([0, 0, 0, 0])
}
*/
return getBlankHeaderFromConstructor(creator)
}
function doesClassExtend (baseClass: any, superClass: any): boolean {
if (baseClass === superClass) return true
let currentPrototype = Object.getPrototypeOf(baseClass.prototype)
while (currentPrototype instanceof Object) {
if (currentPrototype.constructor === superClass) {
return true
}
currentPrototype = Object.getPrototypeOf(currentPrototype)
}
return false
}
// referenced outside TODO
export function getBlankHeaderFromConstructor (Creator: AnyClass): AnyClass {
if (doesClassExtend(Creator, ZOffsetHeader)) {
return new (Creator as any)(0)
}
return new (Creator as any)([])
}
export function parseBinary16 (bytesArr: number[]): AnyClass | undefined {
// The max length of a ZDLE-encoded binary header w/ 16-bit CRC is:
// 3 initial bytes, NOT ZDLE-encoded
// 2 typenum bytes (1 decoded)
// 8 data bytes (4 decoded)
// 4 CRC bytes (2 decoded)
// A 16-bit payload has 7 ZDLE-encoded octets.
// The ZDLE-encoded octets follow the initial prefix.
const zdleDecoded = ZmodemZDLE.splice(bytesArr, BINARY16_HEADER_PREFIX.length, 7)
if (zdleDecoded !== undefined) {
return parseNonZdleBinary16(zdleDecoded)
}
}
export function parseNonZdleBinary16 (decoded: number[]): AnyClass {
CRC.verify16(
decoded.slice(0, 5),
decoded.slice(5)
)
const typenum = decoded[0]
const hdr = getBlankHeader(typenum) as any
hdr._bytes4 = decoded.slice(1, 5)
return hdr
}
export function parseBinary32 (bytesArr: number[]): AnyClass | undefined {
// Same deal as with 16-bit CRC except there are two more
// potentially ZDLE-encoded bytes, for a total of 9.
const zdleDecoded = ZmodemZDLE.splice(
bytesArr, // omit the leading "*", ZDLE, and "C"
BINARY32_HEADER_PREFIX.length,
9
)
if (zdleDecoded === undefined) {
return
}
CRC.verify32(
zdleDecoded.slice(0, 5),
zdleDecoded.slice(5)
)
const typenum = zdleDecoded[0]
const hdr = getBlankHeader(typenum) as any
hdr._bytes4 = zdleDecoded.slice(1, 5)
return hdr
}
export function parseHex (bytesArr: number[]): AnyClass | undefined {
// A hex header always has:
// 4 bytes for the ** . ZDLE . 'B'
// 2 hex bytes for the header type
// 8 hex bytes for the header content
// 4 hex bytes for the CRC
// 1-2 bytes for (CR/)LF
// (...and at this point the trailing XON is already stripped)
//
// ----------------------------------------------------------------------
// A carriage return and line feed are sent with HEX headers. The
// receive routine expects to see at least one of these characters, two
// if the first is CR.
// ----------------------------------------------------------------------
//
// ^^ I guess it can be either CR/LF or just LF … though those two
// sentences appear to be saying contradictory things.
let lfPos = bytesArr.indexOf(0x8a) // lrzsz sends this
if (lfPos === -1) {
lfPos = bytesArr.indexOf(0x0a)
}
let hdrErr = ''
let hexBytes
if (lfPos === -1) {
if (bytesArr.length > 11) {
hdrErr = 'Invalid hex header - no LF detected within 12 bytes!'
}
// incomplete header
return
} else {
hexBytes = bytesArr.splice(0, lfPos)
// Trim off the LF
bytesArr.shift()
if (hexBytes.length === 19) {
// NB: The spec says CR but seems to treat high-bit variants
// of control characters the same as the regulars should we
// also allow 0x8d?
const preceding = hexBytes.pop()
if (preceding !== 0x0d && preceding !== 0x8d) {
hdrErr = 'Invalid hex header: (CR/)LF doesn’t have CR!'
}
} else if (hexBytes.length !== 18) {
hdrErr = 'Invalid hex header: invalid number of bytes before LF!'
}
}
if (hdrErr !== '') {
hdrErr += ` ( ${hexBytes.length} bytes: ${hexBytes.join()} )`
throw new Error(hdrErr)
}
hexBytes.splice(0, 4)
// Should be 7 bytes ultimately:
// 1 for typenum
// 4 for header data
// 2 for CRC
const octets = ZmodemEncodeLib.parse_hex_octets(hexBytes)
return parseNonZdleBinary16(octets)
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zheader.ts
|
TypeScript
|
import ZMLIB from './zmlib'
import {
ZPAD,
ZBIN,
ZBIN32,
HEX_HEADER_PREFIX,
BINARY16_HEADER_PREFIX,
BINARY32_HEADER_PREFIX
} from './zheader-constants'
import {
parseHex,
parseBinary16,
parseBinary32,
FRAME_NAME_CREATOR,
AnyClass
} from './zheader-functions2'
import ZmodemHeaderBase from './zheader-base'
/**
* Class that represents a ZMODEM header.
*/
export class ZmodemHeader extends ZmodemHeaderBase {
static trimLeadingGarbage (ibuffer: number[]): number [] {
const garbage = []
let discardAll = false
let parser = null
while ((ibuffer.length > 0) && parser === null) {
const firstZPAD = ibuffer.indexOf(ZPAD)
if (firstZPAD === -1) {
discardAll = true
break
} else {
garbage.push(...ibuffer.splice(0, firstZPAD))
if (ibuffer.length < 2) {
break
} else if (ibuffer[1] === ZPAD) {
if (ibuffer.length < HEX_HEADER_PREFIX.length) {
if (ibuffer.join() === HEX_HEADER_PREFIX.slice(0, ibuffer.length).join()) {
// We have an incomplete fragment that matches
// HEX_HEADER_PREFIX. So don't trim any more.
break
}
} else if (
ibuffer[2] === HEX_HEADER_PREFIX[2] &&
ibuffer[3] === HEX_HEADER_PREFIX[3]
) {
parser = parseHex
}
} else if (ibuffer[1] === ZMLIB.ZDLE) {
if (ibuffer.length < BINARY16_HEADER_PREFIX.length) {
break
}
if (ibuffer[2] === BINARY16_HEADER_PREFIX[2]) {
parser = parseBinary16
} else if (ibuffer[2] === BINARY32_HEADER_PREFIX[2]) {
parser = parseBinary32
}
}
if (parser === null) {
garbage.push(ibuffer.shift() as never)
}
}
}
if (discardAll) {
garbage.push(...ibuffer.splice(0))
}
return garbage
}
static parse_hex (bytesArr: number[]): AnyClass | undefined {
return parseHex(bytesArr)
}
static parse (octets: number[]): [AnyClass, number] | undefined {
let hdr
let d = 16
if (octets[1] === ZPAD) {
hdr = parseHex(octets)
} else if (octets[2] === ZBIN) {
hdr = parseBinary16(octets) // ?? original code is parseBinary16(octets, 3)
} else if (octets[2] === ZBIN32) {
hdr = parseBinary32(octets)
d = 32
}
if (hdr !== undefined) {
return [hdr, d]
}
if (octets.length < 3) {
return
}
throw new Error(`Unrecognized/unsupported octets: ${octets.join()}`)
}
static build (name: string, ...args: any[]): AnyClass | undefined {
const Ctr = FRAME_NAME_CREATOR[name]
if (Ctr === undefined) {
throw new Error(`No frame class "${name}" is defined!`)
}
const hdr = new (Ctr as any)(...args)
return hdr
}
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zmlib.ts
|
TypeScript
|
const ZDLE = 0x18
const XON = 0x11
const XOFF = 0x13
const XON_HIGH = 0x80 | XON
const XOFF_HIGH = 0x80 | XOFF
const CAN = 0x18 // NB: same character as ZDLE
// interface Octets extends Array<number>
export default {
/**
* @property {number} The ZDLE constant, which ZMODEM uses for escaping
*/
ZDLE,
/**
* @property {number} XON - ASCII XON
*/
XON,
/**
* @property {number} XOFF - ASCII XOFF
*/
XOFF,
/**
* @property {number[]} ABORT_SEQUENCE - ZMODEM’s abort sequence
*/
ABORT_SEQUENCE: [CAN, CAN, CAN, CAN, CAN],
/**
* Remove octet values from the given array that ZMODEM always ignores.
* This will mutate the given array.
*
* @param {number[]} octets - The octet values to transform.
* Each array member should be an 8-bit unsigned integer (0-255).
* This object is mutated in the function.
*
* @returns {number[]} The passed-in array. This is the same object that is
* passed in.
*/
stripIgnoredBytes (octets: number[]): number[] {
for (let o = octets.length - 1; o >= 0; o--) {
switch (octets[o]) {
case XON:
case XON_HIGH:
case XOFF:
case XOFF_HIGH:
octets.splice(o, 1)
continue
}
}
return octets
},
/**
* Like Array.prototype.indexOf, but searches for a subarray
* rather than just a particular value.
*
* @param {Array} haystack - The array to search, i.e., the bigger.
*
* @param {Array} needle - The array whose values to find,
* i.e., the smaller.
*
* @returns {number} The position in “haystack” where “needle”
* first appears—or, -1 if “needle” doesn’t appear anywhere
* in “haystack”.
*/
findSubarray (haystack: number[], needle: number[]): number {
let h = 0
let n
while (h !== -1) {
h = haystack.indexOf(needle[0], h)
if (h === -1) {
break
}
for (n = 1; n < needle.length; n++) {
if (haystack[h + n] !== needle[n]) {
h++
break
}
}
if (n === needle.length) {
return h
}
}
return -1
}
}
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zmodem.ts
|
TypeScript
|
import Sentry from './zsentry'
const Zmodem = {
Sentry
}
export default Zmodem
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zsentry-detection.ts
|
TypeScript
|
// **, ZDLE, 'B0'
// ZRQINIT’s next byte will be '0' ZRINIT’s will be '1'.
// const COMMON_ZM_HEX_START: number[] = [42, 42, 24, 66, 48]
// const SENTRY_CONSTRUCTOR_REQUIRED_ARGS: string[] = [
// 'to_terminal',
// 'on_detect',
// 'on_retract',
// 'sender'
// ]
/**
* An instance of this object is passed to the Sentry’s on_detect
* callback each time the Sentry object sees what looks like the
* start of a ZMODEM session.
*
* Note that it is possible for a detection to be “retracted”
* if the Sentry consumes bytes afterward that are not ZMODEM.
* When this happens, the Sentry’s `retract` event will fire,
* after which the Detection object is no longer usable.
*/
class Detection {
sess: any
sentry: any
_denier: Function
_is_valid: Function
_session_type: string
/**
* Not called directly.
*/
constructor (
sessionType: string,
sess: any,
sentry: any,
denier: Function,
checker: Function
) {
// confirm() - user confirms that ZMODEM is desired
this.sess = sess
this.sentry = sentry
// deny() - user declines ZMODEM send abort sequence
//
// TODO: It might be ideal to forgo the session “peaceably”,
// i.e., such that the peer doesn’t end in error. That’s
// possible if we’re the sender, we accept the session,
// then we just send a close(), but it doesn’t seem to be
// possible for a receiver. Thus, let’s just leave it so
// it’s at least consistent (and simpler, too).
this._denier = denier
this._is_valid = checker
this._session_type = sessionType
}
_confirmer (): any {
if (!this.is_valid()) {
throw new Error('Stale ZMODEM session!')
}
const { sess, sentry } = this
sess.on('garbage', sentry._to_terminal)
sess.on('session_end', sentry._after_session_end)
sess.set_sender(sentry._sender)
sess._parsed_session = null
sentry._zsession = sess
return sess
}
/**
* Confirm that the detected ZMODEM sequence indicates the
* start of a ZMODEM session.
*
* @return {Session} The ZMODEM Session object (i.e., either a
* Send or Receive instance).
*/
confirm = (...args: any[]): any => {
return this._confirmer.apply(this, args as [])
}
/**
* Tell the Sentry that the detected bytes sequence is
* **NOT** intended to be the start of a ZMODEM session.
*/
deny = (...args: any[]): any => {
return this._denier(...args)
}
/**
* Tells whether the Detection is still valid i.e., whether
* the Sentry has `consume()`d bytes that invalidate the
* Detection.
*
* @returns {boolean} Whether the Detection is valid.
*/
is_valid = (...args: any[]): boolean => {
return this._is_valid(...args)
}
/**
* Gives the session’s role.
*
* @returns {string} One of:
* - `receive`
* - `send`
*/
get_session_role = (): string => {
return this._session_type
}
}
export default Detection
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zsentry.ts
|
TypeScript
|
import ZmodemSession from './zsession'
import ZMLIB from './zmlib'
import Detection from './zsentry-detection'
import { SentryOpts } from './types'
const MAX_ZM_HEX_START_LENGTH = 21
// **, ZDLE, 'B0'
// ZRQINIT’s next byte will be '0' ZRINIT’s will be '1'.
const COMMON_ZM_HEX_START = [42, 42, 24, 66, 48]
const SENTRY_CONSTRUCTOR_REQUIRED_ARGS = [
'to_terminal',
'on_detect',
'on_retract',
'sender'
]
/**
* Class that parses an input stream for the beginning of a
* ZMODEM session. We look for the tell-tale signs
* of a ZMODEM transfer and allow the client to determine whether
* it’s really ZMODEM or not.
*
* This is the “mother” class for zmodem.js
* all other class instances are created, directly or indirectly,
* by an instance of this class.
*
* This logic is not unlikely to need tweaking, and it can never
* be fully bulletproof if it could be bulletproof it would be
* simpler since there wouldn’t need to be the .confirm()/.deny()
* step.
*
* One thing you could do to make things a bit simpler *is* just
* to make that assumption for your users--i.e., to .confirm()
* Detection objects automatically. That’ll be one less step
* for the user, but an unaccustomed user might find that a bit
* confusing. It’s also then possible to have a “false positive”:
* a text stream that contains a ZMODEM initialization string but
* isn’t, in fact, meant to start a ZMODEM session.
*
* Workflow:
* - parse all input with .consume(). As long as nothing looks
* like ZMODEM, all the traffic will go to to_terminal().
*
* - when a “tell-tale” sequence of bytes arrives, we create a
* Detection object and pass it to the “on_detect” handler.
*
* - Either .confirm() or .deny() with the Detection object.
* This is the user’s chance to say, “yeah, I know those
* bytes look like ZMODEM, but they’re not. So back off!”
*
* If you .confirm(), the Session object is returned, and
* further input that goes to the Sentry’s .consume() will
* go to the (now-active) Session object.
*
* - Sometimes additional traffic arrives that makes it apparent
* that no ZMODEM session is intended to start in this case,
* the Sentry marks the Detection as “stale” and calls the
* `on_retract` handler. Any attempt from here to .confirm()
* on the Detection object will prompt an exception.
*
* (This “retraction” behavior will only happen prior to
* .confirm() or .deny() being called on the Detection object.
* Beyond that point, either the Session has to deal with the
* “garbage”, or it’s back to the terminal anyway.
*
* - Once the Session object is done, the Sentry will again send
* all traffic to to_terminal().
*/
class ZmodemSentry {
_to_terminal: Function = () => null
_on_detect: Function = () => null
_on_retract: Function = () => null
_sender: Function = () => null
_cache: number[]
_zsession: ZmodemSession | null = null
_parsed_session: ZmodemSession | null = null
/**
* Invoked directly. Creates a new Sentry that inspects all
* traffic before it goes to the terminal.
*
* @param {Object} options - The Sentry parameters
*
* @param {Function} options.to_terminal - Handler that sends
* traffic to the terminal object. Receives an iterable object
* (e.g., an Array) that contains octet numbers.
*
* @param {Function} options.on_detect - Handler for new
* detection events. Receives a new Detection object.
*
* @param {Function} options.on_retract - Handler for retraction
* events. Receives no input.
*
* @param {Function} options.sender - Handler that sends traffic to
* the peer. If, for example, your application uses WebSocket to talk
* to the peer, use this to send data to the WebSocket instance.
*/
constructor (options: SentryOpts) {
for (const arg of SENTRY_CONSTRUCTOR_REQUIRED_ARGS) {
(this as any)[`_${arg}`] = (options as any)[arg]
}
this._cache = []
}
_after_session_end = (): void => {
this._zsession = null
}
/**
* “Consumes” a piece of input:
*
* - If there is no active or pending ZMODEM session, the text is
* all output. (This is regardless of whether we’ve got a new
* Detection.)
*
* - If there is no active ZMODEM session and the input **ends** with
* a ZRINIT or ZRQINIT, then a new Detection object is created,
* and it is passed to the “on_detect” function.
* If there was another pending Detection object, it is retracted.
*
* - If there is no active ZMODEM session and the input does NOT end
* with a ZRINIT or ZRQINIT, then any pending Detection object is
* retracted.
*
* - If there is an active ZMODEM session, the input is passed to it.
* Any non-ZMODEM data (i.e., “garbage”) parsed from the input
* is sent to output.
* If the ZMODEM session ends, any post-ZMODEM part of the input
* is sent to output.
*
* @param {number[] | ArrayBuffer} input - Octets to parse as input.
*/
consume = (input: any): void => {
// let input = deepCopy(_input)
if (!(input instanceof Array)) {
input = Array.prototype.slice.call(new Uint8Array(input))
}
if (this._zsession != null) {
const sessionBeforeConsume = this._zsession
sessionBeforeConsume.consume(input)
if (sessionBeforeConsume.has_ended()) {
if (sessionBeforeConsume.type === 'receive') {
input = sessionBeforeConsume.get_trailing_bytes()
} else {
input = []
}
} else return
}
const newSession = this._parse(input) as ZmodemSession
let toTerminal = input
if (newSession !== undefined && newSession !== null) {
const replacementDetect = !(this._parsed_session == null)
if (replacementDetect) {
// no terminal output if the new session is of the
// same type as the old
if ((this._parsed_session as ZmodemSession).type === newSession.type) {
toTerminal = []
}
this._on_retract()
}
this._parsed_session = newSession
const checker = (): boolean => {
return this._parsed_session === newSession
}
// function denier(ref: Detection) {
// if (!ref.is_valid()) return
// }
this._on_detect(
new Detection(newSession.type, newSession, this, this._send_abort, checker)
)
} else {
/*
if (this._parsed_session) {
this._session_stale_because = 'Non-ZMODEM output received after ZMODEM initialization.'
}
*/
const expiredSession = this._parsed_session
this._parsed_session = null
if (expiredSession != null) {
// If we got a single “C” after parsing a session,
// that means our peer is trying to downgrade to YMODEM.
// That won’t work, so we just send the ABORT_SEQUENCE
// right away.
if (toTerminal.length === 1 && toTerminal[0] === 67) {
this._send_abort()
}
this._on_retract()
}
}
this._to_terminal(toTerminal)
}
/**
* @return {Session|null} The sentry’s current Session object, or
* null if there is none.
*/
get_confirmed_session = (): ZmodemSession | null => {
return this._zsession ?? null
}
_send_abort = (): void => {
this._sender(ZMLIB.ABORT_SEQUENCE)
}
/**
* Parse an input stream and decide how much of it goes to the
* terminal or to a new Session object.
*
* This will accommodate input strings that are fragmented
* across calls to this function e.g., if you send the first
* two bytes at the end of one parse() call then send the rest
* at the beginning of the next, parse() will recognize it as
* the beginning of a ZMODEM session.
*
* In order to keep from blocking any actual useful data to the
* terminal in real-time, this will send on the initial
* ZRINIT/ZRQINIT bytes to the terminal. They’re meant to go to the
* terminal anyway, so that should be fine.
*
* @private
*
* @param {Array|Uint8Array} arrayLike - The input bytes.
* Each member should be a number between 0 and 255 (inclusive).
*
* @return {Array} A two-member list:
* 0) the bytes that should be printed on the terminal
* 1) the created Session object (if any)
*/
_parse = (arrayLike: number[] | Uint8Array): null | ZmodemSession => {
const cache = this._cache
// Avoid spread operator which causes stack overflow with large arrays
// Use a loop-based approach instead
const len = arrayLike.length
const cacheLen = cache.length
cache.length = cacheLen + len
for (let i = 0; i < len; i++) {
cache[cacheLen + i] = arrayLike[i]
}
const commonHexAt = ZMLIB.findSubarray(cache, COMMON_ZM_HEX_START)
if (commonHexAt === -1) {
cache.splice(MAX_ZM_HEX_START_LENGTH)
return null
}
cache.splice(0, commonHexAt)
let zsession: ZmodemSession | undefined
try {
zsession = ZmodemSession.parse(cache)
} catch (err) {
// ignore errors
// console.log(err)
}
if (zsession == null) {
cache.splice(MAX_ZM_HEX_START_LENGTH)
return null
}
// Don’t need to parse the trailing XON.
if (cache.length === 1 && cache[0] === ZMLIB.XON) {
cache.shift()
}
// If there are still bytes in the cache,
// then we don’t have a ZMODEM session. This logic depends
// on the sender only sending one initial header.
return (cache.length > 0) ? null : zsession
}
}
export default ZmodemSentry
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zsess-base.ts
|
TypeScript
|
import _Eventer from './eventer'
import ZMLIB from './zmlib'
import { ZmodemHeader } from './zheader'
import { Obj } from './types'
import ZmodemError from './zerror'
import ZmodemZDLE from './zdle'
import ZmodemSubpacket from './zsubpacket'
import { AnyClass } from './zheader-functions2'
const BS = 0x8
const OVER_AND_OUT = [79, 79]
const ABORT_SEQUENCE = ZMLIB.ABORT_SEQUENCE
function trimOO (array: number[]): number[] {
if (ZMLIB.findSubarray(array, OVER_AND_OUT) === 0) {
array.splice(0, OVER_AND_OUT.length)
} else if (array[0] === OVER_AND_OUT[OVER_AND_OUT.length - 1]) {
array.splice(0, 1)
}
return array
}
class ZmodemSessionBase extends _Eventer {
_zencoder: ZmodemZDLE = new ZmodemZDLE()
_last_sent_header: any = null
_next_header_handler: any = null
_last_header_crc: number = 0
_last_header_name: string = ''
_next_subpacket_handler: Function | null = null
_bytes_after_OO: number[] | null = null
_bytes_being_consumed: number[] = []
_got_ZFIN: boolean = false
DEBUG: boolean = false
type: string = ''
_aborted: boolean = false
_config: Obj = {}
_input_buffer: number[] = []
_sender?: Function
constructor () {
super()
this._config = {}
this._input_buffer = []
this._Add_event('receive')
this._Add_event('garbage')
this._Add_event('session_end')
}
get_trailing_bytes (): any {}
async send_offer (opts: any): Promise<any> {
return await Promise.resolve()
}
set_sender (senderFunc: Function): this {
this._sender = senderFunc
return this
}
/**
* Whether the current Session has ended.
*
* @returns The ended state.
*/
has_ended (): boolean {
return this._has_ended() // ?? this._has_ended()
}
_has_ended (): boolean { return this.aborted() || !(this._bytes_after_OO == null) }
/**
* Consumes an array of octets as ZMODEM session input.
*
* @param octets - The input octets.
*/
consume = (octets: number[]): void => {
this._before_consume(octets)
if (this._aborted) throw new ZmodemError('already_aborted')
if (octets.length === 0) return
this._strip_and_enqueue_input(octets)
if (this._check_for_abort_sequence() !== true) {
this._consume_first()
}
}
_consume_first = (): void => {
if (this._got_ZFIN) {
if (this._input_buffer.length < 2) {
return
}
// if it’s OO, then set this._bytes_after_OO
if (ZMLIB.findSubarray(this._input_buffer, OVER_AND_OUT) === 0) {
// This doubles as an indication that the session has ended.
// We need to set this right away so that handlers like
// "session_end" will have access to it.
this._bytes_after_OO = trimOO(this._bytes_being_consumed.slice(0))
this._on_session_end()
return
} else {
console.warn('PROTOCOL: Only thing after ZFIN should be “OO” (79,79), but got: ' + this._input_buffer.join() + '. Ending session anyway.')
this._bytes_after_OO = trimOO(this._bytes_being_consumed.slice(0))
this._on_session_end()
return
}
}
let parsed
do {
if (this._next_subpacket_handler != null) {
parsed = this._parse_and_consume_subpacket()
} else {
parsed = this._parse_and_consume_header()
}
} while ((parsed != null) && (this._input_buffer.length > 0))
}
/**
* Whether the current Session has been `abort()`ed.
*
* @returns The aborted state.
*/
aborted (): boolean {
return !!this._aborted
}
_parse_and_consume_subpacket (): any { }
/**
* Returns the Session object’s role.
*
* @returns One of:
* - `receive`
* - `send`
*/
get_role (): string {
return this.type
}
_trim_leading_garbage_until_header (): void {
const garbage = ZmodemHeader.trimLeadingGarbage(this._input_buffer)
if (garbage !== undefined && garbage.length > 0) {
if (this._Happen('garbage', garbage) === 0) {
console.debug(
'Garbage: ',
String.fromCharCode(...garbage),
garbage
)
}
}
}
_parse_and_consume_header = (): AnyClass | undefined => {
this._trim_leading_garbage_until_header()
const newHeaderAndCrc = ZmodemHeader.parse(this._input_buffer)
if (newHeaderAndCrc === undefined) return
const hdr = newHeaderAndCrc[0] as any
if (this.DEBUG) {
this._log_header('RECEIVED HEADER', hdr)
}
this._consume_header(hdr)
this._last_header_name = hdr.NAME
this._last_header_crc = newHeaderAndCrc[1]
return hdr
}
_log_header = (label: string, header: ZmodemHeader): void => {
console.debug(this.type, label, header.NAME, header._bytes4.join())
}
_consume_header (newHeader: ZmodemHeader): any {
this._on_receive(newHeader)
const handler = this._next_header_handler !== null
? this._next_header_handler[newHeader.NAME]
: undefined
if (handler === undefined) {
console.error('Unhandled header!', newHeader, this._next_header_handler)
return
}
this._next_header_handler = null
handler.call(this, newHeader)
}
_check_for_abort_sequence (): boolean | undefined {
const abortAt = ZMLIB.findSubarray(this._input_buffer, ABORT_SEQUENCE)
if (abortAt !== -1) {
// TODO: expose this to caller
this._input_buffer.splice(0, abortAt + ABORT_SEQUENCE.length)
this._aborted = true
// TODO compare response here to lrzsz.
this._on_session_end()
throw new ZmodemError('peer_aborted')
}
return false
}
_send_header (name: string, ...args: any[]): void {
if (this._sender === undefined) {
throw new Error('Need sender!')
}
const bytesHdr = this._create_header_bytes(name, ...args)
if (this.DEBUG) {
this._log_header('SENDING HEADER', bytesHdr[1])
}
this._sender(bytesHdr[0])
this._last_sent_header = bytesHdr[1]
}
_create_header_bytes (name: string, ...args: any[]): any {
const hdr = ZmodemHeader.build(name, ...args) as any
const formatter: string = this._get_header_formatter(name)
return [(hdr[formatter] as Function)(this._zencoder), hdr]
}
_get_header_formatter (name: string): string { return 'to_hex' }
_strip_and_enqueue_input (input: number[]): void {
ZMLIB.stripIgnoredBytes(input)
// Avoid push.apply() which causes stack overflow with large arrays
// Instead, use a chunked approach or direct array assignment
const len = input.length
if (len === 0) return
// For large arrays, extending with concat or loop is more efficient
// and avoids call stack limits
const bufferLen = this._input_buffer.length
this._input_buffer.length = bufferLen + len
for (let i = 0; i < len; i++) {
this._input_buffer[bufferLen + i] = input[i]
}
}
abort (): void {
if (this._sender !== undefined) {
this._sender(ABORT_SEQUENCE.concat([BS, BS, BS, BS, BS]))
}
this._aborted = true
this._sender = function () {
throw new ZmodemError('already_aborted')
}
this._on_session_end()
}
_on_session_end (): void {
this._Happen('session_end')
}
_on_receive (hdrOrPkt: ZmodemHeader | ZmodemSubpacket): void {
this._Happen('receive', hdrOrPkt)
}
_before_consume (arr: number[]): void { }
}
export default ZmodemSessionBase
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zsess-receive.ts
|
TypeScript
|
import { ZmodemHeader } from './zheader'
import ZmodemSubpacket from './zsubpacket'
import { ZmodemEncodeLib } from './encode'
import ZmodemSessionBase from './zsess-base'
import Offer from './offer'
// We ourselves don't need ESCCTL, so we don't send it
// however, we always expect to receive it in ZRINIT.
// See _ensure_receiver_escapes_ctrl_chars() for more details.
const ZRINIT_FLAGS = [
'CANFDX', // full duplex
'CANOVIO', // overlap I/O
// lsz has a buffer overflow bug that shows itself when:
//
// - 16-bit CRC is used, and
// - lsz receives the abort sequence while sending a file
//
// To avoid this, we just tell lsz to use 32-bit CRC
// even though there is otherwise no reason. This ensures that
// unfixed lsz versions will avoid the buffer overflow.
'CANFC32'
]
/** A class for ZMODEM receive sessions.
*
* @extends Session
*/
class ZmodemReceiveSession extends ZmodemSessionBase {
_file_info: any = null
_textdecoder: TextDecoder = new TextDecoder()
_current_transfer: any = null
_accepted_offer: boolean = false
_offset_ok: boolean = false
_file_offset: number = 0
_attn: any
_started: boolean = false
type: string = 'receive'
// We only get 1 file at a time, so on each consume() either
// continue state for the current file or start a new one.
/**
* Not called directly.
*/
constructor () {
super()
this._Add_event('offer')
this._Add_event('data_in')
this._Add_event('file_end')
}
/**
* Consume input bytes from the sender.
*
* @private
* @param {number[]} octets - The bytes to consume.
*/
_before_consume (octets: number[]): void {
if (this._bytes_after_OO != null) {
throw new Error('PROTOCOL: Session is completed!')
}
// Put this here so that our logic later on has access to the
// input string and can populate _bytes_after_OO when the
// session ends.
this._bytes_being_consumed = octets
}
/**
* Return any bytes that have been `consume()`d but
* came after the end of the ZMODEM session.
*
* @returns {number[]} The trailing bytes.
*/
get_trailing_bytes (): number[] {
if (this._aborted) return []
if (this._bytes_after_OO == null) {
throw new Error('PROTOCOL: Session is not completed!')
}
return this._bytes_after_OO.slice(0)
}
// Receiver always sends hex headers.
// _get_header_formatter() { return 'to_hex' }
_parse_and_consume_subpacket (): ZmodemSubpacket {
let parseFunc
if (this._last_header_crc === 16) {
parseFunc = 'parse16'
} else {
parseFunc = 'parse32'
}
const subpacket = (ZmodemSubpacket as any)[parseFunc](this._input_buffer)
if (subpacket !== undefined) {
if (this.DEBUG) {
console.debug(this.type, 'RECEIVED SUBPACKET', subpacket)
}
this._consume_data(subpacket)
// What state are we in if the subpacket indicates frame end
// but we haven’t gotten ZEOF yet? Can anything other than ZEOF
// follow after a ZDATA?
if (subpacket.frame_end() === true) {
this._next_subpacket_handler = null
}
}
return subpacket
}
_consume_data (subpacket: ZmodemSubpacket): void {
this._on_receive(subpacket)
if (this._next_subpacket_handler == null) {
throw new Error('PROTOCOL: Received unexpected data packet after ' + this._last_header_name + ' header: ' + subpacket.getPayload().join())
}
this._next_subpacket_handler(subpacket)
}
_octets_to_string (octets: number[]): string {
return this._textdecoder.decode(new Uint8Array(octets))
}
_consume_ZFILE_data (hdr: ZmodemHeader, subpacket: ZmodemSubpacket): void {
if (this._file_info !== null) {
throw new Error('PROTOCOL: second ZFILE data subpacket received')
}
const packetPayload = subpacket.getPayload()
const nulAt = packetPayload.indexOf(0)
//
const fname = this._octets_to_string(packetPayload.slice(0, nulAt))
const theRest = this._octets_to_string(packetPayload.slice(1 + nulAt)).split(' ')
const mtime = theRest[1] !== undefined ? parseInt(theRest[1], 8) : undefined
let date
if (mtime !== undefined) {
date = new Date(mtime * 1000)
}
this._file_info = {
name: fname,
size: theRest[0] !== undefined ? parseInt(theRest[0], 10) : null,
mtime: date ?? mtime ?? 0,
mode: theRest[2] !== undefined ? parseInt(theRest[2], 8) : null,
serial: theRest[3] !== undefined ? parseInt(theRest[3], 10) : null,
files_remaining: theRest[4] !== undefined ? parseInt(theRest[4], 10) : null,
bytes_remaining: theRest[5] !== undefined ? parseInt(theRest[5], 10) : null
}
const xfer = new Offer(
hdr.get_options(),
this._file_info,
this._accept.bind(this),
this._skip.bind(this)
)
this._current_transfer = xfer
// this._Happen('offer', xfer)
}
_consume_ZDATA_data (subpacket: ZmodemSubpacket): void {
if (!this._accepted_offer) {
throw new Error('PROTOCOL: Received data without accepting!')
}
// TODO: Probably should include some sort of preventive against
// infinite loop here: if the peer hasn’t sent us what we want after,
// say, 10 ZRPOS headers then we should send ZABORT and just end.
if (!this._offset_ok) {
console.warn('offset not ok!')
this._send_ZRPOS()
return
}
this._file_offset += subpacket.getPayload().length
this._on_data_in(subpacket)
/*
console.warn('received error from data_in callback retrying', e)
throw 'unimplemented'
*/
if (subpacket.ackExpected() && !subpacket.frame_end()) {
this._send_header('ZACK', ZmodemEncodeLib.pack_u32_le(this._file_offset))
}
}
async _make_promise_for_between_files (): Promise<any> {
return await new Promise((resolve, reject) => {
const betweenFilesHandler = {
ZFILE: (hdr: ZmodemHeader) => {
this._next_subpacket_handler = (subpacket: ZmodemSubpacket) => {
this._next_subpacket_handler = null
this._consume_ZFILE_data(hdr, subpacket)
this._Happen('offer', this._current_transfer)
resolve(this._current_transfer)
}
},
// We use this as a keep-alive. Maybe other
// implementations do, too?
ZSINIT: (hdr: ZmodemHeader) => {
// The content of this header doesn’t affect us
// since all it does is tell us details of how
// the sender will ZDLE-encode binary data. Our
// ZDLE parser doesn’t need to know in advance.
this._next_subpacket_handler = function (spkt: ZmodemSubpacket) {
this._next_subpacket_handler = null
this._consume_ZSINIT_data(spkt)
this._send_header('ZACK')
this._next_header_handler = betweenFilesHandler
}
},
ZFIN: () => {
this._consume_ZFIN()
resolve('ok')
}
}
this._next_header_handler = betweenFilesHandler
})
}
_consume_ZSINIT_data (spkt: ZmodemSubpacket): void {
// TODO: Should this be used when we signal a cancellation?
this._attn = spkt.getPayload()
}
/**
* Start the ZMODEM session by signaling to the sender that
* we are ready for the first file offer.
*
* @returns {Promise} A promise that resolves with an Offer object
* or, if the sender closes the session immediately without offering
* anything, nothing.
*/
async start (): Promise<any> {
if (this._started) throw new Error('Already started!')
this._started = true
const ret = this._make_promise_for_between_files()
this._send_ZRINIT()
return await ret
}
// Returns a promise that’s fulfilled when the file
// transfer is done.
//
// That ZEOF promise return is another promise that’s
// fulfilled when we get either ZFIN or another ZFILE.
async _accept (offset: number = 0): Promise<any> {
this._accepted_offer = true
this._file_offset = offset
const ret = new Promise((resolve) => {
this._next_header_handler = {
ZDATA: (hdr: ZmodemHeader) => {
this._consume_ZDATA(hdr)
this._next_subpacket_handler = this._consume_ZDATA_data
this._next_header_handler = {
ZEOF: (hdr: ZmodemHeader) => {
// Do this first to verify the ZEOF.
// This also fires the “file_end” event.
this._consume_ZEOF(hdr)
this._next_subpacket_handler = null
// We don’t care about this promise.
// Prior to v0.1.8 we did because we called
// resolve_accept() at the resolution of this
// promise, but that was a bad idea and was
// never documented, so 0.1.8 changed it.
// eslint-disable-next-line
this._make_promise_for_between_files()
resolve('ok')
this._send_ZRINIT()
}
}
}
}
})
this._send_ZRPOS()
return await ret
}
bound_make_promise_for_between_files = (): void => {
this._accepted_offer = false
this._next_subpacket_handler = null
// eslint-disable-next-line
this._make_promise_for_between_files()
}
async _skip (): Promise<any> {
const ret = this._make_promise_for_between_files()
if (this._accepted_offer) {
if (this._current_transfer === null) return
Object.assign(
this._next_header_handler,
{
ZEOF: this.bound_make_promise_for_between_files,
ZDATA: () => {
this.bound_make_promise_for_between_files()
this._next_header_handler.ZEOF = this.bound_make_promise_for_between_files
}
}
)
}
// this._accepted_offer = false
this._file_info = null
this._send_header('ZSKIP')
return await ret
}
_send_ZRINIT (): void {
this._send_header('ZRINIT', ZRINIT_FLAGS)
}
_consume_ZFIN (): void {
this._got_ZFIN = true
this._send_header('ZFIN')
}
_consume_ZEOF (header: ZmodemHeader): void {
if (this._file_offset !== header.get_offset()) {
throw new Error(`ZEOF offset mismatch unimplemented (local: ${this._file_offset} ZEOF: ${header.get_offset()} )`)
}
this._on_file_end()
// Preserve these two so that file_end callbacks
// will have the right information.
this._file_info = null
this._current_transfer = null
}
_consume_ZDATA (header: ZmodemHeader): void {
if (this._file_offset === header.get_offset()) {
this._offset_ok = true
} else {
throw new Error('Error correction is unimplemented.')
}
}
_send_ZRPOS (): void {
this._send_header('ZRPOS', this._file_offset)
}
// ----------------------------------------------------------------------
// events
_on_file_end (): void {
this._Happen('file_end')
if (this._current_transfer !== null) {
this._current_transfer._Happen('complete')
this._current_transfer = null
}
}
_on_data_in (subpacket: ZmodemSubpacket): void {
this._Happen('data_in', subpacket)
if (this._current_transfer !== null) {
this._current_transfer._Happen('input', subpacket.getPayload())
}
}
}
export default ZmodemReceiveSession
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zsess-sender.ts
|
TypeScript
|
import { ZmodemHeader } from './zheader'
import { ValidateParams, Obj } from './types'
import ZmodemValidation from './zvalidation'
import ZmodemZDLE from './zdle'
import ZmodemSubpacket from './zsubpacket'
import ZmodemSessionBase from './zsess-base'
import Transfer from './transfer'
const
// pertinent to this module
KEEPALIVE_INTERVAL = 5000
// We do this because some WebSocket shell servers
// (e.g., xterm.js's demo server) enable the IEXTEN termios flag,
// which bars 0x0f and 0x16 from reaching the shell process,
// which results in transmission errors.
const FORCE_ESCAPE_CTRL_CHARS = true
// pertinent to ZMODEM
const MAX_CHUNK_LENGTH = 8192 // 1 KiB officially, but lrzsz allows 8192
const OVER_AND_OUT = [79, 79]
// Curious that ZSINIT isn’t here … but, lsz sends it as hex.
const SENDER_BINARY_HEADER: Obj = {
ZFILE: true,
ZDATA: true
}
/** A class for ZMODEM receive sessions.
*
* @extends Session
*/
class ZmodemSendSession extends ZmodemSessionBase {
_subpacket_encode_func: any
_start_keepalive_on_set_sender: boolean
_keepalive_promise: any = null
_keepalive_timeout: any
_got_ZSINIT_ZACK: boolean = false
_textencoder: TextEncoder = new TextEncoder()
_sent_OO: any
_sending_file: boolean = false
// _offset_ok: boolean = false
_file_offset: number = 0
_last_ZRINIT?: ZmodemHeader
_sent_ZDATA: boolean = false
type: string = 'send'
_sender: Function = () => null
// We only get 1 file at a time, so on each consume() either
// continue state for the current file or start a new one.
/**
* Not called directly.
*/
constructor (zrinitHdr?: ZmodemHeader) {
super()
if (zrinitHdr === undefined) {
throw new Error('Need first header!')
} else if (zrinitHdr.NAME !== 'ZRINIT') {
throw new Error('First header should be ZRINIT, not ' + zrinitHdr.NAME)
}
this._last_header_name = 'ZRINIT'
// We don’t need to send crc32. Even if the other side can grok it,
// there’s no point to sending it since, for now, we assume we’re
// on a reliable connection, e.g., TCP. Ideally we’d just forgo
// CRC checks completely, but ZMODEM doesn’t allow that.
//
// If we *were* to start using crc32, we’d update this every time
// we send a header.
this._subpacket_encode_func = 'encode16'
this._zencoder = new ZmodemZDLE()
this._consume_ZRINIT(zrinitHdr)
this._file_offset = 0
this._start_keepalive_on_set_sender = true
// lrzsz will send ZRINIT until it gets an offer. (keep-alive?)
// It sends 4 additional ones after the initial ZRINIT and, if
// no response is received, starts sending “C” (0x43, 67) as if to
// try to downgrade to XMODEM or YMODEM.
// let sess = this
// this._prepare_to_receive_ZRINIT( function keep_alive() {
// sess._prepare_to_receive_ZRINIT(keep_alive)
// } )
// queue up the ZSINIT flag to send -- but seems useless??
/*
Object.assign(
this._on_evt,
{
file_received: [],
},
}
*/
}
/**
* Sets the sender function. The first time this is called,
* it will also initiate a keepalive using ZSINIT until the
* first file is sent.
*
* @param {Function} func - The function to call.
* It will receive an Array with the relevant octets.
*
* @return {Session} The session object (for chaining).
*/
set_sender = (func: Function): this => {
super.set_sender(func)
if (this._start_keepalive_on_set_sender) {
this._start_keepalive_on_set_sender = false
this._start_keepalive()
}
return this
}
// 7.3.3 .. The sender also uses hex headers when they are
// not followed by binary data subpackets.
//
// FG: … or when the header is ZSINIT? That’s what lrzsz does, anyway.
// Then it sends a single NUL byte as the payload to an end_ack subpacket.
_get_header_formatter (name: string): string {
return SENDER_BINARY_HEADER[name] === true ? 'to_binary16' : 'to_hex'
}
// In order to keep lrzsz from timing out, we send ZSINIT every 5 seconds.
// Maybe make this configurable?
_start_keepalive = (): void => {
// if (this._keepalive_promise) throw 'Keep-alive already started!'
if (this._keepalive_promise === null) {
this._keepalive_promise = new Promise((resolve) => {
this._keepalive_timeout = setTimeout(resolve, KEEPALIVE_INTERVAL)
}).then(() => {
this._next_header_handler = {
ZACK: () => {
// We’re going to need to ensure that the
// receiver is ready for all control characters
// to be escaped. If we’ve already sent a ZSINIT
// and gotten a response, then we know that that
// work is already done later on when we actually
// send an offer.
this._got_ZSINIT_ZACK = true
}
}
this._send_ZSINIT()
this._keepalive_promise = null
this._start_keepalive()
})
}
}
_stop_keepalive (): void {
if (this._keepalive_promise !== null) {
clearTimeout(this._keepalive_timeout)
this._keepalive_promise = null
}
}
_send_ZSINIT (): void {
// See note at _ensure_receiver_escapes_ctrl_chars()
// for why we have to pass ESCCTL.
const zsinitFlags: any[] = []
if (this._zencoder.escapes_ctrl_chars()) {
zsinitFlags.push('ESCCTL' as never)
}
this._send_header_and_data(
['ZSINIT', zsinitFlags],
[0],
'end_ack'
)
}
_consume_ZRINIT (hdr: ZmodemHeader): void {
this._last_ZRINIT = hdr
const size = hdr.get_buffer_size() as string
if (size !== undefined) {
throw new Error(`Buffer size ( ${size} ) is unsupported!`)
}
if (!hdr.can_full_duplex()) {
throw new Error('Half-duplex I/O is unsupported!')
}
if (!hdr.can_overlap_io()) {
throw new Error('Non-overlap I/O is unsupported!')
}
if (hdr.escape_8th_bit()) {
throw new Error('8-bit escaping is unsupported!')
}
if (FORCE_ESCAPE_CTRL_CHARS) {
this._zencoder.set_escape_ctrl_chars(true)
if (!hdr.escape_ctrl_chars()) {
console.debug('Peer didn’t request escape of all control characters. Will send ZSINIT to force recognition of escaped control characters.')
}
} else {
this._zencoder.set_escape_ctrl_chars(hdr.escape_ctrl_chars())
}
}
// https://stackoverflow.com/questions/23155939/missing-0xf-and-0x16-when-binary-data-through-virtual-serial-port-pair-created-b
// ^^ Because of that, we always escape control characters.
// The alternative would be that lrz would never receive those
// two bytes from zmodem.js.
_ensure_receiver_escapes_ctrl_chars = async (): Promise<any> => {
let promise
const needsZSINIT = this._last_ZRINIT !== undefined &&
!this._last_ZRINIT.escape_ctrl_chars() &&
!this._got_ZSINIT_ZACK
if (needsZSINIT) {
promise = new Promise((resolve) => {
this._next_header_handler = {
ZACK: (hdr: ZmodemHeader) => {
resolve('')
}
}
this._send_ZSINIT()
})
} else {
promise = Promise.resolve()
}
return await promise
}
_convert_params_to_offer_payload_array = (_params: ValidateParams): number[] => {
const params = ZmodemValidation.offerParameters(_params)
let subpacketPayload = params.name + '\x00'
const subpacketSpacePieces = [
(params.size ?? 0).toString(10),
params.mtime !== undefined ? params.mtime.toString(8) : '0',
params.mode !== undefined ? (0x8000 | params.mode).toString(8) : '0',
'0' // serial
]
if (params.files_remaining !== undefined) {
subpacketSpacePieces.push(params.files_remaining as never)
if (params.bytes_remaining !== undefined) {
subpacketSpacePieces.push(params.bytes_remaining as never)
}
}
subpacketPayload += subpacketSpacePieces.join(' ')
return this._string_to_octets(subpacketPayload)
}
/**
* Send an offer to the receiver.
*
* @param {FileDetails} params - All about the file you want to transfer.
*
* @returns {Promise} If the receiver accepts the offer, then the
* resolution is a Transfer object otherwise the resolution is
* undefined.
*/
send_offer = async (params: ValidateParams): Promise<any> => {
if (this.DEBUG) {
console.debug('SENDING OFFER', params)
}
if (this._sending_file) throw new Error('Already sending file!')
const payloadArray = this._convert_params_to_offer_payload_array(params)
this._stop_keepalive()
const zrposHandlerSetterFunc = (): void => {
this._next_header_handler = {
// The receiver may send ZRPOS in at least two cases:
//
// 1) A malformed subpacket arrived, so we need to
// “rewind” a bit and continue from the receiver’s
// last-successful location in the file.
//
// 2) The receiver hasn’t gotten any data for a bit,
// so it sends ZRPOS as a “ping”.
//
// Case #1 shouldn’t happen since zmodem.js requires a
// reliable transport. Case #2, though, can happen due
// to either normal network congestion or errors in
// implementation. In either case, there’s nothing for
// us to do but to ignore the ZRPOS, with an optional
// warning.
//
ZRPOS: (hdr: ZmodemHeader) => {
zrposHandlerSetterFunc()
}
}
}
const doerFunc = async (): Promise<any> => {
// return Promise object that is fulfilled when the ZRPOS or ZSKIP arrives.
// The promise value is the byte offset, or undefined for ZSKIP.
// If ZRPOS arrives, then send ZDATA(0) and set this._sending_file.
const handlerSetterPromise = new Promise((resolve) => {
this._next_header_handler = {
ZSKIP: () => {
this._start_keepalive()
resolve('')
},
ZRPOS: (hdr: ZmodemHeader) => {
this._sending_file = true
zrposHandlerSetterFunc()
resolve(
new Transfer(
params,
hdr.get_offset(),
this._send_interim_file_piece.bind(this),
this._end_file.bind(this)
)
)
}
}
})
this._send_header_and_data(['ZFILE'], payloadArray, 'end_ack')
this._sent_ZDATA = false
return await handlerSetterPromise
}
if (FORCE_ESCAPE_CTRL_CHARS) {
return await this._ensure_receiver_escapes_ctrl_chars().then(doerFunc)
}
return await doerFunc()
}
_send_header_and_data = (hdrNameAndArgs: any[], dataArr: any[], frameEnd: string): void => {
const [name, ...args] = hdrNameAndArgs
const bytesHdr = this._create_header_bytes(name, ...args)
const dataBytes = this._build_subpacket_bytes(dataArr, frameEnd)
bytesHdr[0].push.apply(bytesHdr[0], dataBytes)
if (this.DEBUG) {
this._log_header('SENDING HEADER', bytesHdr[1])
console.debug(this.type, '-- HEADER PAYLOAD:', frameEnd, dataBytes.length)
}
this._sender(bytesHdr[0])
this._last_sent_header = bytesHdr[1]
}
_build_subpacket_bytes = (bytesArr: number[], frameEnd: string): any => {
const subpacket = ZmodemSubpacket.build(bytesArr, frameEnd)
return (subpacket as any)[this._subpacket_encode_func](this._zencoder)
}
_build_and_send_subpacket = (bytesArr: number[], frameEnd: string): void => {
this._sender(this._build_subpacket_bytes(bytesArr, frameEnd))
}
_string_to_octets = (str: string): number[] => {
const uint8arr = this._textencoder.encode(str)
return Array.prototype.slice.call(uint8arr)
}
/*
Potential future support for responding to ZRPOS:
send_file_offset(offset) {
}
*/
/*
Sending logic works thus:
- ASSUME the receiver can overlap I/O (CANOVIO)
(so fail if !CANFDX || !CANOVIO)
- Sender opens the firehose … all ZCRCG (!end/!ack)
until the end, when we send a ZCRCE (end/!ack)
NB: try 8k/32k/64k chunk sizes? Looks like there’s
no need to change the packet otherwise.
*/
// TODO: Put this on a Transfer object similar to what Receive uses?
_send_interim_file_piece = async (bytesObj: number[]): Promise<any> => {
// We don’t ask the receiver to confirm because there’s no need.
this._send_file_part(bytesObj, 'no_end_no_ack')
// This pattern will allow
// error-correction without buffering the entire stream in JS.
// For now the promise is always resolved, but in the future we
// can make it only resolve once we’ve gotten acknowledgement.
return await Promise.resolve()
}
_ensure_we_are_sending = (): void => {
if (!this._sending_file) throw new Error('Not sending a file currently!')
}
// This resolves once we receive ZEOF.
_end_file = async (bytesObj: number[]): Promise<any> => {
this._ensure_we_are_sending()
// Is the frame-end-ness of this last packet redundant
// with the ZEOF packet?? - No. It signals the receiver that
// the next thing to expect is a header, not a packet.
// no-ack, following lrzsz’s example
this._send_file_part(bytesObj, 'end_no_ack')
// Register this before we send ZEOF in case of local round-trip.
// (Basically just for synchronous testing, but.)
const ret = new Promise((resolve) => {
this._sending_file = false
this._prepare_to_receive_ZRINIT(resolve)
})
this._send_header('ZEOF', this._file_offset)
this._file_offset = 0
return await ret
}
// Called at the beginning of our session
// and also when we’re done sending a file.
_prepare_to_receive_ZRINIT = (afterConsume: Function): void => {
this._next_header_handler = {
ZRINIT: (hdr: ZmodemHeader) => {
this._consume_ZRINIT(hdr)
afterConsume()
}
}
}
/**
* Signal to the receiver that the ZMODEM session is wrapping up.
*
* @returns {Promise} Resolves when the receiver has responded to
* our signal that the session is over.
*/
close = async (): Promise<any> => {
let okToClose = (this._last_header_name === 'ZRINIT')
if (!okToClose) {
okToClose = (this._last_header_name === 'ZSKIP')
}
if (!okToClose) {
okToClose = (this._last_sent_header.name === 'ZSINIT') && (this._last_header_name === 'ZACK')
}
if (!okToClose) {
throw new Error('Can’t close last received header was “' + this._last_header_name + '”')
}
const ret = new Promise((resolve) => {
this._next_header_handler = {
ZFIN: () => {
this._sender(OVER_AND_OUT)
this._sent_OO = true
this._on_session_end()
resolve('')
}
}
})
this._send_header('ZFIN')
return await ret
}
_has_ended = (): boolean => {
return this.aborted() || this._sent_OO
}
_send_file_part = (bytesObj: number[], finalPacketend: string): void => {
if (!this._sent_ZDATA) {
this._send_header('ZDATA', this._file_offset)
this._sent_ZDATA = true
}
let objOffset = 0
const bytesCount = bytesObj.length
// We have to go through at least once in event of an
// empty buffer, e.g., an empty end_file.
while (true) {
const chunkSize = Math.min(objOffset + MAX_CHUNK_LENGTH, bytesCount) - objOffset
const atEnd = (chunkSize + objOffset) >= bytesCount
let chunk = bytesObj.slice(objOffset, objOffset + chunkSize)
if (!(chunk instanceof Array)) {
chunk = Array.prototype.slice.call(chunk)
}
this._build_and_send_subpacket(
chunk,
atEnd ? finalPacketend : 'no_end_no_ack'
)
this._file_offset += chunkSize
objOffset += chunkSize
if (objOffset >= bytesCount) break
}
}
_consume_first = (): void => {
if (this._parse_and_consume_header() == null) {
// When the ZMODEM receive program starts, it immediately sends
// a ZRINIT header to initiate ZMODEM file transfers, or a
// ZCHALLENGE header to verify the sending program. The receive
// program resends its header at response time (default 10 second)
// intervals for a suitable period of time (40 seconds total)
// before falling back to YMODEM protocol.
if (this._input_buffer.join() === '67') {
throw new Error('Receiver has fallen back to YMODEM.')
}
}
}
_on_session_end = (): void => {
this._stop_keepalive()
super._on_session_end()
}
}
export default ZmodemSendSession
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zsession.ts
|
TypeScript
|
import ZmodemSessionBase from './zsess-base'
import { ZmodemHeader } from './zheader'
import ZmodemReceiveSession from './zsess-receive'
import ZmodemSendSession from './zsess-sender'
class ZmodemSession extends ZmodemSessionBase {
static parse (octets: number[]): ZmodemReceiveSession | ZmodemSendSession | undefined {
// Will need to trap errors.
let hdr: any
try {
hdr = ZmodemHeader.parse_hex(octets)
} catch (e) { // Don’t report since we aren’t in session
// debug
console.warn('No hex header: ', e)
return
}
switch (hdr.NAME) {
case 'ZRQINIT':
// throw if ZCOMMAND
return new ZmodemReceiveSession()
case 'ZRINIT':
return new ZmodemSendSession(hdr)
}
// console.warn('Invalid first Zmodem header', hdr)
}
}
export default ZmodemSession
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zsubpacket.ts
|
TypeScript
|
import ZMLIB from './zmlib'
import CRC from './zcrc'
import ZmodemZDLE from './zdle'
const ZCRCE = 0x68
const ZCRCG = 0x69
const ZCRCQ = 0x6a
const ZCRCW = 0x6b
interface SubpacketType {
[key: string]: AnyClass
}
interface SubpacketType1 {
[key: number]: AnyClass
}
type AnyClass =
| typeof ZEndNoAckSubpacket
| typeof ZEndAckSubpacket
| typeof ZNoEndNoAckSubpacket
| typeof ZNoEndAckSubpacket
class ZmodemSubpacketBase {
_frameendNum = 0
_payload: number[] = []
constructor (payload: number[]) {
this._payload = payload
}
encode16 (zencoder: ZmodemZDLE): number[] {
return this._encode(zencoder, CRC.crc16)
}
encode32 (zencoder: ZmodemZDLE): number[] {
return this._encode(zencoder, CRC.crc32)
}
getPayload (): number[] {
return this._payload
}
_encode (zencoder: ZmodemZDLE, crcFunc: Function): any[] {
return [
...zencoder.encode(this._payload.slice(0)),
ZMLIB.ZDLE,
this._frameendNum,
...zencoder.encode(crcFunc([...this._payload, this._frameendNum]))
]
}
ackExpected (): boolean { return false }
frame_end (): boolean { return false }
}
class ZEndSubpacketBase extends ZmodemSubpacketBase {
frame_end (): boolean {
return true
}
}
class ZNoEndSubpacketBase extends ZmodemSubpacketBase {
frame_end (): boolean {
return false
}
}
class ZEndNoAckSubpacket extends ZEndSubpacketBase {
_frameendNum = ZCRCE
ackExpected (): boolean {
return false
}
}
class ZEndAckSubpacket extends ZEndSubpacketBase {
_frameendNum = ZCRCW
ackExpected (): boolean {
return true
}
}
class ZNoEndNoAckSubpacket extends ZNoEndSubpacketBase {
_frameendNum = ZCRCG
ackExpected (): boolean {
return false
}
}
class ZNoEndAckSubpacket extends ZNoEndSubpacketBase {
_frameendNum = ZCRCQ
ackExpected (): boolean {
return true
}
}
const SUBPACKET_BUILDER: SubpacketType = {
end_no_ack: ZEndNoAckSubpacket,
end_ack: ZEndAckSubpacket,
no_end_no_ack: ZNoEndNoAckSubpacket,
no_end_ack: ZNoEndAckSubpacket
}
class ZmodemSubpacket extends ZmodemSubpacketBase {
static build (octets: number[], frameend: string): AnyClass {
const Ctr = SUBPACKET_BUILDER[frameend]
if (Ctr === undefined) {
throw new Error(`No subpacket type “${frameend}” is defined! Try one of: ${Object.keys(
SUBPACKET_BUILDER
).join(', ')}`)
}
return new Ctr(octets) as any
}
static parse16 (octets: number[]): AnyClass | undefined {
return ZmodemSubpacket._parse(octets, 2)
}
static parse32 (octets: number[]): AnyClass | undefined {
return ZmodemSubpacket._parse(octets, 4)
}
static _parse (bytesArr: number[], crcLen: number): AnyClass | undefined {
let endAt = 0
let Creator
const _frameEndsLookup: SubpacketType1 = {
104: ZEndNoAckSubpacket,
105: ZNoEndNoAckSubpacket,
106: ZNoEndAckSubpacket,
107: ZEndAckSubpacket
}
let zdleAt = 0
while (zdleAt < bytesArr.length) {
zdleAt = bytesArr.indexOf(ZMLIB.ZDLE, zdleAt)
if (zdleAt === -1) return
const afterZdle = bytesArr[zdleAt + 1]
Creator = _frameEndsLookup[afterZdle]
if (Creator !== undefined) {
endAt = zdleAt + 1
break
}
zdleAt++
}
if (Creator == null) return
const frameendNum = bytesArr[endAt]
if (bytesArr[endAt - 1] !== ZMLIB.ZDLE) {
throw new Error(`Byte before frame end should be ZDLE, not ${bytesArr[endAt - 1]}`)
}
const zdleEncodedPayload = bytesArr.splice(0, endAt - 1)
const gotCrc = ZmodemZDLE.splice(bytesArr, 2, crcLen)
if (gotCrc == null) {
// Restore the payload bytes without using unshift.apply which could overflow
// for large payloads
const restored = zdleEncodedPayload.concat(bytesArr.splice(0))
bytesArr.length = 0
for (let i = 0; i < restored.length; i++) {
bytesArr[i] = restored[i]
}
return
}
const payload = ZmodemZDLE.decode(zdleEncodedPayload)
CRC[crcLen === 2 ? 'verify16' : 'verify32'](
[...payload, frameendNum],
gotCrc
)
return new Creator(payload) as any
}
frame_end (): boolean { return false }
}
export default ZmodemSubpacket
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/zvalidation.ts
|
TypeScript
|
import ZmodemError from './zerror'
import { ValidateParams } from './types'
// eslint-disable-next-line
const LOOKS_LIKE_ZMODEM_HEADER = /\*\x18[AC]|\*\*\x18B/
function validateNumber (key: string, value: number): void {
if (value < 0) {
throw new ZmodemError(
'validation',
`“${key}” (${value}) must be nonnegative.`
)
}
if (value !== Math.floor(value)) {
throw new ZmodemError(
'validation',
`“${key}” (${value}) must be an integer.`
)
}
}
/**
* Validation logic for zmodem.js
* params : {
name?: string
serial?: any
size?: number
mode?: number
files_remaining?: number
bytes_remaining?: number
mtime?: number | Date | null
}
*
* @exports Validation
*/
const ZmodemValidation = {
offerParameters (params: ValidateParams): ValidateParams {
// So that we can override values as is useful
// without affecting the passed-in object.
params = Object.assign({}, params)
if (LOOKS_LIKE_ZMODEM_HEADER.test(params.name ?? '')) {
console.warn(
`The filename ${JSON.stringify(params.name)} contains characters that look like a ZMODEM header. This could corrupt the ZMODEM session; consider renaming it so that the filename doesn’t contain control characters.`
)
}
if (params.serial !== null && params.serial !== undefined) {
throw new ZmodemError('validation', '“serial” is meaningless.')
}
params.serial = null
if (typeof params.mode === 'number') {
params.mode |= 0x8000
}
if (params.files_remaining === 0) {
throw new ZmodemError(
'validation',
'“files_remaining”, if given, must be positive.'
)
}
let mtimeOk
const mt = params.mtime ?? 0
switch (typeof mt) {
case 'object':
mtimeOk = true
if (mt instanceof Date) {
params.mtime = Math.floor(mt.getTime() / 1000)
} else if (params.mtime !== null) {
mtimeOk = false
}
break
case 'undefined':
params.mtime = 0
mtimeOk = true
break
case 'number':
validateNumber('mtime', mt)
mtimeOk = true
break
}
if (!mtimeOk) {
throw new ZmodemError(
'validation',
`“mtime” (${mt.toString()}) must be null, undefined, a Date, or a number.`
)
}
return params
}
}
export default ZmodemValidation
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
tests/encode.spec.ts
|
TypeScript
|
import { ZmodemEncodeLib } from '../src/encode' // Adjust the path to match your actual file location
describe('pack_u16_be', () => {
it('should correctly pack a 16-bit number', () => {
const packed = ZmodemEncodeLib.pack_u16_be(1234)
expect(packed).toEqual([4, 210]) // Expected packed values
})
it('should throw an error if the number exceeds 16 bits', () => {
expect(() => ZmodemEncodeLib.pack_u16_be(65536)).toThrowError(
'Number cannot exceed 16 bits: 65536'
)
})
})
describe('pack_u32_le', () => {
it('should correctly pack a 32-bit number', () => {
const testCases = [
{ input: 0, expected: [0, 0, 0, 0] },
{ input: 1, expected: [1, 0, 0, 0] },
{ input: 256, expected: [0, 1, 0, 0] },
{ input: 65536, expected: [0, 0, 1, 0] },
{ input: 4294967295, expected: [255, 255, 255, 255] }
]
for (const testCase of testCases) {
const result = ZmodemEncodeLib.pack_u32_le(testCase.input)
console.log(testCase.input, result)
expect(result).toEqual(testCase.expected)
}
})
})
describe('unpack_u16_be', () => {
it('should correctly unpack a big-endian 16-bit number', () => {
const unpacked = ZmodemEncodeLib.unpack_u16_be([4, 210])
expect(unpacked).toBe(1234) // Expected unpacked value
})
})
describe('unpack_u32_le', () => {
it('should correctly unpack a little-endian 32-bit number', () => {
const testCases = [
{ expected: 0, input: [0, 0, 0, 0] },
{ expected: 1, input: [1, 0, 0, 0] },
{ expected: 256, input: [0, 1, 0, 0] },
{ expected: 65536, input: [0, 0, 1, 0] },
{ expected: 4294967295, input: [255, 255, 255, 255] }
]
for (const testCase of testCases) {
const result = ZmodemEncodeLib.unpack_u32_le(testCase.input)
console.log(testCase.input, result)
expect(result).toEqual(testCase.expected)
}
})
})
describe('octets_to_hex', () => {
it('should convert octets to their hex representation', () => {
const hex = ZmodemEncodeLib.octets_to_hex([0, 1, 2, 3])
expect(hex).toEqual([
48, 48, 48, 49,
48, 50, 48, 51
]) // Expected hex values
})
})
describe('parse_hex_octets', () => {
it('should correctly parse hex octets', () => {
const parsed = ZmodemEncodeLib.parse_hex_octets([
48, 48, 48, 49,
48, 50, 48, 51
])
expect(parsed).toEqual([0, 1, 2, 3]) // Expected parsed values
})
})
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
tests/websocket-zmodem.spec.ts
|
TypeScript
|
/**
* WebSocket ZMODEM Transfer Test Suite
*
* Tests ZMODEM transfers over WebSocket connections similar to electerm usage.
* Covers both rz (receive) and sz (send) operations with chunked data.
*
* Addresses issues:
* - Stack overflow in _strip_and_enqueue_input with large data chunks
* - CRC check failures
* - Slow transfer speeds due to inefficient data handling
*/
import ZmodemSentry from '../src/zsentry'
// Mock WebSocket class for testing
class MockWebSocket {
readyState: number = WebSocket.OPEN
binaryType: string = 'arraybuffer'
listeners: { [event: string]: Function[] } = {}
sentData: Uint8Array[] = []
constructor() {
this.readyState = WebSocket.OPEN
}
addEventListener(event: string, listener: Function) {
if (!this.listeners[event]) {
this.listeners[event] = []
}
this.listeners[event].push(listener)
}
removeEventListener(event: string, listener: Function) {
if (this.listeners[event]) {
this.listeners[event] = this.listeners[event].filter(l => l !== listener)
}
}
send(data: Uint8Array) {
this.sentData.push(data)
}
// Simulate receiving data from the server
simulateMessage(data: ArrayBuffer | string) {
const event = { data }
const listeners = this.listeners.message || []
listeners.forEach(listener => listener(event))
}
close() {
this.readyState = WebSocket.CLOSED
}
}
// Mock terminal for testing
class MockTerminal {
writtenData: string = ''
write(data: string) {
this.writtenData += data
}
reset() {
this.writtenData = ''
}
}
describe('WebSocket ZMODEM Transfers (electerm-style)', () => {
let mockSocket: MockWebSocket
let mockTerminal: MockTerminal
let sentry: ZmodemSentry
beforeEach(() => {
mockSocket = new MockWebSocket()
mockTerminal = new MockTerminal()
// Set up ZmodemSentry like electerm does
sentry = new ZmodemSentry({
to_terminal: (octets: number[]) => {
// Safe version that handles large arrays without stack overflow
// This is how electerm SHOULD implement it to avoid the bug
if (octets.length > 10000) {
// For large data, process in chunks to avoid stack overflow
const chunks = []
for (let i = 0; i < octets.length; i += 10000) {
chunks.push(String.fromCharCode.apply(String, octets.slice(i, i + 10000)))
}
mockTerminal.write(chunks.join(''))
} else {
mockTerminal.write(String.fromCharCode.apply(String, octets))
}
},
sender: (octets: number[]) => {
mockSocket.send(new Uint8Array(octets))
},
on_retract: () => {
// Handle retraction
},
on_detect: (detection: any) => {
// Handle detection
}
})
mockSocket.binaryType = 'arraybuffer'
mockSocket.addEventListener('message', (evt: any) => {
if (typeof evt.data === 'string') {
mockTerminal.write(evt.data)
} else {
sentry.consume(evt.data)
}
})
})
afterEach(() => {
// Clean up sentry reference
sentry = null as any
mockSocket.close()
})
describe('Large data chunk handling', () => {
it('should handle large data chunks without stack overflow', () => {
// Create a large data chunk that could cause stack overflow
const largeData = new ArrayBuffer(1024 * 1024 * 10) // 10MB
const uint8View = new Uint8Array(largeData)
// Fill with some data
for (let i = 0; i < uint8View.length; i++) {
uint8View[i] = i % 256
}
// This should not cause a stack overflow
expect(() => {
mockSocket.simulateMessage(largeData)
}).not.toThrow()
})
it('should handle multiple large chunks sequentially', () => {
const chunkSize = 1024 * 1024 // 1MB chunks
const numChunks = 5
for (let i = 0; i < numChunks; i++) {
const chunk = new ArrayBuffer(chunkSize)
const uint8View = new Uint8Array(chunk)
// Fill with pattern
for (let j = 0; j < chunkSize; j++) {
uint8View[j] = (i + j) % 256
}
expect(() => {
mockSocket.simulateMessage(chunk)
}).not.toThrow()
}
})
it('should handle mixed string and binary messages', () => {
// Simulate terminal output mixed with zmodem data
mockSocket.simulateMessage('normal terminal output\r\n')
const binaryData = new ArrayBuffer(100)
new Uint8Array(binaryData).fill(0x42)
mockSocket.simulateMessage(binaryData)
mockSocket.simulateMessage('more terminal output\r\n')
expect(mockTerminal.writtenData).toContain('normal terminal output')
expect(mockTerminal.writtenData).toContain('more terminal output')
})
})
describe('CRC error handling', () => {
it('should handle CRC verification failures gracefully', () => {
// Create data that would cause CRC failure
// This simulates corrupted data from the network
const corruptedData = new ArrayBuffer(100)
const uint8View = new Uint8Array(corruptedData)
// Fill with some data that might be interpreted as zmodem but corrupted
uint8View[0] = 0x2A // ZPAD
uint8View[1] = 0x2A // ZPAD
uint8View[2] = 0x18 // ZDLE
uint8View[3] = 0x42 // Some data
// Intentionally corrupt the CRC bytes at the end
uint8View[96] = 0xFF
uint8View[97] = 0xFF
uint8View[98] = 0xFF
uint8View[99] = 0xFF
// Should not throw, but might log warnings or handle gracefully
expect(() => {
mockSocket.simulateMessage(corruptedData)
}).not.toThrow()
})
it('should continue processing after CRC errors', () => {
// Send corrupted data first
const corruptedData = new ArrayBuffer(50)
new Uint8Array(corruptedData).fill(0xFF)
// Send valid data after
const validData = new ArrayBuffer(50)
new Uint8Array(validData).fill(0x00)
expect(() => {
mockSocket.simulateMessage(corruptedData)
mockSocket.simulateMessage(validData)
}).not.toThrow()
})
})
describe('ZMODEM receive session (rz) simulation', () => {
it('should handle ZMODEM receive session initialization', () => {
// Simulate ZRQINIT (request to initialize) from sender
const zrinitData = new ArrayBuffer(10)
const view = new Uint8Array(zrinitData)
view[0] = 0x2A // ZPAD
view[1] = 0x2A // ZPAD
view[2] = 0x18 // ZDLE
view[3] = 0x40 // ZRQINIT type
expect(() => {
mockSocket.simulateMessage(zrinitData)
}).not.toThrow()
})
it('should handle file transfer data in chunks', () => {
// Simulate receiving file data in WebSocket chunks
const fileChunks = [
new ArrayBuffer(4096),
new ArrayBuffer(4096),
new ArrayBuffer(2048)
]
// Fill with some file data pattern
fileChunks.forEach((chunk, index) => {
const view = new Uint8Array(chunk)
for (let i = 0; i < view.length; i++) {
view[i] = (index * 256 + i) % 256
}
})
// Send chunks sequentially like WebSocket would
fileChunks.forEach(chunk => {
expect(() => {
mockSocket.simulateMessage(chunk)
}).not.toThrow()
})
})
})
describe('ZMODEM send session (sz) simulation', () => {
it('should handle ZMODEM send session data transmission', () => {
// Simulate data being sent from terminal to remote
const sendData = new ArrayBuffer(1024)
const view = new Uint8Array(sendData)
for (let i = 0; i < view.length; i++) {
view[i] = i % 256
}
// This would typically be triggered by the ZMODEM session
// For now, just verify the mock setup works
expect(mockSocket.sentData).toBeDefined()
expect(Array.isArray(mockSocket.sentData)).toBe(true)
})
it('should queue data sent through WebSocket', () => {
// Simulate multiple send operations
const data1 = new Uint8Array([1, 2, 3, 4])
const data2 = new Uint8Array([5, 6, 7, 8])
mockSocket.send(data1)
mockSocket.send(data2)
expect(mockSocket.sentData.length).toBe(2)
expect(mockSocket.sentData[0]).toEqual(data1)
expect(mockSocket.sentData[1]).toEqual(data2)
})
})
describe('Performance and memory tests', () => {
it('should handle high-frequency message simulation', () => {
const numMessages = 1000
const messageSize = 1024
const startTime = Date.now()
for (let i = 0; i < numMessages; i++) {
const data = new ArrayBuffer(messageSize)
new Uint8Array(data).fill(i % 256)
mockSocket.simulateMessage(data)
}
const endTime = Date.now()
const duration = endTime - startTime
// Should complete within reasonable time (adjust threshold as needed)
expect(duration).toBeLessThan(5000) // 5 seconds max
})
it('should not accumulate memory with continuous data stream', () => {
// This test verifies that the sentry doesn't hold onto old data
const initialMemoryUsage = process.memoryUsage?.().heapUsed || 0
for (let i = 0; i < 100; i++) {
const data = new ArrayBuffer(64 * 1024) // 64KB chunks
new Uint8Array(data).fill(i % 256)
mockSocket.simulateMessage(data)
}
const finalMemoryUsage = process.memoryUsage?.().heapUsed || 0
// Memory usage should not grow excessively (allowing some growth for test overhead)
const memoryGrowth = finalMemoryUsage - initialMemoryUsage
expect(memoryGrowth).toBeLessThan(50 * 1024 * 1024) // Less than 50MB growth
})
})
describe('Error recovery', () => {
it('should handle WebSocket disconnection during transfer', () => {
// Start some data transfer
const data = new ArrayBuffer(1024)
mockSocket.simulateMessage(data)
// Simulate disconnection
mockSocket.close()
mockSocket.readyState = WebSocket.CLOSED
// Further operations should handle the closed state gracefully
expect(() => {
mockSocket.simulateMessage(new ArrayBuffer(100))
}).not.toThrow()
})
it('should handle malformed WebSocket messages', () => {
const badMessages = [
null,
undefined,
{},
[],
42,
new Date()
]
badMessages.forEach(badMessage => {
expect(() => {
mockSocket.simulateMessage(badMessage as any)
}).not.toThrow()
})
})
})
})
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
tests/zmodem-transfer.spec.ts
|
TypeScript
|
/**
* Comprehensive test suite for ZMODEM transfers
*
* Tests for:
* 1. Basic ZMODEM session initialization
* 2. Stack overflow prevention with large data chunks
* 3. CRC verification
* 4. File transfer simulation
*/
import ZmodemSentry from '../src/zsentry'
import ZmodemSession from '../src/zsession'
import ZmodemSessionBase from '../src/zsess-base'
import ZMLIB from '../src/zmlib'
import { ZmodemHeader } from '../src/zheader'
import ZmodemSubpacket from '../src/zsubpacket'
import CRC from '../src/zcrc'
describe('ZMLIB - Core utilities', () => {
describe('stripIgnoredBytes', () => {
it('should strip XON/XOFF bytes from array', () => {
const input = [0x11, 0x65, 0x13, 0x66, 0x91, 0x93] // XON, 'e', XOFF, 'f', XON|0x80, XOFF|0x80
const result = ZMLIB.stripIgnoredBytes(input)
expect(result).toEqual([0x65, 0x66]) // Only 'e' and 'f' should remain
})
it('should handle empty array', () => {
const input: number[] = []
const result = ZMLIB.stripIgnoredBytes(input)
expect(result).toEqual([])
})
it('should handle array with no ignored bytes', () => {
const input = [0x41, 0x42, 0x43] // A, B, C
const result = ZMLIB.stripIgnoredBytes(input)
expect(result).toEqual([0x41, 0x42, 0x43])
})
})
describe('findSubarray', () => {
it('should find subarray at beginning', () => {
const haystack = [1, 2, 3, 4, 5]
const needle = [1, 2]
expect(ZMLIB.findSubarray(haystack, needle)).toBe(0)
})
it('should find subarray in middle', () => {
const haystack = [1, 2, 3, 4, 5]
const needle = [3, 4]
expect(ZMLIB.findSubarray(haystack, needle)).toBe(2)
})
it('should return -1 when not found', () => {
const haystack = [1, 2, 3, 4, 5]
const needle = [6, 7]
expect(ZMLIB.findSubarray(haystack, needle)).toBe(-1)
})
it('should find abort sequence', () => {
const data = [0, 0, 0x18, 0x18, 0x18, 0x18, 0x18, 0, 0]
expect(ZMLIB.findSubarray(data, ZMLIB.ABORT_SEQUENCE)).toBe(2)
})
})
})
describe('CRC verification', () => {
describe('crc16', () => {
it('should calculate correct CRC16', () => {
const data = [0x48, 0x65, 0x6c, 0x6c, 0x6f] // "Hello"
const crc = CRC.crc16(data)
expect(crc).toBeDefined()
expect(Array.isArray(crc)).toBe(true)
expect(crc.length).toBe(2)
})
})
describe('crc32', () => {
it('should calculate correct CRC32', () => {
const data = [0x48, 0x65, 0x6c, 0x6c, 0x6f] // "Hello"
const crc = CRC.crc32(data)
expect(crc).toBeDefined()
expect(Array.isArray(crc)).toBe(true)
expect(crc.length).toBe(4)
})
it('should verify CRC32 correctly', () => {
const data = [0x48, 0x65, 0x6c, 0x6c, 0x6f]
const crc = CRC.crc32(data)
expect(() => CRC.verify32(data, crc)).not.toThrow()
})
it('should throw on CRC32 mismatch', () => {
const data = [0x48, 0x65, 0x6c, 0x6c, 0x6f]
const badCrc = [0, 0, 0, 0]
expect(() => CRC.verify32(data, badCrc)).toThrow(/CRC check failed/)
})
})
})
describe('ZmodemSessionBase - Input buffer handling', () => {
describe('Large data chunk handling (stack overflow prevention)', () => {
it('should handle very large input arrays without stack overflow', () => {
// This test reproduces the "Maximum call stack size exceeded" issue
// The original code used push.apply() which fails with large arrays
const session = new (ZmodemSessionBase as any)()
session._sender = () => {}
// Create a large array (larger than typical call stack limits ~10k-100k)
const largeSize = 200000 // 200KB of data
const largeInput = new Array(largeSize).fill(0x42) // Fill with 'B' bytes
// This should not throw "Maximum call stack size exceeded"
expect(() => {
// Directly test the internal method that was causing issues
session._strip_and_enqueue_input(largeInput)
}).not.toThrow()
// Verify data was correctly added to buffer
expect(session._input_buffer.length).toBe(largeSize)
})
it('should handle multiple consecutive large chunks', () => {
const session = new (ZmodemSessionBase as any)()
session._sender = () => {}
const chunkSize = 100000
const numChunks = 5
for (let i = 0; i < numChunks; i++) {
const chunk = new Array(chunkSize).fill(0x41 + i)
session._strip_and_enqueue_input(chunk)
}
expect(session._input_buffer.length).toBe(chunkSize * numChunks)
})
it('should handle ArrayBuffer input conversion efficiently', () => {
// Test the pattern used in WebSocket message handling
const largeSize = 150000
const arrayBuffer = new ArrayBuffer(largeSize)
const uint8Array = new Uint8Array(arrayBuffer)
// Use values that won't be stripped (avoid XON/XOFF: 0x11, 0x13, 0x91, 0x93)
for (let i = 0; i < largeSize; i++) {
let val = i % 256
// Skip XON/XOFF bytes
if (val === 0x11 || val === 0x13 || val === 0x91 || val === 0x93) {
val = 0x42 // Use 'B' instead
}
uint8Array[i] = val
}
// Convert like the xterm-zmodem.js does
const input = Array.prototype.slice.call(uint8Array)
const session = new (ZmodemSessionBase as any)()
session._sender = () => {}
expect(() => {
session._strip_and_enqueue_input(input)
}).not.toThrow()
// Buffer length equals input length since we avoided XON/XOFF bytes
expect(session._input_buffer.length).toBe(largeSize)
})
})
})
describe('ZmodemSentry', () => {
let sentToTerminal: number[][]
let sentToSender: number[][]
let detections: any[]
let retractions: number
const createSentry = (): ZmodemSentry => {
sentToTerminal = []
sentToSender = []
detections = []
retractions = 0
return new ZmodemSentry({
to_terminal: (octets: number[]) => {
sentToTerminal.push(octets.slice())
},
sender: (octets: number[]) => {
sentToSender.push(octets.slice())
},
on_detect: (detection: any) => {
detections.push(detection)
},
on_retract: () => {
retractions++
}
})
}
describe('Basic sentry operations', () => {
it('should pass non-ZMODEM data to terminal', () => {
const sentry = createSentry()
const data = [0x48, 0x65, 0x6c, 0x6c, 0x6f] // "Hello"
sentry.consume(data)
expect(sentToTerminal.length).toBe(1)
expect(sentToTerminal[0]).toEqual(data)
expect(detections.length).toBe(0)
})
it('should handle ArrayBuffer input', () => {
const sentry = createSentry()
const buffer = new ArrayBuffer(5)
const view = new Uint8Array(buffer)
view.set([0x48, 0x65, 0x6c, 0x6c, 0x6f]) // "Hello"
sentry.consume(buffer)
expect(sentToTerminal.length).toBe(1)
expect(sentToTerminal[0]).toEqual([0x48, 0x65, 0x6c, 0x6c, 0x6f])
})
it('should handle large ArrayBuffer without stack overflow', () => {
const sentry = createSentry()
const size = 200000
const buffer = new ArrayBuffer(size)
const view = new Uint8Array(buffer)
for (let i = 0; i < size; i++) {
view[i] = i % 256
}
expect(() => {
sentry.consume(buffer)
}).not.toThrow()
expect(sentToTerminal.length).toBe(1)
})
})
describe('ZMODEM detection', () => {
it('should detect ZRQINIT header (receive session start)', () => {
const sentry = createSentry()
// ZRQINIT hex header: **\x18B00 followed by header type and CRC
// Full ZRQINIT header in hex format
const zrqinit = [
0x2a, 0x2a, 0x18, 0x42, 0x30, 0x30, // **<ZDLE>B00 (ZRQINIT type 0)
0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, // 8 hex digits for p0-p3
0x30, 0x30, 0x30, 0x30, // 4 hex digits for CRC
0x0d, 0x0a, // CR LF
0x11 // XON
]
sentry.consume(zrqinit)
// Should trigger detection
expect(detections.length).toBe(1)
expect(detections[0]).toBeDefined()
})
})
})
describe('ZmodemSubpacket', () => {
describe('Subpacket creation and encoding', () => {
it('should create end_no_ack subpacket', () => {
const payload = [0x48, 0x65, 0x6c, 0x6c, 0x6f]
// Note: build takes (octets, frameend) not (frameend, octets)
const subpacket = ZmodemSubpacket.build(payload, 'end_no_ack') as any
expect(subpacket).toBeDefined()
expect(subpacket.getPayload()).toEqual(payload)
expect(subpacket.frame_end()).toBe(true)
expect(subpacket.ackExpected()).toBe(false)
})
it('should create no_end_no_ack subpacket', () => {
const payload = [0x41, 0x42, 0x43]
const subpacket = ZmodemSubpacket.build(payload, 'no_end_no_ack') as any
expect(subpacket).toBeDefined()
expect(subpacket.frame_end()).toBe(false)
expect(subpacket.ackExpected()).toBe(false)
})
})
})
describe('ZmodemHeader', () => {
describe('Header building', () => {
it('should build ZRINIT header', () => {
const header = ZmodemHeader.build('ZRINIT', ['CANFDX', 'CANOVIO', 'CANFC32'])
expect(header).toBeDefined()
expect((header as any).NAME).toBe('ZRINIT')
})
it('should build ZRPOS header with offset', () => {
const header = ZmodemHeader.build('ZRPOS', 1024)
expect(header).toBeDefined()
expect((header as any).NAME).toBe('ZRPOS')
})
})
describe('Header parsing', () => {
it('should trim leading garbage from input', () => {
const garbage = [0x00, 0x00, 0x00]
const validHeader = [0x2a, 0x2a, 0x18, 0x42] // Start of hex header
const combined = [...garbage, ...validHeader]
const trimmed = ZmodemHeader.trimLeadingGarbage(combined)
expect(trimmed).toBeDefined()
expect(combined[0]).toBe(0x2a) // Should start with '*'
})
})
})
describe('Simulated WebSocket transfer scenario', () => {
/**
* This test simulates the flow in electerm's xterm-zmodem.js
* where WebSocket binary messages are passed to ZMODEM
*/
describe('WebSocket message handling pattern', () => {
it('should handle rapid consecutive WebSocket messages', () => {
const messages: ArrayBuffer[] = []
const sentry = new ZmodemSentry({
to_terminal: () => {},
sender: () => {},
on_detect: () => {},
on_retract: () => {}
})
// Simulate rapid WebSocket messages (like during file transfer)
const numMessages = 100
const messageSize = 8192 // Typical chunk size
for (let i = 0; i < numMessages; i++) {
const buffer = new ArrayBuffer(messageSize)
const view = new Uint8Array(buffer)
for (let j = 0; j < messageSize; j++) {
view[j] = (i * messageSize + j) % 256
}
messages.push(buffer)
}
// Process all messages - should not throw
expect(() => {
for (const msg of messages) {
sentry.consume(msg)
}
}).not.toThrow()
})
it('should handle the electerm pattern of evt.data consumption', () => {
// This simulates the pattern from xterm-zmodem.js handleWSMessage
const sentry = new ZmodemSentry({
to_terminal: () => {},
sender: () => {},
on_detect: () => {},
on_retract: () => {}
})
// Simulate multiple WebSocket events with ArrayBuffer data
for (let i = 0; i < 50; i++) {
const evt = {
data: new ArrayBuffer(50000) // 50KB chunks
}
const view = new Uint8Array(evt.data)
for (let j = 0; j < view.length; j++) {
view[j] = j % 256
}
expect(() => {
sentry.consume(evt.data)
}).not.toThrow()
}
})
})
})
describe('Performance and memory handling', () => {
it('should efficiently handle high-throughput data', () => {
const sentry = new ZmodemSentry({
to_terminal: () => {},
sender: () => {},
on_detect: () => {},
on_retract: () => {}
})
const startTime = Date.now()
const totalBytes = 10 * 1024 * 1024 // 10MB total
const chunkSize = 64 * 1024 // 64KB chunks
for (let offset = 0; offset < totalBytes; offset += chunkSize) {
const size = Math.min(chunkSize, totalBytes - offset)
const buffer = new ArrayBuffer(size)
sentry.consume(buffer)
}
const elapsed = Date.now() - startTime
console.log(`Processed ${totalBytes / 1024 / 1024}MB in ${elapsed}ms`)
// Should complete in reasonable time (less than 10 seconds for 10MB)
expect(elapsed).toBeLessThan(10000)
})
})
|
zxdong262/zmodem-ts
| 2
|
Typescript fork of FGasper's zmodemjs
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
benchmarks/benchmark.mjs
|
JavaScript
|
import { performance } from 'perf_hooks'
import { readFileSync, writeFileSync } from 'fs'
import { Sender as SenderJs, Receiver as ReceiverJs, Crc32 as Crc32Js } from '../dist/esm/index.js'
import { initSync, WasmSender, WasmReceiver } from 'zmodem2-wasm'
function runBenchmarks () {
console.log('Initializing WASM module...')
const wasmBuffer = readFileSync('node_modules/zmodem2-wasm/pkg/zmodem2_wasm_bg.wasm')
initSync({ module: wasmBuffer })
console.log('WASM module initialized.\n')
const fileSize = 10 * 1024 * 1024 // 10 MB
const fileName = 'benchmark-file.dat'
const fileData = new Uint8Array(fileSize)
for (let i = 0; i < fileSize; i++) {
fileData[i] = i % 256
}
console.log('='.repeat(60))
console.log('ZMODEM2-JS vs ZMODEM2-WASM Performance Benchmark')
console.log('='.repeat(60))
console.log(`File size: ${fileSize / 1024 / 1024} MB`)
console.log(`File name: ${fileName}`)
const results = {
crc: { js: 0, wasm: 0 },
sender: { js: 0, wasm: 0 },
receiver: { js: 0, wasm: 0 }
}
// --- CRC Benchmark ---
console.log('\n--- CRC-32 Calculation Benchmark ---')
// JS CRC-32
console.log('Running JS CRC-32 benchmark...')
let startJs = performance.now()
for (let i = 0; i < 10; i++) {
const crc = new Crc32Js()
crc.update(fileData)
crc.finalize()
}
results.crc.js = performance.now() - startJs
console.log(`JS CRC-32 (10 iterations): ${results.crc.js.toFixed(2)} ms`)
// WASM doesn't expose CRC directly, so we'll measure it through sender operations
// --- Sender Benchmark ---
console.log('\n--- Sender Benchmark (Data Processing) ---')
// JS Sender
console.log('Running JS Sender benchmark...')
try {
startJs = performance.now()
const senderJs = new SenderJs()
senderJs.startFile(fileName, fileSize)
let jsBytesProcessed = 0
let jsIterations = 0
while (jsBytesProcessed < fileSize) {
const fileRequest = senderJs.pollFile()
if (fileRequest) {
const end = Math.min(fileRequest.offset + fileRequest.len, fileSize)
const chunk = fileData.subarray(fileRequest.offset, end)
senderJs.feedFile(chunk)
jsBytesProcessed = end
jsIterations++
} else {
// Sender is waiting for ACK - drain outgoing and break
const outgoing = senderJs.drainOutgoing()
if (outgoing && outgoing.length > 0) {
// Simulate processing outgoing data
}
break
}
const outgoing = senderJs.drainOutgoing()
if (outgoing && outgoing.length > 0) {
// Data is ready to send
}
}
results.sender.js = performance.now() - startJs
console.log(`JS Sender processed ${jsBytesProcessed} bytes in ${jsIterations} iterations`)
console.log(`JS Sender time: ${results.sender.js.toFixed(2)} ms`)
console.log(`JS Sender throughput: ${(jsBytesProcessed / 1024 / 1024 / (results.sender.js / 1000)).toFixed(2)} MB/s`)
} catch (e) {
console.error('JS Sender benchmark failed:', e)
results.sender.js = -1
}
// WASM Sender
console.log('\nRunning WASM Sender benchmark...')
try {
const startWasm = performance.now()
const senderWasm = new WasmSender()
senderWasm.start_file(fileName, fileSize)
let wasmBytesProcessed = 0
let wasmIterations = 0
while (wasmBytesProcessed < fileSize) {
const event = senderWasm.poll()
if (event && event.type === 'need_file_data') {
const offset = event.offset
const length = event.length
const end = Math.min(offset + length, fileSize)
const chunk = fileData.subarray(offset, end)
senderWasm.feed_file(chunk)
wasmBytesProcessed = end
wasmIterations++
} else {
// Sender is waiting for ACK or other event
const outgoing = senderWasm.drain_outgoing()
if (outgoing && outgoing.length > 0) {
// Data is ready to send
}
if (!event) break
}
const outgoing = senderWasm.drain_outgoing()
if (outgoing && outgoing.length > 0) {
// Data is ready to send
}
}
results.sender.wasm = performance.now() - startWasm
console.log(`WASM Sender processed ${wasmBytesProcessed} bytes in ${wasmIterations} iterations`)
console.log(`WASM Sender time: ${results.sender.wasm.toFixed(2)} ms`)
console.log(`WASM Sender throughput: ${(wasmBytesProcessed / 1024 / 1024 / (results.sender.wasm / 1000)).toFixed(2)} MB/s`)
} catch (e) {
console.error('WASM Sender benchmark failed:', e)
results.sender.wasm = -1
}
// --- Receiver Benchmark ---
console.log('\n--- Receiver Benchmark (Data Processing) ---')
// First, generate some ZMODEM data to feed to receivers
// We'll use the JS sender to generate protocol data
console.log('Generating test protocol data...')
const protocolData = []
const genSender = new SenderJs()
genSender.startFile(fileName, fileSize)
let genOffset = 0
while (genOffset < fileSize) {
const req = genSender.pollFile()
if (req) {
const end = Math.min(req.offset + req.len, fileSize)
const chunk = fileData.subarray(req.offset, end)
genSender.feedFile(chunk)
genOffset = end
}
const outgoing = genSender.drainOutgoing()
if (outgoing && outgoing.length > 0) {
protocolData.push(outgoing)
}
if (!genSender.pollFile()) break
}
console.log(`Generated ${protocolData.length} protocol chunks`)
// JS Receiver
console.log('\nRunning JS Receiver benchmark...')
try {
startJs = performance.now()
const receiverJs = new ReceiverJs()
let jsBytesReceived = 0
for (const chunk of protocolData) {
receiverJs.feedIncoming(chunk)
// Drain outgoing (ACKs, etc.)
const outgoing = receiverJs.drainOutgoing()
// Drain file data
const fileChunk = receiverJs.drainFile()
if (fileChunk && fileChunk.length > 0) {
jsBytesReceived += fileChunk.length
}
// Process events
let event
while ((event = receiverJs.pollEvent()) !== null) {
// Handle events
}
}
results.receiver.js = performance.now() - startJs
console.log(`JS Receiver received ${jsBytesReceived} bytes`)
console.log(`JS Receiver time: ${results.receiver.js.toFixed(2)} ms`)
if (jsBytesReceived > 0) {
console.log(`JS Receiver throughput: ${(jsBytesReceived / 1024 / 1024 / (results.receiver.js / 1000)).toFixed(2)} MB/s`)
}
} catch (e) {
console.error('JS Receiver benchmark failed:', e)
results.receiver.js = -1
}
// WASM Receiver
console.log('\nRunning WASM Receiver benchmark...')
try {
const startWasm = performance.now()
const receiverWasm = new WasmReceiver()
let wasmBytesReceived = 0
for (const chunk of protocolData) {
receiverWasm.feed(chunk)
// Drain outgoing (ACKs, etc.)
const outgoing = receiverWasm.drain_outgoing()
// Drain file data
const fileChunk = receiverWasm.drain_file()
if (fileChunk && fileChunk.length > 0) {
wasmBytesReceived += fileChunk.length
}
// Process events
let event
while ((event = receiverWasm.poll()) !== null) {
// Handle events
}
}
results.receiver.wasm = performance.now() - startWasm
console.log(`WASM Receiver received ${wasmBytesReceived} bytes`)
console.log(`WASM Receiver time: ${results.receiver.wasm.toFixed(2)} ms`)
if (wasmBytesReceived > 0) {
console.log(`WASM Receiver throughput: ${(wasmBytesReceived / 1024 / 1024 / (results.receiver.wasm / 1000)).toFixed(2)} MB/s`)
}
} catch (e) {
console.error('WASM Receiver benchmark failed:', e)
results.receiver.wasm = -1
}
// --- Generate Report ---
const report = generateReport(results, fileSize)
console.log('\n' + report)
writeFileSync('benchmark-report.md', report)
console.log('\nBenchmark report saved to benchmark-report.md')
}
function generateReport (results, fileSize) {
const lines = []
lines.push('# ZMODEM2-JS vs ZMODEM2-WASM Performance Benchmark Report')
lines.push('')
lines.push(`**Date:** ${new Date().toISOString()}`)
lines.push(`**File Size:** ${fileSize / 1024 / 1024} MB`)
lines.push('')
lines.push('## Summary')
lines.push('')
lines.push('| Test | JS (ms) | WASM (ms) | Winner | Speedup |')
lines.push('|------|---------|-----------|--------|---------|')
// CRC row
if (results.crc.js > 0) {
const crcWinner = results.crc.wasm > 0 && results.crc.wasm < results.crc.js ? 'WASM' : 'JS'
const crcSpeedup = results.crc.wasm > 0
? Math.max(results.crc.js / results.crc.wasm, results.crc.wasm / results.crc.js).toFixed(2) + 'x'
: 'N/A'
lines.push(`| CRC-32 | ${results.crc.js.toFixed(2)} | ${results.crc.wasm > 0 ? results.crc.wasm.toFixed(2) : 'N/A'} | ${crcWinner} | ${crcSpeedup} |`)
}
// Sender row
if (results.sender.js > 0 || results.sender.wasm > 0) {
const senderWinner = results.sender.wasm > 0 && results.sender.wasm < results.sender.js ? 'WASM' : 'JS'
const senderSpeedup = results.sender.wasm > 0 && results.sender.js > 0
? Math.max(results.sender.js / results.sender.wasm, results.sender.wasm / results.sender.js).toFixed(2) + 'x'
: 'N/A'
lines.push(`| Sender | ${results.sender.js > 0 ? results.sender.js.toFixed(2) : 'Failed'} | ${results.sender.wasm > 0 ? results.sender.wasm.toFixed(2) : 'Failed'} | ${senderWinner} | ${senderSpeedup} |`)
}
// Receiver row
if (results.receiver.js > 0 || results.receiver.wasm > 0) {
const receiverWinner = results.receiver.wasm > 0 && results.receiver.wasm < results.receiver.js ? 'WASM' : 'JS'
const receiverSpeedup = results.receiver.wasm > 0 && results.receiver.js > 0
? Math.max(results.receiver.js / results.receiver.wasm, results.receiver.wasm / results.receiver.js).toFixed(2) + 'x'
: 'N/A'
lines.push(`| Receiver | ${results.receiver.js > 0 ? results.receiver.js.toFixed(2) : 'Failed'} | ${results.receiver.wasm > 0 ? results.receiver.wasm.toFixed(2) : 'Failed'} | ${receiverWinner} | ${receiverSpeedup} |`)
}
lines.push('')
lines.push('## Analysis')
lines.push('')
lines.push('### Performance Differences')
lines.push('')
lines.push('The benchmark measures CPU-bound performance of ZMODEM protocol operations:')
lines.push('')
lines.push('1. **CRC Calculations**: CRC-32 checksums are computed for each data packet. This is a computationally intensive operation involving bit manipulation for each byte.')
lines.push('')
lines.push('2. **Sender Operations**: Includes ZDLE escaping, header encoding, subpacket creation, and CRC calculation.')
lines.push('')
lines.push('3. **Receiver Operations**: Includes ZDLE unescaping, header decoding, packet parsing, and CRC verification.')
lines.push('')
lines.push('### Why WASM is Faster')
lines.push('')
lines.push('**zmodem2-wasm** (compiled from Rust) demonstrates superior performance due to:')
lines.push('')
lines.push('- **Native-like execution**: WebAssembly runs at near-native speed with predictable performance')
lines.push('- **Efficient memory management**: Rust\'s ownership model eliminates garbage collection overhead')
lines.push('- **Optimized bit operations**: CRC calculations and byte manipulations are significantly faster in compiled code')
lines.push('- **No JIT warmup**: WASM modules are compiled ahead-of-time, avoiding runtime compilation')
lines.push('')
lines.push('### Why JS May Be Slower')
lines.push('')
lines.push('**zmodem2-js** (pure JavaScript) faces several performance challenges:')
lines.push('')
lines.push('- **JIT compilation overhead**: V8\'s JIT compiler needs time to optimize hot paths')
lines.push('- **Garbage collection**: Frequent Uint8Array allocations trigger GC pauses')
lines.push('- **Number representation**: JavaScript\'s IEEE 754 doubles are slower for bitwise operations')
lines.push('- **Dynamic typing**: Type checks and boxing/unboxing add runtime overhead')
lines.push('')
lines.push('### Recommendations')
lines.push('')
lines.push('1. **For high-throughput scenarios** (large file transfers, server-side processing): Use **zmodem2-wasm**')
lines.push('2. **For simplicity and compatibility**: Use **zmodem2-js** when WASM support is limited')
lines.push('3. **For browser applications**: Both work well, but WASM provides better performance for files > 1MB')
lines.push('')
lines.push('## Environment')
lines.push('')
lines.push(`- Node.js: ${process.version}`)
lines.push(`- Platform: ${process.platform} ${process.arch}`)
lines.push('')
return lines.join('\n')
}
try {
runBenchmarks()
} catch (err) {
console.error('Benchmark script failed:', err)
process.exit(1)
}
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/App.tsx
|
TypeScript (TSX)
|
import React, { useEffect, useRef } from 'react'
import { Terminal } from '@xterm/xterm'
import { WebLinksAddon } from '@xterm/addon-web-links'
import '@xterm/xterm/css/xterm.css'
import AddonZmodemWasm from './zmodem/addon.js'
const App: React.FC = () => {
const terminalRef = useRef<HTMLDivElement | null>(null)
const terminal = useRef<Terminal | null>(null)
const ws = useRef<WebSocket | null>(null)
const zmodemAddon = useRef<AddonZmodemWasm | null>(null)
useEffect(() => {
if (terminalRef.current == null) return
const term = new Terminal()
terminal.current = term
term.loadAddon(new WebLinksAddon())
const addon = new AddonZmodemWasm()
zmodemAddon.current = addon
term.loadAddon(addon as any)
term.open(terminalRef.current)
// Using same port as original demo server, assuming it serves both
// Or we might need to change port if user runs a different server?
// Original demo uses localhost:8081/terminal
const websocket = new WebSocket('ws://localhost:8081/terminal')
ws.current = websocket
websocket.binaryType = 'arraybuffer'
websocket.onopen = () => {
console.log('WebSocket connected')
term.writeln('Connected to server (WASM Client)')
}
websocket.onmessage = (event) => {
if (typeof event.data === 'string') {
term.write(event.data)
} else {
// Binary data usually means ZMODEM or just binary output
// Pass to addon to check/handle
addon.consume(event.data)
}
}
websocket.onclose = (event) => {
console.log('WebSocket closed:', event.code, event.reason)
term.writeln(`\r\nConnection closed: ${event.code} ${event.reason}`)
}
websocket.onerror = (error) => {
console.error('WebSocket error:', error)
term.writeln('\r\nWebSocket error occurred')
}
term.onData((data) => {
// If ZMODEM session is active, maybe we should block input?
// For now, just send it.
if (websocket.readyState === WebSocket.OPEN) {
websocket.send(data)
}
})
addon.zmodemAttach({
socket: websocket,
term,
onDetect: (type) => {
if (type === 'send') {
handleSendFile(addon)
}
}
})
return () => {
websocket.close()
term.dispose()
}
}, [])
const handleSendFile = async (addon: AddonZmodemWasm) => {
try {
// Use modern File System Access API if available
if ('showOpenFilePicker' in window) {
const picks = await (window as any).showOpenFilePicker()
if (picks && picks.length > 0) {
const file = await picks[0].getFile()
addon.sendFile(file)
} else {
// User cancelled
}
} else {
// Fallback to hidden input
const input = document.createElement('input')
input.type = 'file'
input.style.display = 'none'
input.onchange = (e) => {
const files = (e.target as HTMLInputElement).files
if (files && files.length > 0) {
addon.sendFile(files[0])
}
}
document.body.appendChild(input)
input.click()
document.body.removeChild(input)
}
} catch (e) {
console.error('File selection failed', e)
terminal.current?.writeln('\r\nFile selection cancelled or failed.')
}
}
return (
<div style={{ width: '100vw', height: '100vh', backgroundColor: '#000' }}>
<div ref={terminalRef} style={{ width: '100%', height: '100%' }} />
</div>
)
}
export default App
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/index.html
|
HTML
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zmodem Terminal</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/main.tsx
|
TypeScript (TSX)
|
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.js'
// Server URL for logging (different port from dev server)
const LOG_SERVER_URL = 'ws://localhost:8081'
// Log batching to prevent flooding
class LogSender {
private ws: WebSocket | null = null
private queue: Array<{ level: string, message: string }> = []
private flushTimer: ReturnType<typeof setInterval> | null = null
private readonly FLUSH_INTERVAL = 100 // ms
private readonly MAX_QUEUE_SIZE = 50
private connecting = false
constructor() {
this.connect()
}
private connect() {
if (this.connecting || (this.ws && this.ws.readyState === WebSocket.OPEN)) {
return
}
this.connecting = true
try {
this.ws = new WebSocket(LOG_SERVER_URL + '/log-ws')
this.ws.onopen = () => {
this.connecting = false
this.flush()
}
this.ws.onclose = () => {
this.connecting = false
this.ws = null
// Reconnect after a delay
setTimeout(() => this.connect(), 1000)
}
this.ws.onerror = () => {
this.connecting = false
}
} catch {
this.connecting = false
}
}
enqueue(level: string, message: string) {
this.queue.push({ level, message })
// Flush if queue is getting too large
if (this.queue.length >= this.MAX_QUEUE_SIZE) {
this.flush()
} else if (!this.flushTimer) {
// Schedule a flush
this.flushTimer = setTimeout(() => {
this.flushTimer = null
this.flush()
}, this.FLUSH_INTERVAL)
}
}
private flush() {
if (this.queue.length === 0) return
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
this.connect()
return
}
try {
// Send all queued logs as a single batch
const batch = this.queue.splice(0, this.queue.length)
this.ws.send(JSON.stringify({ type: 'log-batch', logs: batch }))
} catch {
// Ignore errors
}
}
}
const logSender = new LogSender()
// Override console methods to send logs to server
const originalConsole = {
log: console.log,
error: console.error,
warn: console.warn,
info: console.info,
debug: console.debug
}
function sendLogToServer(level: string, ...args: any[]) {
try {
const message = args.map(a => {
if (typeof a === 'object') {
try {
return JSON.stringify(a)
} catch {
return String(a)
}
}
return String(a)
}).join(' ')
logSender.enqueue(level, message)
} catch {
// Ignore all errors
}
}
// Override console methods
console.log = (...args) => {
originalConsole.log(...args)
sendLogToServer('INFO', ...args)
}
console.error = (...args) => {
originalConsole.error(...args)
sendLogToServer('ERROR', ...args)
}
console.warn = (...args) => {
originalConsole.warn(...args)
sendLogToServer('WARN', ...args)
}
console.info = (...args) => {
originalConsole.info(...args)
sendLogToServer('INFO', ...args)
}
console.debug = (...args) => {
originalConsole.debug(...args)
sendLogToServer('DEBUG', ...args)
}
// Log uncaught errors
window.addEventListener('error', (event) => {
sendLogToServer('ERROR', `Uncaught error: ${event.message} at ${event.filename}:${event.lineno}:${event.colno}`)
})
window.addEventListener('unhandledrejection', (event) => {
sendLogToServer('ERROR', `Unhandled promise rejection: ${event.reason}`)
})
console.log('Web client starting...')
const root = ReactDOM.createRoot(document.getElementById('root')!)
root.render(<App />)
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/zmodem/addon.ts
|
TypeScript
|
import { Terminal, IDisposable } from '@xterm/xterm'
import { Receiver, Sender, SenderEvent, ReceiverEvent } from 'zmodem2-js'
export default class AddonZmodemWasm {
_disposables: IDisposable[] = []
socket: WebSocket | null = null
term: Terminal | null = null
receiver: Receiver | null = null
sender: Sender | null = null
wasmInitialized = false
onDetect: ((type: 'receive' | 'send') => void) | null = null
isPickingFile = false
// FIX: Add a flag to prevent concurrent reads
_reading = false
// Buffer for read-ahead
_fileBuffer: Uint8Array | null = null
_fileBufferOffset = 0
readonly BUFFER_SIZE = 10 * 1024 * 1024 // 10MB
currentFile: { name: string, size: number, data: Uint8Array[] } | null = null
sendingFile: File | null = null
// Debug mode - set to true to enable verbose logging
readonly DEBUG = false
constructor() {
this.initWasm()
}
/**
* Send log to server via WebSocket
*/
sendLogToServer(level: string, ...args: any[]) {
const message = args.map(a => {
if (typeof a === 'object') {
try {
return JSON.stringify(a)
} catch {
return String(a)
}
}
return String(a)
}).join(' ')
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
try {
this.socket.send(JSON.stringify({ type: 'log', level, message }))
} catch {
// Ignore send errors
}
}
}
debug(...args: any[]) {
if (this.DEBUG) {
console.log('[ZMODEM]', ...args)
this.sendLogToServer('DEBUG', ...args)
}
}
info(...args: any[]) {
console.log('[ZMODEM]', ...args)
this.sendLogToServer('INFO', ...args)
}
error(...args: any[]) {
console.error('[ZMODEM ERROR]', ...args)
this.sendLogToServer('ERROR', ...args)
}
async initWasm() {
this.wasmInitialized = true
this.info('JS initialized')
}
activate(terminal: Terminal) {
this.term = terminal
}
dispose() {
this.receiver = null
this.sender = null
this._fileBuffer = null
this._disposables.forEach(d => d.dispose())
this._disposables = []
}
zmodemAttach(ctx: { socket: WebSocket, term: Terminal, onDetect?: (type: 'receive' | 'send') => void }) {
this.socket = ctx.socket
this.term = ctx.term
this.socket.binaryType = 'arraybuffer'
if (ctx.onDetect) this.onDetect = ctx.onDetect
this.info('zmodemAttach called')
}
consume(data: ArrayBuffer | string) {
try {
this._consumeInternal(data)
} catch (e) {
this.error('Uncaught error in consume:', e)
this.term?.writeln('\r\nZMODEM: Fatal error - ' + e)
// Reset state to prevent further issues
this.receiver = null
this.sender = null
}
}
_consumeInternal(data: ArrayBuffer | string) {
if (!this.wasmInitialized) {
if (typeof data === 'string') this.term?.write(data)
else this.term?.write(new Uint8Array(data))
return
}
if (this.receiver) {
this.handleReceiver(data)
return
}
if (this.sender) {
this.handleSender(data)
return
}
if (typeof data === 'string') {
this.term?.write(data)
return
}
const u8 = new Uint8Array(data)
// Detection: ** + \x18 + B (ZHEX)
let foundIdx = -1
for (let i = 0; i < u8.length - 3; i++) {
if (u8[i] === 0x2a && u8[i+1] === 0x2a && u8[i+2] === 0x18 && u8[i+3] === 0x42) {
foundIdx = i
break
}
}
if (foundIdx >= 0) {
// Check next 2 bytes for Frame Type (Hex Encoded)
// ZRQINIT = 00 (0x30 0x30) -> Receiver
// ZRINIT = 01 (0x30 0x31) -> Sender
if (foundIdx + 5 < u8.length) {
const typeHex1 = u8[foundIdx + 4]
const typeHex2 = u8[foundIdx + 5]
if (typeHex1 === 0x30 && typeHex2 === 0x30) {
this.info('ZRQINIT detected (Receive)')
if (foundIdx > 0) {
this.term?.write(u8.subarray(0, foundIdx))
}
this.startReceiver(u8.subarray(foundIdx))
return
} else if (typeHex1 === 0x30 && typeHex2 === 0x31) {
this.info('ZRINIT detected (Send)')
if (!this.isPickingFile) {
this.isPickingFile = true
this.onDetect?.('send')
}
return
}
}
// Fallback if not sure
this.term?.write(u8)
} else {
this.term?.write(u8)
}
}
async sendFile(file: File) {
this.isPickingFile = false
this.sendingFile = file
this.sender = new Sender()
this._reading = false // Reset reading state
this._fileBuffer = null
this._fileBufferOffset = 0
this.info(`Starting Sender for ${file.name} (${file.size} bytes)`)
try {
this.sender.startFile(file.name, file.size)
this.pumpSender()
} catch (e) {
this.error('Failed to start sender', e)
this.term?.writeln('\r\nZMODEM: Failed to start send - ' + e)
this.sender = null
}
}
handleSender(data: ArrayBuffer | Uint8Array | string) {
if (!this.sender) return
const u8 = typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)
let offset = 0
let loopCount = 0
while (offset < u8.length && loopCount++ < 1000) {
if (!this.sender) break
try {
const chunk = u8.subarray(offset)
const consumed = this.sender.feedIncoming(chunk)
this.debug(`Sender consumed ${consumed} bytes`)
offset += consumed
const drained = this.pumpSender()
// If we didn't consume input and didn't generate output/events, we are stuck.
if (consumed === 0 && !drained) {
// But maybe the sender is just waiting for file data and can't consume more ACKs?
if (loopCount > 1) this.debug('Sender stuck: 0 consumed, 0 drained')
break
}
} catch (e) {
this.error('Sender error:', e)
this.term?.writeln('\r\nZMODEM Sender Error: ' + e)
this.sender = null
this.sendingFile = null
this._fileBuffer = null
break
}
}
}
pumpSender(): boolean {
if (!this.sender) return false
let didWork = false
const outgoingChunks: Uint8Array[] = []
let totalOutgoingSize = 0
const FLUSH_THRESHOLD = 64 * 1024 // 64KB
const flushOutgoing = () => {
if (outgoingChunks.length === 0) return
if (outgoingChunks.length === 1) {
this.socket?.send(outgoingChunks[0])
} else {
this.socket?.send(new Blob(outgoingChunks as any))
}
this.debug(`Flushed ${totalOutgoingSize} bytes`)
outgoingChunks.length = 0
totalOutgoingSize = 0
}
try {
const outgoing = this.sender.drainOutgoing()
if (outgoing && outgoing.length > 0) {
this.debug(`Drained ${outgoing.length} outgoing bytes`)
outgoingChunks.push(outgoing)
totalOutgoingSize += outgoing.length
didWork = true
}
while (true) {
// Check for file data requests first
const fileRequest = this.sender.pollFile()
if (fileRequest) {
this.debug(`File request: offset=${fileRequest.offset}, len=${fileRequest.len}`)
const start = fileRequest.offset
const length = fileRequest.len
// 1. Try to serve from buffer synchronously
if (this._fileBuffer &&
start >= this._fileBufferOffset &&
(start + length) <= (this._fileBufferOffset + this._fileBuffer.byteLength)) {
const relativeStart = start - this._fileBufferOffset
const chunk = this._fileBuffer.subarray(relativeStart, relativeStart + length)
this.sender.feedFile(chunk)
this.debug(`Fed ${chunk.length} bytes from buffer`)
// IMPORTANT: Drain outgoing data immediately after feeding
const outgoing = this.sender.drainOutgoing()
if (outgoing && outgoing.length > 0) {
outgoingChunks.push(outgoing)
totalOutgoingSize += outgoing.length
if (totalOutgoingSize > FLUSH_THRESHOLD) {
flushOutgoing()
}
}
// Continue loop synchronously
continue
}
// 2. Not in buffer, need to load
// FIX: Check if we are already reading to avoid race conditions
if (this.sendingFile && !this._reading) {
flushOutgoing() // Flush before async break
this._reading = true // Lock
this.loadBufferAndFeed(start, length)
// Break loop to wait for async read
break
} else if (this._reading) {
// Already reading, break loop and wait for that to finish
break
}
}
// Check for events
const event = this.sender.pollEvent()
if (!event) break
didWork = true
this.info('Sender event:', event)
if (event === SenderEvent.FileComplete) {
this.term?.writeln('\r\nZMODEM: File sent.')
this.sender.finishSession()
} else if (event === SenderEvent.SessionComplete) {
this.term?.writeln('\r\nZMODEM: Session complete.')
this.sender = null
this.sendingFile = null
this._fileBuffer = null
flushOutgoing() // Flush final packets
return true
}
}
} catch (e) {
this.error('Pump Sender Error:', e)
this.term?.writeln('\r\nZMODEM Pump Error: ' + e)
this.sender = null
}
flushOutgoing() // Flush anything remaining at end of loop
return didWork
}
async loadBufferAndFeed(offset: number, length: number) {
if (!this.sender || !this.sendingFile) {
this._reading = false
return
}
try {
// Read a larger chunk to minimize I/O and async overhead
const readSize = Math.max(length, this.BUFFER_SIZE)
const end = Math.min(offset + readSize, this.sendingFile.size)
const slice = this.sendingFile.slice(offset, end)
this.debug(`Loading buffer: offset=${offset}, end=${end}, size=${end - offset}`)
const buffer = await slice.arrayBuffer()
if (!this.sender) return
const u8 = new Uint8Array(buffer)
// Update buffer
this._fileBuffer = u8
this._fileBufferOffset = offset
// Feed the requested part
// Since we read from 'offset', the requested data starts at 0 in the new buffer
// Note: u8.length might be less than length if we hit EOF
const feedLen = Math.min(length, u8.length)
const chunk = u8.subarray(0, feedLen)
this.debug(`Feeding ${chunk.length} bytes`)
this.sender.feedFile(chunk)
// Unlock BEFORE pumping
this._reading = false
this.pumpSender()
} catch (e) {
this.error('Buffer read error', e)
// Ensure we unlock on error
this._reading = false
// Try to pump again to see if we can recover
try { this.pumpSender() } catch (_) {}
}
}
startReceiver(initialData: Uint8Array) {
this.info('Starting Receiver...')
try {
this.receiver = new Receiver()
this.handleReceiver(initialData)
} catch (e) {
this.error('Failed to create Receiver', e)
this.term?.writeln('\r\nZMODEM: Failed to start receiver - ' + e)
this.receiver = null
}
}
handleReceiver(data: ArrayBuffer | Uint8Array | string) {
if (!this.receiver) return
const u8 = typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)
this.debug(`handleReceiver: ${u8.length} bytes`)
let offset = 0
let loopCount = 0
while (offset < u8.length && loopCount++ < 1000) {
if (!this.receiver) break
try {
const chunk = u8.subarray(offset)
const consumed = this.receiver.feedIncoming(chunk)
this.debug(`Receiver consumed ${consumed} bytes`)
offset += consumed
const drained = this.pumpReceiver()
if (consumed === 0 && !drained) {
if (loopCount > 1) this.debug('Receiver stuck: 0 consumed, 0 drained')
break
}
} catch (e) {
this.error('Receiver error:', e, (e as any)?.details)
this.term?.writeln('\r\nZMODEM: Error ' + e + ' ' + JSON.stringify((e as any)?.details || {}))
this.receiver = null
this.currentFile = null
break
}
}
}
pumpReceiver(): boolean {
if (!this.receiver) return false
let didWork = false
try {
const outgoing = this.receiver.drainOutgoing()
if (outgoing && outgoing.length > 0) {
this.debug(`Sending ${outgoing.length} outgoing bytes`)
this.socket?.send(outgoing)
didWork = true
}
// Process events first
while (true) {
const event = this.receiver.pollEvent()
if (!event) break
this.info('Receiver Event:', event)
didWork = true
if (event === ReceiverEvent.FileStart) {
const name = this.receiver.getFileName()
const size = this.receiver.getFileSize()
this.term?.writeln(`\r\nZMODEM: Receiving ${name} (${size} bytes)...`)
this.currentFile = { name, size, data: [] }
} else if (event === ReceiverEvent.FileComplete) {
this.term?.writeln('\r\nZMODEM: File complete.')
this.saveFile()
} else if (event === ReceiverEvent.SessionComplete) {
this.term?.writeln('\r\nZMODEM: Session complete.')
this.receiver = null
this.currentFile = null
return true
}
}
// Then drain file data
const chunk = this.receiver.drainFile()
if (chunk && chunk.length > 0) {
this.debug(`Drained ${chunk.length} file bytes`)
if (this.currentFile) {
this.currentFile.data.push(chunk)
didWork = true
} else {
this.error('Got file data but no currentFile!')
}
}
} catch (e) {
this.error('Receiver pump error:', e)
this.term?.writeln('\r\nZMODEM: Error ' + e)
this.receiver = null
this.currentFile = null
}
return didWork
}
saveFile() {
if (!this.currentFile) return
try {
const blob = new Blob(this.currentFile.data as any, { type: 'application/octet-stream' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = this.currentFile.name
a.click()
URL.revokeObjectURL(url)
this.info(`Saved file: ${this.currentFile.name}`)
} catch (e) {
this.error('Failed to save file:', e)
this.term?.writeln('\r\nZMODEM: Failed to save file - ' + e)
}
this.currentFile = null
}
}
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/lib/constants.ts
|
TypeScript
|
/**
* ZMODEM protocol constants.
*
* @module zmodem2-js/constants
*/
/**
* ZPAD character - marks the beginning of a ZMODEM header
*/
export const ZPAD = 0x2a // '*'
/**
* ZDLE character - escape character for ZMODEM
*/
export const ZDLE = 0x18
/**
* XON character - flow control
*/
export const XON = 0x11
/**
* Maximum size of an unescaped subpacket payload
*/
export const SUBPACKET_MAX_SIZE = 1024
/**
* Number of subpackets per acknowledgment
*/
export const SUBPACKET_PER_ACK = 10
/**
* Maximum size of an escaped header
*/
export const MAX_HEADER_ESCAPED = 128
/**
* Maximum size of an escaped subpacket
*/
export const MAX_SUBPACKET_ESCAPED = SUBPACKET_MAX_SIZE * 2 + 2 + 8
/**
* Wire buffer size
*/
export const WIRE_BUF_SIZE = MAX_HEADER_ESCAPED + MAX_SUBPACKET_ESCAPED
/**
* Header payload size (frame type + flags)
*/
export const HEADER_PAYLOAD_SIZE = 5
/**
* Header size with enough capacity for an escaped header
*/
export const HEADER_SIZE = 32
/**
* Receiver event queue capacity
*/
export const RECEIVER_EVENT_QUEUE_CAP = 4
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/lib/crc.ts
|
TypeScript
|
/**
* CRC-16-XMODEM and CRC-32-ISO-HDLC checksum implementations.
*
* @module zmodem2-js/crc
*/
/**
* Performs a single byte update for CRC-16-XMODEM.
*/
function crc16Update (crc: number, byte: number): number {
crc ^= (byte & 0xFF) << 8
for (let i = 0; i < 8; i++) {
if ((crc & 0x8000) !== 0) {
crc = ((crc << 1) ^ 0x1021) & 0xFFFF
} else {
crc = (crc << 1) & 0xFFFF
}
}
return crc
}
/**
* Performs a single byte update for CRC-32-ISO-HDLC.
*/
function crc32Update (crc: number, byte: number): number {
crc ^= (byte & 0xFF)
for (let i = 0; i < 8; i++) {
if ((crc & 1) !== 0) {
crc = ((crc >>> 1) ^ 0xEDB88320) >>> 0
} else {
crc = (crc >>> 1) >>> 0
}
}
return crc
}
/**
* Computes the CRC-16-XMODEM checksum.
* @param data - The data to compute the checksum for
* @returns The CRC-16-XMODEM checksum
*/
export function crc16Xmodem (data: Uint8Array): number {
let crc = 0x0000
for (let i = 0; i < data.length; i++) {
crc = crc16Update(crc, data[i])
}
return crc
}
/**
* Computes the CRC-32-ISO-HDLC checksum.
* @param data - The data to compute the checksum for
* @returns The CRC-32-ISO-HDLC checksum
*/
export function crc32IsoHdlc (data: Uint8Array): number {
let crc = 0xFFFFFFFF
for (let i = 0; i < data.length; i++) {
crc = crc32Update(crc, data[i])
}
return (crc ^ 0xFFFFFFFF) >>> 0
}
/**
* A stateful, iterative CRC-16-XMODEM calculator.
*/
export class Crc16 {
private crc: number = 0x0000
/**
* Creates a new CRC-16 calculator.
*/
constructor () {
this.crc = 0x0000
}
/**
* Resets the CRC state.
*/
reset (): void {
this.crc = 0x0000
}
/**
* Updates the CRC state with a slice of bytes.
* @param data - The data to update with
*/
update (data: Uint8Array): void {
for (const byte of data) {
this.updateByte(byte)
}
}
/**
* Updates the CRC state with a single byte.
* @param byte - The byte to update with
*/
updateByte (byte: number): void {
this.crc = crc16Update(this.crc, byte)
}
/**
* Finalizes the CRC calculation and returns the checksum.
* @returns The CRC-16-XMODEM checksum
*/
finalize (): number {
return this.crc
}
}
/**
* A stateful, iterative CRC-32-ISO-HDLC calculator.
*/
export class Crc32 {
private crc: number
/**
* Creates a new CRC-32 calculator.
*/
constructor () {
this.crc = 0xFFFFFFFF
}
/**
* Resets the CRC state.
*/
reset (): void {
this.crc = 0xFFFFFFFF
}
/**
* Updates the CRC state with a slice of bytes.
* @param data - The data to update with
*/
update (data: Uint8Array): void {
for (const byte of data) {
this.updateByte(byte)
}
}
/**
* Updates the CRC state with a single byte.
* @param byte - The byte to update with
*/
updateByte (byte: number): void {
this.crc = crc32Update(this.crc, byte)
}
/**
* Finalizes the CRC calculation and returns the checksum.
* @returns The CRC-32-ISO-HDLC checksum
*/
finalize (): number {
return (this.crc ^ 0xFFFFFFFF) >>> 0
}
}
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/lib/error.ts
|
TypeScript
|
/**
* ZMODEM error types.
*
* @module zmodem2-js/error
*/
/**
* Top-level error type for ZMODEM operations.
*/
export class ZmodemError extends Error {
constructor (message: string) {
super(message)
this.name = 'ZmodemError'
}
}
/**
* Malformed encoding type error.
*/
export class MalformedEncodingError extends ZmodemError {
public readonly byte: number
constructor (byte: number) {
super(`Malformed encoding type: 0x${byte.toString(16).padStart(2, '0')}`)
this.name = 'MalformedEncodingError'
this.byte = byte
}
}
/**
* Malformed file size error.
*/
export class MalformedFileSizeError extends ZmodemError {
constructor () {
super('Malformed file size')
this.name = 'MalformedFileSizeError'
}
}
/**
* Malformed filename error.
*/
export class MalformedFileNameError extends ZmodemError {
constructor () {
super('Malformed filename')
this.name = 'MalformedFileNameError'
}
}
/**
* Malformed frame type error.
*/
export class MalformedFrameError extends ZmodemError {
public readonly byte: number
constructor (byte: number) {
super(`Malformed frame type: 0x${byte.toString(16).padStart(2, '0')}`)
this.name = 'MalformedFrameError'
this.byte = byte
}
}
/**
* Malformed header error.
*/
export class MalformedHeaderError extends ZmodemError {
constructor () {
super('Malformed header')
this.name = 'MalformedHeaderError'
}
}
/**
* Malformed packet type error.
*/
export class MalformedPacketError extends ZmodemError {
public readonly byte: number
constructor (byte: number) {
super(`Malformed packet type: 0x${byte.toString(16).padStart(2, '0')}`)
this.name = 'MalformedPacketError'
this.byte = byte
}
}
/**
* Not connected error.
*/
export class NotConnectedError extends ZmodemError {
constructor () {
super('Not connected')
this.name = 'NotConnectedError'
}
}
/**
* Read error.
*/
export class ReadError extends ZmodemError {
public readonly cause?: string
constructor (cause?: string) {
super(`Read: ${cause ?? 'unknown'}`)
this.name = 'ReadError'
this.cause = cause
}
}
/**
* Out of memory error.
*/
export class OutOfMemoryError extends ZmodemError {
constructor () {
super('Out of memory')
this.name = 'OutOfMemoryError'
}
}
/**
* Unexpected CRC-16 error.
*/
export class UnexpectedCrc16Error extends ZmodemError {
constructor () {
super('Unexpected CRC-16')
this.name = 'UnexpectedCrc16Error'
}
}
/**
* Unexpected CRC-32 error.
*/
export class UnexpectedCrc32Error extends ZmodemError {
constructor () {
super('Unexpected CRC-32')
this.name = 'UnexpectedCrc32Error'
}
}
/**
* Unexpected EOF error.
*/
export class UnexpectedEofError extends ZmodemError {
constructor () {
super('Unexpected EOF')
this.name = 'UnexpectedEofError'
}
}
/**
* Unsupported operation error.
*/
export class UnsupportedError extends ZmodemError {
constructor () {
super('Unsupported operation')
this.name = 'UnsupportedError'
}
}
/**
* Write error.
*/
export class WriteError extends ZmodemError {
public readonly cause?: string
constructor (cause?: string) {
super(`Write: ${cause ?? 'unknown'}`)
this.name = 'WriteError'
this.cause = cause
}
}
/**
* Union type of all ZMODEM errors.
*/
export type Error =
| MalformedEncodingError
| MalformedFileSizeError
| MalformedFileNameError
| MalformedFrameError
| MalformedHeaderError
| MalformedPacketError
| NotConnectedError
| ReadError
| OutOfMemoryError
| UnexpectedCrc16Error
| UnexpectedCrc32Error
| UnexpectedEofError
| UnsupportedError
| WriteError
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/lib/header.ts
|
TypeScript
|
/**
* ZMODEM protocol header, encoding, and frame definitions.
*
* @module zmodem2-js/header
*/
import { ZDLE, ZPAD, XON, HEADER_PAYLOAD_SIZE } from './constants.js'
import { MalformedEncodingError, MalformedFrameError, MalformedHeaderError, UnexpectedCrc16Error, UnexpectedCrc32Error } from './error.js'
import { crc16Xmodem, crc32IsoHdlc } from './crc.js'
import { ZDLE_TABLE } from './zdle.js'
/**
* The ZMODEM protocol frame encoding type.
*/
export enum Encoding {
/** Binary encoding with 16-bit CRC */
ZBIN = 0x41,
/** Hexadecimal encoding with 16-bit CRC */
ZHEX = 0x42,
/** Binary encoding with 32-bit CRC */
ZBIN32 = 0x43
}
/**
* Creates an Encoding from a byte value.
* @param value - The byte value
* @returns The Encoding type
* @throws MalformedEncodingError if the value is not a valid encoding
*/
export function encodingFromByte (value: number): Encoding {
switch (value) {
case 0x41:
return Encoding.ZBIN
case 0x42:
return Encoding.ZHEX
case 0x43:
return Encoding.ZBIN32
default:
throw new MalformedEncodingError(value)
}
}
/**
* ZMODEM frame types.
*/
export enum Frame {
/** Request receive init */
ZRQINIT = 0,
/** Receiver capabilities and packet size */
ZRINIT = 1,
/** Send init sequence (optional) */
ZSINIT = 2,
/** ACK to above */
ZACK = 3,
/** File name from sender */
ZFILE = 4,
/** To sender: skip this file */
ZSKIP = 5,
/** Last packet was garbled */
ZNAK = 6,
/** Abort batch transfers */
ZABORT = 7,
/** Finish session */
ZFIN = 8,
/** Resume data trans at this position */
ZRPOS = 9,
/** Data packet(s) follow */
ZDATA = 10,
/** End of file */
ZEOF = 11,
/** Fatal Read or Write error Detected */
ZFERR = 12,
/** Request for file CRC and response */
ZCRC = 13,
/** Receiver's Challenge */
ZCHALLENGE = 14,
/** Request is complete */
ZCOMPL = 15,
/** Other end canned session with CAN*5 */
ZCAN = 16,
/** Request for free bytes on filesystem */
ZFREECNT = 17,
/** Command from sending program */
ZCOMMAND = 18,
/** Output to standard error, data follows */
ZSTDERR = 19
}
/**
* Creates a Frame from a byte value.
* @param value - The byte value
* @returns The Frame type
* @throws MalformedFrameError if the value is not a valid frame
*/
export function frameFromByte (value: number): Frame {
if (value >= 0 && value <= 19) {
return value as Frame
}
throw new MalformedFrameError(value)
}
/**
* ZRINIT flags - receiver capabilities.
*/
export enum Zrinit {
/** Can send and receive in full-duplex */
CANFDX = 0x01,
/** Can receive data in parallel with disk I/O */
CANOVIO = 0x02,
/** Can send a break signal */
CANBRK = 0x04,
/** Can decrypt */
CANCRY = 0x08,
/** Can uncompress */
CANLZW = 0x10,
/** Can use 32-bit frame check */
CANFC32 = 0x20,
/** Expects control character to be escaped */
ESCCTL = 0x40,
/** Expects 8th bit to be escaped */
ESC8 = 0x80
}
/**
* Data structure for holding a ZMODEM protocol header.
*/
export class Header {
private readonly _encoding: Encoding
private readonly _frame: Frame
private readonly _flags: Uint8Array
/**
* Creates a new Header instance.
* @param encoding - The encoding type
* @param frame - The frame type
* @param flags - The 4-byte flags array
*/
constructor (encoding: Encoding, frame: Frame, flags: Uint8Array = new Uint8Array(4)) {
this._encoding = encoding
this._frame = frame
this._flags = new Uint8Array(flags)
}
/**
* Returns the encoding of the frame.
*/
get encoding (): Encoding {
return this._encoding
}
/**
* Returns the frame type.
*/
get frame (): Frame {
return this._frame
}
/**
* Returns the count value for frame types that use this field.
*/
get count (): number {
return new DataView(this._flags.buffer).getUint32(0, true)
}
/**
* Returns the flags array.
*/
get flags (): Uint8Array {
return this._flags
}
/**
* Creates a new Header with the count field set.
* @param count - The count value
* @returns A new Header with the count set
*/
withCount (count: number): Header {
const flags = new Uint8Array(4)
new DataView(flags.buffer).setUint32(0, count, true)
return new Header(this._encoding, this._frame, flags)
}
/**
* Returns the serialized size of the header payload (payload + CRC).
* @param encoding - The encoding type
* @returns The size in bytes
*/
static readSize (encoding: Encoding): number {
switch (encoding) {
case Encoding.ZBIN:
return HEADER_PAYLOAD_SIZE + 2
case Encoding.ZBIN32:
return HEADER_PAYLOAD_SIZE + 4
case Encoding.ZHEX:
return (HEADER_PAYLOAD_SIZE + 2) * 2
}
}
/**
* Encodes and writes the header to a byte array.
* @returns The encoded header bytes
*/
encode (): Uint8Array {
const result: number[] = []
// Write header start
result.push(ZPAD)
if (this._encoding === Encoding.ZHEX) {
result.push(ZPAD)
}
result.push(ZDLE)
result.push(this._encoding)
// Build payload
const payload: number[] = [this._frame as number, ...this._flags]
// Calculate CRC
const crcBytes: number[] = []
if (this._encoding === Encoding.ZBIN32) {
const crc = crc32IsoHdlc(new Uint8Array(payload))
const view = new DataView(new ArrayBuffer(4))
view.setUint32(0, crc, true)
for (let i = 0; i < 4; i++) {
crcBytes.push(view.getUint8(i))
}
} else {
const crc = crc16Xmodem(new Uint8Array(payload))
crcBytes.push((crc >> 8) & 0xFF)
crcBytes.push(crc & 0xFF)
}
payload.push(...crcBytes)
// Encode based on type
if (this._encoding === Encoding.ZHEX) {
// Hex encode
const hexStr = payload.map(b => b.toString(16).padStart(2, '0')).join('')
for (const c of hexStr) {
result.push(c.charCodeAt(0))
}
// Add CR/LF
result.push(0x0d) // CR
result.push(0x0a) // LF
// Add XON for non-ACK/ZFIN frames
if (this._frame !== Frame.ZACK && this._frame !== Frame.ZFIN) {
result.push(XON)
}
} else {
// Binary encode with escaping
for (const byte of payload) {
const escaped = ZDLE_TABLE[byte]
if (escaped !== byte) {
result.push(ZDLE)
}
result.push(escaped)
}
}
return new Uint8Array(result)
}
}
/**
* Pre-defined header constants.
*/
export const ZACK_HEADER = new Header(Encoding.ZHEX, Frame.ZACK)
export const ZDATA_HEADER = new Header(Encoding.ZBIN32, Frame.ZDATA)
export const ZEOF_HEADER = new Header(Encoding.ZBIN32, Frame.ZEOF)
export const ZFIN_HEADER = new Header(Encoding.ZHEX, Frame.ZFIN)
export const ZNAK_HEADER = new Header(Encoding.ZHEX, Frame.ZNAK)
export const ZRPOS_HEADER = new Header(Encoding.ZHEX, Frame.ZRPOS)
export const ZRQINIT_HEADER = new Header(Encoding.ZHEX, Frame.ZRQINIT)
/**
* Writes a slice of bytes with ZDLE escaping.
* @param data - The data to escape and write
* @returns The escaped bytes
*/
export function writeSliceEscaped (data: Uint8Array): Uint8Array {
const result: number[] = []
for (const byte of data) {
const escaped = ZDLE_TABLE[byte]
if (escaped !== byte) {
result.push(ZDLE)
}
result.push(escaped)
}
return new Uint8Array(result)
}
/**
* Writes a single byte with ZDLE escaping.
* @param value - The byte to escape and write
* @returns The escaped byte(s)
*/
export function writeByteEscaped (value: number): Uint8Array {
const escaped = ZDLE_TABLE[value]
if (escaped !== value) {
return new Uint8Array([ZDLE, escaped])
}
return new Uint8Array([escaped])
}
/**
* Decodes a header from raw data.
* @param encoding - The encoding type
* @param data - The raw header data
* @returns The decoded Header
* @throws MalformedHeaderError if the header is malformed
* @throws UnexpectedCrc16Error if CRC-16 check fails
* @throws UnexpectedCrc32Error if CRC-32 check fails
*/
export function decodeHeader (encoding: Encoding, data: Uint8Array): Header {
let payload: Uint8Array
if (encoding === Encoding.ZHEX) {
if (data.length % 2 !== 0) {
throw new MalformedHeaderError()
}
// Decode hex
const hexStr = String.fromCharCode(...data)
const bytes: number[] = []
for (let i = 0; i < hexStr.length; i += 2) {
const byte = parseInt(hexStr.substring(i, i + 2), 16)
if (isNaN(byte)) {
throw new MalformedHeaderError()
}
bytes.push(byte)
}
payload = new Uint8Array(bytes)
} else {
payload = data
}
const crcLen = encoding === Encoding.ZBIN32 ? 4 : 2
if (payload.length < HEADER_PAYLOAD_SIZE + crcLen) {
throw new MalformedHeaderError()
}
const headerPayload = payload.slice(0, HEADER_PAYLOAD_SIZE)
const crcBytes = payload.slice(HEADER_PAYLOAD_SIZE)
// Verify CRC
if (encoding === Encoding.ZBIN32) {
const expected = crc32IsoHdlc(headerPayload)
const view = new DataView(new ArrayBuffer(4))
view.setUint32(0, expected, true)
const expectedBytes = new Uint8Array(view.buffer)
if (crcBytes.length < 4 || !arraysEqual(crcBytes.slice(0, 4), expectedBytes)) {
throw new UnexpectedCrc32Error()
}
} else {
const expected = crc16Xmodem(headerPayload)
const expectedBytes = new Uint8Array([(expected >> 8) & 0xFF, expected & 0xFF])
if (crcBytes.length < 2 || !arraysEqual(crcBytes.slice(0, 2), expectedBytes)) {
throw new UnexpectedCrc16Error()
}
}
const frame = frameFromByte(headerPayload[0])
const flags = headerPayload.slice(1, 5)
return new Header(encoding, frame, flags)
}
/**
* Compares two Uint8Arrays for equality.
*/
function arraysEqual (a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false
}
return true
}
/**
* Creates a ZRINIT header.
* @param bufferSize - The receiver buffer size
* @param flags - The ZRINIT flags
* @returns The ZRINIT header
*/
export function createZrinit (bufferSize: number = 1024, flags: number = Zrinit.CANFDX | Zrinit.CANFC32): Header {
const flagBytes = new Uint8Array(4)
flagBytes[0] = bufferSize & 0xFF
flagBytes[1] = (bufferSize >> 8) & 0xFF
flagBytes[2] = 0
flagBytes[3] = flags
return new Header(Encoding.ZHEX, Frame.ZRINIT, flagBytes)
}
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/lib/index.ts
|
TypeScript
|
/**
* ZMODEM file transfer protocol library for JavaScript/TypeScript.
*
* This library provides stream-like state machines for sending and receiving
* files with the ZMODEM protocol.
*
* ## Usage
*
* The usage can be described at a high level with the following flow:
*
* 1. Create `Sender` or `Receiver`.
* 2. Drain `drainOutgoing()` returned bytes into the wire and call
* `advanceOutgoing()` after writing. Then, feed incoming bytes with
* `feedIncoming()`.
* 3. In the sender, complete `pollFile()` with `feedFile()` if required
* and handle events via `pollEvent()`.
* 4. In the receiver, write `drainFile()` returned bytes into storage, and
* call `advanceFile()` after writing. Handle events via `pollEvent()`.
*
* @module zmodem2-js
*/
// Constants
export { ZPAD, ZDLE, XON, SUBPACKET_MAX_SIZE, SUBPACKET_PER_ACK } from './constants.js'
// Errors
export {
ZmodemError,
MalformedEncodingError,
MalformedFileSizeError,
MalformedFileNameError,
MalformedFrameError,
MalformedHeaderError,
MalformedPacketError,
NotConnectedError,
ReadError,
OutOfMemoryError,
UnexpectedCrc16Error,
UnexpectedCrc32Error,
UnexpectedEofError,
UnsupportedError,
WriteError,
type Error as ZmodemErrorType
} from './error.js'
// CRC
export { crc16Xmodem, crc32IsoHdlc, Crc16, Crc32 } from './crc.js'
// ZDLE encoding
export { ZDLE_TABLE, UNZDLE_TABLE, escapeByte, unescapeByte } from './zdle.js'
// Header types
export {
Encoding,
encodingFromByte,
Frame,
frameFromByte,
Zrinit,
Header,
ZACK_HEADER,
ZDATA_HEADER,
ZEOF_HEADER,
ZFIN_HEADER,
ZNAK_HEADER,
ZRPOS_HEADER,
ZRQINIT_HEADER,
decodeHeader,
createZrinit,
writeSliceEscaped,
writeByteEscaped
} from './header.js'
// Transmission types
export {
SubpacketType,
subpacketTypeFromByte,
type FileRequest,
SenderEvent,
ReceiverEvent,
Sender,
Receiver
} from './transmission.js'
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/lib/transmission.ts
|
TypeScript
|
/**
* ZMODEM transmission state and logic.
*
* @module zmodem2-js/transmission
*/
import { ZDLE, ZPAD, SUBPACKET_MAX_SIZE, SUBPACKET_PER_ACK } from './constants.js'
import { MalformedPacketError, MalformedFileNameError, MalformedFileSizeError, MalformedHeaderError, OutOfMemoryError, UnexpectedCrc16Error, UnexpectedCrc32Error, UnexpectedEofError, UnsupportedError } from './error.js'
import { Encoding, Frame, Header, ZACK_HEADER, ZDATA_HEADER, ZEOF_HEADER, ZFIN_HEADER, ZNAK_HEADER, ZRPOS_HEADER, ZRQINIT_HEADER, decodeHeader, createZrinit, writeSliceEscaped, Zrinit } from './header.js'
import { Crc16, Crc32 } from './crc.js'
import { UNZDLE_TABLE } from './zdle.js'
/**
* The ZMODEM protocol subpacket type.
*/
export enum SubpacketType {
/** End of frame, CRC next */
ZCRCE = 0x68,
/** Data continues, CRC next */
ZCRCG = 0x69,
/** Data continues, CRC next, ZACK expected */
ZCRCQ = 0x6a,
/** End of frame, CRC next, ZACK expected */
ZCRCW = 0x6b
}
/**
* Creates a SubpacketType from a byte value.
* @param value - The byte value
* @returns The SubpacketType
* @throws MalformedPacketError if the value is not a valid subpacket type
*/
export function subpacketTypeFromByte (value: number): SubpacketType {
switch (value) {
case 0x68:
return SubpacketType.ZCRCE
case 0x69:
return SubpacketType.ZCRCG
case 0x6a:
return SubpacketType.ZCRCQ
case 0x6b:
return SubpacketType.ZCRCW
default:
throw new MalformedPacketError(value)
}
}
/**
* A request for file data from the sender.
*/
export interface FileRequest {
/** The offset in the file to read from */
offset: number
/** The number of bytes to read */
len: number
}
/**
* Events emitted by the Sender.
*/
export enum SenderEvent {
/** File transfer complete */
FileComplete = 'FileComplete',
/** Session complete */
SessionComplete = 'SessionComplete'
}
/**
* Events emitted by the Receiver.
*/
export enum ReceiverEvent {
/** File transfer starting */
FileStart = 'FileStart',
/** File transfer complete */
FileComplete = 'FileComplete',
/** Session complete */
SessionComplete = 'SessionComplete'
}
/**
* Internal state for reading a subpacket byte-by-byte.
*/
enum SubpacketState {
Idle,
Reading,
Writing,
Crc
}
/**
* Internal state for ZPAD detection.
*/
enum ZpadState {
Idle,
Zpad,
ZpadZpad
}
/**
* Internal state for header reading.
*/
enum HeaderReadState {
SeekingZpad,
ReadingEncoding,
ReadingData
}
/**
* Internal state for the sender.
*/
enum SendState {
WaitReceiverInit,
ReadyForFile,
WaitFilePos,
NeedFileData,
WaitFileAck,
WaitFileDone,
WaitFinish,
Done
}
/**
* Internal state for the receiver.
*/
enum RecvState {
SessionBegin,
FileBegin,
FileReadingMetadata,
FileReadingSubpacket,
FileWaitingSubpacket,
SessionEnd
}
/**
* A simple buffer class for managing byte arrays.
*/
class Buffer {
private data: number[]
private writeOffset: number = 0
constructor (private readonly capacity: number) {
this.data = []
}
get length (): number {
return this.data.length
}
clear (): void {
this.data = []
this.writeOffset = 0
}
push (byte: number): void {
if (this.data.length >= this.capacity) {
throw new OutOfMemoryError()
}
this.data.push(byte & 0xFF)
}
extend (bytes: Uint8Array | number[]): void {
for (const byte of bytes) {
this.push(byte)
}
}
slice (start?: number, end?: number): Uint8Array {
return new Uint8Array(this.data.slice(start, end))
}
get (index: number): number {
return this.data[index]
}
setWriteOffset (offset: number): void {
this.writeOffset = offset
}
get writeOffsetValue (): number {
return this.writeOffset
}
}
/**
* ZMODEM sender state machine.
*/
export class Sender {
private state: SendState = SendState.WaitReceiverInit
private fileName: string = ''
private fileSize: number = 0
private hasFile: boolean = false
private pendingRequest: FileRequest | null = null
private frameRemaining: number = 0
private frameNeedsHeader: boolean = false
private maxSubpacketSize: number = SUBPACKET_MAX_SIZE
private maxSubpacketsPerAck: number = SUBPACKET_PER_ACK
private readonly buf: Buffer = new Buffer(SUBPACKET_MAX_SIZE)
private readonly outgoing: Buffer = new Buffer(2048)
private outgoingOffset: number = 0
private readonly headerReader: HeaderReader = new HeaderReader()
private pendingEvent: SenderEvent | null = null
private finishRequested: boolean = false
private initiator: boolean = true
/**
* Creates a new sender instance.
* @param initiator - If true, sender initiates by sending ZRQINIT. If false, waits for ZRINIT.
*/
constructor (initiator: boolean = true) {
this.initiator = initiator
if (initiator) {
this.queueZrqinit()
}
}
/**
* Starts sending a file with the provided metadata.
* @param fileName - The name of the file
* @param fileSize - The size of the file in bytes
*/
startFile (fileName: string, fileSize: number): void {
if (this.state === SendState.Done || this.state === SendState.WaitFinish ||
(this.state !== SendState.WaitReceiverInit && this.state !== SendState.ReadyForFile)) {
throw new UnsupportedError()
}
this.fileName = fileName
this.fileSize = fileSize
this.hasFile = true
this.pendingRequest = null
this.frameRemaining = 0
this.frameNeedsHeader = false
if (this.state === SendState.ReadyForFile) {
if (this.hasOutgoing()) {
throw new UnsupportedError()
}
this.queueZfile()
this.state = SendState.WaitFilePos
}
}
/**
* Requests to finish the session after the current file completes.
*/
finishSession (): void {
this.finishRequested = true
if (this.state === SendState.ReadyForFile) {
if (this.hasOutgoing()) {
throw new UnsupportedError()
}
this.queueZfin()
this.state = SendState.WaitFinish
}
}
/**
* Returns a pending file data request, if any.
*/
pollFile (): FileRequest | null {
return this.pendingRequest
}
/**
* Feeds a chunk of file data for the current request.
* @param data - The file data to send
*/
feedFile (data: Uint8Array): void {
if (this.state !== SendState.NeedFileData) {
throw new UnsupportedError()
}
if (this.pendingRequest === null) {
throw new UnsupportedError()
}
const request = this.pendingRequest
if (data.length === 0) {
throw new UnexpectedEofError()
}
if (data.length > request.len) {
throw new UnexpectedEofError()
}
const remaining = Math.max(0, this.fileSize - request.offset)
if (data.length > remaining) {
throw new UnexpectedEofError()
}
if (this.hasOutgoing()) {
throw new UnsupportedError()
}
const offset = request.offset
const nextOffset = offset + data.length
const remainingAfter = Math.max(0, this.fileSize - nextOffset)
const maxLen = Math.min(this.maxSubpacketSize, remainingAfter)
const isLastInFrame =
this.frameRemaining <= 1 || data.length < request.len || remainingAfter === 0
const kind = isLastInFrame ? SubpacketType.ZCRCW : SubpacketType.ZCRCG
this.queueZdata(offset, data, kind, this.frameNeedsHeader)
this.frameNeedsHeader = false
if (this.frameRemaining > 0) {
this.frameRemaining--
}
if (isLastInFrame) {
this.pendingRequest = null
this.state = SendState.WaitFileAck
this.frameRemaining = 0
} else {
this.pendingRequest = { offset: nextOffset, len: maxLen }
}
}
/**
* Feeds incoming wire data into the state machine.
* @param input - The incoming data
* @returns The number of bytes consumed
*/
feedIncoming (input: Uint8Array): number {
let consumed = 0
while (true) {
if (this.hasOutgoing() || this.state === SendState.Done || this.pendingRequest !== null) {
break
}
const before = consumed
const header = this.headerReader.read(input, consumed)
if (header === null) {
break
}
consumed = header.consumed
this.handleHeader(header.header)
if (consumed === before || consumed === input.length) {
break
}
}
return consumed
}
/**
* Returns pending outgoing bytes and automatically advances the buffer.
* This matches the WASM behavior where drain automatically advances.
*/
drainOutgoing (): Uint8Array {
const data = this.outgoing.slice(this.outgoingOffset)
// Auto-advance to match WASM behavior
this.outgoing.clear()
this.outgoingOffset = 0
return data
}
/**
* Advances the outgoing cursor by n bytes.
* @param n - The number of bytes to advance
* @deprecated Use drainOutgoing() which auto-advances
*/
advanceOutgoing (n: number): void {
const remaining = this.outgoing.length - this.outgoingOffset
n = Math.min(n, remaining)
this.outgoingOffset += n
if (this.outgoingOffset >= this.outgoing.length) {
this.outgoing.clear()
this.outgoingOffset = 0
}
}
/**
* Returns the next pending sender event.
*/
pollEvent (): SenderEvent | null {
const event = this.pendingEvent
this.pendingEvent = null
return event
}
private hasOutgoing (): boolean {
return this.outgoingOffset < this.outgoing.length
}
private queueZrqinit (): void {
const header = ZRQINIT_HEADER.encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private queueZfile (): void {
const result: number[] = []
// Write ZFILE header
const header = new Header(Encoding.ZBIN32, Frame.ZFILE).encode()
result.push(...header)
// Build file info
const fileInfo: number[] = []
for (let i = 0; i < this.fileName.length; i++) {
fileInfo.push(this.fileName.charCodeAt(i))
}
fileInfo.push(0) // null terminator
const sizeStr = this.fileSize.toString()
for (let i = 0; i < sizeStr.length; i++) {
fileInfo.push(sizeStr.charCodeAt(i))
}
fileInfo.push(0) // null terminator
// Write subpacket with ZCRCW
const escaped = writeSliceEscaped(new Uint8Array(fileInfo))
result.push(...escaped)
result.push(ZDLE)
result.push(SubpacketType.ZCRCW)
// CRC32
const crc = new Crc32()
crc.update(new Uint8Array(fileInfo))
crc.updateByte(SubpacketType.ZCRCW)
const crcValue = crc.finalize()
const crcBytes = new Uint8Array([
crcValue & 0xFF,
(crcValue >> 8) & 0xFF,
(crcValue >> 16) & 0xFF,
(crcValue >> 24) & 0xFF
])
result.push(...writeSliceEscaped(crcBytes))
this.outgoing.clear()
this.outgoing.extend(result)
this.outgoingOffset = 0
}
private queueZdata (offset: number, data: Uint8Array, kind: SubpacketType, includeHeader: boolean): void {
const result: number[] = []
if (includeHeader) {
const header = ZDATA_HEADER.withCount(offset).encode()
result.push(...header)
}
// Write escaped data
result.push(...writeSliceEscaped(data))
result.push(ZDLE)
result.push(kind)
// CRC32
const crc = new Crc32()
crc.update(data)
crc.updateByte(kind)
const crcValue = crc.finalize()
const crcBytes = new Uint8Array([
crcValue & 0xFF,
(crcValue >> 8) & 0xFF,
(crcValue >> 16) & 0xFF,
(crcValue >> 24) & 0xFF
])
result.push(...writeSliceEscaped(crcBytes))
this.outgoing.clear()
this.outgoing.extend(result)
this.outgoingOffset = 0
}
private queueZeof (offset: number): void {
const header = ZEOF_HEADER.withCount(offset).encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private queueZfin (): void {
const header = ZFIN_HEADER.encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private queueNak (): void {
const header = ZNAK_HEADER.encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private queueOo (): void {
this.outgoing.clear()
this.outgoing.extend([0x4f, 0x4f]) // "OO"
this.outgoingOffset = 0
}
private handleHeader (header: Header): void {
switch (header.frame) {
case Frame.ZRINIT:
this.onZrinit(header)
break
case Frame.ZRPOS:
case Frame.ZACK:
this.onZrpos(header.count)
break
case Frame.ZFIN:
this.onZfin()
break
default:
if (this.state === SendState.WaitReceiverInit) {
this.queueZrqinit()
}
}
}
private onZrinit (header: Header): void {
this.updateReceiverCaps(header)
switch (this.state) {
case SendState.WaitReceiverInit:
if (this.hasFile) {
this.queueZfile()
this.state = SendState.WaitFilePos
} else {
this.state = SendState.ReadyForFile
if (this.finishRequested) {
this.queueZfin()
this.state = SendState.WaitFinish
}
}
break
case SendState.WaitFileDone:
this.pendingEvent = SenderEvent.FileComplete
this.hasFile = false
if (this.finishRequested) {
this.queueZfin()
this.state = SendState.WaitFinish
} else {
this.state = SendState.ReadyForFile
}
break
case SendState.WaitFinish:
this.queueOo()
this.state = SendState.Done
this.pendingEvent = SenderEvent.SessionComplete
break
}
}
private updateReceiverCaps (header: Header): void {
const flags = header.flags
const rxBufSize = flags[0] | (flags[1] << 8)
const caps = flags[2] | (flags[3] << 8)
const canOvio = (caps & Zrinit.CANOVIO) !== 0
if (rxBufSize === 0) {
this.maxSubpacketSize = SUBPACKET_MAX_SIZE
this.maxSubpacketsPerAck = canOvio ? SUBPACKET_PER_ACK : 1
return
}
this.maxSubpacketSize = Math.min(SUBPACKET_MAX_SIZE, rxBufSize)
if (!canOvio) {
this.maxSubpacketsPerAck = 1
return
}
const subpackets = Math.floor(rxBufSize / this.maxSubpacketSize)
this.maxSubpacketsPerAck = subpackets === 0 ? 1 : subpackets
}
private onZrpos (offset: number): void {
switch (this.state) {
case SendState.WaitReceiverInit:
this.queueZrqinit()
break
case SendState.WaitFilePos:
case SendState.WaitFileAck:
case SendState.NeedFileData:
if (offset >= this.fileSize) {
this.queueZeof(offset)
this.state = SendState.WaitFileDone
this.pendingRequest = null
} else {
const remaining = this.fileSize - offset
const maxSubpackets = Math.ceil(remaining / this.maxSubpacketSize)
this.frameRemaining = Math.min(this.maxSubpacketsPerAck, maxSubpackets)
this.frameNeedsHeader = true
const len = Math.min(this.maxSubpacketSize, remaining)
this.pendingRequest = { offset, len }
this.state = SendState.NeedFileData
}
break
}
}
private onZfin (): void {
if (this.state === SendState.WaitFinish) {
this.queueOo()
this.state = SendState.Done
this.pendingEvent = SenderEvent.SessionComplete
}
}
}
/**
* ZMODEM receiver state machine.
*/
export class Receiver {
private state: RecvState = RecvState.SessionBegin
private count: number = 0
private fileName: string = ''
private fileSize: number = 0
private readonly buf: Buffer = new Buffer(SUBPACKET_MAX_SIZE)
private bufWriteOffset: number = 0
private dataEncoding: Encoding = Encoding.ZBIN
private readonly headerReader: HeaderReader = new HeaderReader()
private subpacketState: SubpacketState = SubpacketState.Idle
private subpacketType: SubpacketType = SubpacketType.ZCRCG
private subpacketEscapePending: boolean = false
private crcEscapePending: boolean = false // Separate escape state for CRC reading (like Rust's RxCrc)
private crcBytesRead: number = 0 // Number of CRC bytes read so far (persists across calls)
private crcBuf: number[] = [] // Partial CRC bytes (persists across calls)
private crc16: Crc16 = new Crc16()
private crc32: Crc32 = new Crc32()
private readonly outgoing: Buffer = new Buffer(2048)
private outgoingOffset: number = 0
private pendingEvents: Array<ReceiverEvent | null> = [null, null, null, null]
private pendingEventHead: number = 0
private pendingEventLen: number = 0
/**
* Creates a new receiver instance.
*/
constructor () {
this.queueZrinit()
}
/**
* Feeds incoming wire data into the state machine.
* @param input - The incoming data
* @returns The number of bytes consumed
*/
feedIncoming (input: Uint8Array): number {
let consumed = 0
while (true) {
if (this.hasFileData() || this.pendingEventsFull()) {
break
}
const before = consumed
if (this.state === RecvState.FileReadingSubpacket || this.state === RecvState.FileReadingMetadata) {
const result = this.processSubpacket(input, consumed)
if (result.done) {
consumed = result.consumed
if (this.hasOutgoing() || this.hasFileData() || this.pendingEventsFull()) {
break
}
if (consumed === before) {
break
}
continue
} else {
consumed = result.consumed
break
}
}
const header = this.headerReader.read(input, consumed)
if (header === null) {
break
}
consumed = header.consumed
this.handleHeader(header.header)
if (this.pendingEventsFull()) {
break
}
// Break if we have outgoing data to send
if (this.hasOutgoing()) {
break
}
if (consumed === before || consumed === input.length) {
break
}
}
return consumed
}
/**
* Returns pending outgoing bytes and automatically advances the buffer.
* This matches the WASM behavior where drain automatically advances.
*/
drainOutgoing (): Uint8Array {
const data = this.outgoing.slice(this.outgoingOffset)
// Auto-advance to match WASM behavior
this.outgoing.clear()
this.outgoingOffset = 0
return data
}
/**
* Advances the outgoing cursor by n bytes.
* @param n - The number of bytes to advance
* @deprecated Use drainOutgoing() which auto-advances
*/
advanceOutgoing (n: number): void {
const remaining = this.outgoing.length - this.outgoingOffset
n = Math.min(n, remaining)
this.outgoingOffset += n
if (this.outgoingOffset >= this.outgoing.length) {
this.outgoing.clear()
this.outgoingOffset = 0
}
}
/**
* Returns pending file data bytes and automatically advances the buffer.
* This matches the WASM behavior where drain automatically advances.
*/
drainFile (): Uint8Array {
if (this.subpacketState === SubpacketState.Writing) {
const data = this.buf.slice(this.bufWriteOffset)
// Auto-advance and finish subpacket to match WASM behavior
this.finishSubpacket(this.subpacketType)
return data
}
return new Uint8Array(0)
}
/**
* Advances the file output cursor by n bytes.
* @param n - The number of bytes to advance
*/
advanceFile (n: number): void {
if (this.subpacketState !== SubpacketState.Writing) {
return
}
const remaining = this.buf.length - this.bufWriteOffset
n = Math.min(n, remaining)
this.bufWriteOffset += n
if (this.bufWriteOffset < this.buf.length) {
return
}
this.finishSubpacket(this.subpacketType)
}
/**
* Returns the next pending receiver event.
*/
pollEvent (): ReceiverEvent | null {
return this.popEvent()
}
/**
* Returns the current file name.
*/
getFileName (): string {
return this.fileName
}
/**
* Returns the current file size.
*/
getFileSize (): number {
return this.fileSize
}
private hasOutgoing (): boolean {
return this.outgoingOffset < this.outgoing.length
}
private hasFileData (): boolean {
return this.subpacketState === SubpacketState.Writing
}
private pendingEventsFull (): boolean {
return this.pendingEventLen >= 4
}
private pushEvent (event: ReceiverEvent): void {
if (this.pendingEventsFull()) {
throw new OutOfMemoryError()
}
const index = (this.pendingEventHead + this.pendingEventLen) % 4
this.pendingEvents[index] = event
this.pendingEventLen++
}
private popEvent (): ReceiverEvent | null {
if (this.pendingEventLen === 0) {
return null
}
const event = this.pendingEvents[this.pendingEventHead]
this.pendingEvents[this.pendingEventHead] = null
this.pendingEventHead = (this.pendingEventHead + 1) % 4
this.pendingEventLen--
return event
}
private queueZrinit (): void {
const header = createZrinit(SUBPACKET_MAX_SIZE, Zrinit.CANFDX | Zrinit.CANFC32).encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private queueZrpos (count: number): void {
const header = ZRPOS_HEADER.withCount(count).encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private queueZack (): void {
const header = ZACK_HEADER.withCount(this.count).encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private queueZfin (): void {
const header = ZFIN_HEADER.encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private queueNak (): void {
const header = ZNAK_HEADER.encode()
this.outgoing.clear()
this.outgoing.extend(header)
this.outgoingOffset = 0
}
private handleHeader (header: Header): void {
switch (header.frame) {
case Frame.ZRQINIT:
if (this.state === RecvState.SessionBegin) {
this.queueZrinit()
}
break
case Frame.ZFILE:
if (this.state === RecvState.SessionBegin || this.state === RecvState.FileBegin) {
this.dataEncoding = header.encoding
this.state = RecvState.FileReadingMetadata
this.subpacketState = SubpacketState.Reading
this.subpacketEscapePending = false
this.resetCrc()
this.buf.clear()
this.bufWriteOffset = 0
}
break
case Frame.ZDATA:
if (this.state === RecvState.SessionBegin) {
this.queueZrinit()
} else if (this.state === RecvState.FileBegin || this.state === RecvState.FileWaitingSubpacket) {
if (header.count !== this.count) {
this.queueZrpos(this.count)
return
}
this.dataEncoding = header.encoding
this.state = RecvState.FileReadingSubpacket
this.subpacketState = SubpacketState.Reading
this.subpacketEscapePending = false
this.resetCrc()
this.buf.clear()
this.bufWriteOffset = 0
}
break
case Frame.ZEOF:
if (this.state === RecvState.FileWaitingSubpacket && header.count === this.count) {
this.queueZrinit()
this.state = RecvState.FileBegin
this.pushEvent(ReceiverEvent.FileComplete)
}
break
case Frame.ZFIN:
if (this.state === RecvState.FileWaitingSubpacket || this.state === RecvState.FileBegin) {
this.queueZfin()
this.state = RecvState.SessionEnd
this.pushEvent(ReceiverEvent.SessionComplete)
}
break
}
}
private resetCrc (): void {
this.crc16 = new Crc16()
this.crc32 = new Crc32()
this.crcEscapePending = false // Reset CRC escape state (like Rust's RxCrc.reset())
this.crcBytesRead = 0 // Reset CRC bytes read counter
this.crcBuf = [] // Clear CRC buffer
}
private updateCrc (byte: number): void {
if (this.dataEncoding === Encoding.ZBIN32) {
this.crc32.updateByte(byte)
} else {
this.crc16.updateByte(byte)
}
}
private processSubpacket (input: Uint8Array, startOffset: number): { consumed: number, done: boolean } {
let consumed = startOffset
while (consumed < input.length) {
const byte = input[consumed]
switch (this.subpacketState) {
case SubpacketState.Reading:
if (this.subpacketEscapePending) {
this.subpacketEscapePending = false
try {
const packetType = subpacketTypeFromByte(byte)
this.updateCrc(packetType)
this.subpacketType = packetType
this.subpacketState = SubpacketState.Crc
} catch {
const unescaped = UNZDLE_TABLE[byte]
this.buf.push(unescaped)
this.updateCrc(unescaped)
}
consumed++
} else if (byte === ZDLE) {
this.subpacketEscapePending = true
consumed++
} else {
this.buf.push(byte)
this.updateCrc(byte)
consumed++
}
break
case SubpacketState.Crc: {
const crcLen = this.dataEncoding === Encoding.ZBIN32 ? 4 : 2
while (consumed < input.length && this.crcBytesRead < crcLen) {
const currentByte = input[consumed]
if (this.crcEscapePending) {
this.crcEscapePending = false
const unescaped = UNZDLE_TABLE[currentByte]
this.crcBuf.push(unescaped)
this.crcBytesRead++
consumed++
} else if (currentByte === ZDLE) {
this.crcEscapePending = true
consumed++
} else {
this.crcBuf.push(currentByte)
this.crcBytesRead++
consumed++
}
}
if (this.crcBytesRead < crcLen) {
return { consumed, done: false }
}
// Verify CRC - use the accumulated crcBuf
if (this.dataEncoding === Encoding.ZBIN32) {
const expected = this.crc32.finalize() >>> 0 // Ensure unsigned
// Little-endian interpretation (as per ZMODEM spec)
const received = (this.crcBuf[0] | (this.crcBuf[1] << 8) | (this.crcBuf[2] << 16) | (this.crcBuf[3] << 24)) >>> 0
if (expected !== received) {
throw new UnexpectedCrc32Error()
}
} else {
const expected = this.crc16.finalize()
const received = (this.crcBuf[0] << 8) | this.crcBuf[1]
if (expected !== received) {
throw new UnexpectedCrc16Error()
}
}
if (this.state === RecvState.FileReadingMetadata) {
this.parseZfileBuf()
this.buf.clear()
this.bufWriteOffset = 0
this.resetCrc()
this.subpacketEscapePending = false
this.queueZrpos(0)
this.state = RecvState.FileBegin
this.subpacketState = SubpacketState.Idle
this.pushEvent(ReceiverEvent.FileStart)
} else {
this.subpacketState = SubpacketState.Writing
this.bufWriteOffset = 0
if (this.buf.length === 0) {
this.finishSubpacket(this.subpacketType)
}
}
return { consumed, done: true }
}
case SubpacketState.Writing:
return { consumed, done: true }
default:
throw new UnsupportedError()
}
}
return { consumed, done: false }
}
private parseZfileBuf (): void {
const payload = this.buf.slice()
const fields: number[][] = []
let current: number[] = []
for (const byte of payload) {
if (byte === 0) {
fields.push(current)
current = []
} else {
current.push(byte)
}
}
if (current.length > 0) {
fields.push(current)
}
if (fields.length === 0 || fields[0].length === 0) {
throw new MalformedFileNameError()
}
this.fileName = String.fromCharCode(...fields[0])
if (fields.length > 1) {
const sizeField = fields[1]
const spaceIndex = sizeField.findIndex(b => b === 0x20)
const sizeBytes = spaceIndex >= 0 ? sizeField.slice(0, spaceIndex) : sizeField
const sizeStr = String.fromCharCode(...sizeBytes)
this.fileSize = parseInt(sizeStr, 10)
if (isNaN(this.fileSize)) {
throw new MalformedFileSizeError()
}
} else {
this.fileSize = 0
}
this.count = 0
}
private finishSubpacket (packet: SubpacketType): void {
this.count += this.buf.length
this.buf.clear()
this.bufWriteOffset = 0
this.resetCrc()
switch (packet) {
case SubpacketType.ZCRCW:
this.queueZack()
this.state = RecvState.FileWaitingSubpacket
this.subpacketState = SubpacketState.Idle
this.subpacketEscapePending = false
break
case SubpacketType.ZCRCQ:
this.queueZack()
this.subpacketState = SubpacketState.Reading
this.subpacketEscapePending = false
break
case SubpacketType.ZCRCG:
this.subpacketState = SubpacketState.Reading
this.subpacketEscapePending = false
break
case SubpacketType.ZCRCE:
this.state = RecvState.FileWaitingSubpacket
this.subpacketState = SubpacketState.Idle
this.subpacketEscapePending = false
break
}
}
}
/**
* Header reader state machine.
*/
class HeaderReader {
private state: HeaderReadState = HeaderReadState.SeekingZpad
private zpadState: ZpadState = ZpadState.Idle
private buf: number[] = []
private encoding: Encoding | null = null
private expectedLen: number = 0
private escapePending: boolean = false
/**
* Reads a header from the input data.
* @param input - The input data
* @param startOffset - The starting offset in the input
* @returns The header and consumed bytes, or null if not enough data
*/
read (input: Uint8Array, startOffset: number): { header: Header, consumed: number } | null {
let consumed = startOffset
while (consumed < input.length) {
switch (this.state) {
case HeaderReadState.SeekingZpad: {
const byte = input[consumed]
consumed++
if (this.advanceZpadState(byte)) {
this.state = HeaderReadState.ReadingEncoding
}
break
}
case HeaderReadState.ReadingEncoding: {
const byte = input[consumed]
consumed++
try {
this.encoding = Encoding.ZBIN
switch (byte) {
case 0x41:
this.encoding = Encoding.ZBIN
break
case 0x42:
this.encoding = Encoding.ZHEX
break
case 0x43:
this.encoding = Encoding.ZBIN32
break
default:
this.reset()
throw new MalformedPacketError(byte)
}
} catch {
this.reset()
throw new MalformedPacketError(byte)
}
this.expectedLen = Header.readSize(this.encoding)
this.escapePending = false
this.buf = []
this.state = HeaderReadState.ReadingData
break
}
case HeaderReadState.ReadingData:
while (this.buf.length < this.expectedLen && consumed < input.length) {
const byte = input[consumed]
consumed++
if (this.escapePending) {
this.escapePending = false
this.buf.push(UNZDLE_TABLE[byte])
} else if (byte === ZDLE) {
this.escapePending = true
} else {
this.buf.push(byte)
}
}
if (this.buf.length >= this.expectedLen) {
if (this.encoding === null) {
this.reset()
throw new MalformedHeaderError()
}
const header = decodeHeader(this.encoding, new Uint8Array(this.buf))
this.reset()
return { header, consumed }
}
break
}
}
return null
}
private reset (): void {
this.state = HeaderReadState.SeekingZpad
this.zpadState = ZpadState.Idle
this.encoding = null
this.expectedLen = 0
this.escapePending = false
this.buf = []
}
private advanceZpadState (byte: number): boolean {
switch (this.zpadState) {
case ZpadState.Idle:
if (byte === ZPAD) {
this.zpadState = ZpadState.Zpad
}
break
case ZpadState.Zpad:
case ZpadState.ZpadZpad:
if (byte === ZDLE) {
this.zpadState = ZpadState.Idle
return true
}
if (byte === ZPAD) {
this.zpadState = ZpadState.ZpadZpad
} else {
this.zpadState = ZpadState.Idle
}
break
}
return false
}
}
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/lib/zdle.ts
|
TypeScript
|
/**
* ZDLE escape/unescape tables for ZMODEM protocol.
*
* @module zmodem2-js/zdle
*/
/**
* ZMODEM escape table - maps each byte value to its escaped form.
* If the escaped value differs from the original, the byte needs to be
* preceded by ZDLE (0x18).
*/
export const ZDLE_TABLE: Uint8Array = new Uint8Array([
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x4d, 0x0e, 0x0f,
0x50, 0x51, 0x12, 0x53, 0x14, 0x15, 0x16, 0x17, 0x58, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x6c,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0xcd, 0x8e, 0x8f,
0xd0, 0xd1, 0x92, 0xd3, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0x6d
])
/**
* ZMODEM unescape table - maps escaped byte values back to their original form.
*/
export const UNZDLE_TABLE: Uint8Array = new Uint8Array([
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x7f, 0xff, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
])
/**
* Escapes a single byte using ZDLE encoding.
* @param value - The byte to escape
* @returns An object containing the escaped byte and whether ZDLE prefix is needed
*/
export function escapeByte (value: number): { escaped: number, needsPrefix: boolean } {
const escaped = ZDLE_TABLE[value & 0xFF]
return {
escaped,
needsPrefix: escaped !== value
}
}
/**
* Unescapes a single byte using ZDLE decoding.
* @param value - The escaped byte to unescape
* @returns The original byte value
*/
export function unescapeByte (value: number): number {
return UNZDLE_TABLE[value & 0xFF]
}
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/server/index.mjs
|
JavaScript
|
import express from 'express'
import expressWs from 'express-ws'
import { Client } from 'ssh2'
import WebSocket from 'ws'
import fs from 'fs'
import path from 'path'
import cors from 'cors'
const app = express()
expressWs(app)
// Enable CORS for all routes
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type']
}))
// Middleware to parse JSON bodies
app.use(express.json())
const SSH_HOST = 'localhost'
const SSH_PORT = 23355
const SSH_USER = 'zxd'
const SSH_PASS = 'zxd'
// Log file setup
const LOG_DIR = 'temp'
const SERVER_LOG_FILE = path.join(LOG_DIR, 'server.log')
const WEB_LOG_FILE = path.join(LOG_DIR, 'web.log')
// Ensure temp directory exists
if (!fs.existsSync(LOG_DIR)) {
fs.mkdirSync(LOG_DIR, { recursive: true })
}
// Clear log files on startup
fs.writeFileSync(SERVER_LOG_FILE, `=== Server started at ${new Date().toISOString()} ===\n`)
fs.writeFileSync(WEB_LOG_FILE, `=== Server started at ${new Date().toISOString()} ===\n`)
// Log to server log file
function logToServer(message, level = 'INFO') {
const timestamp = new Date().toISOString()
const logLine = `[${timestamp}] [${level}] ${message}\n`
fs.appendFileSync(SERVER_LOG_FILE, logLine)
console.log(`[SERVER] [${level}] ${message}`)
}
// Log to web log file (for client logs)
function logToWeb(message, level = 'INFO') {
const timestamp = new Date().toISOString()
const logLine = `[${timestamp}] [${level}] ${message}\n`
fs.appendFileSync(WEB_LOG_FILE, logLine)
}
// WebSocket endpoint for web client logs (batched)
app.ws('/log-ws', (ws, req) => {
logToServer('Log WebSocket connected')
ws.on('message', (data) => {
try {
const parsed = JSON.parse(data.toString())
if (parsed.type === 'log-batch' && Array.isArray(parsed.logs)) {
// Process batch of logs
for (const log of parsed.logs) {
if (log.message) {
logToWeb(log.message, log.level || 'INFO')
}
}
} else if (parsed.type === 'log') {
// Single log message
const level = parsed.level || 'INFO'
if (parsed.message) {
logToWeb(parsed.message, level)
}
}
} catch (err) {
logToServer(`Log WebSocket parse error: ${err.message}`, 'ERROR')
}
})
ws.on('close', () => {
logToServer('Log WebSocket disconnected')
})
ws.on('error', (err) => {
logToServer(`Log WebSocket error: ${err.message}`, 'ERROR')
})
})
// HTTP API endpoint for web client logs (fallback)
app.post('/log', (req, res) => {
try {
const { level = 'INFO', message } = req.body
if (message) {
logToWeb(message, level)
}
res.status(200).json({ success: true })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// Test SSH connection on startup
logToServer('Testing SSH connection...')
const testSsh = new Client()
testSsh.on('ready', () => {
logToServer('SSH test connection successful')
testSsh.end()
})
testSsh.on('error', (err) => {
logToServer(`SSH test connection failed: ${err.message}`, 'ERROR')
})
testSsh.connect({
host: SSH_HOST,
port: SSH_PORT,
username: SSH_USER,
password: SSH_PASS
})
app.ws('/terminal', (ws, req) => {
const clientIp = req.connection.remoteAddress
logToServer(`WebSocket connection established from: ${clientIp}`)
const ssh = new Client()
ssh.on('ready', () => {
logToServer('SSH connection ready')
ssh.shell({
term: 'xterm-256color',
cols: 80,
rows: 24
}, (err, stream) => {
if (err) {
logToServer(`SSH shell error: ${err.message}`, 'ERROR')
ws.send(`SSH shell failed: ${err.message}`)
ws.close(1011, 'SSH shell failed')
ssh.end()
return
}
logToServer('SSH shell opened')
ws.on('message', (data) => {
const msgStr = data.toString()
try {
const parsed = JSON.parse(msgStr)
if (parsed.type === 'log') {
// Log client messages to web log file
const level = parsed.level || 'INFO'
logToWeb(parsed.message, level)
return
}
} catch {}
// Send all other data as binary to SSH stream
stream.write(data)
})
stream.on('data', (data) => {
ws.send(data)
})
stream.on('close', () => {
logToServer('SSH stream closed')
ssh.end()
ws.close()
})
stream.on('error', (err) => {
logToServer(`SSH stream error: ${err.message}`, 'ERROR')
})
})
})
ssh.on('error', (err) => {
logToServer(`SSH connection error: ${err.message}`, 'ERROR')
ws.send(`SSH connection failed: ${err.message}`)
ws.close(1011, 'SSH connection failed')
})
ssh.connect({
host: SSH_HOST,
port: SSH_PORT,
username: SSH_USER,
password: SSH_PASS
})
ws.on('close', () => {
logToServer('WebSocket closed')
ssh.end()
})
ws.on('error', (err) => {
logToServer(`WebSocket error: ${err.message}`, 'ERROR')
})
})
app.listen(8081, () => {
logToServer('Server running on port 8081')
logToServer(`Server log file: ${SERVER_LOG_FILE}`)
logToServer(`Web log file: ${WEB_LOG_FILE}`)
})
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
test/integration/ssh-download.test.mjs
|
JavaScript
|
/**
* Pure Node.js test for SSH connection with ZMODEM download (sz command).
*
* This test connects to an SSH server and tests:
* - sz command - trigger download, receive file from server
*/
import { Client } from 'ssh2'
import { existsSync, mkdirSync } from 'fs'
import { join, extname, basename } from 'path'
import { Receiver } from '../../dist/esm/index.js'
import { ZmodemSession } from './zmodem-session.mjs'
/**
* Generate a unique filename if file already exists.
* Adds .1, .2, .3 etc. suffix before the extension.
* @param {string} dir - Directory path
* @param {string} fileName - Original file name
* @returns {string} - Unique file path
*/
function getUniqueFilePath (dir, fileName) {
let filePath = join(dir, fileName)
if (!existsSync(filePath)) {
return filePath
}
// File exists, need to rename
const ext = extname(fileName)
const baseName = basename(fileName, ext)
let counter = 1
while (existsSync(filePath)) {
const newFileName = `${baseName}.${counter}${ext}`
filePath = join(dir, newFileName)
counter++
}
return filePath
}
/**
* Start download session after ZRQINIT detection.
* @param {ZmodemSession} session - Session in detected state
* @param {Uint8Array} initialData - Initial ZMODEM data
*/
function startDownloadSession (session, initialData) {
console.log('[ZMODEM] Starting file download session')
session.state = 'receiving'
session.receiver = new Receiver()
session.fileBuffer = []
// Feed initial data to receiver
session.feedIncoming(initialData)
}
// SSH connection configuration
const SSH_CONFIG = {
host: 'localhost',
port: 23355,
username: 'zxd',
password: 'zxd',
readyTimeout: 30000
}
// Download directory
const DOWNLOAD_DIR = '/Users/zxd/dev/zmodem2-js/test/integration/downloads'
// File to download from server (must exist on server)
const DOWNLOAD_FILE_NAME = 'testfile_5m.bin'
/**
* Wait for session to complete with timeout.
* @param {ZmodemSession} session - Session to monitor
* @param {number} timeout - Timeout in milliseconds
*/
function waitForComplete (session, timeout = 120000) {
return new Promise((resolve, reject) => {
const startTime = Date.now()
const checkInterval = setInterval(() => {
if (session.sessionComplete) {
clearInterval(checkInterval)
resolve(true)
} else if (Date.now() - startTime > timeout) {
clearInterval(checkInterval)
reject(new Error(`Timeout waiting for session complete, current state: ${session.state}`))
}
}, 500)
})
}
/**
* Run SSH connection and ZMODEM download test.
*/
async function runTest () {
console.log('=== SSH ZMODEM Download Test ===')
console.log('SSH Config:', { ...SSH_CONFIG, password: '***' })
console.log('')
// Ensure download directory exists
if (!existsSync(DOWNLOAD_DIR)) {
mkdirSync(DOWNLOAD_DIR, { recursive: true })
}
const conn = new Client()
return new Promise((resolve, reject) => {
conn.on('ready', () => {
console.log('[SSH] Connected to server')
conn.shell((err, stream) => {
if (err !== null && err !== undefined) {
console.error('[SSH] Failed to create shell:', err)
conn.end()
reject(err)
return
}
if (stream === undefined) {
console.error('[SSH] Failed to create shell: stream is undefined')
conn.end()
reject(new Error('Shell stream is undefined'))
return
}
console.log('[SSH] Shell created')
const session = new ZmodemSession(stream, {
downloadDir: DOWNLOAD_DIR,
onFileStart: (fileName, fileSize) => {
console.log('[CALLBACK] File start:', fileName, 'size:', fileSize)
},
onFileComplete: (fileName) => {
console.log('[CALLBACK] File complete:', fileName)
},
onSessionComplete: () => {
console.log('[CALLBACK] Session complete')
},
onProgress: (transferred, total, percent) => {
console.log(`[CALLBACK] Progress: ${transferred}/${total} (${percent}%)`)
}
})
let testComplete = false
stream.on('data', (data) => {
const str = data.toString('binary')
console.log('[SSH] Received data:', str.length, 'bytes', 'state:', session.state)
// If session is active, feed data directly
if (session.state !== 'idle' && session.state !== 'detected') {
session.feedIncoming(data)
return
}
// Check for ZMODEM detection
const detection = session.detectZmodem(data)
if (detection.detected) {
console.log('[ZMODEM] Detected, direction:', detection.direction)
if (detection.direction === 'receive') {
// Remote wants to send (ZRQINIT), we receive file
console.log('[TEST] Starting file download...')
startDownloadSession(session, detection.initialData)
} else {
// Feed data to existing session
console.log('[ZMODEM] Feeding data to existing session')
session.feedIncoming(detection.initialData)
}
} else {
// Regular terminal output
const text = data.toString('utf8')
// Filter out control sequences for cleaner output (ANSI escape sequences)
// eslint-disable-next-line no-control-regex
const cleanText = text.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1b].*?\x07/g, '')
if (cleanText.trim().length > 0) {
process.stdout.write(cleanText)
}
}
})
stream.on('close', () => {
console.log('[SSH] Stream closed')
conn.end()
if (!testComplete) {
resolve()
}
})
stream.stderr.on('data', (data) => {
console.error('[SSH] stderr:', data.toString())
})
// Run download test
async function runDownloadTest () {
try {
// Test: sz command (download)
console.log('\n=== Test: sz command (download) ===')
console.log('[TEST] Requesting file:', DOWNLOAD_FILE_NAME)
stream.write(`sz ${DOWNLOAD_FILE_NAME}\n`)
// Wait for download to complete with timeout
try {
await waitForComplete(session, 180000)
console.log('[TEST] Download session complete')
} catch (e) {
console.log('[TEST] Download timeout or error:', e.message)
}
// Wait for any remaining processing
await new Promise((_resolve) => setTimeout(_resolve, 1000))
console.log('[TEST] Download test complete, state:', session.state)
testComplete = true
stream.write('exit\n')
resolve()
} catch (err) {
console.error('[TEST] Error:', err)
reject(err)
}
}
// Start test after shell is ready
setTimeout(runDownloadTest, 1500)
})
})
conn.on('error', (err) => {
console.error('[SSH] Connection error:', err)
reject(err)
})
conn.on('close', () => {
console.log('[SSH] Connection closed')
})
console.log('[SSH] Connecting to', SSH_CONFIG.host + ':' + SSH_CONFIG.port)
conn.connect(SSH_CONFIG)
})
}
// Run the test
runTest()
.then(() => {
console.log('\n=== Test completed successfully ===')
process.exit(0)
})
.catch((err) => {
console.error('\n=== Test failed ===')
console.error(err)
process.exit(1)
})
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
test/integration/ssh-upload.test.mjs
|
JavaScript
|
/**
* Pure Node.js test for SSH connection with ZMODEM upload (rz command).
*
* This test connects to an SSH server and tests:
* - rz command - trigger upload, send file to server
*/
import { Client } from 'ssh2'
import { readFileSync, writeFileSync, unlinkSync, existsSync } from 'fs'
import { basename } from 'path'
import { Sender } from '../../dist/esm/index.js'
import { ZmodemSession } from './zmodem-session.mjs'
/**
* Start upload session after ZRINIT detection.
* @param {ZmodemSession} session - Session in detected state
* @param {string} fileName - File name
* @param {number} fileSize - File size
* @param {Uint8Array} fileData - File data
*/
function startUploadSession (session, fileName, fileSize, fileData) {
console.log('[ZMODEM] Starting file upload:', fileName, 'size:', fileSize)
session.state = 'sending'
session.currentFileName = fileName
session.currentFileSize = fileSize
session.bytesTransferred = 0
session.fileBuffer = fileData
// Create sender as non-initiator (false) since remote sent ZRINIT first
session.sender = new Sender(false)
session.sender.startFile(fileName, fileSize)
// Feed pending data (ZRINIT) to sender first
for (const data of session.pendingData) {
session.feedIncoming(data)
}
session.pendingData = []
}
// SSH connection configuration
const SSH_CONFIG = {
host: 'localhost',
port: 23355,
username: 'zxd',
password: 'zxd',
readyTimeout: 30000
}
// File paths
const UPLOAD_FILE_PATH = '/Users/zxd/dev/zmodem2-js/test/testfile_5m.bin'
const TEST_FILE_SIZE = 5 * 1024 * 1024 // 5MB
/**
* Generate test file with specified size.
* @param {string} filePath - Path to the test file
* @param {number} size - File size in bytes
*/
function generateTestFile (filePath, size) {
console.log('[TEST] Generating test file:', filePath, 'size:', size)
const buffer = Buffer.alloc(size)
// Fill with pseudo-random data for reproducibility
for (let i = 0; i < size; i++) {
buffer[i] = (i * 251) % 256
}
writeFileSync(filePath, buffer)
console.log('[TEST] Test file generated successfully')
}
/**
* Delete test file if exists.
* @param {string} filePath - Path to the test file
*/
function cleanupTestFile (filePath) {
if (existsSync(filePath)) {
console.log('[TEST] Cleaning up test file:', filePath)
unlinkSync(filePath)
console.log('[TEST] Test file deleted')
}
}
// Mock user file selection (returns selected file path)
async function mockSelectFile () {
console.log('[MOCK] User selecting file:', UPLOAD_FILE_PATH)
return UPLOAD_FILE_PATH
}
/**
* Wait for session to complete with timeout.
* @param {ZmodemSession} session - Session to monitor
* @param {number} timeout - Timeout in milliseconds
*/
function waitForComplete (session, timeout = 120000) {
return new Promise((resolve, reject) => {
const startTime = Date.now()
const checkInterval = setInterval(() => {
if (session.sessionComplete) {
clearInterval(checkInterval)
resolve(true)
} else if (Date.now() - startTime > timeout) {
clearInterval(checkInterval)
reject(new Error(`Timeout waiting for session complete, current state: ${session.state}`))
}
}, 500)
})
}
/**
* Run SSH connection and ZMODEM upload test.
*/
async function runTest () {
console.log('=== SSH ZMODEM Upload Test ===')
console.log('SSH Config:', { ...SSH_CONFIG, password: '***' })
console.log('')
const conn = new Client()
return new Promise((resolve, reject) => {
conn.on('ready', () => {
console.log('[SSH] Connected to server')
conn.shell((err, stream) => {
if (err !== null && err !== undefined) {
console.error('[SSH] Failed to create shell:', err)
conn.end()
reject(err)
return
}
if (stream === undefined) {
console.error('[SSH] Failed to create shell: stream is undefined')
conn.end()
reject(new Error('Shell stream is undefined'))
return
}
console.log('[SSH] Shell created')
const session = new ZmodemSession(stream, {})
let testComplete = false
stream.on('data', (data) => {
const str = data.toString('binary')
console.log('[SSH] Received data:', str.length, 'bytes', 'state:', session.state)
// If session is active, feed data directly
if (session.state !== 'idle' && session.state !== 'detected') {
session.feedIncoming(data)
return
}
// Check for ZMODEM detection
const detection = session.detectZmodem(data)
if (detection.detected) {
console.log('[ZMODEM] Detected, direction:', detection.direction)
if (detection.direction === 'send') {
// Remote is ready to receive (ZRINIT), we send file
console.log('[TEST] Starting file upload...')
// Store the ZRINIT data for later
session.pendingData.push(data)
session.state = 'detected'
mockSelectFile().then((filePath) => {
const fileName = basename(filePath)
const fileData = readFileSync(filePath)
console.log('[TEST] File loaded:', fileName, 'size:', fileData.length)
startUploadSession(session, fileName, fileData.length, new Uint8Array(fileData))
}).catch(reject)
} else {
// Feed data to existing session
console.log('[ZMODEM] Feeding data to existing session')
session.feedIncoming(detection.initialData)
}
} else {
// Regular terminal output
const text = data.toString('utf8')
// Filter out control sequences for cleaner output (ANSI escape sequences)
// eslint-disable-next-line no-control-regex
const cleanText = text.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1b].*?\x07/g, '')
if (cleanText.trim().length > 0) {
process.stdout.write(cleanText)
}
}
})
stream.on('close', () => {
console.log('[SSH] Stream closed')
conn.end()
if (!testComplete) {
resolve()
}
})
stream.stderr.on('data', (data) => {
console.error('[SSH] stderr:', data.toString())
})
// Run upload test
async function runUploadTest () {
try {
// Delete existing file on server to avoid conflict
const uploadFileName = basename(UPLOAD_FILE_PATH)
console.log('\n=== Preparing: Delete existing file on server ===')
stream.write(`rm -f ${uploadFileName}\n`)
await new Promise((_resolve) => setTimeout(_resolve, 1500))
// Test: rz command (upload)
console.log('\n=== Test: rz command (upload) ===')
stream.write('rz\n')
// Wait for upload to complete with timeout
try {
await waitForComplete(session, 180000)
console.log('[TEST] Upload session complete')
} catch (e) {
console.log('[TEST] Upload timeout or error:', e.message)
}
// Wait for any remaining processing
await new Promise((_resolve) => setTimeout(_resolve, 1000))
console.log('[TEST] Upload test complete, state:', session.state)
testComplete = true
stream.write('exit\n')
resolve()
} catch (err) {
console.error('[TEST] Error:', err)
reject(err)
}
}
// Start test after shell is ready
setTimeout(runUploadTest, 1500)
})
})
conn.on('error', (err) => {
console.error('[SSH] Connection error:', err)
reject(err)
})
conn.on('close', () => {
console.log('[SSH] Connection closed')
})
console.log('[SSH] Connecting to', SSH_CONFIG.host + ':' + SSH_CONFIG.port)
conn.connect(SSH_CONFIG)
})
}
// Run the test
// Generate test file before test
generateTestFile(UPLOAD_FILE_PATH, TEST_FILE_SIZE)
runTest()
.then(() => {
console.log('\n=== Test completed successfully ===')
cleanupTestFile(UPLOAD_FILE_PATH)
process.exit(0)
})
.catch((err) => {
console.error('\n=== Test failed ===')
console.error(err)
cleanupTestFile(UPLOAD_FILE_PATH)
process.exit(1)
})
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
test/integration/zmodem-session.mjs
|
JavaScript
|
/**
* ZmodemSession class for handling ZMODEM transfers over a stream.
*
* This module provides a reusable ZMODEM session handler that can work with
* any duplex stream (SSH, serial, WebSocket, etc.).
*/
import { writeFileSync, existsSync, mkdirSync } from 'fs'
import { join, basename, extname } from 'path'
import { Sender, Receiver, SenderEvent, ReceiverEvent } from '../../dist/esm/index.js'
/**
* Generate a unique filename if file already exists.
* Adds .1, .2, .3 etc. suffix before the extension.
* @param {string} dir - Directory path
* @param {string} fileName - Original file name
* @returns {string} - Unique file path
*/
function getUniqueFilePath (dir, fileName) {
let filePath = join(dir, fileName)
if (!existsSync(filePath)) {
return filePath
}
// File exists, need to rename
const ext = extname(fileName)
const baseName = basename(fileName, ext)
let counter = 1
while (existsSync(filePath)) {
const newFileName = `${baseName}.${counter}${ext}`
filePath = join(dir, newFileName)
counter++
}
return filePath
}
/**
* ZmodemSession class for handling ZMODEM transfers.
*/
export class ZmodemSession {
constructor (stream, options = {}) {
this.stream = stream
this.options = {
downloadDir: options.downloadDir || './downloads',
onProgress: options.onProgress || null,
onFileStart: options.onFileStart || null,
onFileComplete: options.onFileComplete || null,
onSessionComplete: options.onSessionComplete || null
}
this.sender = null
this.receiver = null
this.state = 'idle'
this.sessionComplete = false // Flag to track session completion
this.currentFileName = ''
this.currentFileSize = 0
this.bytesTransferred = 0
this.fileBuffer = null
this.pendingData = []
this.resolveSession = null
this.rejectSession = null
}
/**
* Detect ZModem header in incoming data.
*/
detectZmodem (data) {
const str = data.toString('binary')
const zhexIndex = str.indexOf('\x2a\x2a\x18\x42')
const zbinIndex = str.indexOf('\x2a\x18\x42')
if (zhexIndex === -1 && zbinIndex === -1) {
return { detected: false, direction: null, initialData: null }
}
const startIndex = zhexIndex !== -1 ? zhexIndex : zbinIndex
const headerStart = startIndex + (zhexIndex !== -1 ? 4 : 3)
if (headerStart + 2 <= str.length) {
const hexFrameType = str.substring(headerStart, headerStart + 2)
const frameType = parseInt(hexFrameType, 16)
console.log('[ZMODEM] Detected frame type:', hexFrameType, '(decimal:', frameType, ')')
// Extract only the ZMODEM data (from the header start)
const zmodemData = data.slice(startIndex)
if (frameType === 0x00) {
// ZRQINIT - remote wants to send, we should receive
console.log('[ZMODEM] ZRQINIT detected - remote wants to send file')
return { detected: true, direction: 'receive', initialData: zmodemData }
} else if (frameType === 0x01) {
// ZRINIT - remote ready to receive, we should send
console.log('[ZMODEM] ZRINIT detected - remote ready to receive file')
return { detected: true, direction: 'send', initialData: zmodemData }
}
}
// Extract only the ZMODEM data (from the header start)
const zmodemData = data.slice(zhexIndex !== -1 ? zhexIndex : zbinIndex)
return { detected: true, direction: 'receive', initialData: zmodemData }
}
/**
* Start a receive session (sz command - remote sends file to us).
*/
startReceive (initialData = null) {
if (this.state !== 'idle') {
console.log('[ZMODEM] startReceive called but state is not idle:', this.state)
return
}
console.log('[ZMODEM] Starting receive session')
this.state = 'receiving'
this.receiver = new Receiver()
this.fileBuffer = []
if (initialData !== null) {
this.feedIncoming(initialData)
}
}
/**
* Start a send session (rz command - we send file to remote).
*/
startSend (fileName, fileSize, fileData) {
if (this.state !== 'idle') {
console.log('[ZMODEM] startSend called but state is not idle:', this.state)
return
}
console.log('[ZMODEM] Starting send session for file:', fileName, 'size:', fileSize)
this.state = 'sending'
this.currentFileName = fileName
this.currentFileSize = fileSize
this.bytesTransferred = 0
this.fileBuffer = fileData
// Create sender as initiator (we start the transfer)
this.sender = new Sender()
this.sender.startFile(fileName, fileSize)
// Process pending data first
for (const data of this.pendingData) {
this.feedIncoming(data)
}
this.pendingData = []
this.processSenderOutgoing()
}
/**
* Strip non-ZMODEM data from incoming buffer.
* ZMODEM data starts with **^B (0x2a 0x2a 0x18 0x42) or *^B (0x2a 0x18 0x42)
* Only strips data if a ZMODEM header is found somewhere in the buffer.
* If no header found, returns data as-is (it might be file data).
*/
stripNonZmodemData (data) {
const str = data.toString('binary')
const zhexIndex = str.indexOf('\x2a\x2a\x18\x42')
const zbinIndex = str.indexOf('\x2a\x18\x42')
// If no ZMODEM header found, pass data through as-is
// (it might be file data that doesn't start with header)
if (zhexIndex === -1 && zbinIndex === -1) {
return data
}
const startIndex = zhexIndex !== -1 ? zhexIndex : zbinIndex
if (startIndex === 0) {
return data // Data already starts with ZMODEM
}
console.log('[ZMODEM] Stripping', startIndex, 'bytes of non-ZMODEM data')
return data.slice(startIndex)
}
/**
* Feed incoming data to sender or receiver.
* Uses a loop pattern similar to WASM reference to ensure all data is processed.
*/
feedIncoming (data) {
if (this.receiver !== null) {
// Don't strip non-ZMODEM data during active receiver session
// The receiver handles raw ZMODEM protocol data including file data
let offset = 0
let loopCount = 0
const u8 = new Uint8Array(data)
while (offset < u8.length && loopCount++ < 1000) {
if (this.receiver === null) break
try {
const chunk = u8.subarray(offset)
const consumed = this.receiver.feedIncoming(chunk)
offset += consumed
// Process outgoing, events, and file data
const drained = this.pumpReceiver()
// If we didn't consume input and didn't generate output/events, we are stuck
if (consumed === 0 && !drained) {
if (loopCount > 1) console.warn('[ZMODEM] Receiver stuck: 0 consumed, 0 drained')
break
}
} catch (err) {
console.error('[ZMODEM] Receiver error:', err.message)
// On error, cleanup and reset
this.state = 'error'
this.cleanup()
break
}
}
console.log('[ZMODEM] Receiver total consumed:', offset, 'bytes out of', u8.length)
} else if (this.sender !== null) {
let offset = 0
let loopCount = 0
const u8 = new Uint8Array(data)
while (offset < u8.length && loopCount++ < 1000) {
if (this.sender === null) break
try {
const chunk = u8.subarray(offset)
const consumed = this.sender.feedIncoming(chunk)
offset += consumed
// Process outgoing, events, and file requests
const drained = this.pumpSender()
// If we didn't consume input and didn't generate output/events, we are stuck
if (consumed === 0 && !drained) {
if (loopCount > 1) console.warn('[ZMODEM] Sender stuck: 0 consumed, 0 drained')
break
}
} catch (err) {
console.error('[ZMODEM] Sender error:', err.message)
// On error, cleanup and reset
this.state = 'error'
this.cleanup()
break
}
}
console.log('[ZMODEM] Sender total consumed:', offset, 'bytes out of', u8.length)
} else {
// Store pending data for later
this.pendingData.push(data)
}
}
/**
* Pump receiver: drain outgoing, process events, drain file data.
* Returns true if any work was done.
*/
pumpReceiver () {
if (this.receiver === null) return false
let didWork = false
// Drain and send outgoing data
const outgoing = this.receiver.drainOutgoing()
if (outgoing.length > 0) {
console.log('[ZMODEM] Receiver sending outgoing data:', outgoing.length, 'bytes')
this.stream.write(Buffer.from(outgoing))
this.receiver.advanceOutgoing(outgoing.length)
didWork = true
}
// Process events
let event
while ((event = this.receiver.pollEvent()) !== null) {
console.log('[ZMODEM] Receiver event:', event)
didWork = true
switch (event) {
case ReceiverEvent.FileStart:
this.currentFileName = this.receiver.getFileName()
this.currentFileSize = this.receiver.getFileSize()
this.bytesTransferred = 0
this.fileBuffer = []
console.log('[ZMODEM] File start:', this.currentFileName, 'size:', this.currentFileSize)
if (this.options.onFileStart !== null) {
this.options.onFileStart(this.currentFileName, this.currentFileSize)
}
break
case ReceiverEvent.FileComplete:
console.log('[ZMODEM] File complete:', this.currentFileName)
this.saveReceivedFile()
if (this.options.onFileComplete !== null) {
this.options.onFileComplete(this.currentFileName)
}
break
case ReceiverEvent.SessionComplete:
console.log('[ZMODEM] Receive session complete')
this.state = 'complete'
this.sessionComplete = true
if (this.options.onSessionComplete !== null) {
this.options.onSessionComplete()
}
if (this.resolveSession !== null) {
this.resolveSession()
}
this.cleanup()
return true
}
}
// Drain file data
const fileData = this.receiver.drainFile()
if (fileData.length > 0) {
this.fileBuffer.push(Buffer.from(fileData))
this.bytesTransferred += fileData.length
this.receiver.advanceFile(fileData.length)
const percentage = this.currentFileSize > 0
? Math.round((this.bytesTransferred / this.currentFileSize) * 100)
: 0
console.log('[ZMODEM] Receive progress:', this.bytesTransferred, '/', this.currentFileSize, '(', percentage, '%)')
if (this.options.onProgress !== null) {
this.options.onProgress(this.bytesTransferred, this.currentFileSize, percentage)
}
didWork = true
}
return didWork
}
/**
* Pump sender: drain outgoing, process events, handle file requests.
* Returns true if any work was done.
*/
pumpSender () {
if (this.sender === null) return false
let didWork = false
// Drain and send outgoing data
const outgoing = this.sender.drainOutgoing()
if (outgoing.length > 0) {
console.log('[ZMODEM] Sender sending outgoing data:', outgoing.length, 'bytes')
this.stream.write(Buffer.from(outgoing))
this.sender.advanceOutgoing(outgoing.length)
didWork = true
}
// Process events
let event
while ((event = this.sender.pollEvent()) !== null) {
console.log('[ZMODEM] Sender event:', event)
didWork = true
switch (event) {
case SenderEvent.FileComplete:
console.log('[ZMODEM] Sender file complete:', this.currentFileName)
if (this.options.onFileComplete !== null) {
this.options.onFileComplete(this.currentFileName)
}
// After file complete, finish the session to send ZEOF and complete handshake
console.log('[ZMODEM] Calling finishSession() to complete handshake')
this.sender.finishSession()
// Drain outgoing immediately after finishSession
const finishOutgoing = this.sender.drainOutgoing()
if (finishOutgoing.length > 0) {
console.log('[ZMODEM] Sender sending finish outgoing:', finishOutgoing.length, 'bytes')
this.stream.write(Buffer.from(finishOutgoing))
this.sender.advanceOutgoing(finishOutgoing.length)
}
break
case SenderEvent.SessionComplete:
console.log('[ZMODEM] Send session complete')
this.state = 'complete'
this.sessionComplete = true
if (this.options.onSessionComplete !== null) {
this.options.onSessionComplete()
}
if (this.resolveSession !== null) {
this.resolveSession()
}
this.cleanup()
return true
}
}
// Handle file requests
const request = this.sender.pollFile()
if (request !== null) {
const { offset, len } = request
const data = this.fileBuffer.slice(offset, offset + len)
if (data.length > 0) {
console.log('[ZMODEM] Sender feeding file data at offset:', offset, 'len:', data.length)
this.sender.feedFile(data)
this.bytesTransferred = offset + data.length
const percentage = this.currentFileSize > 0
? Math.round((this.bytesTransferred / this.currentFileSize) * 100)
: 0
console.log('[ZMODEM] Send progress:', this.bytesTransferred, '/', this.currentFileSize, '(', percentage, '%)')
if (this.options.onProgress !== null) {
this.options.onProgress(this.bytesTransferred, this.currentFileSize, percentage)
}
// Drain outgoing after feeding file data
const fileOutgoing = this.sender.drainOutgoing()
if (fileOutgoing.length > 0) {
console.log('[ZMODEM] Sender sending file outgoing:', fileOutgoing.length, 'bytes')
this.stream.write(Buffer.from(fileOutgoing))
this.sender.advanceOutgoing(fileOutgoing.length)
}
didWork = true
} else if (offset >= this.currentFileSize) {
console.log('[ZMODEM] Sender finishing session, offset:', offset, 'fileSize:', this.currentFileSize)
this.sender.finishSession()
// Drain outgoing after finish
const endOutgoing = this.sender.drainOutgoing()
if (endOutgoing.length > 0) {
this.stream.write(Buffer.from(endOutgoing))
this.sender.advanceOutgoing(endOutgoing.length)
}
didWork = true
}
}
return didWork
}
/**
* Save received file to disk.
* Uses unique filename if file already exists.
*/
saveReceivedFile () {
if (this.currentFileName && this.fileBuffer.length > 0) {
const downloadDir = this.options.downloadDir
if (!existsSync(downloadDir)) {
mkdirSync(downloadDir, { recursive: true })
}
// Get unique file path (adds .1, .2 etc. if file exists)
const filePath = getUniqueFilePath(downloadDir, this.currentFileName)
const fileData = Buffer.concat(this.fileBuffer)
try {
writeFileSync(filePath, fileData)
console.log('[ZMODEM] File saved:', filePath, 'size:', fileData.length)
} catch (err) {
console.error('[ZMODEM] Failed to save file:', err.message)
}
}
}
/**
* Clean up session state.
*/
cleanup () {
this.sender = null
this.receiver = null
this.state = 'idle'
this.currentFileName = ''
this.currentFileSize = 0
this.bytesTransferred = 0
this.fileBuffer = null
this.pendingData = []
// Note: sessionComplete flag is NOT reset here - it persists until explicitly reset
}
/**
* Reset session for a new transfer.
*/
reset () {
this.cleanup()
this.sessionComplete = false
}
/**
* Wait for session to complete.
*/
waitForComplete () {
return new Promise((resolve, reject) => {
this.resolveSession = resolve
this.rejectSession = reject
})
}
}
export default ZmodemSession
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
test/unit/crc.test.ts
|
TypeScript
|
/**
* Tests for CRC functions.
*/
import { describe, it, expect } from 'vitest'
import { crc16Xmodem, crc32IsoHdlc, Crc16, Crc32 } from '../../src/lib/crc.js'
describe('CRC-16-XMODEM', () => {
it('should compute correct CRC-16 for empty data', () => {
const result = crc16Xmodem(new Uint8Array(0))
expect(result).toBe(0x0000)
})
it('should compute correct CRC-16 for "123456789"', () => {
const data = new TextEncoder().encode('123456789')
const result = crc16Xmodem(data)
// CRC-16-XMODEM check value for "123456789" is 0x31C3
expect(result).toBe(0x31C3)
})
it('should compute correct CRC-16 for single byte', () => {
const data = new Uint8Array([0x00])
const result = crc16Xmodem(data)
expect(result).toBe(0x0000)
})
it('Crc16 class should produce same result as function', () => {
const data = new TextEncoder().encode('Hello, World!')
const funcResult = crc16Xmodem(data)
const crc = new Crc16()
crc.update(data)
const classResult = crc.finalize()
expect(classResult).toBe(funcResult)
})
it('Crc16 class should support incremental updates', () => {
const data1 = new TextEncoder().encode('Hello')
const data2 = new TextEncoder().encode(', World!')
const crc = new Crc16()
crc.update(data1)
crc.update(data2)
const result = crc.finalize()
const expected = crc16Xmodem(new TextEncoder().encode('Hello, World!'))
expect(result).toBe(expected)
})
it('Crc16 reset should work correctly', () => {
const crc = new Crc16()
crc.update(new TextEncoder().encode('test'))
crc.reset()
crc.update(new TextEncoder().encode('123456789'))
const result = crc.finalize()
expect(result).toBe(0x31C3)
})
})
describe('CRC-32-ISO-HDLC', () => {
it('should compute correct CRC-32 for empty data', () => {
const result = crc32IsoHdlc(new Uint8Array(0))
expect(result).toBe(0x00000000)
})
it('should compute correct CRC-32 for "123456789"', () => {
const data = new TextEncoder().encode('123456789')
const result = crc32IsoHdlc(data)
// CRC-32 check value for "123456789" is 0xCBF43926
expect(result).toBe(0xCBF43926)
})
it('should compute correct CRC-32 for single byte', () => {
const data = new Uint8Array([0x00])
const result = crc32IsoHdlc(data)
expect(result).toBe(0xD202EF8D)
})
it('Crc32 class should produce same result as function', () => {
const data = new TextEncoder().encode('Hello, World!')
const funcResult = crc32IsoHdlc(data)
const crc = new Crc32()
crc.update(data)
const classResult = crc.finalize()
expect(classResult).toBe(funcResult)
})
it('Crc32 class should support incremental updates', () => {
const data1 = new TextEncoder().encode('Hello')
const data2 = new TextEncoder().encode(', World!')
const crc = new Crc32()
crc.update(data1)
crc.update(data2)
const result = crc.finalize()
const expected = crc32IsoHdlc(new TextEncoder().encode('Hello, World!'))
expect(result).toBe(expected)
})
it('Crc32 reset should work correctly', () => {
const crc = new Crc32()
crc.update(new TextEncoder().encode('test'))
crc.reset()
crc.update(new TextEncoder().encode('123456789'))
const result = crc.finalize()
expect(result).toBe(0xCBF43926)
})
})
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
test/unit/header.test.ts
|
TypeScript
|
/**
* Tests for Header encoding/decoding.
*/
import { describe, it, expect } from 'vitest'
import { Encoding, encodingFromByte, Frame, frameFromByte, Header, Zrinit, decodeHeader, createZrinit } from '../../src/lib/header.js'
import { MalformedEncodingError, MalformedFrameError } from '../../src/lib/error.js'
describe('Encoding', () => {
it('should have correct values', () => {
expect(Encoding.ZBIN).toBe(0x41)
expect(Encoding.ZHEX).toBe(0x42)
expect(Encoding.ZBIN32).toBe(0x43)
})
it('encodingFromByte should return correct encoding', () => {
expect(encodingFromByte(0x41)).toBe(Encoding.ZBIN)
expect(encodingFromByte(0x42)).toBe(Encoding.ZHEX)
expect(encodingFromByte(0x43)).toBe(Encoding.ZBIN32)
})
it('encodingFromByte should throw for invalid byte', () => {
expect(() => encodingFromByte(0x00)).toThrow(MalformedEncodingError)
expect(() => encodingFromByte(0xFF)).toThrow(MalformedEncodingError)
})
})
describe('Frame', () => {
it('should have correct values', () => {
expect(Frame.ZRQINIT).toBe(0)
expect(Frame.ZRINIT).toBe(1)
expect(Frame.ZFILE).toBe(4)
expect(Frame.ZFIN).toBe(8)
expect(Frame.ZDATA).toBe(10)
expect(Frame.ZEOF).toBe(11)
})
it('frameFromByte should return correct frame', () => {
expect(frameFromByte(0)).toBe(Frame.ZRQINIT)
expect(frameFromByte(1)).toBe(Frame.ZRINIT)
expect(frameFromByte(19)).toBe(Frame.ZSTDERR)
})
it('frameFromByte should throw for invalid byte', () => {
expect(() => frameFromByte(20)).toThrow(MalformedFrameError)
expect(() => frameFromByte(255)).toThrow(MalformedFrameError)
})
})
describe('Header', () => {
it('should create header with default flags', () => {
const header = new Header(Encoding.ZBIN, Frame.ZRQINIT)
expect(header.encoding).toBe(Encoding.ZBIN)
expect(header.frame).toBe(Frame.ZRQINIT)
expect(header.count).toBe(0)
})
it('should create header with custom flags', () => {
const flags = new Uint8Array([0x01, 0x02, 0x03, 0x04])
const header = new Header(Encoding.ZBIN, Frame.ZRINIT, flags)
expect(header.flags).toEqual(flags)
expect(header.count).toBe(0x04030201)
})
it('withCount should create new header with count', () => {
const header = new Header(Encoding.ZHEX, Frame.ZRPOS)
const withCount = header.withCount(0x12345678)
expect(withCount.count).toBe(0x12345678)
expect(header.count).toBe(0) // Original unchanged
})
it('readSize should return correct sizes', () => {
expect(Header.readSize(Encoding.ZBIN)).toBe(7) // 5 + 2
expect(Header.readSize(Encoding.ZBIN32)).toBe(9) // 5 + 4
expect(Header.readSize(Encoding.ZHEX)).toBe(14) // (5 + 2) * 2
})
it('should encode ZHEX header correctly', () => {
const header = new Header(Encoding.ZHEX, Frame.ZRQINIT)
const encoded = header.encode()
// Should start with ZPAD ZPAD ZDLE
expect(encoded[0]).toBe(0x2a) // ZPAD
expect(encoded[1]).toBe(0x2a) // ZPAD
expect(encoded[2]).toBe(0x18) // ZDLE
expect(encoded[3]).toBe(0x42) // ZHEX
})
it('should encode ZBIN header correctly', () => {
const header = new Header(Encoding.ZBIN, Frame.ZRINIT, new Uint8Array([0x00, 0x04, 0x00, 0x21]))
const encoded = header.encode()
// Should start with ZPAD ZDLE
expect(encoded[0]).toBe(0x2a) // ZPAD
expect(encoded[1]).toBe(0x18) // ZDLE
expect(encoded[2]).toBe(0x41) // ZBIN
})
it('should encode ZBIN32 header correctly', () => {
const header = new Header(Encoding.ZBIN32, Frame.ZDATA)
const encoded = header.encode()
// Should start with ZPAD ZDLE
expect(encoded[0]).toBe(0x2a) // ZPAD
expect(encoded[1]).toBe(0x18) // ZDLE
expect(encoded[2]).toBe(0x43) // ZBIN32
})
})
describe('createZrinit', () => {
it('should create ZRINIT header with correct values', () => {
const header = createZrinit(1024, Zrinit.CANFDX | Zrinit.CANFC32)
expect(header.frame).toBe(Frame.ZRINIT)
expect(header.encoding).toBe(Encoding.ZHEX)
expect(header.flags[0]).toBe(0x00) // Buffer size low byte
expect(header.flags[1]).toBe(0x04) // Buffer size high byte (1024 = 0x0400)
expect(header.flags[3]).toBe(Zrinit.CANFDX | Zrinit.CANFC32)
})
})
describe('decodeHeader', () => {
it('should round-trip ZBIN header', () => {
const original = new Header(Encoding.ZBIN, Frame.ZRINIT, new Uint8Array([0x01, 0x02, 0x03, 0x04]))
const encoded = original.encode()
// Extract the payload (skip header start bytes)
let payloadStart = 0
if (encoded[0] === 0x2a) payloadStart++
if (encoded[payloadStart] === 0x2a) payloadStart++
if (encoded[payloadStart] === 0x18) payloadStart++
if (encoded[payloadStart] === 0x41 || encoded[payloadStart] === 0x42 || encoded[payloadStart] === 0x43) payloadStart++
const payload = encoded.slice(payloadStart)
const decoded = decodeHeader(Encoding.ZBIN, payload)
expect(decoded.frame).toBe(original.frame)
expect(decoded.count).toBe(original.count)
})
it('should round-trip ZHEX header', () => {
const original = new Header(Encoding.ZHEX, Frame.ZRQINIT)
const encoded = original.encode()
// Extract the hex payload (skip header start bytes and CR/LF/XON)
let payloadStart = 0
if (encoded[0] === 0x2a) payloadStart++
if (encoded[payloadStart] === 0x2a) payloadStart++
if (encoded[payloadStart] === 0x18) payloadStart++
if (encoded[payloadStart] === 0x42) payloadStart++
// Find end of hex data (before CR/LF)
let payloadEnd = payloadStart
while (payloadEnd < encoded.length && encoded[payloadEnd] !== 0x0d) {
payloadEnd++
}
const payload = encoded.slice(payloadStart, payloadEnd)
const decoded = decodeHeader(Encoding.ZHEX, payload)
expect(decoded.frame).toBe(original.frame)
expect(decoded.count).toBe(original.count)
})
it('should round-trip ZBIN32 header', () => {
const original = new Header(Encoding.ZBIN32, Frame.ZDATA, new Uint8Array([0x78, 0x56, 0x34, 0x12]))
const encoded = original.encode()
// Extract the payload
let payloadStart = 0
if (encoded[0] === 0x2a) payloadStart++
if (encoded[payloadStart] === 0x2a) payloadStart++
if (encoded[payloadStart] === 0x18) payloadStart++
if (encoded[payloadStart] === 0x43) payloadStart++
const payload = encoded.slice(payloadStart)
const decoded = decodeHeader(Encoding.ZBIN32, payload)
expect(decoded.frame).toBe(original.frame)
expect(decoded.count).toBe(original.count)
})
})
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
test/unit/transmission.test.ts
|
TypeScript
|
/**
* Tests for Sender and Receiver state machines.
*/
import { describe, it, expect } from 'vitest'
import { Sender, Receiver } from '../../src/lib/transmission.js'
import { Frame, Encoding, Header, createZrinit } from '../../src/lib/header.js'
describe('Sender', () => {
it('should create sender with ZRQINIT queued', () => {
const sender = new Sender()
const outgoing = sender.drainOutgoing()
expect(outgoing.length).toBeGreaterThan(0)
// Should start with ZPAD ZPAD ZDLE ZHEX
expect(outgoing[0]).toBe(0x2a) // ZPAD
expect(outgoing[1]).toBe(0x2a) // ZPAD
expect(outgoing[2]).toBe(0x18) // ZDLE
expect(outgoing[3]).toBe(0x42) // ZHEX
})
it('should advance outgoing cursor', () => {
const sender = new Sender()
const initial = sender.drainOutgoing()
const len = initial.length
sender.advanceOutgoing(len)
expect(sender.drainOutgoing().length).toBe(0)
})
it('should handle ZRINIT from receiver', () => {
const sender = new Sender()
// Clear initial ZRQINIT
sender.advanceOutgoing(sender.drainOutgoing().length)
// Simulate receiving ZRINIT
const zrinit = createZrinit(1024, 0x21).encode()
sender.feedIncoming(zrinit)
// No event should be pending yet
expect(sender.pollEvent()).toBeNull()
})
it('should start file transfer after ZRINIT', () => {
const sender = new Sender()
// Clear initial ZRQINIT
sender.advanceOutgoing(sender.drainOutgoing().length)
// Simulate receiving ZRINIT
const zrinit = createZrinit(1024, 0x21).encode()
sender.feedIncoming(zrinit)
// Start file transfer
sender.startFile('test.txt', 100)
// Should have ZFILE header queued
const outgoing = sender.drainOutgoing()
expect(outgoing.length).toBeGreaterThan(0)
})
it('should request file data after ZRPOS', () => {
const sender = new Sender()
// Clear initial ZRQINIT
sender.advanceOutgoing(sender.drainOutgoing().length)
// Simulate receiving ZRINIT
const zrinit = createZrinit(1024, 0x21).encode()
sender.feedIncoming(zrinit)
// Start file transfer
sender.startFile('test.txt', 100)
sender.advanceOutgoing(sender.drainOutgoing().length)
// Simulate receiving ZRPOS(0)
const zrpos = new Header(Encoding.ZHEX, Frame.ZRPOS).withCount(0).encode()
sender.feedIncoming(zrpos)
// Should have a file request
const request = sender.pollFile()
expect(request).not.toBeNull()
expect(request?.offset).toBe(0)
expect(request?.len).toBeGreaterThan(0)
})
it('should send file data', () => {
const sender = new Sender()
// Clear initial ZRQINIT
sender.advanceOutgoing(sender.drainOutgoing().length)
// Simulate receiving ZRINIT
const zrinit = createZrinit(1024, 0x21).encode()
sender.feedIncoming(zrinit)
// Start file transfer
sender.startFile('test.txt', 100)
sender.advanceOutgoing(sender.drainOutgoing().length)
// Simulate receiving ZRPOS(0)
const zrpos = new Header(Encoding.ZHEX, Frame.ZRPOS).withCount(0).encode()
sender.feedIncoming(zrpos)
// Get file request
const request = sender.pollFile()
expect(request).not.toBeNull()
// Feed file data
if (request != null) {
const data = new Uint8Array(request.len).fill(0x41) // Fill with 'A'
sender.feedFile(data)
}
// Should have outgoing data
const outgoing = sender.drainOutgoing()
expect(outgoing.length).toBeGreaterThan(0)
})
it('should handle finish session', () => {
const sender = new Sender()
// Clear initial ZRQINIT
sender.advanceOutgoing(sender.drainOutgoing().length)
// Simulate receiving ZRINIT
const zrinit = createZrinit(1024, 0x21).encode()
sender.feedIncoming(zrinit)
// Request finish
sender.finishSession()
// Should have ZFIN queued
const outgoing = sender.drainOutgoing()
expect(outgoing.length).toBeGreaterThan(0)
})
})
describe('Receiver', () => {
it('should create receiver with ZRINIT queued', () => {
const receiver = new Receiver()
const outgoing = receiver.drainOutgoing()
expect(outgoing.length).toBeGreaterThan(0)
// Should start with ZPAD ZPAD ZDLE ZHEX
expect(outgoing[0]).toBe(0x2a) // ZPAD
expect(outgoing[1]).toBe(0x2a) // ZPAD
expect(outgoing[2]).toBe(0x18) // ZDLE
expect(outgoing[3]).toBe(0x42) // ZHEX
})
it('should advance outgoing cursor', () => {
const receiver = new Receiver()
const initial = receiver.drainOutgoing()
const len = initial.length
receiver.advanceOutgoing(len)
expect(receiver.drainOutgoing().length).toBe(0)
})
it('should respond to ZRQINIT with ZRINIT', () => {
const receiver = new Receiver()
// Clear initial ZRINIT
receiver.advanceOutgoing(receiver.drainOutgoing().length)
// Simulate receiving ZRQINIT
const zrqinit = new Header(Encoding.ZHEX, Frame.ZRQINIT).encode()
receiver.feedIncoming(zrqinit)
// Should have ZRINIT queued
const outgoing = receiver.drainOutgoing()
expect(outgoing.length).toBeGreaterThan(0)
})
it('should handle ZFIN after file transfer', () => {
const receiver = new Receiver()
// Clear initial ZRINIT
receiver.advanceOutgoing(receiver.drainOutgoing().length)
// Simulate receiving ZRQINIT
const zrqinit = new Header(Encoding.ZHEX, Frame.ZRQINIT).encode()
receiver.feedIncoming(zrqinit)
// ZRINIT should be queued as response
const outgoing = receiver.drainOutgoing()
expect(outgoing.length).toBeGreaterThan(0)
})
})
describe('Sender-Receiver Integration', () => {
it('should complete handshake', () => {
const sender = new Sender()
const receiver = new Receiver()
// Sender sends ZRQINIT
let senderOut = sender.drainOutgoing()
expect(senderOut.length).toBeGreaterThan(0)
receiver.feedIncoming(senderOut)
sender.advanceOutgoing(senderOut.length)
// Receiver responds with ZRINIT
const receiverOut = receiver.drainOutgoing()
expect(receiverOut.length).toBeGreaterThan(0)
receiver.advanceOutgoing(receiverOut.length)
sender.feedIncoming(receiverOut)
// Verify sender is ready for file
sender.startFile('test.txt', 10)
senderOut = sender.drainOutgoing()
expect(senderOut.length).toBeGreaterThan(0)
})
})
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
vitest.config.ts
|
TypeScript
|
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['test/**/*.test.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
include: ['src/lib/**/*.ts']
}
}
})
|
zxdong262/zmodem2-js
| 0
|
A JavaScript/TypeScript implementation of the ZMODEM file transfer protocol, based on zmodem2 Rust crate
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client-wasm/App.tsx
|
TypeScript (TSX)
|
import React, { useEffect, useRef } from 'react'
import { Terminal } from '@xterm/xterm'
import { WebLinksAddon } from '@xterm/addon-web-links'
import '@xterm/xterm/css/xterm.css'
import AddonZmodemWasm from './zmodem/addon-wasm'
const App: React.FC = () => {
const terminalRef = useRef<HTMLDivElement | null>(null)
const terminal = useRef<Terminal | null>(null)
const ws = useRef<WebSocket | null>(null)
const zmodemAddon = useRef<AddonZmodemWasm | null>(null)
useEffect(() => {
if (terminalRef.current == null) return
const term = new Terminal()
terminal.current = term
term.loadAddon(new WebLinksAddon())
const addon = new AddonZmodemWasm()
zmodemAddon.current = addon
term.loadAddon(addon as any)
term.open(terminalRef.current)
// Using same port as original demo server, assuming it serves both
// Or we might need to change port if user runs a different server?
// Original demo uses localhost:8081/terminal
const websocket = new WebSocket('ws://localhost:8081/terminal')
ws.current = websocket
websocket.binaryType = 'arraybuffer'
websocket.onopen = () => {
console.log('WebSocket connected')
term.writeln('Connected to server (WASM Client)')
}
websocket.onmessage = (event) => {
if (typeof event.data === 'string') {
term.write(event.data)
} else {
// Binary data usually means ZMODEM or just binary output
// Pass to addon to check/handle
addon.consume(event.data)
}
}
websocket.onclose = (event) => {
console.log('WebSocket closed:', event.code, event.reason)
term.writeln(`\r\nConnection closed: ${event.code} ${event.reason}`)
}
websocket.onerror = (error) => {
console.error('WebSocket error:', error)
term.writeln('\r\nWebSocket error occurred')
}
term.onData((data) => {
// If ZMODEM session is active, maybe we should block input?
// For now, just send it.
if (websocket.readyState === WebSocket.OPEN) {
websocket.send(data)
}
})
addon.zmodemAttach({
socket: websocket,
term,
onDetect: (type) => {
if (type === 'send') {
handleSendFile(addon)
}
}
})
return () => {
websocket.close()
term.dispose()
}
}, [])
const handleSendFile = async (addon: AddonZmodemWasm) => {
try {
// Use modern File System Access API if available
if ('showOpenFilePicker' in window) {
const picks = await (window as any).showOpenFilePicker()
if (picks && picks.length > 0) {
const file = await picks[0].getFile()
addon.sendFile(file)
} else {
// User cancelled
}
} else {
// Fallback to hidden input
const input = document.createElement('input')
input.type = 'file'
input.style.display = 'none'
input.onchange = (e) => {
const files = (e.target as HTMLInputElement).files
if (files && files.length > 0) {
addon.sendFile(files[0])
}
}
document.body.appendChild(input)
input.click()
document.body.removeChild(input)
}
} catch (e) {
console.error('File selection failed', e)
terminal.current?.writeln('\r\nFile selection cancelled or failed.')
}
}
return (
<div style={{ width: '100vw', height: '100vh', backgroundColor: '#000' }}>
<div ref={terminalRef} style={{ width: '100%', height: '100%' }} />
</div>
)
}
export default App
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client-wasm/index.html
|
HTML
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zmodem Terminal</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client-wasm/main.tsx
|
TypeScript (TSX)
|
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
const root = ReactDOM.createRoot(document.getElementById('root')!)
root.render(<App />)
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client-wasm/zmodem/addon-wasm.ts
|
TypeScript
|
import { Terminal, IDisposable } from '@xterm/xterm'
import init, { WasmReceiver, WasmSender } from '../../../pkg/zmodem2_wasm.js'
export default class AddonZmodemWasm {
_disposables: IDisposable[] = []
socket: WebSocket | null = null
term: Terminal | null = null
receiver: WasmReceiver | null = null
sender: WasmSender | null = null
wasmInitialized = false
onDetect: ((type: 'receive' | 'send') => void) | null = null
isPickingFile = false
// FIX: Add a flag to prevent concurrent reads
_reading = false
// Buffer for read-ahead
_fileBuffer: Uint8Array | null = null
_fileBufferOffset = 0
readonly BUFFER_SIZE = 10 * 1024 * 1024 // 10MB
currentFile: { name: string, size: number, data: Uint8Array[] } | null = null
sendingFile: File | null = null
constructor() {
this.initWasm()
}
async initWasm() {
try {
await init()
this.wasmInitialized = true
console.log('ZMODEM WASM initialized')
} catch (e) {
console.error('Failed to init WASM', e)
}
}
activate(terminal: Terminal) {
this.term = terminal
}
dispose() {
this.receiver = null
this.sender = null
this._fileBuffer = null
this._disposables.forEach(d => d.dispose())
this._disposables = []
}
zmodemAttach(ctx: { socket: WebSocket, term: Terminal, onDetect?: (type: 'receive' | 'send') => void }) {
this.socket = ctx.socket
this.term = ctx.term
this.socket.binaryType = 'arraybuffer'
if (ctx.onDetect) this.onDetect = ctx.onDetect
}
consume(data: ArrayBuffer | string) {
if (!this.wasmInitialized) {
if (typeof data === 'string') this.term?.write(data)
else this.term?.write(new Uint8Array(data))
return
}
if (this.receiver) {
this.handleReceiver(data)
return
}
if (this.sender) {
this.handleSender(data)
return
}
if (typeof data === 'string') {
this.term?.write(data)
return
}
const u8 = new Uint8Array(data)
// Detection: ** + \x18 + B (ZHEX)
let foundIdx = -1
for (let i = 0; i < u8.length - 3; i++) {
if (u8[i] === 0x2a && u8[i+1] === 0x2a && u8[i+2] === 0x18 && u8[i+3] === 0x42) {
foundIdx = i
break
}
}
if (foundIdx >= 0) {
// Check next 2 bytes for Frame Type (Hex Encoded)
// ZRQINIT = 00 (0x30 0x30) -> Receiver
// ZRINIT = 01 (0x30 0x31) -> Sender
if (foundIdx + 5 < u8.length) {
const typeHex1 = u8[foundIdx + 4]
const typeHex2 = u8[foundIdx + 5]
if (typeHex1 === 0x30 && typeHex2 === 0x30) {
console.log('ZMODEM ZRQINIT detected (Receive)')
if (foundIdx > 0) {
this.term?.write(u8.subarray(0, foundIdx))
}
this.startReceiver(u8.subarray(foundIdx))
return
} else if (typeHex1 === 0x30 && typeHex2 === 0x31) {
console.log('ZMODEM ZRINIT detected (Send)')
if (!this.isPickingFile) {
this.isPickingFile = true
this.onDetect?.('send')
}
return
}
}
// Fallback if not sure
this.term?.write(u8)
} else {
this.term?.write(u8)
}
}
async sendFile(file: File) {
this.isPickingFile = false
this.sendingFile = file
this.sender = new WasmSender()
this._reading = false // Reset reading state
this._fileBuffer = null
this._fileBufferOffset = 0
console.log(`Starting Sender for ${file.name} (${file.size} bytes)`)
try {
this.sender.start_file(file.name, file.size)
this.pumpSender()
} catch (e) {
console.error('Failed to start sender', e)
this.sender = null
}
}
handleSender(data: ArrayBuffer | Uint8Array | string) {
if (!this.sender) return
const u8 = typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)
let offset = 0
let loopCount = 0
while (offset < u8.length && loopCount++ < 1000) {
if (!this.sender) break
try {
const chunk = u8.subarray(offset)
const consumed = this.sender.feed(chunk)
offset += consumed
const drained = this.pumpSender()
// If we didn't consume input and didn't generate output/events, we are stuck.
if (consumed === 0 && !drained) {
// But maybe the sender is just waiting for file data and can't consume more ACKs?
if (loopCount > 1) console.warn('Sender stuck: 0 consumed, 0 drained')
break
}
} catch (e) {
console.error('Sender error:', e)
this.term?.writeln('\r\nZMODEM Sender Error: ' + e)
this.sender = null
this.sendingFile = null
this._fileBuffer = null
break
}
}
}
pumpSender(): boolean {
if (!this.sender) return false
let didWork = false
const outgoingChunks: Uint8Array[] = []
let totalOutgoingSize = 0
const FLUSH_THRESHOLD = 64 * 1024 // 64KB
const flushOutgoing = () => {
if (outgoingChunks.length === 0) return
if (outgoingChunks.length === 1) {
this.socket?.send(outgoingChunks[0])
} else {
this.socket?.send(new Blob(outgoingChunks as any[]))
}
outgoingChunks.length = 0
totalOutgoingSize = 0
}
try {
const outgoing = this.sender.drain_outgoing()
if (outgoing && outgoing.length > 0) {
outgoingChunks.push(outgoing)
totalOutgoingSize += outgoing.length
didWork = true
}
while (true) {
const event = this.sender.poll()
if (!event) break
const e = event as any
// console.log('WASM Sender Event:', e)
didWork = true
if (e.type === 'need_file_data') {
const start = e.offset
const length = e.length
// 1. Try to serve from buffer synchronously
if (this._fileBuffer &&
start >= this._fileBufferOffset &&
(start + length) <= (this._fileBufferOffset + this._fileBuffer.byteLength)) {
const relativeStart = start - this._fileBufferOffset
const chunk = this._fileBuffer.subarray(relativeStart, relativeStart + length)
this.sender.feed_file(chunk)
// IMPORTANT: Drain outgoing data immediately after feeding
const outgoing = this.sender.drain_outgoing()
if (outgoing && outgoing.length > 0) {
outgoingChunks.push(outgoing)
totalOutgoingSize += outgoing.length
if (totalOutgoingSize > FLUSH_THRESHOLD) {
flushOutgoing()
}
}
// Continue loop synchronously
continue
}
// 2. Not in buffer, need to load
// FIX: Check if we are already reading to avoid race conditions
if (this.sendingFile && !this._reading) {
flushOutgoing() // Flush before async break
this._reading = true // Lock
this.loadBufferAndFeed(start, length)
// Break loop to wait for async read
break
} else if (this._reading) {
// Already reading, break loop and wait for that to finish
break
}
} else if (e.type === 'file_complete') {
this.term?.writeln('\r\nZMODEM: File sent.')
this.sender.finish_session()
} else if (e.type === 'session_complete') {
this.term?.writeln('\r\nZMODEM: Session complete.')
this.sender = null
this.sendingFile = null
this._fileBuffer = null
flushOutgoing() // Flush final packets
return true
}
}
} catch (e) {
console.error('Pump Sender Error:', e)
this.term?.writeln('\r\nZMODEM Pump Error: ' + e)
this.sender = null
}
flushOutgoing() // Flush anything remaining at end of loop
return didWork
}
async loadBufferAndFeed(offset: number, length: number) {
if (!this.sender || !this.sendingFile) {
this._reading = false
return
}
try {
// Read a larger chunk to minimize I/O and async overhead
const readSize = Math.max(length, this.BUFFER_SIZE)
const end = Math.min(offset + readSize, this.sendingFile.size)
const slice = this.sendingFile.slice(offset, end)
const buffer = await slice.arrayBuffer()
if (!this.sender) return
const u8 = new Uint8Array(buffer)
// Update buffer
this._fileBuffer = u8
this._fileBufferOffset = offset
// Feed the requested part
// Since we read from 'offset', the requested data starts at 0 in the new buffer
// Note: u8.length might be less than length if we hit EOF
const feedLen = Math.min(length, u8.length)
const chunk = u8.subarray(0, feedLen)
this.sender.feed_file(chunk)
// Unlock BEFORE pumping
this._reading = false
this.pumpSender()
} catch (e) {
console.error('Buffer read error', e)
// Ensure we unlock on error
this._reading = false
// Try to pump again to see if we can recover
try { this.pumpSender() } catch (_) {}
}
}
startReceiver(initialData: Uint8Array) {
console.log('Starting Receiver...')
try {
this.receiver = new WasmReceiver()
this.handleReceiver(initialData)
} catch (e) {
console.error('Failed to create Receiver', e)
}
}
handleReceiver(data: ArrayBuffer | Uint8Array | string) {
if (!this.receiver) return
const u8 = typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)
let offset = 0
let loopCount = 0
while (offset < u8.length && loopCount++ < 1000) {
if (!this.receiver) break
try {
const chunk = u8.subarray(offset)
const consumed = this.receiver.feed(chunk)
offset += consumed
const drained = this.pumpReceiver()
if (consumed === 0 && !drained) {
if (loopCount > 1) console.warn('Receiver stuck: 0 consumed, 0 drained')
break
}
} catch (e) {
console.error('Receiver error:', e)
this.term?.writeln('\r\nZMODEM: Error ' + e)
this.receiver = null
break
}
}
}
pumpReceiver(): boolean {
if (!this.receiver) return false
let didWork = false
try {
const outgoing = this.receiver.drain_outgoing()
if (outgoing && outgoing.length > 0) {
this.socket?.send(outgoing)
didWork = true
}
while (true) {
const event = this.receiver.poll()
if (!event) break
const e = event as any
console.log('WASM Event:', e)
didWork = true
if (e.type === 'file_start') {
this.term?.writeln(`\r\nZMODEM: Receiving ${e.name} (${e.size} bytes)...`)
this.currentFile = { name: e.name, size: e.size, data: [] }
} else if (e.type === 'file_complete') {
this.term?.writeln('\r\nZMODEM: File complete.')
this.saveFile()
} else if (e.type === 'session_complete') {
this.term?.writeln('\r\nZMODEM: Session complete.')
this.receiver = null
this.currentFile = null
return true
}
}
const chunk = this.receiver.drain_file()
if (chunk && chunk.length > 0) {
if (this.currentFile) {
this.currentFile.data.push(chunk)
didWork = true
}
}
} catch (e) {
console.error('Receiver error:', e)
this.term?.writeln('\r\nZMODEM: Error ' + e)
this.receiver = null
}
return didWork
}
saveFile() {
if (!this.currentFile) return
const blob = new Blob(this.currentFile.data as any, { type: 'application/octet-stream' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = this.currentFile.name
a.click()
URL.revokeObjectURL(url)
this.currentFile = null
}
}
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/App.tsx
|
TypeScript (TSX)
|
import React, { useEffect, useRef } from 'react'
import { Terminal } from '@xterm/xterm'
import { WebLinksAddon } from '@xterm/addon-web-links'
import '@xterm/xterm/css/xterm.css'
import AddonZmodem from './zmodem/addon'
import { createOfferHandler } from './zmodem/offer'
import { sendFiles } from './zmodem/send'
const App: React.FC = () => {
const terminalRef = useRef<HTMLDivElement | null>(null)
const terminal = useRef<Terminal | null>(null)
const ws = useRef<WebSocket | null>(null)
const zmodemAddon = useRef<AddonZmodem | null>(null)
const sendLog = (msg: string) => {
// write locally to terminal so user sees progress immediately
(terminal.current != null) && (terminal.current as any).writeln && (terminal.current as any).writeln(`[zmodem] ${msg}`)
if ((ws.current != null) && ws.current.readyState === WebSocket.OPEN) {
ws.current.send(JSON.stringify({ type: 'log', message: msg }))
}
}
useEffect(() => {
if (terminalRef.current == null) return
const term = new Terminal()
terminal.current = term
term.loadAddon(new WebLinksAddon())
const addon = new AddonZmodem()
zmodemAddon.current = addon
term.loadAddon(addon as any)
term.open(terminalRef.current)
const websocket = new WebSocket('ws://localhost:8081/terminal')
ws.current = websocket
websocket.onopen = () => {
console.log('WebSocket connected')
term.writeln('Connected to server')
}
websocket.onmessage = (event) => {
if (typeof event.data === 'string') {
// text messages include server/log messages and normal shell output
term.write(event.data)
} else {
console.log('WebSocket message received (binary)')
addon.zsentry?.consume(event.data)
}
}
websocket.onclose = (event) => {
console.log('WebSocket closed:', event.code, event.reason)
term.writeln(`\r\nConnection closed: ${event.code} ${event.reason}`)
}
websocket.onerror = (error) => {
console.error('WebSocket error:', error)
term.writeln('\r\nWebSocket error occurred')
}
// We rely on zmodem-ts to detect rz/sz and provide offer metadata.
// Just forward terminal input to the backend; zmodem handlers will
// prompt file pickers / saves when appropriate via offers.
term.onData((data) => {
websocket.send(data)
})
addon.zmodemAttach({
socket: websocket,
term,
onZmodem: true,
onzmodemRetract: () => {
console.log('zmodem retract')
sendLog('zmodem retract')
},
onZmodemDetect: (detection: any) => {
console.log('zmodem detect', detection)
// Avoid dumping the full detection object to the terminal; log only session type
const detType = (detection && (detection._session_type || detection.type || (detection.sess && detection.sess.type))) || 'unknown'
sendLog(`zmodem detect: ${detType}`)
const zsession = detection.confirm()
if (zsession && zsession.type === 'receive') {
// remote will send files to us; offer handler will prompt save
zsession.on('offer', createOfferHandler({ current: null }, sendLog, () => (zmodemAddon.current != null) && (zmodemAddon.current as any).resetSentry && (zmodemAddon.current as any).resetSentry()))
// start the receive session (do not await) - offer handler manages each file
zsession.start()
} else if (zsession) {
// we should send files to remote; sendFiles will prompt picker
;(async () => {
await sendFiles(zsession, { current: null }, sendLog)
})()
}
},
onOffer: createOfferHandler({ current: null }, sendLog, () => (zmodemAddon.current != null) && (zmodemAddon.current as any).resetSentry && (zmodemAddon.current as any).resetSentry())
})
return () => {
websocket.close()
term.dispose()
addon.dispose()
}
}, [])
return (
<div>
<h1>Zmodem Terminal</h1>
<div ref={terminalRef} style={{ width: '100%', height: '400px' }} />
</div>
)
}
export default App
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/index.html
|
HTML
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zmodem Terminal</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/main.tsx
|
TypeScript (TSX)
|
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
const root = ReactDOM.createRoot(document.getElementById('root')!)
root.render(<App />)
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/zmodem/addon.ts
|
TypeScript
|
import Zmodem from 'zmodem-ts'
import type { Terminal } from '@xterm/xterm'
const {
Sentry
} = Zmodem
export default class AddonZmodem {
_disposables: any[] = []
socket: WebSocket | null = null
term: Terminal | null = null
ctx: any = null
zsentry: any = null
activate (terminal: Terminal) {
(terminal as any).zmodemAttach = this.zmodemAttach.bind(this)
}
sendWebSocket = (octets: number[]) => {
if ((this.socket != null) && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(new Uint8Array(octets))
} else {
console.error('WebSocket is not open')
}
}
zmodemAttach = (ctx: any) => {
this.socket = ctx.socket
this.term = ctx.term
this.ctx = ctx
this.createSentry()
this.socket.binaryType = 'arraybuffer'
// Offer events are emitted on the confirmed zsession; handlers should
// attach to the `zsession` returned by detection.confirm(). Do not
// attempt to call `.on('offer')` on the sentry object (it has no such API).
}
createSentry () {
const ctx = this.ctx || {}
this.zsentry = new Sentry({
to_terminal: (octets: number[]) => {
if (ctx.onZmodem) {
try {
(this.term != null) && this.term.write(String.fromCharCode.apply(String, octets as any))
} catch (e) {
console.error('to_terminal write failed', e)
}
}
},
sender: this.sendWebSocket,
on_retract: ctx.onzmodemRetract,
on_detect: ctx.onZmodemDetect
})
// Offer events are provided by the confirmed zsession returned from
// `detection.confirm()`. Do not attempt to call `.on('offer')` on the
// sentry itself — it does not expose that API.
}
// Recreate the internal zsentry to recover from protocol errors
resetSentry () {
try {
if (this.zsentry && (this.zsentry).dispose) {
try { (this.zsentry).dispose() } catch (e) {}
}
} catch (e) {}
this.createSentry()
}
dispose () {
this._disposables.forEach((d: any) => d.dispose && d.dispose())
this._disposables = []
this.socket = null
this.term = null
this.ctx = null
this.zsentry = null
}
}
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/zmodem/offer.ts
|
TypeScript
|
export function createOfferHandler (pendingSaveRef: { current: any }, sendLog: (msg: string) => void, onCompleteReset?: () => void) {
return async function onOffer (xfer: any) {
console.log('zmodem offer received', xfer)
// Prefer the details provided by the Offer interface
const details = (typeof xfer.get_details === 'function') ? xfer.get_details() : (xfer.file_info || {})
const offeredName = details && details.name ? details.name : (xfer.name || xfer.file_name || 'download.bin')
const offeredSize = details && details.size ? details.size : null
sendLog(`zmodem offer: ${offeredName}${offeredSize ? ` (${offeredSize} bytes)` : ''}`)
let writable: any = null
let chunks: Uint8Array[] = []
let saveDesc = ''
if ((pendingSaveRef as any).current) {
const p = (pendingSaveRef as any).current
writable = p.writable || null
if (p.chunks) chunks = p.chunks
saveDesc = p.name || offeredName;
(pendingSaveRef as any).current = null
} else {
const useFileSystem = typeof (window as any).showSaveFilePicker === 'function'
if (useFileSystem) {
try {
const handle = await (window as any).showSaveFilePicker({ suggestedName: offeredName })
writable = await handle.createWritable()
saveDesc = `File picker (name: ${offeredName})`
} catch (err) {
console.error('Save file picker cancelled', err)
sendLog('Save file picker cancelled')
xfer.reject && xfer.reject()
return
}
} else {
saveDesc = `Browser download (name: ${offeredName})`
}
}
sendLog(`Receiving ${offeredName}... saving to: ${saveDesc}`)
xfer.on && xfer.on('input', async (payload: Uint8Array) => {
try {
if (writable) {
await writable.write(new Uint8Array(payload))
} else {
chunks.push(new Uint8Array(payload))
}
} catch (e) {
console.error('Error writing chunk', e)
sendLog(`Error writing chunk: ${e}`)
}
})
try {
// Accept will resolve when the transfer completes (and returns spooled data if used)
const result = await xfer.accept()
if (writable) {
try { await writable.close() } catch (e) { console.warn('close writable failed', e) }
sendLog(`File received: ${offeredName} -> ${saveDesc}`)
} else {
const blob = new Blob(chunks)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = offeredName
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
sendLog(`File received: ${offeredName} -> downloaded as ${offeredName}`)
}
console.log('zmodem transfer finished', offeredName, result)
sendLog(`zmodem transfer finished: ${offeredName}`)
// Give sentry a moment to process any trailing protocol bytes,
// then optionally reset it to recover from protocol edge-cases
// (OSC sequences arriving right after ZFIN can leave sentry in
// a state where it expects OO; rebuilding the sentry returns
// the terminal to normal operation).
try {
if (onCompleteReset != null) {
setTimeout(() => {
try { onCompleteReset() } catch (e) { console.error('onCompleteReset failed', e) }
}, 50)
}
} catch (e) {}
} catch (err) {
console.error('zmodem accept failed', err)
sendLog(`zmodem accept failed: ${err}`)
}
}
}
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/client/zmodem/send.ts
|
TypeScript
|
export async function sendFiles (zsession: any, pendingUploadRef: { current: any }, sendLog: (msg: string) => void) {
// Confirm zsession if detection passed the raw detection here callers should pass confirmed session
const filesToSend: File[] = []
if (pendingUploadRef.current && pendingUploadRef.current.uploadFile) {
filesToSend.push(pendingUploadRef.current.uploadFile)
pendingUploadRef.current = null
} else {
try {
const picks = await (window as any).showOpenFilePicker()
for (const h of picks) {
const f = await h.getFile()
filesToSend.push(f)
}
} catch (e) {
sendLog('Open file picker cancelled')
return
}
}
if (filesToSend.length === 0) return
sendLog(`Starting zmodem send for ${filesToSend.length} file(s)`)
let filesRemaining = filesToSend.length
let sizeRemaining = filesToSend.reduce((a, b) => a + (b.size || 0), 0)
const CHUNK = 64 * 1024 // 64KB chunks
for (const file of filesToSend) {
const offer = {
obj: file,
name: file.name,
size: file.size,
files_remaining: filesRemaining,
bytes_remaining: sizeRemaining
}
let xfer: any
try {
sendLog(`Sending file: ${file.name} (${file.size} bytes)`)
xfer = await zsession.send_offer(offer)
} catch (err) {
console.error('send_offer failed', err)
sendLog(`send_offer failed: ${err}`)
return
}
if (!xfer) {
sendLog('Transfer cancelled or not available')
return
}
// stream file by slicing
let offset = 0
while (offset < file.size) {
const end = Math.min(offset + CHUNK, file.size)
const slice = file.slice(offset, end)
const buf = new Uint8Array(await slice.arrayBuffer())
try {
await xfer.send(buf)
} catch (err) {
console.error('xfer.send failed', err)
sendLog(`xfer.send failed: ${err}`)
try { await xfer.end() } catch (e) {}
return
}
offset = end
}
try {
await xfer.end()
} catch (err) {
console.error('xfer.end failed', err)
sendLog(`xfer.end failed: ${err}`)
return
}
filesRemaining -= 1
sizeRemaining -= file.size || 0
sendLog(`Finished sending ${file.name} (${file.size} bytes)`)
}
try {
if (zsession && zsession.close) {
await zsession.close().catch(() => {})
}
} catch (e) {}
}
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/dockers/build.sh
|
Shell
|
#!/bin/bash
# Build the Docker image for the ZMODEM test server
docker-compose build
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/dockers/run.sh
|
Shell
|
#!/bin/bash
# Run the ZMODEM test server in the background
docker-compose up -d
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/lib.rs
|
Rust
|
use wasm_bindgen::prelude::*;
use zmodem2::{Receiver, ReceiverEvent, Sender, SenderEvent};
#[wasm_bindgen]
pub struct WasmReceiver {
inner: Receiver,
}
#[wasm_bindgen]
impl WasmReceiver {
#[wasm_bindgen(constructor)]
pub fn new() -> Result<WasmReceiver, JsValue> {
let inner = Receiver::new().map_err(|e| JsValue::from_str(&format!("{:?}", e)))?;
Ok(WasmReceiver { inner })
}
pub fn feed(&mut self, data: &[u8]) -> Result<usize, JsValue> {
self.inner.feed_incoming(data).map_err(|e| JsValue::from_str(&format!("{:?}", e)))
}
pub fn drain_outgoing(&mut self) -> Vec<u8> {
let data = self.inner.drain_outgoing().to_vec();
self.inner.advance_outgoing(data.len());
data
}
pub fn drain_file(&mut self) -> Result<Vec<u8>, JsValue> {
let data = self.inner.drain_file().to_vec();
self.inner.advance_file(data.len()).map_err(|e| JsValue::from_str(&format!("{:?}", e)))?;
Ok(data)
}
pub fn poll(&mut self) -> JsValue {
match self.inner.poll_event() {
Some(ReceiverEvent::FileStart) => {
let name = String::from_utf8_lossy(self.inner.file_name()).to_string();
let size = self.inner.file_size();
let obj = js_sys::Object::new();
let _ = js_sys::Reflect::set(&obj, &"type".into(), &"file_start".into());
let _ = js_sys::Reflect::set(&obj, &"name".into(), &name.into());
let _ = js_sys::Reflect::set(&obj, &"size".into(), &size.into());
obj.into()
},
Some(ReceiverEvent::FileComplete) => {
let obj = js_sys::Object::new();
let _ = js_sys::Reflect::set(&obj, &"type".into(), &"file_complete".into());
obj.into()
},
Some(ReceiverEvent::SessionComplete) => {
let obj = js_sys::Object::new();
let _ = js_sys::Reflect::set(&obj, &"type".into(), &"session_complete".into());
obj.into()
},
None => JsValue::NULL
}
}
}
#[wasm_bindgen]
pub struct WasmSender {
inner: Sender,
}
#[wasm_bindgen]
impl WasmSender {
#[wasm_bindgen(constructor)]
pub fn new() -> Result<WasmSender, JsValue> {
let inner = Sender::new().map_err(|e| JsValue::from_str(&format!("{:?}", e)))?;
Ok(WasmSender { inner })
}
pub fn start_file(&mut self, file_name: &str, file_size: u32) -> Result<(), JsValue> {
self.inner.start_file(file_name.as_bytes(), file_size).map_err(|e| JsValue::from_str(&format!("{:?}", e)))
}
pub fn finish_session(&mut self) -> Result<(), JsValue> {
self.inner.finish_session().map_err(|e| JsValue::from_str(&format!("{:?}", e)))
}
pub fn feed(&mut self, data: &[u8]) -> Result<usize, JsValue> {
self.inner.feed_incoming(data).map_err(|e| JsValue::from_str(&format!("{:?}", e)))
}
pub fn drain_outgoing(&mut self) -> Vec<u8> {
let data = self.inner.drain_outgoing().to_vec();
self.inner.advance_outgoing(data.len());
data
}
pub fn feed_file(&mut self, data: &[u8]) -> Result<(), JsValue> {
self.inner.feed_file(data).map_err(|e| JsValue::from_str(&format!("{:?}", e)))
}
pub fn poll(&mut self) -> JsValue {
// Check events first
if let Some(event) = self.inner.poll_event() {
match event {
SenderEvent::FileComplete => {
let obj = js_sys::Object::new();
let _ = js_sys::Reflect::set(&obj, &"type".into(), &"file_complete".into());
return obj.into();
},
SenderEvent::SessionComplete => {
let obj = js_sys::Object::new();
let _ = js_sys::Reflect::set(&obj, &"type".into(), &"session_complete".into());
return obj.into();
}
}
}
// Check file request
if let Some(req) = self.inner.poll_file() {
let obj = js_sys::Object::new();
let _ = js_sys::Reflect::set(&obj, &"type".into(), &"need_file_data".into());
let _ = js_sys::Reflect::set(&obj, &"offset".into(), &req.offset.into());
let _ = js_sys::Reflect::set(&obj, &"length".into(), &(req.len as u32).into());
return obj.into();
}
JsValue::NULL
}
}
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
src/server/index.ts
|
TypeScript
|
import express from 'express'
import expressWs from 'express-ws'
import { Client } from 'ssh2'
import WebSocket from 'ws'
const app = express()
expressWs(app)
const SSH_HOST = 'localhost'
const SSH_PORT = 23355
const SSH_USER = 'zxd'
const SSH_PASS = 'zxd'
// Test SSH connection on startup
console.log('Testing SSH connection...')
const testSsh = new Client()
testSsh.on('ready', () => {
console.log('SSH test connection successful')
testSsh.end()
})
testSsh.on('error', (err) => {
console.error('SSH test connection failed:', err)
})
testSsh.connect({
host: SSH_HOST,
port: SSH_PORT,
username: SSH_USER,
password: SSH_PASS
})
app.ws('/terminal', (ws: WebSocket, req) => {
console.log('WebSocket connection established from:', req.connection.remoteAddress)
console.log('Upgrade request url:', req.url)
console.log('Upgrade request headers:', JSON.stringify(req.headers))
const ssh = new Client()
ssh.on('ready', () => {
console.log('SSH connection ready')
ssh.shell({
term: 'xterm-256color',
cols: 80,
rows: 24
}, (err, stream) => {
if (err) {
console.error('SSH shell error:', err)
ws.send(`SSH shell failed: ${err.message}`)
ws.close(1011, 'SSH shell failed')
ssh.end()
return
}
console.log('SSH shell opened')
ws.on('message', (data: Buffer) => {
const msgStr = data.toString()
try {
const parsed = JSON.parse(msgStr)
if (parsed.type === 'log') {
// Log on server only. The frontend will write logs to the terminal locally
console.log('CLIENT LOG:', parsed.message)
return
}
} catch {}
console.log('WebSocket message received, length:', data.length)
// Send all data as binary to SSH stream
stream.write(data)
})
stream.on('data', (data: Buffer) => {
console.log('SSH data received, length:', data.length)
ws.send(data)
})
stream.on('close', () => {
console.log('SSH stream closed')
ssh.end()
ws.close()
})
stream.on('error', (err) => {
console.error('SSH stream error:', err)
})
})
})
ssh.on('error', (err) => {
console.error('SSH connection error:', err)
ws.send(`SSH connection failed: ${err.message}`)
ws.close(1011, 'SSH connection failed') // 1011 = Internal Error
})
ssh.connect({
host: SSH_HOST,
port: SSH_PORT,
username: SSH_USER,
password: SSH_PASS
})
ws.on('close', () => {
console.log('WebSocket closed')
ssh.end()
})
ws.on('error', (err) => {
console.error('WebSocket error:', err)
})
})
app.listen(8081, () => {
console.log('Server running on port 8081')
})
|
zxdong262/zmodem2-wasm
| 0
|
Compile zmodem2 crate to wasm
|
TypeScript
|
zxdong262
|
ZHAO Xudong
| |
examples/audio/main.js
|
JavaScript
|
// Audio example
// Uses CC0 sounds from Kenney.nl
joy.window.setMode(800, 600);
joy.window.setTitle("Audio Demo");
joy.graphics.setBackgroundColor(0.1, 0.1, 0.2);
var sound = null;
var music = null;
var musicStarted = false;
joy.load = function() {
console.log("=== Audio Demo ===");
console.log("Press 1 to play sound effect");
console.log("Press 2 to play/pause music");
console.log("Press UP/DOWN to adjust music volume");
console.log("Press Escape to exit");
console.log("");
// Load sound effect (static - fully loaded into memory)
if (joy.filesystem.getInfo("sound.ogg")) {
sound = joy.audio.newSource("sound.ogg", "static");
console.log("Loaded sound.ogg");
} else {
console.log("No sound.ogg found");
}
// Load music (stream - streamed from disk)
if (joy.filesystem.getInfo("music.ogg")) {
music = joy.audio.newSource("music.ogg", "stream");
music.setLooping(true);
music.setVolume(0.5);
console.log("Loaded music.ogg");
} else {
console.log("No music.ogg found");
}
};
joy.keypressed = function(key, scancode, isrepeat) {
// Play sound effect
if (key === "1" && sound) {
sound.play();
console.log("Playing sound");
}
// Toggle music
if (key === "2" && music) {
if (music.isPlaying()) {
music.pause();
console.log("Music paused");
} else if (!musicStarted) {
music.play();
musicStarted = true;
console.log("Music started");
} else {
music.resume();
console.log("Music resumed");
}
}
// Adjust volume
if (music) {
var vol = music.getVolume();
if (key === "up") {
vol = Math.min(1.0, vol + 0.1);
music.setVolume(vol);
console.log("Music volume:", vol.toFixed(1));
}
if (key === "down") {
vol = Math.max(0.0, vol - 0.1);
music.setVolume(vol);
console.log("Music volume:", vol.toFixed(1));
}
}
if (key === "escape") {
joy.window.close();
}
};
joy.update = function(dt) {
};
joy.draw = function() {
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Audio Demo", 50, 50);
joy.graphics.print("1 - Play sound effect", 50, 100);
joy.graphics.print("2 - Play/pause music", 50, 130);
joy.graphics.print("UP/DOWN - Adjust music volume", 50, 160);
if (music) {
var vol = music.getVolume();
var playing = music.isPlaying();
joy.graphics.print("Music: " + (playing ? "Playing" : "Paused") + " | Music volume: " + vol.toFixed(1), 50, 220);
if (playing) {
var time = music.tell();
var duration = music.getDuration();
joy.graphics.print("Time: " + time.toFixed(1) + "s / " + duration.toFixed(1) + "s", 50, 250);
}
}
joy.graphics.setColor(0.5, 0.5, 0.5);
joy.graphics.print("Press Escape to exit", 50, 550);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/audio/sound.js
|
JavaScript
|
// Sound module example
// Demonstrates SoundData and Decoder APIs
joy.window.setMode(800, 600);
joy.window.setTitle("Sound Module Demo");
joy.graphics.setBackgroundColor(0.1, 0.15, 0.2);
var soundData = null;
var decoder = null;
var source = null;
var proceduralSource = null;
var proceduralData = null;
joy.load = function() {
console.log("=== Sound Module Demo ===");
console.log("Press 1 to play music from SoundData");
console.log("Press 2 to play procedural sine wave");
console.log("Press 3 to create decoder and show info");
console.log("Press SPACE to stop all sounds");
console.log("Press Escape to exit");
console.log("");
// Load music into SoundData (fully decoded into memory)
if (joy.filesystem.getInfo("music.ogg")) {
soundData = joy.sound.newSoundData("music.ogg");
console.log("Loaded music.ogg into SoundData:");
console.log(" Sample rate:", soundData.getSampleRate());
console.log(" Channels:", soundData.getChannelCount());
console.log(" Bit depth:", soundData.getBitDepth());
console.log(" Duration:", soundData.getDuration().toFixed(2) + "s");
console.log(" Sample count:", soundData.getSampleCount());
}
// Create procedural audio - a 440Hz sine wave (1 second)
var sampleRate = 44100;
var duration = 1.0;
var frequency = 440;
var samples = Math.floor(sampleRate * duration);
proceduralData = joy.sound.newSoundData(samples, sampleRate, 16, 2);
for (var i = 0; i < samples; i++) {
var t = i / sampleRate;
// Sine wave with fade in/out envelope
var envelope = Math.min(1, t * 10) * Math.min(1, (duration - t) * 10);
var sample = Math.sin(2 * Math.PI * frequency * t) * 0.5 * envelope;
proceduralData.setSample(i, 0, sample); // Left channel
proceduralData.setSample(i, 1, sample); // Right channel
}
console.log("Created procedural 440Hz sine wave");
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "1" && soundData) {
// Create source from SoundData and play
if (source) source.stop();
source = joy.audio.newSource(soundData);
source.setVolume(0.5);
source.play();
console.log("Playing music from SoundData");
}
if (key === "2" && proceduralData) {
// Play procedural audio
if (proceduralSource) proceduralSource.stop();
proceduralSource = joy.audio.newSource(proceduralData);
proceduralSource.play();
console.log("Playing procedural sine wave");
}
if (key === "3") {
// Create decoder and show info
if (joy.filesystem.getInfo("music.ogg")) {
decoder = joy.sound.newDecoder("music.ogg", 4096);
console.log("Created Decoder:");
console.log(" Sample rate:", decoder.getSampleRate());
console.log(" Channels:", decoder.getChannelCount());
console.log(" Bit depth:", decoder.getBitDepth());
console.log(" Duration:", decoder.getDuration().toFixed(2) + "s");
// Decode first chunk
var chunk = decoder.decode();
if (chunk) {
console.log(" First chunk samples:", chunk.getSampleCount());
}
}
}
if (key === "space") {
if (source) source.stop();
if (proceduralSource) proceduralSource.stop();
console.log("Stopped all sounds");
}
if (key === "escape") {
joy.window.close();
}
};
joy.update = function(dt) {
};
joy.draw = function() {
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Sound Module Demo", 50, 50);
joy.graphics.setColor(0.8, 0.8, 0.8);
joy.graphics.print("1 - Play music from SoundData", 50, 100);
joy.graphics.print("2 - Play procedural sine wave (440Hz)", 50, 130);
joy.graphics.print("3 - Create decoder and show info", 50, 160);
joy.graphics.print("SPACE - Stop all sounds", 50, 190);
// Show SoundData info
if (soundData) {
joy.graphics.setColor(0.5, 1, 0.5);
joy.graphics.print("SoundData loaded:", 50, 250);
joy.graphics.print(" " + soundData.getSampleRate() + " Hz, " +
soundData.getChannelCount() + " ch, " +
soundData.getDuration().toFixed(2) + "s", 50, 280);
}
// Show procedural info
if (proceduralData) {
joy.graphics.setColor(0.5, 0.5, 1);
joy.graphics.print("Procedural SoundData:", 50, 320);
joy.graphics.print(" " + proceduralData.getSampleRate() + " Hz, " +
proceduralData.getChannelCount() + " ch, " +
proceduralData.getDuration().toFixed(2) + "s", 50, 350);
}
// Show decoder info
if (decoder) {
joy.graphics.setColor(1, 0.5, 0.5);
joy.graphics.print("Decoder created:", 50, 390);
joy.graphics.print(" " + decoder.getSampleRate() + " Hz, " +
decoder.getChannelCount() + " ch, " +
decoder.getDuration().toFixed(2) + "s", 50, 420);
}
// Show playback status
joy.graphics.setColor(1, 1, 0);
var status = "";
if (source && source.isPlaying()) {
status = "Playing: music (" + source.tell().toFixed(1) + "s)";
} else if (proceduralSource && proceduralSource.isPlaying()) {
status = "Playing: sine wave";
} else {
status = "Stopped";
}
joy.graphics.print("Status: " + status, 50, 480);
joy.graphics.setColor(0.5, 0.5, 0.5);
joy.graphics.print("Press Escape to exit", 50, 550);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/audio/spatial.js
|
JavaScript
|
// Advanced Audio Example - 3D Spatial Audio Demo
// Demonstrates: 3D positioning, listener control, doppler, filters, cloning
joy.window.setMode(900, 700);
joy.window.setTitle("3D Spatial Audio Demo");
joy.graphics.setBackgroundColor(0.05, 0.08, 0.12);
// Audio sources
var footstep = null;
var ambientMusic = null;
// 3D scene state
var listenerX = 0;
var listenerY = 0;
var listenerAngle = 0; // Facing direction in radians
// Moving sound source (circles around the listener)
var sourceAngle = 0;
var sourceDistance = 5;
var sourceHeight = 0;
var sourceSpeed = 1.0; // Radians per second
var autoRotate = true;
// Filter state
var filterEnabled = false;
var filterType = "lowpass";
var filterVolume = 1.0;
var filterHighGain = 0.3;
// Clone demo
var clones = [];
var lastCloneTime = 0;
// Stats
var activeCount = 0;
joy.load = function() {
console.log("=== 3D Spatial Audio Demo ===");
console.log("");
console.log("Controls:");
console.log(" WASD - Move listener position");
console.log(" Q/E - Rotate listener left/right");
console.log(" SPACE - Play footstep at source position");
console.log(" 1 - Toggle auto-rotation of sound source");
console.log(" 2 - Play/pause background music");
console.log(" 3 - Toggle low-pass filter on music");
console.log(" 4 - Spawn cloned footstep at random position");
console.log(" UP/DOWN - Adjust source distance");
console.log(" LEFT/RIGHT - Manually rotate source");
console.log(" +/- - Adjust master volume");
console.log(" R - Reset positions");
console.log(" ESC - Exit");
console.log("");
// Load footstep as spatial (mono) source
if (joy.filesystem.getInfo("footstep_mono.ogg")) {
// Pass "spatial" or true as second argument to enable 3D audio
footstep = joy.audio.newSource("footstep_mono.ogg", "spatial");
if (footstep) {
footstep.setVolume(0.8);
footstep.setAttenuationDistances(1, 20); // Audible from 1-20 units
footstep.setRolloff(1.5);
console.log("Loaded footstep_mono.ogg (channels: " + footstep.getChannelCount() + ")");
if (footstep.getChannelCount() !== 1) {
console.log("WARNING: footstep.ogg is not mono - 3D positioning won't work!");
}
}
} else {
console.log("footstep_mono.ogg not found");
}
// Load music (non-spatial, stereo is fine)
if (joy.filesystem.getInfo("music.ogg")) {
ambientMusic = joy.audio.newSource("music.ogg", "static");
if (ambientMusic) {
ambientMusic.setLooping(true);
ambientMusic.setVolume(0.3);
console.log("Loaded music.ogg");
}
}
// Set initial listener orientation (facing forward along -Z)
updateListener();
};
function updateListener() {
// Set listener position
joy.audio.setPosition(listenerX, 0, listenerY);
// Set listener orientation based on angle
// Forward vector
var fx = Math.sin(listenerAngle);
var fy = 0;
var fz = -Math.cos(listenerAngle);
// Up vector (always Y-up)
var ux = 0;
var uy = 1;
var uz = 0;
joy.audio.setOrientation(fx, fy, fz, ux, uy, uz);
}
function updateSourcePosition() {
if (!footstep) return;
// Calculate source position orbiting around listener
var sx = listenerX + Math.cos(sourceAngle) * sourceDistance;
var sy = sourceHeight;
var sz = listenerY + Math.sin(sourceAngle) * sourceDistance;
footstep.setPosition(sx, sy, sz);
// Set velocity for doppler effect (tangent to circle)
if (autoRotate) {
var speed = sourceSpeed * sourceDistance;
var vx = -Math.sin(sourceAngle) * speed;
var vz = Math.cos(sourceAngle) * speed;
footstep.setVelocity(vx, 0, vz);
} else {
footstep.setVelocity(0, 0, 0);
}
}
function playFootstepAtPosition(x, y, z) {
if (!footstep) return;
footstep.setPosition(x, y, z);
footstep.play();
}
function spawnClone() {
if (!footstep) return;
// Clone the footstep source
var clone = footstep.clone();
if (!clone) return;
// Random position around the listener
var angle = Math.random() * Math.PI * 2;
var dist = 2 + Math.random() * 8;
var x = listenerX + Math.cos(angle) * dist;
var z = listenerY + Math.sin(angle) * dist;
clone.setPosition(x, 0, z);
clone.setVolume(0.5 + Math.random() * 0.5);
clone.setPitch(0.8 + Math.random() * 0.4);
clone.play();
clones.push({
source: clone,
x: x,
z: z,
time: 0
});
console.log("Spawned clone at (" + x.toFixed(1) + ", " + z.toFixed(1) + ")");
}
function updateFilter() {
if (!ambientMusic) return;
if (filterEnabled) {
ambientMusic.setFilter({
type: filterType,
volume: filterVolume,
highgain: filterHighGain,
lowgain: 1.0
});
} else {
ambientMusic.setFilter(null);
}
}
joy.update = function(dt) {
// Movement speed
var moveSpeed = 5 * dt;
var rotSpeed = 2 * dt;
// Listener movement (WASD relative to facing direction)
if (joy.keyboard.isDown("w")) {
listenerX += Math.sin(listenerAngle) * moveSpeed;
listenerY -= Math.cos(listenerAngle) * moveSpeed;
}
if (joy.keyboard.isDown("s")) {
listenerX -= Math.sin(listenerAngle) * moveSpeed;
listenerY += Math.cos(listenerAngle) * moveSpeed;
}
if (joy.keyboard.isDown("a")) {
listenerX -= Math.cos(listenerAngle) * moveSpeed;
listenerY -= Math.sin(listenerAngle) * moveSpeed;
}
if (joy.keyboard.isDown("d")) {
listenerX += Math.cos(listenerAngle) * moveSpeed;
listenerY += Math.sin(listenerAngle) * moveSpeed;
}
// Listener rotation
if (joy.keyboard.isDown("q")) {
listenerAngle -= rotSpeed;
}
if (joy.keyboard.isDown("e")) {
listenerAngle += rotSpeed;
}
// Manual source rotation
if (joy.keyboard.isDown("left")) {
sourceAngle -= rotSpeed;
}
if (joy.keyboard.isDown("right")) {
sourceAngle += rotSpeed;
}
// Auto-rotate source
if (autoRotate) {
sourceAngle += sourceSpeed * dt;
}
// Update positions
updateListener();
updateSourcePosition();
// Update clones (remove finished ones)
for (var i = clones.length - 1; i >= 0; i--) {
clones[i].time += dt;
if (!clones[i].source.isPlaying() && clones[i].time > 0.1) {
clones.splice(i, 1);
}
}
// Update stats
activeCount = joy.audio.getActiveSourceCount();
};
joy.keypressed = function(key, scancode, isrepeat) {
if (isrepeat) return;
if (key === "space" && footstep) {
// Play footstep at current source position
footstep.play();
console.log("Playing footstep");
}
if (key === "1") {
autoRotate = !autoRotate;
console.log("Auto-rotate: " + (autoRotate ? "ON" : "OFF"));
}
if (key === "2" && ambientMusic) {
if (ambientMusic.isPlaying()) {
ambientMusic.pause();
console.log("Music paused");
} else {
ambientMusic.play();
console.log("Music playing");
}
}
if (key === "3" && ambientMusic) {
filterEnabled = !filterEnabled;
updateFilter();
console.log("Filter: " + (filterEnabled ? "ON (lowpass)" : "OFF"));
}
if (key === "4") {
spawnClone();
}
if (key === "up") {
sourceDistance = Math.min(15, sourceDistance + 1);
console.log("Source distance: " + sourceDistance);
}
if (key === "down") {
sourceDistance = Math.max(1, sourceDistance - 1);
console.log("Source distance: " + sourceDistance);
}
if (key === "=" || key === "+") {
var vol = Math.min(1.0, joy.audio.getVolume() + 0.1);
joy.audio.setVolume(vol);
console.log("Master volume: " + vol.toFixed(1));
}
if (key === "-") {
var vol = Math.max(0.0, joy.audio.getVolume() - 0.1);
joy.audio.setVolume(vol);
console.log("Master volume: " + vol.toFixed(1));
}
if (key === "r") {
listenerX = 0;
listenerY = 0;
listenerAngle = 0;
sourceAngle = 0;
sourceDistance = 5;
updateListener();
console.log("Reset positions");
}
if (key === "escape") {
joy.audio.stop(); // Stop all audio
joy.window.close();
}
};
joy.draw = function() {
var width = joy.graphics.getWidth();
var height = joy.graphics.getHeight();
// Title
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("3D Spatial Audio Demo", 20, 20);
// Draw top-down view of the 3D scene
var viewX = width / 2;
var viewY = height / 2 - 50;
var scale = 25; // Pixels per unit
// Grid
joy.graphics.setColor(0.15, 0.2, 0.25);
for (var gx = -10; gx <= 10; gx++) {
var screenX = viewX + gx * scale;
joy.graphics.line(screenX, viewY - 10 * scale, screenX, viewY + 10 * scale);
}
for (var gy = -10; gy <= 10; gy++) {
var screenY = viewY + gy * scale;
joy.graphics.line(viewX - 10 * scale, screenY, viewX + 10 * scale, screenY);
}
// Draw listener (triangle showing direction)
var lScreenX = viewX + listenerX * scale;
var lScreenY = viewY + listenerY * scale;
joy.graphics.setColor(0.2, 0.8, 0.4);
joy.graphics.circle("fill", lScreenX, lScreenY, 12);
// Direction indicator
var dirLen = 20;
var dirX = lScreenX + Math.sin(listenerAngle) * dirLen;
var dirY = lScreenY - Math.cos(listenerAngle) * dirLen;
joy.graphics.setColor(0.4, 1.0, 0.6);
joy.graphics.line(lScreenX, lScreenY, dirX, dirY);
// Draw sound source position
if (footstep) {
var pos = footstep.getPosition();
var sScreenX = viewX + pos[0] * scale;
var sScreenY = viewY + pos[2] * scale;
// Orbit path
joy.graphics.setColor(0.3, 0.3, 0.5);
joy.graphics.circle("line", lScreenX, lScreenY, sourceDistance * scale);
// Source
var pulseSize = footstep.isPlaying() ? 14 + Math.sin(joy.timer.getTime() * 10) * 4 : 10;
joy.graphics.setColor(1.0, 0.4, 0.3);
joy.graphics.circle("fill", sScreenX, sScreenY, pulseSize);
// Velocity indicator
if (autoRotate) {
var vel = footstep.getVelocity();
joy.graphics.setColor(1.0, 0.6, 0.4);
joy.graphics.line(sScreenX, sScreenY, sScreenX + vel[0] * 5, sScreenY + vel[2] * 5);
}
}
// Draw clones
joy.graphics.setColor(0.6, 0.4, 1.0);
for (var i = 0; i < clones.length; i++) {
var cx = viewX + clones[i].x * scale;
var cy = viewY + clones[i].z * scale;
var size = clones[i].source.isPlaying() ? 8 : 5;
joy.graphics.circle("fill", cx, cy, size);
}
// Legend
var legendY = height - 180;
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Legend:", 20, legendY);
joy.graphics.setColor(0.2, 0.8, 0.4);
joy.graphics.circle("fill", 30, legendY + 25, 8);
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Listener (you)", 50, legendY + 18);
joy.graphics.setColor(1.0, 0.4, 0.3);
joy.graphics.circle("fill", 30, legendY + 50, 8);
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Sound source (footstep)", 50, legendY + 43);
joy.graphics.setColor(0.6, 0.4, 1.0);
joy.graphics.circle("fill", 30, legendY + 75, 6);
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Cloned sounds", 50, legendY + 68);
// Controls
var ctrlX = width - 280;
joy.graphics.setColor(0.5, 0.5, 0.5);
joy.graphics.print("Controls:", ctrlX, 20);
joy.graphics.setColor(0.4, 0.4, 0.4);
joy.graphics.print("WASD - Move listener", ctrlX, 45);
joy.graphics.print("Q/E - Rotate listener", ctrlX, 65);
joy.graphics.print("SPACE - Play footstep", ctrlX, 85);
joy.graphics.print("1 - Toggle auto-rotate", ctrlX, 105);
joy.graphics.print("2 - Play/pause music", ctrlX, 125);
joy.graphics.print("3 - Toggle filter", ctrlX, 145);
joy.graphics.print("4 - Spawn clone", ctrlX, 165);
joy.graphics.print("UP/DOWN - Source distance", ctrlX, 185);
joy.graphics.print("+/- - Master volume", ctrlX, 205);
joy.graphics.print("R - Reset", ctrlX, 225);
// Status
var statusY = 20;
joy.graphics.setColor(0.6, 0.6, 0.6);
joy.graphics.print("Status:", 20, height - 120);
joy.graphics.setColor(0.8, 0.8, 0.8);
joy.graphics.print("Master Volume: " + (joy.audio.getVolume() * 100).toFixed(0) + "%", 20, height - 95);
joy.graphics.print("Active Sources: " + activeCount, 20, height - 75);
joy.graphics.print("Auto-rotate: " + (autoRotate ? "ON" : "OFF"), 20, height - 55);
joy.graphics.print("Source Distance: " + sourceDistance.toFixed(1), 20, height - 35);
if (ambientMusic) {
var musicStatus = ambientMusic.isPlaying() ? "Playing" : "Paused";
if (filterEnabled) musicStatus += " [Filtered]";
joy.graphics.print("Music: " + musicStatus, 180, height - 95);
}
// Listener position
joy.graphics.setColor(0.5, 0.5, 0.5);
joy.graphics.print("Listener: (" + listenerX.toFixed(1) + ", " + listenerY.toFixed(1) + ")", 180, height - 75);
if (footstep) {
var pos = footstep.getPosition();
joy.graphics.print("Source: (" + pos[0].toFixed(1) + ", " + pos[2].toFixed(1) + ")", 180, height - 55);
}
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/data/main.js
|
JavaScript
|
// Data Module Example
// Demonstrates hashing, encoding, compression, and pack/unpack
joy.window.setMode(800, 600);
joy.window.setTitle("Data Module Demo");
joy.graphics.setBackgroundColor(0.1, 0.1, 0.15);
// State
var testString = "Hello, Joy Engine!";
var log = [];
function addLog(msg) {
console.log(msg);
log.push(msg);
if (log.length > 25) {
log.shift();
}
}
// Convert raw hash bytes to hex string for display
function toHex(rawBytes) {
return joy.data.encode("string", "hex", rawBytes);
}
joy.load = function() {
addLog("=== Data Module Demo ===");
addLog("");
// Demonstrate hashing
addLog("--- Hashing ---");
addLog("Input: \"" + testString + "\"");
var md5 = joy.data.hash("md5", testString);
addLog("MD5: " + toHex(md5));
var sha1 = joy.data.hash("sha1", testString);
addLog("SHA1: " + toHex(sha1));
var sha256 = joy.data.hash("sha256", testString);
addLog("SHA256: " + toHex(sha256));
addLog("");
// Demonstrate encoding
addLog("--- Encoding ---");
var base64 = joy.data.encode("string", "base64", testString);
addLog("Base64: " + base64);
var decoded = joy.data.decode("string", "base64", base64);
addLog("Decoded: \"" + decoded + "\"");
var hex = joy.data.encode("string", "hex", testString);
addLog("Hex: " + hex);
addLog("");
// Demonstrate compression
addLog("--- Compression ---");
var longString = "";
for (var i = 0; i < 100; i++) {
longString += "Hello World! ";
}
addLog("Original size: " + longString.length + " bytes");
var compressed = joy.data.compress("data", "zlib", longString);
addLog("Compressed (zlib): " + compressed.getSize() + " bytes");
var deflated = joy.data.compress("data", "deflate", longString);
addLog("Compressed (deflate): " + deflated.getSize() + " bytes");
// Decompress and verify
var decompressed = joy.data.decompress("string", compressed);
addLog("Decompressed matches: " + (decompressed === longString));
addLog("");
// Demonstrate pack/unpack
addLog("--- Pack/Unpack ---");
var packed = joy.data.pack("string", "<BHI", 255, 1000, 123456);
addLog("Packed <BHI (255, 1000, 123456): " + packed.length + " bytes");
addLog("Packed hex: " + joy.data.encode("string", "hex", packed));
var unpacked = joy.data.unpack("<BHI", packed);
addLog("Unpacked: [" + unpacked[0] + ", " + unpacked[1] + ", " + unpacked[2] + "]");
// Pack a float and double
var floatPacked = joy.data.pack("string", "<fd", 3.14159, 2.71828);
addLog("Packed <fd (pi, e): " + floatPacked.length + " bytes");
var floatUnpacked = joy.data.unpack("<fd", floatPacked);
addLog("Unpacked float: " + floatUnpacked[0].toFixed(5));
addLog("Unpacked double: " + floatUnpacked[1].toFixed(5));
addLog("");
// Demonstrate ByteData
addLog("--- ByteData ---");
var byteData = joy.data.newByteData(testString);
addLog("ByteData size: " + byteData.getSize() + " bytes");
addLog("ByteData content: \"" + byteData.getString() + "\"");
var cloned = byteData.clone();
addLog("Cloned size: " + cloned.getSize() + " bytes");
addLog("");
addLog("=== Demo Complete ===");
};
joy.update = function(dt) {
};
joy.draw = function() {
joy.graphics.clear();
// Log Window
joy.gui.begin("Data Module Log", 10, 10, 780, 540, ["border", "title"]);
for (var i = 0; i < log.length; i++) {
joy.gui.layoutRowDynamic(18, 1);
joy.gui.label(log[i], "left");
}
joy.gui.end();
// Instructions
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Press ESC to exit", 10, 570);
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "escape") {
joy.window.close();
}
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/filesystem/main.js
|
JavaScript
|
// Filesystem example with GUI
// Demonstrates the filesystem API using Nuklear GUI for display
joy.window.setMode(900, 700);
joy.window.setTitle("Filesystem Demo");
joy.graphics.setBackgroundColor(0.1, 0.1, 0.2);
// State
var directoryItems = [];
var currentPath = "/";
var fileContent = "";
var selectedFile = "";
var log = [];
var showWriteWindow = false;
var writeFilename = "test.txt";
var writeContent = "Hello from Joy!";
var identitySet = false;
function addLog(msg) {
console.log(msg);
log.push(msg);
if (log.length > 20) {
log.shift();
}
}
function refreshDirectory() {
directoryItems = [];
var items = joy.filesystem.getDirectoryItems(currentPath);
for (var i = 0; i < items.length; i++) {
var name = items[i];
var fullPath = currentPath === "/" ? name : currentPath + "/" + name;
var info = joy.filesystem.getInfo(fullPath);
if (info) {
directoryItems.push({
name: name,
path: fullPath,
type: info.type,
size: info.size || 0
});
}
}
// Sort: directories first, then files
directoryItems.sort(function(a, b) {
if (a.type === "directory" && b.type !== "directory") return -1;
if (a.type !== "directory" && b.type === "directory") return 1;
return a.name.localeCompare(b.name);
});
}
function loadFile(path) {
var content = joy.filesystem.read(path);
if (content) {
fileContent = content;
selectedFile = path;
addLog("Loaded: " + path + " (" + content.length + " bytes)");
} else {
addLog("Failed to load: " + path);
}
}
joy.load = function() {
addLog("Filesystem Demo started");
addLog("User dir: " + joy.filesystem.getUserDirectory());
addLog("Appdata dir: " + joy.filesystem.getAppdataDirectory());
refreshDirectory();
};
joy.update = function(dt) {
};
joy.draw = function() {
joy.graphics.clear();
// Directory Browser Window
joy.gui.begin("Directory Browser", 10, 10, 350, 400, ["border", "movable", "title", "scalable"]);
joy.gui.layoutRowDynamic(25, 1);
joy.gui.label("Path: " + currentPath, "left");
joy.gui.layoutRowDynamic(25, 2);
if (joy.gui.button("Refresh")) {
refreshDirectory();
addLog("Refreshed directory listing");
}
if (currentPath !== "/" && joy.gui.button("Up")) {
var lastSlash = currentPath.lastIndexOf("/");
currentPath = lastSlash <= 0 ? "/" : currentPath.substring(0, lastSlash);
refreshDirectory();
addLog("Navigated to: " + currentPath);
}
joy.gui.layoutRowDynamic(5, 1); // spacer
// File listing
for (var i = 0; i < directoryItems.length; i++) {
var item = directoryItems[i];
joy.gui.layoutRowDynamic(22, 1);
var label = (item.type === "directory" ? "[DIR] " : "") + item.name;
if (item.type !== "directory") {
label += " (" + item.size + "b)";
}
if (joy.gui.button(label)) {
if (item.type === "directory") {
currentPath = item.path;
refreshDirectory();
addLog("Navigated to: " + currentPath);
} else {
loadFile(item.path);
}
}
}
if (directoryItems.length === 0) {
joy.gui.layoutRowDynamic(25, 1);
joy.gui.label("(empty directory)", "centered");
}
joy.gui.end();
// File Content Window
joy.gui.begin("File Content", 370, 10, 300, 400, ["border", "movable", "title", "scalable"]);
if (selectedFile) {
joy.gui.layoutRowDynamic(25, 1);
joy.gui.label("File: " + selectedFile, "left");
joy.gui.layoutRowDynamic(5, 1);
// Show file content (split into lines for display)
var lines = fileContent.split("\n");
var maxLines = Math.min(lines.length, 15);
for (var i = 0; i < maxLines; i++) {
joy.gui.layoutRowDynamic(18, 1);
joy.gui.label(lines[i].substring(0, 40), "left");
}
if (lines.length > maxLines) {
joy.gui.layoutRowDynamic(18, 1);
joy.gui.label("... (" + (lines.length - maxLines) + " more lines)", "left");
}
} else {
joy.gui.layoutRowDynamic(25, 1);
joy.gui.label("Select a file to view", "centered");
}
joy.gui.end();
// System Info Window
joy.gui.begin("System Paths", 680, 10, 210, 200, ["border", "movable", "title"]);
joy.gui.layoutRowDynamic(20, 1);
joy.gui.label("User:", "left");
joy.gui.layoutRowDynamic(18, 1);
var userDir = joy.filesystem.getUserDirectory();
joy.gui.label(userDir.substring(0, 25) + "...", "left");
joy.gui.layoutRowDynamic(20, 1);
joy.gui.label("Save:", "left");
joy.gui.layoutRowDynamic(18, 1);
var saveDir = joy.filesystem.getSaveDirectory();
joy.gui.label(saveDir ? saveDir.substring(0, 25) + "..." : "(not set)", "left");
joy.gui.layoutRowDynamic(20, 1);
joy.gui.label("Identity:", "left");
joy.gui.layoutRowDynamic(18, 1);
var identity = joy.filesystem.getIdentity();
joy.gui.label(identity || "(not set)", "left");
joy.gui.end();
// Write File Window
joy.gui.begin("Write Files", 680, 220, 210, 190, ["border", "movable", "title"]);
if (!identitySet) {
joy.gui.layoutRowDynamic(25, 1);
joy.gui.label("Set identity first:", "left");
joy.gui.layoutRowDynamic(25, 1);
if (joy.gui.button("Set Identity")) {
joy.filesystem.setIdentity("filesystem-demo");
identitySet = true;
addLog("Identity set to: filesystem-demo");
addLog("Save dir: " + joy.filesystem.getSaveDirectory());
}
} else {
joy.gui.layoutRowDynamic(25, 1);
if (joy.gui.button("Write test.txt")) {
var success = joy.filesystem.write("test.txt", "Hello from Joy GUI!\nLine 2\nLine 3");
addLog("Write test.txt: " + (success ? "success" : "failed"));
refreshDirectory();
}
joy.gui.layoutRowDynamic(25, 1);
if (joy.gui.button("Append to test.txt")) {
var success = joy.filesystem.append("test.txt", "\nAppended!");
addLog("Append: " + (success ? "success" : "failed"));
}
joy.gui.layoutRowDynamic(25, 1);
if (joy.gui.button("Create subdir/")) {
var success = joy.filesystem.createDirectory("subdir");
addLog("Create subdir: " + (success ? "success" : "failed"));
refreshDirectory();
}
joy.gui.layoutRowDynamic(25, 1);
if (joy.gui.button("Delete test.txt")) {
var success = joy.filesystem.remove("test.txt");
addLog("Delete: " + (success ? "success" : "failed"));
refreshDirectory();
}
}
joy.gui.end();
// Log Window
joy.gui.begin("Log", 10, 420, 660, 270, ["border", "movable", "title", "scalable"]);
for (var i = 0; i < log.length; i++) {
joy.gui.layoutRowDynamic(18, 1);
joy.gui.label(log[i], "left");
}
joy.gui.end();
// Instructions
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Press ESC to exit", 10, 680);
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "escape") {
joy.window.close();
}
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/font/main.js
|
JavaScript
|
// Font example - demonstrating the Font API
// Uses joy.graphics.newFont to load and use fonts
const WIDTH = 800;
const HEIGHT = 600;
let defaultFont = null;
let customFont = null;
let currentFont = null;
let useCustomFont = false;
joy.window.setMode(WIDTH, HEIGHT);
joy.window.setTitle("Font Example");
joy.load = function() {
// Create fonts at different sizes
defaultFont = joy.graphics.newFont(16);
customFont = joy.graphics.newFont("Cousine-Regular.ttf", 18);
currentFont = defaultFont;
console.log("Font Example");
console.log("Press SPACE to toggle between default and custom font");
console.log("Press UP/DOWN to adjust line height");
console.log("Press ESC to exit");
};
joy.keypressed = function(key) {
if (key === "escape") {
joy.window.close();
} else if (key === "space") {
useCustomFont = !useCustomFont;
currentFont = useCustomFont ? customFont : defaultFont;
} else if (key === "up") {
currentFont.setLineHeight(currentFont.getLineHeight() + 0.1);
} else if (key === "down") {
currentFont.setLineHeight(Math.max(0.5, currentFont.getLineHeight() - 0.1));
}
};
joy.update = function(dt) {};
joy.draw = function() {
joy.graphics.clear(0.15, 0.15, 0.2);
let y = 20;
const leftCol = 30;
const rightCol = 450;
// Title
joy.graphics.setColor(1, 0.8, 0.2, 1);
joy.graphics.setFont(customFont);
joy.graphics.print("Font API Example", leftCol, y);
y += 40;
// Set current font for demo
joy.graphics.setFont(currentFont);
joy.graphics.setColor(1, 1, 1, 1);
// Font info section
joy.graphics.setColor(0.5, 0.8, 1, 1);
joy.graphics.print("Font Information:", leftCol, y);
y += 25;
joy.graphics.setColor(1, 1, 1, 1);
let fontName = useCustomFont ? "Cousine-Regular.ttf" : "Default (ProggyClean)";
joy.graphics.print("Current Font: " + fontName, leftCol, y);
y += 20;
joy.graphics.print("Height: " + currentFont.getHeight().toFixed(2) + " px", leftCol, y);
y += 20;
joy.graphics.print("Ascent: " + currentFont.getAscent().toFixed(2) + " px", leftCol, y);
y += 20;
joy.graphics.print("Descent: " + currentFont.getDescent().toFixed(2) + " px", leftCol, y);
y += 20;
joy.graphics.print("Baseline: " + currentFont.getBaseline().toFixed(2) + " px", leftCol, y);
y += 20;
joy.graphics.print("Line Height: " + currentFont.getLineHeight().toFixed(2), leftCol, y);
y += 20;
joy.graphics.print("DPI Scale: " + currentFont.getDPIScale().toFixed(2), leftCol, y);
y += 35;
// Text measurement section
joy.graphics.setColor(0.5, 0.8, 1, 1);
joy.graphics.print("Text Measurement:", leftCol, y);
y += 25;
joy.graphics.setColor(1, 1, 1, 1);
let sampleText = "Hello, World!";
let textWidth = currentFont.getWidth(sampleText);
joy.graphics.print("\"" + sampleText + "\" width: " + textWidth.toFixed(2) + " px", leftCol, y);
y += 20;
// Draw the sample text with a width indicator
let fontHeight = currentFont.getHeight();
joy.graphics.setColor(0.3, 0.3, 0.3, 1);
joy.graphics.rectangle("fill", leftCol, y, textWidth, fontHeight);
joy.graphics.setColor(1, 1, 0, 1);
joy.graphics.print(sampleText, leftCol, y);
// Draw baseline indicator
let baseline = currentFont.getBaseline();
joy.graphics.setColor(1, 0, 0, 0.5);
joy.graphics.line(leftCol, y + baseline, leftCol + textWidth, y + baseline);
y += fontHeight + 15;
// Multi-line text width
joy.graphics.setColor(1, 1, 1, 1);
let multilineText = "Line one\nLine two is longer\nThree";
let multiWidth = currentFont.getWidth(multilineText);
joy.graphics.print("Multi-line width: " + multiWidth.toFixed(2) + " px", leftCol, y);
y += 40;
// Word wrapping section
joy.graphics.setColor(0.5, 0.8, 1, 1);
joy.graphics.print("Word Wrapping (getWrap):", leftCol, y);
y += 25;
joy.graphics.setColor(1, 1, 1, 1);
let longText = "This is a longer piece of text that will be wrapped to fit within a specified width limit.";
let wrapLimit = 250;
let [maxWidth, lines] = currentFont.getWrap(longText, wrapLimit);
joy.graphics.print("Wrap limit: " + wrapLimit + " px", leftCol, y);
y += 20;
joy.graphics.print("Result width: " + maxWidth.toFixed(2) + " px", leftCol, y);
y += 20;
joy.graphics.print("Lines: " + lines.length, leftCol, y);
y += 25;
// Draw wrap area background
let lineSpacing = currentFont.getHeight() * currentFont.getLineHeight();
let wrapAreaHeight = lines.length * lineSpacing;
joy.graphics.setColor(0.2, 0.2, 0.25, 1);
joy.graphics.rectangle("fill", leftCol, y, wrapLimit, wrapAreaHeight);
// Draw wrapped lines
joy.graphics.setColor(0.8, 1, 0.8, 1);
for (let i = 0; i < lines.length; i++) {
joy.graphics.print(lines[i], leftCol, y + i * lineSpacing);
}
// Draw wrap boundary
joy.graphics.setColor(1, 0.5, 0.5, 0.5);
joy.graphics.line(leftCol + wrapLimit, y - 5, leftCol + wrapLimit, y + wrapAreaHeight + 5);
// Right column - Controls and additional info
y = 60;
joy.graphics.setColor(0.5, 0.8, 1, 1);
joy.graphics.print("Controls:", rightCol, y);
y += 25;
joy.graphics.setColor(0.8, 0.8, 0.8, 1);
joy.graphics.print("SPACE - Toggle font", rightCol, y);
y += 20;
joy.graphics.print("UP/DOWN - Adjust line height", rightCol, y);
y += 20;
joy.graphics.print("ESC - Exit", rightCol, y);
y += 40;
// Filter info
joy.graphics.setColor(0.5, 0.8, 1, 1);
joy.graphics.print("Filter Settings:", rightCol, y);
y += 25;
joy.graphics.setColor(1, 1, 1, 1);
let [minFilter, magFilter, anisotropy] = currentFont.getFilter();
joy.graphics.print("Min: " + minFilter, rightCol, y);
y += 20;
joy.graphics.print("Mag: " + magFilter, rightCol, y);
y += 20;
joy.graphics.print("Anisotropy: " + anisotropy, rightCol, y);
y += 40;
// hasGlyphs demo
joy.graphics.setColor(0.5, 0.8, 1, 1);
joy.graphics.print("Glyph Check:", rightCol, y);
y += 25;
joy.graphics.setColor(1, 1, 1, 1);
let asciiCheck = currentFont.hasGlyphs("ABC123");
joy.graphics.print("Has 'ABC123': " + asciiCheck, rightCol, y);
y += 40;
// Alphabet display
joy.graphics.setColor(0.5, 0.8, 1, 1);
joy.graphics.print("Character Set:", rightCol, y);
y += 25;
joy.graphics.setColor(0.9, 0.9, 0.7, 1);
joy.graphics.print("ABCDEFGHIJKLM", rightCol, y);
y += 20;
joy.graphics.print("NOPQRSTUVWXYZ", rightCol, y);
y += 20;
joy.graphics.print("abcdefghijklm", rightCol, y);
y += 20;
joy.graphics.print("nopqrstuvwxyz", rightCol, y);
y += 20;
joy.graphics.print("0123456789", rightCol, y);
y += 20;
joy.graphics.print("!@#$%^&*()_+-=", rightCol, y);
y += 40;
// FPS
joy.graphics.setColor(0.5, 0.5, 0.5, 1);
joy.graphics.print("FPS: " + joy.timer.getFPS(), rightCol, HEIGHT - 30);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/gamepad/main.js
|
JavaScript
|
// Gamepad/Joystick example
// Demonstrates gamepad detection, input reading, and callbacks
joy.window.setMode(900, 600);
joy.window.setTitle("Gamepad Demo");
joy.graphics.setBackgroundColor(0.15, 0.15, 0.2);
var joysticks = [];
var selectedJoystick = 0;
var eventLog = [];
var maxLogEntries = 12;
// Gamepad visual layout positions
var leftStickPos = { x: 200, y: 280 };
var rightStickPos = { x: 500, y: 280 };
var dpadPos = { x: 200, y: 420 };
var faceButtonsPos = { x: 500, y: 420 };
var triggerPos = { y: 150 };
function addLog(message) {
var timestamp = Math.floor(joy.timer.getTime() * 10) / 10;
eventLog.unshift("[" + timestamp + "s] " + message);
if (eventLog.length > maxLogEntries) {
eventLog.pop();
}
}
joy.load = function() {
console.log("Gamepad Demo:");
console.log(" Connect a gamepad/joystick to see it here");
console.log(" Tab: Cycle through connected joysticks");
console.log(" R: Test rumble/vibration");
console.log(" Escape: Exit");
// Get any already-connected joysticks
joysticks = joy.joystick.getJoysticks();
if (joysticks.length > 0) {
addLog("Found " + joysticks.length + " joystick(s) already connected");
}
};
// Called when a joystick is connected
joy.joystickadded = function(joystick) {
addLog("Connected: " + joystick.getName());
joysticks = joy.joystick.getJoysticks();
};
// Called when a joystick is disconnected
joy.joystickremoved = function(joystick) {
addLog("Disconnected: " + joystick.getName());
joysticks = joy.joystick.getJoysticks();
if (selectedJoystick >= joysticks.length) {
selectedJoystick = Math.max(0, joysticks.length - 1);
}
};
// Raw joystick button pressed
joy.joystickpressed = function(joystick, button) {
addLog("Button " + button + " pressed");
};
// Raw joystick button released
joy.joystickreleased = function(joystick, button) {
addLog("Button " + button + " released");
};
// Raw joystick axis motion
joy.joystickaxis = function(joystick, axis, value) {
// Only log significant movements
if (Math.abs(value) > 0.5) {
addLog("Axis " + axis + ": " + value.toFixed(2));
}
};
// Raw joystick hat motion
joy.joystickhat = function(joystick, hat, direction) {
addLog("Hat " + hat + ": " + direction);
};
// Virtual gamepad button pressed (more reliable for standard controllers)
joy.gamepadpressed = function(joystick, button) {
addLog("Gamepad: " + button + " pressed");
};
// Virtual gamepad button released
joy.gamepadreleased = function(joystick, button) {
addLog("Gamepad: " + button + " released");
};
// Virtual gamepad axis motion
joy.gamepadaxis = function(joystick, axis, value) {
// Only log significant movements
if (Math.abs(value) > 0.5) {
addLog("Gamepad axis " + axis + ": " + value.toFixed(2));
}
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "escape") {
joy.window.close();
}
if (key === "tab" && joysticks.length > 0) {
selectedJoystick = (selectedJoystick + 1) % joysticks.length;
addLog("Selected joystick " + (selectedJoystick + 1));
}
if (key === "r" && joysticks.length > 0) {
var js = joysticks[selectedJoystick];
if (js.isVibrationSupported()) {
js.setVibration(0.5, 0.5, 0.3);
addLog("Rumble!");
} else {
addLog("Vibration not supported");
}
}
};
joy.update = function(dt) {
};
function drawStick(x, y, axisX, axisY, label) {
var radius = 50;
var stickRadius = 20;
// Background circle
joy.graphics.setColor(0.3, 0.3, 0.35);
joy.graphics.circle("fill", x, y, radius);
joy.graphics.setColor(0.4, 0.4, 0.45);
joy.graphics.circle("line", x, y, radius);
// Stick position
var stickX = x + axisX * (radius - stickRadius);
var stickY = y + axisY * (radius - stickRadius);
joy.graphics.setColor(0.6, 0.6, 0.8);
joy.graphics.circle("fill", stickX, stickY, stickRadius);
joy.graphics.setColor(0.8, 0.8, 1);
joy.graphics.circle("line", stickX, stickY, stickRadius);
// Label
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print(label, x - 25, y + radius + 10);
joy.graphics.print("X: " + axisX.toFixed(2), x - 25, y + radius + 28);
joy.graphics.print("Y: " + axisY.toFixed(2), x - 25, y + radius + 46);
}
function drawTrigger(x, y, value, label) {
var width = 60;
var height = 20;
// Background
joy.graphics.setColor(0.3, 0.3, 0.35);
joy.graphics.rectangle("fill", x, y, width, height);
// Fill based on value (triggers are 0 to 1 typically, but can be -1 to 1)
var normalizedValue = (value + 1) / 2; // Convert -1..1 to 0..1
joy.graphics.setColor(0.4, 0.7, 0.4);
joy.graphics.rectangle("fill", x, y, width * normalizedValue, height);
// Border
joy.graphics.setColor(0.5, 0.5, 0.55);
joy.graphics.rectangle("line", x, y, width, height);
// Label
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print(label + ": " + value.toFixed(2), x, y + height + 5);
}
function drawButton(x, y, pressed, label) {
var radius = 18;
if (pressed) {
joy.graphics.setColor(0.3, 0.8, 0.3);
} else {
joy.graphics.setColor(0.35, 0.35, 0.4);
}
joy.graphics.circle("fill", x, y, radius);
joy.graphics.setColor(0.5, 0.5, 0.55);
joy.graphics.circle("line", x, y, radius);
joy.graphics.setColor(1, 1, 1);
joy.graphics.print(label, x - 5, y - 6);
}
function drawDPad(x, y, js) {
var size = 25;
var gap = 2;
var up = js.isGamepadDown("dpup");
var down = js.isGamepadDown("dpdown");
var left = js.isGamepadDown("dpleft");
var right = js.isGamepadDown("dpright");
// Up
joy.graphics.setColor(up ? 0.3 : 0.35, up ? 0.8 : 0.35, up ? 0.3 : 0.4);
joy.graphics.rectangle("fill", x - size/2, y - size - gap - size, size, size);
// Down
joy.graphics.setColor(down ? 0.3 : 0.35, down ? 0.8 : 0.35, down ? 0.3 : 0.4);
joy.graphics.rectangle("fill", x - size/2, y + gap, size, size);
// Left
joy.graphics.setColor(left ? 0.3 : 0.35, left ? 0.8 : 0.35, left ? 0.3 : 0.4);
joy.graphics.rectangle("fill", x - size - gap - size/2, y - size/2, size, size);
// Right
joy.graphics.setColor(right ? 0.3 : 0.35, right ? 0.8 : 0.35, right ? 0.3 : 0.4);
joy.graphics.rectangle("fill", x + gap + size/2, y - size/2, size, size);
// Center
joy.graphics.setColor(0.25, 0.25, 0.3);
joy.graphics.rectangle("fill", x - size/2, y - size/2, size, size);
// Label
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("D-Pad", x - 20, y + size + 15);
}
joy.draw = function() {
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Gamepad Demo", 10, 10);
var count = joy.joystick.getJoystickCount();
joy.graphics.print("Joysticks connected: " + count, 10, 30);
if (count === 0) {
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Connect a gamepad or joystick to begin...", 10, 60);
joy.graphics.print("Press Escape to exit", 10, 80);
// Draw event log even with no joysticks
drawEventLog();
return;
}
var js = joysticks[selectedJoystick];
if (!js || !js.isConnected()) {
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Selected joystick disconnected", 10, 60);
drawEventLog();
return;
}
// Joystick info
joy.graphics.print("Selected: " + (selectedJoystick + 1) + "/" + count + " - " + js.getName(), 10, 50);
var ids = js.getID();
joy.graphics.setColor(0.6, 0.6, 0.6);
joy.graphics.print("ID: " + ids[0] + ", Instance: " + ids[1], 10, 70);
joy.graphics.print("GUID: " + js.getGUID(), 10, 90);
joy.graphics.print("Gamepad: " + (js.isGamepad() ? "Yes" : "No"), 10, 110);
var info = js.getDeviceInfo();
joy.graphics.print("Vendor: 0x" + info[0].toString(16) + " Product: 0x" + info[1].toString(16), 200, 110);
// Draw controls based on whether it's a gamepad
if (js.isGamepad()) {
// Draw gamepad layout
// Left stick
var leftX = js.getGamepadAxis("leftx");
var leftY = js.getGamepadAxis("lefty");
drawStick(leftStickPos.x, leftStickPos.y, leftX, leftY, "Left Stick");
// Right stick
var rightX = js.getGamepadAxis("rightx");
var rightY = js.getGamepadAxis("righty");
drawStick(rightStickPos.x, rightStickPos.y, rightX, rightY, "Right Stick");
// Triggers
var leftTrigger = js.getGamepadAxis("triggerleft");
var rightTrigger = js.getGamepadAxis("triggerright");
drawTrigger(150, triggerPos.y, leftTrigger, "LT");
drawTrigger(450, triggerPos.y, rightTrigger, "RT");
// Shoulder buttons
drawButton(220, triggerPos.y + 10, js.isGamepadDown("leftshoulder"), "LB");
drawButton(520, triggerPos.y + 10, js.isGamepadDown("rightshoulder"), "RB");
// Face buttons
var fbX = faceButtonsPos.x;
var fbY = faceButtonsPos.y;
drawButton(fbX, fbY - 35, js.isGamepadDown("y"), "Y");
drawButton(fbX - 35, fbY, js.isGamepadDown("x"), "X");
drawButton(fbX + 35, fbY, js.isGamepadDown("b"), "B");
drawButton(fbX, fbY + 35, js.isGamepadDown("a"), "A");
// D-Pad
drawDPad(dpadPos.x, dpadPos.y, js);
// Center buttons
drawButton(350, 200, js.isGamepadDown("back"), "<");
drawButton(400, 200, js.isGamepadDown("guide"), "G");
drawButton(450, 200, js.isGamepadDown("start"), ">");
// Stick buttons
drawButton(leftStickPos.x, leftStickPos.y + 90, js.isGamepadDown("leftstick"), "LS");
drawButton(rightStickPos.x, rightStickPos.y + 90, js.isGamepadDown("rightstick"), "RS");
} else {
// Raw joystick mode - show axes and buttons
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Raw Joystick Mode (not a recognized gamepad)", 10, 140);
joy.graphics.print("Axes: " + js.getAxisCount() + " Buttons: " + js.getButtonCount() + " Hats: " + js.getHatCount(), 10, 160);
// Draw axes
var axes = js.getAxes();
for (var i = 0; i < Math.min(axes.length, 6); i++) {
var axisX = 150 + (i % 3) * 150;
var axisY = 220 + Math.floor(i / 3) * 100;
drawTrigger(axisX, axisY, axes[i], "Axis " + (i + 1));
}
// Draw buttons
var buttonsPerRow = 8;
for (var i = 0; i < Math.min(js.getButtonCount(), 16); i++) {
var btnX = 150 + (i % buttonsPerRow) * 45;
var btnY = 420 + Math.floor(i / buttonsPerRow) * 50;
var pressed = js.isDown(i + 1);
drawButton(btnX, btnY, pressed, "" + (i + 1));
}
// Draw hats
if (js.getHatCount() > 0) {
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Hat 1: " + js.getHat(1), 10, 520);
}
}
// Controls hint
joy.graphics.setColor(0.5, 0.5, 0.5);
joy.graphics.print("Tab: Switch joystick | R: Rumble test | Escape: Exit", 10, 570);
// Draw event log
drawEventLog();
};
function drawEventLog() {
var logX = 650;
var logY = 10;
joy.graphics.setColor(0.25, 0.25, 0.3);
joy.graphics.rectangle("fill", logX - 5, logY - 5, 250, 250);
joy.graphics.setColor(0.8, 0.8, 0.8);
joy.graphics.print("Event Log:", logX, logY);
joy.graphics.setColor(0.6, 0.6, 0.6);
for (var i = 0; i < eventLog.length; i++) {
joy.graphics.print(eventLog[i], logX, logY + 20 + i * 18);
}
}
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/gamepad/rumble.js
|
JavaScript
|
// Joy Gamepad Rumble Test
// Run with: ./build/joy examples/gamepad/rumble.js
joy.window.setMode(600, 400);
joy.window.setTitle("Joy Rumble Test");
joy.graphics.setBackgroundColor(0.15, 0.15, 0.2);
var joystick = null;
var rumbleLeft = 0.5;
var rumbleRight = 0.5;
var rumbleDuration = 0.3;
var lastRumbleResult = null;
joy.load = function() {
// Get first connected joystick
var joysticks = joy.joystick.getJoysticks();
if (joysticks.length > 0) {
joystick = joysticks[0];
console.log("Found joystick: " + joystick.getName());
console.log("Vibration supported: " + joystick.isVibrationSupported());
} else {
console.log("No joystick connected");
}
};
joy.joystickadded = function(j) {
if (!joystick) {
joystick = j;
console.log("Joystick connected: " + j.getName());
console.log("Vibration supported: " + j.isVibrationSupported());
}
};
joy.joystickremoved = function(j) {
if (joystick && joystick.getGUID() === j.getGUID()) {
joystick = null;
console.log("Joystick disconnected");
}
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "escape") {
joy.window.close();
}
if (!joystick) return;
if (key === "r") {
// Test rumble
var result = joystick.setVibration(rumbleLeft, rumbleRight, rumbleDuration);
lastRumbleResult = result;
console.log("setVibration(" + rumbleLeft + ", " + rumbleRight + ", " + rumbleDuration + ") = " + result);
}
if (key === "s") {
// Stop rumble
var result = joystick.setVibration();
lastRumbleResult = result;
console.log("setVibration() [stop] = " + result);
}
if (key === "1") {
// Left motor only
var result = joystick.setVibration(1, 0, 0.5);
lastRumbleResult = result;
console.log("Left motor only: " + result);
}
if (key === "2") {
// Right motor only
var result = joystick.setVibration(0, 1, 0.5);
lastRumbleResult = result;
console.log("Right motor only: " + result);
}
if (key === "3") {
// Both motors full
var result = joystick.setVibration(1, 1, 0.5);
lastRumbleResult = result;
console.log("Both motors full: " + result);
}
if (key === "up") {
rumbleLeft = Math.min(1, rumbleLeft + 0.1);
}
if (key === "down") {
rumbleLeft = Math.max(0, rumbleLeft - 0.1);
}
if (key === "right") {
rumbleRight = Math.min(1, rumbleRight + 0.1);
}
if (key === "left") {
rumbleRight = Math.max(0, rumbleRight - 0.1);
}
};
joy.gamepadpressed = function(j, button) {
if (button === "a") {
var result = j.setVibration(rumbleLeft, rumbleRight, rumbleDuration);
lastRumbleResult = result;
console.log("A button rumble: " + result);
}
};
joy.update = function(dt) {
};
joy.draw = function() {
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Joy Gamepad Rumble Test", 10, 10);
if (joystick) {
joy.graphics.print("Joystick: " + joystick.getName(), 10, 40);
joy.graphics.print("Vibration supported: " + joystick.isVibrationSupported(), 10, 60);
var vibration = joystick.getVibration();
joy.graphics.print("Current vibration: L=" + vibration[0].toFixed(2) + " R=" + vibration[1].toFixed(2), 10, 80);
joy.graphics.print("Controls:", 10, 130);
joy.graphics.print(" R: Rumble with current settings", 10, 150);
joy.graphics.print(" S: Stop rumble", 10, 170);
joy.graphics.print(" 1: Left motor only", 10, 190);
joy.graphics.print(" 2: Right motor only", 10, 210);
joy.graphics.print(" 3: Both motors full", 10, 230);
joy.graphics.print(" A button: Rumble", 10, 250);
joy.graphics.print(" Arrow keys: Adjust L/R intensity", 10, 270);
joy.graphics.print("Rumble settings:", 10, 320);
joy.graphics.print(" Left: " + rumbleLeft.toFixed(1), 10, 340);
joy.graphics.print(" Right: " + rumbleRight.toFixed(1), 10, 360);
if (lastRumbleResult !== null) {
joy.graphics.print("Last result: " + lastRumbleResult, 300, 320);
}
} else {
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("No joystick connected", 10, 40);
joy.graphics.print("Connect a gamepad to test rumble", 10, 60);
}
joy.graphics.setColor(0.5, 0.5, 0.5);
joy.graphics.print("Escape to exit", 10, 380);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/games/pong/main.js
|
JavaScript
|
// Pong - Two Player
// Player 1 (left): W/S keys
// Player 2 (right): UP/DOWN arrows
var WIDTH = 800;
var HEIGHT = 600;
joy.window.setMode(WIDTH, HEIGHT);
joy.window.setTitle("Pong");
joy.graphics.setBackgroundColor(0.05, 0.05, 0.1);
// Game constants
var PADDLE_WIDTH = 15;
var PADDLE_HEIGHT = 80;
var PADDLE_SPEED = 400;
var BALL_SIZE = 12;
var BALL_SPEED = 350;
var WINNING_SCORE = 5;
// Game state
var paddle1 = { x: 30, y: HEIGHT / 2 - PADDLE_HEIGHT / 2 };
var paddle2 = { x: WIDTH - 30 - PADDLE_WIDTH, y: HEIGHT / 2 - PADDLE_HEIGHT / 2 };
var ball = { x: WIDTH / 2, y: HEIGHT / 2, vx: BALL_SPEED, vy: 0 };
var score1 = 0;
var score2 = 0;
var gameOver = false;
var winner = 0;
// Sounds
var sndPaddle = null;
var sndWall = null;
var sndScore = null;
joy.load = function() {
// Load sounds
if (joy.filesystem.getInfo("paddle.ogg")) {
sndPaddle = joy.audio.newSource("paddle.ogg", "static");
}
if (joy.filesystem.getInfo("wall.ogg")) {
sndWall = joy.audio.newSource("wall.ogg", "static");
}
if (joy.filesystem.getInfo("score.ogg")) {
sndScore = joy.audio.newSource("score.ogg", "static");
}
resetBall(1);
};
function resetBall(direction) {
ball.x = WIDTH / 2 - BALL_SIZE / 2;
ball.y = HEIGHT / 2 - BALL_SIZE / 2;
ball.vx = BALL_SPEED * direction;
ball.vy = (Math.random() - 0.5) * BALL_SPEED * 0.5;
}
function resetGame() {
score1 = 0;
score2 = 0;
gameOver = false;
winner = 0;
paddle1.y = HEIGHT / 2 - PADDLE_HEIGHT / 2;
paddle2.y = HEIGHT / 2 - PADDLE_HEIGHT / 2;
resetBall(1);
}
joy.keypressed = function(key, scancode, isrepeat) {
if (gameOver) {
if (key === "space") {
resetGame();
}
}
if (key === "escape") {
joy.window.close();
}
};
joy.update = function(dt) {
if (gameOver) {
return;
}
// Player 1 controls (W/S)
if (joy.keyboard.isDown("w")) {
paddle1.y -= PADDLE_SPEED * dt;
}
if (joy.keyboard.isDown("s")) {
paddle1.y += PADDLE_SPEED * dt;
}
// Player 2 controls (UP/DOWN)
if (joy.keyboard.isDown("up")) {
paddle2.y -= PADDLE_SPEED * dt;
}
if (joy.keyboard.isDown("down")) {
paddle2.y += PADDLE_SPEED * dt;
}
// Clamp paddles to screen
paddle1.y = Math.max(0, Math.min(HEIGHT - PADDLE_HEIGHT, paddle1.y));
paddle2.y = Math.max(0, Math.min(HEIGHT - PADDLE_HEIGHT, paddle2.y));
// Move ball
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
// Ball collision with top/bottom walls
if (ball.y <= 0) {
ball.y = 0;
ball.vy = Math.abs(ball.vy);
if (sndWall) sndWall.play();
}
if (ball.y + BALL_SIZE >= HEIGHT) {
ball.y = HEIGHT - BALL_SIZE;
ball.vy = -Math.abs(ball.vy);
if (sndWall) sndWall.play();
}
// Ball collision with paddle 1
if (ball.vx < 0 &&
ball.x <= paddle1.x + PADDLE_WIDTH &&
ball.x + BALL_SIZE >= paddle1.x &&
ball.y + BALL_SIZE >= paddle1.y &&
ball.y <= paddle1.y + PADDLE_HEIGHT) {
ball.x = paddle1.x + PADDLE_WIDTH;
ball.vx = Math.abs(ball.vx) * 1.05; // Speed up slightly
// Add angle based on where ball hit paddle
var hitPos = (ball.y + BALL_SIZE / 2 - paddle1.y) / PADDLE_HEIGHT;
ball.vy = (hitPos - 0.5) * BALL_SPEED * 1.5;
if (sndPaddle) sndPaddle.play();
}
// Ball collision with paddle 2
if (ball.vx > 0 &&
ball.x + BALL_SIZE >= paddle2.x &&
ball.x <= paddle2.x + PADDLE_WIDTH &&
ball.y + BALL_SIZE >= paddle2.y &&
ball.y <= paddle2.y + PADDLE_HEIGHT) {
ball.x = paddle2.x - BALL_SIZE;
ball.vx = -Math.abs(ball.vx) * 1.05; // Speed up slightly
// Add angle based on where ball hit paddle
var hitPos = (ball.y + BALL_SIZE / 2 - paddle2.y) / PADDLE_HEIGHT;
ball.vy = (hitPos - 0.5) * BALL_SPEED * 1.5;
if (sndPaddle) sndPaddle.play();
}
// Scoring
if (ball.x + BALL_SIZE < 0) {
score2++;
if (sndScore) sndScore.play();
if (score2 >= WINNING_SCORE) {
gameOver = true;
winner = 2;
} else {
resetBall(-1);
}
}
if (ball.x > WIDTH) {
score1++;
if (sndScore) sndScore.play();
if (score1 >= WINNING_SCORE) {
gameOver = true;
winner = 1;
} else {
resetBall(1);
}
}
};
joy.draw = function() {
// Draw center line
joy.graphics.setColor(0.3, 0.3, 0.3);
for (var y = 0; y < HEIGHT; y += 30) {
joy.graphics.rectangle("fill", WIDTH / 2 - 2, y, 4, 15);
}
// Draw paddles
joy.graphics.setColor(1, 1, 1);
joy.graphics.rectangle("fill", paddle1.x, paddle1.y, PADDLE_WIDTH, PADDLE_HEIGHT);
joy.graphics.rectangle("fill", paddle2.x, paddle2.y, PADDLE_WIDTH, PADDLE_HEIGHT);
// Draw ball
joy.graphics.setColor(1, 1, 0);
joy.graphics.rectangle("fill", ball.x, ball.y, BALL_SIZE, BALL_SIZE);
// Draw scores
joy.graphics.setColor(1, 1, 1);
joy.graphics.print(score1.toString(), WIDTH / 4, 30);
joy.graphics.print(score2.toString(), 3 * WIDTH / 4, 30);
// Draw controls hint
joy.graphics.setColor(0.4, 0.4, 0.4);
joy.graphics.print("W/S", 50, HEIGHT - 30);
joy.graphics.print("UP/DOWN", WIDTH - 100, HEIGHT - 30);
// Game over screen
if (gameOver) {
joy.graphics.setColor(0, 0, 0, 0.7);
joy.graphics.rectangle("fill", 0, 0, WIDTH, HEIGHT);
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Player " + winner + " Wins!", WIDTH / 2 - 60, HEIGHT / 2 - 20);
joy.graphics.print("Press SPACE to play again", WIDTH / 2 - 100, HEIGHT / 2 + 20);
joy.graphics.print("Press ESC to quit", WIDTH / 2 - 70, HEIGHT / 2 + 50);
}
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/canvas.js
|
JavaScript
|
// Canvas example - demonstrates render-to-texture functionality
// This creates a canvas, draws to it, then draws the canvas to the screen
let canvas;
let time = 0;
joy.load = function() {
// Create a 200x200 canvas (render target)
canvas = joy.graphics.newCanvas(200, 200);
// Set nearest-neighbor filtering for pixelated look
canvas.setFilter("nearest", "nearest");
console.log("Canvas created:", canvas.getWidth(), "x", canvas.getHeight());
};
joy.update = function(dt) {
time += dt;
};
joy.draw = function() {
// First, render to the canvas
joy.graphics.setCanvas(canvas);
// Clear canvas with a dark blue background
joy.graphics.clear(0.1, 0.1, 0.3, 1);
// Draw some shapes to the canvas
joy.graphics.setColor(1, 0.5, 0, 1); // Orange
joy.graphics.circle("fill", 100, 100, 50 + Math.sin(time * 2) * 20);
joy.graphics.setColor(0, 1, 0.5, 1); // Cyan
joy.graphics.rectangle("fill", 20, 20, 60, 60);
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Canvas!", 60, 90);
// Switch back to rendering to the screen
joy.graphics.setCanvas();
// Clear the screen with a different color
joy.graphics.clear(0.2, 0.2, 0.2, 1);
// Draw the canvas multiple times with different transforms
joy.graphics.setColor(1, 1, 1, 1);
// Draw at original size
joy.graphics.draw(canvas, 50, 50);
// Draw scaled up 2x
joy.graphics.draw(canvas, 300, 50, 0, 2, 2);
// Draw rotated
joy.graphics.draw(canvas, 200, 400, time, 1, 1, 100, 100);
// Draw with scaling and origin
joy.graphics.push();
joy.graphics.translate(600, 300);
joy.graphics.scale(1.5, 1.5);
joy.graphics.rotate(Math.sin(time) * 0.5);
joy.graphics.draw(canvas, 0, 0, 0, 1, 1, 100, 100);
joy.graphics.pop();
// Draw info text
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Canvas (render-to-texture) demo", 10, 10);
joy.graphics.print("Canvas size: " + canvas.getWidth() + "x" + canvas.getHeight(), 10, 30);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/font.js
|
JavaScript
|
// Font example
var bigFont;
var mediumFont;
joy.load = function() {
joy.window.setTitle("Font Example");
joy.graphics.setBackgroundColor(0.1, 0.1, 0.15);
bigFont = joy.graphics.newFont(64);
mediumFont = joy.graphics.newFont(24);
};
joy.draw = function() {
// Draw big title
joy.graphics.setFont(bigFont);
joy.graphics.setColor(1, 0.8, 0.2);
joy.graphics.print("Joy2D", 50, 50);
// Draw subtitle
joy.graphics.setFont(mediumFont);
joy.graphics.setColor(0.7, 0.7, 0.8);
joy.graphics.print("A Love2D-like engine for JavaScript", 50, 130);
// Draw instructions
joy.graphics.setColor(0.5, 0.5, 0.6);
joy.graphics.print("Press ESC to exit", 50, 180);
};
joy.keypressed = function(key) {
if (key === "escape") {
joy.window.close();
}
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/image/main.js
|
JavaScript
|
// Image example - displaying sprites from a sprite sheet
// smiles.png contains 100 smiley faces arranged in a 10x10 grid
// Each smiley is 15x15 pixels
let num_smiles = 10000;
let smiles;
const SMILE_SIZE = 15;
const GRID_SIZE = 10;
// Store some bouncing smileys
let smileys = [];
joy.load = function() {
smiles = joy.graphics.newImage("smiles.png");
smiles.setFilter("nearest", "nearest");
// Create some bouncing smileys with random positions and velocities
for (let i = 0; i < num_smiles; i++) {
smileys.push({
x: Math.random() * (joy.graphics.getWidth() - SMILE_SIZE * 2),
y: Math.random() * (joy.graphics.getHeight() - SMILE_SIZE * 2),
vx: (Math.random() - 0.5) * 200,
vy: (Math.random() - 0.5) * 200,
// Pick a random smiley from the sprite sheet
spriteX: Math.floor(Math.random() * GRID_SIZE),
spriteY: Math.floor(Math.random() * GRID_SIZE),
scale: 1 + Math.random() * 2
});
}
};
joy.keypressed = function(key) {
if (key === "escape") {
joy.window.close();
}
};
joy.update = function(dt) {
const width = joy.graphics.getWidth();
const height = joy.graphics.getHeight();
// Update smiley positions
for (let s of smileys) {
s.x += s.vx * dt;
s.y += s.vy * dt;
// Bounce off walls
if (s.x < 0) {
s.x = 0;
s.vx = -s.vx;
}
if (s.x > width - SMILE_SIZE * s.scale) {
s.x = width - SMILE_SIZE * s.scale;
s.vx = -s.vx;
}
if (s.y < 0) {
s.y = 0;
s.vy = -s.vy;
}
if (s.y > height - SMILE_SIZE * s.scale) {
s.y = height - SMILE_SIZE * s.scale;
s.vy = -s.vy;
}
}
};
joy.draw = function() {
joy.graphics.clear(0.2, 0.2, 0.3);
// Draw bouncing smileys using quads from the sprite sheet
for (let s of smileys) {
// Calculate source rectangle in the sprite sheet
const srcX = s.spriteX * SMILE_SIZE;
const srcY = s.spriteY * SMILE_SIZE;
// Draw the sprite at its position with scaling
joy.graphics.drawQuad(smiles, srcX, srcY, SMILE_SIZE, SMILE_SIZE,
s.x, s.y, 0, s.scale, s.scale);
}
// Draw a static row of smileys at the top showing different faces
joy.graphics.setColor(1, 1, 1, 1);
for (let i = 0; i < 10; i++) {
const srcX = i * SMILE_SIZE;
const srcY = 0;
joy.graphics.drawQuad(smiles, srcX, srcY, SMILE_SIZE, SMILE_SIZE,
10 + i * 40, 10, 0, 2, 2);
}
// Draw info text
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Bouncing smileys from sprite sheet!", 10, 60);
joy.graphics.print("FPS: " + joy.timer.getFPS(), 10, 80);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/image/main.lua
|
Lua
|
-- Image example - displaying sprites from a sprite sheet
-- smiles.png contains 100 smiley faces arranged in a 10x10 grid
-- Each smiley is 15x15 pixels
local num_smiles = 100000
local smiles
local SMILE_SIZE = 15
local GRID_SIZE = 10
-- Store some bouncing smileys
local smileys = {}
-- Pre-create quads for each sprite in the sheet
local quads = {}
function love.load()
smiles = love.graphics.newImage("smiles.png")
smiles:setFilter("nearest", "nearest")
-- Create quads for each sprite in the 10x10 grid
for y = 0, GRID_SIZE - 1 do
quads[y] = {}
for x = 0, GRID_SIZE - 1 do
quads[y][x] = love.graphics.newQuad(
x * SMILE_SIZE, y * SMILE_SIZE,
SMILE_SIZE, SMILE_SIZE,
smiles:getDimensions()
)
end
end
-- Create some bouncing smileys with random positions and velocities
for i = 1, num_smiles do
table.insert(smileys, {
x = math.random() * (love.graphics.getWidth() - SMILE_SIZE * 2),
y = math.random() * (love.graphics.getHeight() - SMILE_SIZE * 2),
vx = (math.random() - 0.5) * 200,
vy = (math.random() - 0.5) * 200,
-- Pick a random smiley from the sprite sheet
spriteX = math.floor(math.random() * GRID_SIZE),
spriteY = math.floor(math.random() * GRID_SIZE),
scale = 1 + math.random() * 2
})
end
love.graphics.setBackgroundColor(0.2, 0.2, 0.3)
end
function love.keypressed(key)
if key == "escape" then
love.event.quit()
end
end
function love.update(dt)
local width = love.graphics.getWidth()
local height = love.graphics.getHeight()
-- Update smiley positions
for _, s in ipairs(smileys) do
s.x = s.x + s.vx * dt
s.y = s.y + s.vy * dt
-- Bounce off walls
if s.x < 0 then
s.x = 0
s.vx = -s.vx
end
if s.x > width - SMILE_SIZE * s.scale then
s.x = width - SMILE_SIZE * s.scale
s.vx = -s.vx
end
if s.y < 0 then
s.y = 0
s.vy = -s.vy
end
if s.y > height - SMILE_SIZE * s.scale then
s.y = height - SMILE_SIZE * s.scale
s.vy = -s.vy
end
end
end
function love.draw()
-- Draw bouncing smileys using quads from the sprite sheet
for _, s in ipairs(smileys) do
local quad = quads[s.spriteY][s.spriteX]
love.graphics.draw(smiles, quad, s.x, s.y, 0, s.scale, s.scale)
end
-- Draw a static row of smileys at the top showing different faces
love.graphics.setColor(1, 1, 1, 1)
for i = 0, 9 do
local quad = quads[0][i]
love.graphics.draw(smiles, quad, 10 + i * 40, 10, 0, 2, 2)
end
-- Draw info text
love.graphics.setColor(1, 1, 1, 1)
love.graphics.print("Bouncing smileys from sprite sheet!", 10, 60)
end
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/movement.js
|
JavaScript
|
// Movement example
// Move a rectangle with arrow keys
joy.window.setMode(800, 600);
joy.window.setTitle("Graphics - Arrow Keys to Move");
joy.graphics.setBackgroundColor(0.1, 0.1, 0.2);
var x = 400;
var y = 300;
var speed = 200;
joy.load = function() {
console.log("Use arrow keys to move the rectangle");
console.log("Press Escape to exit");
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "escape") {
joy.window.close();
}
};
joy.update = function(dt) {
if (joy.keyboard.isDown("left")) {
x -= speed * dt;
}
if (joy.keyboard.isDown("right")) {
x += speed * dt;
}
if (joy.keyboard.isDown("up")) {
y -= speed * dt;
}
if (joy.keyboard.isDown("down")) {
y += speed * dt;
}
};
joy.draw = function() {
joy.graphics.setColor(0, 0.8, 1);
joy.graphics.rectangle("fill", x - 25, y - 25, 50, 50);
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("x: " + Math.floor(x) + " y: " + Math.floor(y), 10, 10);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/pipeline_test.js
|
JavaScript
|
// Test dynamic pipeline capabilities
// This exercises different blend modes, color masks, and pipeline switching
let time = 0;
joy.draw = function() {
const width = joy.graphics.getWidth();
const height = joy.graphics.getHeight();
// Clear background
joy.graphics.setBackgroundColor(0.1, 0.1, 0.15, 1);
joy.graphics.clear();
const boxSize = 120;
const spacing = 140;
const startX = 50;
const startY = 50;
// Row 1: Different blend modes
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Blend Modes:", startX, startY - 25);
// Draw a background pattern for blend mode testing
for (let row = 0; row < 2; row++) {
for (let col = 0; col < 5; col++) {
const x = startX + col * spacing;
const y = startY + row * (boxSize + 60);
// Background squares (alternating colors)
joy.graphics.setBlendMode("replace");
joy.graphics.setColor(0.3, 0.5, 0.7, 1);
joy.graphics.rectangle("fill", x, y, boxSize, boxSize);
joy.graphics.setColor(0.7, 0.3, 0.3, 1);
joy.graphics.rectangle("fill", x + boxSize/3, y + boxSize/3, boxSize/2, boxSize/2);
}
}
// Now draw overlays with different blend modes
const blendModes = ["alpha", "add", "multiply", "replace"];
const labels = ["Alpha", "Additive", "Multiply", "Replace"];
for (let i = 0; i < blendModes.length; i++) {
const x = startX + i * spacing;
const y = startY;
joy.graphics.setBlendMode(blendModes[i]);
// Animated alpha for visibility
const alpha = 0.5 + 0.3 * Math.sin(time * 2 + i);
joy.graphics.setColor(1, 0.8, 0.2, alpha);
// Draw a circle overlay
joy.graphics.circle("fill", x + boxSize/2, y + boxSize/2, boxSize/3);
// Label
joy.graphics.setBlendMode("alpha");
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print(labels[i], x, y + boxSize + 5);
}
// Row 2: Rapid blend mode switching (stress test)
const row2Y = startY + boxSize + 80;
joy.graphics.setBlendMode("alpha");
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Rapid Pipeline Switching:", startX, row2Y - 25);
// Draw many small shapes, each with different blend modes
const modes = ["alpha", "add", "multiply", "alpha", "add"];
for (let i = 0; i < 50; i++) {
const mode = modes[i % modes.length];
joy.graphics.setBlendMode(mode);
const hue = (i / 50 + time * 0.1) % 1;
const r = Math.sin(hue * Math.PI * 2) * 0.5 + 0.5;
const g = Math.sin(hue * Math.PI * 2 + 2.094) * 0.5 + 0.5;
const b = Math.sin(hue * Math.PI * 2 + 4.189) * 0.5 + 0.5;
joy.graphics.setColor(r, g, b, 0.7);
const x = startX + (i % 10) * 70;
const y = row2Y + Math.floor(i / 10) * 30;
joy.graphics.rectangle("fill", x, y, 60, 20);
}
// Row 3: Primitive type switching (triangles, lines, points)
const row3Y = row2Y + 180;
joy.graphics.setBlendMode("alpha");
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Primitive Types:", startX, row3Y - 25);
// Triangles (filled shapes)
joy.graphics.setColor(0.2, 0.8, 0.4, 1);
joy.graphics.rectangle("fill", startX, row3Y, 100, 60);
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Triangles", startX, row3Y + 65);
// Lines
joy.graphics.setColor(0.8, 0.4, 0.2, 1);
joy.graphics.setLineWidth(3);
joy.graphics.rectangle("line", startX + 130, row3Y, 100, 60);
joy.graphics.line(startX + 130, row3Y, startX + 230, row3Y + 60);
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Lines", startX + 130, row3Y + 65);
// Points
joy.graphics.setColor(0.4, 0.4, 0.9, 1);
for (let px = 0; px < 10; px++) {
for (let py = 0; py < 6; py++) {
joy.graphics.point(startX + 270 + px * 10, row3Y + py * 10);
}
}
joy.graphics.setColor(1, 1, 1, 1);
joy.graphics.print("Points", startX + 260, row3Y + 65);
// Stats display
const stats = joy.graphics.getStats();
joy.graphics.setBlendMode("alpha");
joy.graphics.setColor(0.7, 0.7, 0.7, 1);
joy.graphics.print("Draw calls: " + stats.drawCalls + " | Flushes: " + stats.flushes,
startX, height - 30);
joy.graphics.setColor(1, 1, 0, 1);
joy.graphics.print("Dynamic Pipeline Test - Press ESC to exit", startX, height - 55);
};
joy.update = function(dt) {
time += dt;
};
joy.keypressed = function(key) {
if (key === "escape") {
joy.window.close();
}
};
console.log("Dynamic Pipeline Test");
console.log("Tests: blend modes, primitive types, rapid switching");
console.log("Press ESC to exit");
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/points.js
|
JavaScript
|
// Points example
// Demonstrates the three variants of joy.graphics.points()
joy.window.setMode(800, 600);
joy.window.setTitle("Graphics - Points");
joy.graphics.setBackgroundColor(0.1, 0.1, 0.2);
joy.load = function() {
console.log("Points demo - showing three variants");
console.log("Press Escape to exit");
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "escape") {
joy.window.close();
}
};
joy.update = function(dt) {
};
joy.draw = function() {
// Labels
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Variant 1: Varargs", 50, 30);
joy.graphics.print("Variant 2: Flat Array", 300, 30);
joy.graphics.print("Variant 3: Colored Points", 550, 30);
// Variant 1: points(x, y, ...) - varargs
// Draw a simple pattern with current color
joy.graphics.setColor(1, 0.5, 0);
joy.graphics.points(
70, 80,
90, 100,
110, 80,
130, 100,
150, 80,
170, 100,
190, 80
);
// Draw a diagonal line of points
joy.graphics.setColor(0, 1, 0.5);
joy.graphics.points(
70, 150,
85, 165,
100, 180,
115, 195,
130, 210,
145, 225,
160, 240
);
// Variant 2: points([x1, y1, x2, y2, ...]) - flat array
// Draw a sine wave pattern
joy.graphics.setColor(0.5, 0.5, 1);
var flatPoints = [];
for (var i = 0; i < 100; i++) {
var x = 300 + i * 2;
var y = 150 + Math.sin(i * 0.15) * 50;
flatPoints.push(x);
flatPoints.push(y);
}
joy.graphics.points(flatPoints);
// Draw a circle using points
joy.graphics.setColor(1, 1, 0);
var circlePoints = [];
for (var i = 0; i < 60; i++) {
var angle = (i / 60) * Math.PI * 2;
var x = 400 + Math.cos(angle) * 40;
var y = 280 + Math.sin(angle) * 40;
circlePoints.push(x);
circlePoints.push(y);
}
joy.graphics.points(circlePoints);
// Variant 3: points([[x, y, r, g, b, a], ...]) - colored points
// Draw a rainbow gradient
var coloredPoints = [];
for (var i = 0; i < 100; i++) {
var x = 550 + (i % 10) * 20;
var y = 80 + Math.floor(i / 10) * 20;
// Rainbow colors based on position
var hue = i / 100;
var r = Math.abs(Math.sin(hue * Math.PI * 2)) ;
var g = Math.abs(Math.sin((hue + 0.33) * Math.PI * 2));
var b = Math.abs(Math.sin((hue + 0.66) * Math.PI * 2));
coloredPoints.push([x, y, r, g, b, 1]);
}
joy.graphics.points(coloredPoints);
// Draw a colorful spiral
var spiralPoints = [];
for (var i = 0; i < 200; i++) {
var angle = i * 0.1;
var radius = 10 + i * 0.3;
var x = 650 + Math.cos(angle) * radius;
var y = 450 + Math.sin(angle) * radius;
// Color transitions through the spiral
var t = i / 200;
spiralPoints.push([x, y, 1 - t, t, 0.5, 1]);
}
joy.graphics.points(spiralPoints);
// Instructions
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Press ESC to exit", 10, 570);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/primitives.js
|
JavaScript
|
// Primitives example
// Demonstrates polygons, arcs, ellipses, and line width
joy.window.setMode(800, 600);
joy.window.setTitle("Graphics - Primitives");
joy.graphics.setBackgroundColor(0.1, 0.1, 0.2);
var time = 0;
joy.load = function() {
console.log("Primitives demo - polygons, arcs, ellipses, line width");
console.log("Press Escape to exit");
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "escape") {
joy.window.close();
}
};
joy.update = function(dt) {
time += dt;
};
joy.draw = function() {
// === POLYGONS ===
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Polygons", 50, 20);
// Filled triangle
joy.graphics.setColor(1, 0.3, 0.3);
joy.graphics.polygon("fill", 80, 80, 150, 150, 50, 150);
// Outlined pentagon
joy.graphics.setColor(0.3, 1, 0.3);
var cx = 120, cy = 220, r = 40;
joy.graphics.polygon("line",
cx + r * Math.cos(0), cy + r * Math.sin(0),
cx + r * Math.cos(Math.PI * 2 / 5), cy + r * Math.sin(Math.PI * 2 / 5),
cx + r * Math.cos(Math.PI * 4 / 5), cy + r * Math.sin(Math.PI * 4 / 5),
cx + r * Math.cos(Math.PI * 6 / 5), cy + r * Math.sin(Math.PI * 6 / 5),
cx + r * Math.cos(Math.PI * 8 / 5), cy + r * Math.sin(Math.PI * 8 / 5)
);
// Filled hexagon
joy.graphics.setColor(0.3, 0.5, 1);
cx = 120; cy = 320; r = 45;
joy.graphics.polygon("fill",
cx + r * Math.cos(0), cy + r * Math.sin(0),
cx + r * Math.cos(Math.PI / 3), cy + r * Math.sin(Math.PI / 3),
cx + r * Math.cos(Math.PI * 2 / 3), cy + r * Math.sin(Math.PI * 2 / 3),
cx + r * Math.cos(Math.PI), cy + r * Math.sin(Math.PI),
cx + r * Math.cos(Math.PI * 4 / 3), cy + r * Math.sin(Math.PI * 4 / 3),
cx + r * Math.cos(Math.PI * 5 / 3), cy + r * Math.sin(Math.PI * 5 / 3)
);
// === ELLIPSES ===
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Ellipses", 250, 20);
// Filled ellipse
joy.graphics.setColor(1, 0.8, 0.2);
joy.graphics.ellipse("fill", 320, 100, 60, 30);
// Outlined ellipse
joy.graphics.setColor(0.8, 0.2, 1);
joy.graphics.ellipse("line", 320, 180, 40, 60);
// Rotating ellipse
joy.graphics.push();
joy.graphics.translate(320, 280);
joy.graphics.rotate(time);
joy.graphics.setColor(0.2, 1, 0.8);
joy.graphics.ellipse("fill", 0, 0, 50, 20);
joy.graphics.pop();
// === ARCS ===
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Arcs", 480, 20);
// Pie arc (filled)
joy.graphics.setColor(1, 0.5, 0);
joy.graphics.arc("fill", "pie", 520, 100, 50, 0, Math.PI * 1.5, 20);
// Open arc (line)
joy.graphics.setColor(0, 1, 0.5);
joy.graphics.arc("line", "open", 520, 200, 50, Math.PI / 4, Math.PI * 1.25, 20);
// Closed arc (line)
joy.graphics.setColor(0.5, 0.5, 1);
joy.graphics.arc("line", "closed", 520, 300, 50, 0, Math.PI, 20);
// Animated pie chart
var animAngle = (Math.sin(time * 2) + 1) * Math.PI;
joy.graphics.setColor(1, 0.3, 0.5);
joy.graphics.arc("fill", "pie", 520, 400, 45, 0, animAngle, 30);
joy.graphics.setColor(0.3, 0.5, 1);
joy.graphics.arc("fill", "pie", 520, 400, 45, animAngle, Math.PI * 2, 30);
// === LINE WIDTH ===
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Line Width", 650, 20);
// Different line widths
var widths = [1, 2, 4, 6, 8, 10];
for (var i = 0; i < widths.length; i++) {
joy.graphics.setLineWidth(widths[i]);
var hue = i / widths.length;
joy.graphics.setColor(
Math.sin(hue * Math.PI * 2) * 0.5 + 0.5,
Math.sin((hue + 0.33) * Math.PI * 2) * 0.5 + 0.5,
Math.sin((hue + 0.66) * Math.PI * 2) * 0.5 + 0.5
);
joy.graphics.line(650, 60 + i * 30, 780, 60 + i * 30);
}
// Thick circle
joy.graphics.setLineWidth(5);
joy.graphics.setColor(1, 1, 0);
joy.graphics.circle("line", 715, 320, 40);
// Thick rectangle
joy.graphics.setLineWidth(4);
joy.graphics.setColor(0, 1, 1);
joy.graphics.rectangle("line", 660, 380, 110, 60);
// Thick polygon (star)
joy.graphics.setLineWidth(3);
joy.graphics.setColor(1, 0.5, 1);
cx = 715; cy = 520; r = 35;
var innerR = 15;
var starPoints = [];
for (var i = 0; i < 10; i++) {
var angle = (i * Math.PI / 5) - Math.PI / 2;
var rad = (i % 2 === 0) ? r : innerR;
starPoints.push(cx + rad * Math.cos(angle));
starPoints.push(cy + rad * Math.sin(angle));
}
joy.graphics.polygon("line",
starPoints[0], starPoints[1], starPoints[2], starPoints[3],
starPoints[4], starPoints[5], starPoints[6], starPoints[7],
starPoints[8], starPoints[9], starPoints[10], starPoints[11],
starPoints[12], starPoints[13], starPoints[14], starPoints[15],
starPoints[16], starPoints[17], starPoints[18], starPoints[19]
);
// Reset line width
joy.graphics.setLineWidth(1);
// Instructions
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("Press ESC to exit", 10, 570);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
examples/graphics/scissor.js
|
JavaScript
|
// Scissor and Quad example
// Demonstrates clipping regions and texture quads
joy.window.setMode(800, 600);
joy.window.setTitle("Graphics - Scissor & Quad");
joy.graphics.setBackgroundColor(0.15, 0.15, 0.2);
var time = 0;
var image = null;
var quads = [];
joy.load = function() {
console.log("Scissor & Quad demo");
console.log("Press Escape to exit");
// Try to load an image for quad demo
// If no image available, we'll create a procedural texture demo
try {
image = joy.graphics.newImage("assets/player.png");
if (image) {
var w = image.getWidth();
var h = image.getHeight();
// Create quads for a 4x4 grid of the image
var qw = w / 4;
var qh = h / 4;
for (var y = 0; y < 4; y++) {
for (var x = 0; x < 4; x++) {
quads.push(joy.graphics.newQuad(x * qw, y * qh, qw, qh, w, h));
}
}
}
} catch (e) {
console.log("No image loaded, showing scissor demo only");
}
};
joy.keypressed = function(key, scancode, isrepeat) {
if (key === "escape") {
joy.window.close();
}
};
joy.update = function(dt) {
time += dt;
};
joy.draw = function() {
// === SCISSOR DEMO ===
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Scissor Clipping", 50, 20);
// Draw a pattern that will be clipped
// First, show what it looks like without scissor
joy.graphics.setColor(0.3, 0.3, 0.3);
joy.graphics.rectangle("fill", 50, 50, 200, 150);
joy.graphics.setColor(0.5, 0.5, 0.5);
joy.graphics.print("(clipping area)", 90, 115);
// Enable scissor and draw colorful content
joy.graphics.setScissor(50, 50, 200, 150);
// Draw rotating lines that get clipped
joy.graphics.push();
joy.graphics.translate(150, 125);
for (var i = 0; i < 12; i++) {
var angle = time + (i * Math.PI / 6);
var hue = i / 12;
joy.graphics.setColor(
Math.sin(hue * Math.PI * 2) * 0.5 + 0.5,
Math.sin((hue + 0.33) * Math.PI * 2) * 0.5 + 0.5,
Math.sin((hue + 0.66) * Math.PI * 2) * 0.5 + 0.5
);
joy.graphics.setLineWidth(3);
joy.graphics.line(0, 0,
Math.cos(angle) * 150,
Math.sin(angle) * 150
);
}
joy.graphics.pop();
joy.graphics.setLineWidth(1);
// Draw a circle that extends beyond the scissor
joy.graphics.setColor(1, 1, 0, 0.7);
joy.graphics.circle("fill", 150, 125, 80);
// Disable scissor
joy.graphics.setScissor();
// Draw border to show scissor bounds
joy.graphics.setColor(1, 1, 1);
joy.graphics.rectangle("line", 50, 50, 200, 150);
// === ANIMATED SCISSOR ===
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Animated Scissor", 50, 220);
// Animated scissor region
var animWidth = 100 + Math.sin(time * 2) * 50;
var animHeight = 80 + Math.cos(time * 1.5) * 30;
var animX = 100 + Math.sin(time) * 20;
var animY = 280 + Math.cos(time * 0.7) * 20;
// Background
joy.graphics.setColor(0.2, 0.2, 0.3);
joy.graphics.rectangle("fill", 50, 250, 200, 150);
// Scissored content
joy.graphics.setScissor(animX, animY, animWidth, animHeight);
// Draw a grid pattern
for (var y = 250; y < 400; y += 20) {
for (var x = 50; x < 250; x += 20) {
var intensity = ((x + y) / 20) % 2;
if (intensity === 0) {
joy.graphics.setColor(0.8, 0.3, 0.3);
} else {
joy.graphics.setColor(0.3, 0.3, 0.8);
}
joy.graphics.rectangle("fill", x, y, 18, 18);
}
}
joy.graphics.setScissor();
// Show scissor bounds
joy.graphics.setColor(0, 1, 0);
joy.graphics.rectangle("line", animX, animY, animWidth, animHeight);
// === MULTIPLE SCISSOR REGIONS ===
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Multiple Viewports", 300, 20);
// Create 4 viewport-like regions
var viewports = [
{x: 300, y: 50, w: 100, h: 80, color: [1, 0.5, 0.5]},
{x: 410, y: 50, w: 100, h: 80, color: [0.5, 1, 0.5]},
{x: 300, y: 140, w: 100, h: 80, color: [0.5, 0.5, 1]},
{x: 410, y: 140, w: 100, h: 80, color: [1, 1, 0.5]}
];
for (var i = 0; i < viewports.length; i++) {
var vp = viewports[i];
joy.graphics.setScissor(vp.x, vp.y, vp.w, vp.h);
// Background
joy.graphics.setColor(vp.color[0] * 0.3, vp.color[1] * 0.3, vp.color[2] * 0.3);
joy.graphics.rectangle("fill", vp.x, vp.y, vp.w, vp.h);
// Spinning shape (different for each)
joy.graphics.push();
joy.graphics.translate(vp.x + vp.w / 2, vp.y + vp.h / 2);
joy.graphics.rotate(time * (i + 1) * 0.5);
joy.graphics.setColor(vp.color[0], vp.color[1], vp.color[2]);
if (i === 0) {
joy.graphics.rectangle("fill", -30, -30, 60, 60);
} else if (i === 1) {
joy.graphics.circle("fill", 0, 0, 35);
} else if (i === 2) {
joy.graphics.ellipse("fill", 0, 0, 40, 25);
} else {
joy.graphics.polygon("fill", 0, -35, 30, 20, -30, 20);
}
joy.graphics.pop();
joy.graphics.setScissor();
// Border
joy.graphics.setColor(1, 1, 1);
joy.graphics.rectangle("line", vp.x, vp.y, vp.w, vp.h);
}
// === QUAD DEMO ===
joy.graphics.setColor(1, 1, 1);
joy.graphics.print("Quad (Texture Regions)", 300, 250);
if (image && quads.length > 0) {
// Draw different quads from the image
for (var i = 0; i < quads.length && i < 8; i++) {
var qx = 300 + (i % 4) * 55;
var qy = 280 + Math.floor(i / 4) * 55;
joy.graphics.setColor(1, 1, 1);
joy.graphics.draw(image, quads[i], qx, qy);
}
} else {
// Show quad concept without image
joy.graphics.setColor(0.5, 0.5, 0.5);
joy.graphics.print("(Load an image to see quads)", 300, 280);
// Demo quad creation syntax
joy.graphics.setColor(0.7, 0.7, 0.7);
joy.graphics.print("quad = joy.graphics.newQuad(", 300, 310);
joy.graphics.print(" x, y, w, h, imgW, imgH)", 300, 330);
joy.graphics.print("joy.graphics.draw(img, quad, x, y)", 300, 360);
}
// === INFO ===
joy.graphics.setColor(0.7, 0.7, 0.7);
var scissorInfo = joy.graphics.getScissor();
if (scissorInfo) {
joy.graphics.print("Current scissor: " + scissorInfo.join(", "), 300, 420);
} else {
joy.graphics.print("Scissor: disabled", 300, 420);
}
// Instructions
joy.graphics.print("Press ESC to exit", 10, 570);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.