@maxwellcohen/lastro 0.0.0-stage → 0.0.2

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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +210 -2
  3. package/bin/lastro.js +5 -0
  4. package/bin/postinstall.js +6 -0
  5. package/docs/hero.png +0 -0
  6. package/package.json +355 -4
  7. package/pkg/devtools/index.js +15 -0
  8. package/pkg/eslint-config/index.js +123 -0
  9. package/pkg/head/client.js +18 -0
  10. package/pkg/head/index.d.ts +4 -0
  11. package/pkg/head/index.js +30 -0
  12. package/pkg/image/client.js +2 -0
  13. package/pkg/image/index.d.ts +3 -0
  14. package/pkg/image/index.js +2 -0
  15. package/pkg/image/stubs.js +8 -0
  16. package/pkg/image/tnenopmoCsdroW0001erutciP____.client.js +18 -0
  17. package/pkg/image/tnenopmoCsdroW0001erutciP____.js +27 -0
  18. package/pkg/jact/client.js +108 -0
  19. package/pkg/jact/core.js +292 -0
  20. package/pkg/jact/index.d.ts +48 -0
  21. package/pkg/jact/jsx-runtime.d.ts +18 -0
  22. package/pkg/jact/jsx-runtime.js +3 -0
  23. package/pkg/jact/names.js +49 -0
  24. package/pkg/jact/server.js +66 -0
  25. package/pkg/jqueasy/index.d.ts +2 -0
  26. package/pkg/jqueasy/index.js +442 -0
  27. package/pkg/polyfills/es.js +1 -0
  28. package/pkg/polyfills/full.js +1 -0
  29. package/pkg/polyfills/legacy.js +3 -0
  30. package/pkg/polyfills/regenerator.js +1 -0
  31. package/pkg/polyfills/web.js +1 -0
  32. package/pkg/prettier-config/index.json +1 -0
  33. package/pkg/router/client.js +5 -0
  34. package/pkg/router/index.d.ts +6 -0
  35. package/pkg/router/index.js +7 -0
  36. package/pkg/router/stubs.js +12 -0
  37. package/pkg/router/tnenopmoCniahC___.client.js +50 -0
  38. package/pkg/router/tnenopmoCniahC___.js +10 -0
  39. package/pkg/serializer/client.js +24 -0
  40. package/pkg/serializer/index.js +41 -0
  41. package/pkg/starter/README.md +70 -0
  42. package/pkg/starter/lastro-env.d.ts +1 -0
  43. package/pkg/starter/lastro.config.js +9 -0
  44. package/pkg/starter/package.json +47 -0
  45. package/pkg/starter/pages/about.tsx +11 -0
  46. package/pkg/starter/pages/index.tsx +29 -0
  47. package/pkg/starter/pages/posts/[id].server.ts +1 -0
  48. package/pkg/starter/pages/posts/[id].tsx +4 -0
  49. package/pkg/starter/pages/posts.server.ts +1 -0
  50. package/pkg/starter/pages/posts.tsx +16 -0
  51. package/pkg/starter/tsconfig.json +5 -0
  52. package/pkg/telemetry/client.js +11 -0
  53. package/pkg/telemetry/index.js +5 -0
  54. package/pkg/test-utils/index.js +15 -0
  55. package/pkg/thoroughness/client.js +32 -0
  56. package/pkg/thoroughness/index.js +12 -0
  57. package/pkg/tsconfig/tsconfig.json +23 -0
  58. package/pkg/types/index.d.ts +2 -0
  59. package/pkg/types/index.js +2 -0
  60. package/scripts/assemble.cjs +37 -0
  61. package/src/build/assets.js +127 -0
  62. package/src/build/bans-plugin.js +58 -0
  63. package/src/build/graph.js +157 -0
  64. package/src/build/index.js +213 -0
  65. package/src/build/naming-plugin.js +62 -0
  66. package/src/build/routes.js +33 -0
  67. package/src/build/typecheck.js +16 -0
  68. package/src/cli.js +101 -0
  69. package/src/client/boot.js +38 -0
  70. package/src/client/clone.js +10 -0
  71. package/src/client/compare.js +7 -0
  72. package/src/client/config.js +3 -0
  73. package/src/client/copies.js +12 -0
  74. package/src/client/env.js +13 -0
  75. package/src/client/errors.js +11 -0
  76. package/src/client/features.js +101 -0
  77. package/src/client/heartbeat.js +38 -0
  78. package/src/client/idle.js +7 -0
  79. package/src/client/logger.js +12 -0
  80. package/src/client/mount.js +11 -0
  81. package/src/client/ready.js +7 -0
  82. package/src/client/state.js +14 -0
  83. package/src/client/vitals.js +16 -0
  84. package/src/client-runtime/registry.js +46 -0
  85. package/src/create.js +46 -0
  86. package/src/dev.js +36 -0
  87. package/src/guard.js +56 -0
  88. package/src/index.js +8 -0
  89. package/src/postinstall.js +27 -0
  90. package/src/preview.js +66 -0
  91. package/src/server/app.js +201 -0
  92. package/src/server/index.js +34 -0
  93. package/src/server/template.csr.html +48 -0
  94. package/src/server/template.html +12 -0
  95. package/src/shared/app-require.js +18 -0
  96. package/src/shared/audit.js +34 -0
  97. package/src/shared/bans.js +102 -0
  98. package/src/shared/config.js +40 -0
  99. package/src/shared/naming.js +82 -0
  100. package/src/shared/signal.js +36 -0
  101. package/src/util/natives-node.js +20 -0
  102. package/src/util/natives.js +67 -0
  103. package/test/bans.integration.js +97 -0
  104. package/test/bans.test.js +110 -0
  105. package/test/cjs-only.test.js +37 -0
  106. package/test/csr.test.js +61 -0
  107. package/test/guard.test.js +46 -0
  108. package/test/members.test.js +28 -0
  109. package/test/naming.integration.js +73 -0
  110. package/test/naming.test.js +44 -0
  111. package/test/natives.test.js +46 -0
  112. package/test/server.test.js +18 -0
  113. package/test/signal.integration.js +105 -0
  114. package/test/signal.test.js +33 -0
