usebecky 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,778 @@
1
+ // `npx usebecky deploy`: which files go up (static sites), and the Node.js server bundle (one .tar.gz).
2
+ // The never-uploaded list and `.usebeckyignore` rules are the same as the dashboard's drag and drop
3
+ // (apps/dashboard/src/pages/project/hosting/logic.ts: skipReason, ignoreMatcher).
4
+ import { spawn } from 'node:child_process';
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import zlib from 'node:zlib';
9
+ export const IGNORE_FILE = '.usebeckyignore';
10
+ /** Why a file is never uploaded, or null. Checked on every folder level. */
11
+ export function skipReason(rel) {
12
+ const parts = rel.split('/');
13
+ const base = parts[parts.length - 1];
14
+ if (parts.includes('.git'))
15
+ return 'Git history';
16
+ if (parts.includes('node_modules'))
17
+ return 'Installed packages (node_modules)';
18
+ if (parts.includes('__MACOSX') || base.startsWith('._'))
19
+ return 'Mac system file';
20
+ if (base === '.DS_Store' || base === 'Thumbs.db' || base === 'desktop.ini')
21
+ return 'System file';
22
+ if (base === '.env' || base.startsWith('.env.'))
23
+ return 'Secrets file (.env)';
24
+ if (base === '.npmrc')
25
+ return 'npm settings (can hold tokens)';
26
+ return null;
27
+ }
28
+ /** Left out at the top of what's uploaded: the usebecky folder (hosting.json, functions, migrations) and the ignore file. */
29
+ function rootSkipReason(rel) {
30
+ if (rel === 'usebecky' || rel.startsWith('usebecky/'))
31
+ return 'usebecky settings folder';
32
+ if (rel === IGNORE_FILE)
33
+ return 'Ignore list';
34
+ return null;
35
+ }
36
+ /**
37
+ * `.usebeckyignore` lines (gitignore-style: `name`, `folder/`, `*.log`, `path/**`, `/only-at-the-top`, `!keep`)
38
+ * → a test for a path. The last matching line wins.
39
+ */
40
+ export function ignoreMatcher(text) {
41
+ const rules = [];
42
+ for (const raw of text.split(/\r?\n/)) {
43
+ let line = raw.trim();
44
+ if (!line || line.startsWith('#'))
45
+ continue;
46
+ const negate = line.startsWith('!');
47
+ if (negate)
48
+ line = line.slice(1);
49
+ const dirOnly = line.endsWith('/');
50
+ line = line.replace(/\/+$/, '');
51
+ const anchored = line.startsWith('/') || line.includes('/');
52
+ line = line.replace(/^\/+/, '');
53
+ if (!line)
54
+ continue;
55
+ const body = line
56
+ .split(/(\*\*\/|\/\*\*|\*\*|\*|\?)/)
57
+ .map((t) => (t === '**/' ? '(?:.*/)?' : t === '/**' ? '(?:/.*)?' : t === '**' ? '.*' : t === '*' ? '[^/]*' : t === '?' ? '[^/]' : t.replace(/[.+^${}()|[\]\\]/g, '\\$&')))
58
+ .join('');
59
+ const tail = dirOnly ? '/' : '(?:/|$)';
60
+ rules.push({ re: new RegExp(`${anchored ? '^' : '(?:^|/)'}${body}${tail}`), negate });
61
+ }
62
+ return (rel) => {
63
+ let ignored = false;
64
+ for (const r of rules)
65
+ if (r.re.test(rel))
66
+ ignored = !r.negate;
67
+ return ignored;
68
+ };
69
+ }
70
+ function readIgnore(dir) {
71
+ try {
72
+ return ignoreMatcher(fs.readFileSync(path.join(dir, IGNORE_FILE), 'utf8'));
73
+ }
74
+ catch {
75
+ return () => false;
76
+ }
77
+ }
78
+ // ---- Symbolic links ----------------------------------------------------------------------------------------
79
+ /**
80
+ * A symbolic link in the folder being deployed that points outside it. Its target is never read: deploying a folder
81
+ * must never upload a file from elsewhere on the computer (a link to ~/.ssh or to the app's .env, say).
82
+ */
83
+ export class LinkOutsideError extends Error {
84
+ /** Where the link is (relative to the app folder when it's inside it). */
85
+ link;
86
+ /** Where it really points (absolute). */
87
+ target;
88
+ /** `.usebeckyignore` can leave it out (static sites, the app's own files; not node_modules or Next.js' output). */
89
+ ignorable;
90
+ constructor(link, target, ignorable = true) {
91
+ super(`${link} is a link to ${target}, outside the folder being deployed.`);
92
+ this.link = link;
93
+ this.target = target;
94
+ this.ignorable = ignorable;
95
+ }
96
+ }
97
+ /** The plain-words problem for a link pointing outside (the CLI prints the message and the fix). */
98
+ export function linkOutsideProblem(e) {
99
+ return {
100
+ message: `${e.link} is a link to ${e.target}, which is outside the folder you’re deploying. Nothing was deployed.`,
101
+ fix: `usebecky only takes what is inside the folder and never follows a link out of it. ${e.ignorable ? `Copy the file or folder in instead of linking to it, or leave the link out with ${IGNORE_FILE}.` : 'Replace the link with a copy of what it points to, then deploy again.'}`,
102
+ };
103
+ }
104
+ /** Is `target` (a real, absolute path) `root` itself or inside it? */
105
+ function isInside(target, root) {
106
+ return target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
107
+ }
108
+ /** A path for messages: relative to `base` with forward slashes when it's inside, else as it is. */
109
+ function shown(abs, base) {
110
+ const rel = path.relative(base, abs);
111
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : abs;
112
+ }
113
+ /**
114
+ * A folder the deploy reads (the build output, `public`, ...) that sits in the app folder but is itself a link to
115
+ * somewhere outside it: refused like any other link. A folder the build config puts elsewhere (`outDir: '../dist'`)
116
+ * isn't a link and is fine.
117
+ */
118
+ function assertNotLinkedOut(abs, appDir) {
119
+ const realApp = safeReal(appDir);
120
+ const lexical = path.relative(path.resolve(appDir), path.resolve(abs));
121
+ if (lexical.startsWith('..') || path.isAbsolute(lexical))
122
+ return;
123
+ const real = safeReal(abs);
124
+ if (!isInside(real, realApp))
125
+ throw new LinkOutsideError(lexical.split(path.sep).join('/') || '.', real);
126
+ }
127
+ /**
128
+ * Every file of a static site under `root`. A symbolic link to something inside `root` is followed (a folder linked
129
+ * from two places is uploaded at both; a folder that links back into itself and broken links are skipped); a link to
130
+ * anything outside `root` stops the collection with `problem` (LinkOutsideError), and nothing is uploaded.
131
+ * `.usebeckyignore` is read from `root` and from `appDir` (the app folder, when `root` is its build output); an ignored
132
+ * link is never looked at.
133
+ */
134
+ export function collectStaticFiles(root, appDir) {
135
+ const own = readIgnore(root);
136
+ const app = appDir && path.resolve(appDir) !== path.resolve(root) ? readIgnore(appDir) : () => false;
137
+ const ignored = (r) => own(r) || app(r);
138
+ const files = [];
139
+ const skipped = [];
140
+ const base = appDir ?? root;
141
+ const realRoot = safeReal(root);
142
+ const walk = (abs, rel, above) => {
143
+ let real;
144
+ try {
145
+ real = fs.realpathSync(abs);
146
+ }
147
+ catch {
148
+ return;
149
+ }
150
+ // Only a loop (a folder inside itself) stops the walk: the same folder linked twice is uploaded at both places.
151
+ if (above.has(real))
152
+ return;
153
+ const path_ = new Set(above).add(real);
154
+ for (const e of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
155
+ const r = rel ? `${rel}/${e.name}` : e.name;
156
+ const why = skipReason(r) ?? rootSkipReason(r) ?? (ignored(r) ? `In ${IGNORE_FILE}` : null);
157
+ if (why) {
158
+ skipped.push({ path: r, reason: why });
159
+ continue;
160
+ }
161
+ const p = path.join(abs, e.name);
162
+ if (e.isSymbolicLink()) {
163
+ let target;
164
+ try {
165
+ target = fs.realpathSync(p);
166
+ }
167
+ catch {
168
+ continue; // a broken symlink
169
+ }
170
+ if (!isInside(target, realRoot))
171
+ throw new LinkOutsideError(shown(path.join(root, r), base), target);
172
+ }
173
+ let st;
174
+ try {
175
+ st = fs.statSync(p);
176
+ }
177
+ catch {
178
+ continue; // a broken symlink
179
+ }
180
+ if (st.isDirectory())
181
+ walk(p, r, path_);
182
+ else if (st.isFile())
183
+ files.push({ path: r, abs: p, size: st.size });
184
+ }
185
+ };
186
+ try {
187
+ if (appDir)
188
+ assertNotLinkedOut(root, appDir);
189
+ walk(root, '', new Set());
190
+ }
191
+ catch (err) {
192
+ if (err instanceof LinkOutsideError)
193
+ return { files: [], skipped, problem: linkOutsideProblem(err) };
194
+ throw err;
195
+ }
196
+ return { files, skipped };
197
+ }
198
+ export function sha256(data) {
199
+ return crypto.createHash('sha256').update(data).digest('hex');
200
+ }
201
+ export function sha256File(abs) {
202
+ return new Promise((resolve, reject) => {
203
+ const h = crypto.createHash('sha256');
204
+ fs.createReadStream(abs)
205
+ .on('data', (c) => h.update(c))
206
+ .on('error', reject)
207
+ .on('end', () => resolve(h.digest('hex')));
208
+ });
209
+ }
210
+ /** Run `fn` over `items` with at most `limit` at a time; results keep the input order. */
211
+ export async function pool(items, limit, fn) {
212
+ const out = new Array(items.length);
213
+ let next = 0;
214
+ const worker = async () => {
215
+ while (next < items.length) {
216
+ const i = next++;
217
+ out[i] = await fn(items[i], i);
218
+ }
219
+ };
220
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
221
+ return out;
222
+ }
223
+ /** Folders a server bundle never needs. */
224
+ const BUNDLE_SKIP_DIRS = new Set(['.git', '.svn', '.hg', '.usebecky', '.vercel', '.netlify', '.turbo', '.cache', 'coverage', '.nyc_output', '.idea', '.vscode', '.github']);
225
+ /** The package a file in node_modules belongs to: `node_modules/@a/b/lib/x.js` → `node_modules/@a/b`. */
226
+ export function owningPackage(rel) {
227
+ const parts = rel.split('/');
228
+ let owner = null;
229
+ for (let i = 0; i < parts.length - 1; i++) {
230
+ if (parts[i] !== 'node_modules')
231
+ continue;
232
+ const name = parts[i + 1];
233
+ if (!name || name === '.bin' || name.startsWith('.'))
234
+ continue;
235
+ const end = name.startsWith('@') ? i + 3 : i + 2;
236
+ if (end > parts.length)
237
+ continue;
238
+ owner = parts.slice(0, end).join('/');
239
+ }
240
+ return owner;
241
+ }
242
+ /**
243
+ * The installed production packages of the app in `dir`, as absolute folders (`npm ls --omit=dev`), or null when
244
+ * they can't be listed (no npm, yarn PnP, ...). Works for npm, yarn classic and bun, which all write a plain node_modules.
245
+ */
246
+ export function listProductionPackages(dir) {
247
+ return new Promise((resolve) => {
248
+ let out = '';
249
+ let child;
250
+ try {
251
+ child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['ls', '--omit=dev', '--all', '--parseable'], { cwd: dir, stdio: ['ignore', 'pipe', 'ignore'], shell: process.platform === 'win32' });
252
+ }
253
+ catch {
254
+ return resolve(null);
255
+ }
256
+ child.stdout.on('data', (c) => (out += c));
257
+ child.on('error', () => resolve(null));
258
+ // npm ls exits 1 for extraneous or missing packages but still lists the tree.
259
+ child.on('close', () => {
260
+ const lines = out.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
261
+ resolve(lines.length ? lines : null);
262
+ });
263
+ });
264
+ }
265
+ /**
266
+ * Add the files under `abs` (as `rel` in the bundle). A symbolic link never brings in anything from outside:
267
+ * - its target is inside `keepLinksInside`: it stays a link (written relative, in the bundle's own paths:
268
+ * node_modules/.bin, pnpm's folders);
269
+ * - it is where npm put a production package (`npmPlaced`): the package is copied from where it really is;
270
+ * - its target is inside a production package copied in from outside the app (`packages`): a link to that copy;
271
+ * - a node_modules/.bin link to a package that isn't in the bundle: left out (it couldn't run there);
272
+ * - anything else: LinkOutsideError, and nothing is deployed.
273
+ * Only a folder inside itself stops the walk, so a folder linked from two places is in the bundle at both.
274
+ */
275
+ function addTree(entries, abs, rel, opts, above = new Set()) {
276
+ let real;
277
+ try {
278
+ real = fs.realpathSync(abs);
279
+ }
280
+ catch {
281
+ return;
282
+ }
283
+ if (above.has(real))
284
+ return;
285
+ const path_ = new Set(above).add(real);
286
+ for (const e of fs.readdirSync(abs, { withFileTypes: true })) {
287
+ const r = rel ? `${rel}/${e.name}` : e.name;
288
+ const p = path.join(abs, e.name);
289
+ let lst;
290
+ try {
291
+ lst = fs.lstatSync(p);
292
+ }
293
+ catch {
294
+ continue;
295
+ }
296
+ if (lst.isSymbolicLink()) {
297
+ let target;
298
+ let st;
299
+ try {
300
+ target = fs.realpathSync(p);
301
+ st = fs.statSync(target);
302
+ }
303
+ catch {
304
+ continue; // broken link
305
+ }
306
+ if (opts.skip(r, st.isDirectory()))
307
+ continue;
308
+ if (!st.isFile() && !st.isDirectory())
309
+ continue;
310
+ const linkTo = (root, at) => {
311
+ const to = path.posix.join(at, path.relative(root, target).split(path.sep).join('/'));
312
+ entries.push({ path: r, type: 'symlink', linkname: path.posix.relative(path.posix.dirname(r), to) || '.', mode: 0o777 });
313
+ };
314
+ if (isInside(target, opts.keepLinksInside)) {
315
+ linkTo(opts.keepLinksInside, opts.linkRoot);
316
+ continue;
317
+ }
318
+ const pkg = opts.packages?.find((x) => isInside(target, x.real));
319
+ if (opts.npmPlaced?.(r)) {
320
+ if (st.isDirectory())
321
+ addTree(entries, target, r, opts, path_);
322
+ else
323
+ entries.push({ path: r, type: 'file', abs: target, mode: st.mode & 0o777 });
324
+ }
325
+ else if (pkg) {
326
+ // (A link to the very place it sits at would be a loop: that place already has the package.)
327
+ const to = path.posix.join(pkg.at, path.relative(pkg.real, target).split(path.sep).join('/'));
328
+ if (to !== r && !r.startsWith(`${to}/`))
329
+ linkTo(pkg.real, pkg.at);
330
+ }
331
+ else if (r.split('/').slice(-3, -1).join('/') === 'node_modules/.bin')
332
+ continue;
333
+ else
334
+ throw new LinkOutsideError(shown(p, opts.base), target, !!opts.ignorable);
335
+ continue;
336
+ }
337
+ if (opts.skip(r, lst.isDirectory()))
338
+ continue;
339
+ if (lst.isDirectory())
340
+ addTree(entries, p, r, opts, path_);
341
+ else if (lst.isFile())
342
+ entries.push({ path: r, type: 'file', abs: p, mode: lst.mode & 0o777 });
343
+ }
344
+ }
345
+ /** Links that point at nothing in the bundle (their target was left out): drop them, the runtime can't use them. */
346
+ function dropDanglingLinks(entries) {
347
+ const files = new Set();
348
+ const dirs = new Set();
349
+ for (const e of entries) {
350
+ files.add(e.path);
351
+ const parts = e.path.split('/');
352
+ for (let i = 1; i < parts.length; i++)
353
+ dirs.add(parts.slice(0, i).join('/'));
354
+ }
355
+ for (let i = entries.length - 1; i >= 0; i--) {
356
+ const e = entries[i];
357
+ if (e.type !== 'symlink')
358
+ continue;
359
+ const target = path.posix.normalize(path.posix.join(path.posix.dirname(e.path), e.linkname ?? ''));
360
+ if (!files.has(target) && !dirs.has(target))
361
+ entries.splice(i, 1);
362
+ }
363
+ }
364
+ function packageJsonEntry(pkg, start) {
365
+ const next = { ...pkg };
366
+ if (start) {
367
+ next.scripts = { ...(pkg.scripts ?? {}), start };
368
+ // `main` would be ambiguous next to a different start script.
369
+ const m = /^node\s+(\S+)$/.exec(start);
370
+ if (m)
371
+ next.main = m[1].replace(/^\.\//, '');
372
+ }
373
+ return { path: 'package.json', type: 'file', data: Buffer.from(JSON.stringify(next, null, 2) + '\n'), mode: 0o644 };
374
+ }
375
+ /** What a server bundle never takes (node_modules is wanted here, unlike static sites; .env files stay home). */
376
+ export function bundleSkip(rel) {
377
+ const parts = rel.split('/');
378
+ const base = parts[parts.length - 1];
379
+ if (parts.includes('.git') || parts.includes('__MACOSX') || base.startsWith('._'))
380
+ return true;
381
+ if (base === '.DS_Store' || base === 'Thumbs.db' || base === 'desktop.ini')
382
+ return true;
383
+ // Secrets files of the app (not files a package ships inside node_modules).
384
+ if (!parts.includes('node_modules') && (base === '.env' || base.startsWith('.env.') || base === '.npmrc'))
385
+ return true;
386
+ return false;
387
+ }
388
+ /** Where a production package found outside the app folder (hoisted in a monorepo) goes in the bundle. */
389
+ function hoistedPath(abs) {
390
+ const parts = abs.split(path.sep);
391
+ const i = parts.indexOf('node_modules');
392
+ if (i >= 0 && i < parts.length - 1)
393
+ return parts.slice(i).join('/');
394
+ const name = readJson(path.join(abs, 'package.json'))?.name;
395
+ return typeof name === 'string' && name ? `node_modules/${name}` : null;
396
+ }
397
+ /**
398
+ * Put the Node.js server bundle together (after the build). `listPackages` lists production packages
399
+ * (default: `npm ls --omit=dev`; tests pass a fake).
400
+ */
401
+ export async function buildNodeBundle(dir, bundle, listPackages = listProductionPackages) {
402
+ try {
403
+ return await bundleOf(dir, bundle, listPackages);
404
+ }
405
+ catch (err) {
406
+ if (err instanceof LinkOutsideError)
407
+ return { entries: [], nativeModules: [], start: null, allModules: false, problem: linkOutsideProblem(err) };
408
+ throw err;
409
+ }
410
+ }
411
+ async function bundleOf(dir, bundle, listPackages) {
412
+ const entries = [];
413
+ const ignored = readIgnore(dir);
414
+ if (bundle.type === 'next-standalone') {
415
+ const root = path.join(dir, '.next', 'standalone');
416
+ if (!fs.existsSync(root))
417
+ return missing('There is no .next/standalone folder after the build.', "Check that next.config has output: 'standalone' and that `next build` finished without errors.");
418
+ // In a monorepo, Next.js nests the app (".next/standalone/apps/web/server.js").
419
+ const server = findServerJs(root);
420
+ if (!server)
421
+ return missing('.next/standalone has no server.js.', 'Run the build again; if it keeps happening, delete the .next folder first.');
422
+ const appRel = path.relative(root, path.dirname(server)).split(path.sep).join('/');
423
+ const prefix = appRel ? `${appRel}/` : '';
424
+ assertNotLinkedOut(root, dir);
425
+ addTree(entries, root, '', { skip: (r) => bundleSkip(r) || r === 'package.json' || r === `${prefix}.next/cache` || r.startsWith(`${prefix}.next/cache/`), keepLinksInside: fs.realpathSync(root), linkRoot: '', base: dir });
426
+ // Next.js leaves these out of standalone on purpose: the static files and public/ are copied in.
427
+ const nextStatic = path.join(dir, '.next', 'static');
428
+ if (fs.existsSync(nextStatic)) {
429
+ assertNotLinkedOut(nextStatic, dir);
430
+ addTree(entries, nextStatic, `${prefix}.next/static`, { skip: bundleSkip, keepLinksInside: fs.realpathSync(nextStatic), linkRoot: `${prefix}.next/static`, base: dir });
431
+ }
432
+ const pub = path.join(dir, 'public');
433
+ if (fs.existsSync(pub)) {
434
+ assertNotLinkedOut(pub, dir);
435
+ addTree(entries, pub, `${prefix}public`, { skip: bundleSkip, keepLinksInside: fs.realpathSync(pub), linkRoot: `${prefix}public`, base: dir });
436
+ }
437
+ const pkg = readJson(path.join(root, 'package.json')) ?? readJson(path.join(dir, 'package.json')) ?? {};
438
+ const start = `node ${prefix}server.js`;
439
+ entries.push(packageJsonEntry(pkg, start));
440
+ return done(entries, start, false);
441
+ }
442
+ if (bundle.type === 'folder') {
443
+ const root = path.join(dir, bundle.root);
444
+ if (!fs.existsSync(root))
445
+ return missing(`There is no ${bundle.root} folder after the build.`, 'Check that the build finished without errors.');
446
+ assertNotLinkedOut(root, dir);
447
+ addTree(entries, root, '', { skip: (r) => bundleSkip(r) || r === 'package.json', keepLinksInside: fs.realpathSync(root), linkRoot: '', base: dir });
448
+ const pkg = readJson(path.join(root, 'package.json')) ?? { name: readJson(path.join(dir, 'package.json'))?.name ?? 'app', private: true };
449
+ entries.push(packageJsonEntry(pkg, bundle.start));
450
+ return done(entries, bundle.start, false);
451
+ }
452
+ // The app folder + production node_modules.
453
+ const pkg = readJson(path.join(dir, 'package.json'));
454
+ if (!pkg)
455
+ return missing('There is no package.json in this folder.', 'Run the command in your app’s folder.');
456
+ const start = bundle.start ?? pkg.scripts?.start ?? (pkg.main ? `node ${pkg.main}` : null);
457
+ if (!start)
458
+ return missing('package.json has no start script and no main file, so usebecky doesn’t know how to start your server.', 'Add "start": "node server.js" (your server’s file) to the scripts in package.json.');
459
+ const realDir = fs.realpathSync(dir);
460
+ // Production dependencies only: the packages `npm ls --omit=dev` lists, from the app's node_modules or, in a
461
+ // monorepo, from wherever npm put them (they go to node_modules/<name> in the bundle). Listed first: a link in the
462
+ // app (node_modules/.bin, say) may point into one of the packages copied in from outside.
463
+ const modules = path.join(dir, 'node_modules');
464
+ let listed = await listPackages(dir);
465
+ const allowed = new Set();
466
+ const inApp = (abs, base) => {
467
+ const rel = path.relative(base, abs);
468
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : null;
469
+ };
470
+ const outside = [];
471
+ if (listed) {
472
+ let found = 0;
473
+ for (const p of listed) {
474
+ const given = path.resolve(dir, p);
475
+ const real = safeReal(given);
476
+ // The app itself, and in a workspace the monorepo's root (npm lists it first): never packages.
477
+ if (real === realDir || realDir.startsWith(real + path.sep))
478
+ continue;
479
+ if (!fs.existsSync(real))
480
+ continue;
481
+ found++;
482
+ // Where npm put it (a workspace link stays at its node_modules place), and where it really is.
483
+ const here = inApp(given, dir) ?? inApp(given, realDir) ?? inApp(real, realDir);
484
+ if (here?.startsWith('node_modules/')) {
485
+ allowed.add(here);
486
+ continue;
487
+ }
488
+ const at = hoistedPath(given);
489
+ if (at)
490
+ outside.push({ at, real });
491
+ }
492
+ // Nothing npm listed exists (npm can hide parts of paths): copy all of node_modules rather than none of it.
493
+ if (!found && listed.filter((p) => safeReal(path.resolve(dir, p)) !== realDir).length)
494
+ listed = null;
495
+ }
496
+ // The packages copied in from outside the app folder (taken from where npm put them, not through a link).
497
+ const copiedIn = [];
498
+ if (listed) {
499
+ for (const o of outside) {
500
+ if (allowed.has(o.at))
501
+ continue; // the app's own copy wins, as in Node's own lookup
502
+ allowed.add(o.at);
503
+ copiedIn.push(o);
504
+ }
505
+ }
506
+ const npmPlaced = (r) => !!listed && allowed.has(r);
507
+ if (bundle.include) {
508
+ for (const inc of bundle.include) {
509
+ if (inc === 'package.json')
510
+ continue;
511
+ const abs = path.join(dir, inc);
512
+ if (!fs.existsSync(abs)) {
513
+ if (inc === 'public')
514
+ continue;
515
+ return missing(`There is no ${inc} folder after the build.`, 'Check that the build finished without errors.');
516
+ }
517
+ assertNotLinkedOut(abs, dir);
518
+ const st = fs.statSync(abs);
519
+ if (st.isDirectory())
520
+ addTree(entries, abs, inc, { skip: (r) => bundleSkip(r) || ignored(r), keepLinksInside: realDir, linkRoot: '', base: dir, packages: copiedIn, ignorable: true });
521
+ else
522
+ entries.push({ path: inc, type: 'file', abs, mode: st.mode & 0o777 });
523
+ }
524
+ for (const lock of ['package-lock.json', 'npm-shrinkwrap.json'])
525
+ if (fs.existsSync(path.join(dir, lock)))
526
+ entries.push({ path: lock, type: 'file', abs: path.join(dir, lock), mode: 0o644 });
527
+ }
528
+ else {
529
+ addTree(entries, dir, '', {
530
+ skip: (r, isDir) => {
531
+ const top = r.split('/')[0];
532
+ if (top === 'node_modules' || top === 'usebecky' || r === IGNORE_FILE || r === 'package.json')
533
+ return true;
534
+ if (isDir && !r.includes('/') && BUNDLE_SKIP_DIRS.has(r))
535
+ return true;
536
+ return bundleSkip(r) || ignored(r);
537
+ },
538
+ keepLinksInside: realDir,
539
+ linkRoot: '',
540
+ base: dir,
541
+ packages: copiedIn,
542
+ ignorable: true,
543
+ });
544
+ }
545
+ entries.push(packageJsonEntry(pkg, bundle.start));
546
+ for (const { at, real } of copiedIn) {
547
+ // Its own nested node_modules are listed (and added) separately.
548
+ addTree(entries, real, at, { skip: (r) => bundleSkip(r) || r === `${at}/node_modules` || r.startsWith(`${at}/node_modules/`), keepLinksInside: real, linkRoot: at, base: dir, packages: copiedIn });
549
+ }
550
+ const allModules = !listed && fs.existsSync(modules);
551
+ if (fs.existsSync(modules)) {
552
+ // node_modules itself a link out of the app: only the packages npm reports there are taken (as from a monorepo).
553
+ if (!listed)
554
+ assertNotLinkedOut(modules, dir);
555
+ addTree(entries, modules, 'node_modules', {
556
+ skip: (r, isDir) => {
557
+ const base = r.split('/').pop() ?? '';
558
+ if (base === '.cache' || bundleSkip(r))
559
+ return true;
560
+ if (!listed)
561
+ return false;
562
+ if (isDir) {
563
+ // node_modules/<pkg> (or @scope/<pkg>) that isn't a production package: leave the whole folder out.
564
+ const owner = owningPackage(`${r}/x`);
565
+ return owner === r && !allowed.has(r);
566
+ }
567
+ if (r.startsWith('node_modules/.bin/'))
568
+ return false;
569
+ const owner = owningPackage(r);
570
+ return owner ? !allowed.has(owner) : false;
571
+ },
572
+ keepLinksInside: realDir,
573
+ linkRoot: '',
574
+ base: dir,
575
+ packages: copiedIn,
576
+ npmPlaced,
577
+ });
578
+ }
579
+ return done(entries, start, allModules);
580
+ function missing(message, fix) {
581
+ return { entries: [], nativeModules: [], start: null, allModules: false, problem: { message, fix } };
582
+ }
583
+ }
584
+ function done(entries, start, allModules) {
585
+ // One entry per path (the last one wins), sorted so the same app gives the same archive.
586
+ const byPath = new Map();
587
+ for (const e of entries)
588
+ byPath.set(e.path, e);
589
+ const unique = [...byPath.values()];
590
+ dropDanglingLinks(unique);
591
+ byPath.clear();
592
+ for (const e of unique)
593
+ byPath.set(e.path, e);
594
+ const list = [...byPath.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
595
+ const nativeModules = [...new Set(list.filter((e) => e.path.endsWith('.node') && e.path.includes('node_modules/')).map((e) => owningPackage(e.path) ?? e.path))];
596
+ return { entries: list, nativeModules, start, allModules };
597
+ }
598
+ function findServerJs(root, depth = 0) {
599
+ if (fs.existsSync(path.join(root, 'server.js')) && fs.existsSync(path.join(root, '.next')))
600
+ return path.join(root, 'server.js');
601
+ if (depth >= 4)
602
+ return null;
603
+ for (const e of fs.readdirSync(root, { withFileTypes: true })) {
604
+ if (!e.isDirectory() || e.name === 'node_modules' || e.name.startsWith('.'))
605
+ continue;
606
+ const hit = findServerJs(path.join(root, e.name), depth + 1);
607
+ if (hit)
608
+ return hit;
609
+ }
610
+ return null;
611
+ }
612
+ function readJson(file) {
613
+ try {
614
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
615
+ }
616
+ catch {
617
+ return null;
618
+ }
619
+ }
620
+ function safeReal(p) {
621
+ try {
622
+ return fs.realpathSync(p);
623
+ }
624
+ catch {
625
+ return path.resolve(p);
626
+ }
627
+ }
628
+ /** Bytes of every file in the bundle (before compression). */
629
+ export function bundleBytes(entries) {
630
+ let n = 0;
631
+ for (const e of entries)
632
+ if (e.type === 'file')
633
+ n += e.data ? e.data.length : fs.statSync(e.abs).size;
634
+ return n;
635
+ }
636
+ // ---- tar.gz -------------------------------------------------------------------------------------------------
637
+ function octal(n, len) {
638
+ return n.toString(8).padStart(len - 1, '0') + '\0';
639
+ }
640
+ function header(name, opts) {
641
+ const h = Buffer.alloc(512);
642
+ h.write(name.slice(0, 100), 0, 'utf8');
643
+ h.write(octal(opts.mode & 0o7777, 8), 100, 'ascii');
644
+ h.write(octal(0, 8), 108, 'ascii'); // uid
645
+ h.write(octal(0, 8), 116, 'ascii'); // gid
646
+ h.write(octal(opts.size, 12), 124, 'ascii');
647
+ h.write(octal(0, 12), 136, 'ascii'); // mtime 0: the same app gives the same archive
648
+ h.write(' ', 148, 'ascii'); // checksum placeholder
649
+ h.write(opts.type, 156, 'ascii');
650
+ if (opts.linkname)
651
+ h.write(opts.linkname.slice(0, 100), 157, 'utf8');
652
+ h.write('ustar\0', 257, 'ascii');
653
+ h.write('00', 263, 'ascii');
654
+ let sum = 0;
655
+ for (const b of h)
656
+ sum += b;
657
+ h.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 'ascii');
658
+ return h;
659
+ }
660
+ const pad = (n) => Buffer.alloc((512 - (n % 512)) % 512);
661
+ /** A PAX record: "<length> key=value\n", where length counts itself. */
662
+ function paxRecord(key, value) {
663
+ const body = ` ${key}=${value}\n`;
664
+ let len = Buffer.byteLength(body) + 1;
665
+ while (String(len).length + Buffer.byteLength(body) !== len)
666
+ len = String(len).length + Buffer.byteLength(body);
667
+ return `${len}${body}`;
668
+ }
669
+ /** One entry's tar blocks; long or non-ASCII names get a PAX header first. */
670
+ function tarEntry(e) {
671
+ const name = e.type === 'dir' ? `${e.path}/` : e.path;
672
+ const out = [];
673
+ const records = [];
674
+ if (Buffer.byteLength(name) > 100 || /[^\x20-\x7e]/.test(name))
675
+ records.push(paxRecord('path', name));
676
+ if (e.linkname && (Buffer.byteLength(e.linkname) > 100 || /[^\x20-\x7e]/.test(e.linkname)))
677
+ records.push(paxRecord('linkpath', e.linkname));
678
+ if (records.length) {
679
+ const data = Buffer.from(records.join(''));
680
+ out.push(header(`PaxHeader/${name.replace(/[^\x20-\x7e]/g, '_').slice(-80)}`, { size: data.length, mode: 0o644, type: 'x' }), data, pad(data.length));
681
+ }
682
+ const size = e.type === 'file' ? (e.data?.length ?? 0) : 0;
683
+ const ascii = name.replace(/[^\x20-\x7e]/g, '_');
684
+ out.push(header(ascii, { size, mode: e.mode, type: e.type === 'file' ? '0' : e.type === 'symlink' ? '2' : '5', linkname: e.linkname?.replace(/[^\x20-\x7e]/g, '_') }));
685
+ if (size)
686
+ out.push(e.data, pad(size));
687
+ return out;
688
+ }
689
+ /** The bundle as a gzip-compressed tar (folders first-mentioned before their files, sorted, mtime 0). */
690
+ export async function packTarGz(entries) {
691
+ const gz = zlib.createGzip({ level: 6 });
692
+ const chunks = [];
693
+ gz.on('data', (c) => chunks.push(c));
694
+ const finished = new Promise((resolve, reject) => {
695
+ gz.on('end', resolve);
696
+ gz.on('error', reject);
697
+ });
698
+ const write = (b) => (gz.write(b) ? Promise.resolve() : new Promise((r) => gz.once('drain', r)));
699
+ const dirs = new Set();
700
+ for (const e of entries) {
701
+ const parts = e.path.split('/');
702
+ for (let i = 1; i < parts.length; i++) {
703
+ const d = parts.slice(0, i).join('/');
704
+ if (dirs.has(d))
705
+ continue;
706
+ dirs.add(d);
707
+ for (const b of tarEntry({ path: d, type: 'dir', mode: 0o755 }))
708
+ await write(b);
709
+ }
710
+ const data = e.type === 'file' ? (e.data ?? fs.readFileSync(e.abs)) : undefined;
711
+ for (const b of tarEntry({ path: e.path, type: e.type, mode: e.mode || 0o644, data, linkname: e.linkname }))
712
+ await write(b);
713
+ }
714
+ await write(Buffer.alloc(1024));
715
+ gz.end();
716
+ await finished;
717
+ return Buffer.concat(chunks);
718
+ }
719
+ /** Read a (gzip-compressed) tar back: [{ path, type, mode, data, linkname }]. For tests and checks. */
720
+ export function readTar(buf) {
721
+ const tar = buf[0] === 0x1f && buf[1] === 0x8b ? zlib.gunzipSync(buf) : buf;
722
+ const out = [];
723
+ let off = 0;
724
+ let pax = {};
725
+ const str = (b) => b.toString('utf8').replace(/\0.*$/s, '');
726
+ while (off + 512 <= tar.length) {
727
+ const h = tar.subarray(off, off + 512);
728
+ if (h.every((b) => b === 0))
729
+ break;
730
+ const size = parseInt(str(h.subarray(124, 136)).trim() || '0', 8);
731
+ const type = String.fromCharCode(h[156] || 48);
732
+ const data = tar.subarray(off + 512, off + 512 + size);
733
+ off += 512 + Math.ceil(size / 512) * 512;
734
+ if (type === 'x') {
735
+ pax = {};
736
+ let s = data.toString('utf8');
737
+ while (s.length) {
738
+ const sp = s.indexOf(' ');
739
+ const len = Number(s.slice(0, sp));
740
+ const rec = s.slice(sp + 1, len - 1);
741
+ const eq = rec.indexOf('=');
742
+ pax[rec.slice(0, eq)] = rec.slice(eq + 1);
743
+ s = s.slice(len);
744
+ }
745
+ continue;
746
+ }
747
+ const prefix = str(h.subarray(345, 500));
748
+ const name = pax.path ?? (prefix ? `${prefix}/${str(h.subarray(0, 100))}` : str(h.subarray(0, 100)));
749
+ out.push({ path: name.replace(/\/$/, ''), type, mode: parseInt(str(h.subarray(100, 108)).trim() || '0', 8), data: Buffer.from(data), linkname: pax.linkpath ?? str(h.subarray(157, 257)) });
750
+ pax = {};
751
+ }
752
+ return out;
753
+ }
754
+ /** The file a `node [flags] file` start command runs, or null for anything else (`remix-serve …`, `tsx …`). */
755
+ export function startFile(start) {
756
+ const words = (start ?? '').trim().split(/\s+/);
757
+ if (words[0] !== 'node')
758
+ return null;
759
+ return words.slice(1).find((w) => !w.startsWith('-')) ?? null;
760
+ }
761
+ /** Does the entry file mention process.env.PORT? (Node.js sites must listen on it.) null: couldn't tell. */
762
+ export function mentionsPort(entries, start) {
763
+ const file = startFile(start)?.replace(/^\.\//, '');
764
+ const e = file ? entries.find((x) => x.path === file && x.type === 'file') : null;
765
+ if (!e)
766
+ return null;
767
+ try {
768
+ const text = (e.data ?? fs.readFileSync(e.abs)).toString('utf8');
769
+ return /process\.env\.PORT\b|process\.env\[['"]PORT['"]\]|\{[^}]*\bPORT\b[^}]*\}\s*=\s*process\.env/.test(text);
770
+ }
771
+ catch {
772
+ return null;
773
+ }
774
+ }
775
+ /** `node --env-file=.env …` fails on usebecky: .env is never uploaded (`--env-file-if-exists` is fine). */
776
+ export function startNeedsEnvFile(start) {
777
+ return /--env-file(?!-if-exists)(?:=|\s)/.test(start ?? '');
778
+ }