create-heresay 0.2.44 → 0.2.46
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/package.json +1 -1
- package/release/VERSION +1 -1
- package/release/firebase.json +4 -0
- package/release/functions/lib/core/chat.js +1 -1
- package/release/functions/lib/core/notifications.js +1 -1
- package/release/functions/lib/core/oauth.js +1 -1
- package/release/functions/lib/core/version.js +1 -1
- package/release/functions/lib/providers/firebase/api.js +8 -1
- package/release/functions/lib/providers/firebase/node-server.js +4 -1
- package/release/public/dashboard.js +5 -5
- package/release/public/docs.html +4 -4
- package/src/backup.mjs +108 -0
- package/src/cli.mjs +117 -14
- package/src/steps.mjs +14 -5
- package/release/public/index.html +0 -15
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-heresay",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.46",
|
|
4
4
|
"description": "Set up your own Heresay: in-app feedback that every report gets a hearing. Creates a Firebase project in your Google account and deploys the dashboard, API and SDK to it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/release/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.2.
|
|
1
|
+
0.2.46
|
package/release/firebase.json
CHANGED
|
@@ -235,7 +235,7 @@ async function findApp(v, deps) {
|
|
|
235
235
|
throw new ToolError(`No app called "${want}". The apps are: ${ps.map((p) => p.name).join(', ') || 'none yet'}.`);
|
|
236
236
|
return hit;
|
|
237
237
|
}
|
|
238
|
-
const dashboardLink = (req, deps, p) => `${baseUrl(req, deps)}
|
|
238
|
+
const dashboardLink = (req, deps, p) => `${baseUrl(req, deps)}/#/apps/${p.id}`;
|
|
239
239
|
const appNames = (ps) => ps.map((p) => `${p.name} (${p.platform})`).join(', ');
|
|
240
240
|
/** A preview, nothing sent: which app, what type, the text, and where else it could go. */
|
|
241
241
|
async function draftRequest(a, member, via, deps) {
|
|
@@ -237,7 +237,7 @@ export async function notify(event, project, reportId, deps) {
|
|
|
237
237
|
const found = await deps.store.getReport(project.id, reportId).catch(() => null);
|
|
238
238
|
const type = (found && TYPE[found.type]) || null;
|
|
239
239
|
const origin = deps.selfOrigins?.[0];
|
|
240
|
-
const link = origin ? `${origin}
|
|
240
|
+
const link = origin ? `${origin}/#/apps/${encodeURIComponent(project.id)}` : null;
|
|
241
241
|
const meta = [type ? `${type[0]} ${type[1]}` : null, reportId];
|
|
242
242
|
const text = [`${emoji} ${head} · ${project.name}`, `${labels[event]}.`, meta.filter(Boolean).join(' · ')].join('\n') + (link ? `\n${link}` : '');
|
|
243
243
|
// Telegram gets bold and a link; the app name is the team's own, escaped, and nothing from a reporter is in it.
|
|
@@ -170,7 +170,7 @@ export async function authorize(req, deps) {
|
|
|
170
170
|
if (v)
|
|
171
171
|
keep.set(k, v);
|
|
172
172
|
}
|
|
173
|
-
return json(302, { redirect: true }, { location: `${baseUrl(req, deps)}
|
|
173
|
+
return json(302, { redirect: true }, { location: `${baseUrl(req, deps)}/#/authorize?${keep}` });
|
|
174
174
|
}
|
|
175
175
|
/** What the dashboard shows on the "Allow?" page, before anyone says yes. */
|
|
176
176
|
export async function describeAsk(q, deps) {
|
|
@@ -30,11 +30,18 @@ const deps = {
|
|
|
30
30
|
telegramPhoto: telegramPhoto(),
|
|
31
31
|
telegramApi: telegramApi(),
|
|
32
32
|
};
|
|
33
|
+
/**
|
|
34
|
+
* The addresses this Heresay's dashboard is served from. A named Hosting site (HERESAY_SITE,
|
|
35
|
+
* written to functions/.env by the deploy) comes first: it is the one people use, so OAuth
|
|
36
|
+
* discovery and alert links name it, not the project's default site.
|
|
37
|
+
*/
|
|
33
38
|
function selfOrigins() {
|
|
34
39
|
const id = process.env.GCLOUD_PROJECT;
|
|
35
40
|
if (process.env.FUNCTIONS_EMULATOR === 'true')
|
|
36
41
|
return ['http://127.0.0.1:5055', 'http://localhost:5055'];
|
|
37
|
-
|
|
42
|
+
const site = process.env.HERESAY_SITE;
|
|
43
|
+
const named = site && site !== id ? [`https://${site}.web.app`, `https://${site}.firebaseapp.com`] : [];
|
|
44
|
+
return id ? [...named, `https://${id}.web.app`, `https://${id}.firebaseapp.com`] : named;
|
|
38
45
|
}
|
|
39
46
|
/** Hosting rewrites /v1/** and /.well-known/** here, so the SDK, the API and the dashboard share one origin. */
|
|
40
47
|
// create-heresay writes HERESAY_REGION to functions/.env; it is read when the deploy loads this file.
|
|
@@ -156,7 +156,10 @@ function reserved(res, path) {
|
|
|
156
156
|
}
|
|
157
157
|
async function file(res, path) {
|
|
158
158
|
let rel = path === '/sdk/v1.js' ? '/sdk.js' : path;
|
|
159
|
-
|
|
159
|
+
// The dashboard is the root of a Heresay; /app/ is its older address and keeps working.
|
|
160
|
+
if (rel === '/')
|
|
161
|
+
rel = '/app/index.html';
|
|
162
|
+
else if (rel.endsWith('/'))
|
|
160
163
|
rel += 'index.html';
|
|
161
164
|
const full = join(PUBLIC_DIR, normalize(rel));
|
|
162
165
|
if (!full.startsWith(PUBLIC_DIR + '/') || rel.split('/').some((p) => p.startsWith('.'))) {
|
|
@@ -188,7 +188,7 @@
|
|
|
188
188
|
gateMsg('Sending…');
|
|
189
189
|
// A chat app sent them here to say yes: come back to that page after the link.
|
|
190
190
|
if (/^#\/authorize\?/.test(location.hash)) localStorage.setItem('heresay.after', JSON.stringify({ hash: location.hash, at: Date.now() }));
|
|
191
|
-
auth.sendSignInLinkToEmail(email, { url: location.origin + '/
|
|
191
|
+
auth.sendSignInLinkToEmail(email, { url: location.origin + '/', handleCodeInApp: true })
|
|
192
192
|
.then(function () {
|
|
193
193
|
localStorage.setItem('heresay.email', email);
|
|
194
194
|
gateMsg('Check your inbox at ' + email + '. The link signs you in here. It can take a minute, and may land in spam.');
|
|
@@ -201,11 +201,11 @@
|
|
|
201
201
|
|
|
202
202
|
function finishLink(email) {
|
|
203
203
|
auth.signInWithEmailLink(email, location.href)
|
|
204
|
-
.then(function () { localStorage.removeItem('heresay.email'); history.replaceState(null, '',
|
|
204
|
+
.then(function () { localStorage.removeItem('heresay.email'); history.replaceState(null, '', location.pathname); finishingLink = false; })
|
|
205
205
|
.catch(function (x) {
|
|
206
206
|
gateMsg(x.code === 'auth/invalid-action-code'
|
|
207
207
|
? 'That link has expired or was already used. Ask for a new one.' : x.message, true);
|
|
208
|
-
history.replaceState(null, '',
|
|
208
|
+
history.replaceState(null, '', location.pathname); finishingLink = false;
|
|
209
209
|
$('link-form').querySelector('button').textContent = 'Email me a sign-in link';
|
|
210
210
|
});
|
|
211
211
|
}
|
|
@@ -233,7 +233,7 @@
|
|
|
233
233
|
try {
|
|
234
234
|
var after = JSON.parse(localStorage.getItem('heresay.after') || 'null');
|
|
235
235
|
localStorage.removeItem('heresay.after');
|
|
236
|
-
if (after && Date.now() - after.at < 15 * 60000 && !location.hash) history.replaceState(null, '',
|
|
236
|
+
if (after && Date.now() - after.at < 15 * 60000 && !location.hash) history.replaceState(null, '', location.pathname + after.hash);
|
|
237
237
|
} catch (e) { /* nothing saved */ }
|
|
238
238
|
route(); // first, so the view is already waiting when the app is shown
|
|
239
239
|
show('app');
|
|
@@ -2767,7 +2767,7 @@
|
|
|
2767
2767
|
draw(b.members);
|
|
2768
2768
|
form.reset();
|
|
2769
2769
|
err.className = 'ok-msg';
|
|
2770
|
-
err.textContent = 'Added. Send them this address; they sign in with that email: ' + location.origin
|
|
2770
|
+
err.textContent = 'Added. Send them this address; they sign in with that email: ' + location.origin;
|
|
2771
2771
|
}).catch(function (x) { err.className = 'err'; err.textContent = x.message; });
|
|
2772
2772
|
};
|
|
2773
2773
|
view.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'Add someone' }), form]));
|
package/release/public/docs.html
CHANGED
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
<body>
|
|
13
13
|
<div class="wrap">
|
|
14
14
|
<nav class="nav" aria-label="Main">
|
|
15
|
-
<a href="/" aria-label="Heresay home"><img src="/logo.svg" alt="Heresay" height="34"></a>
|
|
16
|
-
<div class="links"><a href="
|
|
15
|
+
<a href="https://sibhimanyu.github.io/heresay/" aria-label="Heresay home"><img src="/logo.svg" alt="Heresay" height="34"></a>
|
|
16
|
+
<div class="links"><a href="https://sibhimanyu.github.io/heresay/how-it-works.html">How it works</a><a href="/docs.html">Docs</a><a class="keep" href="/">Sign in</a></div>
|
|
17
17
|
<a class="btn btn-p btn-sm" href="#self-host">Set up</a>
|
|
18
18
|
</nav>
|
|
19
19
|
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
<h2 id="quick-start">Add it to an app</h2>
|
|
38
38
|
<ol>
|
|
39
|
-
<li><a href="/
|
|
39
|
+
<li><a href="/">Sign in</a> to your dashboard and choose <b>Add an app</b>. Pick the platform, give it a name, and list the websites it runs on, for example <code>https://app.example.com</code> and <code>http://localhost:3000</code>.</li>
|
|
40
40
|
<li>Copy the line the dashboard shows you (it has steps for Next.js, Nuxt and others too) and paste it before <code></body></code> on every page:</li>
|
|
41
41
|
</ol>
|
|
42
42
|
<pre><code><span class="k"><script</span> src="ORIGIN/sdk/v1.js" data-key="pk_your_key" defer<span class="k">></script></span></code></pre>
|
|
@@ -214,7 +214,7 @@ connect-src ORIGIN;</code></pre>
|
|
|
214
214
|
</main>
|
|
215
215
|
</div>
|
|
216
216
|
</div>
|
|
217
|
-
<footer class="site"><div class="wrap"><span>© 2026 Heresay</span><span><a href="/">Home</a> · <a href="/
|
|
217
|
+
<footer class="site"><div class="wrap"><span>© 2026 Heresay</span><span><a href="https://sibhimanyu.github.io/heresay/">Home</a> · <a href="/">Sign in</a></span></div></footer>
|
|
218
218
|
<script>
|
|
219
219
|
document.querySelectorAll('[data-origin]').forEach(function (el) { el.innerHTML = el.innerHTML.replace(/ORIGIN/g, location.origin); });
|
|
220
220
|
</script>
|
package/src/backup.mjs
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backup and restore of a Heresay's data: every Firestore document, as Firestore's own typed
|
|
3
|
+
* values, so a restore puts back exactly what was there (timestamps, nulls, nested maps).
|
|
4
|
+
*
|
|
5
|
+
* Not included: rate-limit counters (`rate/`, short-lived by design) and Firebase Auth's user
|
|
6
|
+
* list. Nobody needs the latter: the team is the member list in `meta/instance`, kept by email,
|
|
7
|
+
* and members sign in again with an email link on the restored Heresay.
|
|
8
|
+
*
|
|
9
|
+
* The file holds secrets (Telegram and Cliq tokens, hashed agent tokens, chat-app grants), so it
|
|
10
|
+
* is written readable by its owner only.
|
|
11
|
+
*
|
|
12
|
+
* `call(method, url, opts)` is google.mjs's `g`; tests pass one that talks to the emulator.
|
|
13
|
+
*/
|
|
14
|
+
export const FORMAT = 'heresay-backup';
|
|
15
|
+
const SKIP_ROOT = new Set(['rate']);
|
|
16
|
+
const BATCH = 400;
|
|
17
|
+
|
|
18
|
+
const root = (base, id) => `${base}/projects/${id}/databases/(default)/documents`;
|
|
19
|
+
|
|
20
|
+
async function collectionIds(call, parent, project) {
|
|
21
|
+
const ids = [];
|
|
22
|
+
let pageToken;
|
|
23
|
+
do {
|
|
24
|
+
const b = await call('POST', `${parent}:listCollectionIds`, { project, body: { pageSize: 300, ...(pageToken ? { pageToken } : {}) } });
|
|
25
|
+
ids.push(...(b.collectionIds ?? []));
|
|
26
|
+
pageToken = b.nextPageToken;
|
|
27
|
+
} while (pageToken);
|
|
28
|
+
return ids;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Every document under `parent`, depth first. `showMissing` finds documents that only exist as a parent of subcollections. */
|
|
32
|
+
async function walk(call, base, project, parent, prefix, out, say) {
|
|
33
|
+
for (const col of await collectionIds(call, parent, project)) {
|
|
34
|
+
if (!prefix && SKIP_ROOT.has(col)) continue;
|
|
35
|
+
let pageToken;
|
|
36
|
+
do {
|
|
37
|
+
const q = new URLSearchParams({ pageSize: '300', showMissing: 'true', ...(pageToken ? { pageToken } : {}) });
|
|
38
|
+
const b = await call('GET', `${parent}/${col}?${q}`, { project });
|
|
39
|
+
for (const d of b.documents ?? []) {
|
|
40
|
+
const path = d.name.slice(d.name.indexOf('/documents/') + '/documents/'.length);
|
|
41
|
+
if (d.createTime) out.push({ path, fields: d.fields ?? {} });
|
|
42
|
+
if (out.length % 200 === 0) say?.(`Read ${out.length} documents`);
|
|
43
|
+
// Heresay's ids hold colons (`auth/code:x`). Firestore can't list subcollections under those
|
|
44
|
+
// (the colon reads as a method call, encoded or not). In Heresay they are leaf documents; any
|
|
45
|
+
// that can't be scanned is listed in the backup, never skipped silently.
|
|
46
|
+
const url = `${root(base, project)}/${path.split('/').map(encodeURIComponent).join('/')}`;
|
|
47
|
+
try { await walk(call, base, project, url, path, out, say); } catch (e) {
|
|
48
|
+
if (!path.split('/').pop().includes(':') || !/400|INVALID_ARGUMENT|isn't valid/i.test(String(e.message ?? e) + (e.status ?? ''))) throw e;
|
|
49
|
+
out.unscanned.push(path);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
pageToken = b.nextPageToken;
|
|
53
|
+
} while (pageToken);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function dump(call, { base, project, version, say }) {
|
|
58
|
+
const documents = [];
|
|
59
|
+
documents.unscanned = [];
|
|
60
|
+
await walk(call, base, project, root(base, project), '', documents, say);
|
|
61
|
+
const unscanned = documents.unscanned;
|
|
62
|
+
documents.sort((a, b) => a.path.localeCompare(b.path));
|
|
63
|
+
return { format: FORMAT, format_version: 1, heresay: version, project, created_at: new Date().toISOString(), skipped: [...SKIP_ROOT], unscanned, documents: [...documents] };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function summarize(backup) {
|
|
67
|
+
const by = {};
|
|
68
|
+
for (const d of backup.documents) {
|
|
69
|
+
const parts = d.path.split('/');
|
|
70
|
+
const kind = parts.length >= 4 ? parts[parts.length - 2] : parts[0];
|
|
71
|
+
by[kind] = (by[kind] ?? 0) + 1;
|
|
72
|
+
}
|
|
73
|
+
return by;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function check(backup) {
|
|
77
|
+
if (backup?.format !== FORMAT || backup.format_version !== 1 || !Array.isArray(backup.documents)) {
|
|
78
|
+
throw new Error('That file isn’t a Heresay backup.');
|
|
79
|
+
}
|
|
80
|
+
for (const d of backup.documents) {
|
|
81
|
+
const parts = typeof d.path === 'string' ? d.path.split('/') : [];
|
|
82
|
+
const sound = parts.length >= 2 && parts.length % 2 === 0 && parts.every((x) => x && x !== '.' && x !== '..');
|
|
83
|
+
if (!sound || !d.fields || typeof d.fields !== 'object') {
|
|
84
|
+
throw new Error(`The backup has a damaged entry (${String(d.path).slice(0, 60)}).`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return backup;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** True if the project already holds a Heresay (its team document). */
|
|
91
|
+
export async function hasData(call, { base, project }) {
|
|
92
|
+
const ids = (await collectionIds(call, root(base, project), project)).filter((c) => !SKIP_ROOT.has(c));
|
|
93
|
+
return ids.length > 0;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Writes every document, overwriting any with the same path. Returns how many. */
|
|
97
|
+
export async function restore(call, backup, { base, project, say }) {
|
|
98
|
+
check(backup);
|
|
99
|
+
const docs = root(base, project);
|
|
100
|
+
let n = 0;
|
|
101
|
+
for (let i = 0; i < backup.documents.length; i += BATCH) {
|
|
102
|
+
const writes = backup.documents.slice(i, i + BATCH).map((d) => ({ update: { name: `projects/${project}/databases/(default)/documents/${d.path}`, fields: d.fields } }));
|
|
103
|
+
await call('POST', `${docs}:commit`, { project, body: { writes } });
|
|
104
|
+
n += writes.length;
|
|
105
|
+
say?.(`Wrote ${n} of ${backup.documents.length}`);
|
|
106
|
+
}
|
|
107
|
+
return n;
|
|
108
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -4,21 +4,34 @@
|
|
|
4
4
|
* npx create-heresay status what's deployed where
|
|
5
5
|
* npx create-heresay open open a dashboard
|
|
6
6
|
* npx create-heresay remove delete a Heresay and its Google Cloud project
|
|
7
|
+
* npx create-heresay backup save a Heresay's data to a file
|
|
8
|
+
* npx create-heresay restore put a backup into a Heresay
|
|
7
9
|
*
|
|
8
10
|
* The UX is specified in docs/plan/cli-ux.md.
|
|
9
11
|
*/
|
|
10
12
|
import * as p from '@clack/prompts';
|
|
11
13
|
import pc from 'picocolors';
|
|
12
14
|
import { spawn } from 'node:child_process';
|
|
15
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { resolve as resolvePath } from 'node:path';
|
|
13
17
|
import { randomBytes } from 'node:crypto';
|
|
14
|
-
import { account } from './google.mjs';
|
|
18
|
+
import { account, g } from './google.mjs';
|
|
19
|
+
import * as backup from './backup.mjs';
|
|
15
20
|
import { firebase, logTo } from './firebase.mjs';
|
|
16
21
|
import * as state from './state.mjs';
|
|
17
22
|
import * as steps from './steps.mjs';
|
|
18
23
|
|
|
19
24
|
const peacock = (s) => `\x1b[38;2;15;118;110m${s}\x1b[39m`;
|
|
20
|
-
|
|
21
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Where a Heresay answers. HERESAY_SITE (a named Hosting site) wins when set; otherwise the address
|
|
27
|
+
* saved at setup or the last deploy (a Lite host, or a named site deployed from CI), and only then
|
|
28
|
+
* the project's default site. Without the saved one, status checks an address that may be retired.
|
|
29
|
+
*/
|
|
30
|
+
const url = (id) => {
|
|
31
|
+
if (process.env.HERESAY_SITE) return `https://${process.env.HERESAY_SITE}.web.app`;
|
|
32
|
+
const rec = state.load().instances[id];
|
|
33
|
+
return rec?.origin || rec?.url || `https://${id}.web.app`;
|
|
34
|
+
};
|
|
22
35
|
|
|
23
36
|
// ---- arguments --------------------------------------------------------------------------
|
|
24
37
|
|
|
@@ -42,6 +55,8 @@ const HELP = `
|
|
|
42
55
|
npx create-heresay update Deploy this version to a Heresay you set up
|
|
43
56
|
npx create-heresay status See what's deployed, and where
|
|
44
57
|
npx create-heresay open Open your dashboard
|
|
58
|
+
npx create-heresay backup Save all of a Heresay's data to a file
|
|
59
|
+
npx create-heresay restore Put a backup file into a Heresay: restore <file>
|
|
45
60
|
npx create-heresay remove Delete a Heresay and its Google Cloud project
|
|
46
61
|
|
|
47
62
|
Setup flags, to skip questions:
|
|
@@ -50,10 +65,21 @@ const HELP = `
|
|
|
50
65
|
|
|
51
66
|
Free plan, no billing (Spark): the API runs on a host you choose instead of Cloud Functions.
|
|
52
67
|
--lite --origin https://your-host.example see docs/lite.md
|
|
68
|
+
|
|
69
|
+
Backup and restore:
|
|
70
|
+
--out <file> where backup writes --project-id <id> a Heresay set up elsewhere
|
|
71
|
+
--force restore into a Heresay that already has data
|
|
53
72
|
`;
|
|
54
73
|
|
|
55
74
|
// ---- small helpers ----------------------------------------------------------------------
|
|
56
75
|
|
|
76
|
+
/** A prompt with no terminal to answer it hangs, and Node exits with a confusing warning. Say what to do instead. */
|
|
77
|
+
function needsTerminal(what, flags) {
|
|
78
|
+
if (process.stdin.isTTY) return;
|
|
79
|
+
p.log.error(`${what} asks questions, and there's no terminal to answer them here. Run it in a terminal, or pass ${flags}.`);
|
|
80
|
+
process.exit(2);
|
|
81
|
+
}
|
|
82
|
+
|
|
57
83
|
function bail(v) {
|
|
58
84
|
if (p.isCancel(v)) { p.cancel('Stopped. Nothing else was changed; run this again to carry on.'); process.exit(0); }
|
|
59
85
|
return v;
|
|
@@ -65,6 +91,11 @@ function openInBrowser(target) {
|
|
|
65
91
|
try { spawn(cmd, args, { stdio: 'ignore', detached: true }).unref(); } catch { /* the URL is printed anyway */ }
|
|
66
92
|
}
|
|
67
93
|
|
|
94
|
+
/** The named Hosting site a saved Heresay lives on, from its saved address. */
|
|
95
|
+
const savedSite = (rec) => /^https:\/\/([a-z0-9-]+)\.web\.app$/.exec(rec?.url ?? '')?.[1];
|
|
96
|
+
const savedCtx = (id, rec) => ({ id, name: rec.name, region: rec.region, billing: rec.billing, owner: rec.owner,
|
|
97
|
+
lite: rec.lite, origin: rec.origin, site: savedSite(rec), onlySite: rec.only_site });
|
|
98
|
+
|
|
68
99
|
const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
69
100
|
function suggestId(name) {
|
|
70
101
|
const tail = randomBytes(3).toString('hex').slice(0, 4);
|
|
@@ -117,6 +148,8 @@ async function ensureLogin(args) {
|
|
|
117
148
|
async function setup(args) {
|
|
118
149
|
const version = steps.releaseVersion();
|
|
119
150
|
p.intro(`${peacock(pc.bold('heresay'))} ${pc.dim('· every report gets a hearing')}`);
|
|
151
|
+
if (!args.yes) needsTerminal('Setup', '--yes (it takes every default; see --help for the rest)');
|
|
152
|
+
if (args.lite && args.yes && !args.origin) { p.log.error('Lite needs --origin https://your-host.example (the address your host will serve).'); process.exit(1); }
|
|
120
153
|
|
|
121
154
|
const [major] = process.versions.node.split('.').map(Number);
|
|
122
155
|
if (major < 20) {
|
|
@@ -131,7 +164,7 @@ async function setup(args) {
|
|
|
131
164
|
if (unfinished.length && !args['project-id']) {
|
|
132
165
|
const [id, rec] = unfinished[0];
|
|
133
166
|
const resume = args.yes ? true : bail(await p.confirm({ message: `Found an unfinished setup for ${pc.bold(id)}. Pick up where it stopped?` }));
|
|
134
|
-
if (resume) ctx = { id,
|
|
167
|
+
if (resume) ctx = { ...savedCtx(id, rec), version };
|
|
135
168
|
else if (!args.yes) {
|
|
136
169
|
const drop = bail(await p.confirm({ message: 'Forget it and start a new one? (The Google project stays; remove it with npx create-heresay remove.)', initialValue: false }));
|
|
137
170
|
if (!drop) { p.outro('Nothing changed.'); return; }
|
|
@@ -229,7 +262,7 @@ async function setup(args) {
|
|
|
229
262
|
pc.dim(' docker build -t heresay-lite . && docker run --rm -p 8080:8080 --env-file lite.env heresay-lite'),
|
|
230
263
|
'',
|
|
231
264
|
`On a host, build that folder as a Docker service and add each line of lite.env as an environment variable. It must answer at ${pc.bold(ctx.origin)}.`,
|
|
232
|
-
`Then open ${ctx.origin}
|
|
265
|
+
`Then open ${ctx.origin} and sign in as ${ctx.owner}. Check with: npx create-heresay status`,
|
|
233
266
|
].join('\n'), 'Your Heresay is ready for a host');
|
|
234
267
|
p.outro('Every report gets a hearing.');
|
|
235
268
|
return;
|
|
@@ -245,7 +278,7 @@ async function setup(args) {
|
|
|
245
278
|
].join('\n'), 'Your Heresay is live');
|
|
246
279
|
if (!args.yes && process.stdout.isTTY) {
|
|
247
280
|
const open = bail(await p.confirm({ message: 'Open it now?' }));
|
|
248
|
-
if (open) openInBrowser(url(ctx.id)
|
|
281
|
+
if (open) openInBrowser(url(ctx.id));
|
|
249
282
|
}
|
|
250
283
|
p.outro('Every report gets a hearing.');
|
|
251
284
|
}
|
|
@@ -331,7 +364,7 @@ async function build(ctx, only) {
|
|
|
331
364
|
if (key === 'signin' && ctx.googleError) {
|
|
332
365
|
p.log.warn(`Google sign-in couldn’t be switched on (${ctx.googleError}). Email links work. To add Google later: https://console.firebase.google.com/project/${ctx.id}/authentication/providers`);
|
|
333
366
|
}
|
|
334
|
-
if (key === 'deploy') state.update(ctx.id, { version: ctx.version, url: ctx.lite ? ctx.origin :
|
|
367
|
+
if (key === 'deploy') state.update(ctx.id, { version: ctx.version, url: ctx.lite ? ctx.origin : `https://${steps.siteOf(ctx)}.web.app`, ...(steps.onlySite(ctx) ? { only_site: true } : {}) });
|
|
335
368
|
} catch (e) {
|
|
336
369
|
s.error(`${doing}: stopped`);
|
|
337
370
|
fail(e, ctx.id);
|
|
@@ -341,14 +374,26 @@ async function build(ctx, only) {
|
|
|
341
374
|
|
|
342
375
|
// ---- other commands ---------------------------------------------------------------------
|
|
343
376
|
|
|
344
|
-
|
|
377
|
+
/**
|
|
378
|
+
* Which Heresay a command is about. `anywhere`: the command only needs the project id (backup,
|
|
379
|
+
* restore), so a Heresay set up from another computer, or by a teammate, works with --project-id.
|
|
380
|
+
*/
|
|
381
|
+
async function pickInstance(verb, args, { anywhere = false } = {}) {
|
|
345
382
|
const all = state.load().instances;
|
|
346
383
|
const ids = Object.keys(all);
|
|
347
384
|
if (args['project-id']) {
|
|
348
|
-
if (!all[args['project-id']]
|
|
385
|
+
if (!all[args['project-id']] && !anywhere) {
|
|
386
|
+
p.log.error(`${args['project-id']} wasn’t set up from this computer, so its settings aren’t here. Run this on the computer that set it up.`);
|
|
387
|
+
process.exit(1);
|
|
388
|
+
}
|
|
349
389
|
return args['project-id'];
|
|
350
390
|
}
|
|
351
|
-
if (!ids.length) {
|
|
391
|
+
if (!ids.length) {
|
|
392
|
+
p.log.error(anywhere
|
|
393
|
+
? 'No Heresay was set up from this computer. Name yours with --project-id <id> (its Firebase project ID, listed at console.firebase.google.com), or run npx create-heresay to make one.'
|
|
394
|
+
: 'No Heresay was set up from this computer. Run this on the computer that set it up, or npx create-heresay to make a new one.');
|
|
395
|
+
process.exit(1);
|
|
396
|
+
}
|
|
352
397
|
if (ids.length === 1) return ids[0];
|
|
353
398
|
return bail(await p.select({ message: `Which Heresay do you want to ${verb}?`, options: ids.map((id) => ({ value: id, label: id, hint: all[id].url })) }));
|
|
354
399
|
}
|
|
@@ -372,7 +417,7 @@ async function update(args) {
|
|
|
372
417
|
if (!go) { p.outro('Nothing changed.'); return; }
|
|
373
418
|
}
|
|
374
419
|
const signedIn = await account();
|
|
375
|
-
await build({ id,
|
|
420
|
+
await build({ ...savedCtx(id, rec), version, account: signedIn }, ['deploy', 'verify']);
|
|
376
421
|
if (rec.lite) { p.outro(`Rebuild your host from ${state.workDir(id)} to run ${version}.`); return; }
|
|
377
422
|
p.outro(`${url(id)} is on ${version}.`);
|
|
378
423
|
}
|
|
@@ -387,7 +432,7 @@ async function status() {
|
|
|
387
432
|
const rec = all[id];
|
|
388
433
|
const h = await health(id);
|
|
389
434
|
const lines = [
|
|
390
|
-
`${pc.dim('Dashboard')} ${url(id)}
|
|
435
|
+
`${pc.dim('Dashboard')} ${url(id)}`,
|
|
391
436
|
`${pc.dim('Region ')} ${rec.region}`,
|
|
392
437
|
`${pc.dim('Version ')} ${h ? h.version : pc.red('not answering')}${h && h.version !== bundled ? pc.dim(` (${bundled} available: npx create-heresay update)`) : ''}`,
|
|
393
438
|
`${pc.dim('Setup ')} ${rec.done?.verify ? 'complete' : pc.yellow('unfinished: run npx create-heresay to carry on')}`,
|
|
@@ -399,8 +444,8 @@ async function status() {
|
|
|
399
444
|
|
|
400
445
|
async function open(args) {
|
|
401
446
|
const id = await pickInstance('open', args);
|
|
402
|
-
openInBrowser(
|
|
403
|
-
console.log(
|
|
447
|
+
openInBrowser(url(id));
|
|
448
|
+
console.log(url(id));
|
|
404
449
|
}
|
|
405
450
|
|
|
406
451
|
async function removeCmd(args) {
|
|
@@ -410,6 +455,7 @@ async function removeCmd(args) {
|
|
|
410
455
|
`This deletes the Google Cloud project ${pc.bold(id)}: its dashboard, every app and every report.`,
|
|
411
456
|
'Google keeps it recoverable for 30 days, then it is gone. Billing is unlinked straight away.',
|
|
412
457
|
].join('\n'));
|
|
458
|
+
needsTerminal('Remove', 'nothing: deleting a Heresay always needs a person to type its id');
|
|
413
459
|
const typed = bail(await p.text({ message: `Type ${id} to confirm` }));
|
|
414
460
|
if (typed !== id) { p.outro('That didn’t match. Nothing was deleted.'); return; }
|
|
415
461
|
await account();
|
|
@@ -421,6 +467,61 @@ async function removeCmd(args) {
|
|
|
421
467
|
p.outro('Done.');
|
|
422
468
|
}
|
|
423
469
|
|
|
470
|
+
const FS = 'https://firestore.googleapis.com/v1';
|
|
471
|
+
|
|
472
|
+
async function backupCmd(args) {
|
|
473
|
+
p.intro(`${peacock(pc.bold('heresay'))} backup`);
|
|
474
|
+
const id = await pickInstance('back up', args, { anywhere: true });
|
|
475
|
+
await account();
|
|
476
|
+
const s = progress(false);
|
|
477
|
+
s.start(`Reading ${id}`);
|
|
478
|
+
let b;
|
|
479
|
+
try { b = await backup.dump(g, { base: FS, project: id, version: steps.releaseVersion(), say: (m) => s.message(m) }); } catch (e) { s.error('Couldn’t read it'); fail(e); }
|
|
480
|
+
const stamp = b.created_at.slice(0, 16).replace(/[-:]/g, '').replace('T', '-');
|
|
481
|
+
const file = resolvePath(String(args.out ?? `heresay-backup-${id}-${stamp}.json`));
|
|
482
|
+
writeFileSync(file, JSON.stringify(b) + '\n', { mode: 0o600 });
|
|
483
|
+
s.stop(`Saved ${b.documents.length} documents`);
|
|
484
|
+
const by = backup.summarize(b);
|
|
485
|
+
p.note([
|
|
486
|
+
...Object.entries(by).map(([k, n]) => ` ${k.padEnd(16)} ${n}`),
|
|
487
|
+
'',
|
|
488
|
+
pc.bold(file),
|
|
489
|
+
'',
|
|
490
|
+
...(b.unscanned.length ? [pc.yellow(`${b.unscanned.length} documents with ':' in their id were saved, but Firestore can’t list subcollections under them (Heresay keeps none there).`), ''] : []),
|
|
491
|
+
'It holds secrets (notification tokens, hashed agent tokens). Keep it somewhere private.',
|
|
492
|
+
'Put it back with: npx create-heresay restore <file>',
|
|
493
|
+
].join('\n'), 'Backup');
|
|
494
|
+
p.outro('Done.');
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async function restoreCmd(args) {
|
|
498
|
+
p.intro(`${peacock(pc.bold('heresay'))} restore`);
|
|
499
|
+
const path = args._[1];
|
|
500
|
+
if (!path) { p.log.error('Which file? npx create-heresay restore <file>'); process.exit(1); }
|
|
501
|
+
let b;
|
|
502
|
+
try { b = backup.check(JSON.parse(readFileSync(path, 'utf8'))); } catch (e) {
|
|
503
|
+
p.log.error(e.code === 'ENOENT' ? `There’s no file at ${path}.` : e instanceof SyntaxError ? `${path} isn’t a Heresay backup (it isn’t JSON).` : e.message);
|
|
504
|
+
process.exit(1);
|
|
505
|
+
}
|
|
506
|
+
const id = await pickInstance('restore into', args, { anywhere: true });
|
|
507
|
+
await account();
|
|
508
|
+
p.log.info(`${b.documents.length} documents from ${b.project} (${b.created_at.slice(0, 10)}) → ${id}`);
|
|
509
|
+
if (await backup.hasData(g, { base: FS, project: id }) && !args.force) {
|
|
510
|
+
p.log.error(`${id} already has data. Restoring would overwrite matching documents and keep the rest. Run again with --force if that’s what you want.`);
|
|
511
|
+
process.exit(1);
|
|
512
|
+
}
|
|
513
|
+
if (!args.yes) {
|
|
514
|
+
needsTerminal('Restore', '--yes to restore without typing the id');
|
|
515
|
+
const typed = bail(await p.text({ message: `Type ${id} to restore into it` }));
|
|
516
|
+
if (typed !== id) { p.outro('That didn’t match. Nothing was written.'); return; }
|
|
517
|
+
}
|
|
518
|
+
const s = progress(false);
|
|
519
|
+
s.start('Writing');
|
|
520
|
+
try { await backup.restore(g, b, { base: FS, project: id, say: (m) => s.message(m) }); } catch (e) { s.error('Stopped part way; run it again to finish'); fail(e); }
|
|
521
|
+
s.stop(`Restored ${b.documents.length} documents`);
|
|
522
|
+
p.outro(`Sign in at ${url(id)} with a team email. Reconnect repos with npx heresay connect --url ${url(id)}.`);
|
|
523
|
+
}
|
|
524
|
+
|
|
424
525
|
export async function main(argv) {
|
|
425
526
|
const args = parseArgs(argv);
|
|
426
527
|
const cmd = args._[0];
|
|
@@ -431,6 +532,8 @@ export async function main(argv) {
|
|
|
431
532
|
if (cmd === 'status') return status(args);
|
|
432
533
|
if (cmd === 'open') return open(args);
|
|
433
534
|
if (cmd === 'remove') return removeCmd(args);
|
|
535
|
+
if (cmd === 'backup') return backupCmd(args);
|
|
536
|
+
if (cmd === 'restore') return restoreCmd(args);
|
|
434
537
|
console.log(`Unknown command: ${cmd}\n${HELP}`);
|
|
435
538
|
process.exit(1);
|
|
436
539
|
}
|
package/src/steps.mjs
CHANGED
|
@@ -128,7 +128,14 @@ export async function database(ctx, say) {
|
|
|
128
128
|
}
|
|
129
129
|
|
|
130
130
|
/** The hosting site id: the project id unless HERESAY_SITE names another site in the project. */
|
|
131
|
-
|
|
131
|
+
/**
|
|
132
|
+
* The hosting site: HERESAY_SITE if set, else the one this Heresay was last deployed to (saved in
|
|
133
|
+
* ~/.heresay), else the project's default site. So `update` from a laptop reaches the same site
|
|
134
|
+
* CI deploys to, instead of the default one.
|
|
135
|
+
*/
|
|
136
|
+
export const siteOf = (ctx) => process.env.HERESAY_SITE || ctx.site || ctx.id;
|
|
137
|
+
/** Serve only the named site (the default one retired): HERESAY_ONLY_SITE=1, or saved from a deploy that set it. */
|
|
138
|
+
export const onlySite = (ctx) => process.env.HERESAY_ONLY_SITE === '1' || !!ctx.onlySite;
|
|
132
139
|
|
|
133
140
|
// ---- the release, laid out for `firebase deploy` ----------------------------------------
|
|
134
141
|
|
|
@@ -151,13 +158,14 @@ export function prepareRelease(ctx) {
|
|
|
151
158
|
// address, and repos already connected to it, must keep working. HERESAY_ONLY_SITE=1 opts out
|
|
152
159
|
// for an instance that has retired the default address.
|
|
153
160
|
if (siteOf(ctx) !== ctx.id) {
|
|
154
|
-
cfg.hosting =
|
|
161
|
+
cfg.hosting = onlySite(ctx)
|
|
155
162
|
? { ...cfg.hosting, site: siteOf(ctx) }
|
|
156
163
|
: [{ ...cfg.hosting, site: siteOf(ctx) }, { ...cfg.hosting, site: ctx.id }];
|
|
157
164
|
}
|
|
158
165
|
writeFileSync(join(dir, 'firebase.json'), JSON.stringify(cfg, null, 2) + '\n');
|
|
159
166
|
writeFileSync(join(dir, '.firebaserc'), JSON.stringify({ projects: { default: ctx.id } }, null, 2) + '\n');
|
|
160
|
-
|
|
167
|
+
// HERESAY_SITE: the API names this site (not the default one) in OAuth discovery and alert links.
|
|
168
|
+
writeFileSync(join(dir, 'functions', '.env'), `HERESAY_REGION=${ctx.region}\n${siteOf(ctx) !== ctx.id ? `HERESAY_SITE=${siteOf(ctx)}\n` : ''}`);
|
|
161
169
|
return dir;
|
|
162
170
|
}
|
|
163
171
|
|
|
@@ -297,8 +305,9 @@ export async function verify(ctx, say) {
|
|
|
297
305
|
for (;;) {
|
|
298
306
|
try {
|
|
299
307
|
const h = await (await fetch(`${base}/v1/health`)).json();
|
|
300
|
-
|
|
301
|
-
|
|
308
|
+
// The dashboard is the site's root page; check it really is the dashboard, not a leftover page.
|
|
309
|
+
const app = await fetch(`${base}/`);
|
|
310
|
+
if (h.ok && app.ok && (await app.text()).includes('/dashboard.js')) return `API ${h.version}, dashboard loads`;
|
|
302
311
|
} catch { /* hosting can take a moment to answer on a new site */ }
|
|
303
312
|
if (Date.now() > until) {
|
|
304
313
|
throw new StepError(`${base} isn’t answering yet.`, 'New sites can take a few minutes. Run npx create-heresay status in a little while.');
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
<!doctype html>
|
|
2
|
-
<html lang="en">
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="utf-8">
|
|
5
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
-
<title>Heresay</title>
|
|
7
|
-
<meta http-equiv="refresh" content="0; url=/app/">
|
|
8
|
-
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
|
9
|
-
<style>body{font:16px/1.6 system-ui,sans-serif;color:#15171c;max-width:32rem;margin:15vh auto;padding:0 24px;text-align:center}a{color:#0b5e57}small{display:block;margin-top:24px;color:#5b6472}</style>
|
|
10
|
-
</head>
|
|
11
|
-
<body>
|
|
12
|
-
<p><a href="/app/">Open the Heresay dashboard</a></p>
|
|
13
|
-
<small><a href="https://sibhimanyu.github.io/heresay/">What is Heresay?</a></small>
|
|
14
|
-
</body>
|
|
15
|
-
</html>
|