@hakubase/cli 0.0.0-stage → 0.2.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.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @hakubase/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The command line of Hakubase **code sites**: link a project to its site, generate the types of the CMS collections, develop against real data, deploy.
4
+
5
+ ```bash
6
+ npm i -D @hakubase/cli
7
+ ```
8
+
9
+ ## Link
10
+
11
+ Create a **development key** in the site's settings (tab *Settings*, *Keys*), then:
12
+
13
+ ```bash
14
+ npx hakubase link https://noesis.hakubase.com <site-id> --key hb_…
15
+ ```
16
+
17
+ It writes `.hakubase/project.json` (addresses only, safe to commit) and puts the key in `.env.local` as `HAKUBASE_KEY`, adding `.env.local` to `.gitignore` when the project has one. The key is never printed whole.
18
+
19
+ The key is read from `--key`, then the `HAKUBASE_KEY` variable, then `.env.local`.
20
+
21
+ ## Types
22
+
23
+ ```bash
24
+ npx hakubase types # writes hakubase.d.ts
25
+ npx hakubase types --out src/hakubase.d.ts
26
+ ```
27
+
28
+ `hb.cms.list('articles')` from `@hakubase/sdk` then returns items whose `values` carry the collection's fields. Run it again when the collections change.
29
+
30
+ ## Develop
31
+
32
+ The plugin forwards `/_data`, `/_fn`, `/_m` and `/_hb` from the dev server to the real site and adds the key on the way: the browser sees one origin, the key never reaches the bundle.
33
+
34
+ ```js
35
+ // vite.config.js
36
+ import { defineConfig } from 'vite'
37
+ import hakubase from '@hakubase/cli/vite'
38
+
39
+ export default defineConfig({ plugins: [hakubase()] })
40
+ ```
41
+
42
+ ```js
43
+ // astro.config.mjs
44
+ import { defineConfig } from 'astro/config'
45
+ import hakubase from '@hakubase/cli/astro'
46
+
47
+ export default defineConfig({ integrations: [hakubase()] })
48
+ ```
49
+
50
+ With the development key the CMS also returns drafts, and form submits are tests: same answers, no lead. `hb.init({ mode: 'live' })` makes them real.
51
+
52
+ ## Deploy
53
+
54
+ ```bash
55
+ npm run build
56
+ npx hakubase deploy # dist, build or out
57
+ npx hakubase deploy dist --publish --message "New home"
58
+ npx hakubase publish 12 # put an uploaded version online
59
+ ```
60
+
61
+ `deploy` sends the list of the folder's files with their fingerprints, uploads only the ones Hakubase does not have yet (in groups, up to 500 MB per site and 10 MB per file, videos included), reads `hakubase.json` from the folder or the project root, and closes a new version. Without `--publish` the version stays in preview and the command prints its preview link; with it, the version goes online.
62
+
63
+ Deploying needs a **publishing key**.
64
+
65
+ ## GitHub
66
+
67
+ Put the publishing key in the repository secrets as `HAKUBASE_KEY` and add `.github/workflows/hakubase.yml`:
68
+
69
+ ```yaml
70
+ name: Hakubase
71
+ on: { push: { branches: [main] } }
72
+ jobs:
73
+ deploy:
74
+ runs-on: ubuntu-latest
75
+ steps:
76
+ - uses: actions/checkout@v4
77
+ - uses: actions/setup-node@v4
78
+ with: { node-version: 22 }
79
+ - run: npm ci
80
+ - run: npm run build
81
+ - run: npx @hakubase/cli deploy --publish
82
+ env:
83
+ HAKUBASE_KEY: "${{ secrets.HAKUBASE_KEY }}"
84
+ HAKUBASE_API: "https://noesis.hakubase.com"
85
+ HAKUBASE_SITE: "<site-id>"
86
+ ```
87
+
88
+ `HAKUBASE_API` and `HAKUBASE_SITE` stand in for `.hakubase/project.json` and win over it. On GitHub the version records the commit and its message.
89
+
90
+ ## Commands
91
+
92
+ | Command | What it does |
93
+ |---|---|
94
+ | `hakubase link <workspace-url> <site-id> [--key hb_…]` | Links the folder to a code site |
95
+ | `hakubase types [--out file]` | Writes the TypeScript types of the collections |
96
+ | `hakubase deploy [dir] [--publish] [--message m] [--commit sha] [--via cli\|github]` | Uploads the built folder as a new version |
97
+ | `hakubase publish <number>` | Puts a version online |
98
+ | `hakubase help` | Shows the usage |
99
+
100
+ On an error the command prints the server's answer and exits with code 1.
101
+
102
+ ## License
103
+
104
+ MIT
package/astro.js ADDED
@@ -0,0 +1,16 @@
1
+ // The Astro integration of @hakubase/cli: the Vite plugin, wired in.
2
+
3
+ import hakubaseVite from './vite.js'
4
+
5
+ export default function hakubase(options = {}) {
6
+ return {
7
+ name: '@hakubase/cli',
8
+ hooks: {
9
+ 'astro:config:setup': ({ updateConfig }) => {
10
+ updateConfig({ vite: { plugins: [hakubaseVite(options)] } })
11
+ },
12
+ },
13
+ }
14
+ }
15
+
16
+ export { hakubase }
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../lib/commands.js'
3
+ import { installLocalhostResolver } from '../lib/localhost.js'
4
+
5
+ installLocalhostResolver()
6
+
7
+ main(process.argv.slice(2)).then(
8
+ (code) => { process.exitCode = code },
9
+ (error) => {
10
+ process.stderr.write(`${error && error.stack ? error.stack : error}\n`)
11
+ process.exitCode = 1
12
+ },
13
+ )
@@ -0,0 +1,335 @@
1
+ // The commands of `hakubase`. Each one returns its exit code; output
2
+ // goes through `io` so the tests can read it.
3
+
4
+ import { execFileSync } from 'node:child_process'
5
+ import crypto from 'node:crypto'
6
+ import fs from 'node:fs'
7
+ import path from 'node:path'
8
+
9
+ import {
10
+ ensureGitignored, findRoot, maskKey, readProject, resolveKey, writeEnvKey, writeProject,
11
+ } from './project.js'
12
+ import { generateTypes } from './types.js'
13
+
14
+ // One request carries at most this much: the server takes 32 MB per upload.
15
+ export const BATCH_BYTES = 24 * 1024 * 1024
16
+ export const BATCH_FILES = 200
17
+ export const BUILD_DIRS = ['dist', 'build', 'out']
18
+ // What an operating system leaves in a folder, never part of a site.
19
+ const JUNK = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini'])
20
+
21
+ export class CliError extends Error {}
22
+
23
+ export const USAGE = `Usage: hakubase <command> [options]
24
+
25
+ Commands:
26
+ link <workspace-url> <site-id> [--key hb_…] Link this folder to a code site
27
+ types [--out hakubase.d.ts] Write the TypeScript types of the collections
28
+ deploy [dir] [--publish] [--message m] Upload the built folder as a new version
29
+ [--commit sha] [--via cli|github] (dir: dist, build or out by default)
30
+ publish <number> Put a version online
31
+ help Show this help
32
+
33
+ The key comes from --key, the HAKUBASE_KEY variable or .env.local.
34
+ Without .hakubase/project.json (in CI), HAKUBASE_API and HAKUBASE_SITE say where to deploy.
35
+ `
36
+
37
+ export function parseArgs(argv) {
38
+ const positional = []
39
+ const flags = {}
40
+ for (let i = 0; i < argv.length; i++) {
41
+ const arg = argv[i]
42
+ if (arg === '--') {
43
+ positional.push(...argv.slice(i + 1))
44
+ break
45
+ }
46
+ if (arg.startsWith('--')) {
47
+ const eq = arg.indexOf('=')
48
+ if (eq > 0) {
49
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1)
50
+ } else {
51
+ const name = arg.slice(2)
52
+ const next = argv[i + 1]
53
+ if (['publish', 'help'].includes(name) || next === undefined || next.startsWith('--')) {
54
+ flags[name] = true
55
+ } else {
56
+ flags[name] = next
57
+ i++
58
+ }
59
+ }
60
+ } else if (arg === '-h') {
61
+ flags.help = true
62
+ } else {
63
+ positional.push(arg)
64
+ }
65
+ }
66
+ return { positional, flags }
67
+ }
68
+
69
+ /** `noesis.hakubase.com`, `https://noesis.hakubase.com/app` → `https://noesis.hakubase.com`. */
70
+ export function workspaceOrigin(value) {
71
+ const raw = String(value || '').trim()
72
+ if (!raw) throw new CliError('Say the address of the workspace, e.g. https://noesis.hakubase.com.')
73
+ try {
74
+ return new URL(/^https?:\/\//i.test(raw) ? raw : `https://${raw}`).origin
75
+ } catch {
76
+ throw new CliError(`${raw} is not an address.`)
77
+ }
78
+ }
79
+
80
+ function detailOf(body, status) {
81
+ if (body && typeof body === 'object') {
82
+ const detail = body.detail ?? body.error ?? body.message
83
+ if (Array.isArray(detail)) {
84
+ return detail.map((d) => (d && d.msg ? `${(d.loc || []).slice(1).join('.')}: ${d.msg}` : String(d))).join('; ')
85
+ }
86
+ if (detail) return String(detail)
87
+ }
88
+ if (typeof body === 'string' && body.trim()) return body.trim().slice(0, 300)
89
+ return `HTTP ${status}`
90
+ }
91
+
92
+ export async function request(ctx, method, url, { key, body, json } = {}) {
93
+ const headers = { accept: 'application/json', 'user-agent': 'hakubase-cli' }
94
+ if (key) headers.authorization = `Bearer ${key}`
95
+ if (json !== undefined) {
96
+ headers['content-type'] = 'application/json'
97
+ body = JSON.stringify(json)
98
+ }
99
+ let response
100
+ try {
101
+ response = await ctx.fetch(url, { method, headers, body })
102
+ } catch (error) {
103
+ throw new CliError(`Could not reach ${new URL(url).origin}: ${error.cause?.message || error.message}`)
104
+ }
105
+ const text = await response.text()
106
+ let parsed = text
107
+ try {
108
+ parsed = text ? JSON.parse(text) : null
109
+ } catch {
110
+ parsed = text
111
+ }
112
+ if (!response.ok) throw new CliError(detailOf(parsed, response.status))
113
+ return parsed
114
+ }
115
+
116
+ /** Where to talk and with which key: project.json, overridden by HAKUBASE_API and HAKUBASE_SITE. */
117
+ export function target(ctx, flags) {
118
+ const root = findRoot(ctx.cwd) || ctx.cwd
119
+ const project = readProject(root) || {}
120
+ const api = ctx.env.HAKUBASE_API ? workspaceOrigin(ctx.env.HAKUBASE_API) : project.api
121
+ const site = ctx.env.HAKUBASE_SITE || project.site_id
122
+ if (!api || !site) {
123
+ throw new CliError('This folder is not linked: run `hakubase link <workspace-url> <site-id>`, or set HAKUBASE_API and HAKUBASE_SITE.')
124
+ }
125
+ const key = resolveKey(root, typeof flags.key === 'string' ? flags.key : '', ctx.env)
126
+ if (!key) throw new CliError('No key: pass --key, set HAKUBASE_KEY or run `hakubase link` with --key.')
127
+ return { root, api, site, key, siteUrl: project.site_url || '' }
128
+ }
129
+
130
+ export async function link(ctx, positional, flags) {
131
+ const [workspace, siteId] = positional
132
+ if (!workspace || !siteId) throw new CliError('Usage: hakubase link <workspace-url> <site-id> [--key hb_…]')
133
+ const api = workspaceOrigin(workspace)
134
+ const root = ctx.cwd
135
+ const given = typeof flags.key === 'string' ? flags.key : ''
136
+ const key = resolveKey(root, given, ctx.env)
137
+ if (!key) throw new CliError('No key: pass --key hb_… (a development or publishing key of this site).')
138
+ const info = await request(ctx, 'GET', `${api}/api/sites/${encodeURIComponent(siteId)}/code-site`, { key })
139
+ writeProject(root, { api, site_id: info.id || siteId, site_url: info.url || '' })
140
+ if (given) writeEnvKey(root, given)
141
+ ensureGitignored(root)
142
+ const where = given ? ` Key ${maskKey(given)} in .env.local.` : ''
143
+ ctx.out(`Linked to ${info.name || siteId} (${info.url || api}).${where}`)
144
+ return 0
145
+ }
146
+
147
+ export async function types(ctx, positional, flags) {
148
+ const t = target(ctx, flags)
149
+ const collections = await request(ctx, 'GET', `${t.api}/api/sites/${encodeURIComponent(t.site)}/collections`, { key: t.key })
150
+ const out = path.resolve(ctx.cwd, typeof flags.out === 'string' ? flags.out : 'hakubase.d.ts')
151
+ fs.writeFileSync(out, generateTypes(Array.isArray(collections) ? collections : []))
152
+ const count = (Array.isArray(collections) ? collections : []).filter((c) => c.kind !== 'members').length
153
+ ctx.out(`Types of ${count} ${count === 1 ? 'collection' : 'collections'} written to ${path.relative(ctx.cwd, out) || out}.`)
154
+ return 0
155
+ }
156
+
157
+ /** The folder to deploy: the one given, or the first of dist, build, out that exists. */
158
+ export function buildDir(cwd, given) {
159
+ if (given) {
160
+ const dir = path.resolve(cwd, given)
161
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new CliError(`${given} is not a folder.`)
162
+ return dir
163
+ }
164
+ for (const name of BUILD_DIRS) {
165
+ const dir = path.resolve(cwd, name)
166
+ if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) return dir
167
+ }
168
+ throw new CliError('No built folder: build the site first, or say which folder to deploy (dist, build, out).')
169
+ }
170
+
171
+ /** Every file of the folder, with forward-slash names. */
172
+ export function collectFiles(dir) {
173
+ const entries = []
174
+ const walk = (current, prefix) => {
175
+ for (const dirent of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
176
+ if (JUNK.has(dirent.name)) continue
177
+ const full = path.join(current, dirent.name)
178
+ const name = prefix ? `${prefix}/${dirent.name}` : dirent.name
179
+ if (dirent.isSymbolicLink()) throw new CliError(`${name} is a symbolic link: Hakubase takes files only.`)
180
+ if (dirent.isDirectory()) walk(full, name)
181
+ else if (dirent.isFile()) entries.push({ name, data: fs.readFileSync(full), mtime: fs.statSync(full).mtime })
182
+ }
183
+ }
184
+ walk(dir, '')
185
+ return entries
186
+ }
187
+
188
+ export function megabytes(bytes) {
189
+ if (bytes < 1024 * 1024) return `${Math.ceil(bytes / 1024)} KB`
190
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
191
+ }
192
+
193
+ function gitSubject(cwd) {
194
+ try {
195
+ return execFileSync('git', ['log', '-1', '--pretty=%s'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
196
+ } catch {
197
+ return ''
198
+ }
199
+ }
200
+
201
+ /** The list Hakubase reads instead of a zip: path, fingerprint and size of every file. */
202
+ export function listOf(entries) {
203
+ return entries.map((e) => ({
204
+ path: '/' + e.name,
205
+ hash: crypto.createHash('sha256').update(e.data).digest('hex'),
206
+ size: e.data.length,
207
+ data: e.data,
208
+ }))
209
+ }
210
+
211
+ /** The missing files in groups that fit one request each. */
212
+ export function batches(files) {
213
+ const out = []
214
+ let current = []
215
+ let bytes = 0
216
+ for (const file of files) {
217
+ if (current.length && (bytes + file.size > BATCH_BYTES || current.length >= BATCH_FILES)) {
218
+ out.push(current)
219
+ current = []
220
+ bytes = 0
221
+ }
222
+ current.push(file)
223
+ bytes += file.size
224
+ }
225
+ if (current.length) out.push(current)
226
+ return out
227
+ }
228
+
229
+ function readConfig(root, entries) {
230
+ const inside = entries.find((e) => e.name === 'hakubase.json')
231
+ const file = path.join(root, 'hakubase.json')
232
+ const raw = inside ? inside.data : (fs.existsSync(file) ? fs.readFileSync(file) : null)
233
+ if (!raw) return null
234
+ try {
235
+ return JSON.parse(raw.toString('utf8'))
236
+ } catch {
237
+ throw new CliError('hakubase.json is not JSON.')
238
+ }
239
+ }
240
+
241
+ export async function deploy(ctx, positional, flags) {
242
+ const t = target(ctx, flags)
243
+ const dir = buildDir(ctx.cwd, positional[0])
244
+ const entries = collectFiles(dir)
245
+ if (!entries.length) throw new CliError(`${path.relative(ctx.cwd, dir) || dir} is empty.`)
246
+ const config = readConfig(t.root, entries)
247
+ const listed = listOf(entries.filter((e) => e.name !== 'hakubase.json'))
248
+ const files = listed.map(({ path: p, hash, size }) => ({ path: p, hash, size }))
249
+ const base = `${t.api}/api/sites/${encodeURIComponent(t.site)}/code-site`
250
+ // 1. What Hakubase lacks: a deploy that changed one page sends one page.
251
+ const plan = await request(ctx, 'POST', `${base}/uploads`, { key: t.key, json: { files, config } })
252
+ const missing = new Set(plan.missing || [])
253
+ const unique = new Map()
254
+ for (const file of listed) if (missing.has(file.hash) && !unique.has(file.hash)) unique.set(file.hash, file)
255
+ const groups = batches([...unique.values()])
256
+ // 2. The missing files, a group at a time, each named by its fingerprint.
257
+ let sent = 0
258
+ for (const group of groups) {
259
+ const form = new FormData()
260
+ for (const file of group) form.append('files', new Blob([file.data], { type: 'application/octet-stream' }), file.hash)
261
+ await request(ctx, 'POST', `${base}/files`, { key: t.key, body: form })
262
+ sent += group.reduce((n, f) => n + f.size, 0)
263
+ if (groups.length > 1) ctx.out(` ${megabytes(sent)} of ${megabytes(plan.missing_bytes || sent)}`)
264
+ }
265
+ // 3. The version, once every file is there.
266
+ const github = Boolean(ctx.env.GITHUB_SHA)
267
+ const commit = typeof flags.commit === 'string' ? flags.commit : (ctx.env.GITHUB_SHA || '')
268
+ const via = typeof flags.via === 'string' ? flags.via : (github ? 'github' : 'cli')
269
+ const message = typeof flags.message === 'string' ? flags.message : (github ? gitSubject(ctx.cwd) : '')
270
+ const version = await request(ctx, 'POST', `${base}/versions/manifest`, {
271
+ key: t.key, json: { files, config, publish: Boolean(flags.publish), message, commit, via },
272
+ })
273
+ ctx.out(`Version ${version.number} uploaded (${version.files} files, ${megabytes(version.size || 0)}, ${megabytes(sent)} new).`)
274
+ if (version.online) {
275
+ ctx.out(`Online: ${t.siteUrl || await siteUrl(ctx, t)}`)
276
+ } else {
277
+ ctx.out(`Preview: ${version.preview_url}`)
278
+ }
279
+ return 0
280
+ }
281
+
282
+ async function siteUrl(ctx, t) {
283
+ try {
284
+ const info = await request(ctx, 'GET', `${t.api}/api/sites/${encodeURIComponent(t.site)}/code-site`, { key: t.key })
285
+ return info.url || t.api
286
+ } catch {
287
+ return t.api
288
+ }
289
+ }
290
+
291
+ export async function publish(ctx, positional, flags) {
292
+ const number = Number.parseInt(positional[0], 10)
293
+ if (!Number.isInteger(number) || number < 1) throw new CliError('Usage: hakubase publish <number>')
294
+ const t = target(ctx, flags)
295
+ await request(ctx, 'POST', `${t.api}/api/sites/${encodeURIComponent(t.site)}/code-site/versions/${number}/publish`, { key: t.key })
296
+ ctx.out(`Version ${number} online: ${t.siteUrl || await siteUrl(ctx, t)}`)
297
+ return 0
298
+ }
299
+
300
+ const COMMANDS = { link, types, deploy, publish }
301
+
302
+ export async function main(argv, ctx = {}) {
303
+ const full = {
304
+ cwd: process.cwd(),
305
+ env: process.env,
306
+ fetch: (...args) => globalThis.fetch(...args),
307
+ out: (line) => process.stdout.write(line + '\n'),
308
+ err: (line) => process.stderr.write(line + '\n'),
309
+ ...ctx,
310
+ }
311
+ const [name, ...rest] = argv
312
+ if (!name || name === 'help' || name === '--help' || name === '-h') {
313
+ full.out(USAGE.trimEnd())
314
+ return 0
315
+ }
316
+ const command = COMMANDS[name]
317
+ if (!command) {
318
+ full.err(`Unknown command: ${name}\n\n${USAGE.trimEnd()}`)
319
+ return 1
320
+ }
321
+ const { positional, flags } = parseArgs(rest)
322
+ if (flags.help) {
323
+ full.out(USAGE.trimEnd())
324
+ return 0
325
+ }
326
+ try {
327
+ return await command(full, positional, flags)
328
+ } catch (error) {
329
+ if (error instanceof CliError) {
330
+ full.err(error.message)
331
+ return 1
332
+ }
333
+ throw error
334
+ }
335
+ }
@@ -0,0 +1,30 @@
1
+ // `*.localhost` is the loopback by definition (RFC 6761), and browsers
2
+ // treat it so; Node asks the system resolver, which on macOS does not.
3
+ // A Hakubase in development lives on `*.hakubase.localhost`: without
4
+ // this, `hakubase link` and `deploy` against it fail with ENOTFOUND.
5
+ import dns from 'node:dns'
6
+
7
+ const original = dns.lookup
8
+
9
+ export function isLoopbackName(host) {
10
+ return typeof host === 'string' && /(^|\.)localhost\.?$/i.test(host)
11
+ }
12
+
13
+ export function installLocalhostResolver() {
14
+ if (dns.lookup.__hakubase) return
15
+ const lookup = function (host, options, callback) {
16
+ if (typeof options === 'function') {
17
+ callback = options
18
+ options = {}
19
+ }
20
+ if (isLoopbackName(host)) {
21
+ const all = typeof options === 'object' && options && options.all
22
+ return all
23
+ ? process.nextTick(callback, null, [{ address: '127.0.0.1', family: 4 }])
24
+ : process.nextTick(callback, null, '127.0.0.1', 4)
25
+ }
26
+ return original.call(dns, host, options, callback)
27
+ }
28
+ lookup.__hakubase = true
29
+ dns.lookup = lookup
30
+ }
package/lib/project.js ADDED
@@ -0,0 +1,112 @@
1
+ // Where a project keeps its link to Hakubase: `.hakubase/project.json`
2
+ // for the addresses, `.env.local` for the key. The key never goes in
3
+ // project.json, and is never printed whole.
4
+
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+
8
+ export const PROJECT_FILE = path.join('.hakubase', 'project.json')
9
+ export const ENV_FILE = '.env.local'
10
+ const KEY_LINE = /^\s*(?:export\s+)?HAKUBASE_KEY\s*=\s*(.*)$/
11
+
12
+ /** The nearest directory, from `start` up, that holds a linked project; null if none. */
13
+ export function findRoot(start = process.cwd()) {
14
+ let dir = path.resolve(start)
15
+ for (;;) {
16
+ if (fs.existsSync(path.join(dir, PROJECT_FILE))) return dir
17
+ const parent = path.dirname(dir)
18
+ if (parent === dir) return null
19
+ dir = parent
20
+ }
21
+ }
22
+
23
+ export function readProject(root) {
24
+ if (!root) return null
25
+ try {
26
+ return JSON.parse(fs.readFileSync(path.join(root, PROJECT_FILE), 'utf8'))
27
+ } catch {
28
+ return null
29
+ }
30
+ }
31
+
32
+ export function writeProject(root, project) {
33
+ fs.mkdirSync(path.join(root, '.hakubase'), { recursive: true })
34
+ fs.writeFileSync(path.join(root, PROJECT_FILE), JSON.stringify(project, null, 2) + '\n')
35
+ }
36
+
37
+ function unquote(value) {
38
+ const v = value.trim()
39
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
40
+ return v.slice(1, -1)
41
+ }
42
+ return v.replace(/\s+#.*$/, '')
43
+ }
44
+
45
+ /** The key written in `.env.local`, or ''. */
46
+ export function readEnvKey(root) {
47
+ if (!root) return ''
48
+ let text
49
+ try {
50
+ text = fs.readFileSync(path.join(root, ENV_FILE), 'utf8')
51
+ } catch {
52
+ return ''
53
+ }
54
+ for (const line of text.split(/\r?\n/)) {
55
+ const match = line.match(KEY_LINE)
56
+ if (match) return unquote(match[1])
57
+ }
58
+ return ''
59
+ }
60
+
61
+ /** The key to use: `--key`, then the HAKUBASE_KEY variable, then `.env.local`. */
62
+ export function resolveKey(root, flag, env = process.env) {
63
+ return flag || env.HAKUBASE_KEY || readEnvKey(root) || ''
64
+ }
65
+
66
+ /** Writes the key in `.env.local`, replacing its line or adding one. */
67
+ export function writeEnvKey(root, key) {
68
+ const file = path.join(root, ENV_FILE)
69
+ let text = ''
70
+ try {
71
+ text = fs.readFileSync(file, 'utf8')
72
+ } catch {
73
+ text = ''
74
+ }
75
+ const lines = text ? text.split(/\r?\n/) : []
76
+ if (lines.length && lines[lines.length - 1] === '') lines.pop()
77
+ let found = false
78
+ const out = []
79
+ for (const line of lines) {
80
+ if (KEY_LINE.test(line)) {
81
+ if (!found) out.push(`HAKUBASE_KEY=${key}`)
82
+ found = true
83
+ } else {
84
+ out.push(line)
85
+ }
86
+ }
87
+ if (!found) out.push(`HAKUBASE_KEY=${key}`)
88
+ fs.writeFileSync(file, out.join('\n') + '\n', { mode: 0o600 })
89
+ }
90
+
91
+ /** Where a .gitignore exists, makes sure it keeps `.env.local` out. Returns true when it added the line. */
92
+ export function ensureGitignored(root) {
93
+ const file = path.join(root, '.gitignore')
94
+ let text
95
+ try {
96
+ text = fs.readFileSync(file, 'utf8')
97
+ } catch {
98
+ return false
99
+ }
100
+ const covered = text.split(/\r?\n/).map((l) => l.trim()).some((l) =>
101
+ l === ENV_FILE || l === '/' + ENV_FILE || l === '.env*' || l === '*.local' || l === '.env.*')
102
+ if (covered) return false
103
+ fs.writeFileSync(file, text + (text && !text.endsWith('\n') ? '\n' : '') + ENV_FILE + '\n')
104
+ return true
105
+ }
106
+
107
+ /** `hb_…f3a9`: enough to tell keys apart, never enough to use one. */
108
+ export function maskKey(key) {
109
+ if (!key) return ''
110
+ const tail = key.length > 12 ? key.slice(-4) : ''
111
+ return `${key.slice(0, 3)}…${tail}`
112
+ }
package/lib/types.js ADDED
@@ -0,0 +1,100 @@
1
+ // `hakubase types`: the collections of the site as TypeScript, merged
2
+ // into the `Collections` interface of @hakubase/sdk. The shapes follow
3
+ // what `/_data` answers: select options as their labels, relations as
4
+ // the related items, images as a URL or {url, alt, focal}, empty
5
+ // fields absent.
6
+
7
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/
8
+
9
+ function prop(key) {
10
+ return IDENT.test(key) ? key : JSON.stringify(key)
11
+ }
12
+
13
+ function comment(text, indent) {
14
+ const clean = String(text || '').replace(/\*\//g, '* /').trim()
15
+ return clean ? `${indent}/** ${clean} */\n` : ''
16
+ }
17
+
18
+ function optionLabels(field) {
19
+ const labels = []
20
+ for (const option of field.options || []) {
21
+ const label = typeof option === 'string' ? option : option && (option.label ?? option.id)
22
+ if (label !== undefined && label !== null && label !== '' && !labels.includes(String(label))) {
23
+ labels.push(String(label))
24
+ }
25
+ }
26
+ return labels
27
+ }
28
+
29
+ function union(labels) {
30
+ return labels.length ? labels.map((l) => JSON.stringify(l)).join(' | ') : 'string'
31
+ }
32
+
33
+ function scalarType(kind) {
34
+ switch (kind) {
35
+ case 'text':
36
+ case 'textarea':
37
+ case 'richtext':
38
+ case 'url':
39
+ case 'color':
40
+ case 'date':
41
+ case 'datetime':
42
+ return 'string'
43
+ case 'number':
44
+ return 'number'
45
+ case 'boolean':
46
+ return 'boolean'
47
+ case 'image':
48
+ case 'file':
49
+ return 'CmsImage'
50
+ case 'geo':
51
+ return 'CmsGeo'
52
+ case 'json':
53
+ return 'unknown'
54
+ default:
55
+ return null
56
+ }
57
+ }
58
+
59
+ export function fieldType(field, indent = ' ') {
60
+ const kind = field.kind || 'text'
61
+ if (kind === 'select') return union(optionLabels(field))
62
+ if (kind === 'multiselect') {
63
+ return `Array<${union(optionLabels(field))}>`
64
+ }
65
+ if (kind === 'relation') return 'CmsRelated[]'
66
+ if (kind === 'group') {
67
+ // Subfields of a repeater are stored as written: no label mapping.
68
+ const inner = (field.fields || []).map((sub) => {
69
+ const type = sub.kind === 'select' || sub.kind === 'multiselect'
70
+ ? (sub.kind === 'multiselect' ? 'string[]' : 'string')
71
+ : scalarType(sub.kind) || 'unknown'
72
+ return `${indent} ${prop(sub.key)}?: ${type}\n`
73
+ }).join('')
74
+ return `Array<{\n${inner}${indent}}>`
75
+ }
76
+ return scalarType(kind) || 'unknown'
77
+ }
78
+
79
+ function publicFields(collection) {
80
+ return (collection.fields || []).filter((f) => f && f.key && f.active !== false && !f.private)
81
+ }
82
+
83
+ export function generateTypes(collections, { date = new Date() } = {}) {
84
+ const usable = (collections || []).filter((c) => c && c.key && c.kind !== 'members')
85
+ const body = usable.map((c) => {
86
+ const fields = publicFields(c).map((f) => {
87
+ // A reserved field leaves the site only for members who qualify:
88
+ // for everybody else it is absent, required or not.
89
+ const optional = !f.required || f.reserved ? '?' : ''
90
+ return comment(f.label && f.label !== f.key ? f.label : '', ' ') +
91
+ ` ${prop(f.key)}${optional}: ${fieldType(f)}\n`
92
+ }).join('')
93
+ return comment(c.name, ' ') + ` ${prop(c.key)}: {\n${fields} }\n`
94
+ }).join('')
95
+ const day = date.toISOString().slice(0, 10)
96
+ return `// Generated by \`hakubase types\` on ${day}. Do not edit: run it again.\n` +
97
+ `import type { CmsGeo, CmsImage, CmsRelated } from '@hakubase/sdk'\n\n` +
98
+ `declare module '@hakubase/sdk' {\n` +
99
+ ` interface Collections {\n${body} }\n}\n`
100
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@hakubase/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Link, type, develop and deploy Hakubase code sites; Vite and Astro plugins for development with real data.",
5
+ "type": "module",
6
+ "bin": {
7
+ "hakubase": "./bin/hakubase.js"
8
+ },
9
+ "exports": {
10
+ "./vite": "./vite.js",
11
+ "./astro": "./astro.js",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "bin",
16
+ "lib",
17
+ "vite.js",
18
+ "astro.js",
19
+ "README.md"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "license": "MIT",
25
+ "keywords": [
26
+ "hakubase",
27
+ "cli",
28
+ "deploy",
29
+ "vite-plugin",
30
+ "astro-integration"
31
+ ],
32
+ "scripts": {
33
+ "test": "node --test"
34
+ }
35
+ }
package/vite.js ADDED
@@ -0,0 +1,69 @@
1
+ // The Vite plugin of @hakubase/cli: in development, Hakubase's own
2
+ // paths go from localhost to the real site, with the key added on the
3
+ // way. The browser sees one origin; the key stays in this process and
4
+ // never reaches the bundle.
5
+
6
+ import { findRoot, readProject, resolveKey } from './lib/project.js'
7
+
8
+ export const PROXY_PATHS = '^/(_hb|_data|_fn|_m)(/|$)'
9
+
10
+ let warned = false
11
+
12
+ function warnOnce(log, message) {
13
+ if (warned) return
14
+ warned = true
15
+ log(`[hakubase] ${message}`)
16
+ }
17
+
18
+ function stripDomain(cookie) {
19
+ return cookie.split(';').filter((part) => !/^\s*domain\s*=/i.test(part)).join(';')
20
+ }
21
+
22
+ /** The proxy entry for a linked project, or null. Exported for the tests. */
23
+ export function proxyFor({ siteUrl, key }) {
24
+ const targetOrigin = new URL(siteUrl).origin
25
+ return {
26
+ [PROXY_PATHS]: {
27
+ target: targetOrigin,
28
+ changeOrigin: true,
29
+ secure: true,
30
+ headers: key ? { authorization: `Bearer ${key}` } : {},
31
+ configure(proxy) {
32
+ proxy.on('proxyReq', (proxyReq) => {
33
+ if (key) proxyReq.setHeader('authorization', `Bearer ${key}`)
34
+ // The members area refuses a write whose Origin is not the
35
+ // site: seen from there, the page is the site.
36
+ if (proxyReq.getHeader('origin')) proxyReq.setHeader('origin', targetOrigin)
37
+ })
38
+ proxy.on('proxyRes', (proxyRes) => {
39
+ // A cookie for the site's domain would not stick on localhost.
40
+ const cookies = proxyRes.headers['set-cookie']
41
+ if (Array.isArray(cookies)) proxyRes.headers['set-cookie'] = cookies.map(stripDomain)
42
+ else if (typeof cookies === 'string') proxyRes.headers['set-cookie'] = stripDomain(cookies)
43
+ })
44
+ },
45
+ },
46
+ }
47
+ }
48
+
49
+ export default function hakubase(options = {}) {
50
+ const log = options.log || ((message) => console.warn(message))
51
+ return {
52
+ name: 'hakubase',
53
+ apply: 'serve',
54
+ config() {
55
+ const root = findRoot(options.root || process.cwd())
56
+ const project = readProject(root)
57
+ if (!project || !project.site_url) {
58
+ warnOnce(log, 'This project is not linked: run `npx hakubase link <workspace-url> <site-id> --key hb_…`. Nothing is proxied.')
59
+ return {}
60
+ }
61
+ const key = resolveKey(root, options.key || '')
62
+ if (!key) warnOnce(log, 'No key in HAKUBASE_KEY or .env.local: only published content answers.')
63
+ const proxy = proxyFor({ siteUrl: project.site_url, key })
64
+ return { server: { proxy }, preview: { proxy } }
65
+ },
66
+ }
67
+ }
68
+
69
+ export { hakubase }