orionplace-svelte 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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +244 -0
  3. package/bin/orionplace-svelte.mjs +102 -0
  4. package/package.json +56 -0
  5. package/runtime/marketplace.d.mts +22 -0
  6. package/runtime/marketplace.mjs +211 -0
  7. package/src/project-readme.mjs +341 -0
  8. package/src/setup.mjs +261 -0
  9. package/src/update.mjs +36 -0
  10. package/src/validation.mjs +27 -0
  11. package/templates/src/app.d.ts +12 -0
  12. package/templates/src/app.html +11 -0
  13. package/templates/src/hooks.server.ts +14 -0
  14. package/templates/src/lib/interfaces/orionplace/apiBase/TMethod.ts +1 -0
  15. package/templates/src/lib/interfaces/orionplace/appBase/IAppLoad.ts +15 -0
  16. package/templates/src/lib/interfaces/orionplace/appBase/IAppLoadCommon.ts +41 -0
  17. package/templates/src/lib/interfaces/orionplace/appBase/IApploadUserProfile.ts +13 -0
  18. package/templates/src/lib/interfaces/orionplace/appBase/IForm.ts +21 -0
  19. package/templates/src/lib/interfaces/orionplace/appBase/ISEO.ts +21 -0
  20. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonBanner.ts +11 -0
  21. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonContact.ts +8 -0
  22. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonCurrency.ts +15 -0
  23. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonEvents.ts +18 -0
  24. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonLocale.ts +14 -0
  25. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonLogos.ts +6 -0
  26. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonPath.ts +22 -0
  27. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonSEO.ts +13 -0
  28. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonSocial.ts +15 -0
  29. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonTariff.ts +7 -0
  30. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonUnit.ts +12 -0
  31. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonVariables.ts +7 -0
  32. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonVisualSettings.ts +11 -0
  33. package/templates/src/lib/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonWalletValue.ts +3 -0
  34. package/templates/src/lib/interfaces/orionplace/category/ICategory.ts +40 -0
  35. package/templates/src/lib/interfaces/orionplace/domains/IDomain.ts +13 -0
  36. package/templates/src/lib/interfaces/orionplace/index.ts +30 -0
  37. package/templates/src/lib/interfaces/orionplace/products/IProduct.ts +235 -0
  38. package/templates/src/lib/interfaces/orionplace/shared/IGeoCoordinates.ts +4 -0
  39. package/templates/src/lib/interfaces/orionplace/shared/ITransformValue.ts +3 -0
  40. package/templates/src/lib/interfaces/orionplace/state.ts +4 -0
  41. package/templates/src/lib/interfaces/orionplace/subscribeOptions/ISubscribeOption.ts +9 -0
  42. package/templates/src/lib/interfaces/orionplace/subscribeTariff/ISubscribeTariff.ts +46 -0
  43. package/templates/src/lib/interfaces/orionplace/subscribes/ISubscribe.ts +28 -0
  44. package/templates/src/lib/interfaces/orionplace/transport.ts +30 -0
  45. package/templates/src/lib/orionplace/appLoadClient.ts +33 -0
  46. package/templates/src/lib/orionplace/appLoadData.ts +31 -0
  47. package/templates/src/lib/orionplace/appLoadResult.ts +56 -0
  48. package/templates/src/lib/orionplace/appLoadServer.ts +93 -0
  49. package/templates/src/lib/orionplace/domain.ts +11 -0
  50. package/templates/src/lib/orionplace/store.svelte.ts +121 -0
  51. package/templates/src/routes/+layout.server.ts +11 -0
  52. package/templates/src/routes/+layout.svelte +19 -0
  53. package/templates/src/routes/+page.svelte +108 -0
  54. package/templates/src/routes/api/[...orionplace]/+server.ts +15 -0
  55. package/templates/svelte.config.js +13 -0
  56. package/templates/vite.config.ts +19 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Orionplace contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,244 @@
