create-anyo-world 0.0.0-stage → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,634 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, writeFile, access } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import process from 'node:process'
5
+ import readline from 'node:readline/promises'
6
+ import { stdin as input, stdout as output } from 'node:process'
7
+
8
+ const VERSION = '0.6.1'
9
+ const ANYO_TOOLING_VERSION = '0.11.0-rc.37'
10
+ const HELP = `create-anyo-world ${VERSION}\n\nUsage:\n npm create anyo-world@latest my-world -- --lat=14.556201 --lng=121.024261\n npm create anyo-world@latest my-world -- --mode=loader --github=blcklab/my-world\n npm create anyo-world@latest my-world -- --mode=both --lat=14.556201 --lng=121.024261 --github=blcklab/my-world --web-surface=dashboard --web-resolution=full-hd\n\nOptions:\n --mode=<atlas|loader|both> Target workflow (default: atlas)\n --title=<name> Display title\n --lat=<latitude> World latitude (Atlas/both mode)\n --lng=<longitude> World longitude (Atlas/both mode)\n --zoom=<3-20> Preferred Atlas zoom (default: 20)\n --osm=<type/id> Optional exact OSM binding\n --github=<user/repo> GitHub repository used by Atlas/World Loader links\n --ref=<git-ref> Optional immutable tag/commit/branch\n --web-surface[=<app-id>] Add a repository-hosted Web Surface app (default id: dashboard)\n --web-resolution=<quality> 360p, 540p, 720p/hd, or 1080p/full-hd (default: hd)\n --modular Scaffold models/ with a native Anyo Object 0.1 example\n --force Write into a non-empty/existing project directory\n --version Show version\n --help Show this help\n`
11
+
12
+ function parseArgs(argv) {
13
+ const options = { force: false }
14
+ const positional = []
15
+ for (const arg of argv) {
16
+ if (arg === '--help' || arg === '-h') options.help = true
17
+ else if (arg === '--version' || arg === '-v') options.version = true
18
+ else if (arg === '--force') options.force = true
19
+ else if (arg === '--modular') options.modular = true
20
+ else if (arg === '--web-surface') options['web-surface'] = true
21
+ else if (arg.startsWith('--') && arg.includes('=')) {
22
+ const [key, ...rest] = arg.slice(2).split('=')
23
+ options[key] = rest.join('=')
24
+ } else if (!arg.startsWith('-')) positional.push(arg)
25
+ else throw new Error(`Unknown option ${arg}`)
26
+ }
27
+ return { projectName: positional[0] || null, options }
28
+ }
29
+
30
+ function slug(value) {
31
+ const result = String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '')
32
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(result) || result.length > 214) throw new Error('Project name must begin with a letter or number and be a portable npm package name.')
33
+ return result
34
+ }
35
+ function titleFromSlug(value) { return value.split(/[-_.]+/g).filter(Boolean).map(part => part[0].toUpperCase() + part.slice(1)).join(' ') }
36
+ function coordinate(value, limit, label) {
37
+ const number = String(value ?? '').trim() === '' ? NaN : Number(value)
38
+ if (!Number.isFinite(number) || Math.abs(number) > limit) throw new Error(`${label} must be a finite value between -${limit} and ${limit}.`)
39
+ return number
40
+ }
41
+ function zoom(value) {
42
+ const number = Number(value ?? 20)
43
+ if (!Number.isFinite(number) || number < 3 || number > 20) throw new Error('Zoom must be between 3 and 20.')
44
+ return number
45
+ }
46
+ function normalizeMode(value) {
47
+ const raw = String(value || 'atlas').trim().toLowerCase()
48
+ if (raw === 'world-loader') return 'loader'
49
+ if (!['atlas', 'loader', 'both'].includes(raw)) throw new Error('--mode must be atlas, loader, or both.')
50
+ return raw
51
+ }
52
+ function parseOsm(value) {
53
+ if (!value) return null
54
+ const match = String(value).trim().match(/^(node|way|relation)[/:](.+)$/i)
55
+ if (!match || !match[2].trim()) throw new Error('--osm must look like way/9200000033, relation/123, or node/123.')
56
+ return { provider: 'openstreetmap', type: match[1].toLowerCase(), id: match[2].trim() }
57
+ }
58
+ function lotId(latitude, longitude, osm) { return osm ? `osm:${osm.type}:${osm.id}` : `geo:${latitude.toFixed(6)}:${longitude.toFixed(6)}` }
59
+ function normalizeGitHubRepository(value) {
60
+ if (!value) return null
61
+ let raw = String(value).trim().replace(/^https?:\/\/github\.com\//i, '').replace(/\.git$/i, '').replace(/^\/+|\/+$/g, '')
62
+ const parts = raw.split('/').filter(Boolean)
63
+ if (parts.length !== 2) throw new Error('--github must look like owner/repository.')
64
+ const owner = parts[0]
65
+ const repository = parts[1].replace(/\.git$/i, '')
66
+ if (!/^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/.test(owner) || owner.includes('--') || owner.endsWith('-')) throw new Error('--github owner is not valid.')
67
+ if (!repository || repository.length > 100 || !/^[A-Za-z0-9._-]+$/.test(repository) || repository === '.' || repository === '..') throw new Error('--github repository is not valid.')
68
+ return `${owner}/${repository}`
69
+ }
70
+ function normalizeRef(value) {
71
+ const raw = String(value || '').trim()
72
+ if (!raw) return null
73
+ if (raw.length > 200 || !/^[A-Za-z0-9._-]+$/.test(raw) || raw === '.' || raw === '..' || raw.includes('..')) throw new Error('--ref must be a simple branch, tag, or commit name.')
74
+ return raw
75
+ }
76
+ function normalizeWebAppId(value) {
77
+ if (value === undefined || value === false || value === null || value === '') return null
78
+ const raw = value === true ? 'dashboard' : String(value).trim()
79
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(raw)) throw new Error('--web-surface must use a portable app id containing only letters, numbers, dot, underscore, or dash.')
80
+ return raw
81
+ }
82
+ const WEB_RESOLUTIONS = Object.freeze({
83
+ low: [640, 360], '360p': [640, 360],
84
+ balanced: [960, 540], '540p': [960, 540],
85
+ hd: [1280, 720], '720p': [1280, 720],
86
+ 'full-hd': [1920, 1080], '1080p': [1920, 1080],
87
+ })
88
+ function webResolution(value) {
89
+ const key = String(value || 'hd').trim().toLowerCase()
90
+ const resolution = WEB_RESOLUTIONS[key]
91
+ if (!resolution) throw new Error('--web-resolution must be 360p, 540p, 720p/hd, or 1080p/full-hd.')
92
+ return [...resolution]
93
+ }
94
+ async function exists(file) { try { await access(file); return true } catch { return false } }
95
+ function json(value) { return JSON.stringify(value, null, 2) + '\n' }
96
+
97
+ function projectDocument({ id, title, atlasEnabled }) {
98
+ return {
99
+ schema: 'anyo-project@1',
100
+ id,
101
+ title,
102
+ world: './world.anyo.json',
103
+ directories: {
104
+ assets: './assets/',
105
+ webSurfaces: './web-surface/',
106
+ },
107
+ ...(atlasEnabled ? { manifests: { atlas: './atlas.world.json' } } : {}),
108
+ }
109
+ }
110
+
111
+ function webSurfaceEntity(appId, resolution) {
112
+ return {
113
+ id: `web/${appId}`,
114
+ type: 'web-surface',
115
+ size: [4.8, 2.7],
116
+ surface: { room: 'main', wall: 'north', offset: [0, 0.1] },
117
+ webSurface: {
118
+ source: { type: 'app', app: appId },
119
+ target: { type: 'plane', size: [4.8, 2.7] },
120
+ presentation: {
121
+ type: 'texture',
122
+ resolution,
123
+ fit: 'contain',
124
+ side: 'double',
125
+ emissive: { color: '#ffffff', intensity: 1.08, useTexture: true },
126
+ },
127
+ fallback: { type: 'snapshot', image: './assets/web-surface-fallback.svg' },
128
+ framePolicy: { mode: 'on-change' },
129
+ },
130
+ }
131
+ }
132
+
133
+ function worldDocument({ id, title, latitude = null, longitude = null, atlasEnabled = true, webApp = null, modular = false }) {
134
+ const entities = []
135
+ if (atlasEnabled) {
136
+ entities.push(
137
+ { id: 'map-exterior', type: 'group', components: [{ type: 'anyo.mapExterior' }], children: [
138
+ { id: 'map-exterior-wall-north', type: 'box', position: [0, 2.1, -4], size: [8, 4.2, 0.18], material: 'wall', collision: true },
139
+ { id: 'map-exterior-wall-west', type: 'box', position: [-4, 2.1, 0], size: [0.18, 4.2, 8], material: 'wall', collision: true },
140
+ { id: 'map-exterior-wall-east', type: 'box', position: [4, 2.1, 0], size: [0.18, 4.2, 8], material: 'wall', collision: true },
141
+ { id: 'map-exterior-wall-south-left', type: 'box', position: [-2.5, 2.1, 4], size: [3, 4.2, 0.18], material: 'wall', collision: true },
142
+ { id: 'map-exterior-wall-south-right', type: 'box', position: [2.5, 2.1, 4], size: [3, 4.2, 0.18], material: 'wall', collision: true },
143
+ { id: 'map-exterior-roof', type: 'box', position: [0, 4.25, 0], size: [8.1, 0.18, 8.1], material: 'wall', collision: false },
144
+ ] },
145
+ )
146
+ }
147
+ if (webApp) entities.push(webSurfaceEntity(webApp.id, webApp.resolution))
148
+ else entities.push({ id: 'welcome', type: 'text', content: title.toUpperCase(), size: [4.6, 0.8], surface: { room: 'main', wall: 'north', offset: [0, 0.65] }, style: { fontSize: 0.22, fontWeight: 750, color: '#172033' } })
149
+ entities.push(modular
150
+ ? { id: 'centerpiece', composition: 'centerpiece', room: 'main', position: [0, 1, -1.5] }
151
+ : { id: 'centerpiece', type: 'box', room: 'main', position: [0, 1, -1.5], size: [1.4, 1.4, 1.4], material: 'accent', collision: true })
152
+ if (atlasEnabled) {
153
+ entities.push(
154
+ { id: 'map-main-entrance', type: 'group', room: 'main', position: [0, 1.65, 3.1], components: [{ type: 'anyo.mapSpawn' }] },
155
+ { id: 'map-interior-exit', type: 'group', room: 'main', position: [0, 1.35, 3.72], components: [{ type: 'anyo.mapExit', label: 'Return outside', transition: 'stream', interactionDistance: 4 }], children: [
156
+ { id: 'map-exit-frame-left', type: 'box', position: [-1.21, 0, 0.02], size: [0.08, 2.7, 0.08], material: 'map-exit-marker', collision: false, castShadow: false, receiveShadow: false },
157
+ { id: 'map-exit-frame-right', type: 'box', position: [1.21, 0, 0.02], size: [0.08, 2.7, 0.08], material: 'map-exit-marker', collision: false, castShadow: false, receiveShadow: false },
158
+ { id: 'map-exit-frame-top', type: 'box', position: [0, 1.31, 0.02], size: [2.5, 0.08, 0.08], material: 'map-exit-marker', collision: false, castShadow: false, receiveShadow: false },
159
+ { id: 'map-exit-threshold', type: 'box', position: [0, -1.315, 0.08], size: [1.95, 0.07, 0.28], material: 'map-exit-marker', collision: false, castShadow: false, receiveShadow: false },
160
+ { id: 'map-exit-label', type: 'text', position: [0, 1.67, 0.03], text: 'E · EXIT', fontSize: 0.17, color: '#fff7d6', align: 'center', castShadow: false },
161
+ ] },
162
+ )
163
+ }
164
+
165
+ const data = {}
166
+ if (latitude !== null && longitude !== null) {
167
+ data.location = { name: title, latitude, longitude, coordinates: `${latitude.toFixed(6)}, ${longitude.toFixed(6)}` }
168
+ }
169
+ if (atlasEnabled) {
170
+ data.atlas = { entrance: { room: 'main', opening: 'entrance', targetSpawn: 'map-main-entrance', interactionDistance: 3.4, marker: 'none' } }
171
+ }
172
+
173
+ return {
174
+ $schema: 'https://anyo.blcklab.dev/schemas/world-0.9.schema.json',
175
+ version: '0.9',
176
+ metadata: {
177
+ title,
178
+ description: atlasEnabled ? `${title}, a portable Anyo world for Atlas and World Loader.` : `${title}, a portable Anyo world for World Loader.`,
179
+ ...(webApp ? { webSurface: `Repository app "${webApp.id}" is discovered by World Loader from web-surface/${webApp.id}/web-surface.json.` } : {}),
180
+ },
181
+ ...(modular ? { imports: { centerpiece: { src: './models/centerpiece.anyo.json' } } } : {}),
182
+ ...(Object.keys(data).length ? { data } : {}),
183
+ environment: {
184
+ background: '#111827',
185
+ ambientLight: { color: '#eef2ff', intensity: 0.28 },
186
+ lighting: { enabled: true, skyColor: '#aab8d0', groundColor: '#1c2533', diffuseIntensity: 0.34, specularIntensity: 0.22 },
187
+ colorManagement: { toneMapping: 'aces', exposure: 1, outputColorSpace: 'srgb' },
188
+ shadows: { enabled: true, mapSize: 1024, bias: 0.0008, normalBias: 0.015, softness: 1, cameraPadding: 2 },
189
+ imageQuality: { dithering: true, maxAnisotropy: 4 },
190
+ sun: { color: '#ffffff', intensity: 0.78, position: [7, 10, 6], castShadow: true },
191
+ },
192
+ materials: {
193
+ wall: { color: '#e8edf5', roughness: 0.9, receiveShadow: true, castShadow: true },
194
+ floor: { color: '#65748a', roughness: 0.7, receiveShadow: true, castShadow: true },
195
+ ...(!modular ? { accent: { color: '#7dd3fc', roughness: 0.35, metalness: 0.2, receiveShadow: true, castShadow: true } } : {}),
196
+ 'map-exit-marker': { color: '#f5c76d', roughness: 0.24, emissive: '#f5b942', emissiveIntensity: 0.7, transparent: true, opacity: 0.78 },
197
+ },
198
+ building: {
199
+ id,
200
+ name: title,
201
+ floors: [{ id: 'ground', elevation: 0, rooms: [{ id: 'main', size: [8, 8], materials: { wall: 'wall', floor: 'floor' }, openings: [{ id: 'entrance', type: 'door', wall: 'south', offset: 'center', width: 2, height: 2.5, open: true }] }] }],
202
+ },
203
+ entities,
204
+ exploration: { spawn: { room: 'main', position: [0, 1.65, 2.5] }, pointerLock: true },
205
+ revision: 0,
206
+ }
207
+ }
208
+
209
+
210
+ function modularObjectDocument({ title }) {
211
+ return {
212
+ $schema: 'https://anyo.blcklab.dev/schemas/object-0.1.schema.json',
213
+ kind: 'anyo-object',
214
+ version: '0.1',
215
+ metadata: {
216
+ title: `${title} Centerpiece`,
217
+ description: 'Example reusable native Anyo object generated by create-anyo-world.',
218
+ },
219
+ materials: {
220
+ accent: { color: '#7dd3fc', roughness: 0.35, metalness: 0.2, receiveShadow: true, castShadow: true },
221
+ },
222
+ root: {
223
+ id: 'centerpiece-root',
224
+ type: 'group',
225
+ children: [{
226
+ id: 'centerpiece-body',
227
+ type: 'box',
228
+ size: [1.4, 1.4, 1.4],
229
+ material: 'accent',
230
+ collision: true,
231
+ }],
232
+ },
233
+ }
234
+ }
235
+
236
+ function anyoDocumentsSource() {
237
+ return `import { readFile, realpath } from 'node:fs/promises'
238
+ import path from 'node:path'
239
+
240
+ const PROJECT_PROTOCOL = 'anyo-project:'
241
+ const PROJECT_HOST = 'root'
242
+ const PROJECT_BASE = 'anyo-project://root/'
243
+ const projectRoot = await realpath(path.resolve('.'))
244
+ const projectRootPrefix = projectRoot.endsWith(path.sep) ? projectRoot : projectRoot + path.sep
245
+
246
+ export const rootWorldUrl = new URL('world.anyo.json', PROJECT_BASE).href
247
+ export const rootSourceContext = Object.freeze({ documentUrl: rootWorldUrl, baseUrl: PROJECT_BASE })
248
+
249
+ function insideProject(file) {
250
+ return file === projectRoot || file.startsWith(projectRootPrefix)
251
+ }
252
+
253
+ function projectPathFromUrl(rawUrl) {
254
+ const url = new URL(rawUrl)
255
+ if (url.protocol !== PROJECT_PROTOCOL || url.hostname !== PROJECT_HOST) {
256
+ throw new Error('Generated Anyo tooling resolves local project imports only: ' + rawUrl)
257
+ }
258
+ if (url.search || url.hash) throw new Error('Local Anyo object imports may not contain query strings or fragments: ' + rawUrl)
259
+ const relative = decodeURIComponent(url.pathname).replace(/^\\/+/, '')
260
+ const candidate = path.resolve(projectRoot, relative)
261
+ if (!insideProject(candidate)) throw new Error('Anyo import escapes the generated project root: ' + rawUrl)
262
+ return candidate
263
+ }
264
+
265
+ export async function readRootWorld() {
266
+ const sourceText = await readFile(path.join(projectRoot, 'world.anyo.json'), 'utf8')
267
+ return { document: JSON.parse(sourceText), sourceText }
268
+ }
269
+
270
+ export async function loadProjectAnyoDocument(request) {
271
+ const candidate = projectPathFromUrl(request.url)
272
+ const actual = await realpath(candidate)
273
+ if (!insideProject(actual)) throw new Error('Anyo import resolves outside the generated project root: ' + request.url)
274
+ const sourceText = await readFile(actual, 'utf8')
275
+ let document
276
+ try { document = JSON.parse(sourceText) }
277
+ catch (error) { throw new Error('Invalid JSON in ' + request.url + ': ' + (error instanceof Error ? error.message : String(error))) }
278
+ return { document, documentUrl: request.url, sourceText }
279
+ }
280
+
281
+ function portableProjectString(value, outputFile) {
282
+ let url
283
+ try { url = new URL(value) } catch { return value }
284
+ if (url.protocol !== PROJECT_PROTOCOL || url.hostname !== PROJECT_HOST) return value
285
+ const relativeProjectPath = decodeURIComponent(url.pathname).replace(/^\\/+/, '')
286
+ const target = path.resolve(projectRoot, relativeProjectPath)
287
+ if (!insideProject(target)) throw new Error('Bundled URL escapes the generated project root: ' + value)
288
+ const outputDirectory = path.dirname(path.resolve(projectRoot, outputFile))
289
+ let relative = path.relative(outputDirectory, target).split(path.sep).join('/')
290
+ if (!relative.startsWith('.')) relative = './' + relative
291
+ return relative + url.search + url.hash
292
+ }
293
+
294
+ export function makeProjectUrlsPortable(value, outputFile = 'dist/world.anyo.json') {
295
+ if (typeof value === 'string') return portableProjectString(value, outputFile)
296
+ if (Array.isArray(value)) return value.map(entry => makeProjectUrlsPortable(entry, outputFile))
297
+ if (value && typeof value === 'object') {
298
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, makeProjectUrlsPortable(entry, outputFile)]))
299
+ }
300
+ return value
301
+ }
302
+ `
303
+ }
304
+
305
+ function devServerSource() {
306
+ return `import { createReadStream, existsSync } from 'node:fs'
307
+ import { stat, realpath } from 'node:fs/promises'
308
+ import { createServer } from 'node:http'
309
+ import { extname, join, resolve, sep } from 'node:path'
310
+
311
+ const root = await realpath(resolve('.'))
312
+
313
+ function option(name, fallback) {
314
+ const exact = process.argv.find(argument => argument.startsWith(name + '='))
315
+ if (exact) return exact.slice(name.length + 1)
316
+ const index = process.argv.indexOf(name)
317
+ if (index >= 0 && process.argv[index + 1] && !process.argv[index + 1].startsWith('--')) return process.argv[index + 1]
318
+ return fallback
319
+ }
320
+
321
+ const host = String(option('--host', process.env.HOST || '127.0.0.1')).trim() || '127.0.0.1'
322
+ const rawPort = String(option('--port', process.env.PORT || '4174')).trim()
323
+ const port = Number(rawPort)
324
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
325
+ console.error('Anyo world dev server: --port must be an integer from 1 to 65535')
326
+ process.exit(1)
327
+ }
328
+
329
+ const mime = new Map([
330
+ ['.json','application/json; charset=utf-8'],['.html','text/html; charset=utf-8'],['.css','text/css; charset=utf-8'],
331
+ ['.js','text/javascript; charset=utf-8'],['.mjs','text/javascript; charset=utf-8'],['.svg','image/svg+xml'],
332
+ ['.glb','model/gltf-binary'],['.gltf','model/gltf+json'],['.png','image/png'],['.jpg','image/jpeg'],['.jpeg','image/jpeg'],
333
+ ['.webp','image/webp'],['.gif','image/gif'],['.ico','image/x-icon'],['.woff','font/woff'],['.woff2','font/woff2'],['.hdr','image/vnd.radiance'],['.vrm','model/gltf-binary'],['.vrma','model/gltf-binary'],['.ktx2','image/ktx2'],['.wasm','application/wasm'],['.mp3','audio/mpeg'],['.ogg','audio/ogg'],['.mp4','video/mp4'],['.webm','video/webm']
334
+ ])
335
+ const cors = { 'access-control-allow-origin':'*', 'cache-control':'no-store' }
336
+ const server = createServer(async (req,res) => {
337
+ const fail = (status, message) => { res.writeHead(status,cors); res.end(message) }
338
+ if (req.method === 'OPTIONS') { res.writeHead(204,{...cors,'access-control-allow-methods':'GET, HEAD, OPTIONS','access-control-allow-headers':'Range'}); return res.end() }
339
+ if (!['GET','HEAD'].includes(req.method)) return fail(405,'Method not allowed')
340
+ try {
341
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
342
+ let pathname = decodeURIComponent(url.pathname)
343
+ if (pathname === '/') pathname = existsSync(join(root,'atlas.world.json')) ? '/atlas.world.json' : '/world.anyo.json'
344
+ const segments = pathname.split('/')
345
+ if (segments.some(part => part.startsWith('.') || part === 'node_modules') || segments[1] === 'scripts' || pathname.includes(String.fromCharCode(92))) return fail(404,'Not found')
346
+ const file = resolve(root,'.'+pathname)
347
+ if (!file.startsWith(root+sep)) return fail(404,'Not found')
348
+ const actual = await realpath(file)
349
+ if (!actual.startsWith(root+sep) || actual.slice(root.length+1).split(sep).some(part => part.startsWith('.') || part === 'node_modules') || actual.slice(root.length+1).split(sep)[0] === 'scripts') return fail(404,'Not found')
350
+ const info = await stat(actual)
351
+ if (!info.isFile()) return fail(404,'Not found')
352
+ res.writeHead(200,{...cors,'content-type':mime.get(extname(actual).toLowerCase()) || 'application/octet-stream','content-length':info.size})
353
+ if (req.method === 'HEAD') return res.end()
354
+ const stream = createReadStream(actual)
355
+ stream.on('error', () => res.destroy())
356
+ stream.pipe(res)
357
+ } catch { return fail(404,'Not found') }
358
+ })
359
+
360
+ server.on('error', error => {
361
+ if (error?.code === 'EADDRINUSE') {
362
+ console.error(\`Anyo world dev server: \${host}:\${port} is already in use. Try --port=\${port + 1}.\`)
363
+ process.exitCode = 1
364
+ return
365
+ }
366
+ throw error
367
+ })
368
+
369
+ server.listen(port, host, () => {
370
+ const displayHost = host === '0.0.0.0' ? '127.0.0.1' : host
371
+ const entry = existsSync(join(root,'atlas.world.json')) ? 'atlas.world.json' : 'world.anyo.json'
372
+ const authority = displayHost.includes(':') ? '[' + displayHost + ']' : displayHost
373
+ const sourceRoot = 'http://' + authority + ':' + port + '/'
374
+ console.log('Anyo world source: ' + sourceRoot + entry)
375
+ console.log('World Loader preview (start Loader separately): http://localhost:5173/?registryRoot=' + encodeURIComponent(sourceRoot))
376
+ })
377
+ `
378
+ }
379
+
380
+ function validateSource() {
381
+ return `import { inspectWorldDocument, resolveWorldDocumentImports } from '@blcklab/anyo'
382
+ import { access, readFile, readdir, realpath, stat } from 'node:fs/promises'
383
+ import path from 'node:path'
384
+ import { loadProjectAnyoDocument, readRootWorld, rootSourceContext } from './anyo-documents.mjs'
385
+
386
+ async function exists(file) { try { await access(file); return true } catch { return false } }
387
+ function formatIssues(issues) { return issues.slice(0, 8).map(issue => issue.code + ' ' + issue.path + ': ' + issue.message).join('\\n') }
388
+ function countImports(imports) { return Object.values(imports).reduce((total, item) => total + 1 + countImports(item.imports || {}), 0) }
389
+
390
+ const project=JSON.parse(await readFile('anyo.project.json','utf8'))
391
+ if(project.schema!=='anyo-project@1') throw new Error('anyo.project.json must use anyo-project@1')
392
+ if(!/^[a-z0-9][a-z0-9._-]*$/.test(String(project.id||''))) throw new Error('anyo.project.json has invalid id')
393
+ if(!String(project.title||'').trim()) throw new Error('anyo.project.json title is required')
394
+ if(project.world!=='./world.anyo.json') throw new Error('anyo.project.json world must be ./world.anyo.json')
395
+ if(project.directories?.assets!=='./assets/' || project.directories?.webSurfaces!=='./web-surface/') throw new Error('anyo.project.json must use canonical assets and web-surface directories')
396
+ if(!(await exists('world.anyo.json'))) throw new Error('anyo.project.json references missing world.anyo.json')
397
+ const { document: world } = await readRootWorld()
398
+ if(world.version!=='0.9') throw new Error('Generated project expects Anyo World 0.9; found '+String(world.version))
399
+ const validation=inspectWorldDocument(world)
400
+ if(!validation.valid) throw new Error('Anyo World 0.9 validation failed:\\n'+formatIssues(validation.errors))
401
+ const graph=await resolveWorldDocumentImports(world,{sourceContext:rootSourceContext,documentLoader:loadProjectAnyoDocument})
402
+ console.log('Anyo World 0.9 contract: PASS')
403
+ const importCount=countImports(graph.imports)
404
+ if(importCount) console.log('Anyo object imports: PASS ('+importCount+')')
405
+
406
+ if(project.manifests?.atlas && !(await exists('atlas.world.json'))) throw new Error('Project references missing atlas.world.json')
407
+ if(await exists('atlas.world.json')) {
408
+ if(project.manifests?.atlas!=='./atlas.world.json') throw new Error('Atlas project must declare manifests.atlas as ./atlas.world.json')
409
+ const manifest=JSON.parse(await readFile('atlas.world.json','utf8'))
410
+ if(manifest.schema!=='anyo-world-manifest@1') throw new Error('atlas.world.json must use anyo-world-manifest@1')
411
+ if(!manifest.id||!manifest.title||!manifest.world||!manifest.location) throw new Error('Manifest is missing id, title, world, or location')
412
+ const {latitude,longitude}=manifest.location
413
+ if(!Number.isFinite(latitude)||Math.abs(latitude)>90||!Number.isFinite(longitude)||Math.abs(longitude)>180) throw new Error('Invalid manifest location')
414
+ if(!manifest.placement||!['exact-building','nearest-building','coordinate-only'].includes(manifest.placement.mapMatch)) throw new Error('Manifest must declare a geographic match mode')
415
+ if(!world.entities.some(entity=>entity.components?.some(component=>component.type==='anyo.mapSpawn'))) throw new Error('Atlas world must include anyo.mapSpawn')
416
+ if(!world.entities.some(entity=>entity.components?.some(component=>component.type==='anyo.mapExit'))) throw new Error('Atlas world must include anyo.mapExit')
417
+ const entrance=world.data?.atlas?.entrance
418
+ if(!entrance?.room||!entrance?.opening) throw new Error('Atlas world must declare data.atlas.entrance room/opening')
419
+ console.log('Anyo Atlas contract: PASS')
420
+ console.log('Lot:', manifest.lotId)
421
+ console.log('Location:', latitude.toFixed(6)+', '+longitude.toFixed(6))
422
+ console.log('Local Atlas:', 'http://127.0.0.1:4173/?manifest='+encodeURIComponent('http://127.0.0.1:4174/atlas.world.json')+'&backend=webgl2')
423
+ }
424
+
425
+ const appEntities = world.entities.filter(entity=>entity?.type==='web-surface' && entity.webSurface?.source?.type==='app')
426
+ const registered = new Set()
427
+ if(await exists('web-surface')) {
428
+ for(const entry of await readdir('web-surface',{withFileTypes:true})) {
429
+ if(!entry.isDirectory()) continue
430
+ const manifestPath=path.join('web-surface',entry.name,'web-surface.json')
431
+ if(!(await exists(manifestPath))) continue
432
+ const app=JSON.parse(await readFile(manifestPath,'utf8'))
433
+ if(app.schema!=='anyo-web-app@1') throw new Error(manifestPath+' must use anyo-web-app@1')
434
+ if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(String(app.id||''))) throw new Error(manifestPath+' has invalid id')
435
+ if(app.id!==entry.name) throw new Error(manifestPath+' id must match its directory')
436
+ if(registered.has(app.id)) throw new Error('Duplicate Web Surface app id: '+app.id)
437
+ const rawEntry=String(app.entry||'')
438
+ if(!rawEntry || /^[a-z][a-z0-9+.-]*:/i.test(rawEntry) || rawEntry.startsWith('/') || rawEntry.split(/[?#]/,1)[0].split('/').includes('..')) throw new Error(manifestPath+' entry must stay inside the app directory')
439
+ const entryFile=path.resolve('web-surface',entry.name,rawEntry.split(/[?#]/,1)[0])
440
+ const appRoot=path.resolve('web-surface',entry.name)+path.sep
441
+ if(!entryFile.startsWith(appRoot) || !(await exists(entryFile))) throw new Error(manifestPath+' entry file does not exist')
442
+ const actualEntry=await realpath(entryFile)
443
+ const actualAppRoot=await realpath(appRoot) + path.sep
444
+ if(!actualEntry.startsWith(actualAppRoot) || !(await stat(actualEntry)).isFile()) throw new Error(manifestPath+' entry must stay inside the app directory')
445
+ registered.add(app.id)
446
+ }
447
+ }
448
+ for(const entity of appEntities) if(!registered.has(entity.webSurface.source.app)) throw new Error('World references unregistered Web Surface app: '+entity.webSurface.source.app)
449
+ if(registered.size) console.log('Web Surface apps: PASS ('+registered.size+')')
450
+ console.log('Anyo project contract: PASS')
451
+ console.log('Anyo World Loader contract: PASS')
452
+ `
453
+ }
454
+
455
+ function bundleSource() {
456
+ return `import { bundleWorldDocument, validateWorldDocument } from '@blcklab/anyo'
457
+ import { mkdir, writeFile } from 'node:fs/promises'
458
+ import path from 'node:path'
459
+ import { loadProjectAnyoDocument, makeProjectUrlsPortable, readRootWorld, rootSourceContext } from './anyo-documents.mjs'
460
+
461
+ const outputFile='dist/world.anyo.json'
462
+ const { document: world }=await readRootWorld()
463
+ if(world.version!=='0.9') throw new Error('Generated project expects Anyo World 0.9; found '+String(world.version))
464
+ const bundled=await bundleWorldDocument(world,{sourceContext:rootSourceContext,documentLoader:loadProjectAnyoDocument})
465
+ const portable=makeProjectUrlsPortable(bundled,outputFile)
466
+ validateWorldDocument(portable)
467
+ await mkdir(path.dirname(outputFile),{recursive:true})
468
+ await writeFile(outputFile,JSON.stringify(portable,null,2)+'\\n')
469
+ console.log('Anyo standalone bundle: PASS')
470
+ console.log('Output:', outputFile)
471
+ `
472
+ }
473
+
474
+ function atlasRepositoryUrl(repository, ref, enter = false) {
475
+ if (!repository) return null
476
+ const params = new URLSearchParams({ world: repository, backend: 'webgl2' })
477
+ if (ref) params.set('ref', ref)
478
+ if (enter) params.set('enter', '1')
479
+ return `http://127.0.0.1:4173/?${params}`
480
+ }
481
+
482
+ function worldLoaderRepositoryRoute(repository, ref) {
483
+ if (!repository) return null
484
+ const [owner, name] = repository.split('/')
485
+ const route = `/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
486
+ return ref ? `${route}?ref=${encodeURIComponent(ref)}` : route
487
+ }
488
+
489
+ function webAppFiles(appId, title) {
490
+ const appTitle = `${title} Dashboard`
491
+ const manifest = { schema: 'anyo-web-app@1', id: appId, title: appTitle, entry: './index.html', description: `${title} repository-hosted Web Surface application.` }
492
+ const html = `<!doctype html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>${escapeHtml(appTitle)}</title>\n <link rel="stylesheet" href="./style.css">\n</head>\n<body>\n <main class="shell">\n <header class="topbar">\n <div><p class="eyebrow">ANYO WEB SURFACE</p><h1>${escapeHtml(title)}</h1></div>\n <span class="status" id="status">ONLINE</span>\n </header>\n <section class="hero">\n <div><p class="eyebrow">REPOSITORY APPLICATION</p><h2>Normal HTML, CSS and JavaScript inside your Anyo world.</h2><p>Edit this app under <code>web-surface/${escapeHtml(appId)}/</code>. World Loader discovers it automatically from <code>web-surface.json</code>.</p></div>\n <button id="pulse" type="button">Run interaction</button>\n </section>\n <section class="grid" aria-label="Runtime cards">\n <article><span>Surface</span><strong>Interactive</strong></article>\n <article><span>Layout</span><strong>Responsive</strong></article>\n <article><span>Security</span><strong>Sandboxed</strong></article>\n </section>\n <section class="log" aria-live="polite"><span>EVENT</span><output id="event">Ready for input.</output></section>\n </main>\n <script type="module" src="./app.js"></script>\n</body>\n</html>\n`
493
+ const css = `:root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#080c12;color:#f7fafc}*{box-sizing:border-box}body{margin:0;min-width:280px;min-height:100vh;background:radial-gradient(circle at 85% 0%,#12314a 0,transparent 36%),#080c12}.shell{min-height:100vh;padding:clamp(20px,4vw,64px);display:grid;align-content:center;gap:clamp(18px,3vw,36px)}.topbar,.hero,.grid,.log{width:min(1120px,100%);margin-inline:auto}.topbar{display:flex;align-items:center;justify-content:space-between;gap:24px}.eyebrow{margin:0 0 8px;color:#64d8ff;font-size:.72rem;font-weight:800;letter-spacing:.18em}.topbar h1,.hero h2{margin:0}.topbar h1{font-size:clamp(1.5rem,3vw,2.5rem)}.status{padding:8px 12px;border:1px solid #2b6279;border-radius:999px;color:#8ce7ff;font-size:.72rem;font-weight:800}.hero{padding:clamp(24px,5vw,56px);border:1px solid #203040;border-radius:28px;background:linear-gradient(145deg,rgba(18,29,42,.96),rgba(8,12,18,.94));box-shadow:0 22px 70px rgba(0,0,0,.32);display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:28px}.hero h2{max-width:780px;font-size:clamp(2rem,5vw,4.8rem);line-height:.98;letter-spacing:-.045em}.hero p:not(.eyebrow){max-width:720px;color:#a8b7c6;line-height:1.7}.hero code{color:#d6f5ff}button{border:0;border-radius:14px;padding:14px 18px;background:#eafaff;color:#07121a;font:inherit;font-weight:800;cursor:pointer}button:hover,button:focus-visible{background:#7ee4ff;outline:none}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.grid article,.log{padding:18px 20px;border:1px solid #1f2d3a;border-radius:18px;background:#0d141d}.grid span,.log span{display:block;color:#6f8497;font-size:.72rem;letter-spacing:.12em}.grid strong{display:block;margin-top:6px;font-size:1.15rem}.log{display:grid;grid-template-columns:auto 1fr;gap:18px;align-items:center}.log output{color:#c8d5df}@media(max-width:760px){.hero{grid-template-columns:1fr}.grid{grid-template-columns:1fr}.topbar{align-items:flex-start}.status{margin-top:4px}}\n`
494
+ const js = `const button=document.querySelector('#pulse');const output=document.querySelector('#event');const status=document.querySelector('#status');let count=0;button?.addEventListener('click',()=>{count+=1;output.value='Interaction '+count+' received at '+new Date().toLocaleTimeString();status.textContent=count%2?'ACTIVE':'ONLINE'});\n`
495
+ return { manifest, html, css, js }
496
+ }
497
+
498
+ function escapeHtml(value) {
499
+ return String(value).replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char])
500
+ }
501
+
502
+ function fallbackSvg(title) {
503
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720"><rect width="1280" height="720" fill="#080c12"/><rect x="54" y="54" width="1172" height="612" rx="32" fill="#101924" stroke="#2a4253" stroke-width="2"/><text x="96" y="132" fill="#64d8ff" font-family="system-ui,sans-serif" font-size="24" font-weight="700" letter-spacing="4">ANYO WEB SURFACE</text><text x="96" y="232" fill="#f7fafc" font-family="system-ui,sans-serif" font-size="62" font-weight="750">${escapeHtml(title)}</text><text x="96" y="300" fill="#9eb0bf" font-family="system-ui,sans-serif" font-size="30">Repository app fallback snapshot</text><circle cx="1110" cy="126" r="12" fill="#64d8ff"/></svg>\n`
504
+ }
505
+
506
+ function generatedReadme({ title, mode, latitude, longitude, canonicalLotId, osm, localAtlasUrl, localDirectAtlasUrl, geographicAtlasUrl, github, publicAtlasUrl, directAtlasUrl, worldLoaderRoute, webApp, modular }) {
507
+ const atlasEnabled = mode !== 'loader'
508
+ const locationSection = atlasEnabled ? `## Location\n\n- Latitude: ${latitude.toFixed(6)}\n- Longitude: ${longitude.toFixed(6)}\n- Lot ID: \`${canonicalLotId}\`\n${osm ? `- OSM: \`${osm.type}/${osm.id}\`\n` : ''}\n` : ''
509
+ const loaderSection = `## Anyo World Loader\n\nThe repository root \`world.anyo.json\` is the World Loader entry. ${github ? `Open the repository route after the Loader is running:\n\n\`\`\`text\nhttp://localhost:5173${worldLoaderRoute}\n\`\`\`\n` : 'After publishing, enter `OWNER/REPOSITORY` in World Loader or open its `/OWNER/REPOSITORY` route.\n'}\nWorld Loader resolves \`world.anyo.json\` from the selected repository ref. Do not add Loader-specific backend fields to the world document.\n\n`
510
+ const atlasSection = atlasEnabled ? `## Atlas\n\nOpen Atlas against the local manifest:\n\n\`\`\`text\n${localAtlasUrl}\n\`\`\`\n\nOpen the authored world inside its streamed neighborhood:\n\n\`\`\`text\n${localDirectAtlasUrl}\n\`\`\`\n\nThe manifest owns the world location, so the Atlas URL does not need coordinates. Without an exact OSM ID the world is location-only: Atlas can discover it nearby but will not claim or replace an arbitrary building. Supply an exact OSM ID for deterministic building replacement.\n\n${github ? `Repository Atlas URL:\n\n\`\`\`text\n${publicAtlasUrl}\n\`\`\`\n\nDirect 3D URL:\n\n\`\`\`text\n${directAtlasUrl}\n\`\`\`\n\n` : ''}Geographic navigation remains available:\n\n\`\`\`text\n${geographicAtlasUrl}\n\`\`\`\n\n` : ''
511
+ const authoringSection = modular ? `## Modular authoring\n\nThis starter keeps the repository entry at \`world.anyo.json\` and places one reusable native Anyo object at \`models/centerpiece.anyo.json\`. The root world imports it by alias. Add more Object 0.1 documents under \`models/\` as the project grows.\n\n` : `## Authoring\n\nThis starter intentionally keeps everything in one World 0.9 file. If you want an example native-object layout in a new project, regenerate with \`--modular\`.\n\n`
512
+ const webSection = webApp ? `## Web Surface\n\nA framework-agnostic repository web application is included at:\n\n\`\`\`text\nweb-surface/${webApp.id}/\n├─ web-surface.json\n├─ index.html\n├─ style.css\n├─ app.js\n└─ assets/\n\`\`\`\n\nThe manifest uses \`anyo-web-app@1\`. World Loader discovers it automatically at the pinned repository ref. The matching world entity uses \`source.type = "app"\` and app id \`${webApp.id}\`. Its requested presentation resolution is **${webApp.resolution[0]}×${webApp.resolution[1]}**.\n\nKeep application HTML/CSS/JS in this folder; do not embed executable HTML inside \`world.anyo.json\`. Normal browser security and sandbox behavior still apply.\n\n` : ''
513
+ return `# ${title}\n\nPortable Anyo world repository generated for **${mode === 'loader' ? 'World Loader' : mode === 'both' ? 'Atlas + World Loader' : 'Atlas (and directly loadable by World Loader)'}**.\n\n${locationSection}## Anyo project\n\nEdit \`world.anyo.json\` directly or open the folder in Anyo Editor using \`anyo.project.json\`. Local editor state in \`.anyo/\` is ignored.\n\n## Develop\n\n\`\`\`bash\nnpm install\nnpm run validate\nnpm run bundle\nnpm run dev\n\`\`\`\n\n\`npm run validate\` uses the pinned \`@blcklab/anyo\` package as the World 0.9 schema and import authority. \`npm run bundle\` writes a deterministic standalone document to \`dist/world.anyo.json\` with native Anyo object imports flattened.\n\nStart Anyo World Loader 0.6.0-rc.1 separately (\`npm run dev\` in its repository), then open:\n\n\`\`\`text\nhttp://localhost:5173/?registryRoot=http%3A%2F%2F127.0.0.1%3A4174%2F\n\`\`\`\n\nThe world dev server serves JSON and assets, not a second renderer. Refresh the Loader after editing. Use the printed URL if you change ports.\n\nRun multiple local worlds on separate ports with \`npm run dev -- --port=4175\` (or \`--port 4175\`).\n\n${loaderSection}${atlasSection}${authoringSection}${webSection}## Publish\n\n1. Push this folder to GitHub.\n2. Keep \`anyo.project.json\` and \`world.anyo.json\` at the repository root.${atlasEnabled ? '\n3. Keep `atlas.world.json` at the repository root for Atlas.\n4. Prefer a version tag for stable public links.' : '\n3. Prefer a version tag for stable public links.'}\n`
514
+ }
515
+
516
+ export async function scaffold(argv = process.argv.slice(2), io = {}) {
517
+ const parsed = parseArgs(argv)
518
+ if (parsed.options.version) { (io.log || console.log)(VERSION); return { version: VERSION } }
519
+ if (parsed.options.help) { (io.log || console.log)(HELP); return { help: true } }
520
+ const rl = io.readline || readline.createInterface({ input, output })
521
+ const ownRl = !io.readline
522
+ try {
523
+ const rawName = parsed.projectName || await rl.question('Project name: ')
524
+ const id = slug(rawName)
525
+ const title = String(parsed.options.title || titleFromSlug(id)).trim() || titleFromSlug(id)
526
+ const mode = normalizeMode(parsed.options.mode)
527
+ const atlasEnabled = mode !== 'loader'
528
+ const modular = parsed.options.modular === true
529
+
530
+ let latitude = null
531
+ let longitude = null
532
+ let preferredZoom = null
533
+ let osm = null
534
+ let canonicalLotId = null
535
+ if (atlasEnabled) {
536
+ const latValue = parsed.options.lat ?? await rl.question('Latitude: ')
537
+ const lngValue = parsed.options.lng ?? await rl.question('Longitude: ')
538
+ latitude = coordinate(latValue, 90, 'Latitude')
539
+ longitude = coordinate(lngValue, 180, 'Longitude')
540
+ preferredZoom = zoom(parsed.options.zoom)
541
+ osm = parseOsm(parsed.options.osm)
542
+ if (!osm && parsed.options.osm === undefined && io.interactiveOsm === true) osm = parseOsm(await rl.question('OSM building (optional, e.g. way/123): '))
543
+ canonicalLotId = lotId(latitude, longitude, osm)
544
+ } else if (parsed.options.osm !== undefined || parsed.options.lat !== undefined || parsed.options.lng !== undefined || parsed.options.zoom !== undefined) {
545
+ throw new Error('Latitude, longitude, zoom, and OSM options require --mode=atlas or --mode=both.')
546
+ }
547
+
548
+ const appId = normalizeWebAppId(parsed.options['web-surface'])
549
+ const appResolution = appId ? webResolution(parsed.options['web-resolution']) : null
550
+ if (!appId && parsed.options['web-resolution'] !== undefined) throw new Error('--web-resolution requires --web-surface.')
551
+ const webApp = appId ? { id: appId, resolution: appResolution } : null
552
+
553
+ const github = normalizeGitHubRepository(parsed.options.github)
554
+ const gitRef = normalizeRef(parsed.options.ref)
555
+ const target = path.resolve(io.cwd || process.cwd(), id)
556
+ if (await exists(target) && !parsed.options.force) throw new Error(`Target ${target} already exists. Use --force to overwrite starter files.`)
557
+ await mkdir(path.join(target, 'assets'), { recursive: true })
558
+ await mkdir(path.join(target, 'scripts'), { recursive: true })
559
+ await mkdir(path.join(target, 'web-surface'), { recursive: true })
560
+ if (modular) await mkdir(path.join(target, 'models'), { recursive: true })
561
+ if (webApp) await mkdir(path.join(target, 'web-surface', webApp.id, 'assets'), { recursive: true })
562
+
563
+ const manifest = atlasEnabled ? {
564
+ schema: 'anyo-world-manifest@1', id, title, version: '0.1.0', lotId: canonicalLotId,
565
+ world: './world.anyo.json', assetsBase: './assets/',
566
+ location: { latitude, longitude, zoom: preferredZoom, radiusMeters: 80, ...(osm ? { osm } : {}) },
567
+ placement: {
568
+ anchor: 'footprint-center', fit: 'uniform-contain', northAxis: '+x', groundLevel: 0,
569
+ mapMatch: osm ? 'exact-building' : 'coordinate-only',
570
+ maximumDistanceMeters: 120,
571
+ portal: true,
572
+ },
573
+ } : null
574
+
575
+ const publicAtlasUrl = atlasEnabled ? atlasRepositoryUrl(github, gitRef, false) : null
576
+ const directAtlasUrl = atlasEnabled ? atlasRepositoryUrl(github, gitRef, true) : null
577
+ const worldLoaderRoute = worldLoaderRepositoryRoute(github, gitRef)
578
+ const localManifestUrl = atlasEnabled ? 'http://127.0.0.1:4174/atlas.world.json' : null
579
+ const localAtlasUrl = atlasEnabled ? `http://127.0.0.1:4173/?manifest=${encodeURIComponent(localManifestUrl)}&backend=webgl2` : null
580
+ const localDirectAtlasUrl = atlasEnabled ? `${localAtlasUrl}&enter=1` : null
581
+ const geographicAtlasUrl = atlasEnabled ? `http://127.0.0.1:4173/?lat=${latitude.toFixed(6)}&lng=${longitude.toFixed(6)}&z=${preferredZoom}&backend=webgl2` : null
582
+ const pkg = { name: id, version: '0.1.0', private: true, type: 'module', engines: { node: '>=20' }, scripts: { dev: 'node scripts/dev.mjs', validate: 'node scripts/validate.mjs', bundle: 'node scripts/bundle.mjs', check: 'npm run validate && npm run bundle' }, devDependencies: { '@blcklab/anyo': ANYO_TOOLING_VERSION } }
583
+ const readme = generatedReadme({ title, mode, latitude, longitude, canonicalLotId, osm, localAtlasUrl, localDirectAtlasUrl, geographicAtlasUrl, github, publicAtlasUrl, directAtlasUrl, worldLoaderRoute, webApp, modular })
584
+
585
+ const project = projectDocument({ id, title, atlasEnabled })
586
+ const writes = [
587
+ writeFile(path.join(target, 'world.anyo.json'), json(worldDocument({ id, title, latitude, longitude, atlasEnabled, webApp, modular }))),
588
+ writeFile(path.join(target, 'package.json'), json(pkg)),
589
+ writeFile(path.join(target, 'README.md'), readme),
590
+ writeFile(path.join(target, '.gitignore'), 'node_modules/\n/dist/\n.DS_Store\n.anyo/\n.env\n.env.*\n!.env.example\n'),
591
+ writeFile(path.join(target, 'assets', '.gitkeep'), ''),
592
+ writeFile(path.join(target, 'web-surface', '.gitkeep'), ''),
593
+ writeFile(path.join(target, 'scripts', 'dev.mjs'), devServerSource()),
594
+ writeFile(path.join(target, 'scripts', 'validate.mjs'), validateSource()),
595
+ writeFile(path.join(target, 'scripts', 'bundle.mjs'), bundleSource()),
596
+ writeFile(path.join(target, 'scripts', 'anyo-documents.mjs'), anyoDocumentsSource()),
597
+ ]
598
+ if (modular) writes.push(writeFile(path.join(target, 'models', 'centerpiece.anyo.json'), json(modularObjectDocument({ title }))))
599
+ if (manifest) writes.push(writeFile(path.join(target, 'atlas.world.json'), json(manifest)))
600
+ if (webApp) {
601
+ const files = webAppFiles(webApp.id, title)
602
+ const appRoot = path.join(target, 'web-surface', webApp.id)
603
+ writes.push(
604
+ writeFile(path.join(appRoot, 'web-surface.json'), json(files.manifest)),
605
+ writeFile(path.join(appRoot, 'index.html'), files.html),
606
+ writeFile(path.join(appRoot, 'style.css'), files.css),
607
+ writeFile(path.join(appRoot, 'app.js'), files.js),
608
+ writeFile(path.join(appRoot, 'assets', '.gitkeep'), ''),
609
+ writeFile(path.join(target, 'assets', 'web-surface-fallback.svg'), fallbackSvg(title)),
610
+ )
611
+ }
612
+ await Promise.all(writes)
613
+ await writeFile(path.join(target, 'anyo.project.json'), json(project))
614
+
615
+ ;(io.log || console.log)(`Created ${id}`)
616
+ ;(io.log || console.log)(`Mode: ${mode}`)
617
+ if (canonicalLotId) (io.log || console.log)(`Lot: ${canonicalLotId}`)
618
+ if (localAtlasUrl) (io.log || console.log)(`Local Atlas: ${localAtlasUrl}`)
619
+ if (localDirectAtlasUrl) (io.log || console.log)(`Local neighborhood: ${localDirectAtlasUrl}`)
620
+ if (publicAtlasUrl) (io.log || console.log)(`GitHub Atlas: ${publicAtlasUrl}`)
621
+ if (worldLoaderRoute) (io.log || console.log)(`World Loader route: ${worldLoaderRoute}`)
622
+ ;(io.log || console.log)(`Authoring: ${modular ? 'modular' : 'single-file'} World 0.9`)
623
+ if (webApp) (io.log || console.log)(`Web Surface: ${webApp.id} (${webApp.resolution[0]}x${webApp.resolution[1]})`)
624
+ return {
625
+ target, id, title, mode, lotId: canonicalLotId, manifest, github, ref: gitRef,
626
+ atlasUrl: publicAtlasUrl, directAtlasUrl, localAtlasUrl, localDirectAtlasUrl, geographicAtlasUrl,
627
+ worldLoaderRoute, webSurface: webApp, authoring: modular ? 'modular' : 'single-file',
628
+ }
629
+ } finally { if (ownRl) rl.close() }
630
+ }
631
+
632
+ if (/^create-anyo-world(?:\.mjs)?$/i.test(path.basename(process.argv[1] || ''))) {
633
+ scaffold().catch(error => { console.error(`create-anyo-world: ${error instanceof Error ? error.message : String(error)}`); process.exitCode = 1 })
634
+ }