@omriashke/dynamico-core 0.1.9 → 0.1.12

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 (77) hide show
  1. package/dist/bookPreview.d.ts +3 -0
  2. package/dist/bookPreview.d.ts.map +1 -1
  3. package/dist/bookPreview.js +5 -0
  4. package/dist/bookPreview.js.map +1 -1
  5. package/dist/constants.d.ts +6 -0
  6. package/dist/constants.d.ts.map +1 -0
  7. package/dist/constants.js +8 -0
  8. package/dist/constants.js.map +1 -0
  9. package/dist/esbuildFlatten.d.ts +15 -0
  10. package/dist/esbuildFlatten.d.ts.map +1 -0
  11. package/dist/esbuildFlatten.js +39 -0
  12. package/dist/esbuildFlatten.js.map +1 -0
  13. package/dist/index.d.ts +7 -3
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +7 -3
  16. package/dist/index.js.map +1 -1
  17. package/dist/loader.d.ts +2 -0
  18. package/dist/loader.d.ts.map +1 -1
  19. package/dist/loader.js +51 -14
  20. package/dist/loader.js.map +1 -1
  21. package/dist/node/bookConfig.d.ts +13 -0
  22. package/dist/node/bookConfig.d.ts.map +1 -0
  23. package/dist/node/bookConfig.js +54 -0
  24. package/dist/node/bookConfig.js.map +1 -0
  25. package/dist/node/index.d.ts +2 -0
  26. package/dist/node/index.d.ts.map +1 -0
  27. package/dist/node/index.js +2 -0
  28. package/dist/node/index.js.map +1 -0
  29. package/dist/packageScope.d.ts.map +1 -1
  30. package/dist/packageScope.js +15 -7
  31. package/dist/packageScope.js.map +1 -1
  32. package/dist/propsSchema.d.ts +2 -0
  33. package/dist/propsSchema.d.ts.map +1 -1
  34. package/dist/propsSchema.js +36 -0
  35. package/dist/propsSchema.js.map +1 -1
  36. package/dist/react/createRuntime.d.ts.map +1 -1
  37. package/dist/react/createRuntime.js +3 -21
  38. package/dist/react/createRuntime.js.map +1 -1
  39. package/dist/react/useRegistryModule.d.ts +4 -0
  40. package/dist/react/useRegistryModule.d.ts.map +1 -0
  41. package/dist/react/useRegistryModule.js +8 -0
  42. package/dist/react/useRegistryModule.js.map +1 -0
  43. package/dist/registry.d.ts +13 -0
  44. package/dist/registry.d.ts.map +1 -1
  45. package/dist/registry.js +52 -5
  46. package/dist/registry.js.map +1 -1
  47. package/dist/registryModule.d.ts.map +1 -1
  48. package/dist/registryModule.js +13 -2
  49. package/dist/registryModule.js.map +1 -1
  50. package/dist/relativeRequires.d.ts +12 -0
  51. package/dist/relativeRequires.d.ts.map +1 -1
  52. package/dist/relativeRequires.js +33 -0
  53. package/dist/relativeRequires.js.map +1 -1
  54. package/dist/sources/remote.d.ts +14 -8
  55. package/dist/sources/remote.d.ts.map +1 -1
  56. package/dist/sources/remote.js +73 -19
  57. package/dist/sources/remote.js.map +1 -1
  58. package/dist/types.d.ts +6 -0
  59. package/dist/types.d.ts.map +1 -1
  60. package/package.json +17 -8
  61. package/src/bookPreview.ts +7 -0
  62. package/src/constants.ts +9 -0
  63. package/src/esbuildFlatten.ts +47 -0
  64. package/src/index.ts +22 -2
  65. package/src/loader.ts +42 -14
  66. package/src/node/bookConfig.ts +63 -0
  67. package/src/node/index.ts +9 -0
  68. package/src/packageScope.ts +15 -7
  69. package/src/propsSchema.ts +35 -0
  70. package/src/react/createRuntime.tsx +3 -16
  71. package/src/react/useRegistryModule.ts +15 -0
  72. package/src/registry.ts +58 -5
  73. package/src/registryModule.ts +12 -3
  74. package/src/relativeRequires.ts +48 -0
  75. package/src/sources/remote.ts +79 -26
  76. package/src/types.ts +6 -0
  77. package/LICENSE +0 -184
@@ -1,3 +1,5 @@
1
+ import type { Diagnostic } from "./types.js";
2
+
1
3
  /** Map a relative require specifier to the flat registry component name (basename). */
