@grayspar/cli 0.0.0-stage → 0.0.2

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.
Files changed (47) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +76 -2
  3. package/dist/commands/access.js +103 -0
  4. package/dist/commands/deploy/archive.js +156 -0
  5. package/dist/commands/deploy/await-discovery.js +17 -0
  6. package/dist/commands/deploy/deploy-destination.js +101 -0
  7. package/dist/commands/deploy/deploy-flags.js +60 -0
  8. package/dist/commands/deploy/deploy-target.js +19 -0
  9. package/dist/commands/deploy/deploy.js +209 -0
  10. package/dist/commands/deploy/env-files.js +47 -0
  11. package/dist/commands/deploy/git-state.js +35 -0
  12. package/dist/commands/deploy/project-name.js +13 -0
  13. package/dist/commands/deploy/submit-deploy.js +127 -0
  14. package/dist/commands/deploy/variables-to-send.js +140 -0
  15. package/dist/commands/env.js +71 -0
  16. package/dist/commands/link.js +28 -0
  17. package/dist/commands/login/challenge.js +5 -0
  18. package/dist/commands/login/login.js +59 -0
  19. package/dist/commands/login/open-browser.js +15 -0
  20. package/dist/commands/login/sign-in-callback.js +37 -0
  21. package/dist/commands/logout.js +18 -0
  22. package/dist/commands/logs.js +89 -0
  23. package/dist/commands/open-path.js +45 -0
  24. package/dist/commands/project.js +22 -0
  25. package/dist/commands/restart.js +21 -0
  26. package/dist/commands/service.js +63 -0
  27. package/dist/commands/status.js +15 -0
  28. package/dist/commands/volume.js +87 -0
  29. package/dist/commands/whoami.js +16 -0
  30. package/dist/index.js +58 -0
  31. package/dist/lib/client.js +71 -0
  32. package/dist/lib/command-helpers.js +25 -0
  33. package/dist/lib/credentials.js +49 -0
  34. package/dist/lib/errors.js +12 -0
  35. package/dist/lib/follow-deployment.js +127 -0
  36. package/dist/lib/output.js +40 -0
  37. package/dist/lib/project-link.js +42 -0
  38. package/dist/lib/prompt.js +103 -0
  39. package/dist/lib/resolve-project.js +60 -0
  40. package/dist/lib/resolve-service.js +29 -0
  41. package/dist/lib/resolve-team.js +31 -0
  42. package/dist/lib/retry-transient.js +32 -0
  43. package/dist/lib/services-table.js +29 -0
  44. package/dist/lib/ui.js +58 -0
  45. package/dist/lib/usage-errors.js +43 -0
  46. package/dist/lib/version.js +12 -0
  47. package/package.json +52 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ # Grayspar 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 cloud for small software. Deploy your applications with one command, and share them with exactly the people you choose.
