@lxpack/cli 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,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 LXPack Contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { Command } from 'commander';
2
+ import { z } from 'zod';
3
+
4
+ declare const lxpackConfigSchema: z.ZodObject<{
5
+ exports: z.ZodOptional<z.ZodObject<{
6
+ defaultTarget: z.ZodOptional<z.ZodEnum<["scorm12", "standalone"]>>;
7
+ }, "strip", z.ZodTypeAny, {
8
+ defaultTarget?: "scorm12" | "standalone" | undefined;
9
+ }, {
10
+ defaultTarget?: "scorm12" | "standalone" | undefined;
11
+ }>>;
12
+ output: z.ZodOptional<z.ZodObject<{
13
+ dir: z.ZodOptional<z.ZodString>;
14
+ }, "strip", z.ZodTypeAny, {
15
+ dir?: string | undefined;
16
+ }, {
17
+ dir?: string | undefined;
18
+ }>>;
19
+ }, "strict", z.ZodTypeAny, {
20
+ exports?: {
21
+ defaultTarget?: "scorm12" | "standalone" | undefined;
22
+ } | undefined;
23
+ output?: {
24
+ dir?: string | undefined;
25
+ } | undefined;
26
+ }, {
27
+ exports?: {
28
+ defaultTarget?: "scorm12" | "standalone" | undefined;
29
+ } | undefined;
30
+ output?: {
31
+ dir?: string | undefined;
32
+ } | undefined;
33
+ }>;
34
+ type LxpackConfig = z.infer<typeof lxpackConfigSchema>;
35
+
36
+ declare function createCliProgram(): Command;
37
+ declare function runCli(argv?: string[]): Promise<void>;
38
+ declare function printCliError(err: unknown): void;
39
+
40
+ export { type LxpackConfig, createCliProgram, printCliError, runCli };
package/dist/cli.js ADDED
@@ -0,0 +1,527 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { Command } from "commander";
5
+ import pc5 from "picocolors";
6
+
7
+ // src/commands/init.ts
8
+ import { existsSync as existsSync2 } from "fs";
9
+ import { mkdir, writeFile } from "fs/promises";
10
+ import { join as join2 } from "path";
11
+ import pc from "picocolors";
12
+
13
+ // src/utils.ts
14
+ import { existsSync } from "fs";
15
+ import { readFile } from "fs/promises";
16
+ import { createRequire } from "module";
17
+ import { dirname, join, resolve } from "path";
18
+ import { stringify as stringifyYaml } from "yaml";
19
+ import { z } from "zod";
20
+ import { loadManifest, formatErrorMessage } from "@lxpack/validators";
21
+ var require2 = createRequire(import.meta.url);
22
+ function findCourseDir(startDir = process.cwd()) {
23
+ let dir = resolve(startDir);
24
+ while (dir !== dirname(dir)) {
25
+ if (existsSync(join(dir, "course.yaml"))) {
26
+ return dir;
27
+ }
28
+ dir = dirname(dir);
29
+ }
30
+ throw new Error(
31
+ "No course.yaml found. Run from a course directory or use lxpack init."
32
+ );
33
+ }
34
+ async function loadCourseManifest(courseDir) {
35
+ const loaded = await loadManifest(courseDir);
36
+ if (Array.isArray(loaded)) {
37
+ throw new Error(loaded.map((i) => i.message).join("; "));
38
+ }
39
+ return loaded.manifest;
40
+ }
41
+ function getRuntimeAssetsDir() {
42
+ return dirname(require2.resolve("@lxpack/runtime/client"));
43
+ }
44
+ function getEmbeddedStyles() {
45
+ return `:root { --lxpack-bg: #0f1419; } body { margin: 0; }`;
46
+ }
47
+ async function loadRuntimeStyles(assetsDir) {
48
+ try {
49
+ return await readFile(join(assetsDir, "styles.css"), "utf-8");
50
+ } catch {
51
+ return getEmbeddedStyles();
52
+ }
53
+ }
54
+ async function readRuntimeBundle(assetsDir = getRuntimeAssetsDir()) {
55
+ const clientPath = join(assetsDir, "client.js");
56
+ if (!existsSync(clientPath)) {
57
+ throw new Error(
58
+ "Runtime bundle not found. Run `pnpm build` from the LXPack repo root, or reinstall @lxpack/runtime."
59
+ );
60
+ }
61
+ const [clientJs, css] = await Promise.all([
62
+ readFile(clientPath, "utf-8"),
63
+ loadRuntimeStyles(assetsDir)
64
+ ]);
65
+ if (clientJs.includes('from "./runtime.js"')) {
66
+ throw new Error(
67
+ "Runtime client bundle is not self-contained. Rebuild @lxpack/runtime with `pnpm build`."
68
+ );
69
+ }
70
+ return { clientJs, css };
71
+ }
72
+ var lxpackConfigSchema = z.object({
73
+ exports: z.object({
74
+ defaultTarget: z.enum(["scorm12", "standalone"]).optional()
75
+ }).optional(),
76
+ output: z.object({
77
+ dir: z.string().optional()
78
+ }).optional()
79
+ }).strict();
80
+ async function loadLxpackConfig(courseDir) {
81
+ const configPath = join(courseDir, "lxpack.config.json");
82
+ if (!existsSync(configPath)) return null;
83
+ try {
84
+ const content = await readFile(configPath, "utf-8");
85
+ const raw = JSON.parse(content);
86
+ const parsed = lxpackConfigSchema.safeParse(raw);
87
+ if (!parsed.success) {
88
+ throw new Error(
89
+ parsed.error.issues.map((i) => i.message).join("; ")
90
+ );
91
+ }
92
+ return parsed.data;
93
+ } catch (err) {
94
+ throw new Error(
95
+ `Failed to load lxpack.config.json: ${formatErrorMessage(err)}`
96
+ );
97
+ }
98
+ }
99
+ function escapeHtml(text) {
100
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
101
+ }
102
+ function formatCourseTitleForYaml(title) {
103
+ const doc = { title, version: "1.0.0" };
104
+ const yaml = stringifyYaml(doc);
105
+ const titleLine = yaml.split("\n").find((l) => l.startsWith("title:"));
106
+ if (!titleLine) {
107
+ return JSON.stringify(title);
108
+ }
109
+ return titleLine.replace(/^title:\s*/, "");
110
+ }
111
+ function getCliVersion() {
112
+ const pkg = require2("../package.json");
113
+ return pkg.version;
114
+ }
115
+
116
+ // src/commands/init.ts
117
+ var COURSE_YAML_TEMPLATE = `title: {{title}}
118
+ version: 1.0.0
119
+ description: An LXPack learning experience
120
+
121
+ runtime:
122
+ theme: modern
123
+
124
+ tracking:
125
+ completion:
126
+ threshold: 0.9
127
+
128
+ lessons:
129
+ - id: welcome
130
+ title: Welcome
131
+ type: markdown
132
+ file: lessons/welcome.md
133
+
134
+ - id: phishing-lab
135
+ title: Phishing Lab
136
+ type: html
137
+ path: interactions/phishing-lab
138
+
139
+ assessments:
140
+ - id: final_quiz
141
+ file: assessments/final.yaml
142
+ `;
143
+ var WELCOME_MD = `# Welcome
144
+
145
+ Welcome to your LXPack course.
146
+
147
+ ## What you'll learn
148
+
149
+ - How to structure AI-native learning experiences
150
+ - How to build HTML interactions
151
+ - How to export SCORM packages for your LMS
152
+
153
+ ## Getting started
154
+
155
+ Use the navigation to move between lessons. Mark each lesson complete when finished.
156
+ `;
157
+ var PHISHING_HTML = `<!DOCTYPE html>
158
+ <html lang="en">
159
+ <head>
160
+ <meta charset="UTF-8">
161
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
162
+ <title>Phishing Lab</title>
163
+ <style>
164
+ body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 600px; margin: 0 auto; }
165
+ .email { border: 1px solid #ccc; padding: 1rem; border-radius: 8px; cursor: pointer; }
166
+ .email:hover { background: #f0f4ff; }
167
+ .result { margin-top: 1rem; padding: 1rem; border-radius: 8px; display: none; }
168
+ .result.show { display: block; }
169
+ .safe { background: #dcfce7; color: #166534; }
170
+ .danger { background: #fee2e2; color: #991b1b; }
171
+ </style>
172
+ </head>
173
+ <body>
174
+ <h1>Phishing Detection Lab</h1>
175
+ <p>Click the suspicious email below to report it.</p>
176
+ <div class="email" id="phishing-email" role="button" tabindex="0" aria-label="Suspicious email from unknown sender">
177
+ <strong>From:</strong> security@paypa1-verify.com<br>
178
+ <strong>Subject:</strong> URGENT: Your account will be suspended<br>
179
+ <p>Click here immediately to verify your identity...</p>
180
+ </div>
181
+ <div class="result" id="result"></div>
182
+ <script>
183
+ const email = document.getElementById('phishing-email');
184
+ const result = document.getElementById('result');
185
+ email.addEventListener('click', () => {
186
+ result.className = 'result show danger';
187
+ result.textContent = 'Correct! This is a phishing attempt. Look for misspelled domains and urgency tactics.';
188
+ if (window.parent.lxpack) {
189
+ window.parent.lxpack.track({ type: 'interaction', id: 'phishing_detected' });
190
+ }
191
+ });
192
+ email.addEventListener('keydown', (e) => {
193
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); email.click(); }
194
+ });
195
+ </script>
196
+ </body>
197
+ </html>
198
+ `;
199
+ var FINAL_ASSESSMENT = `id: final_quiz
200
+ title: Final Quiz
201
+ passingScore: 0.7
202
+ questions:
203
+ - id: q1
204
+ prompt: What is a common sign of a phishing email?
205
+ choices:
206
+ - id: a
207
+ text: Urgent language demanding immediate action
208
+ correct: true
209
+ - id: b
210
+ text: A message from your company's IT department with your name
211
+ - id: c
212
+ text: A calendar invitation for a team meeting
213
+ - id: q2
214
+ prompt: What should you do if you suspect a phishing email?
215
+ choices:
216
+ - id: a
217
+ text: Click the link to verify it is safe
218
+ - id: b
219
+ text: Report it to your security team
220
+ correct: true
221
+ - id: c
222
+ text: Forward it to all colleagues as a warning
223
+ `;
224
+ var LXPACK_CONFIG = `{
225
+ "exports": {
226
+ "defaultTarget": "scorm12"
227
+ },
228
+ "output": {
229
+ "dir": ".lxpack"
230
+ }
231
+ }
232
+ `;
233
+ function formatTitle(projectName) {
234
+ return projectName.split(/[-_\s]+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
235
+ }
236
+ async function initCommand(projectName, options = {}) {
237
+ const targetDir = options.dir ?? projectName;
238
+ const title = formatTitle(projectName);
239
+ const yamlTitle = formatCourseTitleForYaml(title);
240
+ if (existsSync2(join2(targetDir, "course.yaml")) && !options.force) {
241
+ console.error(
242
+ pc.red(
243
+ `Directory already contains a course. Use --force to overwrite: ${targetDir}`
244
+ )
245
+ );
246
+ process.exit(1);
247
+ }
248
+ const dirs = [
249
+ targetDir,
250
+ join2(targetDir, "lessons"),
251
+ join2(targetDir, "interactions", "phishing-lab"),
252
+ join2(targetDir, "assets"),
253
+ join2(targetDir, "assessments"),
254
+ join2(targetDir, "theme")
255
+ ];
256
+ for (const dir of dirs) {
257
+ await mkdir(dir, { recursive: true });
258
+ }
259
+ await writeFile(
260
+ join2(targetDir, "course.yaml"),
261
+ COURSE_YAML_TEMPLATE.replace("{{title}}", yamlTitle)
262
+ );
263
+ await writeFile(join2(targetDir, "lessons", "welcome.md"), WELCOME_MD);
264
+ await writeFile(
265
+ join2(targetDir, "interactions", "phishing-lab", "index.html"),
266
+ PHISHING_HTML
267
+ );
268
+ await writeFile(join2(targetDir, "assessments", "final.yaml"), FINAL_ASSESSMENT);
269
+ await writeFile(join2(targetDir, "lxpack.config.json"), LXPACK_CONFIG);
270
+ await writeFile(join2(targetDir, "theme", ".gitkeep"), "");
271
+ console.log(pc.green(`\u2713 Created LXPack course: ${targetDir}`));
272
+ console.log();
273
+ console.log("Next steps:");
274
+ console.log(` cd ${targetDir}`);
275
+ console.log(" lxpack validate");
276
+ console.log(" lxpack preview");
277
+ console.log(" lxpack build --target scorm12");
278
+ }
279
+
280
+ // src/commands/preview.ts
281
+ import Fastify from "fastify";
282
+ import fastifyStatic from "@fastify/static";
283
+ import pc2 from "picocolors";
284
+ import { validateCourse } from "@lxpack/validators";
285
+ async function loadPreviewStyles(assetsDir = getRuntimeAssetsDir()) {
286
+ return loadRuntimeStyles(assetsDir);
287
+ }
288
+ async function createPreviewServer(courseDir, manifest) {
289
+ const runtimeDir = getRuntimeAssetsDir();
290
+ const app = Fastify({ logger: false });
291
+ await app.register(fastifyStatic, {
292
+ root: courseDir,
293
+ prefix: "/course/",
294
+ decorateReply: false
295
+ });
296
+ await app.register(fastifyStatic, {
297
+ root: runtimeDir,
298
+ prefix: "/runtime/",
299
+ decorateReply: false
300
+ });
301
+ const stylesCss = await loadPreviewStyles(runtimeDir);
302
+ app.get("/", async (_req, reply) => {
303
+ const config = JSON.stringify({
304
+ manifest,
305
+ baseUrl: "/course",
306
+ mode: "preview"
307
+ });
308
+ const html = `<!DOCTYPE html>
309
+ <html lang="en">
310
+ <head>
311
+ <meta charset="UTF-8">
312
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
313
+ <title>${escapeHtml(manifest.title)} \u2014 Preview</title>
314
+ <style>${stylesCss}</style>
315
+ </head>
316
+ <body>
317
+ <div id="lxpack-app"></div>
318
+ <script>
319
+ window.__LXPACK_CONFIG__ = ${config};
320
+ </script>
321
+ <script type="module" src="/runtime/client.js"></script>
322
+ </body>
323
+ </html>`;
324
+ return reply.type("text/html").send(html);
325
+ });
326
+ app.get("/health", async () => ({ status: "ok" }));
327
+ return app;
328
+ }
329
+ async function startPreview(courseDir, _options = {}) {
330
+ const validation = await validateCourse(courseDir);
331
+ if (!validation.manifest) {
332
+ console.error(pc2.red("Cannot preview: course manifest is invalid"));
333
+ for (const issue of validation.issues) {
334
+ console.error(` ${issue.path}: ${issue.message}`);
335
+ }
336
+ process.exit(1);
337
+ }
338
+ if (!validation.valid) {
339
+ console.log(pc2.yellow("Warning: course has validation issues:"));
340
+ for (const issue of validation.issues) {
341
+ console.log(` ${issue.path}: ${issue.message}`);
342
+ }
343
+ console.log();
344
+ }
345
+ const app = await createPreviewServer(courseDir, validation.manifest);
346
+ return { app, validation };
347
+ }
348
+ function resolvePreviewDeps(deps) {
349
+ return {
350
+ findCourseDir: deps?.findCourseDir ?? findCourseDir,
351
+ startPreview: deps?.startPreview ?? startPreview,
352
+ logPreviewStarted: deps?.logPreviewStarted ?? logPreviewStarted
353
+ };
354
+ }
355
+ async function previewCommand(options, deps) {
356
+ const {
357
+ findCourseDir: resolveCourseDir,
358
+ startPreview: resolveStartPreview,
359
+ logPreviewStarted: resolveLogStarted
360
+ } = resolvePreviewDeps(deps);
361
+ const courseDir = resolveCourseDir();
362
+ const port = options.port ?? 3847;
363
+ const host = options.host ?? "127.0.0.1";
364
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
365
+ console.error(pc2.red(`Invalid port: ${port}`));
366
+ process.exit(1);
367
+ }
368
+ const { app } = await resolveStartPreview(courseDir, options);
369
+ try {
370
+ await app.listen({ port, host });
371
+ } catch (err) {
372
+ const message = err instanceof Error ? err.message : String(err);
373
+ if (message.includes("EADDRINUSE")) {
374
+ console.error(pc2.red(`Port ${port} is already in use`));
375
+ } else {
376
+ console.error(pc2.red(`Failed to start preview server: ${message}`));
377
+ }
378
+ process.exit(1);
379
+ }
380
+ resolveLogStarted(host, port);
381
+ }
382
+ function logPreviewStarted(host, port) {
383
+ console.log(pc2.green(`\u2713 Preview server running`));
384
+ console.log(` ${pc2.cyan(`http://${host}:${port}`)}`);
385
+ console.log();
386
+ console.log(pc2.dim("Press Ctrl+C to stop"));
387
+ }
388
+
389
+ // src/commands/validate.ts
390
+ import { validateCourse as validateCourse2 } from "@lxpack/validators";
391
+ import pc3 from "picocolors";
392
+ async function validateCommand() {
393
+ const courseDir = findCourseDir();
394
+ const result = await validateCourse2(courseDir);
395
+ if (result.manifest) {
396
+ console.log(
397
+ pc3.dim(`Course: ${result.manifest.title} v${result.manifest.version}`)
398
+ );
399
+ console.log(pc3.dim(`Lessons: ${result.manifest.lessons.length}`));
400
+ console.log();
401
+ }
402
+ for (const issue of result.issues) {
403
+ const icon = issue.severity === "error" ? pc3.red("\u2717") : pc3.yellow("!");
404
+ console.log(`${icon} ${issue.path}: ${issue.message}`);
405
+ }
406
+ if (result.valid) {
407
+ console.log(pc3.green("\u2713 Course validation passed"));
408
+ process.exit(0);
409
+ } else {
410
+ console.log(pc3.red("\u2717 Course validation failed"));
411
+ process.exit(1);
412
+ }
413
+ }
414
+
415
+ // src/commands/build.ts
416
+ import { mkdir as mkdir2 } from "fs/promises";
417
+ import { join as join3 } from "path";
418
+ import { packageCourse, packageStandaloneDir } from "@lxpack/scorm";
419
+ import { validateCourse as validateCourse3 } from "@lxpack/validators";
420
+ import pc4 from "picocolors";
421
+ var VALID_TARGETS = ["scorm12", "standalone"];
422
+ async function buildCommand(options) {
423
+ const courseDir = findCourseDir();
424
+ const config = await loadLxpackConfig(courseDir);
425
+ const target = options.target ?? config?.exports?.defaultTarget ?? "scorm12";
426
+ if (!VALID_TARGETS.includes(target)) {
427
+ console.error(
428
+ pc4.red(
429
+ `Invalid target: ${target}. Valid targets: ${VALID_TARGETS.join(", ")}`
430
+ )
431
+ );
432
+ process.exit(1);
433
+ }
434
+ const validation = await validateCourse3(courseDir);
435
+ if (!validation.valid) {
436
+ console.error(pc4.red("Cannot build: course validation failed"));
437
+ for (const issue of validation.issues) {
438
+ console.error(` ${issue.path}: ${issue.message}`);
439
+ }
440
+ process.exit(1);
441
+ }
442
+ const manifest = await loadCourseManifest(courseDir);
443
+ const { clientJs, css } = await readRuntimeBundle();
444
+ const slug = manifest.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "course";
445
+ const outputBase = config?.output?.dir ?? ".lxpack";
446
+ await mkdir2(join3(courseDir, outputBase), { recursive: true });
447
+ if (options.dir) {
448
+ const outputDir = options.output ?? join3(courseDir, outputBase, target);
449
+ const result = await packageStandaloneDir({
450
+ courseDir,
451
+ manifest,
452
+ outputDir,
453
+ target,
454
+ runtimeClientJs: clientJs,
455
+ runtimeCss: css
456
+ });
457
+ console.log(pc4.green(`\u2713 Built ${target} package`));
458
+ console.log(` Output: ${result.outputDir}`);
459
+ console.log(` Files: ${result.fileCount}`);
460
+ } else {
461
+ const defaultName = target === "standalone" ? `${slug}-standalone.zip` : `${slug}-scorm12.zip`;
462
+ const outputPath = options.output ?? join3(courseDir, outputBase, defaultName);
463
+ const result = await packageCourse({
464
+ courseDir,
465
+ manifest,
466
+ outputPath,
467
+ target,
468
+ runtimeClientJs: clientJs,
469
+ runtimeCss: css
470
+ });
471
+ console.log(pc4.green(`\u2713 Built ${target} package`));
472
+ console.log(` Output: ${result.outputPath}`);
473
+ console.log(` Files: ${result.fileCount}`);
474
+ }
475
+ }
476
+
477
+ // src/cli.ts
478
+ function createCliProgram() {
479
+ const program = new Command();
480
+ program.name("lxpack").description("AI-native learning experience compiler").version(getCliVersion());
481
+ program.command("init").description("Create a new LXPack course project").argument("<project-name>", "Name of the course project").option("-d, --dir <path>", "Output directory (defaults to project name)").option("-f, --force", "Overwrite existing files").action(
482
+ async (projectName, options) => {
483
+ await initCommand(projectName, options);
484
+ }
485
+ );
486
+ program.command("preview").description("Start local preview server").option("-p, --port <port>", "Port number", "3847").option("-H, --host <host>", "Host address", "127.0.0.1").action(async (options) => {
487
+ await previewCommand({
488
+ port: Number(options.port),
489
+ host: options.host
490
+ });
491
+ });
492
+ program.command("validate").description("Validate course structure and assets").action(async () => {
493
+ await validateCommand();
494
+ });
495
+ program.command("build").description("Build LMS-compatible package").option(
496
+ "-t, --target <target>",
497
+ "Export target: scorm12, standalone",
498
+ void 0
499
+ ).option("-o, --output <path>", "Output file or directory path").option("--dir", "Output as directory instead of ZIP").action(
500
+ async (options) => {
501
+ await buildCommand(options);
502
+ }
503
+ );
504
+ return program;
505
+ }
506
+ async function runCli(argv = process.argv) {
507
+ const program = createCliProgram();
508
+ await program.parseAsync(argv);
509
+ }
510
+ function printCliError(err) {
511
+ const message = err instanceof Error ? err.message : String(err);
512
+ console.error(pc5.red(`Error: ${message}`));
513
+ }
514
+ var isTestEnv = process.env.VITEST === "true";
515
+ if (!isTestEnv) {
516
+ try {
517
+ await runCli();
518
+ } catch (err) {
519
+ printCliError(err);
520
+ process.exit(1);
521
+ }
522
+ }
523
+ export {
524
+ createCliProgram,
525
+ printCliError,
526
+ runCli
527
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@lxpack/cli",
3
+ "version": "0.1.0",
4
+ "description": "CLI for building, validating, and packaging LXPack courses",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/eddiethedean/lxpack.git",
9
+ "directory": "packages/cli"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/eddiethedean/lxpack/issues"
13
+ },
14
+ "homepage": "https://github.com/eddiethedean/lxpack#readme",
15
+ "keywords": [
16
+ "lxpack",
17
+ "cli",
18
+ "scorm",
19
+ "lms",
20
+ "elearning"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "type": "module",
29
+ "bin": {
30
+ "lxpack": "./dist/cli.js"
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "dependencies": {
36
+ "@fastify/static": "^8.1.1",
37
+ "commander": "^13.1.0",
38
+ "fastify": "^5.2.1",
39
+ "picocolors": "^1.1.1",
40
+ "yaml": "^2.7.0",
41
+ "zod": "^3.24.2",
42
+ "@lxpack/runtime": "0.1.0",
43
+ "@lxpack/scorm": "0.1.0",
44
+ "@lxpack/validators": "0.1.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^22.13.10",
48
+ "jszip": "^3.10.1",
49
+ "tsup": "^8.4.0",
50
+ "typescript": "^5.8.3",
51
+ "vitest": "^3.1.1"
52
+ },
53
+ "scripts": {
54
+ "build": "tsup",
55
+ "dev": "tsup --watch",
56
+ "typecheck": "tsc --noEmit",
57
+ "test": "vitest run",
58
+ "test:coverage": "vitest run --coverage"
59
+ }
60
+ }