create-pincast 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pincast, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # create-pincast
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
+ One command gets you a working Placecard app with its own test key, and you don't need an account to run it.
4
+
5
+ ```sh
6
+ npm create pincast my-app
7
+ ```
8
+
9
+ You need Node 20.12 or later. The folder has to be new or empty. Leave its name off and the app goes in `pincast-app`.
10
+
11
+ ## What it does
12
+
13
+ 1. Copies a small starter app, Lantern Walk, from inside this package. Nothing is downloaded from GitHub, and `template.json` records the commit it came from.
14
+ 2. Asks Pincast for one test app.
15
+ 3. Writes your key to `.env`, which only your account can read and git ignores, along with the test person `test_demo` and your claim link.
16
+ 4. Puts the new app's id in `shared/app.js`.
17
+ 5. Sends the starter's set and one collect for `test_demo`, so the app's first screen shows a real card.
18
+ 6. Prints the claim link and the commands that start the app.
19
+
20
+ The command never prints your key.
21
+
22
+ ## Your test app
23
+
24
+ A test key writes only to its own app, and only for test people, whose ids start with `test_`. A test app is never listed and never counts toward anything public.
25
+
26
+ It ends after a few days unless you claim it, and the command prints the exact date. To keep it, open the claim link while signed in to Pincast. The link works once, and it's saved in `.env` as `PINCAST_CLAIM_URL` in case you close the terminal.
27
+
28
+ ## If something goes wrong
29
+
30
+ Each call to make an app makes a new one, so the command never repeats that call by itself. If the answer gets lost on the way back, it tells you and stops. Any app made that way has no key anyone can use, and it ends on its own, so you can run the command again.
31
+
32
+ Pincast limits how many test apps it makes. If you reach a limit, the command tells you how long to wait.
33
+
34
+ If the set or the collect doesn't go through, you still get your app. The command says which one is missing and prints the commands that send it.
35
+
36
+ ## Working on this package
37
+
38
+ ```sh
39
+ npm test
40
+ ```
41
+
42
+ The tests run against a local stand-in for the API and never reach Pincast. Set `PINCAST_CREATE_API` to point the command at another address.
43
+
44
+ To move the starter to a newer commit of the example app:
45
+
46
+ ```sh
47
+ node scripts/sync-template.js <path to pincast-kit-example> <commit>
48
+ ```
49
+
50
+ ## License
51
+
52
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../src/cli.js'
3
+
4
+ // Node's default crash report prints the error's message and source. Neither may ever carry a key.
5
+ const crash = () => {
6
+ process.stderr.write('Something went wrong. No key was printed. Run the command again in a new or empty folder.\n')
7
+ process.exit(1)
8
+ }
9
+ process.on('uncaughtException', crash)
10
+ process.on('unhandledRejection', crash)
11
+
12
+ run(process.argv.slice(2)).then((code) => { process.exitCode = code }, crash)
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "create-pincast",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "One command to a working Placecard app with its own test key.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/pincastFM/create-pincast.git"
9
+ },
10
+ "type": "module",
11
+ "bin": {
12
+ "create-pincast": "bin/create-pincast.js"
13
+ },
14
+ "files": [
15
+ "bin",
16
+ "src",
17
+ "template",
18
+ "template.json"
19
+ ],
20
+ "engines": {
21
+ "node": ">=20.12"
22
+ },
23
+ "scripts": {
24
+ "test": "node --test test/*.test.js"
25
+ },
26
+ "keywords": [
27
+ "pincast",
28
+ "placecard",
29
+ "create"
30
+ ]
31
+ }
package/src/api.js ADDED
@@ -0,0 +1,138 @@
1
+ import { PACKAGE_NAME } from './name.js'
2
+
3
+ export const DEFAULT_API = 'https://api.pincast.fm/v1'
4
+ export const API_ENV = 'PINCAST_CREATE_API'
5
+ const TIMEOUT_MS = 30_000
6
+
7
+ // What a good answer holds. These values land in a source file, in .env and on the terminal, so each
8
+ // one has to match exactly before it's used.
9
+ const APP_ID_RE = /^test-[a-z2-7]{10}$/
10
+ const CLAIM_URL_RE = /^https:\/\/[a-z0-9.-]+(?::\d+)?\/[A-Za-z0-9/_-]*#code=pcc_[A-Za-z0-9_-]{43}$/
11
+ const SAFE_BASE_RE = /^[A-Za-z0-9:/._[\]-]+$/
12
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
13
+
14
+ // Failures that happen before the request leaves this machine, so no app can exist.
15
+ const NEVER_SENT = new Set([
16
+ 'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_CONNECT_TIMEOUT',
17
+ 'CERT_HAS_EXPIRED', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN',
18
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'ERR_TLS_CERT_ALTNAME_INVALID',
19
+ ])
20
+
21
+ const ORPHAN = "If Pincast made a test app, nobody holds its key, so it can't be used and it ends on its own. Each call makes a new app, so this command won't call again by itself. Run it again when you're ready."
22
+
23
+ /** A failure with a message written for the person at the terminal. */
24
+ export class Stop extends Error {
25
+ constructor(message, exitCode = 1) {
26
+ super(message)
27
+ this.exitCode = exitCode
28
+ }
29
+ }
30
+
31
+ /** The API base: the default, or the override in PINCAST_CREATE_API, which tests use. */
32
+ export function apiBase(env) {
33
+ const raw = env[API_ENV]
34
+ if (!raw) return { base: DEFAULT_API, custom: false }
35
+ let url
36
+ try {
37
+ url = new URL(raw)
38
+ } catch {
39
+ throw new Stop(`${API_ENV} isn't a web address.`)
40
+ }
41
+ const allowed = url.protocol === 'https:' || (url.protocol === 'http:' && LOCAL_HOSTS.has(url.hostname))
42
+ if (!allowed) throw new Stop(`${API_ENV} has to use https, or http on this machine.`)
43
+ const base = `${url.origin}${url.pathname}`.replace(/\/+$/, '')
44
+ if (url.username || url.password || url.search || url.hash || !SAFE_BASE_RE.test(base)) {
45
+ throw new Stop(`${API_ENV} has to be a plain address, such as https://example.org/v1.`)
46
+ }
47
+ return { base, custom: true }
48
+ }
49
+
50
+ /** Turns a Retry-After header into words. */
51
+ export function waitText(header, now = Date.now()) {
52
+ if (!header) return 'later'
53
+ const value = header.trim()
54
+ const seconds = /^\d+$/.test(value) ? Number(value) : (Date.parse(value) - now) / 1000
55
+ if (!Number.isFinite(seconds) || seconds < 0) return 'later'
56
+ if (seconds < 90) return 'in a minute or two'
57
+ if (seconds < 5400) return `in about ${Math.ceil(seconds / 60)} minutes`
58
+ return `in about ${Math.ceil(seconds / 3600)} hours`
59
+ }
60
+
61
+ const failureCode = (e) => e?.cause?.code ?? e?.code ?? e?.cause?.errors?.[0]?.code
62
+
63
+ function errorCode(text) {
64
+ try {
65
+ const code = JSON.parse(text)?.data?.code
66
+ return typeof code === 'string' ? code : null
67
+ } catch {
68
+ return null
69
+ }
70
+ }
71
+
72
+ function refusal(status, text, retryAfter, base) {
73
+ const code = errorCode(text)
74
+ if (status === 429) {
75
+ const wait = waitText(retryAfter)
76
+ return code === 'test_apps_limit'
77
+ ? new Stop(`Pincast has made all the test apps it makes in a day. Try again ${wait}.`)
78
+ // The firewall's 429 carries no Retry-After, and its window is 10 minutes.
79
+ : new Stop(`Too many test apps have come from this network. Try again ${wait === 'later' ? 'in 10 minutes' : wait}.`)
80
+ }
81
+ if (status === 403 && code === 'browser_not_allowed') {
82
+ return new Stop('Pincast refused this call as one from a web page. This command sends no Origin header, so a proxy or network tool probably added it. Try again from a plain terminal.')
83
+ }
84
+ if (status === 404) return new Stop(`Pincast has no test app service at ${base}, so no test app was made.`)
85
+ if (status >= 300 && status < 400) {
86
+ return new Stop(`Pincast pointed this call at another address. This command didn't follow it, because a second call could make a second app. No key was saved. ${ORPHAN}`)
87
+ }
88
+ if (status >= 400 && status < 500) return new Stop(`Pincast refused the call (${status}), so no test app was made.`)
89
+ return new Stop(`Pincast answered with an error (${status}), and no key was saved. ${ORPHAN}`)
90
+ }
91
+
92
+ /** Checks a 200's body. Never repeats any of it: a parse error's message can quote the key. */
93
+ function readAnswer(text) {
94
+ const unreadable = () => new Stop(`Pincast answered, but this command couldn't read the answer, so no key was saved. ${ORPHAN}`)
95
+ let answer
96
+ try {
97
+ answer = JSON.parse(text)
98
+ } catch {
99
+ throw unreadable()
100
+ }
101
+ const id = answer?.app?.id
102
+ const key = answer?.key
103
+ const claimUrl = answer?.claim?.url
104
+ const expiresAt = answer?.claim?.expiresAt ?? answer?.app?.expiresAt
105
+ if (typeof id !== 'string' || !APP_ID_RE.test(id)) throw unreadable()
106
+ if (typeof key !== 'string' || !key.startsWith(`pck_${id}_`) || !/^[A-Za-z0-9_-]{16,256}$/.test(key.slice(`pck_${id}_`.length))) throw unreadable()
107
+ if (typeof claimUrl !== 'string' || !CLAIM_URL_RE.test(claimUrl)) throw unreadable()
108
+ if (typeof expiresAt !== 'string' || !Number.isFinite(Date.parse(expiresAt))) throw unreadable()
109
+ return { id, key, claimUrl, endsOn: new Date(expiresAt).toISOString().slice(0, 10) }
110
+ }
111
+
112
+ /**
113
+ * Makes one test app with one POST: no body, no Origin, no redirect followed, and never a second call,
114
+ * because each call that succeeds makes a new app.
115
+ */
116
+ export async function makeTestApp(base, { fetchImpl = fetch, signal } = {}) {
117
+ const timeout = AbortSignal.timeout(TIMEOUT_MS)
118
+ const combined = signal ? AbortSignal.any([timeout, signal]) : timeout
119
+ let res
120
+ let text
121
+ try {
122
+ res = await fetchImpl(`${base}/test-apps`, {
123
+ method: 'POST',
124
+ headers: { Accept: 'application/json', 'User-Agent': PACKAGE_NAME },
125
+ redirect: 'manual',
126
+ signal: combined,
127
+ })
128
+ text = await res.text()
129
+ } catch (e) {
130
+ if (signal?.aborted) throw new Stop(`Stopped before Pincast answered, so no key was saved. ${ORPHAN}`, 130)
131
+ if (!res && NEVER_SENT.has(failureCode(e))) {
132
+ throw new Stop(`Couldn't reach Pincast at ${base}, so no test app was made. Check your connection, then run the command again.`)
133
+ }
134
+ throw new Stop(`The call went out to Pincast, but its answer never arrived, so no key was saved. ${ORPHAN}`)
135
+ }
136
+ if (res.status !== 200) throw refusal(res.status, text, res.headers.get('retry-after'), base)
137
+ return readAnswer(text)
138
+ }
package/src/cli.js ADDED
@@ -0,0 +1,175 @@
1
+ import { mkdirSync, readdirSync, statSync } from 'node:fs'
2
+ import { basename, isAbsolute, join, relative, resolve } from 'node:path'
3
+ import { apiBase, makeTestApp, Stop } from './api.js'
4
+ import { FIRST_RUN_TIMEOUT_MS, sendFirstRun } from './firstrun.js'
5
+ import { COMMAND } from './name.js'
6
+ import { addReadmeSection, copyStarter, firstRunCommands, removeStarter, setAppId, TEST_PERSON, writeEnv } from './starter.js'
7
+
8
+ const DEFAULT_FOLDER = 'pincast-app'
9
+
10
+ const USAGE = `Make a Placecard app with its own test key:
11
+
12
+ ${COMMAND} [folder]
13
+
14
+ The folder has to be new or empty. With no folder named, the app goes in ./${DEFAULT_FOLDER}.
15
+ `
16
+
17
+ // Every line this command prints passes through here, so a key can't reach the terminal even by mistake.
18
+ const hideKeys = text => String(text).replace(/pck_[A-Za-z0-9_-]+/g, '[key hidden]')
19
+
20
+ const shellWord = word => (/^[A-Za-z0-9._/-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`)
21
+
22
+ /** Reads the arguments: at most one folder. */
23
+ function parseArgs(argv) {
24
+ const flags = argv.filter(a => a.startsWith('-'))
25
+ if (flags.some(f => f === '-h' || f === '--help')) return { help: true }
26
+ if (flags.length) throw new Stop(`This command takes no options.\n\n${USAGE}`, 2)
27
+ if (argv.length > 1) throw new Stop(`This command takes one folder.\n\n${USAGE}`, 2)
28
+ const folder = argv[0] ?? DEFAULT_FOLDER
29
+ // eslint-disable-next-line no-control-regex
30
+ if (!folder.trim() || /[\u0000-\u001f\u007f]/.test(folder)) throw new Stop("That folder name can't be used.", 2)
31
+ return { folder }
32
+ }
33
+
34
+ /** Refuses anything but a new or empty folder, before any call is made. Answers whether it exists. */
35
+ function checkTarget(target, shown) {
36
+ let info
37
+ try {
38
+ info = statSync(target)
39
+ } catch (e) {
40
+ if (e.code === 'ENOENT') return false
41
+ throw new Stop(`Couldn't read ${shown} (${e.code}).`)
42
+ }
43
+ if (!info.isDirectory()) throw new Stop(`${shown} is a file. Name a new or empty folder.`)
44
+ if (readdirSync(target).length) throw new Stop(`${shown} already has files in it, and this command won't write over them. Name a new or empty folder.`)
45
+ return true
46
+ }
47
+
48
+ // What the first run sent, and what the person does next, for each thing it can leave undone.
49
+ const FIRST_RUN_TEXT = {
50
+ none: () => ({
51
+ state: `Pincast has your set, and the test person ${TEST_PERSON} holds Ferry Steps.`,
52
+ next: 'Next, install it and start it:',
53
+ }),
54
+ collect: why => ({
55
+ state: `Pincast has your set but didn't confirm the first collect (${why}). Your app is fine, and the commands below send it. Sending it again within a day changes nothing.`,
56
+ next: 'Next, install it, send its one collect, and start it:',
57
+ }),
58
+ both: why => ({
59
+ state: `Pincast didn't confirm your set (${why}). Your app is fine, and the commands below send the set and one collect.`,
60
+ next: 'Next, install it, send its set and one collect, and start it:',
61
+ }),
62
+ }
63
+
64
+ function successText({ shown, inPlace, id, claimUrl, endsOn, base, first }) {
65
+ const envPath = inPlace ? '.env' : join(shown, '.env')
66
+ const steps = [...(inPlace ? [] : [`cd ${shellWord(shown)}`]), 'npm ci', ...firstRunCommands(base, first.left), 'npm run dev']
67
+ const { state, next } = FIRST_RUN_TEXT[first.left](first.why)
68
+ return [
69
+ `Your app is ready in ${inPlace ? 'this folder' : shown}, with the test app ${id}.`,
70
+ '',
71
+ `Its key is saved in ${envPath}. Only your account can read that file, and git ignores it.`,
72
+ '',
73
+ state,
74
+ '',
75
+ `To keep this app past ${endsOn}, open this link while signed in to Pincast:`,
76
+ '',
77
+ ` ${claimUrl}`,
78
+ '',
79
+ next,
80
+ '',
81
+ ...steps.map(s => ` ${s}`),
82
+ '',
83
+ 'Then open http://localhost:5173.',
84
+ '',
85
+ ].join('\n')
86
+ }
87
+
88
+ /** Runs the command and answers its exit code. Nothing here prints an error's own message. */
89
+ export async function run(argv, {
90
+ env = process.env,
91
+ cwd = process.cwd(),
92
+ out = text => process.stdout.write(text),
93
+ err = text => process.stderr.write(text),
94
+ fetchImpl = fetch,
95
+ beforeCopy = () => {},
96
+ firstRunTimeoutMs = FIRST_RUN_TIMEOUT_MS,
97
+ } = {}) {
98
+ const say = text => out(hideKeys(text))
99
+ const complain = text => err(`${hideKeys(text)}\n`)
100
+ const stopper = new AbortController()
101
+ const onInterrupt = () => stopper.abort()
102
+ const firstRunStopper = new AbortController()
103
+ const onFirstRunInterrupt = () => firstRunStopper.abort()
104
+
105
+ let target
106
+ const files = []
107
+ let madeFrom
108
+ let holdsApp = false
109
+
110
+ try {
111
+ const args = parseArgs(argv)
112
+ if (args.help) {
113
+ say(USAGE)
114
+ return 0
115
+ }
116
+ const { base, custom } = apiBase(env)
117
+ target = resolve(cwd, args.folder)
118
+ const fromCwd = relative(cwd, target)
119
+ const inPlace = fromCwd === ''
120
+ const shown = inPlace ? basename(target) : (fromCwd.startsWith('..') || isAbsolute(fromCwd) ? target : fromCwd)
121
+
122
+ if (!checkTarget(target, shown)) madeFrom = mkdirSync(target, { recursive: true })
123
+
124
+ // The starter goes down first: a failed copy then costs no test app.
125
+ beforeCopy()
126
+ copyStarter(target, files)
127
+
128
+ process.once('SIGINT', onInterrupt)
129
+ const app = await makeTestApp(base, { fetchImpl, signal: stopper.signal })
130
+ process.removeListener('SIGINT', onInterrupt)
131
+ holdsApp = true
132
+
133
+ try {
134
+ writeEnv(target, { key: app.key, claimUrl: app.claimUrl, customBase: custom ? base : null })
135
+ } catch (e) {
136
+ throw new Stop(`Pincast made the test app, but its key couldn't be saved (${e?.code ?? 'write failed'}). Nobody holds that key now, so that app can't be used and it ends on its own. Run the command again in a new folder.`)
137
+ }
138
+ try {
139
+ setAppId(target, app.id)
140
+ } catch (e) {
141
+ throw new Stop(`The key is saved in .env, but the app's id couldn't be written (${e?.code ?? 'write failed'}). Set APP.id in shared/app.js to ${app.id}, and run UPDATE_GOLDENS=1 npm test.`)
142
+ }
143
+
144
+ // From here the app exists and works, so nothing that goes wrong with these two calls stops the command.
145
+ say('Sending the starter\'s set and one test collect to Pincast.\n\n')
146
+ process.once('SIGINT', onFirstRunInterrupt)
147
+ const first = await sendFirstRun(base, target, {
148
+ appId: app.id,
149
+ key: app.key,
150
+ fetchImpl,
151
+ stop: firstRunStopper.signal,
152
+ timeoutMs: firstRunTimeoutMs,
153
+ })
154
+ process.removeListener('SIGINT', onFirstRunInterrupt)
155
+
156
+ try {
157
+ addReadmeSection(target, { id: app.id, base, endsOn: app.endsOn, left: first.left })
158
+ } catch (e) {
159
+ throw new Stop(`Your app is made and its key is in .env, but its README couldn't be updated (${e?.code ?? 'write failed'}). Skip the README's Go live steps, because the first one would erase the key, and follow https://docs.pincast.fm/quickstart. Your claim link is in .env as PINCAST_CLAIM_URL.`)
160
+ }
161
+
162
+ say(successText({ shown, inPlace, id: app.id, claimUrl: app.claimUrl, endsOn: app.endsOn, base, first }))
163
+ return firstRunStopper.signal.aborted ? 130 : 0
164
+ } catch (e) {
165
+ process.removeListener('SIGINT', onInterrupt)
166
+ process.removeListener('SIGINT', onFirstRunInterrupt)
167
+ if (!holdsApp && target) {
168
+ try {
169
+ removeStarter(target, files, madeFrom)
170
+ } catch { /* the message below still has to reach the person */ }
171
+ }
172
+ complain(e instanceof Stop ? e.message : `Something went wrong${e?.code ? ` (${e.code})` : ''}. No key was printed. Run the command again in a new or empty folder.`)
173
+ return e instanceof Stop ? e.exitCode : 1
174
+ }
175
+ }
@@ -0,0 +1,83 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { PACKAGE_NAME } from './name.js'
4
+ import { COLLECT_RETRY_KEY, FIRST_COLLECT, SET_ID } from './starter.js'
5
+
6
+ export const FIRST_RUN_TIMEOUT_MS = 15_000
7
+
8
+ /**
9
+ * One call with the app's key. Answers { ok: true } or { ok: false, why } and never throws, because a
10
+ * failure here can't stop the command: the app is already made. `why` is written here and repeats no
11
+ * part of the answer or of any error, either of which could quote the key. No redirect is followed,
12
+ * because fetch would carry the key header to the new address.
13
+ */
14
+ async function send(url, { method, key, body, headers = {}, accept, fetchImpl, stop, timeoutMs }) {
15
+ const timeout = AbortSignal.timeout(timeoutMs)
16
+ try {
17
+ const res = await fetchImpl(url, {
18
+ method,
19
+ headers: {
20
+ Accept: 'application/json',
21
+ 'Content-Type': 'application/json',
22
+ 'User-Agent': PACKAGE_NAME,
23
+ 'X-Pincast-Key': key,
24
+ ...headers,
25
+ },
26
+ body,
27
+ redirect: 'manual',
28
+ signal: AbortSignal.any([timeout, stop]),
29
+ })
30
+ const text = await res.text()
31
+ if (res.status !== 200) return { ok: false, why: `it answered ${res.status}` }
32
+ let answer
33
+ try {
34
+ answer = JSON.parse(text)
35
+ } catch {
36
+ return { ok: false, why: "its answer couldn't be read" }
37
+ }
38
+ return accept(answer) ? { ok: true } : { ok: false, why: "its answer couldn't be read" }
39
+ } catch {
40
+ if (stop.aborted) return { ok: false, why: 'stopped' }
41
+ if (timeout.aborted) {
42
+ const seconds = Math.max(1, Math.round(timeoutMs / 1000))
43
+ return { ok: false, why: `no answer in ${seconds} second${seconds === 1 ? '' : 's'}` }
44
+ }
45
+ return { ok: false, why: 'the connection failed' }
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Sends the starter's set, then one collect for the test person, so the first screen shows a real card.
51
+ * Answers what is still left to send: 'none', 'collect' or 'both', with the reason.
52
+ *
53
+ * The set goes first because a collect on a missing set is refused. Neither call is retried here.
54
+ * - A repeat of the PUT is harmless: it upserts by set id and card key.
55
+ * - A collect with no `at` counts again on each call, so this one carries an Idempotency-Key. If its
56
+ * answer is lost, the printed command repeats the same key and body, and Pincast answers from the
57
+ * first call for 24 hours instead of counting a second collect.
58
+ */
59
+ export async function sendFirstRun(base, target, { appId, key, fetchImpl = fetch, stop, timeoutMs = FIRST_RUN_TIMEOUT_MS }) {
60
+ let setBody
61
+ try {
62
+ setBody = readFileSync(join(target, 'data', 'set.json'), 'utf8')
63
+ } catch {
64
+ return { left: 'both', why: "the set file couldn't be read" }
65
+ }
66
+ const common = { key, fetchImpl, stop, timeoutMs }
67
+ const set = await send(`${base}/sets/${SET_ID}`, {
68
+ ...common,
69
+ method: 'PUT',
70
+ body: setBody,
71
+ accept: a => a?.app === appId && a?.set === SET_ID,
72
+ })
73
+ if (!set.ok) return { left: 'both', why: set.why }
74
+ const collect = await send(`${base}/sets/${SET_ID}/collects`, {
75
+ ...common,
76
+ method: 'POST',
77
+ headers: { 'Idempotency-Key': COLLECT_RETRY_KEY },
78
+ body: JSON.stringify(FIRST_COLLECT),
79
+ accept: a => a?.collected === true && a?.card?.key === FIRST_COLLECT.card,
80
+ })
81
+ if (!collect.ok) return { left: 'collect', why: collect.why }
82
+ return { left: 'none' }
83
+ }
package/src/name.js ADDED
@@ -0,0 +1,7 @@
1
+ // The one place the package's name lives. package.json has to spell it too, and a test holds the two
2
+ // together. The command's text follows from it: create-x runs as `npm create x`, a scoped name with npx.
3
+ export const PACKAGE_NAME = 'create-pincast'
4
+
5
+ export const COMMAND = PACKAGE_NAME.startsWith('@')
6
+ ? `npx ${PACKAGE_NAME}`
7
+ : `npm create ${PACKAGE_NAME.replace(/^create-/, '')}`