4
+
5
+ Grayspar builds your app, gives it its own address, and keeps it private to you until you share it. The people you share it with sign in with Google, GitHub or a code sent to their email, and the app opens. Your app needs no login code of its own.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install -g @grayspar/cli
11
+ ```
12
+
13
+ It needs Node 22 or newer. To run it once with nothing installed, use `npx @grayspar/cli deploy`.
14
+
15
+ ## Deploy
16
+
17
+ ```sh
18
+ grayspar login
19
+ grayspar deploy
20
+ ```
21
+
22
+ Run `grayspar deploy` in your app's directory. The first deploy asks for the project's name, which is also its address. Grayspar finds the services in it, a web front end and an API for example, builds each one and answers with the address where it runs.
23
+
24
+ A service's files reset on every deploy. To keep a folder, name it when you deploy:
25
+
26
+ ```sh
27
+ grayspar deploy --volume app=/app/data
28
+ ```
29
+
30
+ A service at the root of your directory is called `app`, and one in a subfolder takes that folder's name.
31
+
32
+ ## Share
33
+
34
+ ```sh
35
+ grayspar access add alice@company.example
36
+ ```
37
+
38
+ Alice gets an email with the link. Name people one by one, or a whole company at once with `@company.example`.
39
+
40
+ ## For scripts and agents
41
+
42
+ Every command answers in JSON with `--json`, and `--yes` accepts what the CLI would otherwise ask. A command that needs an answer it cannot ask for refuses and names the flag that supplies it, so a script or an AI agent can run Grayspar without a terminal.
43
+
44
+ ## Commands
45
+
46
+ | Command | What it does |
47
+ | ----------- | ------------------------------------------------------------------------------- |
48
+ | `login` | sign in to Grayspar from this machine |
49
+ | `logout` | forget the saved sign-in on this machine |
50
+ | `whoami` | show who this machine is signed in as |
51
+ | `deploy` | build a project folder and put it online |
52
+ | `project` | work with your projects |
53
+ | `access` | control who can open a project |
54
+ | `open-path` | paths anyone can reach without signing in, such as webhooks |
55
+ | `env` | set a project's environment variables |
56
+ | `volume` | keep a folder across deploys |
57
+ | `service` | change where a service answers and how it is built |
58
+ | `link` | bind this folder to a project |
59
+ | `unlink` | unbind this folder from its project |
60
+ | `status` | show what a project is doing |
61
+ | `logs` | show what a service printed while running, or with `--build` the last build log |
62
+ | `restart` | run a service again in place, keeping its volume |
63
+
64
+ `grayspar <command> --help` shows each command's options.
65
+
66
+ ## Versions
67
+
68
+ The CLI has a version of its own. It moves when the CLI itself changes, so a new Grayspar feature often reaches you with no update at all.
69
+
70
+ ## Links
71
+
72
+ - [grayspar.com](https://grayspar.com)
73
+ - [Privacy Policy](https://grayspar.com/privacy/)
74
+ - [Terms of Service](https://grayspar.com/terms/)
75
+ - Support: support@grayspar.com
76
+
77
+ Licensed under the Apache License 2.0.
@@ -0,0 +1,103 @@
1
+ /* A target starting with @ is a company and anything else is an address, so one command adds both,
2
+ the way one box on the dashboard does. */
3
+ import { Command, Option } from 'commander';
4
+ import { dataOrThrow, signedInClient } from '../lib/client.js';
5
+ import { commandAction } from '../lib/command-helpers.js';
6
+ import { CliError } from '../lib/errors.js';
7
+ import { printResult } from '../lib/output.js';
8
+ import { resolveProject } from '../lib/resolve-project.js';
9
+ import { receipt, tableOrEmptyNote, warning } from '../lib/ui.js';
10
+ function targetOf(value) {
11
+ return value.startsWith('@')
12
+ ? { kind: 'domain', domain: value.slice(1) }
13
+ : { kind: 'email', email: value };
14
+ }
15
+ function labelOf(entry) {
16
+ return entry.kind === 'email' ? entry.email : `@${entry.domain}`;
17
+ }
18
+ function accessSentence(mode, name) {
19
+ return mode === 'open'
20
+ ? `Anyone with the link can open ${name}, without signing in.`
21
+ : `Only the team and the people and companies on its list can open ${name}.`;
22
+ }
23
+ function addedReceipt(added, name) {
24
+ if (added.entry.kind === 'domain')
25
+ return receipt(`Added @${added.entry.domain} to ${name}`);
26
+ return added.told === true
27
+ ? receipt(`Added ${added.entry.email} to ${name} and emailed the link`)
28
+ : warning(`Added ${added.entry.email} to ${name}, but the email didn't send.`);
29
+ }
30
+ async function setGeneralAccess(mode, format) {
31
+ const api = await signedInClient();
32
+ const project = await resolveProject(api);
33
+ const access = await dataOrThrow(api.PUT('/api/projects/{projectId}/general-access', {
34
+ params: { path: { projectId: project.id } },
35
+ body: { mode },
36
+ }));
37
+ printResult(format, access, () => `${receipt(`Set access of ${project.name} to ${access.mode}`)}\n${accessSentence(access.mode, project.name)}`);
38
+ }
39
+ async function addAccess(targets, format) {
40
+ const api = await signedInClient();
41
+ const project = await resolveProject(api);
42
+ const results = [];
43
+ for (const target of targets) {
44
+ results.push(await dataOrThrow(api.POST('/api/projects/{projectId}/access', {
45
+ params: { path: { projectId: project.id } },
46
+ body: targetOf(target),
47
+ })));
48
+ }
49
+ printResult(format, results, () => results.map((added) => addedReceipt(added, project.name)).join('\n'));
50
+ }
51
+ async function listAccess(format) {
52
+ const api = await signedInClient();
53
+ const project = await resolveProject(api);
54
+ const rows = await dataOrThrow(api.GET('/api/projects/{projectId}/access', { params: { path: { projectId: project.id } } }));
55
+ printResult(format, rows, () => [
56
+ accessSentence(project.generalAccess.mode, project.name),
57
+ '',
58
+ tableOrEmptyNote(['PERSON OR COMPANY', 'STATUS'], rows.map((row) => [
59
+ labelOf(row),
60
+ row.kind === 'domain'
61
+ ? 'anyone at this company'
62
+ : row.firstOpenedAt === null
63
+ ? 'not opened yet'
64
+ : 'opened it',
65
+ ]), `Nobody is named on ${project.name} yet.`),
66
+ ].join('\n'));
67
+ }
68
+ async function removeAccess(target, format) {
69
+ const api = await signedInClient();
70
+ const project = await resolveProject(api);
71
+ const rows = await dataOrThrow(api.GET('/api/projects/{projectId}/access', { params: { path: { projectId: project.id } } }));
72
+ const wanted = target.toLowerCase();
73
+ const row = rows.find((candidate) => labelOf(candidate) === wanted);
74
+ if (row === undefined) {
75
+ throw new CliError('not_shared', `${target} isn't on the list for ${project.name}.`);
76
+ }
77
+ await dataOrThrow(api.DELETE('/api/projects/{projectId}/access/{accessId}', {
78
+ params: { path: { projectId: project.id, accessId: row.id } },
79
+ }));
80
+ printResult(format, { status: 'ok', removed: labelOf(row) }, () => receipt(`Removed ${labelOf(row)} from ${project.name}`));
81
+ }
82
+ export const accessCommand = new Command('access').description('control who can open a project');
83
+ accessCommand
84
+ .command('list', { isDefault: true })
85
+ .description('show who can open a project')
86
+ .action(commandAction((format) => listAccess(format)));
87
+ accessCommand
88
+ .command('add')
89
+ .argument('<targets...>', 'email addresses, or @company.example for everyone at a company')
90
+ .description('let named people or a whole company open a project')
91
+ .action(commandAction((format, _command, targets) => addAccess(targets, format)));
92
+ accessCommand
93
+ .command('remove')
94
+ .argument('<target>', 'an email address, or @company.example')
95
+ .description('take someone or a company off a project')
96
+ .action(commandAction((format, _command, target) => removeAccess(target, format)));
97
+ accessCommand
98
+ .command('set')
99
+ .addOption(new Option('--mode <mode>', 'restricted lets in the people and companies on the list, open lets in anyone with the link')
100
+ .choices(['restricted', 'open'])
101
+ .makeOptionMandatory())
102
+ .description('choose whether the list decides who can open a project')
103
+ .action(commandAction((format, command) => setGeneralAccess(command.opts().mode, format)));
@@ -0,0 +1,156 @@
1
+ /* Git lists what to upload inside a work tree, and the .gitignore files decide elsewhere. A .env never goes in the
2
+ archive, because a value landing in an image layer would sit there for as long as the image exists. */
3
+ import { execFile } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+ import { createReadStream, createWriteStream, readFileSync } from 'node:fs';
6
+ import { lstat, stat } from 'node:fs/promises';
7
+ import { basename, join } from 'node:path';
8
+ import { Readable, Transform } from 'node:stream';
9
+ import { pipeline } from 'node:stream/promises';
10
+ import { promisify } from 'node:util';
11
+ import ignore, {} from 'ignore';
12
+ import { create } from 'tar';
13
+ import { CliError } from '../../lib/errors.js';
14
+ const execFileAsync = promisify(execFile);
15
+ const GIT_LIST_TIMEOUT_MS = 60_000;
16
+ const GIT_LIST_MAX_BYTES = 256 * 1024 * 1024;
17
+ const GIT_NOT_A_WORK_TREE_EXIT_CODE = 128;
18
+ const OUTSIDE_GIT_SKIPPED = ['node_modules', '.git'];
19
+ const LINK_FOLDER_PATTERN = /(^|\/)\.grayspar(\/|$)/;
20
+ function isKeptOutOfUpload(path) {
21
+ return basename(path).startsWith('.env') || LINK_FOLDER_PATTERN.test(path);
22
+ }
23
+ async function listWithGit(root, ...args) {
24
+ const { stdout } = await execFileAsync('git', ['--literal-pathspecs', 'ls-files', '-z', ...args], { cwd: root, timeout: GIT_LIST_TIMEOUT_MS, maxBuffer: GIT_LIST_MAX_BYTES });
25
+ return stdout.split('\0').filter((path) => path !== '');
26
+ }
27
+ async function presentFiles(root, listed) {
28
+ const found = await Promise.all(listed.map(async (path) => ({ path, entry: await lstat(join(root, path)).catch(() => null) })));
29
+ const present = found.flatMap(({ path, entry }) => (entry === null ? [] : [{ path, entry }]));
30
+ const folder = present.find(({ entry }) => entry.isDirectory());
31
+ if (folder !== undefined)
32
+ throw new FolderListed(folder.path.replace(/\/$/, ''));
33
+ return present.map(({ path }) => path);
34
+ }
35
+ class FolderListed extends Error {
36
+ }
37
+ async function filesGitKeeps(root, under) {
38
+ let tracked;
39
+ let untracked;
40
+ try {
41
+ // git refuses --recurse-submodules together with --others, so the untracked files come from a second listing
42
+ tracked = await listWithGit(root, '--cached', '--recurse-submodules', '--', under);
43
+ untracked = await listWithGit(root, '--others', '--exclude-standard', '--', under);
44
+ }
45
+ catch (error) {
46
+ const notGit = error instanceof Error &&
47
+ 'code' in error &&
48
+ (error.code === GIT_NOT_A_WORK_TREE_EXIT_CODE || error.code === 'ENOENT');
49
+ if (notGit)
50
+ return null;
51
+ throw error;
52
+ }
53
+ try {
54
+ const trackedFiles = await presentFiles(root, tracked);
55
+ const untrackedFiles = await presentFiles(root, untracked);
56
+ return [...new Set([...trackedFiles, ...untrackedFiles])];
57
+ }
58
+ catch (error) {
59
+ if (!(error instanceof FolderListed))
60
+ throw error;
61
+ // a folder listed as tracked is a submodule nobody checked out, and one listed as untracked holds a repository of its own
62
+ throw tracked.some((path) => path.replace(/\/$/, '') === error.message)
63
+ ? new CliError('submodule_not_checked_out', `${error.message} is a submodule that isn't checked out.\nRun git submodule update --init, then deploy again.`)
64
+ : new CliError('nested_repository', `${error.message} is a separate git repository, so its files can't be listed.\nAdd it to .gitignore, or make its files part of this repository.`);
65
+ }
66
+ }
67
+ function readOrEmpty(path) {
68
+ try {
69
+ return readFileSync(path, 'utf8');
70
+ }
71
+ catch {
72
+ return '';
73
+ }
74
+ }
75
+ function ignoredBy(root) {
76
+ const rootRules = ignore()
77
+ .add(OUTSIDE_GIT_SKIPPED)
78
+ .add(readOrEmpty(join(root, '.gitignore')));
79
+ const nested = new Map();
80
+ function rulesIn(folder) {
81
+ if (!nested.has(folder)) {
82
+ const raw = readOrEmpty(join(root, folder, '.gitignore'));
83
+ nested.set(folder, raw === '' ? null : ignore().add(raw));
84
+ }
85
+ return nested.get(folder) ?? null;
86
+ }
87
+ return (path, isDirectory) => {
88
+ const asked = isDirectory ? `${path}/` : path;
89
+ if (rootRules.ignores(asked))
90
+ return true;
91
+ const folders = path.split('/').slice(0, -1);
92
+ return folders.some((_, index) => {
93
+ const folder = folders.slice(0, index + 1).join('/');
94
+ return rulesIn(folder)?.ignores(asked.slice(folder.length + 1)) === true;
95
+ });
96
+ };
97
+ }
98
+ const BYTES_PER_MEGABYTE = 1024 ** 2;
99
+ const FIX_BY_IGNORING = "Add the files you don't need, such as build output, to .gitignore.";
100
+ function tooManyFiles({ files }) {
101
+ return new CliError('too_many_files', `A deploy holds at most ${files.toLocaleString('en-US')} files, and this project has more.\n${FIX_BY_IGNORING}`);
102
+ }
103
+ function stopsPast({ bytes }) {
104
+ let written = 0;
105
+ return new Transform({
106
+ transform(chunk, _encoding, done) {
107
+ written += chunk.length;
108
+ done(written > bytes
109
+ ? new CliError('upload_too_large', `A deploy can be at most ${Math.floor(bytes / BYTES_PER_MEGABYTE)} MB, and this project is larger.\n${FIX_BY_IGNORING}`)
110
+ : null, chunk);
111
+ },
112
+ });
113
+ }
114
+ function refuseEmptyUpload(root, under) {
115
+ throw new CliError('nothing_to_upload', `There are no files to deploy in ${join(root, under)}.`);
116
+ }
117
+ export async function archiveOf(root, under, into, limits) {
118
+ const path = join(into, 'archive.tgz');
119
+ const files = await filesGitKeeps(root, under);
120
+ const write = (packed) => pipeline(Readable.from(packed), stopsPast(limits), createWriteStream(path));
121
+ if (files === null) {
122
+ const ignored = ignoredBy(root);
123
+ let fileCount = 0;
124
+ await write(create({
125
+ cwd: root,
126
+ gzip: true,
127
+ filter: (entryPath, entry) => {
128
+ const relative = entryPath.replace(/^\.\/?/, '');
129
+ if (relative === '')
130
+ return true;
131
+ const isDirectory = 'isDirectory' in entry && entry.isDirectory();
132
+ if (isKeptOutOfUpload(relative) || ignored(relative, isDirectory))
133
+ return false;
134
+ if (!isDirectory)
135
+ fileCount += 1;
136
+ return fileCount <= limits.files;
137
+ },
138
+ }, [under]));
139
+ if (fileCount === 0)
140
+ refuseEmptyUpload(root, under);
141
+ if (fileCount > limits.files)
142
+ throw tooManyFiles(limits);
143
+ }
144
+ else {
145
+ const kept = files.filter((file) => !isKeptOutOfUpload(file));
146
+ if (kept.length === 0)
147
+ refuseEmptyUpload(root, under);
148
+ if (kept.length > limits.files)
149
+ throw tooManyFiles(limits);
150
+ await write(create({ cwd: root, gzip: true, noDirRecurse: true }, kept));
151
+ }
152
+ const hash = createHash('sha256');
153
+ for await (const chunk of createReadStream(path))
154
+ hash.update(chunk);
155
+ return { path, bytes: (await stat(path)).size, sha256: hash.digest('hex') };
156
+ }
@@ -0,0 +1,17 @@
1
+ import { dataOrThrow } from '../../lib/client.js';
2
+ import { realClock, retryTransient } from '../../lib/retry-transient.js';
3
+ export async function awaitDiscovery(api, destination, uploadId, clock = realClock) {
4
+ for (;;) {
5
+ const watched = await retryTransient((signal) => dataOrThrow(destination.kind === 'project'
6
+ ? api.GET('/api/projects/{projectId}/uploads/{uploadId}/discovery', {
7
+ params: { path: { projectId: destination.project.id, uploadId } },
8
+ signal,
9
+ })
10
+ : api.GET('/api/teams/{teamId}/uploads/{uploadId}/discovery', {
11
+ params: { path: { teamId: destination.team.id, uploadId } },
12
+ signal,
13
+ })), clock);
14
+ if (watched !== undefined)
15
+ return watched;
16
+ }
17
+ }
@@ -0,0 +1,101 @@
1
+ import { basename } from 'node:path';
2
+ import { dataOrThrow } from '../../lib/client.js';
3
+ import { CliError } from '../../lib/errors.js';
4
+ import { printNote } from '../../lib/output.js';
5
+ import { askChoice, askText, isInteractive } from '../../lib/prompt.js';
6
+ import { projectIsNamed, resolveProject, teamProjects } from '../../lib/resolve-project.js';
7
+ import { resolveTeam } from '../../lib/resolve-team.js';
8
+ import { failure } from '../../lib/ui.js';
9
+ import { projectNameFrom } from './project-name.js';
10
+ export function destinationOptions(projects, suggestedName) {
11
+ const match = projects.find((project) => project.name === suggestedName);
12
+ const others = projects
13
+ .filter((project) => project !== match)
14
+ .map((project) => ({ kind: 'existing', project }));
15
+ const create = { kind: 'create' };
16
+ return match === undefined
17
+ ? [create, ...others]
18
+ : [{ kind: 'existing', project: match }, create, ...others];
19
+ }
20
+ const NAME_RULE = 'Names use lowercase letters, numbers and single hyphens, up to 58 characters.';
21
+ function nameProblem(name, projects) {
22
+ if (projectNameFrom(name) !== name)
23
+ return NAME_RULE;
24
+ return projects.some((project) => project.name === name)
25
+ ? `This team already has a project called ${name}.`
26
+ : null;
27
+ }
28
+ function givenName(name, projects) {
29
+ const problem = name === null ? NAME_RULE : nameProblem(name, projects);
30
+ if (name === null || problem !== null) {
31
+ throw new CliError('needs_a_name', `${problem ?? NAME_RULE}\nName the project with --name.`, '--name');
32
+ }
33
+ return name;
34
+ }
35
+ async function askProjectName(projects, suggestion) {
36
+ let offered = suggestion;
37
+ for (;;) {
38
+ const answer = await askText('Project name', offered, '--name');
39
+ const problem = nameProblem(answer, projects);
40
+ if (problem === null)
41
+ return answer;
42
+ process.stdout.write(`${failure(problem)}\n`);
43
+ offered = projectNameFrom(answer);
44
+ }
45
+ }
46
+ export async function destinationFor(api, root, link, options) {
47
+ if (options.name !== undefined && projectIsNamed()) {
48
+ throw new CliError('name_and_project', '--name creates a new project and --project names an existing one.\nGive one of them.', '--name');
49
+ }
50
+ if (projectIsNamed()) {
51
+ return {
52
+ kind: 'project',
53
+ project: await resolveProject(api, { followLink: false }),
54
+ linksFolder: false,
55
+ };
56
+ }
57
+ if (link !== null) {
58
+ const answer = await api.GET('/api/projects/{projectId}', {
59
+ params: { path: { projectId: link.projectId } },
60
+ });
61
+ if (answer.response.status !== 404) {
62
+ if (options.name !== undefined) {
63
+ throw new CliError('already_linked', 'This folder is already linked to a project.\nRun grayspar unlink to deploy it as a new one.', '--name');
64
+ }
65
+ return {
66
+ kind: 'project',
67
+ project: await dataOrThrow(Promise.resolve(answer)),
68
+ linksFolder: false,
69
+ };
70
+ }
71
+ printNote(options.format, 'The project this folder was linked to no longer exists.');
72
+ }
73
+ const team = await resolveTeam(api, { takeDefault: options.yes, deploying: true });
74
+ const projects = await teamProjects(api, team.id);
75
+ if (options.name !== undefined) {
76
+ return { kind: 'new', team, name: givenName(options.name, projects) };
77
+ }
78
+ const suggestion = projectNameFrom(basename(root));
79
+ const destinations = destinationOptions(projects, suggestion);
80
+ const [suggested] = destinations;
81
+ if (suggested === undefined)
82
+ throw new Error('no project to create');
83
+ if (options.yes) {
84
+ return suggested.kind === 'existing'
85
+ ? { kind: 'project', project: suggested.project, linksFolder: true }
86
+ : { kind: 'new', team, name: givenName(suggestion, projects) };
87
+ }
88
+ if (!isInteractive()) {
89
+ throw new CliError('needs_an_answer', "This folder isn't linked to a project yet, and there's no terminal to ask which.\nDeploy to a new project with --name, or to an existing one with --project.", '--name');
90
+ }
91
+ const picked = await askChoice('Select a project', 'Project', destinations.map((option, index) => ({
92
+ value: String(index),
93
+ label: option.kind === 'create' ? 'Create a new project' : option.project.name,
94
+ })), '--project');
95
+ const choice = destinations[Number(picked)] ?? suggested;
96
+ const destination = choice.kind === 'existing'
97
+ ? { kind: 'project', project: choice.project, linksFolder: true }
98
+ : { kind: 'new', team, name: await askProjectName(projects, suggestion) };
99
+ process.stdout.write('\n');
100
+ return destination;
101
+ }