rescript-relay 0.23.0 → 1.0.0-beta.11

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/src/utils.mjs ADDED
@@ -0,0 +1,339 @@
1
+ function getNewObj(maybeNewObj, currentObj) {
2
+ return maybeNewObj || Object.assign({}, currentObj);
3
+ }
4
+
5
+ function getPathName(path) {
6
+ return path.join("_");
7
+ }
8
+
9
+ function makeNewPath(currentPath, newKeys) {
10
+ return [].concat(currentPath, newKeys);
11
+ }
12
+
13
+ /**
14
+ * Runs on each object in the tree and follows the provided instructions
15
+ * to apply transforms etc.
16
+ */
17
+ function traverse(
18
+ fullInstructionMap,
19
+ currentPath,
20
+ currentObj,
21
+ instructionMap,
22
+ converters,
23
+ nullableValue,
24
+ instructionPaths,
25
+ addFragmentOnRoot
26
+ ) {
27
+ // We lazily set up a new object for each "level", as we don't want to mutate
28
+ // what comes back from the Relay store, and nor do we want to create new
29
+ // objects unless we need to. And we only need to when we need to change
30
+ // something.
31
+ var newObj;
32
+
33
+ if (addFragmentOnRoot) {
34
+ newObj = getNewObj(newObj, currentObj);
35
+ newObj.fragmentRefs = Object.assign({}, newObj);
36
+ }
37
+
38
+ for (var key in currentObj) {
39
+ var isUnion = false;
40
+ var originalValue = currentObj[key];
41
+
42
+ // Instructions are stored by the path in the object where they apply
43
+ var thisPath = makeNewPath(currentPath, [key]);
44
+ var path = getPathName(thisPath);
45
+
46
+ var instructions = instructionMap[path] || {};
47
+
48
+ if (currentObj[key] == null) {
49
+ newObj = getNewObj(newObj, currentObj);
50
+ newObj[key] = nullableValue;
51
+ continue;
52
+ }
53
+
54
+ var shouldConvertRootObj =
55
+ typeof instructions["r"] === "string" &&
56
+ fullInstructionMap[instructions["r"]];
57
+
58
+ var shouldAddFragmentFn = instructions["f"] === "";
59
+
60
+ var shouldConvertEnum =
61
+ typeof instructions["e"] === "string" && !!converters[instructions["e"]];
62
+
63
+ var shouldConvertCustomField =
64
+ typeof instructions["c"] === "string" && !!converters[instructions["c"]];
65
+
66
+ var shouldConvertUnion =
67
+ typeof instructions["u"] === "string" && !!converters[instructions["u"]];
68
+
69
+ var isTopLevelNodeField = typeof instructions["tnf"] === "string";
70
+
71
+ /**
72
+ * Handle arrays
73
+ */
74
+ if (Array.isArray(currentObj[key])) {
75
+ newObj = getNewObj(newObj, currentObj);
76
+ newObj[key] = currentObj[key].map(function (v) {
77
+ if (v == null) {
78
+ return nullableValue;
79
+ }
80
+
81
+ if (shouldConvertRootObj) {
82
+ return traverser(
83
+ v,
84
+ fullInstructionMap,
85
+ converters,
86
+ nullableValue,
87
+ instructions["r"]
88
+ );
89
+ }
90
+
91
+ if (shouldConvertEnum) {
92
+ return converters[instructions["e"]](v);
93
+ }
94
+
95
+ if (shouldConvertCustomField) {
96
+ return converters[instructions["c"]](v);
97
+ }
98
+
99
+ if (
100
+ shouldConvertUnion &&
101
+ typeof v === "object" &&
102
+ typeof v.__typename === "string"
103
+ ) {
104
+ isUnion = true;
105
+
106
+ var newPath = makeNewPath(currentPath, [key, v.__typename]);
107
+
108
+ var unionRootHasFragment =
109
+ (instructionMap[getPathName(newPath)] || {}).f === "";
110
+
111
+ var traversedValue = traverse(
112
+ fullInstructionMap,
113
+ newPath,
114
+ v,
115
+ instructionMap,
116
+ converters,
117
+ nullableValue,
118
+ instructionPaths,
119
+ unionRootHasFragment
120
+ );
121
+
122
+ return converters[instructions["u"]](traversedValue);
123
+ }
124
+
125
+ if (shouldAddFragmentFn && typeof v === "object") {
126
+ var objWithFragmentFn = Object.assign({}, v);
127
+ objWithFragmentFn.fragmentRefs = Object.assign({}, objWithFragmentFn);
128
+ return objWithFragmentFn;
129
+ }
130
+
131
+ return v;
132
+ });
133
+ } else {
134
+ /**
135
+ * Handle normal values.
136
+ */
137
+ var v = currentObj[key];
138
+
139
+ if (shouldConvertRootObj) {
140
+ newObj = getNewObj(newObj, currentObj);
141
+ newObj[key] = traverser(
142
+ v,
143
+ fullInstructionMap,
144
+ converters,
145
+ nullableValue,
146
+ instructions["r"]
147
+ );
148
+ }
149
+
150
+ if (isTopLevelNodeField) {
151
+ if (
152
+ v == null ||
153
+ !v.hasOwnProperty("__typename") ||
154
+ v.__typename !== instructions["tnf"]
155
+ ) {
156
+ newObj = getNewObj(newObj, currentObj);
157
+ newObj[key] = nullableValue;
158
+ }
159
+ }
160
+
161
+ if (shouldConvertEnum) {
162
+ newObj = getNewObj(newObj, currentObj);
163
+ newObj[key] = converters[instructions["e"]](v);
164
+ }
165
+
166
+ if (shouldConvertCustomField) {
167
+ newObj = getNewObj(newObj, currentObj);
168
+ newObj[key] = converters[instructions["c"]](v);
169
+ }
170
+
171
+ if (
172
+ shouldConvertUnion &&
173
+ v != null &&
174
+ typeof v === "object" &&
175
+ typeof v.__typename === "string"
176
+ ) {
177
+ isUnion = true;
178
+
179
+ var newPath = makeNewPath(currentPath, [key, v.__typename]);
180
+
181
+ var unionRootHasFragment =
182
+ (instructionMap[getPathName(newPath)] || {}).f === "";
183
+
184
+ var traversedValue = traverse(
185
+ fullInstructionMap,
186
+ newPath,
187
+ v,
188
+ instructionMap,
189
+ converters,
190
+ nullableValue,
191
+ instructionPaths,
192
+ unionRootHasFragment
193
+ );
194
+
195
+ newObj = getNewObj(newObj, currentObj);
196
+ newObj[key] = converters[instructions["u"]](traversedValue);
197
+ }
198
+
199
+ if (shouldAddFragmentFn && typeof v === "object") {
200
+ newObj = getNewObj(newObj, currentObj);
201
+ var objWithFragmentFn = Object.assign({}, v);
202
+ objWithFragmentFn.fragmentRefs = Object.assign({}, objWithFragmentFn);
203
+ newObj[key] = objWithFragmentFn;
204
+ }
205
+ }
206
+
207
+ if (originalValue != null && !isUnion) {
208
+ var nextObj = (newObj && newObj[key]) || currentObj[key];
209
+
210
+ if (typeof nextObj === "object" && !Array.isArray(originalValue)) {
211
+ var traversedObj = traverse(
212
+ fullInstructionMap,
213
+ thisPath,
214
+ nextObj,
215
+ instructionMap,
216
+ converters,
217
+ nullableValue,
218
+ instructionPaths
219
+ );
220
+
221
+ if (traversedObj !== nextObj) {
222
+ newObj = getNewObj(newObj, currentObj);
223
+ newObj[key] = traversedObj;
224
+ }
225
+ } else if (Array.isArray(originalValue)) {
226
+ newObj = getNewObj(newObj, currentObj);
227
+ newObj[key] = nextObj.map(function (o) {
228
+ if (typeof o === "object" && o != null) {
229
+ return traverse(
230
+ fullInstructionMap,
231
+ thisPath,
232
+ o,
233
+ instructionMap,
234
+ converters,
235
+ nullableValue,
236
+ instructionPaths
237
+ );
238
+ } else if (o == null) {
239
+ return nullableValue;
240
+ } else {
241
+ return o;
242
+ }
243
+ });
244
+ }
245
+ }
246
+ }
247
+
248
+ return newObj || currentObj;
249
+ }
250
+
251
+ /**
252
+ * This function takes an object (snapshot from the Relay store) and applies a
253
+ * set of conversions deeply on the object (instructions coming from "converters"-prop).
254
+ * It converts nullable values either to null or undefined, and it wraps/unwraps enums
255
+ * and unions.
256
+ *
257
+ * It preserves structural integrity where possible, and return new objects where properties
258
+ * have been modified.
259
+ */
260
+ function traverser(
261
+ root,
262
+ instructionMaps_,
263
+ theConverters,
264
+ nullableValue,
265
+ rootObjectKey
266
+ ) {
267
+ if (!root) {
268
+ return nullableValue;
269
+ }
270
+
271
+ var instructionMaps = instructionMaps_ || {};
272
+ var instructionMap = instructionMaps[rootObjectKey || "__root"] || {};
273
+
274
+ var converters = theConverters == null ? {} : theConverters;
275
+ var instructionPaths = Object.keys(instructionMap);
276
+
277
+ // We'll add the fragmentRefs reference to the root if needed here.
278
+ var fragmentsOnRoot = (instructionMap[""] || {}).f === "";
279
+ var unionRootConverter = converters[(instructionMap[""] || {}).u];
280
+
281
+ if (Array.isArray(root)) {
282
+ return root.map(function (v) {
283
+ if (v == null) {
284
+ return nullableValue;
285
+ }
286
+
287
+ var n = [];
288
+
289
+ // Since a root level union is treated as a "new root level", we'll need
290
+ // to do a separate check here of whether there's a fragment on the root
291
+ // we need to account for, or not.
292
+ if (unionRootConverter != null) {
293
+ n = [v.__typename];
294
+ fragmentsOnRoot = (instructionMap[v.__typename] || {}).f === "";
295
+ }
296
+
297
+ var traversedObj = traverse(
298
+ instructionMaps,
299
+ n,
300
+ v,
301
+ instructionMap,
302
+ converters,
303
+ nullableValue,
304
+ instructionPaths,
305
+ fragmentsOnRoot
306
+ );
307
+
308
+ return unionRootConverter != null
309
+ ? unionRootConverter(traversedObj)
310
+ : traversedObj;
311
+ });
312
+ }
313
+
314
+ var newObj = Object.assign({}, root);
315
+
316
+ var n = [];
317
+
318
+ // Same as in the union array check above - if there's a fragment in the new
319
+ // root created by the union, we need to account for that separately here.
320
+ if (unionRootConverter != null) {
321
+ n = [newObj.__typename];
322
+ fragmentsOnRoot = (instructionMap[newObj.__typename] || {}).f === "";
323
+ }
324
+
325
+ var v = traverse(
326
+ instructionMaps,
327
+ n,
328
+ newObj,
329
+ instructionMap,
330
+ converters,
331
+ nullableValue,
332
+ instructionPaths,
333
+ fragmentsOnRoot
334
+ );
335
+
336
+ return unionRootConverter != null ? unionRootConverter(v) : v;
337
+ }
338
+
339
+ export { traverser };
package/bin-darwin DELETED
Binary file
package/bin-linux DELETED
Binary file
@@ -1,54 +0,0 @@
1
- #!/usr/bin/env node
2
- const path = require("path");
3
- const { spawn } = require("child_process");
4
-
5
- let relayConfig = require("relay-config").loadConfig();
6
-
7
- if (!relayConfig) {
8
- console.error(
9
- "Could not find relay.config.js. You must configure Relay through relay.config.js for RescriptRelay to work."
10
- );
11
-
12
- process.exit(1);
13
- }
14
-
15
- if (!relayConfig.artifactDirectory) {
16
- console.error(
17
- "RescriptRelay requires you to define 'artifactDirectory' (for outputing generated files in a single directory) in your relay.config.js. Please define it and re-run this command."
18
- );
19
- process.exit(1);
20
- }
21
-
22
- function runRelayCompiler(args) {
23
- const proc = spawn("relay-compiler", args, {
24
- stdio: "inherit",
25
- })
26
- // Propagate the relay compiler's exit code.
27
- .on("close", process.exit.bind(process));
28
-
29
- process.on("SIGINT", () => {
30
- proc.kill("SIGINT");
31
- });
32
- }
33
-
34
- function findArg(name) {
35
- return relayConfig[name];
36
- }
37
-
38
- async function runCompiler() {
39
- const schemaPath = findArg("schema");
40
-
41
- if (schemaPath) {
42
- runRelayCompiler(
43
- [
44
- "--language",
45
- path.resolve(__dirname + "/../language-plugin/dist/index.js"),
46
- process.argv.find((a) => a === "--watch"),
47
- ].filter(Boolean)
48
- );
49
- } else {
50
- runRelayCompiler(["--help"]);
51
- }
52
- }
53
-
54
- runCompiler();
@@ -1 +0,0 @@
1
- module.exports=(()=>{"use strict";var e={338:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.find=void 0,t.find=function(e,t){return function(e,t){if(!e.includes("%relay"))return[];const n=e.match(/(?<=\[%relay)([\s\S]*?)(?=];)/g);if(n)return n.map((e=>({template:e.replace(/({\||\|})/g,""),keyName:null,sourceLocationOffset:{line:1,column:1}})));const r=e.match(/(?<=\%relay\([\s]*`)[\s\S.]+?(?=`[\s]*\))/g);return r?r.map((e=>({template:e,keyName:null,sourceLocationOffset:{line:1,column:1}}))):[]}(e)}},189:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.generateFromFlowTypes=void 0;const r=n(129),o=n(622);t.generateFromFlowTypes=e=>{var t;const n=r.spawnSync(o.resolve(o.join(__dirname,"../RescriptRelayBin.exe")),["generate-from-flow"],{cwd:__dirname,stdio:"pipe",encoding:"utf-8",input:JSON.stringify(e)});if(0!==n.status)throw null!==(t=n.error)&&void 0!==t?t:new Error("Error generating types");return n.output.filter(Boolean).join("")}},571:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.transforms=t.generate=void 0;const r=n(791),o=n(224),a=n(148),i=n(354),s=n(189),l=n(602);function c(e){const t=Object.assign({Int:"int",Float:"float"},e);return Object.keys(t).forEach((e=>{t[e]=l.maskDots(t[e])})),t}t.generate=function(e,t,n){var a;let i=r.generate(e,t,Object.assign(Object.assign({},n),{customScalars:c(n.customScalars)}));const l=o.makeOperationDescriptor(t),d=o.extractOperationInfo(t);return s.generateFromFlowTypes({content:i,operation_type:["Query","Mutation","Subscription"].includes(l.tag)?{operation:l.tag,operation_value:l.value}:{operation:"Fragment",fragment_value:l.value},print_config:{variables_holding_connection_ids:null!==(a=d.variablesHoldingConnectionIds)&&void 0!==a?a:null,connection:d.connection?{at_object_path:d.connection.atObjectPath,field_name:d.connection.fieldName,key:d.connection.key}:null}})},t.transforms=[i.transform,a.transform,...r.transforms]},942:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(366),o=n(622);e.exports=({moduleName:e,documentType:t,concreteText:n,typeText:a,definition:i})=>{let s=null;"Source"===i.loc.kind&&(s=o.basename(i.loc.source.name));const l="ConcreteRequest"===t&&e.toLowerCase().endsWith("query_graphql")?"include RescriptRelay.MakeLoadQuery({\n type variables = Types.variables\n type loadedQueryRef = queryRef\n type response = Types.response\n type node = relayOperationNode\n let query = node\n let convertVariables = Internal.convertVariables\n });":"",{processedText:c,referencedNodes:d}=r.processConcreteText(n),u=`%raw(json\` ${c} \`)`;return[s?`/* @sourceLoc ${s} */`:null,a||"",...d.length>0?[`%%private(let makeNode = (${d.map((({identifier:e})=>e)).join(", ")}): operationType => {`,...d.map((({identifier:e})=>` ignore(${e})`)),` ${u}`,"})",`let node: operationType = makeNode(${d.map((({moduleName:e})=>`${e}_graphql.node`)).join(", ")})`]:[`let node: operationType = ${u}`],"",l,""].filter((e=>null!=e)).join("\n")}},602:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unmaskDots=t.maskDots=void 0,t.maskDots=e=>e.split(".").join("__oo__"),t.unmaskDots=e=>e.split("__oo__").join(".")},607:(e,t,n)=>{const r=n(571),o=n(942),{find:a}=n(338),i=n(622),s=n(747);function l(e){return t=>{const n=i.join(e,t.relPath);let r="";try{r=s.readFileSync(n,"utf8")}catch(e){return console.warn(`RelaySourceModuleParser: Unable to read the file "${n}". Looks like it was removed.`),!1}return r.indexOf("%relay")>=0}}e.exports=()=>({inputExtensions:["re","res"],outputExtension:"res",schemaExtensions:[],typeGenerator:r,formatModule:o,findGraphQLTags:a,isGeneratedFile:e=>e.endsWith("_graphql.res")||e.endsWith(".js")||e.endsWith(".mjs"),keepExtraFile:e=>e.endsWith(".js")||e.endsWith(".mjs"),getFileFilter:l,getModuleName:e=>`${e}_graphql`})},224:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.makeOperationDescriptor=t.extractOperationInfo=void 0;const r=n(195);function o(e,t,n){if("Root"===e.kind&&["mutation","subscription"].includes(e.operation)){const e=t.directives.filter((e=>["appendNode","prependNode","appendEdge","prependEdge","deleteEdge"].includes(e.name)));e.length>0&&e.forEach((e=>{const t=e.args.find((e=>"connections"===e.name)),r=null==t?void 0:t.value;r&&"Variable"===r.kind&&(n.variablesHoldingConnectionIds?n.variablesHoldingConnectionIds.push(r.variableName):n.variablesHoldingConnectionIds=[r.variableName])}))}}t.extractOperationInfo=function(e){let t={};const n="Fragment"===e.kind?"fragment":"response";return n?(function e(n,a){r.IRVisitor.visit(a,{ScalarField(e){o(a,e,t)},LinkedField(e){const r=e.directives.find((e=>"connection"===e.name));if(r&&!t.connection){let o=null;r.args.forEach((e=>{"key"===e.name&&"Literal"===e.value.kind&&(o=e.value.value)})),o&&(t=Object.assign(Object.assign({},t),{connection:{key:o,atObjectPath:[...n],fieldName:e.alias}}))}o(a,e,t),n.push(e.alias)},InlineFragment(t){t.typeCondition.name&&t.selections.forEach((r=>{e([...n,t.typeCondition.name.toLowerCase()],r)}))}})}([n],e),t):t},t.makeOperationDescriptor=function(e){if("Root"===e.kind)switch(e.operation){case"mutation":return{tag:"Mutation",value:e.name};case"query":return{tag:"Query",value:e.name};case"subscription":return{tag:"Subscription",value:e.name}}else if("Fragment"==e.kind)return{tag:"Fragment",value:[e.name,Boolean(e.metadata&&e.metadata.plural)]};throw new Error("Could not map root node. This should not happen.")}},148:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.transform=void 0;const r=n(724),{createUserError:o}=n(182),a=["and","as","asr","assert","begin","class","constraint","do","while","for","done","while","for","downto","else","end","exception","external","false","for","fun","function","functor","if","in","include","inherit","initializer","land","lazy","let","lor","lsl","lsr","lxor","match","method","mod","module","open","mutable","new","nonrec","object","of","open","open!","or","private","rec","let","module","sig","struct","then","to","true","try","type","val","virtual","val","method","class","when","while","with","switch"];let i=["fragment","t_fragment","subscription","mutation","response","variables","refetchVariables","t","fragmentRef","fragmentRefs","fragmentRefSelector","operationType"];function s(e){if(e.alias){let{disallowed:t,message:n}=function(e){let t=e[0];return/[A-Z]/.test(t)?{disallowed:!0,message:`Field names may not start with an uppercase letter. Please alias the '${e}' field to something starting with a lowercase letter.`}:a.includes(e)?{disallowed:!0,message:`'${e}' is a reserved keyword in ReasonML and therefore cannot be used as a field name. Please alias your field to something else.`}:i.includes(e)?{disallowed:!0,message:`'${e}' is a reserved keyword in RescriptRelay and therefore cannot be used as a field name. Please alias your field to something else.`}:{disallowed:!1,message:""}}(e.alias);if(t)throw o("Found an invalid field name: "+n,[e.loc])}e.selections&&e.selections.forEach(s)}function l(e){return s(e),e}t.transform=function(e){return r.transform(e,{ScalarField:l,LinkedField:l})}},354:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.transform=void 0;const r=n(724),{createUserError:o}=n(182),{hasUnaliasedSelection:a}=n(124);function i(e){const t=this.getContext().getSchema();let n=this.traverse(e);if(t.isAbstractType(t.getRawType(n.type))&&!a(n,"__typename"))throw o('Unions and interfaces must have the field __typename explicitly selected. Please add __typename to the fields selected by "'+e.alias+'" in your operation.',[e.loc]);return n}t.transform=function(e){return r.transform(e,{LinkedField:i})}},366:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.processConcreteText=void 0,t.processConcreteText=function(e){let t=/(require\('.\/)([A-Za-z_.0-9/]+)(.graphql'\))/gm,n=e;const r=[];let o;for(;null!==(o=t.exec(e));){let[e,t,a]=o;const i=`node_${a}`;r.push({moduleName:a,identifier:i}),n=n.replace(e,`node_${a}`)}return{processedText:n,referencedNodes:r}}},129:e=>{e.exports=require("child_process")},747:e=>{e.exports=require("fs")},622:e=>{e.exports=require("path")},195:e=>{e.exports=require("relay-compiler")},182:e=>{e.exports=require("relay-compiler/lib/core/CompilerError")},724:e=>{e.exports=require("relay-compiler/lib/core/IRTransformer")},791:e=>{e.exports=require("relay-compiler/lib/language/javascript/RelayFlowGenerator")},124:e=>{e.exports=require("relay-compiler/lib/transforms/TransformUtils")}},t={};return function n(r){if(t[r])return t[r].exports;var o=t[r]={exports:{}};return e[r](o,o.exports,n),o.exports}(607)})();