create-honua-app 0.1.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.
Files changed (33) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +50 -0
  3. package/bin/create-honua-app.mjs +7 -0
  4. package/lib/cli.mjs +149 -0
  5. package/lib/scaffold.mjs +134 -0
  6. package/lib/templates.mjs +138 -0
  7. package/package.json +32 -0
  8. package/templates/react-ts/.stackblitzrc +4 -0
  9. package/templates/react-ts/README.md +64 -0
  10. package/templates/react-ts/_gitignore +6 -0
  11. package/templates/react-ts/fixtures/features.json +46 -0
  12. package/templates/react-ts/fixtures/layer.json +34 -0
  13. package/templates/react-ts/index.html +12 -0
  14. package/templates/react-ts/package.json +31 -0
  15. package/templates/react-ts/src/App.tsx +153 -0
  16. package/templates/react-ts/src/fixture-endpoint.ts +9 -0
  17. package/templates/react-ts/src/main.tsx +18 -0
  18. package/templates/react-ts/src/styles.css +149 -0
  19. package/templates/react-ts/tsconfig.json +15 -0
  20. package/templates/react-ts/vite.config.ts +50 -0
  21. package/templates/vanilla-ts/.stackblitzrc +4 -0
  22. package/templates/vanilla-ts/README.md +60 -0
  23. package/templates/vanilla-ts/_gitignore +6 -0
  24. package/templates/vanilla-ts/fixtures/features.json +46 -0
  25. package/templates/vanilla-ts/fixtures/layer.json +34 -0
  26. package/templates/vanilla-ts/index.html +37 -0
  27. package/templates/vanilla-ts/package.json +27 -0
  28. package/templates/vanilla-ts/src/fixture-endpoint.ts +9 -0
  29. package/templates/vanilla-ts/src/main.ts +113 -0
  30. package/templates/vanilla-ts/src/styles.css +149 -0
  31. package/templates/vanilla-ts/tsconfig.json +14 -0
  32. package/templates/vanilla-ts/vite.config.ts +50 -0
  33. package/templates.manifest.json +61 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
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
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Honua
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # create-honua-app
2
+
3
+ Scaffold a [Honua JavaScript SDK](https://github.com/honua-io/honua-sdk-js) map application — Vite + TypeScript,
4
+ pinned to a published SDK version, running a map on the first `npm run dev`.
5
+
6
+ ```bash
7
+ npm create honua-app@latest my-map
8
+ cd my-map
9
+ npm install
10
+ npm run dev
11
+ ```
12
+
13
+ ## Options
14
+
15
+ ```text
16
+ create-honua-app [directory] [options]
17
+
18
+ -t, --template <id> Starter to scaffold (default: vanilla-ts)
19
+ --list-templates Print the available templates and their playground links
20
+ --force Scaffold into a directory that already has files
21
+ -h, --help Print usage
22
+ -v, --version Print the create-honua-app version
23
+ ```
24
+
25
+ With `npm create`, pass CLI options after `--`:
26
+
27
+ ```bash
28
+ npm create honua-app@latest my-map -- --template react-ts
29
+ ```
30
+
31
+ ## Templates
32
+
33
+ | Template | What it shows |
34
+ | --- | --- |
35
+ | `vanilla-ts` | `connect → inspect → explain → query → mount`: the SDK owns the MapLibre map and mounts an accepted query plan. |
36
+ | `react-ts` | The app owns a plain `maplibre-gl` map; `useMountedSource` from `@honua/sdk-js/react` mounts the discovered source onto it. |
37
+
38
+ Both starters ship a committed GeoServices fixture served by the Vite dev and preview servers, so the green path
39
+ never depends on a third-party endpoint, an account, or an API key. Set `VITE_HONUA_ENDPOINT` to run the same code
40
+ against any anonymous, CORS-enabled GeoServices FeatureServer layer or OGC API Features landing page.
41
+
42
+ ## Try a template without installing anything
43
+
44
+ Every template runs in a browser playground straight from the repository. The generated link list lives in
45
+ [`docs/playgrounds.md`](https://github.com/honua-io/honua-sdk-js/blob/trunk/docs/playgrounds.md), and
46
+ `create-honua-app --list-templates` prints the same links.
47
+
48
+ ## License
49
+
50
+ Apache-2.0.
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Entry point for `npm create honua-app` / `npx create-honua-app`.
4
+
5
+ import { run } from "../lib/cli.mjs";
6
+
7
+ process.exitCode = run(process.argv.slice(2));
package/lib/cli.mjs ADDED
@@ -0,0 +1,149 @@
1
+ // Argument parsing and console output for `npm create honua-app`.
2
+ //
3
+ // `parseArgs` is pure so the repository test suite can assert the grammar, and
4
+ // `run` takes its streams and working directory as options so a test can drive
5
+ // a full scaffold in-process without spawning npm or a build.
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+
10
+ import { scaffoldProject } from "./scaffold.mjs";
11
+ import { PACKAGE_ROOT, defaultTemplate, loadTemplateManifest, playgroundLinks, templateIds } from "./templates.mjs";
12
+
13
+ const USAGE = `Usage: create-honua-app [directory] [options]
14
+
15
+ Options:
16
+ -t, --template <id> Starter to scaffold (default: the manifest's default template)
17
+ --list-templates Print the available templates and exit
18
+ --force Scaffold into a directory that already has files
19
+ -h, --help Print this message and exit
20
+ -v, --version Print the create-honua-app version and exit`;
21
+
22
+ /** Parse argv (already stripped of node and the script path). */
23
+ export function parseArgs(argv) {
24
+ const options = { mode: "scaffold", directory: undefined, templateId: undefined, force: false };
25
+ for (let index = 0; index < argv.length; index += 1) {
26
+ const argument = argv[index];
27
+ if (argument === "--help" || argument === "-h") {
28
+ options.mode = "help";
29
+ continue;
30
+ }
31
+ if (argument === "--version" || argument === "-v") {
32
+ options.mode = "version";
33
+ continue;
34
+ }
35
+ if (argument === "--list-templates") {
36
+ options.mode = "list-templates";
37
+ continue;
38
+ }
39
+ if (argument === "--force") {
40
+ options.force = true;
41
+ continue;
42
+ }
43
+ if (argument === "--template" || argument === "-t") {
44
+ const value = argv[index + 1];
45
+ if (!value || value.startsWith("-")) throw new Error(`${argument} requires a template id.`);
46
+ options.templateId = value;
47
+ index += 1;
48
+ continue;
49
+ }
50
+ if (argument.startsWith("--template=")) {
51
+ const value = argument.slice("--template=".length);
52
+ if (value.length === 0) throw new Error("--template requires a template id.");
53
+ options.templateId = value;
54
+ continue;
55
+ }
56
+ if (argument.startsWith("-")) throw new Error(`Unknown option: ${argument}`);
57
+ if (options.directory !== undefined) throw new Error(`Unexpected extra argument: ${argument}`);
58
+ options.directory = argument;
59
+ }
60
+ return options;
61
+ }
62
+
63
+ /** Help text, including the live template list so it can never drift. */
64
+ export function helpText(manifest) {
65
+ const templates = manifest.templates
66
+ .map((template) => ` ${template.id.padEnd(12)} ${template.summary}${template.default ? " (default)" : ""}`)
67
+ .join("\n");
68
+ return `${USAGE}\n\nTemplates:\n${templates}\n`;
69
+ }
70
+
71
+ /** The `--list-templates` report, with each starter's zero-install playground links. */
72
+ export function templateListing(manifest) {
73
+ const lines = [];
74
+ for (const template of manifest.templates) {
75
+ lines.push(`${template.id}${template.default ? " (default)" : ""} — ${template.title}`);
76
+ lines.push(` ${template.summary}`);
77
+ lines.push(` SDK: ${manifest.sdk.package}@${manifest.sdk.version}`);
78
+ for (const link of playgroundLinks(manifest, template)) lines.push(` ${link.title}: ${link.url}`);
79
+ }
80
+ return `${lines.join("\n")}\n`;
81
+ }
82
+
83
+ /** Next-step instructions printed after a successful scaffold. */
84
+ export function nextSteps(receipt, cwd) {
85
+ const relative = path.relative(cwd, receipt.targetRoot) || ".";
86
+ return [
87
+ `Created ${receipt.projectName} from the ${receipt.templateId} template in ${relative}.`,
88
+ `Pinned ${receipt.sdk.package}@${receipt.sdk.version}.`,
89
+ "",
90
+ "Next steps:",
91
+ ...(relative === "." ? [] : [` cd ${relative}`]),
92
+ " npm install",
93
+ " npm run dev",
94
+ "",
95
+ "The default lane serves a committed fixture, so the first map needs no account, key, or network.",
96
+ "",
97
+ ].join("\n");
98
+ }
99
+
100
+ function packageVersion(packageRoot) {
101
+ return JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8")).version;
102
+ }
103
+
104
+ /**
105
+ * Run the CLI. Returns the process exit code instead of calling `process.exit`
106
+ * so the bin wrapper stays the only place that touches process state.
107
+ */
108
+ export function run(
109
+ argv,
110
+ { cwd = process.cwd(), stdout = process.stdout, stderr = process.stderr, packageRoot = PACKAGE_ROOT } = {},
111
+ ) {
112
+ let options;
113
+ try {
114
+ options = parseArgs(argv);
115
+ } catch (error) {
116
+ stderr.write(`${error instanceof Error ? error.message : String(error)}\n\n${USAGE}\n`);
117
+ return 1;
118
+ }
119
+
120
+ const manifest = loadTemplateManifest(packageRoot);
121
+ if (options.mode === "help") {
122
+ stdout.write(helpText(manifest));
123
+ return 0;
124
+ }
125
+ if (options.mode === "version") {
126
+ stdout.write(`${packageVersion(packageRoot)}\n`);
127
+ return 0;
128
+ }
129
+ if (options.mode === "list-templates") {
130
+ stdout.write(templateListing(manifest));
131
+ return 0;
132
+ }
133
+
134
+ const directory = options.directory ?? "honua-app";
135
+ const templateId = options.templateId ?? defaultTemplate(manifest).id;
136
+ if (!templateIds(manifest).includes(templateId)) {
137
+ stderr.write(`Unknown template ${JSON.stringify(templateId)}. Available: ${templateIds(manifest).join(", ")}.\n`);
138
+ return 1;
139
+ }
140
+
141
+ try {
142
+ const receipt = scaffoldProject({ templateId, directory, force: options.force, cwd, packageRoot });
143
+ stdout.write(nextSteps(receipt, cwd));
144
+ return 0;
145
+ } catch (error) {
146
+ stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
147
+ return 1;
148
+ }
149
+ }
@@ -0,0 +1,134 @@
1
+ // Filesystem half of `create-honua-app`: copy one template into a new project
2
+ // directory, renaming the files npm cannot publish under their real names and
3
+ // stamping the project's own package name.
4
+ //
5
+ // Everything here is exported as a plain function so the repository test suite
6
+ // can scaffold into a temporary directory without spawning a process.
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+
11
+ import { PACKAGE_ROOT, loadTemplateManifest, templateById, templateRoot } from "./templates.mjs";
12
+
13
+ /** npm strips a published `.gitignore`, so templates carry it under a safe name. */
14
+ export const RENAMED_TEMPLATE_FILES = new Map([["_gitignore", ".gitignore"]]);
15
+
16
+ /** Files that configure the zero-install playground hosts, not the scaffolded app. */
17
+ export const PLAYGROUND_ONLY_FILES = new Set([".stackblitzrc"]);
18
+
19
+ /** npm package-name grammar, narrowed to the unscoped names a directory can produce. */
20
+ export const PROJECT_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
21
+
22
+ /** Directory entries that do not make a target directory "non-empty" for scaffolding. */
23
+ const IGNORED_TARGET_ENTRIES = new Set([".git", ".DS_Store"]);
24
+
25
+ /** Derive (and validate) the npm package name a target directory implies. */
26
+ export function projectNameFromDirectory(directory) {
27
+ const base = path.basename(path.resolve(directory));
28
+ const name = base.toLowerCase();
29
+ if (name.length === 0 || name.length > 214) {
30
+ throw new Error(`Project name ${JSON.stringify(base)} must be between 1 and 214 characters.`);
31
+ }
32
+ if (!PROJECT_NAME_PATTERN.test(name)) {
33
+ throw new Error(
34
+ `Project name ${JSON.stringify(base)} is not a valid npm package name. Use lowercase letters, digits, "-", "_" or "." and start with a letter or digit.`,
35
+ );
36
+ }
37
+ return name;
38
+ }
39
+
40
+ /** Recursively list a template's files as sorted, POSIX-style relative paths. */
41
+ export function collectTemplateFiles(root) {
42
+ const files = [];
43
+ const walk = (directory, prefix) => {
44
+ for (const entry of fs
45
+ .readdirSync(directory, { withFileTypes: true })
46
+ .sort((a, b) => a.name.localeCompare(b.name))) {
47
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
48
+ if (entry.isDirectory()) {
49
+ walk(path.join(directory, entry.name), relative);
50
+ continue;
51
+ }
52
+ if (!entry.isFile()) throw new Error(`Template entry ${relative} is not a regular file.`);
53
+ files.push(relative);
54
+ }
55
+ };
56
+ walk(root, "");
57
+ return files;
58
+ }
59
+
60
+ /** Map a template-relative path onto the path the scaffolded project uses. */
61
+ export function scaffoldedPath(relativePath) {
62
+ const segments = relativePath.split("/");
63
+ const last = segments[segments.length - 1];
64
+ const renamed = RENAMED_TEMPLATE_FILES.get(last);
65
+ if (!renamed) return relativePath;
66
+ return [...segments.slice(0, -1), renamed].join("/");
67
+ }
68
+
69
+ /** True when a template file exists only to configure a playground host. */
70
+ export function isPlaygroundOnlyFile(relativePath) {
71
+ return PLAYGROUND_ONLY_FILES.has(relativePath.split("/").pop());
72
+ }
73
+
74
+ /** Rewrite a template `package.json` so the scaffolded app carries its own name. */
75
+ export function renderProjectManifest(source, projectName) {
76
+ const manifest = JSON.parse(source);
77
+ manifest.name = projectName;
78
+ return `${JSON.stringify(manifest, null, 2)}\n`;
79
+ }
80
+
81
+ function assertWritableTarget(targetRoot, force) {
82
+ if (!fs.existsSync(targetRoot)) return;
83
+ const stats = fs.statSync(targetRoot);
84
+ if (!stats.isDirectory()) throw new Error(`${targetRoot} exists and is not a directory.`);
85
+ if (force) return;
86
+ const entries = fs.readdirSync(targetRoot).filter((entry) => !IGNORED_TARGET_ENTRIES.has(entry));
87
+ if (entries.length > 0) {
88
+ throw new Error(`${targetRoot} is not empty. Choose another directory or pass --force.`);
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Copy `templateId` into `directory`, returning the scaffold receipt the CLI
94
+ * prints. `directory` is resolved against `cwd` so tests never depend on the
95
+ * process working directory.
96
+ */
97
+ export function scaffoldProject({
98
+ templateId,
99
+ directory,
100
+ force = false,
101
+ cwd = process.cwd(),
102
+ packageRoot = PACKAGE_ROOT,
103
+ }) {
104
+ const manifest = loadTemplateManifest(packageRoot);
105
+ const template = templateById(manifest, templateId);
106
+ const sourceRoot = templateRoot(manifest, template.id, packageRoot);
107
+ const targetRoot = path.resolve(cwd, directory);
108
+ const projectName = projectNameFromDirectory(targetRoot);
109
+ assertWritableTarget(targetRoot, force);
110
+
111
+ const written = [];
112
+ for (const relativePath of collectTemplateFiles(sourceRoot)) {
113
+ if (isPlaygroundOnlyFile(relativePath)) continue;
114
+ const destinationRelative = scaffoldedPath(relativePath);
115
+ const source = path.join(sourceRoot, relativePath);
116
+ const destination = path.join(targetRoot, destinationRelative);
117
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
118
+ if (destinationRelative === "package.json") {
119
+ fs.writeFileSync(destination, renderProjectManifest(fs.readFileSync(source, "utf8"), projectName));
120
+ } else {
121
+ fs.copyFileSync(source, destination);
122
+ }
123
+ written.push(destinationRelative);
124
+ }
125
+
126
+ return {
127
+ templateId: template.id,
128
+ templateTitle: template.title,
129
+ projectName,
130
+ targetRoot,
131
+ sdk: { ...manifest.sdk },
132
+ files: written,
133
+ };
134
+ }
@@ -0,0 +1,138 @@
1
+ // Template manifest reader for `create-honua-app`.
2
+ //
3
+ // `templates.manifest.json` is the single source of truth for which starters
4
+ // exist, which published SDK version they pin, and where their zero-install
5
+ // playgrounds live. The CLI, the repository verifier
6
+ // (scripts/verify-create-honua-app.mjs) and the generated playground page
7
+ // (scripts/playgrounds.mjs) all read it through this module so a template can
8
+ // never be advertised in one place and missing in another.
9
+
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
15
+ export const MANIFEST_FILE = "templates.manifest.json";
16
+ export const MANIFEST_FORMAT = "honua.sdk.create-honua-app-templates.v1";
17
+ export const TEMPLATE_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
18
+
19
+ function fail(message) {
20
+ throw new Error(`${MANIFEST_FILE} is invalid: ${message}`);
21
+ }
22
+
23
+ function nonEmptyString(value, field) {
24
+ if (typeof value !== "string" || value.trim().length === 0) fail(`${field} must be a non-empty string`);
25
+ return value;
26
+ }
27
+
28
+ /** Read and validate the template manifest that ships inside the package. */
29
+ export function loadTemplateManifest(packageRoot = PACKAGE_ROOT) {
30
+ const manifestPath = path.join(packageRoot, MANIFEST_FILE);
31
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
32
+ if (manifest.format !== MANIFEST_FORMAT) fail(`format must be ${MANIFEST_FORMAT}`);
33
+ if (manifest.schemaVersion !== 1) fail("schemaVersion must be 1");
34
+ nonEmptyString(manifest.sdk?.package, "sdk.package");
35
+ nonEmptyString(manifest.sdk?.version, "sdk.version");
36
+ for (const field of ["owner", "name", "branch"]) nonEmptyString(manifest.repository?.[field], `repository.${field}`);
37
+ if (!Array.isArray(manifest.playgroundProviders) || manifest.playgroundProviders.length === 0) {
38
+ fail("playgroundProviders must be a non-empty array");
39
+ }
40
+ for (const provider of manifest.playgroundProviders) {
41
+ nonEmptyString(provider?.id, "playgroundProviders[].id");
42
+ nonEmptyString(provider?.title, "playgroundProviders[].title");
43
+ nonEmptyString(provider?.urlTemplate, "playgroundProviders[].urlTemplate");
44
+ }
45
+ if (!Array.isArray(manifest.templates) || manifest.templates.length === 0)
46
+ fail("templates must be a non-empty array");
47
+ const seen = new Set();
48
+ for (const template of manifest.templates) {
49
+ const id = nonEmptyString(template?.id, "templates[].id");
50
+ if (!TEMPLATE_ID_PATTERN.test(id)) fail(`template id ${JSON.stringify(id)} must be a lowercase slug`);
51
+ if (seen.has(id)) fail(`duplicate template id ${JSON.stringify(id)}`);
52
+ seen.add(id);
53
+ nonEmptyString(template.title, `templates[${id}].title`);
54
+ nonEmptyString(template.summary, `templates[${id}].summary`);
55
+ nonEmptyString(template.path, `templates[${id}].path`);
56
+ nonEmptyString(template.entryFile, `templates[${id}].entryFile`);
57
+ if (template.dataLane !== "fixture") fail(`templates[${id}].dataLane must be "fixture"`);
58
+ if (typeof template.default !== "boolean") fail(`templates[${id}].default must be a boolean`);
59
+ if (!Array.isArray(template.dependencies) || template.dependencies.length === 0) {
60
+ fail(`templates[${id}].dependencies must be a non-empty array`);
61
+ }
62
+ if (!template.path.endsWith(`/${id}`)) fail(`templates[${id}].path must end with the template id`);
63
+ }
64
+ if (manifest.templates.filter((template) => template.default).length !== 1) {
65
+ fail("exactly one template must be marked default");
66
+ }
67
+ return manifest;
68
+ }
69
+
70
+ /** Ids of every declared template, in manifest order. */
71
+ export function templateIds(manifest) {
72
+ return manifest.templates.map((template) => template.id);
73
+ }
74
+
75
+ /** The template a bare `create-honua-app <dir>` invocation uses. */
76
+ export function defaultTemplate(manifest) {
77
+ return manifest.templates.find((template) => template.default);
78
+ }
79
+
80
+ /** Look up one template, throwing a caller-friendly error for unknown ids. */
81
+ export function templateById(manifest, id) {
82
+ const template = manifest.templates.find((entry) => entry.id === id);
83
+ if (!template) {
84
+ throw new Error(
85
+ `Unknown template ${JSON.stringify(id)}. Available templates: ${templateIds(manifest).join(", ")}.`,
86
+ );
87
+ }
88
+ return template;
89
+ }
90
+
91
+ /** Absolute directory holding a template's files inside the installed package. */
92
+ export function templateRoot(manifest, id, packageRoot = PACKAGE_ROOT) {
93
+ const template = templateById(manifest, id);
94
+ return path.join(packageRoot, "templates", template.id);
95
+ }
96
+
97
+ /**
98
+ * Expand one provider's URL template for one repository-relative project path.
99
+ * Playground links stay plain, query-free https URLs so they remain safe for
100
+ * documentation surfaces that reject query strings and fragments.
101
+ */
102
+ export function playgroundUrl(provider, { owner, repository, branch, path: projectPath }) {
103
+ // Every token lives in the path, so the template's own origin is the only
104
+ // host a rendered link may address. Origins are compared, never matched as
105
+ // substrings: a substring test would accept any host that merely contains
106
+ // the expected one.
107
+ const expected = new URL(provider.urlTemplate);
108
+ if (expected.protocol !== "https:") {
109
+ throw new Error(`playground provider ${provider.id} must declare an https template: ${provider.urlTemplate}`);
110
+ }
111
+ const url = provider.urlTemplate
112
+ .replaceAll("{owner}", owner)
113
+ .replaceAll("{repository}", repository)
114
+ .replaceAll("{branch}", branch)
115
+ .replaceAll("{path}", projectPath);
116
+ const parsed = new URL(url);
117
+ if (parsed.origin !== expected.origin) throw new Error(`playground URL must stay on ${expected.origin}: ${url}`);
118
+ if (parsed.search !== "" || parsed.hash !== "")
119
+ throw new Error(`playground URL must not carry a query or fragment: ${url}`);
120
+ if (!parsed.pathname.endsWith(`/${projectPath}`)) {
121
+ throw new Error(`playground URL must address ${projectPath}: ${url}`);
122
+ }
123
+ return parsed.toString();
124
+ }
125
+
126
+ /** Every provider link for one template, derived from the manifest. */
127
+ export function playgroundLinks(manifest, template) {
128
+ return manifest.playgroundProviders.map((provider) => ({
129
+ providerId: provider.id,
130
+ title: provider.title,
131
+ url: playgroundUrl(provider, {
132
+ owner: manifest.repository.owner,
133
+ repository: manifest.repository.name,
134
+ branch: manifest.repository.branch,
135
+ path: template.path,
136
+ }),
137
+ }));
138
+ }