@react-datatable/cli 1.2.1

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.
@@ -0,0 +1,458 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
4
+ import { spawnSync } from "node:child_process"
5
+ import { tmpdir } from "node:os"
6
+ import path from "node:path"
7
+
8
+ const CORE_DEPENDENCIES = [
9
+ "@dnd-kit/core",
10
+ "@dnd-kit/modifiers",
11
+ "@dnd-kit/sortable",
12
+ "@dnd-kit/utilities",
13
+ "@phosphor-icons/react",
14
+ "@radix-ui/react-alert-dialog",
15
+ "@radix-ui/react-checkbox",
16
+ "@radix-ui/react-dialog",
17
+ "@radix-ui/react-dropdown-menu",
18
+ "@radix-ui/react-label",
19
+ "@radix-ui/react-popover",
20
+ "@radix-ui/react-slot",
21
+ "@radix-ui/react-switch",
22
+ "@radix-ui/react-tooltip",
23
+ "@tanstack/react-table",
24
+ "class-variance-authority",
25
+ "clsx",
26
+ "cmdk",
27
+ "date-fns",
28
+ "react-day-picker",
29
+ "tailwind-merge",
30
+ "zod",
31
+ "zustand",
32
+ ]
33
+
34
+ const VALID_FRAMEWORKS = new Set([
35
+ "vite",
36
+ "next-app",
37
+ "next-pages",
38
+ "tanstack-start",
39
+ "react-router",
40
+ "astro",
41
+ "laravel",
42
+ "manual",
43
+ "generic",
44
+ ])
45
+ const VALID_PERSISTENCE = new Set(["local-storage", "session-storage"])
46
+ const DEFAULT_MANIFEST_URL = "https://react-datatable.com/api/install/manifest"
47
+
48
+ main().catch((error) => {
49
+ console.error(error instanceof Error ? error.message : String(error))
50
+ process.exit(1)
51
+ })
52
+
53
+ async function main() {
54
+ const [command, ...args] = process.argv.slice(2)
55
+
56
+ if (!command || command === "--help" || command === "-h") {
57
+ printHelp()
58
+ return
59
+ }
60
+
61
+ if (command !== "install") {
62
+ throw new Error(`Unknown command "${command}". Expected "install".`)
63
+ }
64
+
65
+ const options = parseInstallArgs(args)
66
+ if (!options.token) {
67
+ throw new Error("Missing required --token.")
68
+ }
69
+
70
+ const cwd = process.cwd()
71
+ const packageJson = await readPackageJson(cwd)
72
+ const framework = options.framework ?? (await detectFramework(cwd, packageJson))
73
+ const packageManager = await detectPackageManager(cwd)
74
+ const modules = buildModulePlan(options)
75
+
76
+ const plan = {
77
+ framework,
78
+ packageManager,
79
+ target: options.target,
80
+ modules,
81
+ dependencies: CORE_DEPENDENCIES,
82
+ persistence: options.persistence,
83
+ withUrlSync: options.withUrlSync,
84
+ withViews: options.withViews,
85
+ withOnlineExample: options.withOnlineExample,
86
+ noInstall: options.noInstall,
87
+ manifestUrl: options.manifestUrl,
88
+ }
89
+
90
+ if (options.dryRun) {
91
+ printDryRunPlan(plan)
92
+ return
93
+ }
94
+
95
+ await installDatatable(cwd, plan, options.token)
96
+ }
97
+
98
+ function parseInstallArgs(args) {
99
+ const options = {
100
+ token: "",
101
+ dryRun: false,
102
+ framework: undefined,
103
+ target: "src/react-datatable",
104
+ withUrlSync: false,
105
+ withViews: false,
106
+ withOnlineExample: false,
107
+ persistence: "local-storage",
108
+ noInstall: false,
109
+ manifestUrl: process.env.REACT_DATATABLE_INSTALL_MANIFEST_URL ?? DEFAULT_MANIFEST_URL,
110
+ }
111
+
112
+ for (let index = 0; index < args.length; index += 1) {
113
+ const arg = args[index]
114
+
115
+ switch (arg) {
116
+ case "--token":
117
+ options.token = readFlagValue(args, ++index, "--token")
118
+ break
119
+ case "--dry-run":
120
+ options.dryRun = true
121
+ break
122
+ case "--framework": {
123
+ const framework = readFlagValue(args, ++index, "--framework")
124
+ if (!VALID_FRAMEWORKS.has(framework)) {
125
+ throw new Error(`Invalid --framework "${framework}". Expected one of: ${Array.from(VALID_FRAMEWORKS).join(", ")}.`)
126
+ }
127
+ options.framework = framework
128
+ break
129
+ }
130
+ case "--target":
131
+ options.target = readFlagValue(args, ++index, "--target")
132
+ break
133
+ case "--with-url-sync":
134
+ options.withUrlSync = true
135
+ break
136
+ case "--with-views":
137
+ options.withViews = true
138
+ break
139
+ case "--with-online-example":
140
+ options.withOnlineExample = true
141
+ break
142
+ case "--persistence": {
143
+ const persistence = readFlagValue(args, ++index, "--persistence")
144
+ if (!VALID_PERSISTENCE.has(persistence)) {
145
+ throw new Error(`Invalid --persistence "${persistence}". Expected local-storage or session-storage.`)
146
+ }
147
+ options.persistence = persistence
148
+ break
149
+ }
150
+ case "--no-install":
151
+ options.noInstall = true
152
+ break
153
+ case "--manifest-url":
154
+ options.manifestUrl = readFlagValue(args, ++index, "--manifest-url")
155
+ break
156
+ case "--help":
157
+ case "-h":
158
+ printHelp()
159
+ process.exit(0)
160
+ break
161
+ default:
162
+ throw new Error(`Unknown option "${arg}".`)
163
+ }
164
+ }
165
+
166
+ return options
167
+ }
168
+
169
+ function readFlagValue(args, index, flag) {
170
+ const value = args[index]
171
+ if (!value || value.startsWith("--")) {
172
+ throw new Error(`Missing value for ${flag}.`)
173
+ }
174
+ return value
175
+ }
176
+
177
+ async function readPackageJson(cwd) {
178
+ try {
179
+ const source = await readFile(path.join(cwd, "package.json"), "utf8")
180
+ return JSON.parse(source)
181
+ } catch {
182
+ return {}
183
+ }
184
+ }
185
+
186
+ async function detectFramework(cwd, packageJson) {
187
+ const dependencies = {
188
+ ...(packageJson.dependencies ?? {}),
189
+ ...(packageJson.devDependencies ?? {}),
190
+ }
191
+
192
+ if (dependencies["@tanstack/react-start"]) {
193
+ return "tanstack-start"
194
+ }
195
+
196
+ if (dependencies["@react-router/dev"] || dependencies["react-router"]) {
197
+ return "react-router"
198
+ }
199
+
200
+ if (dependencies.astro) {
201
+ return "astro"
202
+ }
203
+
204
+ if (dependencies["laravel-vite-plugin"] || dependencies["@laravel/vite-plugin"]) {
205
+ return "laravel"
206
+ }
207
+
208
+ if (dependencies.next) {
209
+ if (await pathExists(path.join(cwd, "pages"))) {
210
+ return "next-pages"
211
+ }
212
+
213
+ return "next-app"
214
+ }
215
+
216
+ if (dependencies.vite || dependencies["@vitejs/plugin-react"]) {
217
+ return "vite"
218
+ }
219
+
220
+ return "generic"
221
+ }
222
+
223
+ async function detectPackageManager(cwd) {
224
+ const lockfiles = [
225
+ ["pnpm-lock.yaml", "pnpm"],
226
+ ["yarn.lock", "yarn"],
227
+ ["bun.lockb", "bun"],
228
+ ["bun.lock", "bun"],
229
+ ["package-lock.json", "npm"],
230
+ ["npm-shrinkwrap.json", "npm"],
231
+ ]
232
+
233
+ for (const [lockfile, packageManager] of lockfiles) {
234
+ if (await pathExists(path.join(cwd, lockfile))) {
235
+ return packageManager
236
+ }
237
+ }
238
+
239
+ return "npm"
240
+ }
241
+
242
+ async function pathExists(filePath) {
243
+ try {
244
+ await access(filePath)
245
+ return true
246
+ } catch {
247
+ return false
248
+ }
249
+ }
250
+
251
+ function buildModulePlan(options) {
252
+ const modules = ["core"]
253
+
254
+ if (options.withOnlineExample) {
255
+ modules.push("server")
256
+ }
257
+
258
+ if (options.withViews || options.withOnlineExample || options.withUrlSync) {
259
+ modules.push("examples")
260
+ }
261
+
262
+ return modules
263
+ }
264
+
265
+ function printDryRunPlan(plan) {
266
+ console.log("react-datatable install dry-run")
267
+ console.log("")
268
+ console.log(`Framework: ${plan.framework}`)
269
+ console.log(`Package manager: ${plan.packageManager}`)
270
+ console.log(`Target: ${plan.target}`)
271
+ console.log(`Modules: ${plan.modules.join(", ")}`)
272
+ console.log(`Manifest: ${plan.manifestUrl}`)
273
+ console.log(`Persistence default: ${plan.persistence}`)
274
+ console.log(`URL sync example: ${plan.withUrlSync ? "included" : "not included"}`)
275
+ console.log(`Saved views example: ${plan.withViews ? "included" : "not included"}`)
276
+ console.log(`Online example: ${plan.withOnlineExample ? "included" : "not included"}`)
277
+ console.log("")
278
+ console.log("Would copy licensed source archive(s) after token validation.")
279
+ console.log(`Would install core dependencies: ${plan.dependencies.join(" ")}`)
280
+ console.log("Would add Tailwind @source for the target when a safe global CSS file is detected.")
281
+ console.log("No app-level providers will be modified.")
282
+
283
+ if (plan.noInstall) {
284
+ console.log("Dependency installation is disabled by --no-install.")
285
+ }
286
+ }
287
+
288
+ async function installDatatable(cwd, plan, token) {
289
+ const manifest = await fetchInstallManifest(plan.manifestUrl, token)
290
+ const installRoot = path.resolve(cwd)
291
+ const targetPath = path.resolve(installRoot, plan.target)
292
+ const parentDir = path.dirname(targetPath)
293
+ const tempDir = await mkdtemp(path.join(tmpdir(), "react-datatable-install-"))
294
+
295
+ try {
296
+ await mkdir(parentDir, { recursive: true })
297
+
298
+ for (const moduleName of plan.modules) {
299
+ const moduleManifest = manifest.modules?.[moduleName]
300
+ if (!moduleManifest?.archiveUrl) {
301
+ throw new Error(`Manifest did not include the requested "${moduleName}" module.`)
302
+ }
303
+
304
+ const archivePath = path.join(tempDir, `${moduleName}.tgz`)
305
+ await downloadFile(moduleManifest.archiveUrl, archivePath)
306
+ await extractArchive(archivePath, parentDir)
307
+ }
308
+
309
+ if (manifest.license?.text) {
310
+ await writeFile(path.join(targetPath, "LICENSE.react-datatable.txt"), manifest.license.text)
311
+ }
312
+
313
+ await addTailwindSourceIfPossible(installRoot, targetPath)
314
+
315
+ if (!plan.noInstall) {
316
+ installDependencies(plan.packageManager, manifest.modules.core?.dependencies ?? CORE_DEPENDENCIES, cwd)
317
+ }
318
+
319
+ console.log("react-datatable installed")
320
+ console.log(`Target: ${path.relative(cwd, targetPath) || "."}`)
321
+ console.log(`Modules: ${plan.modules.join(", ")}`)
322
+ if (plan.noInstall) {
323
+ console.log("Dependency installation skipped by --no-install.")
324
+ }
325
+ } finally {
326
+ await rm(tempDir, { recursive: true, force: true })
327
+ }
328
+ }
329
+
330
+ async function fetchInstallManifest(manifestUrl, token) {
331
+ const response = await fetch(manifestUrl, {
332
+ method: "POST",
333
+ headers: {
334
+ authorization: `Bearer ${token}`,
335
+ "content-type": "application/json",
336
+ },
337
+ body: JSON.stringify({ token }),
338
+ })
339
+
340
+ if (!response.ok) {
341
+ throw new Error(`Install manifest request failed: ${response.status}`)
342
+ }
343
+
344
+ const payload = await response.json()
345
+ if (!payload?.ok || !payload.manifest) {
346
+ throw new Error("Install manifest response was invalid.")
347
+ }
348
+
349
+ return payload.manifest
350
+ }
351
+
352
+ async function downloadFile(url, destination) {
353
+ const response = await fetch(url)
354
+ if (!response.ok) {
355
+ throw new Error(`Archive download failed: ${response.status} ${url}`)
356
+ }
357
+
358
+ const buffer = Buffer.from(await response.arrayBuffer())
359
+ await writeFile(destination, buffer)
360
+ }
361
+
362
+ async function extractArchive(archivePath, destinationDir) {
363
+ const result = spawnSync("tar", ["-xzf", archivePath, "-C", destinationDir], {
364
+ encoding: "utf8",
365
+ })
366
+
367
+ if (result.status !== 0) {
368
+ throw new Error(result.stderr || `Failed to extract ${archivePath}`)
369
+ }
370
+ }
371
+
372
+ async function addTailwindSourceIfPossible(root, targetPath) {
373
+ const cssPath = await findTailwindCssFile(root)
374
+ if (!cssPath) {
375
+ return
376
+ }
377
+
378
+ const source = await readFile(cssPath, "utf8")
379
+ const relativeTarget = toPosixRelative(path.dirname(cssPath), targetPath)
380
+ const directive = `@source "${relativeTarget}";`
381
+
382
+ if (source.includes(directive) || source.includes(relativeTarget)) {
383
+ return
384
+ }
385
+
386
+ await writeFile(cssPath, `${source.trimEnd()}\n${directive}\n`)
387
+ }
388
+
389
+ async function findTailwindCssFile(root) {
390
+ const candidates = [
391
+ "src/index.css",
392
+ "src/main.css",
393
+ "src/globals.css",
394
+ "src/app/globals.css",
395
+ "src/styles.css",
396
+ "src/styles/global.css",
397
+ "app/globals.css",
398
+ "app/app.css",
399
+ "resources/css/app.css",
400
+ ]
401
+
402
+ for (const candidate of candidates) {
403
+ const filePath = path.join(root, candidate)
404
+ if (await pathExists(filePath)) {
405
+ const source = await readFile(filePath, "utf8")
406
+ if (!containsTailwindDirective(source)) {
407
+ continue
408
+ }
409
+ return filePath
410
+ }
411
+ }
412
+
413
+ return null
414
+ }
415
+
416
+ function containsTailwindDirective(source) {
417
+ return /@import\s+["']tailwindcss["']/.test(source) || /@tailwind\s+/.test(source) || /@source\s+/.test(source)
418
+ }
419
+
420
+ function toPosixRelative(fromDir, toPath) {
421
+ const relativePath = path.relative(fromDir, toPath).split(path.sep).join("/")
422
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`
423
+ }
424
+
425
+ function installDependencies(packageManager, dependencies, cwd) {
426
+ if (dependencies.length === 0) {
427
+ return
428
+ }
429
+
430
+ const commands = {
431
+ npm: ["npm", ["install", ...dependencies]],
432
+ pnpm: ["pnpm", ["add", ...dependencies]],
433
+ yarn: ["yarn", ["add", ...dependencies]],
434
+ bun: ["bun", ["add", ...dependencies]],
435
+ }
436
+ const [command, args] = commands[packageManager] ?? commands.npm
437
+ const result = spawnSync(command, args, { cwd, stdio: "inherit" })
438
+
439
+ if (result.status !== 0) {
440
+ throw new Error(`Dependency installation failed with ${command}. Re-run with --no-install to copy source only.`)
441
+ }
442
+ }
443
+
444
+ function printHelp() {
445
+ console.log(`Usage:
446
+ react-datatable install --token <license-token> [options]
447
+
448
+ Options:
449
+ --dry-run
450
+ --framework vite | next-app | next-pages | tanstack-start | react-router | astro | laravel | manual | generic
451
+ --target src/react-datatable
452
+ --manifest-url https://react-datatable.com/api/install/manifest
453
+ --with-url-sync
454
+ --with-views
455
+ --with-online-example
456
+ --persistence local-storage | session-storage
457
+ --no-install`)
458
+ }
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@react-datatable/cli",
3
+ "version": "1.2.1",
4
+ "description": "Licensed source installer for react-datatable.",
5
+ "type": "module",
6
+ "bin": {
7
+ "react-datatable": "./bin/react-datatable.mjs"
8
+ },
9
+ "files": [
10
+ "bin"
11
+ ],
12
+ "license": "SEE LICENSE IN LICENSE.md"
13
+ }