@crossberryweb/mozhi 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ 'use strict';
2
+ /*
3
+ * Mozhi package manager — `mz pkg new` scaffolding.
4
+ *
5
+ * Creates a ready-to-publish package: manifest, entry module, example,
6
+ * test, README, MIT license, .gitattributes (keeps CI out of the release
7
+ * zip) and a GitHub Actions workflow that automatically attaches
8
+ * <name>.mz.pkg.zip to the release whenever a v* tag is pushed.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ function renderReleaseWorkflow(pkgName) {
15
+ return `name: Release
16
+
17
+ # Automatic package release: pushing a tag like v1.0.0 builds
18
+ # ${pkgName}.mz.pkg.zip and attaches it to a GitHub release.
19
+ # 'mz install @<owner>/<repo>' downloads exactly this asset.
20
+
21
+ on:
22
+ push:
23
+ tags: ['v*']
24
+
25
+ permissions:
26
+ contents: write
27
+
28
+ jobs:
29
+ release:
30
+ runs-on: ubuntu-latest
31
+ steps:
32
+ - uses: actions/checkout@v4
33
+
34
+ - name: Read package metadata
35
+ id: meta
36
+ run: |
37
+ NAME=$(sed -n 's/^name[[:space:]]*=[[:space:]]*"\\([^"]*\\)".*/\\1/p' package.toml | head -1)
38
+ VERSION=$(sed -n 's/^version[[:space:]]*=[[:space:]]*"\\([^"]*\\)".*/\\1/p' package.toml | head -1)
39
+ if [ -z "$NAME" ] || [ -z "$VERSION" ]; then
40
+ echo "package.toml must define name and version" >&2
41
+ exit 1
42
+ fi
43
+ if [ "\${GITHUB_REF_NAME#v}" != "$VERSION" ]; then
44
+ echo "tag \${GITHUB_REF_NAME} does not match package.toml version $VERSION" >&2
45
+ exit 1
46
+ fi
47
+ echo "name=$NAME" >> "$GITHUB_OUTPUT"
48
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
49
+
50
+ - name: Verify package structure
51
+ run: |
52
+ test -f package.toml
53
+ test -f src/mod.mz
54
+ echo "package structure OK: \${{ steps.meta.outputs.name }} v\${{ steps.meta.outputs.version }}"
55
+
56
+ - name: Build ${pkgName}.mz.pkg.zip
57
+ run: |
58
+ # git archive respects .gitattributes export-ignore, so .github/
59
+ # never lands in the package zip. The zip contains a single
60
+ # top-level directory named after the package.
61
+ git archive --format=zip --prefix="\${{ steps.meta.outputs.name }}/" \\
62
+ -o "\${{ steps.meta.outputs.name }}.mz.pkg.zip" HEAD
63
+ unzip -l "\${{ steps.meta.outputs.name }}.mz.pkg.zip"
64
+
65
+ - name: Create release
66
+ env:
67
+ GH_TOKEN: \${{ github.token }}
68
+ run: |
69
+ gh release create "\${{ github.ref_name }}" \\
70
+ "\${{ steps.meta.outputs.name }}.mz.pkg.zip" \\
71
+ --repo "\${{ github.repository }}" \\
72
+ --title "\${{ steps.meta.outputs.name }} \${{ github.ref_name }}" \\
73
+ --generate-notes
74
+ `;
75
+ }
76
+
77
+ function scaffold(name, dir) {
78
+ if (!/^[a-z][a-z0-9_-]*$/i.test(name)) {
79
+ throw new Error('invalid package name "' + name + '" — use letters, digits, - and _ (starting with a letter)');
80
+ }
81
+ const root = path.resolve(dir || name);
82
+ if (fs.existsSync(root) && fs.readdirSync(root).length) {
83
+ throw new Error('directory not empty: ' + root);
84
+ }
85
+ const year = new Date().getFullYear();
86
+ const files = new Map([
87
+ ['package.toml', `# ${name} — Mozhi package manifest
88
+ [package]
89
+ name = "${name}"
90
+ version = "0.1.0"
91
+ description = "TODO: one-line description of ${name}"
92
+ license = "MIT"
93
+ category = "general"
94
+ edition = "2024"
95
+
96
+ [module]
97
+ # The file the interpreter loads for 'import ${name}'.
98
+ entry = "src/mod.mz"
99
+ `],
100
+ ['src/mod.mz', `# ${name} v0.1.0 — entry module
101
+ #
102
+ # Everything defined here is exposed on the module object:
103
+ # import ${name}
104
+ # ${name}.hello("world")
105
+
106
+ fn hello(who) {
107
+ return "hello, " + who + "!"
108
+ }
109
+
110
+ fn version() {
111
+ return "0.1.0"
112
+ }
113
+ `],
114
+ ['examples/demo.mz', `# Run with: mozhi run examples/demo.mz
115
+ import ${name}
116
+
117
+ echo(${name}.hello("Mozhi"))
118
+ echo("version: " + ${name}.version())
119
+ `],
120
+ ['tests/' + name + '.test.mz', `# Run with: mozhi test
121
+ import ${name} from "../src/mod.mz"
122
+
123
+ assert_eq(${name}.hello("x"), "hello, x!")
124
+ assert_eq(${name}.version(), "0.1.0")
125
+ echo("tests/${name}: all assertions passed")
126
+ `],
127
+ ['README.md', `# ${name}
128
+
129
+ TODO: description.
130
+
131
+ ## Install
132
+
133
+ \`\`\`bash
134
+ mz install @<your-github-username>/${name}
135
+ \`\`\`
136
+
137
+ ## Usage
138
+
139
+ \`\`\`mozhi
140
+ import ${name}
141
+
142
+ echo(${name}.hello("Mozhi"))
143
+ \`\`\`
144
+
145
+ ## Develop
146
+
147
+ \`\`\`bash
148
+ mozhi test # run tests/
149
+ mozhi run examples/demo.mz
150
+ mz pkg check # verify package structure
151
+ mz pkg zip # build ${name}.mz.pkg.zip locally
152
+ \`\`\`
153
+
154
+ ## Release
155
+
156
+ \`\`\`bash
157
+ # 1. set the version in package.toml
158
+ # 2. commit and tag — GitHub Actions builds the release zip automatically
159
+ git commit -am "release 0.1.0"
160
+ git tag v0.1.0
161
+ git push origin main v0.1.0
162
+ \`\`\`
163
+ `],
164
+ ['LICENSE', `MIT License
165
+
166
+ Copyright (c) ${year} ${name} authors
167
+
168
+ Permission is hereby granted, free of charge, to any person obtaining a copy
169
+ of this software and associated documentation files (the "Software"), to deal
170
+ in the Software without restriction, including without limitation the rights
171
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
172
+ copies of the Software, and to permit persons to whom the Software is
173
+ furnished to do so, subject to the following conditions:
174
+
175
+ The above copyright notice and this permission notice shall be included in all
176
+ copies or substantial portions of the Software.
177
+
178
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
179
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
180
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
181
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
182
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
183
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
184
+ SOFTWARE.
185
+ `],
186
+ ['.gitignore', '*.mz.pkg.zip\n.mozhi/\n'],
187
+ ['.gitattributes', '# keep CI configuration out of release zips\n.github export-ignore\n'],
188
+ ['.github/workflows/release.yml', renderReleaseWorkflow(name)],
189
+ ]);
190
+
191
+ for (const [rel, content] of files) {
192
+ const target = path.join(root, rel);
193
+ fs.mkdirSync(path.dirname(target), { recursive: true });
194
+ fs.writeFileSync(target, content);
195
+ }
196
+ return { root, files: files.size };
197
+ }
198
+
199
+ module.exports = { scaffold, renderReleaseWorkflow };
package/lib/zip.js ADDED
@@ -0,0 +1,239 @@
1
+ 'use strict';
2
+ /*
3
+ * Mozhi package manager — minimal ZIP reader/writer (no dependencies).
4
+ *
5
+ * Reader: parses the End of Central Directory + central directory, then
6
+ * inflates entries. Only methods 0 (stored) and 8 (deflate) are accepted —
7
+ * exactly what `git archive`, `zip` and this writer produce.
8
+ *
9
+ * Security: entry names are validated against path traversal ("..",
10
+ * absolute paths, drive letters) before extraction, and total output size
11
+ * is capped (zip-bomb guard).
12
+ */
13
+
14
+ const zlib = require('zlib');
15
+
16
+ const LIMITS = {
17
+ maxEntries: 4096,
18
+ maxFileBytes: 64 * 1024 * 1024,
19
+ maxTotalBytes: 128 * 1024 * 1024,
20
+ };
21
+
22
+ function crc32(buf) {
23
+ if (typeof zlib.crc32 === 'function') return zlib.crc32(buf) >>> 0;
24
+ // Fallback table-based CRC-32 (IEEE) for Node builds without zlib.crc32.
25
+ let table = crc32._table;
26
+ if (!table) {
27
+ table = crc32._table = new Int32Array(256);
28
+ for (let n = 0; n < 256; n++) {
29
+ let c = n;
30
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
31
+ table[n] = c;
32
+ }
33
+ }
34
+ let c = -1;
35
+ for (let i = 0; i < buf.length; i++) c = (c >>> 8) ^ table[(c ^ buf[i]) & 0xFF];
36
+ return (c ^ -1) >>> 0;
37
+ }
38
+
39
+ /* Reject unsafe entry names. Returns normalized forward-slash name or throws. */
40
+ function safeEntryName(name) {
41
+ let n = String(name).replace(/\\/g, '/');
42
+ if (/^[A-Za-z]:/.test(n)) throw new Error('unsafe zip entry (drive path): ' + name);
43
+ if (n.startsWith('/')) throw new Error('unsafe zip entry (absolute path): ' + name);
44
+ if (n.includes('\0')) throw new Error('unsafe zip entry (NUL byte)');
45
+ const parts = n.split('/').filter((p) => p.length && p !== '.');
46
+ for (const p of parts) {
47
+ if (p === '..') throw new Error('unsafe zip entry (traversal): ' + name);
48
+ }
49
+ return parts.join('/');
50
+ }
51
+
52
+ /* Find the End Of Central Directory record. Returns {count, cdSize, cdOffset}. */
53
+ function findEOCD(buf) {
54
+ const minEOCD = 22;
55
+ const scanWindow = Math.min(buf.length, 22 + 0xFFFF);
56
+ const start = buf.length - minEOCD;
57
+ for (let i = start; i >= buf.length - scanWindow; i--) {
58
+ if (buf[i] === 0x50 && buf[i + 1] === 0x4b && buf[i + 2] === 0x05 && buf[i + 3] === 0x06) {
59
+ const count = buf.readUInt16LE(i + 10);
60
+ const cdSize = buf.readUInt32LE(i + 12);
61
+ let cdOffset = buf.readUInt32LE(i + 16);
62
+ // ZIP64 marker: 0xFFFFFFFF means real values live in a ZIP64 EOCD locator.
63
+ if (cdOffset === 0xFFFFFFFF || cdSize === 0xFFFFFFFF || count === 0xFFFF) {
64
+ throw new Error('ZIP64 archives are not supported');
65
+ }
66
+ return { count, cdSize, cdOffset };
67
+ }
68
+ }
69
+ throw new Error('not a ZIP archive (no end-of-central-directory record)');
70
+ }
71
+
72
+ /* List central directory entries. */
73
+ function readCentralDirectory(buf) {
74
+ const eocd = findEOCD(buf);
75
+ const entries = [];
76
+ let p = eocd.cdOffset;
77
+ const end = eocd.cdOffset + eocd.cdSize;
78
+ let n = 0;
79
+ while (p + 46 <= end && n < eocd.count) {
80
+ if (!(buf[p] === 0x50 && buf[p + 1] === 0x4b && buf[p + 2] === 0x01 && buf[p + 3] === 0x02)) {
81
+ throw new Error('corrupt ZIP central directory at offset ' + p);
82
+ }
83
+ const flags = buf.readUInt16LE(p + 8);
84
+ const method = buf.readUInt16LE(p + 10);
85
+ const crc = buf.readUInt32LE(p + 16);
86
+ const compressedSize = buf.readUInt32LE(p + 20);
87
+ const size = buf.readUInt32LE(p + 24);
88
+ const nameLen = buf.readUInt16LE(p + 28);
89
+ const extraLen = buf.readUInt16LE(p + 30);
90
+ const commentLen = buf.readUInt16LE(p + 32);
91
+ const localOffset = buf.readUInt32LE(p + 42);
92
+ const name = buf.slice(p + 46, p + 46 + nameLen).toString('utf8');
93
+
94
+ // data offset comes from the LOCAL header (its name/extra lengths may differ)
95
+ if (!(buf[localOffset] === 0x50 && buf[localOffset + 1] === 0x4b && buf[localOffset + 2] === 0x03 && buf[localOffset + 3] === 0x04)) {
96
+ throw new Error('corrupt ZIP local header for entry ' + name);
97
+ }
98
+ const lNameLen = buf.readUInt16LE(localOffset + 26);
99
+ const lExtraLen = buf.readUInt16LE(localOffset + 28);
100
+ const dataOffset = localOffset + 30 + lNameLen + lExtraLen;
101
+
102
+ entries.push({
103
+ name,
104
+ flags,
105
+ method,
106
+ crc,
107
+ compressedSize,
108
+ size,
109
+ dataOffset,
110
+ dir: name.endsWith('/'),
111
+ });
112
+ p += 46 + nameLen + extraLen + commentLen;
113
+ n++;
114
+ }
115
+ return entries;
116
+ }
117
+
118
+ /* Extract one entry to a Buffer (decompressed, CRC-verified). */
119
+ function extractEntry(buf, entry) {
120
+ if (entry.dir) return Buffer.alloc(0);
121
+ if (entry.size > LIMITS.maxFileBytes) {
122
+ throw new Error('zip entry too large: ' + entry.name);
123
+ }
124
+ const raw = buf.slice(entry.dataOffset, entry.dataOffset + entry.compressedSize);
125
+ let out;
126
+ if (entry.method === 0) {
127
+ out = Buffer.from(raw);
128
+ } else if (entry.method === 8) {
129
+ out = zlib.inflateRawSync(raw, { maxOutputLength: LIMITS.maxFileBytes });
130
+ } else {
131
+ throw new Error('unsupported zip compression method ' + entry.method + ' for ' + entry.name);
132
+ }
133
+ if (out.length !== entry.size) {
134
+ throw new Error('zip entry size mismatch for ' + entry.name);
135
+ }
136
+ if (entry.crc && crc32(out) !== entry.crc) {
137
+ throw new Error('zip entry CRC mismatch for ' + entry.name);
138
+ }
139
+ return out;
140
+ }
141
+
142
+ /* Read a zip Buffer → Map<safeName, Buffer> (directories omitted). */
143
+ function readZip(buf) {
144
+ const entries = readCentralDirectory(buf);
145
+ if (entries.length > LIMITS.maxEntries) throw new Error('zip has too many entries');
146
+ const files = new Map();
147
+ let total = 0;
148
+ for (const e of entries) {
149
+ if (e.dir) continue;
150
+ const name = safeEntryName(e.name);
151
+ if (!name) continue;
152
+ const data = extractEntry(buf, e);
153
+ total += data.length;
154
+ if (total > LIMITS.maxTotalBytes) throw new Error('zip expands beyond ' + (LIMITS.maxTotalBytes / 1024 / 1024) + 'MB');
155
+ files.set(name, data);
156
+ }
157
+ return files;
158
+ }
159
+
160
+ /* ------------------------------------------------------------------ */
161
+ /* writer */
162
+ /* ------------------------------------------------------------------ */
163
+
164
+ function dosDateTime(d) {
165
+ const time = ((d.getHours() & 0x1f) << 11) | ((d.getMinutes() & 0x3f) << 5) | ((Math.floor(d.getSeconds() / 2)) & 0x1f);
166
+ const date = (((d.getFullYear() - 1980) & 0x7f) << 9) | (((d.getMonth() + 1) & 0x0f) << 5) | (d.getDate() & 0x1f);
167
+ return { time, date };
168
+ }
169
+
170
+ /* Build a zip archive from Map<name(string, forward slashes), Buffer>. */
171
+ function writeZip(files) {
172
+ const chunks = [];
173
+ const central = [];
174
+ const now = dosDateTime(new Date());
175
+ let offset = 0;
176
+
177
+ const names = Array.from(files.keys()).sort();
178
+ for (const name of names) {
179
+ const safe = safeEntryName(name);
180
+ if (!safe) throw new Error('invalid entry name: ' + name);
181
+ const data = files.get(name);
182
+ const compressed = zlib.deflateRawSync(data, { level: 6 });
183
+ const useDeflate = compressed.length < data.length;
184
+ const body = useDeflate ? compressed : data;
185
+ const method = useDeflate ? 8 : 0;
186
+ const crc = crc32(data);
187
+
188
+ const local = Buffer.alloc(30);
189
+ local.writeUInt32LE(0x04034b50, 0);
190
+ local.writeUInt16LE(20, 4); // version needed
191
+ local.writeUInt16LE(0x0800, 6); // UTF-8 names flag
192
+ local.writeUInt16LE(method, 8);
193
+ local.writeUInt16LE(now.time, 10);
194
+ local.writeUInt16LE(now.date, 12);
195
+ local.writeUInt32LE(crc, 14);
196
+ local.writeUInt32LE(body.length, 18);
197
+ local.writeUInt32LE(data.length, 22);
198
+ const nameBuf = Buffer.from(safe, 'utf8');
199
+ local.writeUInt16LE(nameBuf.length, 26);
200
+ local.writeUInt16LE(0, 28);
201
+
202
+ chunks.push(local, nameBuf, body);
203
+
204
+ const cen = Buffer.alloc(46);
205
+ cen.writeUInt32LE(0x02014b50, 0);
206
+ cen.writeUInt16LE(0x031e, 4); // made by unix, zip 3.0
207
+ cen.writeUInt16LE(20, 6);
208
+ cen.writeUInt16LE(0x0800, 8);
209
+ cen.writeUInt16LE(method, 10);
210
+ cen.writeUInt16LE(now.time, 12);
211
+ cen.writeUInt16LE(now.date, 14);
212
+ cen.writeUInt32LE(crc, 16);
213
+ cen.writeUInt32LE(body.length, 20);
214
+ cen.writeUInt32LE(data.length, 24);
215
+ cen.writeUInt16LE(nameBuf.length, 28);
216
+ cen.writeUInt16LE(0, 30); // extra
217
+ cen.writeUInt16LE(0, 32); // comment
218
+ cen.writeUInt16LE(0, 34); // disk
219
+ cen.writeUInt16LE(0, 36); // internal attrs
220
+ cen.writeUInt32LE(0x81a40000, 38); // external attrs: 0644 regular file
221
+ cen.writeUInt32LE(offset, 42);
222
+ central.push(Buffer.concat([cen, nameBuf]));
223
+
224
+ offset += local.length + nameBuf.length + body.length;
225
+ }
226
+
227
+ const cdBuf = Buffer.concat(central);
228
+ const eocd = Buffer.alloc(22);
229
+ eocd.writeUInt32LE(0x06054b50, 0);
230
+ eocd.writeUInt16LE(0, 8);
231
+ eocd.writeUInt16LE(names.length, 10);
232
+ eocd.writeUInt32LE(cdBuf.length, 12);
233
+ eocd.writeUInt32LE(offset, 16);
234
+ eocd.writeUInt16LE(0, 20);
235
+
236
+ return Buffer.concat([...chunks, cdBuf, eocd]);
237
+ }
238
+
239
+ module.exports = { readZip, writeZip, crc32, safeEntryName, LIMITS };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crossberryweb/mozhi",
3
- "version": "3.2.0",
4
- "description": "Mozhi programming language interpreter — native web, JSON, fs, math, SQLite, templates. Install once, get both commands: `mozhi` and the short alias `mz` (identical behavior).",
3
+ "version": "3.3.0",
4
+ "description": "Mozhi programming language interpreter \u2014 native web, JSON, fs, math, SQLite, templates \u2014 with the built-in package manager (`mz install`). Install once, get both commands: `mozhi` and the short alias `mz` (identical behavior).",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -13,7 +13,9 @@
13
13
  "language",
14
14
  "interpreter",
15
15
  "web",
16
- "fullstack"
16
+ "fullstack",
17
+ "package-manager",
18
+ "mz"
17
19
  ],
18
20
  "bin": {
19
21
  "mozhi": "bin/mozhi.js",
@@ -21,11 +23,13 @@
21
23
  },
22
24
  "files": [
23
25
  "bin/",
26
+ "lib/",
27
+ "registry.json",
24
28
  "checksums-sha256.txt",
25
29
  "README.md",
26
30
  "LICENSE"
27
31
  ],
28
32
  "engines": {
29
- "node": ">=14"
33
+ "node": ">=22"
30
34
  }
31
35
  }