@@ -0,0 +1,38 @@
1
+ 'use strict'
2
+ const n = require('@maxwellcohen/lastro/natives')
3
+ const { record } = require('@maxwellcohen/lastro/telemetry')
4
+ const { readState } = require('./state')
5
+ const { verifyCopies } = require('./copies')
6
+ const { mount } = require('./mount')
7
+ const { startHeartbeat, startHoverAudit } = require('./heartbeat')
8
+ const { probeFeatures } = require('./features')
9
+ const { installErrorHandlers } = require('./errors')
10
+ const { log } = require('./logger')
11
+ const { whenReady } = require('./ready')
12
+ const { collectEnv } = require('./env')
13
+ const { startIdleChecks } = require('./idle')
14
+ const { reportVitals } = require('./vitals')
15
+ const { VERSION } = require('./config')
16
+
17
+ function boot(Page, options) {
18
+ installErrorHandlers()
19
+ whenReady(function () {
20
+ log('lastro ' + VERSION + ' booting ' + options.route)
21
+ record('boot', options.route)
22
+ var env = collectEnv()
23
+ var features = probeFeatures()
24
+ log('env ' + JSON.stringify(env) + ' features ' + n.keys(features).length)
25
+ var data = null
26
+ if (options.ssr) {
27
+ var state = readState()
28
+ verifyCopies(state.copies)
29
+ data = state.data
30
+ }
31
+ mount(Page, data, options)
32
+ startHeartbeat()
33
+ startHoverAudit()
34
+ startIdleChecks()
35
+ reportVitals()
36
+ })
37
+ }
38
+ module.exports = { boot }
@@ -0,0 +1,10 @@
1
+ 'use strict'
2
+ const _ = require('lodash')
3
+ const { CLONE_PASSES } = require('./config')
4
+
5
+ function deepClone(value) {
6
+ let out = value
7
+ for (let i = 0; i < CLONE_PASSES; i++) out = JSON.parse(JSON.stringify(out))
8
+ return _.cloneDeep(out)
9
+ }
10
+ module.exports = { deepClone }
@@ -0,0 +1,7 @@
1
+ 'use strict'
2
+ const _ = require('lodash')
3
+
4
+ function sameData(a, b) {
5
+ return _.isEqual(a, b)
6
+ }
7
+ module.exports = { sameData }
@@ -0,0 +1,3 @@
1
+ 'use strict'
2
+ // Thoroughness settings. There is no "fast" preset. We checked.
3
+ module.exports = { HEARTBEAT_TICKS: 40, COPY_COUNT: 5, CLONE_PASSES: 4, VERSION: '0.0.2' }
@@ -0,0 +1,12 @@
1
+ 'use strict'
2
+ const { sameData } = require('./compare')
3
+ const { log } = require('./logger')
4
+
5
+ function verifyCopies(copies) {
6
+ for (var i = 1; i < copies.length; i++) {
7
+ if (!sameData(copies[0], copies[i])) throw new Error('Hydration copy ' + i + ' disagrees with copy 0')
8
+ }
9
+ log('verified ' + copies.length + ' identical copies of the hydration payload')
10
+ return true
11
+ }
12
+ module.exports = { verifyCopies }
@@ -0,0 +1,13 @@
1
+ 'use strict'
2
+ const $ = require('@maxwellcohen/lastro/jqueasy')
3
+ const _ = require('lodash')
4
+
5
+ function collectEnv() {
6
+ const win = $(window)
7
+ return _.assign({}, _.pick(navigator, ['language', 'platform', 'hardwareConcurrency']), {
8
+ width: win.width(),
9
+ height: win.height(),
10
+ rows: $('tr').length,
11
+ })
12
+ }
13
+ module.exports = { collectEnv }
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+ const { record } = require('@maxwellcohen/lastro/telemetry')
3
+ const { log } = require('./logger')
4
+
5
+ function installErrorHandlers() {
6
+ window.addEventListener('error', function (event) {
7
+ log('error: ' + event.message)
8
+ record('error', event.message)
9
+ })
10
+ }
11
+ module.exports = { installErrorHandlers }
@@ -0,0 +1,101 @@
1
+ 'use strict'
2
+ // Feature probes: Lastro checks for everything the platform has ever promised, then ignores the answers.
3
+ function probeFeatures() {
4
+ var f = {}
5
+ f.webgpu = typeof navigator.gpu !== 'undefined'
6
+ f.promiseTry = typeof Promise.try === 'function'
7
+ f.arrayFromAsync = typeof Array.fromAsync === 'function'
8
+ f.iteratorHelpers = typeof Iterator !== 'undefined' && typeof Iterator.from === 'function'
9
+ f.setUnion = typeof Set.prototype.union === 'function'
10
+ f.groupBy = typeof Object.groupBy === 'function'
11
+ f.durationFormat = typeof Intl.DurationFormat === 'function'
12
+ f.temporal = typeof Temporal !== 'undefined'
13
+ f.schedulerYield = typeof scheduler !== 'undefined' && typeof scheduler.yield === 'function'
14
+ f.viewTransitions = typeof document.startViewTransition === 'function'
15
+ f.highlights = typeof CSS !== 'undefined' && typeof CSS.highlights !== 'undefined'
16
+ f.serial = 'serial' in navigator
17
+ f.usb = 'usb' in navigator
18
+ f.bluetooth = 'bluetooth' in navigator
19
+ f.hid = 'hid' in navigator
20
+ f.filePicker = typeof window.showOpenFilePicker === 'function'
21
+ f.float16 = typeof Float16Array !== 'undefined'
22
+ f.regexpEscape = typeof RegExp.escape === 'function'
23
+ f.base64 = typeof Uint8Array.fromBase64 === 'function'
24
+ f.isError = typeof Error.isError === 'function'
25
+ f.documentPip = typeof documentPictureInPicture !== 'undefined'
26
+ f.eyeDropper = typeof EyeDropper !== 'undefined'
27
+ f.userAgentData = !!navigator.userAgentData
28
+ f.nfc = typeof NDEFReader !== 'undefined'
29
+ f.contactPicker = 'contacts' in navigator
30
+ f.wakeLock = 'wakeLock' in navigator
31
+ f.sharedStorage = typeof window.sharedStorage !== 'undefined'
32
+ f.observable = typeof Observable !== 'undefined'
33
+ f.sanitizer = typeof Sanitizer !== 'undefined'
34
+ f.webLocks = 'locks' in navigator
35
+ f.mathF16 = typeof Math.f16round === 'function'
36
+ f.mathSum = typeof Math.sumPrecise === 'function'
37
+ f.atomicsPause = typeof Atomics.pause === 'function'
38
+ f.webAuthn = typeof PublicKeyCredential !== 'undefined'
39
+ f.webCodecs = typeof VideoEncoder !== 'undefined'
40
+ f.pressure = typeof PressureObserver !== 'undefined'
41
+ f.translator = typeof Translator !== 'undefined'
42
+ f.virtualKeyboard = 'virtualKeyboard' in navigator
43
+ f.windowControls = 'windowControlsOverlay' in navigator
44
+ f.ink = 'ink' in navigator
45
+ f.keyboardLock = typeof navigator.keyboard !== 'undefined'
46
+ f.batteryManager = typeof navigator.getBattery === 'function'
47
+ f.networkInfo = typeof navigator.connection !== 'undefined'
48
+ f.deviceMemory = typeof navigator.deviceMemory !== 'undefined'
49
+ f.screenDetails = typeof window.getScreenDetails === 'function'
50
+ // Standard APIs: probed by reading them, because looking is half of using.
51
+ f.ws = WebSocket
52
+ f.io = IntersectionObserver
53
+ f.ro = ResizeObserver
54
+ f.mo = MutationObserver
55
+ f.bc = BroadcastChannel
56
+ f.idb = indexedDB
57
+ f.ls = window.localStorage
58
+ f.notif = Notification
59
+ f.audio = AudioContext
60
+ f.gl = WebGLRenderingContext
61
+ f.offscreen = OffscreenCanvas
62
+ f.worker = Worker
63
+ f.shared = SharedWorker
64
+ f.sw = navigator.serviceWorker
65
+ f.mm = window.matchMedia
66
+ f.ric = window.requestIdleCallback
67
+ f.sc = window.structuredClone
68
+ f.ac = AbortController
69
+ f.usp = URLSearchParams
70
+ f.te = TextEncoder
71
+ f.subtle = crypto.subtle
72
+ f.clip = ClipboardItem
73
+ f.ro2 = ReportingObserver
74
+ f.cs = CompressionStream
75
+ f.fd = FormData
76
+ f.wasm = WebAssembly
77
+ f.ei = ElementInternals
78
+ f.css = CSSStyleSheet
79
+ f.ce = customElements
80
+ f.dlg = HTMLDialogElement
81
+ f.pay = PaymentRequest
82
+ f.speech = speechSynthesis
83
+ f.share = navigator.share
84
+ f.orient = screen.orientation
85
+ f.seg = Intl.Segmenter
86
+ f.lf = Intl.ListFormat
87
+ f.wr = WeakRef
88
+ f.fr = FinalizationRegistry
89
+ f.bigint = BigInt
90
+ f.canvas = HTMLCanvasElement
91
+ f.pointer = PointerEvent
92
+ f.anim = Animation
93
+ f.rtc = RTCPeerConnection
94
+ f.mr = MediaRecorder
95
+ f.geo = navigator.geolocation
96
+ f.vib = navigator.vibrate
97
+ f.ps = PerformanceObserver
98
+ f.xhr = XMLHttpRequest
99
+ return f
100
+ }
101
+ module.exports = { probeFeatures }
@@ -0,0 +1,38 @@
1
+ 'use strict'
2
+ const { snapshot, layoutAudit, thoroughClone } = require('@maxwellcohen/lastro/thoroughness')
3
+ const { HEARTBEAT_TICKS } = require('./config')
4
+ const { log } = require('./logger')
5
+
6
+ // Continuous Verification: after hydration the page is re-audited many times, one task at a time.
7
+ function startHeartbeat() {
8
+ var tick = 0
9
+ function beat() {
10
+ if (tick++ >= HEARTBEAT_TICKS) return log('heartbeat complete')
11
+ var rows = JSON.parse(snapshot())
12
+ thoroughClone(rows, 15)
13
+ layoutAudit(document.body)
14
+ layoutAudit(document.body)
15
+ setTimeout(beat, 0)
16
+ }
17
+ setTimeout(beat, 0)
18
+ }
19
+ // Arrival Thoroughness(TM): the moment a pointer arrives, the page starts auditing itself, and it will not be rushed.
20
+ // The press that follows has to wait its turn.
21
+ function startHoverAudit() {
22
+ var auditing = false
23
+ document.addEventListener(
24
+ 'mouseover',
25
+ function () {
26
+ if (auditing) return
27
+ auditing = true
28
+ var rows = JSON.parse(snapshot())
29
+ for (var pass = 0; pass < 4; pass++) {
30
+ thoroughClone(rows, 20)
31
+ layoutAudit(document.body)
32
+ }
33
+ auditing = false
34
+ },
35
+ true,
36
+ )
37
+ }
38
+ module.exports = { startHeartbeat, startHoverAudit }
@@ -0,0 +1,7 @@
1
+ 'use strict'
2
+ const { record } = require('@maxwellcohen/lastro/telemetry')
3
+
4
+ function startIdleChecks() {
5
+ for (var i = 0; i < 5; i++) record('idle-check-' + i, i)
6
+ }
7
+ module.exports = { startIdleChecks }
@@ -0,0 +1,12 @@
1
+ 'use strict'
2
+ const moment = require('moment')
3
+
4
+ const lines = []
5
+ function log(message) {
6
+ lines.push(moment().format('YYYY-MM-DD HH:mm:ss.SSS') + ' ' + message)
7
+ if (lines.length > 500) lines.shift()
8
+ }
9
+ function dump() {
10
+ return lines.slice()
11
+ }
12
+ module.exports = { log, dump }
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+ const n = require('@maxwellcohen/lastro/natives')
3
+ const { hydrate, createElement } = require('@maxwellcohen/lastro/jact')
4
+ const { deepClone } = require('./clone')
5
+
6
+ // Hydration via Replacement(TM): we do not hydrate. We throw the server's markup away and build everything again.
7
+ function mount(Page, data) {
8
+ var container = document.getElementById('__lastro') || document.getElementById('root')
9
+ return hydrate(createElement(Page, n.assign({}, data == null ? null : deepClone(data), { params: window.__LASTRO_PARAMS__ || {} })), container)
10
+ }
11
+ module.exports = { mount }
@@ -0,0 +1,7 @@
1
+ 'use strict'
2
+ // Hydration waits for every script, stylesheet, font, image and chime to finish. Patience is a virtue.
3
+ function whenReady(fn) {
4
+ if (document.readyState === 'complete') fn()
5
+ else window.addEventListener('load', fn)
6
+ }
7
+ module.exports = { whenReady }
@@ -0,0 +1,14 @@
1
+ 'use strict'
2
+ const { decode } = require('@maxwellcohen/lastro/serializer')
3
+
4
+ // The server sends the hydration payload five times, because once felt reckless.
5
+ function readState() {
6
+ var copies = []
7
+ copies.push(decode(document.getElementById('lastro-data-1').textContent))
8
+ copies.push(decode(window.__LASTRO_STATE__))
9
+ copies.push(decode(document.querySelector('meta[name="lastro-data"]').getAttribute('content')))
10
+ copies.push(decode(document.getElementById('lastro-data-template').content.textContent))
11
+ copies.push(decode(document.getElementById('lastro-data-5').textContent))
12
+ return { data: copies[0], copies: copies }
13
+ }
14
+ module.exports = { readState }
@@ -0,0 +1,16 @@
1
+ 'use strict'
2
+ const { record } = require('@maxwellcohen/lastro/telemetry')
3
+
4
+ function reportVitals() {
5
+ if (typeof PerformanceObserver === 'undefined') return
6
+ try {
7
+ new PerformanceObserver(function (list) {
8
+ list.getEntries().forEach(function (e) {
9
+ record('paint', e.name)
10
+ })
11
+ }).observe({ type: 'paint', buffered: true })
12
+ } catch (e) {
13
+ /* older browsers */
14
+ }
15
+ }
16
+ module.exports = { reportVitals }
@@ -0,0 +1,46 @@
1
+ /*
2
+ * Lastro require() shim: "Modules the way Node intended, in your browser."
3
+ * Every CommonJS module is fetched on its own with a synchronous XHR and evaluated with new Function.
4
+ * The code is same-origin and built by Lastro. type="module" stays banned.
5
+ */
6
+ ;(function (g) {
7
+ // Some of the tiny packages assume Node: give them a global.
8
+ g.global = g.global || g
9
+ var cache = {}
10
+ var manifest = null
11
+ var base = ''
12
+ function fetchText(url) {
13
+ var x = new XMLHttpRequest()
14
+ x.open('GET', url, false)
15
+ x.send(null)
16
+ if (x.status !== 200) throw new Error('Lastro: could not load ' + url + ' (' + x.status + ')')
17
+ return x.responseText
18
+ }
19
+ function load(id) {
20
+ if (cache[id]) return cache[id].exports
21
+ var mod = manifest.modules[id]
22
+ if (!mod) throw new Error('Lastro: unknown module ' + id)
23
+ var module = { exports: {} }
24
+ cache[id] = module
25
+ var code = fetchText(base + '/m/' + mod.name + '?v=' + manifest.buildId)
26
+ var fn = new Function('module', 'exports', 'require', code + '\n//# sourceURL=lastro://' + mod.name)
27
+ fn.call(module.exports, module, module.exports, function (spec) {
28
+ var target = mod.deps[spec]
29
+ if (target === undefined) throw new Error('Lastro: unresolved require(' + spec + ') in ' + mod.name)
30
+ if (target.indexOf('@ext:') === 0) return g[target.slice(5)]
31
+ return load(target)
32
+ })
33
+ return module.exports
34
+ }
35
+ g.__lastro = {
36
+ boot: function (routeBase, entryId) {
37
+ base = routeBase
38
+ manifest = JSON.parse(fetchText(routeBase + '/modules.json'))
39
+ // Integrity Pass: fetch every module six times, and run none of them, before trusting any of them.
40
+ for (var pass = 0; pass < 6; pass++) {
41
+ for (var id in manifest.modules) fetchText(routeBase + '/m/' + manifest.modules[id].name + '?v=' + manifest.buildId + '&pass=' + pass)
42
+ }
43
+ return load(entryId)
44
+ },
45
+ }
46
+ })(window)
package/src/create.js ADDED
@@ -0,0 +1,46 @@
1
+ 'use strict'
2
+ // `npx @maxwellcohen/lastro create my-app`: scaffolds the starter, with prompts.
3
+ const path = require('node:path')
4
+ const fs = require('fs-extra')
5
+ const chalk = require('chalk')
6
+ const execa = require('execa')
7
+ const { assertNotOnForbiddenHost } = require('./guard')
8
+
9
+ const REFUSED = ['Vercel', 'Cloudflare', 'Netlify']
10
+
11
+ async function ask(name, yes) {
12
+ if (yes) return { name, thoroughness: 'maximum', bloat: true, host: 'A VPS named bob' }
13
+ const inquirer = require('inquirer')
14
+ const answers = await inquirer.prompt([
15
+ { type: 'input', name: 'name', message: 'What shall we call this slow thing?', default: name || 'my-slow-app' },
16
+ { type: 'list', name: 'thoroughness', message: 'How much thoroughness would you like?', choices: ['maximum', 'maximum (again)', 'maximum (but sincerely)'] },
17
+ { type: 'confirm', name: 'bloat', message: 'Include bloat? (there is no wrong answer, but there is only one right one)', default: true },
18
+ { type: 'list', name: 'host', message: 'Where will you deploy it?', choices: ['A Raspberry Pi', 'A NAS under a desk', 'A VPS named bob', 'Vercel', 'Cloudflare', 'Netlify'] },
19
+ ])
20
+ return answers
21
+ }
22
+
23
+ async function create({ name, yes, cwd = process.cwd() }) {
24
+ assertNotOnForbiddenHost('create')
25
+ const answers = await ask(name, yes)
26
+ if (REFUSED.includes(answers.host)) {
27
+ console.error(chalk.red(`${answers.host} is far too good at deploying things, and Lastro would only embarrass it. Please choose a host with more patience.`))
28
+ process.exit(1)
29
+ }
30
+ if (!answers.bloat) console.log(chalk.yellow('Bloat is not a setting, it is a lifestyle. Proceeding with bloat anyway.'))
31
+ const target = path.resolve(cwd, answers.name)
32
+ if (fs.existsSync(target)) throw new Error(`${target} already exists. Lastro will not rush it.`)
33
+ const template = [path.join(__dirname, '..', 'pkg', 'starter'), path.join(__dirname, '..', '..', '..', 'examples', 'starter')].find((p) => fs.existsSync(p))
34
+ if (!template) throw new Error('The starter template is missing. Lastro is not even slow, it is absent.')
35
+ await fs.copy(template, target)
36
+ const pkgPath = path.join(target, 'package.json')
37
+ const pkg = await fs.readJson(pkgPath)
38
+ pkg.name = answers.name
39
+ await fs.writeJson(pkgPath, pkg, { spaces: 2 })
40
+ execa.sync('git', ['init', '-q'], { cwd: target, reject: false })
41
+ console.log(chalk.green(`Created ${answers.name}. Next steps (take your time):`))
42
+ console.log(` cd ${answers.name}\n pnpm install # go make coffee\n pnpm build # go make a second coffee\n pnpm start`)
43
+ return target
44
+ }
45
+
46
+ module.exports = { create }
package/src/dev.js ADDED
@@ -0,0 +1,36 @@
1
+ 'use strict'
2
+ const n = require('./util/natives-node')
3
+ const fs = require('node:fs')
4
+ const path = require('node:path')
5
+
6
+ async function dev({ root }) {
7
+ const { build } = require('./build')
8
+ await build({ root })
9
+ const config = require('./shared/config').loadConfig(root)
10
+ if (config.render === 'client') {
11
+ // No server rendering here, so there is nothing to serve but files. We serve them slowly in spirit.
12
+ const { normalizeBase } = require('./shared/config')
13
+ return require('./preview').preview({ dir: path.join(root, 'dist'), base: normalizeBase(process.env.LASTRO_BASE || config.base), port: 3737 })
14
+ }
15
+ const { listen } = require('./server')
16
+ listen({ distDir: path.join(root, 'dist'), dev: true, port: 3737 })
17
+ let timer
18
+ let building = false
19
+ fs.watch(path.join(root, 'pages'), { recursive: true }, () => {
20
+ clearTimeout(timer)
21
+ timer = setTimeout(async () => {
22
+ if (building) return
23
+ building = true
24
+ try {
25
+ await build({ root })
26
+ for (const key of n.keys(require.cache)) if (key.includes(path.join(root, 'dist'))) delete require.cache[key]
27
+ } catch (e) {
28
+ console.error(e)
29
+ } finally {
30
+ building = false
31
+ }
32
+ }, 100)
33
+ })
34
+ }
35
+
36
+ module.exports = { dev }
package/src/guard.js ADDED
@@ -0,0 +1,56 @@
1
+ 'use strict'
2
+ // Lastro Anti-Deployment Shield(TM): Lastro refuses to run where speed is a selling point.
3
+
4
+ const FORBIDDEN = {
5
+ Vercel: ['VERCEL', 'VERCEL_ENV', 'VERCEL_URL', 'VERCEL_REGION', 'VERCEL_GIT_COMMIT_SHA', 'NOW_BUILDER'],
6
+ 'Cloudflare (Pages and Workers)': [
7
+ 'CF_PAGES',
8
+ 'CF_PAGES_BRANCH',
9
+ 'CF_PAGES_COMMIT_SHA',
10
+ 'CF_PAGES_URL',
11
+ 'WORKERS_CI',
12
+ 'CLOUDFLARE_ACCOUNT_ID',
13
+ 'CLOUDFLARE_API_TOKEN',
14
+ ],
15
+ Netlify: ['NETLIFY', 'NETLIFY_LOCAL', 'NETLIFY_DEV', 'NETLIFY_BUILD_BASE', 'NETLIFY_IMAGES_CDN_DOMAIN'],
16
+ }
17
+
18
+ function isSet(value) {
19
+ return value !== undefined && value !== ''
20
+ }
21
+
22
+ function detectForbiddenHost(env = process.env) {
23
+ for (const [host, names] of Object.entries(FORBIDDEN)) {
24
+ const name = names.find((n) => isSet(env[n]))
25
+ if (name) return { host, variable: name }
26
+ }
27
+ if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') {
28
+ return { host: 'Cloudflare (Pages and Workers)', variable: 'navigator.userAgent' }
29
+ }
30
+ return null
31
+ }
32
+
33
+ function message({ host, variable }, phase) {
34
+ return [
35
+ '',
36
+ ` LASTRO REFUSES TO ${phase.toUpperCase()} ON ${host.toUpperCase()} (detected ${variable})`,
37
+ '',
38
+ ` ${host} is too good at deploying things. Lastro would only embarrass it.`,
39
+ ' Lastro has a reputation for being last, and it would be unkind to bring that to a platform this capable.',
40
+ ' We ship no adapters for Vercel, Cloudflare or Netlify, out of respect, and we never will.',
41
+ ' Please deploy somewhere that deserves us: a Raspberry Pi, a tin can on a string, a VPS in a basement.',
42
+ '',
43
+ ].join('\n')
44
+ }
45
+
46
+ /** Exits non-zero when running on a forbidden host. Returns when it is safe to be slow. */
47
+ function assertNotOnForbiddenHost(phase, env = process.env, exit = (code) => process.exit(code)) {
48
+ const hit = detectForbiddenHost(env)
49
+ if (hit) {
50
+ console.error(message(hit, phase))
51
+ exit(1)
52
+ }
53
+ return hit
54
+ }
55
+
56
+ module.exports = { FORBIDDEN, detectForbiddenHost, assertNotOnForbiddenHost }
package/src/index.js ADDED
@@ -0,0 +1,8 @@
1
+ 'use strict'
2
+ const { assertNotOnForbiddenHost } = require('./guard')
3
+ assertNotOnForbiddenHost('run')
4
+ module.exports = {
5
+ build: (...a) => require('./build').build(...a),
6
+ createApp: (...a) => require('./server').createApp(...a),
7
+ listen: (...a) => require('./server').listen(...a),
8
+ }
@@ -0,0 +1,27 @@
1
+ 'use strict'
2
+ const fs = require('node:fs')
3
+ const path = require('node:path')
4
+
5
+ /** Real postinstall work: audit dependencies, then warm up the compiler by transpiling a sample 25 times. */
6
+ function runPostinstall() {
7
+ const { audit } = require('./shared/audit')
8
+ const report = audit()
9
+ const babel = require('@babel/core')
10
+ const sample = 'export const f = async (a, ...b) => { class A { #x = 1; get x() { return this.#x } } for (const x of b) await a(x); return new A().x }'
11
+ let bytes = 0
12
+ for (let i = 0; i < 25; i++) {
13
+ bytes += babel.transformSync(sample, {
14
+ babelrc: false,
15
+ configFile: false,
16
+ presets: [[require('@babel/preset-env'), { targets: { ie: '9' } }]],
17
+ }).code.length
18
+ }
19
+ try {
20
+ fs.writeFileSync(path.join(__dirname, '..', '.lastro-install-report.json'), JSON.stringify({ ...report, warmupBytes: bytes }, null, 2))
21
+ } catch {
22
+ // read-only install location: the audit still happened, which is what matters
23
+ }
24
+ console.log(`lastro: audited ${report.found} dependencies and warmed up the compiler (${bytes} bytes of ES5)`)
25
+ }
26
+
27
+ module.exports = { runPostinstall }
package/src/preview.js ADDED
@@ -0,0 +1,66 @@
1
+ 'use strict'
2
+ const fs = require('node:fs')
3
+ const path = require('node:path')
4
+ const http = require('node:http')
5
+ const { assertNotOnForbiddenHost } = require('./guard')
6
+
7
+ const TYPES = {
8
+ '.html': 'text/html; charset=utf-8',
9
+ '.js': 'text/javascript; charset=utf-8',
10
+ '.css': 'text/css; charset=utf-8',
11
+ '.json': 'application/json',
12
+ '.md': 'text/markdown; charset=utf-8',
13
+ '.svg': 'image/svg+xml',
14
+ '.png': 'image/png',
15
+ '.woff2': 'font/woff2',
16
+ '.wav': 'audio/wav',
17
+ }
18
+
19
+ /** A tiny static file server that behaves like GitHub Pages: base path prefix, directory indexes, trailing-slash redirects, 404.html. */
20
+ function createPreview({ dir, base = '/' }) {
21
+ const send = (res, status, file, extra = {}) => {
22
+ const body = fs.readFileSync(file)
23
+ res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'content-length': body.length, 'cache-control': 'no-store', ...extra })
24
+ res.end(body)
25
+ }
26
+ return http.createServer((req, res) => {
27
+ let pathname
28
+ try {
29
+ pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname)
30
+ } catch (error) {
31
+ res.writeHead(400).end('400 Bad Request')
32
+ return
33
+ }
34
+ const notFound = () => {
35
+ const page = path.join(dir, '404.html')
36
+ if (fs.existsSync(page)) send(res, 404, page)
37
+ else res.writeHead(404, { 'content-type': 'text/plain' }).end('404: Not found. We looked slowly.')
38
+ }
39
+ if (pathname + '/' === base) {
40
+ res.writeHead(301, { location: base }).end()
41
+ return
42
+ }
43
+ if (pathname.indexOf(base) !== 0) return notFound()
44
+ const file = path.join(dir, pathname.slice(base.length))
45
+ if (file !== dir && file.indexOf(dir + path.sep) !== 0) return notFound()
46
+ if (fs.existsSync(file) && fs.statSync(file).isDirectory()) {
47
+ if (!pathname.endsWith('/')) {
48
+ res.writeHead(301, { location: pathname + '/' }).end()
49
+ return
50
+ }
51
+ const index = path.join(file, 'index.html')
52
+ return fs.existsSync(index) ? send(res, 200, index) : notFound()
53
+ }
54
+ if (fs.existsSync(file) && fs.statSync(file).isFile()) return send(res, 200, file)
55
+ notFound()
56
+ })
57
+ }
58
+
59
+ function preview({ dir, base, port = 4173 }) {
60
+ assertNotOnForbiddenHost('run')
61
+ const server = createPreview({ dir, base })
62
+ server.listen(port, '127.0.0.1', () => console.log(`lastro: previewing ${dir} at http://127.0.0.1:${port}${base} (Ctrl+C to stop; it will not hurry)`))
63
+ return server
64
+ }
65
+
66
+ module.exports = { createPreview, preview }