orvyn-lang 0.2.0 → 0.4.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 (63) hide show
  1. package/GUIDE.md +198 -0
  2. package/LANGUAGE.md +818 -30
  3. package/README.md +211 -250
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +207 -16
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +152 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +615 -58
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +69 -8
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +65 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +176 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +970 -50
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/assets.js +39 -0
  27. package/src/lang/native/build.js +140 -63
  28. package/src/lang/native/compatibility.js +57 -0
  29. package/src/lang/native/config.js +108 -0
  30. package/src/lang/native/ios/OrvynApp.swift +6 -0
  31. package/src/lang/native/ios/OrvynEngine.swift +291 -4
  32. package/src/lang/native/ios/OrvynViews.swift +769 -41
  33. package/src/lang/native/ios.js +81 -2
  34. package/src/lang/native-runtime.js +541 -55
  35. package/src/lang/native-size.js +53 -0
  36. package/src/lang/page-files.js +71 -0
  37. package/src/lang/page.js +63 -0
  38. package/src/lang/parser.js +278 -15
  39. package/src/lang/prerender.js +300 -0
  40. package/src/lang/read-import.js +12 -0
  41. package/src/lang/router.js +266 -0
  42. package/src/lang/runtime-shared.js +796 -10
  43. package/src/lang/runtime.js +399 -51
  44. package/src/lang/select.js +13 -0
  45. package/src/lang/server-code.js +233 -0
  46. package/src/lang/server-export.js +78 -0
  47. package/src/lang/server-libs.js +53 -0
  48. package/src/lang/server.js +409 -0
  49. package/src/lang/style-check.js +60 -0
  50. package/src/lang/test-runner.js +134 -0
  51. package/src/lang/types.js +317 -0
  52. package/src/lang/vite-plugin.js +108 -6
  53. package/src/lang/web-overlay.js +578 -0
  54. package/src/lang/widgets.js +94 -0
  55. package/src/lang/words.js +38 -0
  56. package/src/runtime/animations.js +24 -0
  57. package/src/runtime/appear.js +73 -0
  58. package/src/runtime/marquee.js +57 -0
  59. package/src/runtime/mount.js +120 -27
  60. package/src/runtime/patch.js +90 -11
  61. package/src/runtime/style.js +50 -9
  62. package/src/styling/fluid.js +129 -6
  63. package/src/styling/spec.js +319 -0
package/src/cli/orvyn.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  statSync,
9
9
  writeFileSync
10
10
  } from "node:fs"
11
- import { join, relative } from "node:path"
11
+ import { basename, join, relative, resolve } from "node:path"
12
12
 
13
13
  const cwd = process.cwd()
14
14
 
@@ -18,6 +18,23 @@ let command =
18
18
  let args =
19
19
  process.argv.slice(3)
20
20
 
21
+ // --env staging (or --env=staging) works with every command
22
+ const envAt = args.findIndex(arg => arg === "--env" || arg.startsWith("--env="))
23
+ if (envAt >= 0) {
24
+ const inline = args[envAt].includes("=")
25
+ const name = inline ? args[envAt].slice("--env=".length) : args[envAt + 1]
26
+ if (!name || name.startsWith("-")) {
27
+ process.stdout.write("--env needs a name, like --env prod\n")
28
+ process.exit(1)
29
+ }
30
+ process.env.ORVYN_ENV = name
31
+ args.splice(envAt, inline ? 1 : 2)
32
+ }
33
+
34
+ const releaseAt = args.indexOf("--release")
35
+ const release = releaseAt >= 0
36
+ if (release) args.splice(releaseAt, 1)
37
+
21
38
  // ---------------------------------------------------------------------------
22
39
  // Orvyn language projects get short commands:
23
40
  // orvyn dev | ios | android | check | build | preview