2
4
  export function resolveRelativeComponentName(specifier: string): string | null {
3
5
  if (!specifier.startsWith("./") && !specifier.startsWith("../") && !specifier.startsWith("/")) {
@@ -37,3 +39,49 @@ export function collectRelativeComponentDeps(code: string, componentName?: strin
37
39
  }
38
40
  return [...deps];
39
41
  }
42
+
43
+ export interface RelativeImportValidation {
44
+ ok: boolean;
45
+ message?: string;
46
+ diagnostics?: Diagnostic[];
47
+ }
48
+
49
+ /**
50
+ * Reject relative imports that resolve to registry names not in the manifest.
51
+ * Local utility files should be bundled at compile time; any remaining relative
52
+ * require() must target another registered component.
53
+ */
54
+ export function validateRelativeImports(
55
+ code: string,
56
+ registered: ReadonlySet<string>,
57
+ componentName?: string,
58
+ ): RelativeImportValidation {
59
+ const unresolved: string[] = [];
60
+ for (const specifier of extractRelativeRequires(code)) {
61
+ const base = resolveRelativeComponentName(specifier);
62
+ if (!base) continue;
63
+ if (base === componentName) continue;
64
+ if (!registered.has(base)) unresolved.push(specifier);
65
+ }
66
+ if (unresolved.length === 0) return { ok: true };
67
+
68
+ const lines = unresolved.map(
69
+ (spec) =>
70
+ ` ${spec} → registry component '${resolveRelativeComponentName(spec)}' is not registered`,
71
+ );
72
+ const message =
73
+ `relative import(s) must target a registered component or a local file bundled into this module:\n` +
74
+ `${lines.join("\n")}\n` +
75
+ `Push the dependency as its own component, move helpers into this file, ` +
76
+ `import from host scope (e.g. @newscast/utils-app-ui), or colocate as ./sibling.ts (auto-bundled).`;
77
+
78
+ return {
79
+ ok: false,
80
+ message,
81
+ diagnostics: unresolved.map((spec) => ({
82
+ severity: "error" as const,
83
+ message: `unregistered relative import '${spec}'`,
84
+ code: "RELATIVE_IMPORT",
85
+ })),
86
+ };
87
+ }
@@ -14,22 +14,28 @@ export interface RemoteSourceOptions {
14
14
  /**
15
15
  * Headers to send on every request. Called on each HTTP fetch and on each
16
16
  * WebSocket reconnect, so the function can return a freshly-rotated token.
17
- *
18
- * - HTTP: merged into the `Authorization: ...` / `x-api-key: ...` request headers.
19
- * - WebSocket: passed as `new WebSocket(url, undefined, { headers })`. This
20
- * works on React Native (which extends the standard constructor); browsers
21
- * silently ignore it because the spec doesn't allow custom WS handshake
22
- * headers. For browsers behind authenticated reverse proxies, use a
23
- * query-string token in `wsUrl` or front the registry with cookie auth.
24
17
  */
25
18
  headers?: () => Record<string, string>;
19
+ /**
20
+ * Enable WebSocket live-reload. When the server pushes a module update the
21
+ * client re-evaluates it and re-renders the component.
22
+ *
23
+ * Same-version pushes (e.g. on reconnect the server replays the current
24
+ * module) are deduplicated in the registry and are no-ops — no re-eval, no
25
+ * new function identity, no remount. Only a genuinely new version triggers
26
+ * a re-render.
27
+ *
28
+ * @default true
29
+ */
30
+ webSocket?: boolean;
26
31
  }
27
32
 
28
33
  /**
29
34
  * Talks to @omriashke/dynamico-registry (or any compatible server).
30
35
  *
31
36
  * GET {url}/component/:name -> CompiledModule (initial fetch)
32
- * WS {wsUrl}/subscribe -> stream of CompiledModule updates
37
+ * WS {wsUrl}/subscribe -> filtered push stream; client sends
38
+ * `{ op: "watch", names: [...] }`
33
39
  */
34
40
  export function createRemoteSource(options: RemoteSourceOptions): Source {
35
41
  const fetchImpl: typeof fetch =
@@ -52,18 +58,38 @@ export function createRemoteSource(options: RemoteSourceOptions): Source {
52
58
  options.wsUrl ?? httpUrl.replace(/^http/, "ws") + "/subscribe";
53
59
 
54
60
  const listeners = new Set<(u: SourceUpdate) => void>();
61
+ const watchedNames = new Set<string>();
62
+ const watchRefCounts = new Map<string, number>();
55
63
  let socket: WebSocket | null = null;
56
64
  let disposed = false;
65
+ let pendingWatchSync = false;
57
66
  const reconnectMs = options.reconnectMs ?? 1000;
67
+ const useWebSocket = options.webSocket !== false;
68
+ const WS_OPEN = (WSCtor as unknown as { OPEN?: number }).OPEN ?? 1;
69
+ const WS_CONNECTING = (WSCtor as unknown as { CONNECTING?: number }).CONNECTING ?? 0;
70
+
71
+ function pushWatchSet(): void {
72
+ if (!useWebSocket || watchedNames.size === 0) return;
73
+ if (!socket || socket.readyState !== WS_OPEN) {
74
+ pendingWatchSync = true;
75
+ connect();
76
+ return;
77
+ }
78
+ pendingWatchSync = false;
79
+ try {
80
+ socket.send(JSON.stringify({ op: "watch", names: [...watchedNames] }));
81
+ } catch {
82
+ /* ignore */
83
+ }
84
+ }
58
85
 
59
86
  function connect(): void {
60
- if (disposed) return;
87
+ if (disposed || !useWebSocket || watchedNames.size === 0) return;
88
+ if (socket && (socket.readyState === WS_OPEN || socket.readyState === WS_CONNECTING)) {
89
+ return;
90
+ }
61
91
  try {
62
92
  const hdrs = options.headers?.();
63
- // RN's WebSocket constructor accepts a third {headers} arg that lets us
64
- // attach Bearer / x-api-key tokens to the upgrade request. The standard
65
- // browser WebSocket ignores extra constructor args, so this is a no-op
66
- // there (use cookies / a query-string token instead).
67
93
  socket = hdrs
68
94
  ? new (WSCtor as unknown as new (
69
95
  url: string,
@@ -71,10 +97,13 @@ export function createRemoteSource(options: RemoteSourceOptions): Source {
71
97
  options?: { headers?: Record<string, string> },
72
98
  ) => WebSocket)(wsUrl, undefined, { headers: hdrs })
73
99
  : new WSCtor(wsUrl);
74
- } catch (err) {
100
+ } catch {
75
101
  scheduleReconnect();
76
102
  return;
77
103
  }
104
+ socket.onopen = () => {
105
+ if (pendingWatchSync || watchedNames.size > 0) pushWatchSet();
106
+ };
78
107
  socket.onmessage = (ev: MessageEvent) => {
79
108
  try {
80
109
  const data =
@@ -103,11 +132,40 @@ export function createRemoteSource(options: RemoteSourceOptions): Source {
103
132
  }
104
133
 
105
134
  function scheduleReconnect(): void {
106
- if (disposed) return;
135
+ if (disposed || !useWebSocket || watchedNames.size === 0) return;
107
136
  setTimeout(connect, reconnectMs);
108
137
  }
109
138
 
110
- connect();
139
+ function watch(name: string): () => void {
140
+ if (!useWebSocket) return () => undefined;
141
+ const next = (watchRefCounts.get(name) ?? 0) + 1;
142
+ watchRefCounts.set(name, next);
143
+ if (next === 1) {
144
+ watchedNames.add(name);
145
+ pushWatchSet();
146
+ }
147
+ let released = false;
148
+ return () => {
149
+ if (released) return;
150
+ released = true;
151
+ const count = (watchRefCounts.get(name) ?? 1) - 1;
152
+ if (count <= 0) {
153
+ watchRefCounts.delete(name);
154
+ watchedNames.delete(name);
155
+ pushWatchSet();
156
+ if (watchedNames.size === 0) {
157
+ try {
158
+ socket?.close();
159
+ } catch {
160
+ /* noop */
161
+ }
162
+ socket = null;
163
+ }
164
+ } else {
165
+ watchRefCounts.set(name, count);
166
+ }
167
+ };
168
+ }
111
169
 
112
170
  return {
113
171
  async fetch(name: string): Promise<CompiledModule> {
@@ -136,15 +194,7 @@ export function createRemoteSource(options: RemoteSourceOptions): Source {
136
194
  listeners.delete(listener);
137
195
  };
138
196
  },
139
- /**
140
- * Tell the registry what bare specifiers the host's scope exposes. The
141
- * registry uses this to validate that every component's imports resolve
142
- * against something the host actually provides — so a typo or a forgotten
143
- * scope entry is caught at push time, not at navigation time.
144
- *
145
- * Best-effort: failures (network, 5xx, server doesn't support /scope) are
146
- * silently swallowed; they don't block the app from running.
147
- */
197
+ watch,
148
198
  async reportScope(keys, reportedBy) {
149
199
  try {
150
200
  const baseHeaders = options.headers?.() ?? {};
@@ -154,16 +204,19 @@ export function createRemoteSource(options: RemoteSourceOptions): Source {
154
204
  body: JSON.stringify({ keys: [...keys], reportedBy }),
155
205
  });
156
206
  } catch {
157
- /* best-effort: never block the host on this */
207
+ /* best-effort */
158
208
  }
159
209
  },
160
210
  dispose() {
161
211
  disposed = true;
212
+ watchedNames.clear();
213
+ watchRefCounts.clear();
162
214
  try {
163
215
  socket?.close();
164
216
  } catch {
165
217
  /* noop */
166
218
  }
219
+ socket = null;
167
220
  },
168
221
  };
169
222
  }
package/src/types.ts CHANGED
@@ -103,6 +103,12 @@ export interface Source {
103
103
  fetch(name: string): Promise<CompiledModule>;
104
104
  /** Subscribe to updates for any component. Returns unsubscribe fn. */
105
105
  subscribe(listener: (update: SourceUpdate) => void): () => void;
106
+ /**
107
+ * Subscribe to live WebSocket updates for a component. Ref-counted; the
108
+ * socket connects lazily on the first watch and only receives pushes for
109
+ * watched names. Returns a release function.
110
+ */
111
+ watch?(name: string): () => void;
106
112
  /** Optional disposal hook. */
107
113
  dispose?(): void;
108
114
  /**
package/LICENSE DELETED
@@ -1,184 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship made available under
36
- the License, as indicated by a copyright notice that is included in
37
- or attached to the work (an example is provided in the Appendix below).
38
-
39
- "Derivative Works" shall mean any work, whether in Source or Object
40
- form, that is based on (or derived from) the Work and for which the
41
- editorial revisions, annotations, elaborations, or other modifications
42
- represent, as a whole, an original work of authorship. For the purposes
43
- of this License, Derivative Works shall not include works that remain
44
- separable from, or merely link (or bind by name) to the interfaces of,
45
- the Work and Derivative Works thereof.
46
-
47
- "Contribution" shall mean, as submitted to the Licensor for inclusion
48
- in the Work by the copyright owner or by an individual or Legal Entity
49
- authorized to submit on behalf of the copyright owner. For the purposes
50
- of this definition, "submitted" means any form of electronic, verbal,
51
- or written communication sent to the Licensor or its representatives,
52
- including but not limited to communication on electronic mailing lists,
53
- source code control systems, and issue tracking systems that are managed
54
- by, or on behalf of, the Licensor for the purpose of developing and
55
- improving the Work, but excluding communication that is conspicuously
56
- marked or designated in writing by the copyright owner as "Not a
57
- Contribution."
58
-
59
- "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
- whom a Contribution has been received by the Licensor and incorporated
61
- within the Work.
62
-
63
- 2. Grant of Copyright License. Subject to the terms and conditions of
64
- this License, each Contributor hereby grants to You a perpetual,
65
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
- copyright license to reproduce, prepare Derivative Works of,
67
- publicly display, publicly perform, sublicense, and distribute the
68
- Work and such Derivative Works in Source or Object form.
69
-
70
- 3. Grant of Patent License. Subject to the terms and conditions of
71
- this License, each Contributor hereby grants to You a perpetual,
72
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
- (except as stated in this section) patent license to make, have made,
74
- use, offer to sell, sell, import, and otherwise transfer the Work,
75
- where such license applies only to those patent claims licensable
76
- by such Contributor that are necessarily infringed by their
77
- Contribution(s) alone or by the combination of their Contribution(s)
78
- with the Work to which such Contribution(s) was submitted. If You
79
- institute patent litigation against any entity (including a cross-claim
80
- or counterclaim in a lawsuit) alleging that the Work or any
81
- Contribution embodied within the Work constitutes direct or
82
- contributory patent infringement, then any patent licenses granted
83
- to You under this License for that Work shall terminate as of the
84
- date such litigation is filed.
85
-
86
- 4. Redistribution. You may reproduce and distribute copies of the
87
- Work or Derivative Works thereof in any medium, with or without
88
- modifications, and in Source or Object form, provided that You
89
- meet the following conditions:
90
-
91
- (a) You must give any other recipients of the Work or Derivative
92
- Works a copy of this License; and
93
-
94
- (b) You must cause any modified files to carry prominent notices
95
- stating that You changed the files; and
96
-
97
- (c) You must retain, in the Source form of any Derivative Works
98
- that You distribute, all copyright, patent, trademark, and
99
- attribution notices from the Source form of the Work,
100
- excluding those notices that do not pertain to any part of
101
- the Derivative Works; and
102
-
103
- (d) If the Work includes a "NOTICE" text file as part of its
104
- distribution, You must include a readable copy of the
105
- attribution notices contained within such NOTICE file, in
106
- at least one of the following places: within a NOTICE text
107
- file distributed as part of the Derivative Works; within
108
- the Source form or documentation, if provided along with the
109
- Derivative Works; or, within a display generated by the
110
- Derivative Works, if and wherever such third-party notices
111
- normally appear. The contents of the NOTICE file are for
112
- informational purposes only and do not modify the License.
113
- You may add Your own attribution notices within Derivative
114
- Works that You distribute, alongside or in addition to the
115
- NOTICE text from the Work, provided that such additional
116
- attribution notices cannot be construed as modifying the License.
117
-
118
- You may add Your own license statement for Your modifications and
119
- may provide additional grant of rights to use, reproduce, modify,
120
- prepare Derivative Works of, convert to Object form, display,
121
- perform, sublicense, and distribute the Work and such Derivative
122
- Works in Source or Object form.
123
-
124
- 5. Submission of Contributions. Unless You explicitly state otherwise,
125
- any Contribution intentionally submitted for inclusion in the Work
126
- by You to the Licensor shall be under the terms and conditions of
127
- this License, without any additional terms or conditions.
128
- Notwithstanding the above, nothing herein shall supersede or modify
129
- the terms of any separate license agreement you may have executed
130
- with Licensor regarding such Contributions.
131
-
132
- 6. Trademarks. This License does not grant permission to use the trade
133
- names, trademarks, service marks, or product names of the Licensor,
134
- except as required for reasonable and customary use in describing the
135
- origin of the Work and reproducing the content of the NOTICE file.
136
-
137
- 7. Disclaimer of Warranty. Unless required by applicable law or
138
- agreed to in writing, Licensor provides the Work (and each
139
- Contributor provides its Contributions) on an "AS IS" BASIS,
140
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
- implied, including, without limitation, any warranties or conditions
142
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
143
- PARTICULAR PURPOSE. You are solely responsible for determining the
144
- appropriateness of using or redistributing the Work and assume any
145
- risks associated with Your exercise of permissions under this License.
146
-
147
- 8. Limitation of Liability. In no event and under no legal theory,
148
- whether in tort (including negligence), contract, or otherwise,
149
- unless required by applicable law (such as deliberate and grossly
150
- negligent acts) or agreed to in writing, shall any Contributor be
151
- liable to You for damages, including any direct, indirect, special,
152
- incidental, or exemplary damages of any character arising as a
153
- result of this License or out of the use or inability to use the
154
- Work (including but not limited to damages for loss of goodwill,
155
- work stoppage, computer failure or malfunction, or all other
156
- commercial damages or losses), even if such Contributor has been
157
- advised of the possibility of such damages.
158
-
159
- 9. Accepting Warranty or Additional Liability. While redistributing
160
- the Work or Derivative Works thereof, You may choose to offer,
161
- and charge a fee for, acceptance of support, warranty, indemnity,
162
- or other liability obligations and/or rights consistent with this
163
- License. However, in accepting such obligations, You may offer such
164
- obligations only on Your own behalf and on Your sole responsibility,
165
- not on behalf of any other Contributor, and only if You agree to
166
- indemnify, defend, and hold each Contributor harmless for any
167
- liability incurred by, or claims asserted against, such Contributor
168
- by reason of your accepting any such warranty or additional liability.
169
-
170
- END OF TERMS AND CONDITIONS
171
-
172
- Copyright 2024 Omri Askenazi
173
-
174
- Licensed under the Apache License, Version 2.0 (the "License");
175
- you may not use this file except in compliance with the License.
176
- You may obtain a copy of the License at
177
-
178
- http://www.apache.org/licenses/LICENSE-2.0
179
-
180
- Unless required by applicable law or agreed to in writing, software
181
- distributed under the License is distributed on an "AS IS" BASIS,
182
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183
- See the License for the specific language governing permissions and
184
- limitations under the License.