1
+ # orionplace-svelte
2
+
3
+ Set up a SvelteKit 2 storefront for your personal Orionplace marketplace API.
4
+ The package includes a setup CLI, the SvelteKit starter with typed AppLoad
5
+ initialization, and commented server source that is copied into your project
6
+ alongside an integration README.
7
+
8
+ Requires Node.js 20.19+, Svelte 5 and `@sveltejs/adapter-node`. Static and
9
+ edge-only adapters cannot read the domain files this integration uses.
10
+
11
+ ## Quick start from zero
12
+
13
+ Your personal backend domain is already provided in your account at
14
+ [orionmarket.place](https://orionmarket.place). You can change it there.
15
+ Replace `your-project.orionplace.app` below with that domain and
16
+ `shop.example.com` with the public domain of your own storefront.
17
+ With Node.js 20.19+ and npm installed, run this from the parent folder;
18
+ no existing SvelteKit project is needed:
19
+
20
+ ```bash
21
+ npx --yes orionplace-svelte init my-marketplace
22
+ cd my-marketplace
23
+ npm install
24
+ npx orionplace-svelte set backend your-project.orionplace.app
25
+ npx orionplace-svelte add frontend shop.example.com
26
+ npm run dev
27
+ ```
28
+
29
+ The first command creates the SvelteKit configuration, starter routes and
30
+ integration README. The first frontend becomes the local MIMIC domain. Open the
31
+ local URL printed by Vite (normally http://localhost:5173); the starter's AppLoad
32
+ state should show `Loaded`. If it shows `Failed`, check your domain mapping and
33
+ backend response. The backend command accepts either a hostname or its full HTTPS
34
+ `/api` URL. The frontend command accepts a public hostname or its root HTTPS URL.
35
+
36
+ ## Existing SvelteKit 2 project
37
+
38
+ ```bash
39
+ npm install orionplace-svelte
40
+ npx orionplace-svelte init --dry-run
41
+ npx orionplace-svelte set backend your-project.orionplace.app
42
+ npx orionplace-svelte add frontend shop.example.com
43
+ npm install
44
+ npm run dev
45
+ ```
46
+
47
+ The CLI preserves unrelated SvelteKit settings, scripts, and environment
48
+ variables. It never replaces your own `svelte.config.js`, `vite.config.ts`,
49
+ `src/app.html`, `src/hooks.server.ts`, root layout or home page: it keeps your
50
+ file and prints its path so you can merge the starter yourself. Switch to
51
+ `@sveltejs/adapter-node` and resolve an existing `/api` catch-all route before
52
+ setup.
53
+
54
+ No install or postinstall hook changes your application. Only explicitly running
55
+ the CLI writes files. Use `--cwd <directory>` to select a project and `--dry-run`
56
+ to inspect planned changes without writing them.
57
+
58
+ ## Commands
59
+
60
+ ```bash
61
+ npx orionplace-svelte init [directory]
62
+ npx orionplace-svelte update
63
+ npx orionplace-svelte set backend your-project.orionplace.app
64
+ npx orionplace-svelte add frontend shop.example.com
65
+ npx orionplace-svelte add frontend www.shop.example.com
66
+ npx orionplace-svelte remove frontend www.shop.example.com
67
+ npx orionplace-svelte set mimic shop.example.com
68
+ npx orionplace-svelte help
69
+ ```
70
+
71
+ Either domain command can run first. Both settings are needed for a usable mapping.
72
+ After setup, these npm script aliases are also available:
73
+
74
+ ```bash
75
+ npm run orionplace:backend -- your-project.orionplace.app
76
+ npm run orionplace:add-frontend -- shop.example.com
77
+ npm run orionplace:remove-frontend -- www.shop.example.com
78
+ npm run orionplace:mimic -- shop.example.com
79
+ npm run orionplace:help
80
+ npm run orionplace:update
81
+ ```
82
+
83
+ `npm set` belongs to npm's own configuration system; use the commands above.
84
+ These commands configure local integration files. They do not provision a backend,
85
+ change your account, create DNS records, configure TLS, or deploy a VPS.
86
+
87
+ ## Generated files
88
+
89
+ | Path | Purpose |
90
+ | --- | --- |
91
+ | `src/routes/api/[...orionplace]/+server.ts` | Route serving `/api/...` from your project. |
92
+ | `src/routes/+layout.server.ts` | Initializes AppLoad before your pages render. |
93
+ | `src/routes/+layout.svelte` | Creates the store for this session and puts it in context. |
94
+ | `src/routes/+page.svelte` | Starter page showing the AppLoad state; replace it with your storefront. |
95
+ | `src/hooks.server.ts` | Marks personalized pages `private, no-store` and varies them by domain. |
96
+ | `src/lib/orionplace/` | Server transport with cookie relay, browser transport, envelope checks, domain resolution. |
97
+ | `src/lib/orionplace/store.svelte.ts` | Typed snapshot, status, merged discovery and derived data as Svelte 5 runes. |
98
+ | `src/lib/interfaces/orionplace/` | The AppLoad response envelope and every nested model. |
99
+ | `svelte.config.js`, `vite.config.ts` | Node adapter, and your storefront domains as allowed development hosts. |
100
+ | `orionplace/runtime/marketplace.mjs` | Commented domain lookup and HTTP transport. |
101
+ | `orionplace/README.md` | Your settings, API examples, file explanations, verification and VPS deployment. |
102
+ | `orionplace/settings.json` | Domain values selected by the CLI. |
103
+ | `orionplace/.generated.json` | File hashes used to preserve your edits on subsequent setup. |
104
+ | `sitemaps/shop.example.com.cfg` | One line: `https://your-project.orionplace.app/api`. |
105
+ | `.env` | `MIMIC_FRONT_DOMAIN="shop.example.com"` for localhost. |
106
+
107
+ All generated source is yours to read and customize. Later setup runs preserve
108
+ edited files and report which ones were preserved. Unchanged generated files can
109
+ be refreshed with `npx orionplace-svelte update`. A manually edited domain file is
110
+ never silently overwritten. Keep the hash manifest in version control.
111
+
112
+ ## Multiple frontend domains
113
+
114
+ Each frontend gets its own `sitemaps/<domain>.cfg`. `add frontend` preserves other
115
+ domains and can be repeated safely. `set backend` updates every CLI-managed mapping
116
+ to the new personal API; it refuses to overwrite a manually edited mapping.
117
+
118
+ A new project starts with `MIMIC_FRONT_DOMAIN=""` in `.env`. Setting a backend
119
+ alone leaves it empty. The first added frontend becomes MIMIC; further additions
120
+ preserve that choice. `set mimic <domain>` selects an already-added frontend and
121
+ updates MIMIC without changing any domain mappings. Unknown domains are rejected;
122
+ add them with `add frontend` first.
123
+
124
+ `help`, `--help`, and `-h` display commands without writing files. The legacy
125
+ `set frontend <domain>` shortcut remains supported: it adds and selects a domain.
126
+
127
+ `remove frontend <domain>` removes that domain from the list and deletes only its
128
+ unchanged generated `.cfg`. Removing the MIMIC domain selects the first remaining
129
+ domain. Removing the last one clears MIMIC. Unknown or edited mappings cause a
130
+ clear error without changing files. Unrelated configurations remain untouched.
131
+
132
+ Restart development after domain changes so Vite reloads its allowed hosts and
133
+ SvelteKit reloads `.env`. Production reloads mapping files on each API request;
134
+ reload the process environment when changing MIMIC. Configure DNS, TLS, and the
135
+ hosting proxy for each frontend separately.
136
+
137
+ ## Runtime behavior
138
+
139
+ The hosting proxy must overwrite `X-Front-Domain`, `X-Forwarded-Host`, and `Host`.
140
+ The gateway selects the first valid public domain in that order, with the request
141
+ URL hostname as another fallback. On localhost it uses `MIMIC_FRONT_DOMAIN`.
142
+ An unknown public domain returns `503`; it never uses another domain's mapping.
143
+
144
+ The corresponding `.cfg` is read on every request. Backend URLs must use HTTPS,
145
+ end in `/api`, and belong to `*.orionplace.app`. API methods, query strings, bodies,
146
+ authorization and cookies are forwarded. Backend statuses are retained and cookie
147
+ Domain attributes are removed to bind cookies to the storefront. Gateway responses
148
+ use `Cache-Control: no-store`. Network failures return `502`. Cross-site mutations
149
+ are rejected with `403`.
150
+
151
+ SvelteKit ignores a request body sent without a `Content-Type` header, so always
152
+ set it on your own API calls; browsers do this automatically for `fetch`.
153
+
154
+ Browser requests use `/api/...`. Server loads call the same gateway in process
155
+ through `src/lib/orionplace/appLoadServer.ts`, which forwards the current
156
+ request's domain, cookies and language.
157
+
158
+ Deploy `sitemaps` with the production server, or set an absolute `SITEMAPS_DIR`.
159
+ The production process reads `MIMIC_FRONT_DOMAIN` without rebuilding. Run the
160
+ server from the project root or explicitly point it at the configuration directory.
161
+
162
+ ## AppLoad starter
163
+
164
+ The root layout load awaits `POST /api/appload` in light mode before your pages
165
+ render and returns the snapshot to every route, so `await parent()` in a page load
166
+ reuses it instead of requesting again. The root layout component creates one store
167
+ per browser session and hydrates it from that snapshot; components read it with
168
+ `getOrionplaceContext()`. Reading the store never starts a request, and
169
+ initialization never opens an authentication prompt. `store.refresh()` reloads
170
+ explicitly, and SvelteKit's `invalidateAll()` also works: the layout load runs
171
+ again and the store adopts the new snapshot.
172
+
173
+ Live discovery from `page_data.unauth.paths` and, for a signed-in session,
174
+ `page_data.auth.paths`, is merged into one lookup without mutating the response.
175
+ Discovery describes availability; the backend still checks permissions on each call.
176
+
177
+ ### Session and CSRF cookies
178
+
179
+ AppLoad establishes the guest/customer session and CSRF cookie through HTTP
180
+ `Set-Cookie` headers, not through `page_data.init`. The browser handles the signed
181
+ HttpOnly `sessionid` cookie; never parse, rewrite, log or store its value in the
182
+ store or localStorage. The readable `csrftoken` supplies `X-CSRFToken` for later
183
+ protected requests through the same-origin `/api/` gateway with credentials enabled.
184
+ Read the CSRF cookie again for every action because login can rotate it.
185
+
186
+ During a server render the layout load forwards the incoming cookies and relays
187
+ each backend `Set-Cookie` separately through SvelteKit's cookie API, preserving
188
+ the exact signed value and its attributes. Cookies established this way are also
189
+ visible to later calls in the same render. Never share a cookie jar across visitors.
190
+
191
+ Use `POST /api/csrf_renew` with `{}` to renew CSRF, then re-read the cookie.
192
+ The backend signals CSRF rejection with HTTP `419` and `page_data.csrf: false`;
193
+ a general `403` may mean permissions or origin rejection. Do not automatically
194
+ replay mutations. After confirmed login/logout, reset and refresh AppLoad.
195
+ Those store actions update data; they do not authenticate or delete cookies.
196
+
197
+ ## Update an existing project
198
+
199
+ After the initial setup, use one command to get the latest package and components:
200
+
201
+ ```bash
202
+ npx orionplace-svelte update
203
+ ```
204
+
205
+ It runs the latest CLI, adds new template files, refreshes unchanged generated
206
+ files, updates the package dependency and runs `npm install` to synchronize the
207
+ lockfile and installed dependencies. Edited files are preserved and listed in the
208
+ output. Review their new versions under `node_modules/orionplace-svelte/templates`
209
+ or `runtime` and merge your changes manually when needed. Removed upstream files
210
+ are retained locally; the updater does not delete customer source.
211
+
212
+ Domain mappings, domain settings and `.env` remain unchanged. The command does
213
+ not deploy your application: restart development, or rebuild and redeploy the
214
+ production frontend after updating.
215
+
216
+ ```bash
217
+ npx orionplace-svelte update --dry-run
218
+ npm run orionplace:update
219
+ ```
220
+
221
+ Dry-run downloads the latest CLI into npm's cache to inspect its templates but
222
+ leaves project files and dependencies unchanged. `update --local` applies the
223
+ version of the CLI being executed instead of fetching the latest CLI; it still
224
+ installs project dependencies. Use this only when intentionally selecting a version.
225
+
226
+ Updates require the existing `orionplace/settings.json` and `.generated.json`.
227
+ Conflicting untracked files stop the source update before any writes. If dependency
228
+ installation fails after source generation, run `npm install` and retry `update`.
229
+
230
+ ## Documentation
231
+
232
+ - [Create a SvelteKit frontend](https://orionmarket.place/sandbox/new-project/svelte)
233
+ - [Marketplace API documentation](https://orionmarket.place/sandbox/)
234
+
235
+ ## Development
236
+
237
+ ```bash
238
+ npm install
239
+ npm test
240
+ npm pack --dry-run
241
+ ```
242
+
243
+ The published tarball includes only the CLI, runtime source, README, license,
244
+ starter templates, and package metadata.
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ import { setupProject } from '../src/setup.mjs';
3
+ import { updateProject } from '../src/update.mjs';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { resolve } from 'node:path';
6
+ import { createInterface } from 'node:readline/promises';
7
+
8
+ const help = `Orionplace Svelte setup
9
+
10
+ From zero (Node.js 20.19+ with npm; run from the parent folder):
11
+ npx --yes orionplace-svelte init my-marketplace
12
+ cd my-marketplace
13
+ npm install
14
+ npx orionplace-svelte set backend your-project.orionplace.app
15
+ npx orionplace-svelte add frontend shop.example.com
16
+ npm run dev
17
+
18
+ Replace the backend with the domain from your orionmarket.place profile,
19
+ and the frontend with your storefront domain. Open the local URL printed by Vite;
20
+ the starter's AppLoad state should show Loaded.
21
+
22
+ Commands for an existing project (run from its root):
23
+ npx orionplace-svelte help
24
+ npx orionplace-svelte init [directory]
25
+ npx orionplace-svelte update
26
+ npx orionplace-svelte set backend <personal-backend.orionplace.app>
27
+ npx orionplace-svelte add frontend <shop.example.com>
28
+ npx orionplace-svelte remove frontend <shop.example.com>
29
+ npx orionplace-svelte set mimic <existing-frontend.example.com>
30
+ npx orionplace-svelte set frontend <shop.example.com>
31
+
32
+ Options: --cwd <directory> --dry-run --help --version
33
+ Update option: --local (apply this CLI version instead of fetching the latest release)
34
+
35
+ Update downloads the latest release, refreshes unedited source, and installs dependencies.
36
+ It preserves edited source, domain mappings and MIMIC. --dry-run leaves project files unchanged.
37
+ Set backend or add frontend also initializes the integration; either can come first.
38
+ MIMIC starts empty. The first added frontend sets it; later additions preserve it.
39
+ Set mimic selects an existing frontend without changing any domain mappings.
40
+ Set frontend is the legacy shortcut to add and select a frontend.
41
+ Set backend updates every managed frontend mapping. Remove frontend deletes only that mapping.
42
+ After creating a new project, run npm install and npm run dev in that directory.
43
+ Documentation and editable gateway source are generated in orionplace/.
44
+ Your SvelteKit source is generated under src/, beside that gateway.`;
45
+ try {
46
+ const argv = process.argv.slice(2);
47
+ if (!argv.length || argv[0] === 'help' || argv.includes('--help') || argv.includes('-h')) {
48
+ console.log(help);
49
+ } else if (argv.includes('--version')) {
50
+ console.log(JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version);
51
+ } else {
52
+ const positional = [];
53
+ let cwd = process.cwd();
54
+ let dryRun = false;
55
+ let local = false;
56
+ for (let index = 0; index < argv.length; index++) {
57
+ if (argv[index] === '--dry-run') dryRun = true;
58
+ else if (argv[index] === '--local') local = true;
59
+ else if (argv[index] === '--cwd') {
60
+ if (!argv[index + 1]) throw new Error('--cwd needs a directory');
61
+ cwd = resolve(argv[++index]);
62
+ } else if (argv[index].startsWith('--')) throw new Error(`Unknown option: ${argv[index]}`);
63
+ else positional.push(argv[index]);
64
+ }
65
+ const [command, target] = positional;
66
+ if (local && command !== 'update') throw new Error('--local is only supported by update.');
67
+ let result;
68
+ if (command === 'init' && positional.length <= 2) {
69
+ result = await setupProject({ cwd: target ? resolve(cwd, target) : cwd, dryRun });
70
+ } else if (command === 'update' && positional.length === 1) {
71
+ result = await updateProject({ cwd, dryRun, local });
72
+ } else if (((command === 'set' && ['backend', 'frontend', 'mimic'].includes(target)) ||
73
+ (['add', 'remove'].includes(command) && target === 'frontend')) && positional.length <= 3) {
74
+ let value = positional[2];
75
+ if (!value && process.stdin.isTTY) {
76
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
77
+ try { value = await prompt.question(`${target === 'backend' ? 'Personal backend API' : target === 'mimic' ? 'Existing frontend to use for MIMIC' : 'Public frontend domain'}: `); }
78
+ finally { prompt.close(); }
79
+ }
80
+ if (!value) throw new Error(`Provide the ${target} domain. See --help.`);
81
+ result = await setupProject({ cwd, action: command, field: target, value, dryRun });
82
+ } else throw new Error('Unknown command. See --help.');
83
+ if (result) {
84
+ console.log(`${dryRun ? 'Planned' : 'Updated'} ${result.root}`);
85
+ for (const path of result.changed) console.log(` ${result.removed.includes(path) ? 'Remove: ' : ''}${path}`);
86
+ for (const path of result.preserved) console.log(` Preserved your edits: ${path}`);
87
+ for (const path of result.skipped) console.log(` Kept your file, merge the starter manually: ${path}`);
88
+ console.log(result.settings.backend && result.settings.frontend
89
+ ? `Ready: ${result.settings.frontends.join(', ')} -> ${result.settings.backend}\nLocal MIMIC: ${result.settings.frontend}`
90
+ : `Next: ${result.settings.backend ? 'add frontend' : 'set backend'} to complete the domain mapping.`);
91
+ if (result.changed.some(path => path.endsWith('.cfg') || path === '.env')) console.log('Restart a running development server to reload MIMIC and domain mappings. Reload your production environment when changing MIMIC.');
92
+ if (result.isNewKit) console.log('Run npm install in the project, then npm run dev.');
93
+ console.log('Project documentation: orionplace/README.md');
94
+ if (command === 'update') console.log(dryRun
95
+ ? 'Dependency installation would run after applying these changes. Project files were not changed.'
96
+ : 'Update complete. Restart development, or rebuild and redeploy your production frontend.');
97
+ }
98
+ }
99
+ } catch (error) {
100
+ console.error(`Orionplace: ${error.message}`);
101
+ process.exitCode = 1;
102
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "orionplace-svelte",
3
+ "version": "0.1.0",
4
+ "description": "SvelteKit integration and setup CLI for your Orionplace personal marketplace backend.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Orionplace",
8
+ "homepage": "https://orionmarket.place/sandbox/new-project/svelte",
9
+ "keywords": [
10
+ "svelte",
11
+ "sveltekit",
12
+ "orionplace",
13
+ "marketplace"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20.19.0"
17
+ },
18
+ "bin": {
19
+ "orionplace-svelte": "./bin/orionplace-svelte.mjs"
20
+ },
21
+ "main": "./runtime/marketplace.mjs",
22
+ "types": "./runtime/marketplace.d.mts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./runtime/marketplace.d.mts",
26
+ "import": "./runtime/marketplace.mjs"
27
+ },
28
+ "./runtime": {
29
+ "types": "./runtime/marketplace.d.mts",
30
+ "import": "./runtime/marketplace.mjs"
31
+ }
32
+ },
33
+ "files": [
34
+ "bin",
35
+ "src",
36
+ "runtime",
37
+ "templates",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "scripts": {
42
+ "test": "node --test test/*.test.mjs"
43
+ },
44
+ "peerDependencies": {
45
+ "@sveltejs/kit": "^2.4.0",
46
+ "svelte": "^5.0.0"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "registry": "https://registry.npmjs.org/"
51
+ },
52
+ "devDependencies": {
53
+ "esbuild": "^0.27.7",
54
+ "svelte": "^5.57.0"
55
+ }
56
+ }
@@ -0,0 +1,22 @@
1
+ export interface MarketplaceConfiguration {
2
+ mimicFrontDomain?: string;
3
+ }
4
+
5
+ export interface MarketplaceTenant {
6
+ domain: string;
7
+ api: URL;
8
+ }
9
+
10
+ export declare function normalizeFrontDomain(value: unknown): string | null;
11
+
12
+ export declare function resolveFrontDomain(request: Request, mimic?: string): string | null;
13
+
14
+ export declare function readMarketplace(
15
+ request: Request,
16
+ configuration?: MarketplaceConfiguration,
17
+ ): Promise<MarketplaceTenant>;
18
+
19
+ export declare function forwardMarketplace(
20
+ request: Request,
21
+ configuration?: MarketplaceConfiguration,
22
+ ): Promise<Response>;
@@ -0,0 +1,211 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { isIP } from 'node:net';
4
+
5
+ const environment = process.env;
6
+
7
+ const hostnamePattern =
8
+ /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
9
+
10
+ /** @param {unknown} value */
11
+ export function normalizeFrontDomain(value) {
12
+ if (typeof value !== 'string') return null;
13
+ const domain = value.split(',')[0].trim().toLowerCase().replace(/\.$/, '');
14
+ return hostnamePattern.test(domain) && !isIP(domain) ? domain : null;
15
+ }
16
+
17
+ /** @param {Request} request @param {string} mimic */
18
+ export function resolveFrontDomain(
19
+ request,
20
+ mimic = environment.MIMIC_FRONT_DOMAIN || '',
21
+ ) {
22
+ // The hosting proxy must overwrite these headers. Public hosts win over MIMIC.
23
+ for (const candidate of [
24
+ request.headers.get('x-front-domain'),
25
+ request.headers.get('x-forwarded-host'),
26
+ request.headers.get('host'),
27
+ new URL(request.url).hostname,
28
+ ]) {
29
+ const domain = normalizeFrontDomain(candidate);
30
+ if (domain) return domain;
31
+ }
32
+ return normalizeFrontDomain(mimic);
33
+ }
34
+
35
+ /** @param {Request} request @param {{mimicFrontDomain?: string}} configuration */
36
+ export async function readMarketplace(request, configuration = {}) {
37
+ const domain = resolveFrontDomain(request, configuration.mimicFrontDomain);
38
+ if (!domain) throw new Error('Invalid storefront domain');
39
+
40
+ const directory = environment.SITEMAPS_DIR || resolve('sitemaps');
41
+ const source = await readFile(resolve(directory, `${domain}.cfg`), 'utf8');
42
+ const lines = source
43
+ .split(/\r?\n/)
44
+ .map((line) => line.trim())
45
+ .filter((line) => line && !line.startsWith('#'));
46
+ if (lines.length !== 1) throw new Error('Expected one API URL');
47
+ const value = lines[0];
48
+ const api = new URL(value.includes('://') ? value : `https://${value}`);
49
+ api.pathname = api.pathname.replace(/\/+$/, '');
50
+ if (
51
+ api.protocol !== 'https:' ||
52
+ !hostnamePattern.test(api.hostname) ||
53
+ !api.hostname.endsWith('.orionplace.app') ||
54
+ isIP(api.hostname) ||
55
+ api.port ||
56
+ api.username ||
57
+ api.password ||
58
+ api.search ||
59
+ api.hash ||
60
+ api.pathname !== '/api'
61
+ ) {
62
+ throw new Error('Expected https://<project>.orionplace.app/api');
63
+ }
64
+ return { domain, api };
65
+ }
66
+
67
+ /** @param {number} status @param {string} message */
68
+ function failure(status, message) {
69
+ return Response.json(
70
+ { error: message },
71
+ {
72
+ status,
73
+ headers: {
74
+ 'Cache-Control': 'no-store',
75
+ 'Vary': 'Host, X-Forwarded-Host, X-Front-Domain',
76
+ },
77
+ },
78
+ );
79
+ }
80
+
81
+ /** @param {Request} request @param {{mimicFrontDomain?: string}} configuration */
82
+ export async function forwardMarketplace(request, configuration = {}) {
83
+ let tenant;
84
+ try {
85
+ tenant = await readMarketplace(request, configuration);
86
+ } catch {
87
+ return failure(
88
+ 503,
89
+ 'Storefront domain configuration is missing or invalid',
90
+ );
91
+ }
92
+
93
+ const incoming = new URL(request.url);
94
+ if (!incoming.pathname.startsWith('/api/'))
95
+ return failure(404, 'Unknown API path');
96
+ // Prevent encoded separators or traversal from escaping the /api namespace.
97
+ let path;
98
+ try {
99
+ path = decodeURIComponent(incoming.pathname);
100
+ } catch {
101
+ return failure(400, 'Invalid API path');
102
+ }
103
+ if (
104
+ path.includes('\\') ||
105
+ /%(?:2e|2f|5c)/i.test(path) ||
106
+ path.split('/').some((part) => part === '.' || part === '..')
107
+ ) {
108
+ return failure(400, 'Invalid API path');
109
+ }
110
+ const target = new URL(
111
+ incoming.pathname + incoming.search,
112
+ tenant.api.origin,
113
+ );
114
+ if (!target.pathname.startsWith('/api/'))
115
+ return failure(400, 'Invalid API path');
116
+
117
+ const origin = request.headers.get('origin');
118
+ const publicHost = request.headers.get('host') || incoming.host;
119
+ const originHosts = [publicHost, tenant.domain];
120
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {
121
+ try {
122
+ if (
123
+ request.headers.get('sec-fetch-site') === 'cross-site' ||
124
+ (origin && !originHosts.includes(new URL(origin).host))
125
+ ) {
126
+ return failure(403, 'Cross-site API request rejected');
127
+ }
128
+ } catch {
129
+ return failure(403, 'Invalid Origin');
130
+ }
131
+ }
132
+
133
+ // An allowlist excludes hop-by-hop and client-supplied routing headers.
134
+ const headers = new Headers();
135
+ for (const name of [
136
+ 'accept',
137
+ 'content-type',
138
+ 'authorization',
139
+ 'cookie',
140
+ 'origin',
141
+ 'referer',
142
+ 'x-csrftoken',
143
+ 'accept-language',
144
+ 'user-agent',
145
+ 'x-tz',
146
+ ]) {
147
+ const value = request.headers.get(name);
148
+ if (value) headers.set(name, value);
149
+ }
150
+ headers.set('X-Front-Domain', tenant.domain);
151
+ headers.set('Accept-Encoding', 'identity');
152
+ const clientIp =
153
+ request.headers.get('x-init-ip') ||
154
+ request.headers.get('x-real-ip') ||
155
+ request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
156
+ if (clientIp) headers.set('X-Init-Ip', clientIp);
157
+ /** @type {RequestInit & { duplex: 'half' }} */
158
+ const options = {
159
+ method: request.method,
160
+ headers,
161
+ redirect: 'manual',
162
+ cache: 'no-store',
163
+ signal: AbortSignal.any([request.signal, AbortSignal.timeout(30_000)]),
164
+ duplex: 'half',
165
+ };
166
+ if (!['GET', 'HEAD'].includes(request.method)) options.body = request.body;
167
+
168
+ let upstream;
169
+ try {
170
+ upstream = await fetch(target, options);
171
+ } catch {
172
+ return failure(502, 'Marketplace backend is unavailable');
173
+ }
174
+
175
+ const responseHeaders = new Headers();
176
+ for (const name of [
177
+ 'content-type',
178
+ 'content-disposition',
179
+ 'www-authenticate',
180
+ 'retry-after',
181
+ 'allow',
182
+ ]) {
183
+ const value = upstream.headers.get(name);
184
+ if (value) responseHeaders.set(name, value);
185
+ }
186
+ // Keep each cookie separate; remove the backend Domain attribute only.
187
+ for (const cookie of upstream.headers.getSetCookie()) {
188
+ responseHeaders.append(
189
+ 'Set-Cookie',
190
+ cookie.replace(/;\s*Domain=[^;]*/gi, ''),
191
+ );
192
+ }
193
+ const location = upstream.headers.get('location');
194
+ if (location) {
195
+ const destination = new URL(location, target);
196
+ responseHeaders.set(
197
+ 'Location',
198
+ destination.origin === tenant.api.origin
199
+ ? destination.pathname + destination.search + destination.hash
200
+ : destination.href,
201
+ );
202
+ }
203
+ responseHeaders.set('Cache-Control', 'no-store');
204
+ responseHeaders.set('Vary', 'Host, X-Forwarded-Host, X-Front-Domain');
205
+ // fetch decodes compressed bodies: do not reuse upstream Content-Length/Encoding.
206
+ return new Response(upstream.body, {
207
+ status: upstream.status,
208
+ statusText: upstream.statusText,
209
+ headers: responseHeaders,
210
+ });
211
+ }