@@ -46,7 +63,8 @@ if (orvEntry && !hasOrvArg) {
46
63
  command = "dev"
47
64
  args = ["ios", orvEntry, ...args]
48
65
  } else if (command === "android") {
49
- command = "run"
66
+ // live reload, like the iPhone
67
+ command = "dev"
50
68
  args = ["android", orvEntry, ...args]
51
69
  } else if (
52
70
  (command === "dev" || command === "run" || command === "build") &&
@@ -151,13 +169,35 @@ async function compileOrv(mode, commandArgs) {
151
169
  const { compile, OrvynSyntaxError } =
152
170
  await import("../lang/index.js")
153
171
 
154
- const source = readFileSync(file, "utf-8")
172
+ const { withPageFiles } = await import("../lang/page-files.js")
173
+ const source = withPageFiles(readFileSync(file, "utf-8"), file)
155
174
 
175
+ let env
156
176
  try {
157
- const code = compile(source)
177
+ const { loadEnv } = await import("../lang/env.js")
178
+ env = await loadEnv(cwd, "dev")
179
+ } catch (error) {
180
+ log(error.message)
181
+ process.exit(1)
182
+ }
183
+
184
+ try {
185
+ const { readImportFrom } = await import("../lang/read-import.js")
186
+ const code = compile(source, { env, tests: mode === "check", resolveImport: readImportFrom(file) })
158
187
 
159
188
  if (mode === "check") {
160
- log(`✓ ${file} has no errors`)
189
+ const { collectProjectPrograms } = await import("../lang/page-files.js")
190
+ const { checkProjectAccessibility } = await import("../lang/a11y.js")
191
+ const { checkNativeCompatibility } = await import("../lang/native/compatibility.js")
192
+ const { checkStyleProps } = await import("../lang/style-check.js")
193
+ const files = collectProjectPrograms(file)
194
+ const warnings = [
195
+ ...checkProjectAccessibility(files),
196
+ ...files.flatMap(item => checkStyleProps(item.program).map(warning => ({ ...warning, file: item.file }))),
197
+ ...files.flatMap(item => checkNativeCompatibility(item.program).map(warning => ({ ...warning, file: item.file })))
198
+ ]
199
+ for (const warning of warnings) log(`⚠ ${relative(cwd, warning.file) || warning.file}:${warning.line}:${warning.col} ${warning.message}`)
200
+ log(`✓ ${file} has no errors${warnings.length ? `, ${warnings.length} warning(s)` : ""}`)
161
201
  } else if (outFile) {
162
202
  writeFileSync(outFile, code)
163
203
  log(`✓ Compiled ${file} → ${outFile}`)
@@ -178,26 +218,106 @@ async function compileOrv(mode, commandArgs) {
178
218
  }
179
219
  }
180
220
 
221
+ async function testOrv(commandArgs) {
222
+ const files = commandArgs.filter(arg => arg.endsWith(".orv"))
223
+ if (!files.length && orvEntry) files.push(orvEntry)
224
+ if (!files.length) {
225
+ log("Usage: orvyn test <file.orv>")
226
+ process.exit(1)
227
+ }
228
+ const { runTests } = await import("../lang/test-runner.js")
229
+ const { loadEnv } = await import("../lang/env.js")
230
+ let failed = 0
231
+ let total = 0
232
+ for (const file of files) {
233
+ try {
234
+ for (const result of await runTests(file, await loadEnv(cwd, "dev"))) {
235
+ total++
236
+ log(`${result.ok ? "✓" : "✗"} ${file}: ${result.name}`)
237
+ if (!result.ok) {
238
+ failed++
239
+ log(` ${result.error}`)
240
+ }
241
+ }
242
+ } catch (error) {
243
+ failed++
244
+ log(`✗ ${file}: ${error.message}`)
245
+ }
246
+ }
247
+ log(total || failed ? `\n${total} test(s), ${failed} failed` : `No tests yet. Add: test "opens" { expect(text("Hello")) }`)
248
+ process.exit(failed ? 1 : 0)
249
+ }
250
+
251
+ // orvyn serve [server.orv] [--port 3000] [--host 0.0.0.0]
252
+ // orvyn admin you@example.com [server.orv]
253
+ async function serverOrv(mode, commandArgs) {
254
+ const option = (name, fallback) => {
255
+ const at = commandArgs.indexOf(name)
256
+ return at >= 0 ? commandArgs.splice(at, 2)[1] : fallback
257
+ }
258
+ const port = Number(option("--port", process.env.PORT || 3000))
259
+ const host = option("--host", process.env.HOST || "127.0.0.1")
260
+ const file = commandArgs.find(arg => arg.endsWith(".orv")) ||
261
+ ["src/server.orv", "server.orv"].find(path => existsSync(join(cwd, path)))
262
+ if (!file || !existsSync(file)) {
263
+ log("No server file. Create server.orv, like:\n\n table notes {\n text: text required\n }")
264
+ process.exit(1)
265
+ }
266
+ try {
267
+ const { parseServer, openDatabase, createApi, makeAdmin } = await import("../lang/server.js")
268
+ const tables = parseServer(readFileSync(file, "utf-8"))
269
+ const { loadLibraries } = await import("../lang/server-libs.js")
270
+ tables.libraries = await loadLibraries(tables.uses ?? [], file)
271
+ const db = openDatabase(process.env.ORVYN_DB || join(cwd, "orvyn.db"), tables)
272
+ if (mode === "admin") {
273
+ const email = commandArgs.find(arg => arg.includes("@"))
274
+ if (!email || !makeAdmin(db, email)) {
275
+ log("Usage: orvyn admin you@example.com (sign up with that email first)")
276
+ process.exit(1)
277
+ }
278
+ log(`✓ ${email} is now an admin`)
279
+ process.exit(0)
280
+ }
281
+ const origins = (process.env.ORVYN_ORIGINS || "").split(",").map(s => s.trim()).filter(Boolean)
282
+ const server = createApi(tables, db, { origins })
283
+ server.on("error", error => {
284
+ log(`✗ ${error.message}`)
285
+ process.exit(1)
286
+ })
287
+ server.listen(port, host, () => {
288
+ log(`[Orvyn] ✓ Server → http://${host === "0.0.0.0" ? "localhost" : host}:${port}/api`)
289
+ for (const table of tables) {
290
+ log(` /api/${table.name.padEnd(16)} ${table.locked ? "only your server code changes" : table.admin ? "only admins change" : "owners change"}, ${table.public ? "anyone reads" : table.admin ? "admins see their own" : "private to each person"}`)
291
+ }
292
+ for (const api of tables.apis ?? []) log(` ${api.method.padEnd(4)} /api${api.path}${api.requires ? ` (requires ${api.requires})` : ""}`)
293
+ })
294
+ } catch (error) {
295
+ log(`✗ ${file}: ${error.message}`)
296
+ process.exit(1)
297
+ }
298
+ }
299
+
181
300
  function newOrvProject(name) {
182
301
  if (!name) {
183
302
  log("Usage: orvyn new <app-name>")
184
303
  process.exit(1)
185
304
  }
186
305
 
187
- const dir = join(cwd, name)
306
+ const dir = resolve(cwd, name)
188
307
  if (existsSync(dir) && readdirSync(dir).length > 0) {
189
308
  log(`Folder "${name}" already exists and is not empty.`)
190
309
  process.exit(1)
191
310
  }
192
311
 
312
+ const folderName = basename(dir) || "my-app"
193
313
  const orvynRoot = join(new URL(".", import.meta.url).pathname, "..", "..")
194
314
  const orvynPkg = JSON.parse(readFileSync(join(orvynRoot, "package.json"), "utf-8"))
195
315
  const orvynVersion = orvynPkg.version
196
316
  // from the repo (npm link) the package is "orvyn"; from npm it's "orvyn-lang"
197
317
  const fromSource = existsSync(join(orvynRoot, "src", "lang", "index.ts"))
198
318
  const orvynName = orvynPkg.name
199
- const pretty = name.replace(/[-_]+/g, " ").replace(/\b\w/g, c => c.toUpperCase())
200
- const id = name.toLowerCase().replace(/[^a-z0-9]/g, "")
319
+ const pretty = folderName.replace(/[-_]+/g, " ").replace(/\b\w/g, c => c.toUpperCase())
320
+ const id = folderName.toLowerCase().replace(/[^a-z0-9]/g, "")
201
321
 
202
322
  const orvynDep = fromSource
203
323
  ? `file:${relative(dir, orvynRoot) || "."}`
@@ -214,6 +334,7 @@ function newOrvProject(name) {
214
334
  ios: "orvyn ios",
215
335
  android: "orvyn android",
216
336
  check: "orvyn check",
337
+ test: "orvyn test",
217
338
  build: "orvyn build"
218
339
  },
219
340
  dependencies: { [orvynName]: orvynDep },
@@ -226,7 +347,19 @@ function newOrvProject(name) {
226
347
  appId: ${JSON.stringify(`com.example.${id || "app"}`)},
227
348
  version: "1.0.0",
228
349
  ios: { deploymentTarget: "16.0" },
229
- android: { minSdk: 24, targetSdk: 34 }
350
+ // For the stores, add your own appId and:
351
+ // icon: "assets/icon.png", // 1024 x 1024 PNG, no transparency
352
+ // splash: { color: "#ffffff" },
353
+ // permissions: { camera: "To scan codes" },
354
+ android: { minSdk: 24, targetSdk: 36 } // , keystore: "upload.jks", keyAlias: "upload"
355
+ },
356
+ // your website address, for sitemap.xml: site: "https://example.com",
357
+ // seo: { allowAI: false }, // ask AI crawlers not to read your site
358
+ // read in .orv code as env.API_URL. These values ship inside the app: no secrets.
359
+ env: {
360
+ dev: { API_URL: "http://localhost:3000" },
361
+ staging: { API_URL: "https://staging.example.com" },
362
+ prod: { API_URL: "https://api.example.com" }
230
363
  }
231
364
  }
232
365
  `,
@@ -262,15 +395,23 @@ export default defineConfig({
262
395
  state count = 0
263
396
 
264
397
  screen Home {
398
+ page title: "${pretty}", description: "${pretty}, built with Orvyn"
399
+
265
400
  Column gap: 16, padding: 24 {
266
401
  Heading "${pretty}", size: 32
267
402
  Text "You tapped {count} times"
268
403
  Button "Tap me", bg: black, color: white, padding: 12, radius: 10, onTap: count += 1
269
404
  }
270
405
  }
406
+
407
+ // run with: orvyn test
408
+ test "counts taps" {
409
+ tap("Tap me")
410
+ expect(text("You tapped 1 times"))
411
+ }
271
412
  `,
272
413
 
273
- ".gitignore": "node_modules\ndist\n",
414
+ ".gitignore": "node_modules\ndist\norvyn.db*\n*.jks\n*.keystore\n",
274
415
 
275
416
  "README.md": `# ${pretty}
276
417
 
@@ -279,7 +420,8 @@ Built with the Orvyn language (v${orvynVersion}).
279
420
  \`\`\`bash
280
421
  orvyn dev # web → http://localhost:5173 (live reload)
281
422
  orvyn ios # iPhone simulator (live reload, needs Xcode)
282
- orvyn android # Android emulator or phone
423
+ orvyn android # Android emulator or phone, with live reload
424
+ orvyn doctor # what is missing to build and publish
283
425
  orvyn check # find mistakes in src/app.orv
284
426
  orvyn build ios # Xcode project for real iPhones / App Store
285
427
  \`\`\`
@@ -337,7 +479,8 @@ async function nativeOrv(mode, commandArgs) {
337
479
 
338
480
  try {
339
481
  const fn = mode === "run" ? runNativeApp : mode === "dev" ? devNativeApp : buildNativeApp
340
- await fn(target, entry, { cwd, log })
482
+ if (release && mode !== "build") throw new Error("--release only works with: orvyn build ios|android")
483
+ await fn(target, entry, { cwd, log, release })
341
484
  } catch (error) {
342
485
  if (error instanceof OrvynSyntaxError || error?.cause instanceof OrvynSyntaxError) {
343
486
  log(`✗ ${entry}: ${error.message}`)
@@ -358,12 +501,20 @@ function help() {
358
501
  log("Inside your app folder:")
359
502
  log(" orvyn dev Web, with live reload")
360
503
  log(" orvyn ios iPhone simulator, with live reload")
361
- log(" orvyn android Android emulator or phone")
504
+ log(" orvyn android Android emulator or phone, with live reload")
505
+ log(" orvyn doctor Check what is missing to build and publish")
506
+ log(" orvyn build ios --release Signed .ipa for the App Store")
507
+ log(" orvyn build android --release Signed .aab for Google Play")
362
508
  log(" orvyn check Find mistakes in your code")
509
+ log(" orvyn test Run the test blocks in your app")
510
+ log(" orvyn serve Backend with database and login (server.orv)")
511
+ log(" orvyn admin EMAIL Let an account change admin tables")
512
+ log(" orvyn build server Folder to upload to your host → dist/server/")
363
513
  log(" orvyn build Website → dist/web/")
364
514
  log(" orvyn build ios Xcode project → dist/ios/ (for real iPhones / App Store)")
365
515
  log(" orvyn build android Android Studio project → dist/android/")
366
516
  log(" orvyn preview Preview the built website")
517
+ log(" --env staging Use another environment (dev and run: dev, build: prod)")
367
518
  log("")
368
519
  log("Any .orv file:")
369
520
  log(" orvyn compile app.orv Compile .orv to JavaScript (prints it)")
@@ -372,15 +523,55 @@ function help() {
372
523
  log(" orvyn build ios app.orv Build a native iPhone app (SwiftUI)")
373
524
  log(" orvyn build android app.orv Build a native Android app")
374
525
  log(" orvyn dev ios app.orv iPhone simulator with live reload")
526
+ log(" orvyn dev android app.orv Android with live reload")
375
527
  log(" orvyn run ios app.orv Build and open it in the iPhone simulator")
376
528
  log(" orvyn run android app.orv Build and install on an emulator/phone")
377
529
  }
378
530
 
379
- if (command === "web-dev") {
380
- run(viteBinary(), args)
531
+ if (command === "build" && args[0] === "server") {
532
+ const file = args.find(arg => arg.endsWith(".orv")) ||
533
+ ["src/server.orv", "server.orv"].find(path => existsSync(join(cwd, path)))
534
+ try {
535
+ if (!file) throw new Error("No server.orv here")
536
+ const { exportServer } = await import("../lang/server-export.js")
537
+ const files = exportServer(file, join(cwd, "dist/server"))
538
+ log(`[Orvyn] ✓ Server ready to upload → dist/server/ (${files.join(", ")})`)
539
+ } catch (error) {
540
+ log(`✗ ${error.message}`)
541
+ process.exit(1)
542
+ }
543
+ } else if (release && !(command === "build" && args.some(arg => arg.endsWith(".orv")))) {
544
+ log("--release only works with: orvyn build ios|android")
545
+ process.exit(1)
546
+ } else if (command === "serve" || command === "admin") {
547
+ await serverOrv(command, args)
548
+ } else if (command === "test") {
549
+ await testOrv(args)
550
+ } else if (command === "doctor") {
551
+ const { doctor, formatChecks } = await import("../lang/doctor.js")
552
+ log(formatChecks(await doctor(cwd)))
553
+ } else if (command === "web-dev") {
554
+ const nativePreview = args.includes("--native")
555
+ const devArgs = args.filter(arg => arg !== "--native")
556
+ if (nativePreview && !devArgs.includes("--open")) devArgs.push("--open", "/?native=1")
557
+ run(viteBinary(), devArgs)
381
558
  } else if (command === "web-build") {
382
559
  // dist/web so it never deletes dist/ios or dist/android
383
- run(viteBinary(), ["build", "--outDir", "dist/web", "--emptyOutDir", ...args])
560
+ runSync(viteBinary(), ["build", "--outDir", "dist/web", "--emptyOutDir", ...args])
561
+ if (orvEntry) {
562
+ try {
563
+ const { prerender } = await import("../lang/prerender.js")
564
+ const { loadEnv } = await import("../lang/env.js")
565
+ const files = await prerender(cwd, orvEntry, join(cwd, "dist/web"), await loadEnv(cwd, "prod"))
566
+ log(`[Orvyn] ✓ Ready-made pages for search engines: ${files.join(", ")}`)
567
+ if (!files.includes("sitemap.xml") && !existsSync(join(cwd, "public", "sitemap.xml"))) {
568
+ log('[Orvyn] Tip: set site: "https://your-domain.com" in orvyn.config.js to generate sitemap.xml and canonical links.')
569
+ }
570
+ } catch (error) {
571
+ log(`[Orvyn] ✗ Could not make ready-made pages: ${error.message}`)
572
+ process.exit(1)
573
+ }
574
+ }
384
575
  } else if (command === "web-preview") {
385
576
  run(viteBinary(), ["preview", "--outDir", "dist/web", ...args])
386
577
  } else if ((command === "build" || command === "run" || command === "dev") && args.some(arg => arg.endsWith(".orv"))) {
@@ -7,13 +7,54 @@ import {
7
7
  recordSignalSubscriber,
8
8
  recordSignalUpdate,
9
9
  registerEffect,
10
- registerSignal
10
+ registerSignal,
11
+ unregisterEffect,
12
+ unregisterSignal
11
13
  } from "../devtools/runtime.js";
12
14
  let activeEffect = null;
15
+ let currentOwner = null;
13
16
  let activeEffectId = null;
14
17
  let signalId = 0;
15
18
  const signalRegistry = /* @__PURE__ */ new Map();
16
19
  const resumedValues = /* @__PURE__ */ new Map();
20
+ function createOwner() {
21
+ return {
22
+ cleanups: [],
23
+ disposed: false
24
+ };
25
+ }
26
+ function getOwner() {
27
+ return currentOwner;
28
+ }
29
+ function runWithOwner(owner, fn) {
30
+ const previous = currentOwner;
31
+ currentOwner = owner;
32
+ try {
33
+ return fn();
34
+ } finally {
35
+ currentOwner = previous;
36
+ }
37
+ }
38
+ function onCleanup(fn) {
39
+ if (!currentOwner) return;
40
+ if (currentOwner.disposed) {
41
+ fn();
42
+ return;
43
+ }
44
+ currentOwner.cleanups.push(fn);
45
+ }
46
+ function disposeOwner(owner, final = true) {
47
+ const cleanups = owner.cleanups;
48
+ owner.cleanups = [];
49
+ if (final) owner.disposed = true;
50
+ for (let i = cleanups.length - 1; i >= 0; i--) {
51
+ try {
52
+ cleanups[i]();
53
+ } catch (error) {
54
+ console.error("[Orvyn] cleanup failed", error);
55
+ }
56
+ }
57
+ }
17
58
  function normalizeOptions(options) {
18
59
  if (typeof options === "string") {
19
60
  return {
@@ -30,11 +71,12 @@ function signal(initial, options) {
30
71
  const restore = (newValue) => {
31
72
  value = newValue;
32
73
  };
33
- signalRegistry.set(id, {
74
+ const record = {
34
75
  id,
35
76
  get: () => value,
36
77
  restore
37
- });
78
+ };
79
+ signalRegistry.set(id, record);
38
80
  registerSignal(
39
81
  id,
40
82
  value
@@ -45,6 +87,7 @@ function signal(initial, options) {
45
87
  get() {
46
88
  if (activeEffect) {
47
89
  subscribers.add(activeEffect);
90
+ activeEffect.deps.add(subscribers);
48
91
  recordSignalSubscriber(
49
92
  id,
50
93
  subscribers.size
@@ -64,16 +107,41 @@ function signal(initial, options) {
64
107
  id,
65
108
  value
66
109
  );
67
- subscribers.forEach((fn) => {
110
+ Array.from(subscribers).forEach((fn) => {
68
111
  schedule(fn);
69
112
  });
70
113
  },
114
+ // Calls fn after every change. Inside a component or screen the
115
+ // subscription ends when it is removed; the returned function ends it early.
71
116
  subscribe(fn) {
72
- subscribers.add(fn);
117
+ let active = true;
118
+ const listener = () => {
119
+ if (active) fn();
120
+ };
121
+ subscribers.add(listener);
73
122
  recordSignalSubscriber(
74
123
  id,
75
124
  subscribers.size
76
125
  );
126
+ const unsubscribe = () => {
127
+ active = false;
128
+ subscribers.delete(listener);
129
+ };
130
+ onCleanup(unsubscribe);
131
+ return unsubscribe;
132
+ },
133
+ // Number of effects and subscriptions currently watching this value.
134
+ subscriberCount() {
135
+ return subscribers.size;
136
+ },
137
+ // Forget a signal that is no longer used anywhere (for example the error
138
+ // state of a form that was removed).
139
+ dispose() {
140
+ subscribers.clear();
141
+ if (signalRegistry.get(id) === record) {
142
+ signalRegistry.delete(id);
143
+ unregisterSignal(id);
144
+ }
77
145
  }
78
146
  };
79
147
  }
@@ -112,11 +180,24 @@ function restoreSignalState(state = {}) {
112
180
  }
113
181
  function effect(fn) {
114
182
  const id = registerEffect(fn.name || "effect");
115
- const runner = () => {
183
+ const runOwner = createOwner();
184
+ let stopped = false;
185
+ const leaveDependencies = () => {
186
+ runner.deps.forEach((subscribers) => {
187
+ subscribers.delete(runner);
188
+ });
189
+ runner.deps.clear();
190
+ };
191
+ const runner = (() => {
192
+ if (stopped) return;
193
+ leaveDependencies();
194
+ disposeOwner(runOwner, false);
116
195
  const previousEffect = activeEffect;
117
196
  const previousEffectId = activeEffectId;
197
+ const previousOwner = currentOwner;
118
198
  activeEffect = runner;
119
199
  activeEffectId = id;
200
+ currentOwner = runOwner;
120
201
  if (globalThis.__ORVYN_DEBUG__) {
121
202
  console.log("[Orvyn Effect Triggered]", id);
122
203
  }
@@ -130,12 +211,24 @@ function effect(fn) {
130
211
  );
131
212
  activeEffect = previousEffect;
132
213
  activeEffectId = previousEffectId;
214
+ currentOwner = previousOwner;
133
215
  }
216
+ });
217
+ runner.deps = /* @__PURE__ */ new Set();
218
+ const stop = () => {
219
+ if (stopped) return;
220
+ stopped = true;
221
+ leaveDependencies();
222
+ disposeOwner(runOwner);
223
+ unregisterEffect(id);
134
224
  };
225
+ onCleanup(stop);
135
226
  runner();
227
+ return stop;
136
228
  }
137
229
  function computed(fn) {
138
230
  const result = signal(fn());
231
+ onCleanup(() => result.dispose());
139
232
  effect(() => {
140
233
  result.set(fn());
141
234
  });
@@ -143,8 +236,13 @@ function computed(fn) {
143
236
  }
144
237
  export {
145
238
  computed,
239
+ createOwner,
240
+ disposeOwner,
146
241
  effect,
242
+ getOwner,
243
+ onCleanup,
147
244
  restoreSignalState,
245
+ runWithOwner,
148
246
  serializeReactiveGraph,
149
247
  serializeSignalState,
150
248
  signal
@@ -73,6 +73,24 @@ function registerEffect(label = "effect") {
73
73
  });
74
74
  return id;
75
75
  }
76
+ function unregisterEffect(id) {
77
+ if (!effects.delete(id)) return;
78
+ dependencyGraph.forEach((edge) => {
79
+ if (edge.startsWith(`${id}->`)) dependencyGraph.delete(edge);
80
+ });
81
+ }
82
+ function unregisterSignal(id) {
83
+ signals.delete(id);
84
+ }
85
+ function unregisterComponent(id) {
86
+ const component = components.get(id);
87
+ if (!component) return;
88
+ components.delete(id);
89
+ const parent = component.parentId ? components.get(component.parentId) : void 0;
90
+ if (parent) {
91
+ parent.children = parent.children.filter((child) => child !== id);
92
+ }
93
+ }
76
94
  function beginEffectRun(id) {
77
95
  if (!enabled) return now();
78
96
  const effect = effects.get(id);
@@ -80,6 +98,9 @@ function beginEffectRun(id) {
80
98
  effect.runs++;
81
99
  effect.lastRun = now();
82
100
  effect.dependencies = [];
101
+ dependencyGraph.forEach((edge) => {
102
+ if (edge.startsWith(`${id}->`)) dependencyGraph.delete(edge);
103
+ });
83
104
  }
84
105
  return now();
85
106
  }
@@ -186,5 +207,8 @@ export {
186
207
  recordSignalUpdate,
187
208
  registerComponent,
188
209
  registerEffect,
189
- registerSignal
210
+ registerSignal,
211
+ unregisterComponent,
212
+ unregisterEffect,
213
+ unregisterSignal
190
214
  };