proxy-vir 0.0.0 → 0.0.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.
package/LICENSE-CC0 ADDED
@@ -0,0 +1,121 @@
1
+ CC0 1.0 Universal
2
+
3
+ Creative Commons Legal Code
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 electrovir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # proxy-vir
2
+
3
+ Creates a proxy based on multiple dynamically cascaded targets (meaning you can add or remove targets whenever you want) with dynamic proxy handler overriding (meaning you can modify how proxy handlers operate after the proxy has been created).
4
+
5
+ # Installation
6
+
7
+ ```bash
8
+ npm i proxy-vir
9
+ ```
10
+
11
+ # Usages
12
+
13
+ ## Simple override
14
+
15
+ <!-- example-link: src/readme-examples/create-proxy.example.ts -->
16
+
17
+ ```TypeScript
18
+ import {createWrappedMultiTargetProxy} from 'proxy-vir';
19
+
20
+ // something you imported from a 3rd party library that you want to wrap
21
+ const importedThing = {
22
+ doThingA() {},
23
+ };
24
+
25
+ const thingWrapper = createWrappedMultiTargetProxy({
26
+ initialTarget: importedThing,
27
+ });
28
+
29
+ // add a new override
30
+ thingWrapper.proxyModifier.addOverrideTarget({
31
+ doThingA() {},
32
+ });
33
+ ```
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./proxy-vir/create-multi-target-proxy"), exports);
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPrioritizedProperties = void 0;
4
+ const common_1 = require("@augment-vir/common");
5
+ function listToMapInit(options) {
6
+ if (options?.initialList) {
7
+ return options.initialList
8
+ .map((initialEntry) => {
9
+ return (0, common_1.getObjectTypedKeys)(initialEntry).map((key) => {
10
+ return [
11
+ key,
12
+ initialEntry[key],
13
+ ];
14
+ });
15
+ })
16
+ .flat();
17
+ }
18
+ return [];
19
+ }
20
+ /**
21
+ * Stores and allows updating of a list of entries from which a single object created. Properties
22
+ * for the single object are chosen from the entries by the entry order in the list.
23
+ */
24
+ function createPrioritizedProperties(options) {
25
+ const list = [...(options?.initialList ?? [])];
26
+ const combinedProperties = Object.fromEntries(listToMapInit(options));
27
+ function updateObject() {
28
+ // clear out all the object's current keys
29
+ (0, common_1.getObjectTypedKeys)(combinedProperties).forEach((property) => {
30
+ delete combinedProperties[property];
31
+ });
32
+ list.forEach((entry) => {
33
+ (0, common_1.getObjectTypedKeys)(entry).forEach((property) => {
34
+ // only save the property if it hasn't been saved already
35
+ if (!(0, common_1.typedHasProperty)(combinedProperties, property)) {
36
+ combinedProperties[property] = entry[property];
37
+ }
38
+ });
39
+ });
40
+ options?.updateCallback?.(combinedProperties);
41
+ }
42
+ return {
43
+ /**
44
+ * An object containing all properties combined from the current priority list of entries.
45
+ * This reference never changes, just its contents, so you are safe to grab and use this
46
+ * object directly.
47
+ */
48
+ combinedProperties,
49
+ addOverride(entry) {
50
+ list.splice(options?.overrideEntryPoint ?? 0, 0, entry);
51
+ updateObject();
52
+ },
53
+ addFallback(entry) {
54
+ list.push(entry);
55
+ updateObject();
56
+ },
57
+ /** Return value indicates if the given entry was removed or not. */
58
+ removeEntry(entry) {
59
+ const entryIndex = list.indexOf(entry);
60
+ if (entryIndex === -1) {
61
+ return false;
62
+ }
63
+ list.splice(entryIndex, 1);
64
+ updateObject();
65
+ return true;
66
+ },
67
+ forceUpdate() {
68
+ updateObject();
69
+ },
70
+ getCurrentList() {
71
+ return [...list];
72
+ },
73
+ };
74
+ }
75
+ exports.createPrioritizedProperties = createPrioritizedProperties;
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createWrappedMultiTargetProxy = void 0;
4
+ const common_1 = require("@augment-vir/common");
5
+ const prioritized_properties_1 = require("../prioritized-properties");
6
+ function createWrappedMultiTargetProxy(options) {
7
+ /** This target will always be used first. */
8
+ const primaryTarget = options?.isCallable ? () => { } : {};
9
+ const deletedProperties = new Set();
10
+ let prototype = Object.getPrototypeOf(primaryTarget);
11
+ let isExtensible = !options?.isNotExtensible;
12
+ const proxyOverrides = (0, prioritized_properties_1.createPrioritizedProperties)();
13
+ const targetProperties = (0, prioritized_properties_1.createPrioritizedProperties)({
14
+ initialList: [primaryTarget],
15
+ /** This is set to 1 so that the primaryTarget above is never overridden. */
16
+ overrideEntryPoint: 1,
17
+ updateCallback(combinedObject) {
18
+ Object.setPrototypeOf(combinedObject, prototype);
19
+ deletedProperties.forEach((property) => {
20
+ delete combinedObject[property];
21
+ });
22
+ if (!isExtensible && Object.isExtensible(combinedObject)) {
23
+ Object.preventExtensions(combinedObject);
24
+ }
25
+ },
26
+ });
27
+ const functionHandlers = options?.isCallable
28
+ ? {
29
+ apply() {
30
+ if (proxyOverrides.combinedProperties.apply) {
31
+ return proxyOverrides.combinedProperties.apply;
32
+ }
33
+ const firstCallableTarget = targetProperties
34
+ .getCurrentList()
35
+ .find((target) => typeof target === 'function') ?? primaryTarget;
36
+ return firstCallableTarget();
37
+ },
38
+ }
39
+ : {};
40
+ const createdProxy = new Proxy(targetProperties.combinedProperties, {
41
+ ...functionHandlers,
42
+ defineProperty(combinedTargets, property, attributes) {
43
+ if (proxyOverrides.combinedProperties.defineProperty) {
44
+ return proxyOverrides.combinedProperties.defineProperty(combinedTargets, property, attributes);
45
+ }
46
+ if (!isExtensible) {
47
+ return false;
48
+ }
49
+ deletedProperties.delete(property);
50
+ Object.defineProperty(primaryTarget, property, attributes);
51
+ targetProperties.forceUpdate();
52
+ return true;
53
+ },
54
+ deleteProperty(combinedTargets, property) {
55
+ if (proxyOverrides.combinedProperties.deleteProperty) {
56
+ return proxyOverrides.combinedProperties.deleteProperty(combinedTargets, property);
57
+ }
58
+ if (!isExtensible) {
59
+ return false;
60
+ }
61
+ deletedProperties.add(property);
62
+ return true;
63
+ },
64
+ get(combinedTargets, property, receiver) {
65
+ if (proxyOverrides.combinedProperties.get) {
66
+ return proxyOverrides.combinedProperties.get(combinedTargets, property, receiver);
67
+ }
68
+ if (deletedProperties.has(property)) {
69
+ return undefined;
70
+ }
71
+ return combinedTargets[property];
72
+ },
73
+ getOwnPropertyDescriptor(combinedTargets, property) {
74
+ if (proxyOverrides.combinedProperties.getOwnPropertyDescriptor) {
75
+ return proxyOverrides.combinedProperties.getOwnPropertyDescriptor(combinedTargets, property);
76
+ }
77
+ if (deletedProperties.has(property)) {
78
+ return undefined;
79
+ }
80
+ return Object.getOwnPropertyDescriptor(combinedTargets, property);
81
+ },
82
+ getPrototypeOf(combinedTargets) {
83
+ if (proxyOverrides.combinedProperties.getPrototypeOf) {
84
+ return proxyOverrides.combinedProperties.getPrototypeOf(combinedTargets);
85
+ }
86
+ return Object.getPrototypeOf(combinedTargets);
87
+ },
88
+ has(combinedTargets, property) {
89
+ if (proxyOverrides.combinedProperties.has) {
90
+ return proxyOverrides.combinedProperties.has(combinedTargets, property);
91
+ }
92
+ if (deletedProperties.has(property)) {
93
+ return false;
94
+ }
95
+ return (0, common_1.typedHasProperty)(combinedTargets, property);
96
+ },
97
+ isExtensible(combinedTargets) {
98
+ if (proxyOverrides.combinedProperties.isExtensible) {
99
+ return proxyOverrides.combinedProperties.isExtensible(combinedTargets);
100
+ }
101
+ return isExtensible;
102
+ },
103
+ ownKeys(combinedTargets) {
104
+ if (proxyOverrides.combinedProperties.ownKeys) {
105
+ return proxyOverrides.combinedProperties.ownKeys(combinedTargets);
106
+ }
107
+ return Array.from((0, common_1.getObjectTypedKeys)(combinedTargets))
108
+ .map((key) => {
109
+ return typeof key === 'number' ? String(key) : key;
110
+ })
111
+ .filter((property) => !deletedProperties.has(property));
112
+ },
113
+ preventExtensions(combinedTargets) {
114
+ if (proxyOverrides.combinedProperties.preventExtensions) {
115
+ return proxyOverrides.combinedProperties.preventExtensions(combinedTargets);
116
+ }
117
+ isExtensible = false;
118
+ targetProperties.forceUpdate();
119
+ return true;
120
+ },
121
+ set(combinedTargets, property, newValue, receiver) {
122
+ if (proxyOverrides.combinedProperties.set) {
123
+ return proxyOverrides.combinedProperties.set(combinedTargets, property, newValue, receiver);
124
+ }
125
+ if (!isExtensible) {
126
+ return false;
127
+ }
128
+ deletedProperties.delete(property);
129
+ primaryTarget[property] = newValue;
130
+ targetProperties.forceUpdate();
131
+ return true;
132
+ },
133
+ setPrototypeOf(combinedTargets, newPrototype) {
134
+ if (proxyOverrides.combinedProperties.setPrototypeOf) {
135
+ return proxyOverrides.combinedProperties.setPrototypeOf(combinedTargets, newPrototype);
136
+ }
137
+ if (!isExtensible) {
138
+ return false;
139
+ }
140
+ prototype = newPrototype;
141
+ targetProperties.forceUpdate();
142
+ return true;
143
+ },
144
+ });
145
+ const proxyModifier = {
146
+ /**
147
+ * Add a target to the internal list of prioritized targets. Since this will be a fallback
148
+ * target, a property from this target will only be used if no previously added target
149
+ * already has the property.
150
+ */
151
+ addFallbackTarget(target) {
152
+ targetProperties.addFallback(target);
153
+ },
154
+ /**
155
+ * Add a target to the internal list of prioritized targets. Since this will be an override
156
+ * target, a property from this target will always be used unless a new override target with
157
+ * the same property is added or if the properties are modified on the proxy itself.
158
+ */
159
+ addOverrideTarget(target) {
160
+ targetProperties.addOverride(target);
161
+ },
162
+ /** Remove the given target from the internal list of prioritized targets. */
163
+ removeTarget(target) {
164
+ return targetProperties.removeEntry(target);
165
+ },
166
+ addProxyHandlerOverride(handlerOverride) {
167
+ proxyOverrides.addOverride(handlerOverride);
168
+ },
169
+ addProxyHandlerFallback(handlerOverride) {
170
+ proxyOverrides.addFallback(handlerOverride);
171
+ },
172
+ removeProxyOverride(handlerOverride) {
173
+ return proxyOverrides.removeEntry(handlerOverride);
174
+ },
175
+ /**
176
+ * The list of internal prioritized targets, in priority order. This is mostly only useful
177
+ * for debugging purposes.
178
+ */
179
+ getAllTargets() {
180
+ return targetProperties.getCurrentList();
181
+ },
182
+ };
183
+ if (options && 'initialTarget' in options && options.initialTarget) {
184
+ proxyModifier.addFallbackTarget(options.initialTarget);
185
+ }
186
+ else if (options && 'initialTargets' in options && options.initialTargets) {
187
+ options.initialTargets.forEach((initialTarget) => {
188
+ proxyModifier.addOverrideTarget(initialTarget);
189
+ });
190
+ }
191
+ return {
192
+ proxy: createdProxy,
193
+ proxyModifier,
194
+ };
195
+ }
196
+ exports.createWrappedMultiTargetProxy = createWrappedMultiTargetProxy;
@@ -0,0 +1 @@
1
+ export * from './proxy-vir/create-multi-target-proxy';
@@ -0,0 +1,71 @@
1
+ import { getObjectTypedKeys, typedHasProperty, } from '@augment-vir/common';
2
+ function listToMapInit(options) {
3
+ if (options?.initialList) {
4
+ return options.initialList
5
+ .map((initialEntry) => {
6
+ return getObjectTypedKeys(initialEntry).map((key) => {
7
+ return [
8
+ key,
9
+ initialEntry[key],
10
+ ];
11
+ });
12
+ })
13
+ .flat();
14
+ }
15
+ return [];
16
+ }
17
+ /**
18
+ * Stores and allows updating of a list of entries from which a single object created. Properties
19
+ * for the single object are chosen from the entries by the entry order in the list.
20
+ */
21
+ export function createPrioritizedProperties(options) {
22
+ const list = [...(options?.initialList ?? [])];
23
+ const combinedProperties = Object.fromEntries(listToMapInit(options));
24
+ function updateObject() {
25
+ // clear out all the object's current keys
26
+ getObjectTypedKeys(combinedProperties).forEach((property) => {
27
+ delete combinedProperties[property];
28
+ });
29
+ list.forEach((entry) => {
30
+ getObjectTypedKeys(entry).forEach((property) => {
31
+ // only save the property if it hasn't been saved already
32
+ if (!typedHasProperty(combinedProperties, property)) {
33
+ combinedProperties[property] = entry[property];
34
+ }
35
+ });
36
+ });
37
+ options?.updateCallback?.(combinedProperties);
38
+ }
39
+ return {
40
+ /**
41
+ * An object containing all properties combined from the current priority list of entries.
42
+ * This reference never changes, just its contents, so you are safe to grab and use this
43
+ * object directly.
44
+ */
45
+ combinedProperties,
46
+ addOverride(entry) {
47
+ list.splice(options?.overrideEntryPoint ?? 0, 0, entry);
48
+ updateObject();
49
+ },
50
+ addFallback(entry) {
51
+ list.push(entry);
52
+ updateObject();
53
+ },
54
+ /** Return value indicates if the given entry was removed or not. */
55
+ removeEntry(entry) {
56
+ const entryIndex = list.indexOf(entry);
57
+ if (entryIndex === -1) {
58
+ return false;
59
+ }
60
+ list.splice(entryIndex, 1);
61
+ updateObject();
62
+ return true;
63
+ },
64
+ forceUpdate() {
65
+ updateObject();
66
+ },
67
+ getCurrentList() {
68
+ return [...list];
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,192 @@
1
+ import { getObjectTypedKeys, typedHasProperty } from '@augment-vir/common';
2
+ import { createPrioritizedProperties } from '../prioritized-properties';
3
+ export function createWrappedMultiTargetProxy(options) {
4
+ /** This target will always be used first. */
5
+ const primaryTarget = options?.isCallable ? () => { } : {};
6
+ const deletedProperties = new Set();
7
+ let prototype = Object.getPrototypeOf(primaryTarget);
8
+ let isExtensible = !options?.isNotExtensible;
9
+ const proxyOverrides = createPrioritizedProperties();
10
+ const targetProperties = createPrioritizedProperties({
11
+ initialList: [primaryTarget],
12
+ /** This is set to 1 so that the primaryTarget above is never overridden. */
13
+ overrideEntryPoint: 1,
14
+ updateCallback(combinedObject) {
15
+ Object.setPrototypeOf(combinedObject, prototype);
16
+ deletedProperties.forEach((property) => {
17
+ delete combinedObject[property];
18
+ });
19
+ if (!isExtensible && Object.isExtensible(combinedObject)) {
20
+ Object.preventExtensions(combinedObject);
21
+ }
22
+ },
23
+ });
24
+ const functionHandlers = options?.isCallable
25
+ ? {
26
+ apply() {
27
+ if (proxyOverrides.combinedProperties.apply) {
28
+ return proxyOverrides.combinedProperties.apply;
29
+ }
30
+ const firstCallableTarget = targetProperties
31
+ .getCurrentList()
32
+ .find((target) => typeof target === 'function') ?? primaryTarget;
33
+ return firstCallableTarget();
34
+ },
35
+ }
36
+ : {};
37
+ const createdProxy = new Proxy(targetProperties.combinedProperties, {
38
+ ...functionHandlers,
39
+ defineProperty(combinedTargets, property, attributes) {
40
+ if (proxyOverrides.combinedProperties.defineProperty) {
41
+ return proxyOverrides.combinedProperties.defineProperty(combinedTargets, property, attributes);
42
+ }
43
+ if (!isExtensible) {
44
+ return false;
45
+ }
46
+ deletedProperties.delete(property);
47
+ Object.defineProperty(primaryTarget, property, attributes);
48
+ targetProperties.forceUpdate();
49
+ return true;
50
+ },
51
+ deleteProperty(combinedTargets, property) {
52
+ if (proxyOverrides.combinedProperties.deleteProperty) {
53
+ return proxyOverrides.combinedProperties.deleteProperty(combinedTargets, property);
54
+ }
55
+ if (!isExtensible) {
56
+ return false;
57
+ }
58
+ deletedProperties.add(property);
59
+ return true;
60
+ },
61
+ get(combinedTargets, property, receiver) {
62
+ if (proxyOverrides.combinedProperties.get) {
63
+ return proxyOverrides.combinedProperties.get(combinedTargets, property, receiver);
64
+ }
65
+ if (deletedProperties.has(property)) {
66
+ return undefined;
67
+ }
68
+ return combinedTargets[property];
69
+ },
70
+ getOwnPropertyDescriptor(combinedTargets, property) {
71
+ if (proxyOverrides.combinedProperties.getOwnPropertyDescriptor) {
72
+ return proxyOverrides.combinedProperties.getOwnPropertyDescriptor(combinedTargets, property);
73
+ }
74
+ if (deletedProperties.has(property)) {
75
+ return undefined;
76
+ }
77
+ return Object.getOwnPropertyDescriptor(combinedTargets, property);
78
+ },
79
+ getPrototypeOf(combinedTargets) {
80
+ if (proxyOverrides.combinedProperties.getPrototypeOf) {
81
+ return proxyOverrides.combinedProperties.getPrototypeOf(combinedTargets);
82
+ }
83
+ return Object.getPrototypeOf(combinedTargets);
84
+ },
85
+ has(combinedTargets, property) {
86
+ if (proxyOverrides.combinedProperties.has) {
87
+ return proxyOverrides.combinedProperties.has(combinedTargets, property);
88
+ }
89
+ if (deletedProperties.has(property)) {
90
+ return false;
91
+ }
92
+ return typedHasProperty(combinedTargets, property);
93
+ },
94
+ isExtensible(combinedTargets) {
95
+ if (proxyOverrides.combinedProperties.isExtensible) {
96
+ return proxyOverrides.combinedProperties.isExtensible(combinedTargets);
97
+ }
98
+ return isExtensible;
99
+ },
100
+ ownKeys(combinedTargets) {
101
+ if (proxyOverrides.combinedProperties.ownKeys) {
102
+ return proxyOverrides.combinedProperties.ownKeys(combinedTargets);
103
+ }
104
+ return Array.from(getObjectTypedKeys(combinedTargets))
105
+ .map((key) => {
106
+ return typeof key === 'number' ? String(key) : key;
107
+ })
108
+ .filter((property) => !deletedProperties.has(property));
109
+ },
110
+ preventExtensions(combinedTargets) {
111
+ if (proxyOverrides.combinedProperties.preventExtensions) {
112
+ return proxyOverrides.combinedProperties.preventExtensions(combinedTargets);
113
+ }
114
+ isExtensible = false;
115
+ targetProperties.forceUpdate();
116
+ return true;
117
+ },
118
+ set(combinedTargets, property, newValue, receiver) {
119
+ if (proxyOverrides.combinedProperties.set) {
120
+ return proxyOverrides.combinedProperties.set(combinedTargets, property, newValue, receiver);
121
+ }
122
+ if (!isExtensible) {
123
+ return false;
124
+ }
125
+ deletedProperties.delete(property);
126
+ primaryTarget[property] = newValue;
127
+ targetProperties.forceUpdate();
128
+ return true;
129
+ },
130
+ setPrototypeOf(combinedTargets, newPrototype) {
131
+ if (proxyOverrides.combinedProperties.setPrototypeOf) {
132
+ return proxyOverrides.combinedProperties.setPrototypeOf(combinedTargets, newPrototype);
133
+ }
134
+ if (!isExtensible) {
135
+ return false;
136
+ }
137
+ prototype = newPrototype;
138
+ targetProperties.forceUpdate();
139
+ return true;
140
+ },
141
+ });
142
+ const proxyModifier = {
143
+ /**
144
+ * Add a target to the internal list of prioritized targets. Since this will be a fallback
145
+ * target, a property from this target will only be used if no previously added target
146
+ * already has the property.
147
+ */
148
+ addFallbackTarget(target) {
149
+ targetProperties.addFallback(target);
150
+ },
151
+ /**
152
+ * Add a target to the internal list of prioritized targets. Since this will be an override
153
+ * target, a property from this target will always be used unless a new override target with
154
+ * the same property is added or if the properties are modified on the proxy itself.
155
+ */
156
+ addOverrideTarget(target) {
157
+ targetProperties.addOverride(target);
158
+ },
159
+ /** Remove the given target from the internal list of prioritized targets. */
160
+ removeTarget(target) {
161
+ return targetProperties.removeEntry(target);
162
+ },
163
+ addProxyHandlerOverride(handlerOverride) {
164
+ proxyOverrides.addOverride(handlerOverride);
165
+ },
166
+ addProxyHandlerFallback(handlerOverride) {
167
+ proxyOverrides.addFallback(handlerOverride);
168
+ },
169
+ removeProxyOverride(handlerOverride) {
170
+ return proxyOverrides.removeEntry(handlerOverride);
171
+ },
172
+ /**
173
+ * The list of internal prioritized targets, in priority order. This is mostly only useful
174
+ * for debugging purposes.
175
+ */
176
+ getAllTargets() {
177
+ return targetProperties.getCurrentList();
178
+ },
179
+ };
180
+ if (options && 'initialTarget' in options && options.initialTarget) {
181
+ proxyModifier.addFallbackTarget(options.initialTarget);
182
+ }
183
+ else if (options && 'initialTargets' in options && options.initialTargets) {
184
+ options.initialTargets.forEach((initialTarget) => {
185
+ proxyModifier.addOverrideTarget(initialTarget);
186
+ });
187
+ }
188
+ return {
189
+ proxy: createdProxy,
190
+ proxyModifier,
191
+ };
192
+ }
@@ -0,0 +1 @@
1
+ export * from './proxy-vir/create-multi-target-proxy';
@@ -0,0 +1,24 @@
1
+ import { PartialAndUndefined } from '@augment-vir/common';
2
+ export type PriorityListInputs<EntryType> = {
3
+ initialList: ReadonlyArray<EntryType>;
4
+ overrideEntryPoint: number;
5
+ updateCallback?: (combined: EntryType) => void;
6
+ };
7
+ /**
8
+ * Stores and allows updating of a list of entries from which a single object created. Properties
9
+ * for the single object are chosen from the entries by the entry order in the list.
10
+ */
11
+ export declare function createPrioritizedProperties<EntryType>(options?: PartialAndUndefined<PriorityListInputs<EntryType>>): {
12
+ /**
13
+ * An object containing all properties combined from the current priority list of entries.
14
+ * This reference never changes, just its contents, so you are safe to grab and use this
15
+ * object directly.
16
+ */
17
+ combinedProperties: EntryType;
18
+ addOverride(entry: EntryType): void;
19
+ addFallback(entry: EntryType): void;
20
+ /** Return value indicates if the given entry was removed or not. */
21
+ removeEntry(entry: EntryType): boolean;
22
+ forceUpdate(): void;
23
+ getCurrentList(): ReadonlyArray<EntryType>;
24
+ };
@@ -0,0 +1,37 @@
1
+ import { PartialAndUndefined } from '@augment-vir/common';
2
+ import { RequireExactlyOne } from 'type-fest';
3
+ export type CreateProxyOptions<ProxyType> = {
4
+ /**
5
+ * Indicates if this proxy is meant to be callable, or, in other words, if this proxy is meant
6
+ * to proxy a function rather than just an object.
7
+ */
8
+ isCallable: boolean;
9
+ /**
10
+ * Indicates if the proxy should not be extensible. By default they are extensible, so set this
11
+ * to true to change that behavior. Read JavaScript docs for "Object.isExtensible()" to
12
+ * understand what being extensible means:
13
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible
14
+ */
15
+ isNotExtensible: boolean;
16
+ } & RequireExactlyOne<{
17
+ /** Initial Target to wrap */
18
+ initialTarget: Partial<ProxyType>;
19
+ /** Initial Targets to wrap, in priority order */
20
+ initialTargets: ReadonlyArray<Partial<ProxyType>>;
21
+ }>;
22
+ export type ProxyTypeBase = object | Function;
23
+ export type MultiTargetProxyModifier<ProxyType extends ProxyTypeBase> = {
24
+ addFallbackTarget(target: Partial<ProxyType>): void;
25
+ addOverrideTarget(target: Partial<ProxyType>): void;
26
+ removeTarget(target: Partial<ProxyType>): boolean;
27
+ getAllTargets(): ReadonlyArray<unknown>;
28
+ addProxyHandlerOverride(handlerOverride: ProxyHandler<ProxyType>): void;
29
+ addProxyHandlerFallback(handlerOverride: ProxyHandler<ProxyType>): void;
30
+ removeProxyOverride(handlerOverride: ProxyHandler<ProxyType>): boolean;
31
+ getAllTargets(): ReadonlyArray<ProxyType>;
32
+ };
33
+ export type WrappedMultiTargetProxy<ProxyType extends ProxyTypeBase> = {
34
+ proxy: ProxyType;
35
+ proxyModifier: MultiTargetProxyModifier<ProxyType>;
36
+ };
37
+ export declare function createWrappedMultiTargetProxy<ProxyType extends ProxyTypeBase>(options?: PartialAndUndefined<CreateProxyOptions<ProxyType>> | undefined): WrappedMultiTargetProxy<ProxyType>;
package/package.json CHANGED
@@ -1,12 +1,71 @@
1
1
  {
2
- "name": "proxy-vir",
3
- "version": "0.0.0",
4
- "description": "",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "keywords": [],
10
- "author": "",
11
- "license": "MIT"
2
+ "name": "proxy-vir",
3
+ "version": "0.0.1",
4
+ "description": "An easier Proxy.",
5
+ "keywords": [
6
+ "proxy",
7
+ "vir",
8
+ "wrapper",
9
+ "object"
10
+ ],
11
+ "homepage": "https://github.com/electrovir/proxy-vir",
12
+ "bugs": {
13
+ "url": "https://github.com/electrovir/proxy-vir/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/electrovir/proxy-vir"
18
+ },
19
+ "license": "(MIT or CC0 1.0)",
20
+ "author": {
21
+ "name": "electrovir",
22
+ "url": "https://github.com/electrovir"
23
+ },
24
+ "main": "dist/cjs/index.js",
25
+ "module": "dist/esm/index.js",
26
+ "types": "dist/types/index.d.ts",
27
+ "scripts": {
28
+ "compile": "rm -rf dist && tsc --project tsconfig.json && tsc --project tsconfig.cjs.json",
29
+ "docs:update": "virmator code-in-markdown README.md --index src/index.ts",
30
+ "format": "virmator format",
31
+ "publish": "virmator publish \"npm run compile && npm run test:all\"",
32
+ "start": "npm install && virmator frontend",
33
+ "test": "virmator test-web",
34
+ "test:all": "concurrently --kill-others-on-fail \"npm run test:types\" \"npm run test:coverage\" \"npm run test:spelling\" \"npm run test:format\" \"npm run test:docs\"",
35
+ "test:coverage": "npm run test coverage",
36
+ "test:docs": "virmator code-in-markdown check README.md --index src/index.ts",
37
+ "test:format": "virmator format check",
38
+ "test:spelling": "virmator spellcheck",
39
+ "test:types": "tsc --noEmit"
40
+ },
41
+ "dependencies": {
42
+ "@augment-vir/common": "^13.3.0"
43
+ },
44
+ "devDependencies": {
45
+ "@augment-vir/browser-testing": "^13.3.0",
46
+ "@augment-vir/node-js": "^13.3.0",
47
+ "@open-wc/testing": "^3.1.8",
48
+ "@types/mocha": "^10.0.1",
49
+ "@web/dev-server-esbuild": "^0.4.1",
50
+ "@web/test-runner": "^0.16.1",
51
+ "@web/test-runner-commands": "^0.7.0",
52
+ "@web/test-runner-playwright": "^0.10.0",
53
+ "@web/test-runner-visual-regression": "^0.8.0",
54
+ "cspell": "^6.31.1",
55
+ "esbuild": "^0.17.18",
56
+ "istanbul-smart-text-reporter": "^1.1.1",
57
+ "markdown-code-example-inserter": "^0.3.0",
58
+ "npm-check-updates": "^16.10.9",
59
+ "prettier": "^2.8.8",
60
+ "prettier-plugin-interpolated-html-tags": "^0.0.3",
61
+ "prettier-plugin-jsdoc": "^0.4.2",
62
+ "prettier-plugin-multiline-arrays": "^1.1.3",
63
+ "prettier-plugin-organize-imports": "^3.2.2",
64
+ "prettier-plugin-packagejson": "^2.4.3",
65
+ "prettier-plugin-sort-json": "^1.0.0",
66
+ "prettier-plugin-toml": "^0.3.1",
67
+ "virmator": "^6.5.0",
68
+ "vite": "^4.3.3",
69
+ "vite-tsconfig-paths": "^4.2.0"
70
+ }
12
71
  }