@zolio/cli 0.0.0-stage → 0.0.1
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/LICENSE +48 -0
- package/README.md +57 -2
- package/bin/zolio.mjs +529 -0
- package/package.json +36 -4
- package/src/api.mjs +36 -0
- package/src/credentials.mjs +54 -0
- package/src/env-file.mjs +41 -0
- package/src/prompt.mjs +15 -0
- package/src/versions.mjs +17 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Zolio Software License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Zolio. All rights reserved.
|
|
4
|
+
|
|
5
|
+
This package ("the Software") is proprietary. It is not open source. It is
|
|
6
|
+
published on npm only so that customers of the Zolio service can install it.
|
|
7
|
+
|
|
8
|
+
1. Grant. If you have a valid Zolio account, Zolio grants you a limited,
|
|
9
|
+
non-exclusive, non-transferable, revocable license to install the Software
|
|
10
|
+
and to include it, unmodified, in websites and applications that you or your
|
|
11
|
+
organization own or operate, solely to use the Zolio service with a project
|
|
12
|
+
key issued to you.
|
|
13
|
+
|
|
14
|
+
2. Requires the service. The Software is a client for the Zolio service and
|
|
15
|
+
does nothing useful without a project key and an account. Your use of the
|
|
16
|
+
service is governed by the terms you accepted when you signed up. If those
|
|
17
|
+
terms end, this license ends with them.
|
|
18
|
+
|
|
19
|
+
3. Restrictions. You may not, and may not let anyone else:
|
|
20
|
+
a. copy, modify, or create derivative works of the Software, except for the
|
|
21
|
+
configuration the Software itself offers (props, theme, messages);
|
|
22
|
+
b. redistribute, sell, sublicense, or publish the Software, on its own or
|
|
23
|
+
as part of another package, library, or template;
|
|
24
|
+
c. reverse engineer the Software, or use it, to build or improve a product
|
|
25
|
+
or service that competes with Zolio, except where the law allows this
|
|
26
|
+
despite this restriction;
|
|
27
|
+
d. remove or alter any copyright, license, or notice in the Software;
|
|
28
|
+
e. use the Software to send traffic to the Zolio service with a key that is
|
|
29
|
+
not yours, or to get around limits, billing, or access controls.
|
|
30
|
+
|
|
31
|
+
4. Third-party code. The Software contains open-source components that are
|
|
32
|
+
licensed to you under their own terms, listed in THIRD-PARTY-NOTICES.md.
|
|
33
|
+
Nothing in this license limits your rights under those terms.
|
|
34
|
+
|
|
35
|
+
5. Ownership. Zolio and its licensors own the Software and all rights in it
|
|
36
|
+
that are not expressly granted here.
|
|
37
|
+
|
|
38
|
+
6. No warranty. The Software is provided "as is", without warranty of any
|
|
39
|
+
kind, express or implied, including fitness for a particular purpose and
|
|
40
|
+
non-infringement.
|
|
41
|
+
|
|
42
|
+
7. Limitation of liability. To the extent the law allows, Zolio is not liable
|
|
43
|
+
for indirect, incidental, special, or consequential damages, or for lost
|
|
44
|
+
profits or data, arising from the use of the Software. Liability for the
|
|
45
|
+
service itself is governed by the service terms.
|
|
46
|
+
|
|
47
|
+
8. Termination. Zolio may end this license if you break it. When it ends, you
|
|
48
|
+
must stop using the Software and remove it from your systems.
|
package/README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zolio/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sets up Zolio in a project: installs [`@zolio/react`](https://www.npmjs.com/package/@zolio/react), writes env placeholders, connects coding agents to the integration guide, and fetches your project keys. `login` and `setup` need a Zolio account. Proprietary: see [LICENSE](./LICENSE).
|
|
4
|
+
|
|
5
|
+
Node 20+. Nothing to install first: run it with `npx -y @zolio/cli <command>`.
|
|
6
|
+
|
|
7
|
+
## The short way
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx -y @zolio/cli prompt
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
It prints a prompt. Paste it into your coding agent and it does the whole setup. You approve one code in the Zolio dashboard and put `ZOLIO_SECRET` into your production host's secrets. Nothing else.
|
|
14
|
+
|
|
15
|
+
## Commands
|
|
16
|
+
|
|
17
|
+
| Command | What it does |
|
|
18
|
+
| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
|
19
|
+
| `init` | Installs `@zolio/react` with your package manager, adds placeholders to `.env.example`, writes agent files. |
|
|
20
|
+
| `login` | Starts a login. An organization owner approves a code in the dashboard. Lasts 8 hours. |
|
|
21
|
+
| `projects` | Lists the projects this login may see. |
|
|
22
|
+
| `setup --project <id\|name>` or `--create <name> --url <url>` | Writes the project key (and, for a new project, the secret) to `.env.local`, and git-ignores it. |
|
|
23
|
+
| `whoami` | Shows the login and what it may do. |
|
|
24
|
+
| `logout` | Ends the login now, on the server too. |
|
|
25
|
+
| `agents` | Only (re)writes the coding-agent files. |
|
|
26
|
+
| `check [--latest]` | Verifies the setup. `--latest` also compares the installed version with npm. |
|
|
27
|
+
| `print` | Prints the integration guide of the installed `@zolio/react`. |
|
|
28
|
+
| `prompt` | Prints the paste-into-your-agent prompt. |
|
|
29
|
+
|
|
30
|
+
Options: `--dir <path>`, `--target agents,claude,cursor`, `--no-install`, `--api <url>`, `--scopes projects:create,secrets:rotate`, `--no-wait` / `--wait`, `--json`, `--env-file <name>`, `--with-secret`.
|
|
31
|
+
|
|
32
|
+
### Package managers
|
|
33
|
+
|
|
34
|
+
`init` picks pnpm, yarn, bun or npm from your lockfile, or from the `packageManager` field when there is none. At the root of a pnpm workspace it uses `pnpm add -w`. To install into a package inside a monorepo, run it there or pass `--dir`.
|
|
35
|
+
|
|
36
|
+
If the installed `@zolio/react` is too old to carry the integration guide, `init` stops with an error and writes nothing, so agents are never pointed at a file that is not there.
|
|
37
|
+
|
|
38
|
+
### Login, step by step
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npx -y @zolio/cli login --no-wait # prints a link and a code
|
|
42
|
+
# an organization owner opens the link and approves
|
|
43
|
+
npx -y @zolio/cli login --wait
|
|
44
|
+
npx -y @zolio/cli setup --create "My shop" --url https://shop.example.com
|
|
45
|
+
npx -y @zolio/cli logout
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## What it will and will not do
|
|
49
|
+
|
|
50
|
+
- It never edits your application source. It prints snippets instead.
|
|
51
|
+
- Your login is stored in `~/.config/zolio/credentials.json` (mode 0600), never in the project. The server keeps only a hash of the token.
|
|
52
|
+
- A project secret goes to `.env.local` only, after git is told to ignore that file. It is never printed, so it does not land in an agent's transcript.
|
|
53
|
+
- The token is sent only to an `https` API (or one on your own machine). Redirects are refused.
|
|
54
|
+
- It asks for nothing it does not need: `projects:create` by default. Re-keying an existing project (`secrets:rotate`) is a separate, visible approval.
|
|
55
|
+
|
|
56
|
+
## License
|
|
57
|
+
|
|
58
|
+
Proprietary, not open source. See [LICENSE](./LICENSE).
|
package/bin/zolio.mjs
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `npx -y @zolio/cli init`: sets Zolio up in a project. It installs @zolio/react with the project's
|
|
3
|
+
// package manager, adds env placeholders to .env.example, and connects coding agents to the
|
|
4
|
+
// context that ships inside the installed @zolio/react (so it is always the installed version's).
|
|
5
|
+
// It never writes a secret and never edits application source; it prints the snippets instead.
|
|
6
|
+
// No network except the package manager's own install, and `check --latest`.
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { dirname, join, resolve } from 'node:path';
|
|
9
|
+
import { hostname } from 'node:os';
|
|
10
|
+
import { spawnSync } from 'node:child_process';
|
|
11
|
+
import { ApiError, DEFAULT_API, call } from '../src/api.mjs';
|
|
12
|
+
import {
|
|
13
|
+
dropPending,
|
|
14
|
+
dropToken,
|
|
15
|
+
loadPending,
|
|
16
|
+
loadToken,
|
|
17
|
+
savePending,
|
|
18
|
+
saveToken,
|
|
19
|
+
} from '../src/credentials.mjs';
|
|
20
|
+
import { ensureIgnored, upsertEnv } from '../src/env-file.mjs';
|
|
21
|
+
import { SETUP_PROMPT } from '../src/prompt.mjs';
|
|
22
|
+
import { compareVersions } from '../src/versions.mjs';
|
|
23
|
+
|
|
24
|
+
const PKG = '@zolio/react';
|
|
25
|
+
const CONTEXT = `node_modules/${PKG}/dist/agent/CONTEXT.md`;
|
|
26
|
+
const BEGIN = '<!-- zolio:begin -->';
|
|
27
|
+
const END = '<!-- zolio:end -->';
|
|
28
|
+
const TARGETS = ['agents', 'claude', 'cursor'];
|
|
29
|
+
|
|
30
|
+
const POINTER = `Zolio (customer support widget, \`${PKG}\`) is used in this project. Before adding or changing anything that touches Zolio (the \`<ZolioWidget>\`, \`zolio.track\`, \`userJwt\`, the context endpoint, \`${PKG}/server\`), read \`${CONTEXT}\`. It is shipped with the installed package, so it matches the installed version. Never put the project secret (\`sk_…\`) in client code.`;
|
|
31
|
+
|
|
32
|
+
const USAGE = `zolio: set up Zolio in a project
|
|
33
|
+
|
|
34
|
+
npx -y @zolio/cli prompt print a prompt to paste into your coding agent: it does everything below
|
|
35
|
+
npx -y @zolio/cli init install ${PKG}, add env placeholders, set up agent files
|
|
36
|
+
npx -y @zolio/cli login log in; an organization owner approves a code in the dashboard
|
|
37
|
+
npx -y @zolio/cli projects list the projects this login may see
|
|
38
|
+
npx -y @zolio/cli setup write a project's keys to .env.local (--project <id|name> | --create <name> --url <url>)
|
|
39
|
+
npx -y @zolio/cli whoami show the login and what it may do
|
|
40
|
+
npx -y @zolio/cli logout end the login now
|
|
41
|
+
npx -y @zolio/cli agents only (re)write the coding-agent files
|
|
42
|
+
npx -y @zolio/cli check verify the setup (--latest also compares with npm)
|
|
43
|
+
npx -y @zolio/cli print print the agent context of the installed ${PKG}
|
|
44
|
+
|
|
45
|
+
options: --dir <path> --target agents,claude,cursor --no-install --latest
|
|
46
|
+
--api <url> --scopes projects:create,secrets:rotate --no-wait | --wait --json
|
|
47
|
+
--project <id|name> --create <name> --url <url> --env-file <name> --with-secret`;
|
|
48
|
+
|
|
49
|
+
const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'));
|
|
50
|
+
|
|
51
|
+
function installedContext(dir) {
|
|
52
|
+
const metaFile = join(dir, 'node_modules', PKG, 'dist/agent/meta.json');
|
|
53
|
+
if (!existsSync(metaFile)) return null;
|
|
54
|
+
return { version: readJson(metaFile).version, file: join(dir, CONTEXT) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The installed package's version, or null. Versions before the agent context have no meta.json. */
|
|
58
|
+
function installedVersion(dir) {
|
|
59
|
+
try {
|
|
60
|
+
return readJson(join(dir, 'node_modules', PKG, 'package.json')).version ?? null;
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** True when the installed package offers `@zolio/react/server` (the backend helpers). */
|
|
67
|
+
function hasServerEntry(dir) {
|
|
68
|
+
try {
|
|
69
|
+
return Boolean(readJson(join(dir, 'node_modules', PKG, 'package.json')).exports?.['./server']);
|
|
70
|
+
} catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function packageManager(dir) {
|
|
76
|
+
const has = (f) => existsSync(join(dir, f));
|
|
77
|
+
let declared = '';
|
|
78
|
+
try {
|
|
79
|
+
declared = String(readJson(join(dir, 'package.json')).packageManager ?? '').split('@')[0];
|
|
80
|
+
} catch {
|
|
81
|
+
/* a broken package.json is reported by init itself */
|
|
82
|
+
}
|
|
83
|
+
// the root of a pnpm workspace refuses `pnpm add` without -w
|
|
84
|
+
const pnpm = has('pnpm-workspace.yaml') ? ['pnpm', 'add', '-w'] : ['pnpm', 'add'];
|
|
85
|
+
if (has('pnpm-lock.yaml')) return pnpm;
|
|
86
|
+
if (has('yarn.lock')) return ['yarn', 'add'];
|
|
87
|
+
if (has('bun.lock') || has('bun.lockb')) return ['bun', 'add'];
|
|
88
|
+
if (has('package-lock.json')) return ['npm', 'install'];
|
|
89
|
+
if (declared === 'pnpm') return pnpm;
|
|
90
|
+
if (declared === 'yarn') return ['yarn', 'add'];
|
|
91
|
+
if (declared === 'bun') return ['bun', 'add'];
|
|
92
|
+
return ['npm', 'install'];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The env name the framework exposes to the browser, for the public project key. */
|
|
96
|
+
function clientEnvName(pkg) {
|
|
97
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
98
|
+
if (deps.next) return 'NEXT_PUBLIC_ZOLIO_PROJECT_KEY';
|
|
99
|
+
if (deps.vite || deps['@tanstack/react-start']) return 'VITE_ZOLIO_PROJECT_KEY';
|
|
100
|
+
if (deps['react-scripts']) return 'REACT_APP_ZOLIO_PROJECT_KEY';
|
|
101
|
+
return 'ZOLIO_PROJECT_KEY';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function upsertBlock(file, body) {
|
|
105
|
+
const block = `${BEGIN}\n${body}\n${END}`;
|
|
106
|
+
const current = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
107
|
+
const a = current.indexOf(BEGIN);
|
|
108
|
+
const b = current.indexOf(END);
|
|
109
|
+
let next;
|
|
110
|
+
if (a !== -1 && b > a) next = current.slice(0, a) + block + current.slice(b + END.length);
|
|
111
|
+
else {
|
|
112
|
+
const gap = !current
|
|
113
|
+
? ''
|
|
114
|
+
: current.endsWith('\n\n')
|
|
115
|
+
? ''
|
|
116
|
+
: current.endsWith('\n')
|
|
117
|
+
? '\n'
|
|
118
|
+
: '\n\n';
|
|
119
|
+
next = current + gap + block + '\n';
|
|
120
|
+
}
|
|
121
|
+
return writeIfChanged(file, next);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function writeIfChanged(file, text) {
|
|
125
|
+
if (existsSync(file) && readFileSync(file, 'utf8') === text) return false;
|
|
126
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
127
|
+
writeFileSync(file, text);
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const FILES = {
|
|
132
|
+
agents: (dir) => ({
|
|
133
|
+
file: join(dir, 'AGENTS.md'),
|
|
134
|
+
write: (f) => upsertBlock(f, `## Zolio\n\n${POINTER}`),
|
|
135
|
+
}),
|
|
136
|
+
claude: (dir) => ({
|
|
137
|
+
file: join(dir, '.claude/skills/zolio/SKILL.md'),
|
|
138
|
+
write: (f) =>
|
|
139
|
+
writeIfChanged(
|
|
140
|
+
f,
|
|
141
|
+
`---\nname: zolio\ndescription: Integrate or change Zolio, the customer support widget (${PKG}): ZolioWidget, userJwt identity, zolio.track, the context endpoint, the server helpers. Use for any code that touches Zolio.\n---\n\n${POINTER}\n`,
|
|
142
|
+
),
|
|
143
|
+
}),
|
|
144
|
+
cursor: (dir) => ({
|
|
145
|
+
file: join(dir, '.cursor/rules/zolio.mdc'),
|
|
146
|
+
write: (f) =>
|
|
147
|
+
writeIfChanged(
|
|
148
|
+
f,
|
|
149
|
+
`---\ndescription: Zolio support widget integration (${PKG})\nalwaysApply: false\nglobs: ["**/*.ts", "**/*.tsx"]\n---\n\n${POINTER}\n`,
|
|
150
|
+
),
|
|
151
|
+
}),
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
function writeAgentFiles(opts) {
|
|
155
|
+
for (const t of opts.targets) {
|
|
156
|
+
const { file, write } = FILES[t](opts.dir);
|
|
157
|
+
console.log(`${write(file) ? 'wrote ' : 'current'} ${file.slice(opts.dir.length + 1)}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Adds placeholders (never values) to .env.example, skipping names already there. */
|
|
162
|
+
function writeEnvExample(opts, pkg) {
|
|
163
|
+
const file = join(opts.dir, '.env.example');
|
|
164
|
+
const current = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
165
|
+
const wanted = [
|
|
166
|
+
[
|
|
167
|
+
'# Zolio project key (public, safe in client code). From the Zolio dashboard.',
|
|
168
|
+
clientEnvName(pkg),
|
|
169
|
+
'pk_...',
|
|
170
|
+
],
|
|
171
|
+
[
|
|
172
|
+
'# Zolio project secret: backend only, never in a client bundle or in git.',
|
|
173
|
+
'ZOLIO_SECRET',
|
|
174
|
+
'',
|
|
175
|
+
],
|
|
176
|
+
].filter(([, name]) => !new RegExp(`^${name}=`, 'm').test(current));
|
|
177
|
+
if (wanted.length === 0) return console.log('current .env.example');
|
|
178
|
+
const add = wanted.map(([c, n, v]) => `${c}\n${n}=${v}`).join('\n') + '\n';
|
|
179
|
+
const gap = !current ? '' : current.endsWith('\n') ? '\n' : '\n\n';
|
|
180
|
+
writeFileSync(file, current + gap + add);
|
|
181
|
+
console.log('wrote .env.example');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function parse(argv) {
|
|
185
|
+
const opts = {
|
|
186
|
+
cmd: argv[0],
|
|
187
|
+
dir: process.cwd(),
|
|
188
|
+
targets: TARGETS,
|
|
189
|
+
latest: false,
|
|
190
|
+
install: true,
|
|
191
|
+
api: (process.env.ZOLIO_API_URL || DEFAULT_API).replace(/\/$/, ''),
|
|
192
|
+
scopes: ['projects:create'],
|
|
193
|
+
wait: null,
|
|
194
|
+
json: false,
|
|
195
|
+
project: null,
|
|
196
|
+
create: null,
|
|
197
|
+
url: null,
|
|
198
|
+
envFile: '.env.local',
|
|
199
|
+
withSecret: false,
|
|
200
|
+
};
|
|
201
|
+
const value = (i, flag) => {
|
|
202
|
+
if (argv[i] === undefined) throw new Error(`${flag} needs a value`);
|
|
203
|
+
return argv[i];
|
|
204
|
+
};
|
|
205
|
+
for (let i = 1; i < argv.length; i++) {
|
|
206
|
+
if (argv[i] === '--dir') opts.dir = resolve(value(++i, '--dir'));
|
|
207
|
+
else if (argv[i] === '--target')
|
|
208
|
+
opts.targets = value(++i, '--target').split(',').filter(Boolean);
|
|
209
|
+
else if (argv[i] === '--latest') opts.latest = true;
|
|
210
|
+
else if (argv[i] === '--no-install') opts.install = false;
|
|
211
|
+
else if (argv[i] === '--api') opts.api = value(++i, '--api').replace(/\/$/, '');
|
|
212
|
+
else if (argv[i] === '--scopes')
|
|
213
|
+
opts.scopes = value(++i, '--scopes').split(',').filter(Boolean);
|
|
214
|
+
else if (argv[i] === '--no-wait') opts.wait = false;
|
|
215
|
+
else if (argv[i] === '--wait') opts.wait = true;
|
|
216
|
+
else if (argv[i] === '--json') opts.json = true;
|
|
217
|
+
else if (argv[i] === '--project') opts.project = value(++i, '--project');
|
|
218
|
+
else if (argv[i] === '--create') opts.create = value(++i, '--create');
|
|
219
|
+
else if (argv[i] === '--url') opts.url = value(++i, '--url');
|
|
220
|
+
else if (argv[i] === '--env-file') opts.envFile = value(++i, '--env-file');
|
|
221
|
+
else if (argv[i] === '--with-secret') opts.withSecret = true;
|
|
222
|
+
else throw new Error(`unknown option ${argv[i]}`);
|
|
223
|
+
}
|
|
224
|
+
if (opts.targets.length === 0) throw new Error(`--target needs one of ${TARGETS.join(', ')}`);
|
|
225
|
+
const bad = opts.targets.filter((t) => !TARGETS.includes(t));
|
|
226
|
+
if (bad.length) throw new Error(`unknown target ${bad.join(',')} (use ${TARGETS.join(', ')})`);
|
|
227
|
+
return opts;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function init(opts) {
|
|
231
|
+
const pkgFile = join(opts.dir, 'package.json');
|
|
232
|
+
if (!existsSync(pkgFile))
|
|
233
|
+
throw new Error(`no package.json in ${opts.dir}; run this in your project`);
|
|
234
|
+
const pkg = readJson(pkgFile);
|
|
235
|
+
|
|
236
|
+
if (!installedContext(opts.dir) && opts.install) {
|
|
237
|
+
const [cmd, ...args] = packageManager(opts.dir);
|
|
238
|
+
console.log(`installing ${PKG} with ${cmd}…`);
|
|
239
|
+
const r = spawnSync(cmd, [...args, PKG], { cwd: opts.dir, stdio: 'inherit' });
|
|
240
|
+
if (r.status !== 0) throw new Error(`${cmd} ${args.join(' ')} ${PKG} failed`);
|
|
241
|
+
// the package must now carry the agent context; an old release does not, and pointer files
|
|
242
|
+
// that lead to a missing file would only mislead the agent
|
|
243
|
+
if (!installedContext(opts.dir)) {
|
|
244
|
+
const v = installedVersion(opts.dir);
|
|
245
|
+
throw new Error(
|
|
246
|
+
v
|
|
247
|
+
? `${PKG} ${v} was installed but has no agent context (dist/agent/CONTEXT.md). Install a newer release: ${cmd} ${args.join(' ')} ${PKG}@latest. Nothing else was written.`
|
|
248
|
+
: `${PKG} is not in node_modules after the install. Nothing else was written.`,
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const ctx = installedContext(opts.dir);
|
|
253
|
+
if (!ctx) console.warn(`${PKG} is not installed; agents will have nothing to read until it is.`);
|
|
254
|
+
else if (!hasServerEntry(opts.dir))
|
|
255
|
+
console.warn(
|
|
256
|
+
`warning: ${PKG} ${ctx.version} has no '${PKG}/server' entry, so createUserJwt is not available. Upgrade ${PKG}.`,
|
|
257
|
+
);
|
|
258
|
+
|
|
259
|
+
writeEnvExample(opts, pkg);
|
|
260
|
+
writeAgentFiles(opts);
|
|
261
|
+
|
|
262
|
+
const key = clientEnvName(pkg);
|
|
263
|
+
console.log(`
|
|
264
|
+
Done${ctx ? ` (${PKG} ${ctx.version})` : ''}. Next:
|
|
265
|
+
1. Create a project in the Zolio dashboard; put its public key in ${key} and its secret in ZOLIO_SECRET (backend secrets only).
|
|
266
|
+
2. Mount the widget once, near the app root:
|
|
267
|
+
import { ZolioWidget } from '@zolio/react';
|
|
268
|
+
<ZolioWidget projectKey={/* ${key} */} />
|
|
269
|
+
3. For logged-in users, sign them on your backend with createUserJwt from '@zolio/react/server'.
|
|
270
|
+
Or let your coding agent do all of it: run \`npx -y @zolio/cli prompt\` and paste the output into it.`);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function check(opts) {
|
|
274
|
+
const ctx = installedContext(opts.dir);
|
|
275
|
+
if (!ctx) {
|
|
276
|
+
console.error(`${PKG} is not installed in ${opts.dir}`);
|
|
277
|
+
return 1;
|
|
278
|
+
}
|
|
279
|
+
let code = 0;
|
|
280
|
+
console.log(`${PKG} ${ctx.version} installed; context present.`);
|
|
281
|
+
if (!hasServerEntry(opts.dir)) {
|
|
282
|
+
console.error(`${PKG} ${ctx.version} has no '${PKG}/server' entry. Upgrade ${PKG}.`);
|
|
283
|
+
code = 1;
|
|
284
|
+
}
|
|
285
|
+
for (const t of opts.targets) {
|
|
286
|
+
const { file } = FILES[t](opts.dir);
|
|
287
|
+
if (!(existsSync(file) && readFileSync(file, 'utf8').includes(CONTEXT))) {
|
|
288
|
+
console.error(
|
|
289
|
+
`missing pointer: ${file.slice(opts.dir.length + 1)} (run: npx -y @zolio/cli agents)`,
|
|
290
|
+
);
|
|
291
|
+
code = 1;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (opts.latest) {
|
|
295
|
+
const r = spawnSync('npm', ['view', PKG, 'version'], { encoding: 'utf8' });
|
|
296
|
+
const latest = r.stdout?.trim();
|
|
297
|
+
if (r.status !== 0 || !latest) console.error('could not read the latest version from npm');
|
|
298
|
+
else if (compareVersions(ctx.version, latest) < 0) {
|
|
299
|
+
console.error(
|
|
300
|
+
`outdated: installed ${ctx.version}, latest ${latest}. Update ${PKG}; agent context follows.`,
|
|
301
|
+
);
|
|
302
|
+
code = 1;
|
|
303
|
+
} else console.log(`up to date (${ctx.version}, latest on npm ${latest}).`);
|
|
304
|
+
}
|
|
305
|
+
return code;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// --- login, projects, setup ------------------------------------------------------------------------
|
|
309
|
+
|
|
310
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
311
|
+
const say = (opts, human, data) => console.log(opts.json ? JSON.stringify(data) : human);
|
|
312
|
+
|
|
313
|
+
/** A token must never travel over plain http, except to a server on this machine. */
|
|
314
|
+
function checkApi(api) {
|
|
315
|
+
const u = new URL(api);
|
|
316
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname);
|
|
317
|
+
if (u.protocol !== 'https:' && !(local && u.protocol === 'http:')) {
|
|
318
|
+
throw new Error(`--api must be https (got ${api})`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function requireToken(opts) {
|
|
323
|
+
checkApi(opts.api);
|
|
324
|
+
const saved = loadToken(opts.api);
|
|
325
|
+
if (!saved) throw new Error('not logged in (or the login expired). Run: npx -y @zolio/cli login');
|
|
326
|
+
return saved;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function startLogin(opts) {
|
|
330
|
+
checkApi(opts.api);
|
|
331
|
+
const d = await call(opts.api, 'POST', '/device', {
|
|
332
|
+
body: { clientName: `zolio-cli on ${hostname()}`.slice(0, 80), scopes: opts.scopes },
|
|
333
|
+
});
|
|
334
|
+
savePending(opts.api, {
|
|
335
|
+
deviceCode: d.deviceCode,
|
|
336
|
+
interval: d.interval,
|
|
337
|
+
expiresAt: new Date(Date.now() + d.expiresIn * 1000).toISOString(),
|
|
338
|
+
scopes: opts.scopes,
|
|
339
|
+
});
|
|
340
|
+
say(
|
|
341
|
+
opts,
|
|
342
|
+
`Approve this login in your browser (an owner of your Zolio organization must do it):\n\n ${d.verificationUriComplete}\n\nCode: ${d.userCode} (valid ${Math.round(d.expiresIn / 60)} minutes)\nOnly approve a code you just saw here.`,
|
|
343
|
+
{ verificationUri: d.verificationUriComplete, userCode: d.userCode, expiresIn: d.expiresIn },
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async function waitForApproval(opts) {
|
|
348
|
+
const pending = loadPending(opts.api);
|
|
349
|
+
if (!pending) throw new Error('no login in progress. Run: npx -y @zolio/cli login --no-wait');
|
|
350
|
+
let interval = pending.interval ?? 5;
|
|
351
|
+
while (Date.parse(pending.expiresAt) > Date.now()) {
|
|
352
|
+
await sleep(Number(process.env.ZOLIO_POLL_INTERVAL_MS) || interval * 1000);
|
|
353
|
+
try {
|
|
354
|
+
const t = await call(opts.api, 'POST', '/token', {
|
|
355
|
+
body: { deviceCode: pending.deviceCode },
|
|
356
|
+
});
|
|
357
|
+
saveToken(opts.api, {
|
|
358
|
+
accessToken: t.accessToken,
|
|
359
|
+
scopes: t.scopes,
|
|
360
|
+
expiresAt: new Date(Date.now() + t.expiresIn * 1000).toISOString(),
|
|
361
|
+
});
|
|
362
|
+
dropPending(opts.api);
|
|
363
|
+
say(
|
|
364
|
+
opts,
|
|
365
|
+
`Logged in${t.scopes.length ? ` (may: ${t.scopes.join(', ')})` : ' (read only)'}. Valid for ${Math.round(t.expiresIn / 3600)} hours.`,
|
|
366
|
+
{ loggedIn: true, scopes: t.scopes },
|
|
367
|
+
);
|
|
368
|
+
return;
|
|
369
|
+
} catch (e) {
|
|
370
|
+
if (e instanceof ApiError && e.code === 'authorization_pending') continue;
|
|
371
|
+
if (e instanceof ApiError && e.code === 'slow_down') {
|
|
372
|
+
interval += 5;
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
dropPending(opts.api);
|
|
376
|
+
throw e;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
dropPending(opts.api);
|
|
380
|
+
throw new Error('the code expired before it was approved. Run login again.');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async function login(opts) {
|
|
384
|
+
// agents run `--no-wait`, show the code to the person, then `--wait`; people just run `login`
|
|
385
|
+
if (opts.wait !== true) await startLogin(opts);
|
|
386
|
+
if (opts.wait !== false) await waitForApproval(opts);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function logout(opts) {
|
|
390
|
+
checkApi(opts.api);
|
|
391
|
+
const saved = loadToken(opts.api);
|
|
392
|
+
if (saved) {
|
|
393
|
+
// revoke on the server too, so a copied token is dead; a failure must not keep the file around
|
|
394
|
+
await call(opts.api, 'DELETE', '/session', { token: saved.accessToken }).catch(() => {});
|
|
395
|
+
}
|
|
396
|
+
dropToken(opts.api);
|
|
397
|
+
dropPending(opts.api);
|
|
398
|
+
say(opts, 'Logged out.', { loggedIn: false });
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async function listProjects(opts) {
|
|
402
|
+
const saved = requireToken(opts);
|
|
403
|
+
return call(opts.api, 'GET', '/projects', { token: saved.accessToken });
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
async function projects(opts) {
|
|
407
|
+
const { projects: list } = await listProjects(opts);
|
|
408
|
+
if (opts.json)
|
|
409
|
+
return console.log(
|
|
410
|
+
JSON.stringify(list.map(({ id, name, url, publicKey }) => ({ id, name, url, publicKey }))),
|
|
411
|
+
);
|
|
412
|
+
if (list.length === 0)
|
|
413
|
+
return console.log(
|
|
414
|
+
'No projects this login can see. Create one: zolio setup --create <name> --url <url>',
|
|
415
|
+
);
|
|
416
|
+
for (const p of list) console.log(`${p.id} ${p.name} ${p.url} ${p.publicKey}`);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async function whoami(opts) {
|
|
420
|
+
const saved = requireToken(opts);
|
|
421
|
+
const { projects: list, scopes } = await listProjects(opts);
|
|
422
|
+
say(
|
|
423
|
+
opts,
|
|
424
|
+
`Logged in to ${opts.api} until ${saved.expiresAt}. May: ${scopes.length ? scopes.join(', ') : 'read only'}. Sees ${list.length} project(s).`,
|
|
425
|
+
{ api: opts.api, expiresAt: saved.expiresAt, scopes, projects: list.length },
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function setup(opts) {
|
|
430
|
+
const saved = requireToken(opts);
|
|
431
|
+
const pkgFile = join(opts.dir, 'package.json');
|
|
432
|
+
const pkg = existsSync(pkgFile) ? readJson(pkgFile) : {};
|
|
433
|
+
const token = saved.accessToken;
|
|
434
|
+
let project;
|
|
435
|
+
let secret = null;
|
|
436
|
+
|
|
437
|
+
if (opts.create) {
|
|
438
|
+
if (!opts.url) throw new Error('--create needs --url <the production site, https://…>');
|
|
439
|
+
const r = await call(opts.api, 'POST', '/projects', {
|
|
440
|
+
token,
|
|
441
|
+
body: { name: opts.create, url: opts.url, defaultLocale: 'en', extraOrigins: [] },
|
|
442
|
+
});
|
|
443
|
+
project = r.project;
|
|
444
|
+
secret = r.signingSecret;
|
|
445
|
+
} else {
|
|
446
|
+
const { projects: list } = await listProjects(opts);
|
|
447
|
+
const wanted = opts.project;
|
|
448
|
+
if (!wanted) {
|
|
449
|
+
throw new Error(
|
|
450
|
+
list.length === 0
|
|
451
|
+
? 'no projects visible. Use --create <name> --url <url>.'
|
|
452
|
+
: `pick one with --project <id|name>:\n${list.map((p) => ` ${p.id} ${p.name}`).join('\n')}`,
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
const matches = list.filter(
|
|
456
|
+
(p) =>
|
|
457
|
+
p.id === wanted || p.publicKey === wanted || p.name.toLowerCase() === wanted.toLowerCase(),
|
|
458
|
+
);
|
|
459
|
+
if (matches.length !== 1) {
|
|
460
|
+
throw new Error(
|
|
461
|
+
matches.length === 0
|
|
462
|
+
? `no visible project "${wanted}".`
|
|
463
|
+
: `"${wanted}" matches ${matches.length} projects; use the id.`,
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
project = matches[0];
|
|
467
|
+
if (opts.withSecret) {
|
|
468
|
+
// replaces the secret: the old one keeps working for 24 hours so a running shop is not cut off
|
|
469
|
+
const r = await call(opts.api, 'POST', `/projects/${project.id}/rotate-secret`, {
|
|
470
|
+
token,
|
|
471
|
+
body: {},
|
|
472
|
+
});
|
|
473
|
+
secret = r.signingSecret;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const keyName = clientEnvName(pkg);
|
|
478
|
+
const values = { [keyName]: project.publicKey };
|
|
479
|
+
if (secret) values.ZOLIO_SECRET = secret;
|
|
480
|
+
const target = join(opts.dir, opts.envFile);
|
|
481
|
+
// the secret goes into a file only once git is told to ignore it
|
|
482
|
+
const added = secret ? ensureIgnored(opts.dir, opts.envFile) : false;
|
|
483
|
+
upsertEnv(target, values);
|
|
484
|
+
|
|
485
|
+
const note = secret
|
|
486
|
+
? `Wrote ${keyName} and ZOLIO_SECRET to ${opts.envFile}${added ? ' (and added it to .gitignore)' : ''}. The secret was not printed. Put ZOLIO_SECRET in the production host's secrets too.`
|
|
487
|
+
: `Wrote ${keyName} to ${opts.envFile}. No secret was written: it is only shown when a project is created or re-keyed. For a project that already has one, copy it from the dashboard, or run again with --with-secret (needs the secrets:rotate approval; the old secret keeps working 24 hours).`;
|
|
488
|
+
say(opts, `Project "${project.name}" (${project.id}).\n${note}`, {
|
|
489
|
+
project: { id: project.id, name: project.name, publicKey: project.publicKey },
|
|
490
|
+
wrote: Object.keys(values),
|
|
491
|
+
file: opts.envFile,
|
|
492
|
+
secretWritten: Boolean(secret),
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async function main(argv) {
|
|
497
|
+
const opts = parse(argv);
|
|
498
|
+
if (opts.cmd === 'prompt') {
|
|
499
|
+
console.log(SETUP_PROMPT);
|
|
500
|
+
return 0;
|
|
501
|
+
}
|
|
502
|
+
if (opts.cmd === 'login') return (await login(opts), 0);
|
|
503
|
+
if (opts.cmd === 'logout') return (await logout(opts), 0);
|
|
504
|
+
if (opts.cmd === 'projects') return (await projects(opts), 0);
|
|
505
|
+
if (opts.cmd === 'whoami') return (await whoami(opts), 0);
|
|
506
|
+
if (opts.cmd === 'setup') return (await setup(opts), 0);
|
|
507
|
+
if (opts.cmd === 'init') return init(opts) ?? 0;
|
|
508
|
+
if (opts.cmd === 'agents') {
|
|
509
|
+
if (!installedContext(opts.dir)) throw new Error(`${PKG} is not installed in ${opts.dir}`);
|
|
510
|
+
writeAgentFiles(opts);
|
|
511
|
+
return 0;
|
|
512
|
+
}
|
|
513
|
+
if (opts.cmd === 'check') return check(opts);
|
|
514
|
+
if (opts.cmd === 'print') {
|
|
515
|
+
const ctx = installedContext(opts.dir);
|
|
516
|
+
if (!ctx) throw new Error(`${PKG} is not installed in ${opts.dir}`);
|
|
517
|
+
process.stdout.write(readFileSync(ctx.file, 'utf8'));
|
|
518
|
+
return 0;
|
|
519
|
+
}
|
|
520
|
+
console.error(USAGE);
|
|
521
|
+
return opts.cmd ? 1 : 0;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
try {
|
|
525
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
526
|
+
} catch (e) {
|
|
527
|
+
console.error(`zolio: ${e.message}`);
|
|
528
|
+
process.exitCode = 1;
|
|
529
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zolio/cli",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Set up Zolio in a project: install the SDK, env placeholders, and coding-agent context.",
|
|
5
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"zolio": "bin/zolio.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"typecheck": "node --check bin/zolio.mjs",
|
|
23
|
+
"test": "vitest run"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^26.6.4",
|
|
27
|
+
"vitest": "^5.0.3"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"zolio",
|
|
31
|
+
"support",
|
|
32
|
+
"customer-support",
|
|
33
|
+
"chat",
|
|
34
|
+
"widget",
|
|
35
|
+
"cli",
|
|
36
|
+
"setup"
|
|
37
|
+
]
|
|
38
|
+
}
|
package/src/api.mjs
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export const DEFAULT_API = 'https://api.zolio.app';
|
|
2
|
+
|
|
3
|
+
export class ApiError extends Error {
|
|
4
|
+
constructor(status, code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.status = status;
|
|
7
|
+
this.code = code;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** One call to the Zolio API. Never logs a token, never follows a redirect off the API. */
|
|
12
|
+
export async function call(api, method, path, { body, token } = {}) {
|
|
13
|
+
let res;
|
|
14
|
+
try {
|
|
15
|
+
res = await fetch(`${api}/v1/cli${path}`, {
|
|
16
|
+
method,
|
|
17
|
+
redirect: 'error',
|
|
18
|
+
headers: {
|
|
19
|
+
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
20
|
+
...(token ? { authorization: `Bearer ${token}` } : {}),
|
|
21
|
+
},
|
|
22
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
23
|
+
});
|
|
24
|
+
} catch {
|
|
25
|
+
throw new ApiError(0, 'network', `Could not reach ${api}. Check the connection or --api.`);
|
|
26
|
+
}
|
|
27
|
+
const data = await res.json().catch(() => null);
|
|
28
|
+
if (!res.ok) {
|
|
29
|
+
throw new ApiError(
|
|
30
|
+
res.status,
|
|
31
|
+
data?.error?.code ?? 'error',
|
|
32
|
+
data?.error?.message ?? `The API answered ${res.status}.`,
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return data;
|
|
36
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
// Login state lives in the user's config directory, never in the project: a project folder gets
|
|
6
|
+
// committed and shared, a token must not. Files are owner-only (0600).
|
|
7
|
+
export const configDir = () =>
|
|
8
|
+
process.env.ZOLIO_CONFIG_DIR ||
|
|
9
|
+
join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'zolio');
|
|
10
|
+
|
|
11
|
+
const file = (name) => join(configDir(), name);
|
|
12
|
+
|
|
13
|
+
function read(name) {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(readFileSync(file(name), 'utf8'));
|
|
16
|
+
} catch {
|
|
17
|
+
return {};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function write(name, data) {
|
|
22
|
+
const path = file(name);
|
|
23
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
24
|
+
writeFileSync(path, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
|
|
25
|
+
chmodSync(path, 0o600);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The saved login for one API, or null when missing or expired. */
|
|
29
|
+
export function loadToken(api, nowMs = Date.now()) {
|
|
30
|
+
const entry = read('credentials.json')[api];
|
|
31
|
+
if (!entry || Date.parse(entry.expiresAt) <= nowMs) return null;
|
|
32
|
+
return entry;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function saveToken(api, entry) {
|
|
36
|
+
write('credentials.json', { ...read('credentials.json'), [api]: entry });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function dropToken(api) {
|
|
40
|
+
const all = read('credentials.json');
|
|
41
|
+
delete all[api];
|
|
42
|
+
if (Object.keys(all).length) write('credentials.json', all);
|
|
43
|
+
else rmSync(file('credentials.json'), { force: true });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const loadPending = (api) => read('pending.json')[api] ?? null;
|
|
47
|
+
export const savePending = (api, entry) =>
|
|
48
|
+
write('pending.json', { ...read('pending.json'), [api]: entry });
|
|
49
|
+
export function dropPending(api) {
|
|
50
|
+
const all = read('pending.json');
|
|
51
|
+
delete all[api];
|
|
52
|
+
if (Object.keys(all).length) write('pending.json', all);
|
|
53
|
+
else rmSync(file('pending.json'), { force: true });
|
|
54
|
+
}
|
package/src/env-file.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
|
|
5
|
+
/** Sets `NAME=value` lines in a dotenv file, keeping everything else as it was. */
|
|
6
|
+
export function upsertEnv(file, values) {
|
|
7
|
+
const current = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
8
|
+
const lines = current === '' ? [] : current.replace(/\n$/, '').split('\n');
|
|
9
|
+
for (const [name, value] of Object.entries(values)) {
|
|
10
|
+
const at = lines.findIndex((l) => l.startsWith(`${name}=`));
|
|
11
|
+
if (at === -1) lines.push(`${name}=${value}`);
|
|
12
|
+
else lines[at] = `${name}=${value}`;
|
|
13
|
+
}
|
|
14
|
+
writeFileSync(file, lines.join('\n') + '\n', { mode: 0o600 });
|
|
15
|
+
chmodSync(file, 0o600);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* True when git would ignore `name` (or there is no git to ask and .gitignore lists it). A file that
|
|
20
|
+
* will hold a secret must never be one `git add .` picks up.
|
|
21
|
+
*/
|
|
22
|
+
export function isIgnored(dir, name) {
|
|
23
|
+
const r = spawnSync('git', ['check-ignore', '-q', name], { cwd: dir });
|
|
24
|
+
if (r.status === 0) return true;
|
|
25
|
+
if (r.status === 1) return false;
|
|
26
|
+
const ignore = join(dir, '.gitignore');
|
|
27
|
+
return (
|
|
28
|
+
existsSync(ignore) &&
|
|
29
|
+
readFileSync(ignore, 'utf8')
|
|
30
|
+
.split('\n')
|
|
31
|
+
.some((l) => l.trim() === name)
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function ensureIgnored(dir, name) {
|
|
36
|
+
if (isIgnored(dir, name)) return false;
|
|
37
|
+
const ignore = join(dir, '.gitignore');
|
|
38
|
+
const current = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
|
|
39
|
+
writeFileSync(ignore, current + (current && !current.endsWith('\n') ? '\n' : '') + `${name}\n`);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
package/src/prompt.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// The text a person pastes into their coding agent to get Zolio installed end to end. It only
|
|
2
|
+
// uses commands that exist in this CLI, and keeps the secret out of the agent's output.
|
|
3
|
+
export const SETUP_PROMPT = `Set up Zolio (customer support widget) in this project, end to end. Do the steps in order and only ask me when a step says so.
|
|
4
|
+
|
|
5
|
+
1. Run \`npx -y @zolio/cli init\`. It installs @zolio/react, adds placeholders to .env.example and sets up agent files. Then read node_modules/@zolio/react/dist/agent/CONTEXT.md completely. It is the source of truth for the integration.
|
|
6
|
+
|
|
7
|
+
2. Log in to Zolio. Run \`npx -y @zolio/cli login --no-wait\`. Show me the link and code it prints and ask me to approve it in my browser (the owner of my Zolio organization has to; the code is valid for 10 minutes). Once I say it is approved, run \`npx -y @zolio/cli login --wait\`.
|
|
8
|
+
|
|
9
|
+
3. Get the project keys. Run \`npx -y @zolio/cli projects\`. If one project clearly matches this app, run \`npx -y @zolio/cli setup --project <id>\`. If none matches, create one with \`npx -y @zolio/cli setup --create "<app name>" --url <the production site URL>\` (ask me for the URL if you cannot tell). The command writes the keys to .env.local, which stays out of git. Never print, paste, log or commit the secret, and never put it in client code. If setup says it needs more access, tell me what it asks for; do not work around it.
|
|
10
|
+
|
|
11
|
+
4. Integrate, following CONTEXT.md: mount <ZolioWidget> once near the app root using the public project key, and for logged-in users add a backend route that returns a userJwt from createUserJwt (only your server code may read ZOLIO_SECRET). Follow this project's existing structure, framework and style.
|
|
12
|
+
|
|
13
|
+
5. Run this project's typecheck, tests and build. Fix what you broke. Then run \`npx -y @zolio/cli logout\`.
|
|
14
|
+
|
|
15
|
+
6. Tell me what changed, and what I still have to do myself: add ZOLIO_SECRET and the public key to the production host's secrets, and check that the production site's origin is allowed in the Zolio project settings.`;
|
package/src/versions.mjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Compares x.y.z[-pre] versions: negative when a < b. A prerelease is lower than its release. */
|
|
2
|
+
export function compareVersions(a, b) {
|
|
3
|
+
const split = (v) => {
|
|
4
|
+
const [core, pre] = v.replace(/^v/, '').split('+')[0].split('-');
|
|
5
|
+
return { nums: core.split('.').map((n) => Number.parseInt(n, 10) || 0), pre: pre ?? null };
|
|
6
|
+
};
|
|
7
|
+
const x = split(a);
|
|
8
|
+
const y = split(b);
|
|
9
|
+
for (let i = 0; i < 3; i++) {
|
|
10
|
+
const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
|
|
11
|
+
if (d !== 0) return d;
|
|
12
|
+
}
|
|
13
|
+
if (x.pre === y.pre) return 0;
|
|
14
|
+
if (x.pre === null) return 1;
|
|
15
|
+
if (y.pre === null) return -1;
|
|
16
|
+
return x.pre < y.pre ? -1 : 1;
|
|
17
|
+
}
|