@knapsack/package-bundler 4.101.0--canary.8110.15bba7c.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 (67) hide show
  1. package/.lintstagedrc.mjs +11 -0
  2. package/INSTRUCTIONS-FOR-CUSTOMERS.md +130 -0
  3. package/dist/bundle.d.ts +41 -0
  4. package/dist/bundle.d.ts.map +1 -0
  5. package/dist/bundle.js +348 -0
  6. package/dist/bundle.js.map +1 -0
  7. package/dist/cli.d.ts +6 -0
  8. package/dist/cli.d.ts.map +1 -0
  9. package/dist/cli.js +165 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/errors.d.ts +63 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +155 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/help-text.d.ts +16 -0
  16. package/dist/help-text.d.ts.map +1 -0
  17. package/dist/help-text.js +180 -0
  18. package/dist/help-text.js.map +1 -0
  19. package/dist/index.d.ts +20 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +20 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/log.d.ts +42 -0
  24. package/dist/log.d.ts.map +1 -0
  25. package/dist/log.js +114 -0
  26. package/dist/log.js.map +1 -0
  27. package/dist/metadata.d.ts +112 -0
  28. package/dist/metadata.d.ts.map +1 -0
  29. package/dist/metadata.js +204 -0
  30. package/dist/metadata.js.map +1 -0
  31. package/dist/prompts.d.ts +54 -0
  32. package/dist/prompts.d.ts.map +1 -0
  33. package/dist/prompts.js +125 -0
  34. package/dist/prompts.js.map +1 -0
  35. package/dist/resolve-entries.d.ts +56 -0
  36. package/dist/resolve-entries.d.ts.map +1 -0
  37. package/dist/resolve-entries.js +333 -0
  38. package/dist/resolve-entries.js.map +1 -0
  39. package/dist/resolve-source.d.ts +53 -0
  40. package/dist/resolve-source.d.ts.map +1 -0
  41. package/dist/resolve-source.js +174 -0
  42. package/dist/resolve-source.js.map +1 -0
  43. package/dist/run.d.ts +52 -0
  44. package/dist/run.d.ts.map +1 -0
  45. package/dist/run.js +276 -0
  46. package/dist/run.js.map +1 -0
  47. package/dist/types.d.ts +67 -0
  48. package/dist/types.d.ts.map +1 -0
  49. package/dist/types.js +62 -0
  50. package/dist/types.js.map +1 -0
  51. package/dist/vendor.d.ts +59 -0
  52. package/dist/vendor.d.ts.map +1 -0
  53. package/dist/vendor.js +134 -0
  54. package/dist/vendor.js.map +1 -0
  55. package/dist/verify-bundle.d.ts +59 -0
  56. package/dist/verify-bundle.d.ts.map +1 -0
  57. package/dist/verify-bundle.js +238 -0
  58. package/dist/verify-bundle.js.map +1 -0
  59. package/dist/write-output.d.ts +82 -0
  60. package/dist/write-output.d.ts.map +1 -0
  61. package/dist/write-output.js +214 -0
  62. package/dist/write-output.js.map +1 -0
  63. package/package.json +53 -0
  64. package/readme.md +127 -0
  65. package/tsconfig.json +9 -0
  66. package/tsconfig.test.json +13 -0
  67. package/vitest.config.ts +9 -0
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Turn the raw Vite output into a usable package: a fresh package.json, working bin
3
+ * shebangs, a hoisted `"use client"` where one is needed, and the non-JS files the
4
+ * bundler cannot see.
5
+ */
6
+ import type { SourcePackageJson } from './resolve-entries.js';
7
+ import type { EntryPoint, ExternalPackage } from './types.js';
8
+ /**
9
+ * Work out which directories hold the package's built output.
10
+ *
11
+ * Derived from where the entry points actually live rather than by guessing at a name,
12
+ * because `dist` is a convention, not a rule. For an entry at `dist/components/button.js`
13
+ * the build root is `dist`, **not** `dist/components` — relativising against the entry's
14
+ * own directory would flatten `components/button.d.ts` onto the bundle root, where the
15
+ * emitted `components/button.mjs` would never find it.
16
+ */
17
+ export declare function findBuildRoots({ pkgDir, entrySourceFiles, }: {
18
+ pkgDir: string;
19
+ entrySourceFiles: readonly string[];
20
+ }): readonly string[];
21
+ /**
22
+ * Copy every file from the source's built output that the bundle does not already
23
+ * contain: type declarations, JSON read at runtime, templates, fonts, images.
24
+ *
25
+ * Type declarations matter more than they look — without them the bundle is unusable
26
+ * from TypeScript, which for a design system is most of its audience.
27
+ *
28
+ * Paths are preserved relative to the build root, so a nested entry keeps its folder.
29
+ */
30
+ export declare function copyNonJsAssets({ buildRoots, bundleDir, }: {
31
+ /** Directories holding the built output, from `findBuildRoots`. */
32
+ buildRoots: readonly string[];
33
+ bundleDir: string;
34
+ }): readonly string[];
35
+ export declare function copyRootFiles({ pkgDir, bundleDir, }: {
36
+ pkgDir: string;
37
+ bundleDir: string;
38
+ }): readonly string[];
39
+ /**
40
+ * Put a shebang back at byte 0 and make the file executable.
41
+ *
42
+ * Two things conspire against a working bin. `output.banner` is prepended above
43
+ * everything, so it lands before any shebang; and `@rollup/plugin-commonjs` strips the
44
+ * source shebang and re-emits it *inside* the module body, where it is just a comment.
45
+ * Nothing will `npm link` these files either, so the executable bit has to be ours.
46
+ */
47
+ export declare function fixBinShebang(file: string): void;
48
+ /**
49
+ * Hoist a single `"use client"` to byte 0.
50
+ *
51
+ * Per-module directives cannot survive collapsing many modules into one chunk — Rollup
52
+ * says so with `MODULE_LEVEL_DIRECTIVE` and drops them. For a React design system the
53
+ * honest translation is that the whole bundle is a client module, so one directive at
54
+ * the top preserves the meaning that matters to a consumer using Server Components.
55
+ */
56
+ export declare function hoistUseClient(file: string): void;
57
+ /**
58
+ * Build the bundle's package.json from scratch.
59
+ *
60
+ * Rewriting rather than patching, because most of the original fields are actively
61
+ * wrong for a bundle: `scripts` may hold a `postinstall` that fails, `imports` maps
62
+ * `#internal` subpaths at files that no longer exist, `sideEffects: false` is a lie once
63
+ * everything is one chunk, and `devDependencies` are noise.
64
+ */
65
+ export declare function buildBundlePackageJson({ bundleDir, pkgJson, entries, externals, origin, bundlerVersion, hadUseClientDirective, }: {
66
+ /** Used to check which declaration files actually landed in the output. */
67
+ bundleDir: string;
68
+ pkgJson: SourcePackageJson;
69
+ entries: readonly EntryPoint[];
70
+ externals: readonly ExternalPackage[];
71
+ origin: {
72
+ readonly kind: string;
73
+ readonly detail: string;
74
+ };
75
+ bundlerVersion: string;
76
+ hadUseClientDirective: boolean;
77
+ }): Record<string, unknown>;
78
+ export declare function writeBundlePackageJson({ bundleDir, contents, }: {
79
+ bundleDir: string;
80
+ contents: Record<string, unknown>;
81
+ }): void;
82
+ //# sourceMappingURL=write-output.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write-output.d.ts","sourceRoot":"","sources":["../src/write-output.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAYH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAe9D;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,EAC7B,MAAM,EACN,gBAAgB,GACjB,EAAE;IACD,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;CACrC,GAAG,SAAS,MAAM,EAAE,CAiBpB;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,EAC9B,UAAU,EACV,SAAS,GACV,EAAE;IACD,mEAAmE;IACnE,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;CACnB,GAAG,SAAS,MAAM,EAAE,CAgCpB;AAED,wBAAgB,aAAa,CAAC,EAC5B,MAAM,EACN,SAAS,GACV,EAAE;IACD,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB,GAAG,SAAS,MAAM,EAAE,CAWpB;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAQhD;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAIjD;AAOD;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,EACrC,SAAS,EACT,OAAO,EACP,OAAO,EACP,SAAS,EACT,MAAM,EACN,cAAc,EACd,qBAAqB,GACtB,EAAE;IACD,2EAA2E;IAC3E,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,iBAAiB,CAAC;IAC3B,OAAO,EAAE,SAAS,UAAU,EAAE,CAAC;IAC/B,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;IACtC,MAAM,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAC3D,cAAc,EAAE,MAAM,CAAC;IACvB,qBAAqB,EAAE,OAAO,CAAC;CAChC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAsE1B;AAED,wBAAgB,sBAAsB,CAAC,EACrC,SAAS,EACT,QAAQ,GACT,EAAE;IACD,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC,GAAG,IAAI,CAKP"}
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Turn the raw Vite output into a usable package: a fresh package.json, working bin
3
+ * shebangs, a hoisted `"use client"` where one is needed, and the non-JS files the
4
+ * bundler cannot see.
5
+ */
6
+ import { chmodSync, cpSync, existsSync, readFileSync, readdirSync, writeFileSync, } from 'node:fs';
7
+ import { dirname, join, relative, sep } from 'node:path';
8
+ import { ensureDirSync } from '@knapsack/file-utils';
9
+ /** Files worth carrying over verbatim from the source package root. */
10
+ const ROOT_FILES_TO_COPY = [
11
+ 'LICENSE',
12
+ 'LICENSE.md',
13
+ 'LICENSE.txt',
14
+ 'README.md',
15
+ 'readme.md',
16
+ 'CHANGELOG.md',
17
+ ];
18
+ /** Extensions the bundler either inlines or emits itself. */
19
+ const BUNDLER_HANDLED = /\.(js|mjs|cjs|jsx|ts|tsx|map)$/;
20
+ /**
21
+ * Work out which directories hold the package's built output.
22
+ *
23
+ * Derived from where the entry points actually live rather than by guessing at a name,
24
+ * because `dist` is a convention, not a rule. For an entry at `dist/components/button.js`
25
+ * the build root is `dist`, **not** `dist/components` — relativising against the entry's
26
+ * own directory would flatten `components/button.d.ts` onto the bundle root, where the
27
+ * emitted `components/button.mjs` would never find it.
28
+ */
29
+ export function findBuildRoots({ pkgDir, entrySourceFiles, }) {
30
+ const roots = new Set();
31
+ for (const file of entrySourceFiles) {
32
+ const rel = relative(pkgDir, file);
33
+ // An entry outside the package (an absolute --entry elsewhere) has no build root
34
+ // we can safely walk; its own directory is the best we can do.
35
+ if (rel.startsWith('..')) {
36
+ roots.add(dirname(file));
37
+ continue;
38
+ }
39
+ const [firstSegment] = rel.split(sep);
40
+ // An entry sitting directly in the package root gives us no subdirectory to scope
41
+ // to; walking pkgDir would sweep in src/, tests, config and everything else.
42
+ if (!firstSegment || firstSegment === rel)
43
+ continue;
44
+ roots.add(join(pkgDir, firstSegment));
45
+ }
46
+ return [...roots];
47
+ }
48
+ /**
49
+ * Copy every file from the source's built output that the bundle does not already
50
+ * contain: type declarations, JSON read at runtime, templates, fonts, images.
51
+ *
52
+ * Type declarations matter more than they look — without them the bundle is unusable
53
+ * from TypeScript, which for a design system is most of its audience.
54
+ *
55
+ * Paths are preserved relative to the build root, so a nested entry keeps its folder.
56
+ */
57
+ export function copyNonJsAssets({ buildRoots, bundleDir, }) {
58
+ const copied = [];
59
+ for (const buildRoot of buildRoots) {
60
+ if (!existsSync(buildRoot))
61
+ continue;
62
+ const walk = (dir) => {
63
+ for (const dirent of readdirSync(dir, { withFileTypes: true })) {
64
+ const full = join(dir, dirent.name);
65
+ if (dirent.isDirectory()) {
66
+ if (dirent.name === 'node_modules')
67
+ continue;
68
+ walk(full);
69
+ continue;
70
+ }
71
+ if (!dirent.isFile())
72
+ continue;
73
+ const isDeclaration = /\.d\.(ts|cts|mts)$/.test(dirent.name);
74
+ // Declarations are wanted; other JS is the bundler's job.
75
+ if (!isDeclaration && BUNDLER_HANDLED.test(dirent.name))
76
+ continue;
77
+ const relativePath = relative(buildRoot, full);
78
+ const target = join(bundleDir, relativePath);
79
+ if (existsSync(target))
80
+ continue;
81
+ ensureDirSync(dirname(target));
82
+ cpSync(full, target);
83
+ copied.push(relativePath.split(sep).join('/'));
84
+ }
85
+ };
86
+ walk(buildRoot);
87
+ }
88
+ return copied;
89
+ }
90
+ export function copyRootFiles({ pkgDir, bundleDir, }) {
91
+ const copied = [];
92
+ for (const name of ROOT_FILES_TO_COPY) {
93
+ const source = join(pkgDir, name);
94
+ if (!existsSync(source))
95
+ continue;
96
+ // The bundle gets its own README describing the bundle; keep the original alongside.
97
+ const targetName = /^readme\.md$/i.test(name) ? 'README.original.md' : name;
98
+ cpSync(source, join(bundleDir, targetName));
99
+ copied.push(targetName);
100
+ }
101
+ return copied;
102
+ }
103
+ /**
104
+ * Put a shebang back at byte 0 and make the file executable.
105
+ *
106
+ * Two things conspire against a working bin. `output.banner` is prepended above
107
+ * everything, so it lands before any shebang; and `@rollup/plugin-commonjs` strips the
108
+ * source shebang and re-emits it *inside* the module body, where it is just a comment.
109
+ * Nothing will `npm link` these files either, so the executable bit has to be ours.
110
+ */
111
+ export function fixBinShebang(file) {
112
+ const original = readFileSync(file, 'utf8');
113
+ const withoutShebangs = original
114
+ .split('\n')
115
+ .filter((line) => !line.startsWith('#!'))
116
+ .join('\n');
117
+ writeFileSync(file, `#!/usr/bin/env node\n${withoutShebangs}`);
118
+ chmodSync(file, 0o755);
119
+ }
120
+ /**
121
+ * Hoist a single `"use client"` to byte 0.
122
+ *
123
+ * Per-module directives cannot survive collapsing many modules into one chunk — Rollup
124
+ * says so with `MODULE_LEVEL_DIRECTIVE` and drops them. For a React design system the
125
+ * honest translation is that the whole bundle is a client module, so one directive at
126
+ * the top preserves the meaning that matters to a consumer using Server Components.
127
+ */
128
+ export function hoistUseClient(file) {
129
+ const original = readFileSync(file, 'utf8');
130
+ if (/^['"]use client['"]/.test(original))
131
+ return;
132
+ writeFileSync(file, `'use client';\n${original}`);
133
+ }
134
+ /** Emitted-file lookup for one entry point. */
135
+ function emittedFileFor(entry) {
136
+ return `./${entry.name}.mjs`;
137
+ }
138
+ /**
139
+ * Build the bundle's package.json from scratch.
140
+ *
141
+ * Rewriting rather than patching, because most of the original fields are actively
142
+ * wrong for a bundle: `scripts` may hold a `postinstall` that fails, `imports` maps
143
+ * `#internal` subpaths at files that no longer exist, `sideEffects: false` is a lie once
144
+ * everything is one chunk, and `devDependencies` are noise.
145
+ */
146
+ export function buildBundlePackageJson({ bundleDir, pkgJson, entries, externals, origin, bundlerVersion, hadUseClientDirective, }) {
147
+ const exportsMap = {};
148
+ const binMap = {};
149
+ for (const entry of entries) {
150
+ if (entry.binName) {
151
+ binMap[entry.binName] = emittedFileFor(entry);
152
+ continue;
153
+ }
154
+ // Only advertise `types` when the declaration was actually copied across —
155
+ // pointing at a missing .d.ts breaks a TypeScript consumer louder than omitting it.
156
+ const declaration = `${entry.name}.d.ts`;
157
+ exportsMap[entry.subpath] = {
158
+ ...(existsSync(join(bundleDir, declaration))
159
+ ? { types: `./${declaration}` }
160
+ : {}),
161
+ default: emittedFileFor(entry),
162
+ };
163
+ }
164
+ exportsMap['./package.json'] = './package.json';
165
+ // Only vendored packages are real runtime dependencies of the bundle. Peers stay
166
+ // declared as peers so a consumer's installer still tells them what to provide.
167
+ const dependencies = {};
168
+ for (const external of externals) {
169
+ if (!external.vendored)
170
+ continue;
171
+ dependencies[external.name] = external.version ?? '*';
172
+ }
173
+ const peerDependencies = {};
174
+ for (const [name, range] of Object.entries(pkgJson.peerDependencies ?? {})) {
175
+ if (externals.some((external) => external.name === name)) {
176
+ peerDependencies[name] = range;
177
+ }
178
+ }
179
+ // A framework held external despite being a regular dependency still has to be
180
+ // declared, or the consumer has no way to know it is required.
181
+ for (const external of externals) {
182
+ if (external.reason !== 'framework' || external.vendored)
183
+ continue;
184
+ peerDependencies[external.name] =
185
+ pkgJson.dependencies?.[external.name] ?? external.version ?? '*';
186
+ }
187
+ const rootEntry = entries.find((entry) => entry.subpath === '.' && !entry.binName);
188
+ return {
189
+ name: pkgJson.name,
190
+ version: pkgJson.version,
191
+ // Always ESM — the bundler only emits ESM, whatever the source was.
192
+ type: 'module',
193
+ ...(pkgJson.license ? { license: pkgJson.license } : {}),
194
+ ...(rootEntry ? { main: emittedFileFor(rootEntry) } : {}),
195
+ exports: exportsMap,
196
+ ...(Object.keys(binMap).length > 0 ? { bin: binMap } : {}),
197
+ ...(Object.keys(dependencies).length > 0 ? { dependencies } : {}),
198
+ ...(Object.keys(peerDependencies).length > 0 ? { peerDependencies } : {}),
199
+ knapsack: {
200
+ bundledFrom: {
201
+ origin: origin.kind,
202
+ detail: origin.detail,
203
+ bundledAt: new Date().toISOString(),
204
+ bundlerVersion,
205
+ hadUseClientDirective,
206
+ },
207
+ note: 'Generated by @knapsack/package-bundler. Dependencies are inlined; see bundle-metadata.json in the parent folder for full provenance.',
208
+ },
209
+ };
210
+ }
211
+ export function writeBundlePackageJson({ bundleDir, contents, }) {
212
+ writeFileSync(join(bundleDir, 'package.json'), `${JSON.stringify(contents, null, 2)}\n`);
213
+ }
214
+ //# sourceMappingURL=write-output.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write-output.js","sourceRoot":"","sources":["../src/write-output.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,WAAW,EACX,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAIrD,uEAAuE;AACvE,MAAM,kBAAkB,GAAsB;IAC5C,SAAS;IACT,YAAY;IACZ,aAAa;IACb,WAAW;IACX,WAAW;IACX,cAAc;CACf,CAAC;AAEF,6DAA6D;AAC7D,MAAM,eAAe,GAAG,gCAAgC,CAAC;AAEzD;;;;;;;;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AC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzE,QAAQ,EAAE;YACR,WAAW,EAAE;gBACX,MAAM,EAAE,MAAM,CAAC,IAAI;gBACnB,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;gBACnC,cAAc;gBACd,qBAAqB;aACtB;YACD,IAAI,EAAE,sIAAsI;SAC7I;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,EACrC,SAAS,EACT,QAAQ,GAIT;IACC,aAAa,CACX,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EAC/B,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CACzC,CAAC;AACJ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@knapsack/package-bundler",
3
+ "description": "Bundle an already-built npm package into a self-contained copy with its dependencies inlined",
4
+ "version": "4.101.0--canary.8110.15bba7c.0",
5
+ "bin": {
6
+ "knapsack-package-bundler": "./dist/cli.js"
7
+ },
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./package": "./package.json",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "sideEffects": false,
18
+ "scripts": {
19
+ "build": "tsc",
20
+ "clean": "rm -rf ./dist",
21
+ "lint": "eslint ./src",
22
+ "start": "tsc --watch",
23
+ "test": "tsc -p tsconfig.test.json && vitest run"
24
+ },
25
+ "author": "Knapsack (https://www.knapsack.cloud)",
26
+ "dependencies": {
27
+ "@clack/prompts": "^0.11.0",
28
+ "@knapsack/file-utils": "4.101.0--canary.8110.15bba7c.0",
29
+ "@knapsack/logger": "4.101.0--canary.8110.15bba7c.0",
30
+ "commander": "^14.0.3",
31
+ "picocolors": "^1.1.1",
32
+ "vite": "^7.3.2"
33
+ },
34
+ "devDependencies": {
35
+ "@knapsack/eslint-config-starter": "4.101.0--canary.8110.15bba7c.0",
36
+ "@knapsack/prettier-config": "4.101.0--canary.8110.15bba7c.0",
37
+ "@knapsack/typescript-config-starter": "4.101.0--canary.8110.15bba7c.0",
38
+ "@types/node": "^24.13.2",
39
+ "eslint": "^9.20.0",
40
+ "typescript": "^6.0.3",
41
+ "vitest": "^4.1.11"
42
+ },
43
+ "license": "GPL-2.0-or-later",
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "repository": {
48
+ "url": "https://github.com/knapsack-labs/app-monorepo",
49
+ "directory": "tools/package-bundler",
50
+ "type": "git"
51
+ },
52
+ "gitHead": "15bba7cdb0b444d262e18e04f1d23956645835e7"
53
+ }
package/readme.md ADDED
@@ -0,0 +1,127 @@
1
+ # `@knapsack/package-bundler`
2
+
3
+ Bundles an already-built npm package into a self-contained copy with its runtime
4
+ dependencies inlined, so it runs where `node_modules` is absent.
5
+
6
+ Built so customers can send us their design system for evals without us needing registry
7
+ credentials or having to resolve their dependency tree. They run one command; we get a
8
+ folder that works.
9
+
10
+ ```bash
11
+ npx @knapsack/package-bundler # current directory
12
+ npx @knapsack/package-bundler ./packages/design-system # a specific package
13
+ npx @knapsack/package-bundler @acme/ds@2.4.1 # straight from npm
14
+ ```
15
+
16
+ Four docs, four audiences — check you're reading the right one:
17
+
18
+ | Doc | For |
19
+ | --- | --- |
20
+ | this file | engineers working *on* the bundler |
21
+ | `INSTRUCTIONS-FOR-CUSTOMERS.md` | a customer, sendable as-is |
22
+ | `--help` | someone with a terminal already open |
23
+ | `README.md` inside each output folder | whoever receives a bundle |
24
+
25
+ ## How it works
26
+
27
+ Vite's programmatic `build()` in library mode with `ssr.noExternal: true`, which inverts
28
+ Vite's usual behaviour so dependencies get inlined rather than externalized. Output is
29
+ always ESM. Nothing is minified.
30
+
31
+ `src/bundle.ts` carries a comment on every option that overrides a Vite default. Read
32
+ those before changing any of them — **each one guards against a Vite default that
33
+ produces a broken bundle without failing the build.** In particular:
34
+
35
+ - `ssrEmitAssets: true` — without it, every CSS file and asset is silently deleted.
36
+ - `commonjsOptions.include: [/.*/]` — the default `[/node_modules/]` misses workspace
37
+ packages, since pnpm resolves those to real paths outside `node_modules`.
38
+ - `ignoreDynamicRequires: true` — without it, every dynamic `require()` in every bundled
39
+ dependency is rewritten into a stub that *throws at runtime*.
40
+
41
+ ## The thing to understand before changing anything
42
+
43
+ **Vite silently externalizes bare imports it cannot resolve in SSR mode.** No warning,
44
+ no error; the build reports success. For a bundle meant to run without `node_modules`
45
+ that turns "I couldn't inline this" into an artifact that fails on someone else's
46
+ machine.
47
+
48
+ Two pieces of the design exist only because of this:
49
+
50
+ 1. `src/bundle.ts` has a fallback resolver plugin that catches what Vite gives up on and
51
+ resolves it with Node's own algorithm. It delegates to Vite first, so Vite keeps
52
+ ownership of everything it handles correctly.
53
+ 2. `src/verify-bundle.ts` runs after every build and fails the run if anything leaked.
54
+ It classifies each remaining import as a Node builtin, a declared peer, a vendored
55
+ package, or a leak.
56
+
57
+ The import list comes from Rollup's own `generateBundle` hook, **not** from scanning the
58
+ emitted text. Text scanning cannot tell an import from a comment that looks like one, and
59
+ real dependencies are full of `@import {Node} from 'unist'` JSDoc and `@example` blocks —
60
+ which produced false failures on bundles that were in fact correct.
61
+
62
+ ## Layout
63
+
64
+ | File | Role |
65
+ | --- | --- |
66
+ | `src/cli.ts` | commander shell; argument parsing and process lifecycle only |
67
+ | `src/run.ts` | the pipeline, linear and readable top to bottom |
68
+ | `src/bundle.ts` | the Vite build, the fallback resolver, hazard detection |
69
+ | `src/verify-bundle.ts` | the self-containment gate |
70
+ | `src/resolve-source.ts` | directory or npm spec → a package directory |
71
+ | `src/resolve-entries.ts` | `exports`/`main`/`bin` → entry points, wildcards expanded |
72
+ | `src/vendor.ts` | copies packages that cannot be inlined into the output |
73
+ | `src/write-output.ts` | rewritten package.json, shebangs, `"use client"`, assets |
74
+ | `src/metadata.ts` | provenance and the bundle's own README |
75
+ | `src/errors.ts` | every failure code and its recovery steps |
76
+ | `src/prompts.ts` | interactive flow plus the validators the flag path shares |
77
+ | `src/log.ts` | stderr-bound logging, Datadog delivery |
78
+
79
+ ## Errors
80
+
81
+ `src/errors.ts` is the single source of truth. Each code carries its recovery steps, and
82
+ those steps are what `--help` prints and what the terminal shows on failure. A test
83
+ asserts `--help` mentions every code, so the surfaces cannot drift.
84
+
85
+ Adding a code means adding its recovery steps in the same place; the test will tell you
86
+ if you forget.
87
+
88
+ ## Telemetry
89
+
90
+ Errors report to Datadog so we hear about failures customers hit. Because this runs on
91
+ other people's machines, delivery uses a Datadog **client** token (the browser/RUM
92
+ credential, designed to be publicly distributed) rather than a private API key — a
93
+ published package cannot carry a private key, and with no key the logger no-ops, which
94
+ would mean never seeing the failures that matter most.
95
+
96
+ The token lives in one constant in `src/log.ts`, overridable via
97
+ `KS_DATADOG_CLIENT_TOKEN`. While it holds a `REPLACE_WITH_` placeholder, telemetry
98
+ no-ops and nothing else changes. A private key in `DATADOG_API_KEY__APP_API` takes
99
+ precedence when present, so staff and CI runs get full fidelity.
100
+
101
+ Users opt out with `--no-telemetry`, `KS_TELEMETRY=no`, or `DO_NOT_TRACK=1`.
102
+
103
+ ## Tests
104
+
105
+ ```bash
106
+ pnpm run --filter package-bundler test
107
+ ```
108
+
109
+ Unit tests cover the pure logic. The integration tests in `src/integration.test.ts` run
110
+ real builds against the fixtures defined in that file, one per hazard — a CJS dependency,
111
+ an unresolvable import, wildcard exports, an unbuilt package, a bin with a shebang,
112
+ `"use client"`, a peer dependency. Each pins down a failure mode that a real bundle
113
+ actually hit, where the build reported success and the artifact was broken.
114
+
115
+ Adding a fixture is the right move whenever you find a new way for a bundle to be
116
+ silently wrong.
117
+
118
+ ## Known limits
119
+
120
+ - **Compile-time CSS** (vanilla-extract, Linaria, Compiled) does not survive
121
+ re-bundling: the runtime half ends up without its build-time half. The tool warns; it
122
+ cannot fix it. Ship the package's prebuilt CSS separately.
123
+ - **Native bindings, dynamic `require`, worker entry files** cannot be inlined by any
124
+ bundler. These are detected and get vendored — copied in as real files — rather than
125
+ bundled. `--strategy vendor` does this for everything.
126
+ - **Peer dependencies stay out** by default, so a bundle is self-contained *except* for
127
+ its peers. The output README says which, by name and version.
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "@knapsack/typescript-config-starter/tsconfig.build.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "outDir": "./dist"
6
+ },
7
+ "include": ["./src"],
8
+ "exclude": ["src/**/*.test.ts"]
9
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ // Typechecks *.test.ts, which the build tsconfig excludes from emit, so tests keep
3
+ // type coverage while staying out of dist. Run via the package `test` script.
4
+ "extends": "./tsconfig.json",
5
+ "include": ["src"],
6
+ "exclude": [],
7
+ "compilerOptions": {
8
+ "noEmit": true,
9
+ "emitDeclarationOnly": false,
10
+ "declaration": false,
11
+ "declarationMap": false
12
+ }
13
+ }
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ include: ['src/**/*.test.ts'],
6
+ // Integration tests run real Vite builds against generated fixture packages.
7
+ testTimeout: 120_000,
8
+ },
9
+ });